feat(notifications): Web Push delivers notifications to every device, even with TREK closed

A fourth built-in channel next to email, webhook and ntfy. Browsers
register per device, the server encrypts per RFC 8291 and signs per RFC
8292 with node:crypto and sends only to known push services through the
SSRF guard. The event matrix decides per category what arrives by push;
admins switch the channel on under Notifications.

VAPID keys come from the environment or are generated once, only while
neither stored row exists, and kept encrypted. A pair that does not
decrypt or match is never overwritten and never swapped for another one:
push stays off with an error in the log and every device stays
registered until the key is fixed. The subject is VAPID_SUBJECT, then an
https APP_URL, then the project URL.

Only chat messages collapse into one notification per trip, and a
replacement still alerts. A 403 removes a device only after three
failures in a row; 404 and 410 remove it at once. Password change, reset
and an admin setting a password drop the user's devices with the other
credentials. The request log redacts subscriptions and endpoints, boot
errors print *** for every secret variable, and logout forgets the
device with a plain fetch so an expired session cannot redirect midway.

Addresses discussion #894.
This commit is contained in:
Maurice
2026-09-24 23:17:03 +00:00
parent 7ce31756a3
commit 650451bdf7
177 changed files with 7809 additions and 271 deletions
+4
View File
@@ -68,6 +68,10 @@ DEMO_MODE=false # Demo mode - resets data hourly
# LLM_TIMEOUT_MS=900000 # Ceiling (ms) for one AI-parsing call before it is abandoned. One value for every provider, and the underlying HTTP client is held to it too. Generous by default so heavier parsing work fits without a code change; lower it on a cloud provider to fail fast. (default: 900000)
# VAPID_PUBLIC_KEY= # Web Push: the public half of the key pair browsers subscribe with (base64url, 65 bytes). Leave both halves unset and TREK generates a pair on first start and keeps it in the database, so it travels with every backup. Set both to use a pair of your own, e.g. printed by `npx web-push generate-vapid-keys`. Changing the pair later means every device has to turn push on again.
# VAPID_PRIVATE_KEY= # Web Push: the private half (base64url, 32 bytes). Only used together with VAPID_PUBLIC_KEY; a pair whose halves do not belong together, or only one half, turns push off with an error in the log until the pair is fixed. A pair stored in the database is not used in its place, and every device stays registered.
# VAPID_SUBJECT=mailto:admin@example.com # Web Push: the contact push services see with every message, a mailto: address or an https:// URL. Unset, TREK uses APP_URL when it is https, else the TREK project page.
# UNSPLASH_ACCESS_KEY= # Optional Unsplash Access Key for trip-cover and place-image search. Without one, TREK uses Unsplash's unauthenticated endpoint, which some datacenter/VPS IPs get blocked from (#1449). Get a free key at unsplash.com/developers. Overrides any key set per-admin in Admin > Settings. Can also be configured there instead of here.
# Initial admin account — ONLY applied on the first boot, when the database has no
+5
View File
@@ -283,6 +283,10 @@ async function main() {
// rotation leaves it encrypted under the old key, which reads back as "no
// key" and silently drops the install to OpenStreetMap, so the copy is
// pinned by tests/unit/db/migrate-encryption-parity.test.ts.
//
// web_push_vapid_private_key is the Web Push signing key VapidKeysService
// generates. Missed here it would no longer decrypt under the new key, and
// push would stay off on every device until the old key came back.
for (const key of [
'oidc_client_secret',
'smtp_pass',
@@ -291,6 +295,7 @@ async function main() {
'maps_api_key',
'unsplash_api_key',
'amap_api_key',
'web_push_vapid_private_key',
]) {
const row = db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined;
if (!row?.value) continue;
+6 -1
View File
@@ -31,6 +31,10 @@ tokens, `RuntimeEnvService`) and consumes the SAME derive functions.
together wrong. It is empty without the switch, so a self-hoster never meets
it. Put a rule there only if booting anyway would be a security or data
problem — not to enforce a preference.
The report prints each malformed value, because that is what makes a typo
findable, except for the credentials in `SECRET_ENV_KEYS` (`env.ts`), which
print as `***`. A new password, token, key or secret variable goes into that
set; `validate.test.ts` fails on a credential-sounding name missing from it.
3. **Parity is law — with one deliberate exception.** Every derived field pins
the exact coercion of the call site(s) it replaced (`Number(x) || d`
treating `"0"` as unset, per-site defaults for the same variable, …). Do not
@@ -82,7 +86,8 @@ TREK_PLUGINS_ENABLED / _DEV_LINK / _IGNORE_TREK_RANGE / _DIR / _DATA_DIR / TREK_
OIDC_*, SMTP_*, FORCE_HTTPS, COOKIE_SECURE, HSTS_INCLUDE_SUBDOMAINS,
ALLOWED_ORIGINS, UNSPLASH_ACCESS_KEY, WEBAUTHN_*, TZ, ADMIN_EMAIL,
ADMIN_PASSWORD, IDEMPOTENCY_TTL_SECONDS, MCP_RATE_LIMIT (request-path check),
LLM_TIMEOUT_MS, NOMINATIM_URL.
LLM_TIMEOUT_MS, NOMINATIM_URL, VAPID_* (resolved per use by the Web Push key
service, which the notification suites build without the container).
## Exemptions — raw `process.env` stays
+11
View File
@@ -334,6 +334,16 @@ export function deriveNet(raw: RawEnv) {
};
}
export function derivePush(raw: RawEnv) {
return {
// Trimmed, and blank counts as unset: the schema validated the trimmed value,
// so a padded key must not reach the crypto as a different string.
vapidPublicKey: raw.VAPID_PUBLIC_KEY?.trim() || undefined,
vapidPrivateKey: raw.VAPID_PRIVATE_KEY?.trim() || undefined,
vapidSubject: raw.VAPID_SUBJECT?.trim() || undefined,
};
}
export function deriveAll(raw: RawEnv) {
return {
app: deriveApp(raw),
@@ -353,6 +363,7 @@ export function deriveAll(raw: RawEnv) {
db: deriveDb(raw),
paths: derivePaths(raw),
net: deriveNet(raw),
push: derivePush(raw),
};
}
+19 -1
View File
@@ -11,7 +11,13 @@
*/
import { z } from 'zod';
import { SUPPORTED_LANGUAGE_CODES } from '@trek/shared';
import { parseDurationMs, parseLinkLocalAllowList } from './parsers';
import {
isP256PrivateKey,
isUncompressedP256Key,
isVapidSubject,
parseDurationMs,
parseLinkLocalAllowList,
} from './parsers';
/** Present-but-malformed fails; unset/blank always passes (defaults apply). */
function optionalWith(test: (v: string) => boolean, message: string) {
@@ -104,6 +110,18 @@ export const envSchema = z.object({
WEBAUTHN_RP_ID: anyString,
WEBAUTHN_ORIGINS: anyString,
// Web Push (VAPID). All optional: without them the server keeps a pair of its
// own in the database. Only the shape is checked here; whether the two keys
// belong together is checked where they are used, which turns push off while
// they do not (never signing with a stored pair in their place) and says so
// in the log instead of refusing to boot.
VAPID_PUBLIC_KEY: optionalWith(
isUncompressedP256Key,
'must be a base64url-encoded P-256 public key (65 bytes, uncompressed, starting with 0x04)',
),
VAPID_PRIVATE_KEY: optionalWith(isP256PrivateKey, 'must be a base64url-encoded P-256 private key (32 bytes)'),
VAPID_SUBJECT: optionalWith(isVapidSubject, 'must be a mailto: address or an https:// URL'),
// MCP
MCP_SESSION_TTL: positiveNumber,
MCP_MAX_SESSION_PER_USER: positiveNumber,
+26 -1
View File
@@ -14,6 +14,31 @@ export function readEnv(): AppEnv {
return deriveAll(process.env as RawEnv);
}
/**
* Variables whose value never goes into the boot report, even when it is the
* malformed one: the report lands in container logs, and a key that is merely
* mistyped is still a real key. The name and the problem are enough to fix it.
*/
export const SECRET_ENV_KEYS: ReadonlySet<string> = new Set([
'ENCRYPTION_KEY',
'OIDC_CLIENT_SECRET',
'SMTP_PASS',
'VAPID_PRIVATE_KEY',
'UNSPLASH_ACCESS_KEY',
'ADMIN_PASSWORD',
'PLACES_API_KEY',
'AMAP_API_KEY',
'AMAP_API_SECRET',
'MAPBOX_ACCESS_TOKEN',
'CARTO_API_KEY',
'DEMO_ADMIN_PASS',
]);
/** How a variable's value appears in the boot report. */
function reportedValue(key: string, value: string | undefined): string {
return SECRET_ENV_KEYS.has(key) ? '***' : JSON.stringify(value);
}
/**
* Fail-fast startup validation: a variable that is PRESENT but malformed aborts
* boot with an aggregated report; unset/blank variables always pass (their
@@ -28,7 +53,7 @@ export function validateEnvAtBoot(raw: RawEnv = process.env as RawEnv): void {
? []
: result.error.issues.map((issue) => {
const key = String(issue.path[0]);
return ` - ${key}=${JSON.stringify(raw[key])}: ${issue.message}`;
return ` - ${key}=${reportedValue(key, raw[key])}: ${issue.message}`;
});
lines.push(...managedPreconditions(raw));
if (lines.length === 0) return;
+1
View File
@@ -20,6 +20,7 @@ export {
deriveDb,
derivePaths,
deriveNet,
derivePush,
} from './derive';
export * from './parsers';
export { envSchema } from './env.schema';
+43
View File
@@ -209,3 +209,46 @@ export function parseLinkLocalAllowList(raw: string | undefined): { ips: string[
}
return { ips, invalid };
}
// ── Web Push key material ──────────────────────────────────────────────────
const BASE64URL = /^[A-Za-z0-9_-]+={0,2}$/;
/**
* Strict base64url decode, null for anything that is not base64url. Web Push
* keys arrive in this alphabet from the browser and from the VAPID_* variables.
* Buffer.from(value, 'base64url') alone skips characters it does not know, so a
* mangled key would decode to fewer bytes instead of being refused, and the size
* checks below would then report the wrong problem.
*/
export function decodeBase64Url(value: string): Buffer | null {
const trimmed = value.trim();
if (!BASE64URL.test(trimmed)) return null;
return Buffer.from(trimmed, 'base64url');
}
/** An uncompressed P-256 point: 65 bytes, the first one 0x04 (VAPID public key, subscription p256dh). */
export function isUncompressedP256Key(value: string): boolean {
const bytes = decodeBase64Url(value);
return bytes?.length === 65 && bytes[0] === 0x04;
}
/** A P-256 private scalar as the Web Push tools print it: 32 bytes. */
export function isP256PrivateKey(value: string): boolean {
return decodeBase64Url(value)?.length === 32;
}
/**
* The VAPID `sub` claim (RFC 8292 section 2.1): a mailto: address or an https:
* URL. Apple refuses anything else, and so does this check, so a subject that
* boots is one every push service accepts.
*/
export function isVapidSubject(value: string): boolean {
const trimmed = value.trim();
if (/^mailto:[^\s@]+@[^\s@]+$/i.test(trimmed)) return true;
try {
return new URL(trimmed).protocol === 'https:';
} catch {
return false;
}
}
+30
View File
@@ -5257,6 +5257,36 @@ function runMigrations(db: Database.Database): void {
`);
}
},
/*
* Web Push (#894): one row per browser a user switched push on in.
*
* The endpoint is the push service URL that browser handed out, so it is
* unique: a browser shared by two accounts belongs to whoever subscribed on
* it last. p256dh and auth are the browser's keys for the RFC 8291 message
* encryption. vapid_public_key is the server key the subscription was made
* against, so a changed key pair shows up as a mismatch the sender can clean
* up, rather than as a push service refusing every message. failure_count
* and last_success_at are bookkeeping for the sender; the rows go with the
* user.
*/
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS push_subscriptions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
endpoint TEXT NOT NULL UNIQUE,
p256dh TEXT NOT NULL,
auth TEXT NOT NULL,
vapid_public_key TEXT NOT NULL,
user_agent TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_success_at TEXT,
failure_count INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_push_subscriptions_user ON push_subscriptions(user_id);
`);
},
];
if (currentVersion < migrations.length) {
+27 -2
View File
@@ -28,6 +28,11 @@ export const SENSITIVE_KEYS = new Set([
'code',
'smtp_pass',
'secretaccesskey',
// A Web Push subscription's keys: whoever holds them together with the
// endpoint can encrypt messages for that browser. No other request body has
// either field, and an `auth` anywhere else would be a credential as well.
'p256dh',
'auth',
]);
/**
@@ -43,7 +48,26 @@ function isSensitiveName(name: string): boolean {
return SENSITIVE_KEYS.has(lower) || SENSITIVE_SUFFIXES.some((suffix) => lower.endsWith(suffix));
}
/** Deep-redacts every key in `SENSITIVE_KEYS` (case-insensitive) from a request-log value. */
/**
* The fields PushSubscription.toJSON() puts next to `endpoint`. Either one is
* enough to know the object is a subscription, so a body that arrives without
* its keys (which the route then refuses) still keeps its endpoint out of the log.
*/
const PUSH_SUBSCRIPTION_FIELDS = new Set(['keys', 'expirationtime']);
/**
* A Web Push endpoint is a capability URL: anyone holding it can post to that
* browser's push service. It arrives inside a subscription, or on its own in
* the body that forgets a device. Anywhere else `endpoint` is an ordinary
* setting (the S3 backend's URL, for one) and stays readable.
*/
function isPushEndpoint(entries: Record<string, unknown>, name: string): boolean {
if (name.toLowerCase() !== 'endpoint') return false;
const siblings = Object.keys(entries).filter((k) => k !== name);
return siblings.length === 0 || siblings.some((k) => PUSH_SUBSCRIPTION_FIELDS.has(k.toLowerCase()));
}
/** Deep-redacts every key in `SENSITIVE_KEYS` (case-insensitive) and every Web Push endpoint from a request-log value. */
export function redact(value: unknown): unknown {
if (!value || typeof value !== 'object') return value;
if (Array.isArray(value)) return (value as unknown[]).map(redact);
@@ -54,7 +78,8 @@ export function redact(value: unknown): unknown {
const namedSecret = typeof entries.key === 'string' && isSensitiveName(entries.key);
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(entries)) {
out[k] = isSensitiveName(k) || (namedSecret && k === 'value') ? '[REDACTED]' : redact(v);
const hidden = isSensitiveName(k) || (namedSecret && k === 'value') || isPushEndpoint(entries, k);
out[k] = hidden ? '[REDACTED]' : redact(v);
}
return out;
}
+3
View File
@@ -226,6 +226,9 @@ export class AdminService {
id,
);
} catch { /* very old installs predate oauth_tokens */ }
// Push devices outlive every session, so the intruder's browser would
// keep receiving this account's notifications. They go with the rest.
this.db.run('DELETE FROM push_subscriptions WHERE user_id = ?', id);
}
});
+11 -1
View File
@@ -7,6 +7,7 @@ import { authenticator } from 'otplib';
import QRCode from 'qrcode';
import { randomBytes, createHash } from 'crypto';
import type { Request, Response } from 'express';
import { WEB_PUSH_CHANNEL_ID } from '@trek/shared';
import { readEnv } from '../../app-config';
import { JWT_SECRET, SESSION_DURATION_SECONDS, SESSION_DURATION_REMEMBER_SECONDS } from '../../config';
import { DatabaseService } from '../database/database.service';
@@ -285,6 +286,7 @@ export class AuthService {
const notifChannelsRaw = this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'notification_channels'")?.value || notifChannel;
const activeChannels = notifChannelsRaw === 'none' ? [] : notifChannelsRaw.split(',').map((c: string) => c.trim()).filter(Boolean);
const hasWebhookEnabled = activeChannels.includes('webhook');
const hasPushEnabled = activeChannels.includes(WEB_PUSH_CHANNEL_ID);
const tripRemindersEnabled = tripReminderSetting !== 'false';
const placesPhotosSetting = this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'places_photos_enabled'")?.value;
const placesPhotosEnabled = placesPhotosSetting !== 'false';
@@ -343,7 +345,7 @@ export class AuthService {
timezone: readEnv().app.tz || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC',
notification_channel: notifChannel,
notification_channels: activeChannels,
available_channels: { email: hasSmtpHost, webhook: hasWebhookEnabled, inapp: true },
available_channels: { email: hasSmtpHost, webhook: hasWebhookEnabled, push: hasPushEnabled, inapp: true },
trip_reminders_enabled: tripRemindersEnabled,
places_photos_enabled: placesPhotosEnabled,
places_autocomplete_enabled: placesAutocompleteEnabled,
@@ -596,6 +598,11 @@ export class AuthService {
try {
this.db.run("UPDATE oauth_tokens SET revoked_at = CURRENT_TIMESTAMP WHERE user_id = ? AND revoked_at IS NULL", userId);
} catch { /* oauth_tokens table may not exist in very old installs */ }
// Push devices keep receiving notifications without any session, so they
// go too. The device the change was made on registers again right away:
// the client reloads the user after the change, and that re-syncs its
// subscription. Other devices do so after their next sign-in.
this.db.run('DELETE FROM push_subscriptions WHERE user_id = ?', userId);
});
try { revokeUserSessions?.(userId); } catch { /* best-effort */ }
@@ -1056,6 +1063,9 @@ export class AuthService {
user.id
);
} catch { /* oauth_tokens table may not exist in very old installs */ }
// Push devices are a delivery channel that outlives every session, so an
// intruder's browser would keep reading this account's notifications.
this.db.run('DELETE FROM push_subscriptions WHERE user_id = ?', user.id);
});
// Kick off any MCP/WS session cleanup — same hook the account-delete path uses.
@@ -1,13 +1,16 @@
import { WEB_PUSH_CHANNEL_ID } from '@trek/shared';
import { registerChannel } from '../channel-registry';
import type { ChannelMessage, ExternalChannel } from '../notification-events';
import { ADMIN_SCOPED_EVENTS, type ChannelMessage, type ExternalChannel } from '../notification-events';
import type { MailerService } from '../mailer/mailer.service';
import { resolveAdminNtfyUrl, resolveNtfyToken, resolveNtfyUrl, type NtfyService } from '../transports/ntfy.service';
import type { WebhookService } from '../transports/webhook.service';
import type { WebPushService } from '../transports/web-push.service';
// The three built-in external channels, wrapping the transports that were free
// functions in services/notifications.ts before the fold. No delivery logic is
// rewritten here - it is only relocated behind the ExternalChannel interface so
// NotificationsService.send() can iterate instead of branching.
// The built-in external channels. Email, webhook and ntfy wrap the transports
// that were free functions in services/notifications.ts before the fold; no
// delivery logic is rewritten here, it is only relocated behind the
// ExternalChannel interface so NotificationsService.send() can iterate instead
// of branching. Web Push (#894) joined later on the same terms.
function supportsAllButSynology(event: string): boolean {
return event !== 'synology_session_cleared';
@@ -17,10 +20,11 @@ export interface BuiltinChannelDeps {
mailer: MailerService;
webhook: WebhookService;
ntfy: NtfyService;
push: WebPushService;
}
/**
* Build the three built-in channels over the given transports.
* Build the built-in channels over the given transports.
*
* They take their dependencies as an argument rather than importing them,
* because the registry they land in is a module singleton while the transports
@@ -32,7 +36,7 @@ export interface BuiltinChannelDeps {
* preferences; dropping that import would have silenced email, webhook and ntfy
* without a single error.
*/
export function buildBuiltinChannels({ mailer, webhook, ntfy }: BuiltinChannelDeps): ExternalChannel[] {
export function buildBuiltinChannels({ mailer, webhook, ntfy, push }: BuiltinChannelDeps): ExternalChannel[] {
const emailChannel: ExternalChannel = {
id: 'email',
source: 'builtin',
@@ -114,7 +118,26 @@ export function buildBuiltinChannels({ mailer, webhook, ntfy }: BuiltinChannelDe
},
};
return [emailChannel, webhookChannel, ntfyChannel];
// Per user and per browser. It carries no admin-scoped events: those have
// their own admin-global copy on the channels above, and a push column in
// the admin matrix could never be switched on. There is no sendGlobal for the
// same reason, and no credentials to check beyond the user having turned it
// on in at least one browser. Subscribing is a browser-only act, so there is
// no MCP twin for the routes behind it. While the server's key pair cannot be
// used, push is not sent and not offered, and every device stays subscribed.
const pushChannel: ExternalChannel = {
id: WEB_PUSH_CHANNEL_ID,
source: 'builtin',
labelKey: 'settings.notificationPreferences.push',
hiddenWhileInstanceUnconfigured: true,
supportsEvent: (event) => supportsAllButSynology(event) && !ADMIN_SCOPED_EVENTS.has(event),
isInstanceConfigured: () => push.isAvailable(),
isConfiguredFor: (userId) => push.hasDevices(userId),
sendToUser: (userId, msg) => push.sendToUser(userId, msg),
test: (userId) => push.sendTest(userId),
};
return [emailChannel, webhookChannel, ntfyChannel, pushChannel];
}
/** Idempotent - safe to call from every entry point that needs the registry populated. */
@@ -127,6 +127,13 @@ export interface ExternalChannel {
readonly bypassesActiveToggleForAdminEvents?: boolean;
/** Delivers the one admin-scoped global copy (not per-recipient). */
readonly supportsAdminGlobal?: boolean;
/**
* The user's matrix marks this channel inactive (no column, no settings card)
* while isInstanceConfigured() says no. Web Push sets it: without a usable key
* pair a browser could not even subscribe. Email does not, and keeps its
* column while SMTP is not set up, as it always has.
*/
readonly hiddenWhileInstanceUnconfigured?: boolean;
supportsEvent(event: NotifEventType): boolean;
/**
@@ -80,6 +80,16 @@ export class NotificationPreferencesService {
return channel.source === 'plugin' || this.getActiveChannels().includes(channel.id);
}
/**
* Is the channel offered to users at all right now? Switched on, and for a
* channel that says so, ready on this instance too: Web Push without a usable
* key pair is off for everyone, whatever the admin switch says.
*/
private isChannelOffered(channel: ExternalChannel): boolean {
if (!this.isChannelActive(channel)) return false;
return !channel.hiddenWhileInstanceUnconfigured || channel.isInstanceConfigured?.() !== false;
}
// ── Per-user preference checks ─────────────────────────────────────────────
/**
@@ -123,8 +133,10 @@ export class NotificationPreferencesService {
const hasAdminNtfy = !!this.getAppSetting('admin_ntfy_topic');
const adminActive: Record<string, boolean> = { email: hasSmtp, webhook: hasAdminWebhook, ntfy: hasAdminNtfy };
for (const channel of listChannels()) {
// Plugin channels are user-scoped only — they never carry admin-global events.
if (channel.source !== 'builtin') continue;
// Only the channels with an admin-global copy. Plugin channels and push are
// user-scoped: they never carry an admin-scoped event, so a column for them
// here could never be switched on.
if (channel.source !== 'builtin' || !isAdminGlobalChannel(channel.id)) continue;
const active = adminActive[channel.id] ?? false;
out.push({
id: channel.id,
@@ -147,7 +159,7 @@ export class NotificationPreferencesService {
settingsPath: channel.settingsPath,
// A live plugin channel is always a column. `configured` tells the user whether
// they still need to enter credentials — it does not hide the channel from them.
active: this.isChannelActive(channel),
active: this.isChannelOffered(channel),
configured: channel.isConfiguredFor(userId),
});
}
@@ -5,6 +5,8 @@ import {
testWebhookRequestSchema,
testNtfyRequestSchema,
notificationRespondRequestSchema,
pushSubscribeRequestSchema,
pushUnsubscribeRequestSchema,
} from '@trek/shared';
/**
@@ -19,3 +21,5 @@ export class TestSmtpDto extends createZodDto(testSmtpRequestSchema) {}
export class TestWebhookDto extends createZodDto(testWebhookRequestSchema) {}
export class TestNtfyDto extends createZodDto(testNtfyRequestSchema) {}
export class NotificationRespondDto extends createZodDto(notificationRespondRequestSchema) {}
export class PushSubscribeDto extends createZodDto(pushSubscribeRequestSchema) {}
export class PushUnsubscribeDto extends createZodDto(pushUnsubscribeRequestSchema) {}
@@ -7,6 +7,10 @@ import { ReminderJobsService } from './reminder-jobs.service';
import { StorageHealthNotifierService } from './storage-health-notifier.service';
import { NtfyService } from './transports/ntfy.service';
import { WebhookService } from './transports/webhook.service';
import { WebPushService } from './transports/web-push.service';
import { PushController } from './push/push.controller';
import { PushSubscriptionsService } from './push/push-subscriptions.service';
import { VapidKeysService } from './push/vapid-keys.service';
import { MailerModule } from './mailer/mailer.module';
import { AuthModule } from '../auth/auth.module';
import { SchedulingModule } from '../scheduling/scheduling.module';
@@ -19,17 +23,23 @@ import { StorageModule } from '../storage/storage.module';
* StorageModule feeds StorageHealthNotifierService, which bridges replica
* failures into admin notifications — this direction has no cycle (Storage
* imports only AppConfig+Audit+Scheduling).
* Web Push (#894) lives in push/: VapidKeysService holds the server's key
* pair, PushSubscriptionsService the browsers, PushController the routes
* a browser signs up through; the transport is transports/web-push.service.ts.
* NotificationsService and NotificationPreferencesService are exported for
* in-container consumers (AdminController's dev test send and preferences tab,
* the plugin RPC surface, HostSurfaceRpc). */
@Module({
imports: [AuthModule, MailerModule, SchedulingModule, StorageModule],
controllers: [NotificationsController, AdminNotificationPreferencesController],
controllers: [NotificationsController, AdminNotificationPreferencesController, PushController],
providers: [
NotificationsService,
NotificationPreferencesService,
WebhookService,
NtfyService,
WebPushService,
VapidKeysService,
PushSubscriptionsService,
NotificationsMcp,
ReminderJobsService,
StorageHealthNotifierService,
@@ -6,6 +6,7 @@ import { getEventText } from './mailer/email-html';
import { MailerService } from './mailer/mailer.service';
import { NtfyService, type NtfyConfig } from './transports/ntfy.service';
import { WebhookService } from './transports/webhook.service';
import { WebPushService } from './transports/web-push.service';
import { NotificationPreferencesService, type PreferencesMatrix } from './notification-preferences.service';
import { registerBuiltinChannels } from './channels/builtins';
import {
@@ -272,7 +273,6 @@ function shouldSendToUser(
prefs: NotificationPreferencesService,
): boolean {
if (!channel.supportsEvent(event)) return false;
if (channel.isInstanceConfigured && !channel.isInstanceConfigured()) return false;
if (ADMIN_SCOPED_EVENTS.has(event)) {
if (!channel.bypassesActiveToggleForAdminEvents) return false;
@@ -285,7 +285,10 @@ function shouldSendToUser(
if (!prefs.isEnabledForEvent(recipientId, event, channel.id)) return false;
}
return channel.isConfiguredFor(recipientId);
if (!channel.isConfiguredFor(recipientId)) return false;
// Last, since it is the costly check: Web Push reads and verifies the server's
// key pair. Every check here is a plain AND, so the order changes no answer.
return !channel.isInstanceConfigured || channel.isInstanceConfigured();
}
/**
@@ -316,12 +319,13 @@ export class NotificationsService {
private readonly webhook: WebhookService,
private readonly ntfy: NtfyService,
private readonly prefs: NotificationPreferencesService,
push: WebPushService,
) {
// The registry is a module singleton shared with the plugin runtime and any
// separately-constructed instance (which never runs onModuleInit), so
// registering from here means every path that can dispatch has the
// built-ins. registerChannel is an idempotent Map.set.
registerBuiltinChannels({ mailer, webhook, ntfy });
registerBuiltinChannels({ mailer, webhook, ntfy, push });
}
getPreferences(userId: number, role: string): PreferencesMatrix {
@@ -779,7 +783,7 @@ export class NotificationsService {
);
}
// ── External channels (email, webhook, ntfy, plugin:*) ───────────────
// ── External channels (email, webhook, ntfy, push, plugin:*) ─────────
// One loop over the registry. The message is rendered once per recipient, in
// their language, and handed to every channel that wants it — so a plugin
// channel never touches i18n.
@@ -0,0 +1,97 @@
import { MAX_PUSH_ENDPOINT_LENGTH, type PushSubscriptionInput } from '@trek/shared';
import { decodeBase64Url } from '../../../app-config';
import { isP256Point } from './web-push-crypto';
/**
* The browser hands us a URL and the server POSTs to it for as long as the row
* lives, so the URL is checked like any other user-supplied target, and more
* narrowly: it has to be one of the push services browsers actually use. The
* SSRF guard still runs on every send; this list is what keeps a subscription
* from turning the server into a POST relay towards some other public host.
*/
export const PUSH_SERVICE_HOSTS: readonly string[] = [
// Chrome, Edge on Android, and every Chromium browser that uses Google's push.
'fcm.googleapis.com',
'android.googleapis.com',
// Firefox (autopush).
'updates.push.services.mozilla.com',
'push.services.mozilla.com',
// Safari on macOS, and Home Screen apps on iOS and iPadOS 16.4+.
'web.push.apple.com',
];
/** Services that hand out per-region or per-cluster hosts under one domain. */
export const PUSH_SERVICE_HOST_SUFFIXES: readonly string[] = [
'.push.apple.com',
// Edge on Windows (WNS).
'.notify.windows.com',
];
/** The bespoke 400 bodies for a subscription the browser should not have sent. */
export const PUSH_SUBSCRIPTION_ERRORS = {
endpoint: 'Invalid push endpoint',
service: 'Push endpoint is not a known push service',
p256dh: 'Invalid push subscription key',
auth: 'Invalid push subscription auth secret',
} as const;
export interface CheckedPushSubscription {
endpoint: string;
/** Canonical base64url, no padding. */
p256dh: string;
/** Canonical base64url, no padding. */
auth: string;
}
export type PushSubscriptionCheck = { ok: true; value: CheckedPushSubscription } | { ok: false; error: string };
function isKnownPushServiceHost(host: string): boolean {
return (
PUSH_SERVICE_HOSTS.includes(host) ||
PUSH_SERVICE_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix) && host.length > suffix.length)
);
}
/**
* The endpoint half of the check, shared with the sender so a row that no
* longer passes (a host dropped from the list) is not posted to again.
* Answers 'ok', or which of the errors applies: 'endpoint' for anything that is
* not a plain https URL on the default port without credentials, 'service' for
* a host that is not on the list.
*/
export function checkPushEndpoint(endpoint: string): 'ok' | 'endpoint' | 'service' {
if (endpoint.length > MAX_PUSH_ENDPOINT_LENGTH) return 'endpoint';
let url: URL;
try {
url = new URL(endpoint);
} catch {
return 'endpoint';
}
if (url.protocol !== 'https:' || url.username || url.password || url.port) return 'endpoint';
return isKnownPushServiceHost(url.hostname) ? 'ok' : 'service';
}
export function isPushServiceEndpoint(endpoint: string): boolean {
return checkPushEndpoint(endpoint) === 'ok';
}
/**
* Everything the Zod contract cannot say about a subscription: where it points,
* and that its keys have the sizes RFC 8291 needs (and the p256dh a point on
* the curve), so the sender never meets a row it cannot encrypt for.
*/
export function checkPushSubscription(input: PushSubscriptionInput): PushSubscriptionCheck {
const endpointVerdict = checkPushEndpoint(input.endpoint);
if (endpointVerdict !== 'ok') return { ok: false, error: PUSH_SUBSCRIPTION_ERRORS[endpointVerdict] };
const p256dh = decodeBase64Url(input.keys.p256dh);
if (!p256dh || !isP256Point(p256dh)) return { ok: false, error: PUSH_SUBSCRIPTION_ERRORS.p256dh };
const auth = decodeBase64Url(input.keys.auth);
if (auth?.length !== 16) return { ok: false, error: PUSH_SUBSCRIPTION_ERRORS.auth };
return {
ok: true,
value: { endpoint: input.endpoint, p256dh: p256dh.toString('base64url'), auth: auth.toString('base64url') },
};
}
@@ -0,0 +1,131 @@
import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../../database/database.service';
import type { CheckedPushSubscription } from './push-subscription.helpers';
export interface PushSubscriptionRow {
id: number;
user_id: number;
endpoint: string;
p256dh: string;
auth: string;
vapid_public_key: string;
user_agent: string | null;
created_at: string;
last_success_at: string | null;
failure_count: number;
}
/**
* How many browsers one account can receive push on. Generous for phones,
* tablets and a few desktop profiles; the cap only exists so a client that
* subscribes in a loop cannot grow the table or the fan-out without bound.
*/
export const MAX_PUSH_DEVICES_PER_USER = 20;
/** Only there to tell one user's devices apart in the table, never parsed, so a cut-off one does no harm. */
const USER_AGENT_MAX_LENGTH = 256;
/**
* The push_subscriptions table: one row per browser a user switched push on
* in. Only rows the checks in push-subscription.helpers.ts accepted get here.
*/
@Injectable()
export class PushSubscriptionsService {
constructor(private readonly db: DatabaseService) {}
/**
* Register a browser, or refresh it when it subscribes again. The endpoint
* is unique, so a browser shared by two accounts moves to whoever subscribed
* on it last instead of notifying both. A refresh renews created_at, which
* makes the cap drop the device that registered longest ago rather than one
* that is in daily use. Answers how many devices the user now has.
*/
upsert(
userId: number,
subscription: CheckedPushSubscription,
vapidPublicKey: string,
userAgent?: string | null,
): number {
const agent = userAgent ? userAgent.slice(0, USER_AGENT_MAX_LENGTH) : null;
return this.db.transaction(() => {
this.db.run(
`INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth, vapid_public_key, user_agent)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(endpoint) DO UPDATE SET
user_id = excluded.user_id,
p256dh = excluded.p256dh,
auth = excluded.auth,
vapid_public_key = excluded.vapid_public_key,
user_agent = excluded.user_agent,
created_at = CURRENT_TIMESTAMP,
failure_count = 0`,
userId,
subscription.endpoint,
subscription.p256dh,
subscription.auth,
vapidPublicKey,
agent,
);
const overflow = this.countForUser(userId) - MAX_PUSH_DEVICES_PER_USER;
if (overflow > 0) {
this.db.run(
`DELETE FROM push_subscriptions WHERE id IN (
SELECT id FROM push_subscriptions
WHERE user_id = ? AND endpoint <> ?
ORDER BY created_at ASC, id ASC
LIMIT ?
)`,
userId,
subscription.endpoint,
overflow,
);
}
return this.countForUser(userId);
});
}
/** Forget one of the caller's own browsers. Someone else's endpoint is never touched. */
removeForUser(userId: number, endpoint: string): boolean {
return (
this.db.run('DELETE FROM push_subscriptions WHERE user_id = ? AND endpoint = ?', userId, endpoint).changes > 0
);
}
listForUser(userId: number): PushSubscriptionRow[] {
return this.db.all<PushSubscriptionRow>('SELECT * FROM push_subscriptions WHERE user_id = ? ORDER BY id', userId);
}
countForUser(userId: number): number {
return this.db.get<{ n: number }>('SELECT COUNT(*) AS n FROM push_subscriptions WHERE user_id = ?', userId)?.n ?? 0;
}
hasAny(userId: number): boolean {
return !!this.db.get('SELECT 1 FROM push_subscriptions WHERE user_id = ? LIMIT 1', userId);
}
/** The sender's clean-up: the push service said the browser is gone, or the row can no longer be sent to. */
deleteById(id: number): void {
this.db.run('DELETE FROM push_subscriptions WHERE id = ?', id);
}
recordSuccess(id: number): void {
this.db.run(
'UPDATE push_subscriptions SET last_success_at = CURRENT_TIMESTAMP, failure_count = 0 WHERE id = ?',
id,
);
}
/**
* Counts one more failed send since the last success and answers the new
* count, read in the same statement so two sends at once cannot both see
* the old value. 0 when the row is gone already.
*/
recordFailure(id: number): number {
return (
this.db.get<{ failure_count: number }>(
'UPDATE push_subscriptions SET failure_count = failure_count + 1 WHERE id = ? RETURNING failure_count',
id,
)?.failure_count ?? 0
);
}
}
@@ -0,0 +1,77 @@
import { Body, Controller, Delete, Get, Headers, HttpCode, HttpException, Post, UseGuards } from '@nestjs/common';
import type { PushPublicKeyResult, PushSubscribeResult, PushUnsubscribeResult } from '@trek/shared';
import type { User } from '../../../types';
import { CurrentUser } from '../../auth/current-user.decorator';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { PushSubscribeDto, PushUnsubscribeDto } from '../notifications.dto';
import { checkPushSubscription } from './push-subscription.helpers';
import { PushSubscriptionsService } from './push-subscriptions.service';
import { PUSH_UNAVAILABLE_ERROR, PushUnavailableError, VapidKeysService } from './vapid-keys.service';
/**
* /api/notifications/push: how a browser signs up for Web Push (#894).
*
* The browser fetches the server's public key, subscribes with its push
* service, and hands the subscription over here; logging out or switching push
* off in that browser deletes it again. Which events arrive is the ordinary
* preference matrix ('push' column), and the test send is the generic
* POST /api/notifications/test/push.
*
* No MCP tool mirrors these routes on purpose: a subscription is created by a
* browser's push manager for that one browser, and there is nothing an MCP
* client could subscribe with.
*/
@Controller('api/notifications/push')
@UseGuards(JwtAuthGuard)
export class PushController {
constructor(
private readonly keys: VapidKeysService,
private readonly subscriptions: PushSubscriptionsService,
) {}
@Get('public-key')
publicKey(): PushPublicKeyResult {
return { publicKey: this.currentPublicKey() };
}
@Post('subscriptions')
@HttpCode(200)
subscribe(
@CurrentUser() user: User,
@Body() body: PushSubscribeDto,
@Headers('user-agent') userAgent?: string,
): PushSubscribeResult {
const checked = checkPushSubscription(body.subscription);
if ('error' in checked) throw new HttpException({ error: checked.error }, 400);
const devices = this.subscriptions.upsert(user.id, checked.value, this.currentPublicKey(), userAgent);
return { success: true, devices };
}
/**
* Idempotent: the push service may already have expired the row, and a
* browser logging out must not get an error for that. Only the caller's own
* endpoint can go; the same URL on someone else's account is left alone.
* Works while push is unavailable too, so a device can always be forgotten.
*/
@Delete('subscriptions')
@HttpCode(200)
unsubscribe(@CurrentUser() user: User, @Body() body: PushUnsubscribeDto): PushUnsubscribeResult {
this.subscriptions.removeForUser(user.id, body.endpoint);
return { success: true };
}
/**
* The key browsers subscribe with. While the key pair cannot be used, stored
* or from VAPID_* (the log says why), the answer is a 503: nothing could be
* signed for a new subscription, and the devices already subscribed stay as
* they are.
*/
private currentPublicKey(): string {
try {
return this.keys.getPublicKey();
} catch (err) {
if (err instanceof PushUnavailableError) throw new HttpException({ error: PUSH_UNAVAILABLE_ERROR }, 503);
throw err;
}
}
}
@@ -0,0 +1,301 @@
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
import { decodeBase64Url, isVapidSubject, readEnv, stripTrailingSlashes } from '../../../app-config';
import { logError, logInfo } from '../../audit/audit-log.logger';
import { decrypt_api_key, encrypt_api_key } from '../../common/crypto/apiKeyCrypto';
import { DatabaseService } from '../../database/database.service';
import { generateVapidKeyPair, isVapidKeyPair, type VapidKeyPair } from './web-push-crypto';
/** app_settings rows holding the generated pair. The private half is stored encrypted. */
export const VAPID_PUBLIC_KEY_SETTING = 'web_push_vapid_public_key';
export const VAPID_PRIVATE_KEY_SETTING = 'web_push_vapid_private_key';
/** The VAPID contact when nothing better is configured: a real https URL every push service accepts. */
export const FALLBACK_VAPID_SUBJECT = 'https://github.com/liketrek/TREK';
/** What the push routes answer while the key pair cannot be used. */
export const PUSH_UNAVAILABLE_ERROR = 'Web Push is currently unavailable on this server';
export interface ResolvedVapidKeys extends VapidKeyPair {
source: 'env' | 'database';
}
/**
* Thrown by getKeys() while push is off because the pair it would sign with
* cannot be used: the VAPID_* variables name one that cannot, or, with them
* unset, the stored one cannot. The reason is in the server log (once, without
* key material); this error only says that nothing can be signed right now.
*/
export class PushUnavailableError extends Error {
constructor() {
super('there is no usable VAPID key pair; see the earlier Web Push error in the log');
this.name = 'PushUnavailableError';
}
}
type UnusableReason = 'incomplete' | 'undecryptable' | 'mismatched';
type StoredPair =
| { state: 'absent' }
| { state: 'usable'; keys: VapidKeyPair }
| { state: UnusableReason; fingerprint: string };
type PresentPair = Exclude<StoredPair, { state: 'absent' }>;
type EnvPair =
| { state: 'unset' }
| { state: 'usable'; keys: VapidKeyPair }
| { state: 'unusable'; fingerprint: string; problem: string };
const DELETE_BOTH_ROWS =
`delete both app_settings rows ${VAPID_PUBLIC_KEY_SETTING} and ${VAPID_PRIVATE_KEY_SETTING} ` +
'to generate a new pair (every device then has to turn push on again)';
/** The admin-facing explanation for each unusable state. Never contains key material. */
const UNUSABLE_MESSAGES: Record<UnusableReason, string> = {
incomplete: `only one half of the stored VAPID key pair exists. To start over, ${DELETE_BOTH_ROWS}.`,
undecryptable:
'the stored VAPID private key cannot be decrypted with the current ENCRYPTION_KEY (for example after a ' +
'restore under a different key). Start the server with the ENCRYPTION_KEY it was encrypted with to bring ' +
`push back as it was, or ${DELETE_BOTH_ROWS}.`,
mismatched: `the stored VAPID private key does not belong to the stored public key. To start over, ${DELETE_BOTH_ROWS}.`,
};
/** Re-encoded without padding, so the key the browser gets and the one rows are compared with is one string. */
function canonical(value: string): string {
return decodeBase64Url(value)?.toString('base64url') ?? value;
}
/** An https URL on a host other than localhost: what APP_URL has to be to serve as the VAPID contact. */
function isPublicHttpsUrl(value: string): boolean {
try {
const url = new URL(value);
return url.protocol === 'https:' && url.hostname !== 'localhost';
} catch {
return false;
}
}
/**
* The server's VAPID identity: the key pair every subscription is bound to, and
* the contact (`sub`) sent with each request.
*
* VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY win when both are set and belong
* together. Otherwise the pair lives in app_settings, created once and then
* kept: it travels with the database into every backup, where a key file in
* data/ would not, and a restore that minted a new pair would silently cut off
* every device.
*
* When the pair push should sign with cannot be used, push is off: it never
* falls back on another pair. A pair in the environment that does not fit
* together (or only one half of it) is logged rather than refusing to boot,
* and push stays off until the variables are fixed, even while a usable pair
* is stored: the devices subscribed with the environment key, so the first
* send under any other pair would drop every one of them. A stored pair that
* is there but cannot be used (a private key the current ENCRYPTION_KEY cannot
* open, halves that do not match, one half missing) is never replaced either.
* Either way the log says why, every device stays subscribed, and fixing the
* variables or starting with the right ENCRYPTION_KEY again brings everything
* back unchanged. A new pair is only ever generated while neither row exists
* and neither VAPID_* variable is set.
*/
@Injectable()
export class VapidKeysService implements OnApplicationBootstrap {
/** The last environment problem logged, so a bad pair is reported once and not on every send. */
private reportedEnvProblem: string | null = null;
/** The last stored-pair problem logged, for the same reason. */
private reportedStoredProblem: string | null = null;
/** The decrypted stored pair, keyed by the ciphertext it came from. */
private stored: { ciphertext: string; keys: VapidKeyPair } | null = null;
constructor(private readonly db: DatabaseService) {}
/**
* Make sure the pair exists before the first request. The public-key GET is
* the first thing a browser asks for, and a GET must not write; creating the
* pair here keeps that route a read. The lazy path in getKeys() covers
* instances built without the Nest lifecycle and a database restored under a
* running server.
*/
onApplicationBootstrap(): void {
this.succeeds(() => this.getKeys());
}
/**
* Whether there is a pair to sign with right now. Only reads, so the
* dispatcher and the preference matrix GET can ask on every call: while
* neither row exists the answer is yes and nothing is written, because the
* next send or subscribe creates the pair through getKeys(). Never throws;
* the reason for a no is in the log.
*/
isAvailable(): boolean {
return this.succeeds(() => this.checkUsable());
}
/**
* The pair to sign with, creating the stored one first while neither row
* exists. Throws PushUnavailableError while the pair it would use cannot be.
*/
getKeys(): ResolvedVapidKeys {
const fromEnv = this.envKeys();
if (fromEnv) return { ...fromEnv, source: 'env' };
return { ...this.usableStored(this.readOrCreateStored()), source: 'database' };
}
getPublicKey(): string {
return this.getKeys().publicKey;
}
/**
* The `sub` claim: VAPID_SUBJECT, else APP_URL when it is public https, else
* the project URL. Push services use it to reach whoever runs the sender, and
* Apple refuses a token without a valid one. Only APP_URL itself counts, not
* getAppUrl()'s stand-ins: the first ALLOWED_ORIGINS entry can be another
* site that is merely allowed to call this API, and http://localhost is no
* valid subject.
*/
getSubject(): string {
const env = readEnv();
const configured = env.push.vapidSubject;
if (configured && isVapidSubject(configured)) return configured;
const appUrl = env.app.appUrl?.trim();
return appUrl && isPublicHttpsUrl(appUrl) ? stripTrailingSlashes(appUrl) : FALLBACK_VAPID_SUBJECT;
}
/** getKeys() without the create: the same refusals, and a missing stored pair counts as usable. */
private checkUsable(): void {
if (this.envKeys()) return;
const stored = this.readStored();
if (stored.state !== 'absent') this.usableStored(stored);
}
private succeeds(attempt: () => unknown): boolean {
try {
attempt();
return true;
} catch (err) {
// An unusable pair has already been explained where it was found.
if (!(err instanceof PushUnavailableError)) {
logError(`Web Push: could not prepare the VAPID key pair: ${err instanceof Error ? err.message : err}`);
}
return false;
}
}
/**
* The pair from VAPID_*, or null while neither variable is set. A pair that
* is set but cannot be used turns push off rather than handing out the
* stored pair (or a new one) in its place: the devices subscribed with the
* environment key, and the first send under another pair would drop them
* all. Push comes back unchanged once the variables are fixed.
*/
private envKeys(): VapidKeyPair | null {
const env = this.readEnvPair();
if (env.state !== 'unusable') {
this.reportedEnvProblem = null;
return env.state === 'usable' ? env.keys : null;
}
if (this.reportedEnvProblem !== env.fingerprint) {
this.reportedEnvProblem = env.fingerprint;
logError(
`Web Push is off: ${env.problem}. Set both variables to the two halves of one pair to turn it back on. ` +
'Until then nothing is sent, every device stays subscribed, and no pair stored in the database is ' +
'used in its place.',
);
}
throw new PushUnavailableError();
}
/** What the VAPID_* variables hold. The fingerprint only tells one broken state from the next. */
private readEnvPair(): EnvPair {
const { vapidPublicKey, vapidPrivateKey } = readEnv().push;
if (!vapidPublicKey && !vapidPrivateKey) return { state: 'unset' };
if (!vapidPublicKey || !vapidPrivateKey) {
return {
state: 'unusable',
fingerprint: `half:${vapidPublicKey ?? ''}`,
problem: `${vapidPublicKey ? 'VAPID_PUBLIC_KEY' : 'VAPID_PRIVATE_KEY'} is set without its other half`,
};
}
if (!isVapidKeyPair(vapidPublicKey, vapidPrivateKey)) {
return {
state: 'unusable',
fingerprint: `pair:${vapidPublicKey}`,
problem: 'VAPID_PUBLIC_KEY does not belong to VAPID_PRIVATE_KEY',
};
}
return { state: 'usable', keys: { publicKey: canonical(vapidPublicKey), privateKey: canonical(vapidPrivateKey) } };
}
private setting(key: string): string | null {
return this.db.get<{ value: string | null }>('SELECT value FROM app_settings WHERE key = ?', key)?.value || null;
}
private writeSetting(key: string, value: string): void {
this.db.run(
`INSERT INTO app_settings (key, value) VALUES (?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
key,
value,
);
}
/** What app_settings holds right now. The fingerprint only tells one broken state from the next. */
private readStored(): StoredPair {
const publicKey = this.setting(VAPID_PUBLIC_KEY_SETTING);
const ciphertext = this.setting(VAPID_PRIVATE_KEY_SETTING);
if (!publicKey && !ciphertext) return { state: 'absent' };
const fingerprint = `${publicKey ?? ''}\n${ciphertext ?? ''}`;
if (!publicKey || !ciphertext) return { state: 'incomplete', fingerprint };
if (this.stored?.ciphertext === ciphertext && this.stored.keys.publicKey === publicKey) {
return { state: 'usable', keys: this.stored.keys };
}
const privateKey = decrypt_api_key(ciphertext);
if (!privateKey) return { state: 'undecryptable', fingerprint };
if (!isVapidKeyPair(publicKey, privateKey)) return { state: 'mismatched', fingerprint };
const keys = { publicKey, privateKey };
this.stored = { ciphertext, keys };
return { state: 'usable', keys };
}
/**
* The stored pair, created first only when neither row exists: checked again
* inside the transaction and written in it, both rows or neither, so the
* pair is created exactly once.
*/
private readOrCreateStored(): PresentPair {
const first = this.readStored();
if (first.state !== 'absent') return first;
return this.db.transaction((): PresentPair => {
const again = this.readStored();
if (again.state !== 'absent') return again;
return { state: 'usable', keys: this.generateAndStore() };
});
}
/** The keys of a stored pair, or PushUnavailableError (logged once per state) when it cannot be used. */
private usableStored(found: PresentPair): VapidKeyPair {
if (found.state === 'usable') {
this.reportedStoredProblem = null;
return found.keys;
}
this.reportStoredProblem(found.state, found.fingerprint);
throw new PushUnavailableError();
}
private reportStoredProblem(reason: UnusableReason, fingerprint: string): void {
const key = `${reason}:${fingerprint}`;
if (this.reportedStoredProblem === key) return;
this.reportedStoredProblem = key;
logError(`Web Push is off: ${UNUSABLE_MESSAGES[reason]}`);
}
private generateAndStore(): VapidKeyPair {
const keys = generateVapidKeyPair();
const ciphertext = encrypt_api_key(keys.privateKey);
this.writeSetting(VAPID_PUBLIC_KEY_SETTING, keys.publicKey);
this.writeSetting(VAPID_PRIVATE_KEY_SETTING, ciphertext);
this.stored = { ciphertext, keys };
logInfo('Web Push: generated the VAPID key pair for this instance.');
return keys;
}
}
@@ -0,0 +1,214 @@
import {
createCipheriv,
createECDH,
createPrivateKey,
ECDH,
generateKeyPairSync,
hkdfSync,
randomBytes,
type KeyObject,
} from 'node:crypto';
import jwt from 'jsonwebtoken';
import { decodeBase64Url } from '../../../app-config';
/**
* Web Push message encryption (RFC 8291, `aes128gcm` from RFC 8188) and the
* VAPID Authorization header (RFC 8292), on node:crypto and the jsonwebtoken
* the server already signs its sessions with.
*
* Pure: no database, no network, no DI. The `web-push` package does the same
* arithmetic, but it posts through its own https.request and so past the SSRF
* guard; the request is the part this domain has to own, and what is left of
* the package is this file.
*/
/** Record size announced in the header. One record carries the whole message. */
export const PUSH_RECORD_SIZE = 4096;
const P256_POINT_BYTES = 65;
const AUTH_SECRET_BYTES = 16;
const SALT_BYTES = 16;
const GCM_TAG_BYTES = 16;
/** salt (16) + rs (4) + idlen (1) + keyid (the 65-byte sender key). */
const HEADER_BYTES = SALT_BYTES + 4 + 1 + P256_POINT_BYTES;
const KEY_INFO_PREFIX = Buffer.from('WebPush: info\0', 'latin1');
const CEK_INFO = Buffer.from('Content-Encoding: aes128gcm\0', 'latin1');
const NONCE_INFO = Buffer.from('Content-Encoding: nonce\0', 'latin1');
/** Padding delimiter of the last (here: only) record, RFC 8188 section 2. */
const LAST_RECORD_DELIMITER = Buffer.from([0x02]);
/** Largest plaintext that still fits one record next to its delimiter and tag. */
export const MAX_PUSH_PLAINTEXT_BYTES = PUSH_RECORD_SIZE - HEADER_BYTES - 1 - GCM_TAG_BYTES;
/**
* How long a VAPID token is good for. RFC 8292 allows up to 24 hours and Apple
* refuses anything longer, so this stays well inside it.
*/
export const VAPID_TOKEN_TTL_SECONDS = 12 * 60 * 60;
/** A VAPID key pair in the form browsers and the Web Push tools use: base64url, raw. */
export interface VapidKeyPair {
/** Uncompressed P-256 point, 65 bytes. What the browser subscribes with. */
publicKey: string;
/** The 32-byte private scalar. */
privateKey: string;
}
/** The two secrets a browser hands over with its subscription. */
export interface PushEncryptionKeys {
/** The browser's P-256 public key, uncompressed. */
p256dh: Buffer;
/** The 16-byte authentication secret. */
auth: Buffer;
}
/**
* Fixed inputs for the RFC 8291 test vector. Leave both unset for real
* messages: every message needs a fresh salt and a fresh sender key, or the
* same key and nonce would encrypt two plaintexts.
*/
export interface PushEncryptionOptions {
salt?: Buffer;
senderPrivateKey?: Buffer;
}
function hkdf(ikm: Buffer, salt: Buffer, info: Buffer, length: number): Buffer {
return Buffer.from(hkdfSync('sha256', ikm, salt, info, length));
}
/** True for a point that is actually on P-256, not just 65 bytes that start with 0x04. */
export function isP256Point(bytes: Buffer): boolean {
if (bytes.length !== P256_POINT_BYTES || bytes[0] !== 0x04) return false;
try {
ECDH.convertKey(bytes, 'prime256v1');
return true;
} catch {
return false;
}
}
/** A fresh P-256 pair. Exported as JWK so both halves come out at full length. */
export function generateVapidKeyPair(): VapidKeyPair {
const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
const { x, y, d } = privateKey.export({ format: 'jwk' });
if (!x || !y || !d) throw new Error('P-256 key export did not produce x, y and d');
return {
publicKey: Buffer.concat([Buffer.from([0x04]), Buffer.from(x, 'base64url'), Buffer.from(y, 'base64url')]).toString(
'base64url',
),
privateKey: d,
};
}
/** The public key a private scalar belongs to, or null when the scalar is not a usable P-256 key. */
export function derivePublicKey(privateKey: string): Buffer | null {
const scalar = decodeBase64Url(privateKey);
if (scalar?.length !== 32) return null;
try {
const ecdh = createECDH('prime256v1');
ecdh.setPrivateKey(scalar);
return ecdh.getPublicKey();
} catch {
return null;
}
}
/** Whether the two halves belong together. Compared as bytes, so padding and the like do not matter. */
export function isVapidKeyPair(publicKey: string, privateKey: string): boolean {
const expected = derivePublicKey(privateKey);
const given = decodeBase64Url(publicKey);
return !!expected && !!given && given.equals(expected);
}
/**
* Encrypt one push message for one browser (RFC 8291 section 3.4): ECDH with
* the browser key, HKDF over the shared secret and the auth secret, then a
* single AES-128-GCM record behind the aes128gcm header, whose key id is the
* sender's public key.
*/
export function encryptPushMessage(
plaintext: Buffer,
keys: PushEncryptionKeys,
options: PushEncryptionOptions = {},
): Buffer {
if (!isP256Point(keys.p256dh)) throw new Error('p256dh is not an uncompressed P-256 public key');
if (keys.auth.length !== AUTH_SECRET_BYTES) throw new Error('auth secret must be 16 bytes');
if (plaintext.length > MAX_PUSH_PLAINTEXT_BYTES) {
throw new Error(`push payload of ${plaintext.length} bytes does not fit one record`);
}
const salt = options.salt ?? randomBytes(SALT_BYTES);
if (salt.length !== SALT_BYTES) throw new Error('salt must be 16 bytes');
const sender = createECDH('prime256v1');
if (options.senderPrivateKey) sender.setPrivateKey(options.senderPrivateKey);
else sender.generateKeys();
const senderPublicKey = sender.getPublicKey();
const ecdhSecret = sender.computeSecret(keys.p256dh);
const keyInfo = Buffer.concat([KEY_INFO_PREFIX, keys.p256dh, senderPublicKey]);
const ikm = hkdf(ecdhSecret, keys.auth, keyInfo, 32);
const contentKey = hkdf(ikm, salt, CEK_INFO, 16);
const nonce = hkdf(ikm, salt, NONCE_INFO, 12);
const cipher = createCipheriv('aes-128-gcm', contentKey, nonce);
const record = Buffer.concat([
cipher.update(plaintext),
cipher.update(LAST_RECORD_DELIMITER),
cipher.final(),
cipher.getAuthTag(),
]);
const header = Buffer.alloc(SALT_BYTES + 4 + 1);
salt.copy(header, 0);
header.writeUInt32BE(PUSH_RECORD_SIZE, SALT_BYTES);
header.writeUInt8(senderPublicKey.length, SALT_BYTES + 4);
return Buffer.concat([header, senderPublicKey, record]);
}
/** The signing key, and the public key re-encoded the way the `k=` parameter wants it (no padding). */
function vapidSigningKey(keys: VapidKeyPair): { signingKey: KeyObject; publicKey: string } {
const point = decodeBase64Url(keys.publicKey);
const scalar = decodeBase64Url(keys.privateKey);
if (point?.length !== P256_POINT_BYTES || scalar?.length !== 32) throw new Error('VAPID key pair is malformed');
const signingKey = createPrivateKey({
key: {
kty: 'EC',
crv: 'P-256',
x: point.subarray(1, 33).toString('base64url'),
y: point.subarray(33).toString('base64url'),
d: scalar.toString('base64url'),
},
format: 'jwk',
});
return { signingKey, publicKey: point.toString('base64url') };
}
/**
* Returns a function that builds the Authorization header for an endpoint
* (RFC 8292): `vapid t=<ES256 JWT>, k=<public key>`, the token's audience being
* the endpoint's origin. Tokens are reused per origin for the life of the
* signer, which is one delivery, so a user with three Chrome devices signs once.
*/
export function createVapidSigner(keys: VapidKeyPair, subject: string, now: () => number = Date.now) {
const { signingKey, publicKey } = vapidSigningKey(keys);
const byOrigin = new Map<string, string>();
return (endpoint: string): string => {
const audience = new URL(endpoint).origin;
let header = byOrigin.get(audience);
if (!header) {
const token = jwt.sign(
{ aud: audience, exp: Math.floor(now() / 1000) + VAPID_TOKEN_TTL_SECONDS, sub: subject },
signingKey,
// The three claims RFC 8292 names and nothing else: an extra iat buys
// nothing and is one more thing a strict push service could object to.
{ algorithm: 'ES256', noTimestamp: true },
);
header = `vapid t=${token}, k=${publicKey}`;
byOrigin.set(audience, header);
}
return header;
};
}
export type VapidSigner = ReturnType<typeof createVapidSigner>;
@@ -0,0 +1,292 @@
import { Injectable } from '@nestjs/common';
import type { ChannelTestResult, PushPayload } from '@trek/shared';
import { decodeBase64Url } from '../../../app-config';
import { discardBody, readCappedText } from '../../../utils/cappedFetch';
import { safeFetchFollow, SsrfBlockedError } from '../../../utils/ssrfGuard';
import { logError, logInfo } from '../../audit/audit-log.logger';
import type { ChannelMessage } from '../notification-events';
import { isPushServiceEndpoint } from '../push/push-subscription.helpers';
import { PushSubscriptionsService, type PushSubscriptionRow } from '../push/push-subscriptions.service';
import { PUSH_UNAVAILABLE_ERROR, VapidKeysService } from '../push/vapid-keys.service';
import { createVapidSigner, encryptPushMessage, type VapidSigner } from '../push/web-push-crypto';
/**
* Ceiling for the JSON the service worker receives. A single aes128gcm record
* can carry just under 4 KB and some push services refuse anything larger, so
* the payload stays well clear of that and the body gives way first.
*/
export const MAX_PUSH_PAYLOAD_BYTES = 3000;
const TITLE_MAX_CHARS = 120;
/** A navigate target is an app path like /trips/12; anything longer is not one. */
const URL_MAX_LENGTH = 256;
const ELLIPSIS = '…';
const PUSH_TIMEOUT_MS = 10_000;
/** A day: a reminder that reaches a phone after a longer flight is still worth showing, a week-old one is not. */
const PUSH_TTL_SECONDS = 24 * 60 * 60;
const ERROR_BODY_MAX_BYTES = 1024;
/**
* How many failed sends in a row (with no success between them) a device gets
* before a 403 removes it. A 403 is not proof the subscription is dead: Apple
* also answers it for a token it rejects (BadJwtToken, a bad subject, clock
* skew), which is the server's problem and must not cost the user their device
* on the first try.
*/
export const FORBIDDEN_FAILURES_BEFORE_REMOVAL = 3;
/**
* The one event whose notifications replace each other: a burst of chat
* messages in one trip shows as one notification that keeps updating. Every
* other event stands on its own, so two todos, two bookings or two plugin
* notices never hide one another.
*/
const COLLAPSING_EVENT = 'collab_message';
type Urgency = 'normal' | 'high';
/** The events that are about a date, where arriving late defeats the point (RFC 8030 section 5.3). */
const HIGH_URGENCY_EVENTS: ReadonlySet<string> = new Set(['trip_reminder', 'todo_due']);
/** No tag either: two presses of Send test are two notifications, like two of anything but chat. */
const TEST_PAYLOAD: PushPayload = {
title: 'Test Notification',
body: 'This is a test notification from TREK. If you received this, push notifications are working on this device.',
url: '/settings?tab=notifications',
};
/**
* The target the worker may open: a path on this origin only. Absolute URLs
* and protocol-relative ones (`//host`, `/\host`) would take the click to
* another site, so they are dropped rather than passed on.
*/
export function samePagePath(target: string | undefined): string | undefined {
if (!target || target.length > URL_MAX_LENGTH) return undefined;
if (!/^\/(?![/\\])[\x21-\x7e]*$/.test(target)) return undefined;
return target;
}
function truncateChars(value: string, max: number): string {
const chars = Array.from(value);
return chars.length <= max ? value : `${chars.slice(0, max - 1).join('')}${ELLIPSIS}`;
}
function payloadBytes(payload: PushPayload): number {
return Buffer.byteLength(JSON.stringify(payload), 'utf8');
}
/**
* The rendered notification as the service worker gets it. Title and body are
* already in the recipient's language; the worker has no translations. Only
* chat messages carry a tag, `collab_message:<trip path>`, so a burst of them in
* one trip shows as one notification that keeps updating instead of a pile of
* them. Everything else has no tag and never replaces an earlier notification.
*
* The body is cut, at a character boundary and with an ellipsis, until the
* JSON fits MAX_PUSH_PAYLOAD_BYTES. The title and the path are capped first, so
* whatever they are, the body always keeps room of its own.
*/
export function buildPushPayload(
msg: Pick<ChannelMessage, 'event' | 'title' | 'body' | 'navigateTarget'>,
): PushPayload {
const url = samePagePath(msg.navigateTarget);
const base: PushPayload = {
title: truncateChars(msg.title, TITLE_MAX_CHARS),
body: '',
...(url ? { url } : {}),
...(url && msg.event === COLLAPSING_EVENT ? { tag: `${COLLAPSING_EVENT}:${url}` } : {}),
};
const full = { ...base, body: msg.body };
if (payloadBytes(full) <= MAX_PUSH_PAYLOAD_BYTES) return full;
const chars = Array.from(msg.body);
let fits = 0;
let tooLong = chars.length;
// Largest prefix that still fits with the ellipsis behind it.
while (tooLong - fits > 1) {
const mid = Math.floor((fits + tooLong) / 2);
if (payloadBytes({ ...base, body: `${chars.slice(0, mid).join('')}${ELLIPSIS}` }) <= MAX_PUSH_PAYLOAD_BYTES)
fits = mid;
else tooLong = mid;
}
return { ...base, body: `${chars.slice(0, fits).join('')}${ELLIPSIS}` };
}
function hostOf(endpoint: string): string {
try {
return new URL(endpoint).hostname;
} catch {
return 'invalid-endpoint';
}
}
/**
* Web Push delivery: encrypt the payload for each of a user's browsers and
* POST it to that browser's push service, through the SSRF guard.
*
* Mirrors the ntfy and webhook transports: every failure is logged and turned
* into `false`, nothing throws into the dispatcher. It also tends the table as
* it goes, because the push services are the only ones who know a browser is
* gone: 404 and 410 mean the subscription expired or was revoked, and the row
* is deleted at once. A 403 is counted like any other failure and only removes
* the row once it has failed FORBIDDEN_FAILURES_BEFORE_REMOVAL times in a row,
* because the same status also means a rejected token. While the server's key
* pair is unusable (VapidKeysService logs why) nothing is sent, every row
* stays and the test send says so. Endpoints are capability URLs, so the log
* names the push service host, never the URL.
*/
@Injectable()
export class WebPushService {
constructor(
private readonly keys: VapidKeysService,
private readonly subscriptions: PushSubscriptionsService,
) {}
hasDevices(userId: number): boolean {
return this.subscriptions.hasAny(userId);
}
/**
* False while the server has no key pair it can sign with. The channel
* reports it as its instance readiness, so the dispatcher skips push for
* everyone (every device stays subscribed) and the user's settings drop the
* Push card and column instead of offering a switch that could only fail.
*/
isAvailable(): boolean {
return this.keys.isAvailable();
}
/** True when at least one of the user's browsers accepted the message. */
sendToUser(userId: number, msg: ChannelMessage): Promise<boolean> {
const urgency: Urgency = HIGH_URGENCY_EVENTS.has(msg.event) ? 'high' : 'normal';
return this.deliver(userId, buildPushPayload(msg), urgency, msg.event);
}
/** The Send test button: a short fixed message to every browser the user turned push on in. */
async sendTest(userId: number): Promise<ChannelTestResult> {
if (!this.isAvailable()) return { success: false, error: PUSH_UNAVAILABLE_ERROR };
const sent = await this.deliver(userId, TEST_PAYLOAD, 'normal', 'test');
return sent ? { success: true } : { success: false, error: 'Failed to send push notification' };
}
private async deliver(userId: number, payload: PushPayload, urgency: Urgency, event: string): Promise<boolean> {
try {
const rows = this.subscriptions.listForUser(userId);
if (rows.length === 0) return false;
const keys = this.keys.getKeys();
const sign = createVapidSigner(keys, this.keys.getSubject());
const plaintext = Buffer.from(JSON.stringify(payload), 'utf8');
const results = await Promise.all(
rows.map((row) => this.deliverTo(row, plaintext, keys.publicKey, sign, urgency, event)),
);
return results.includes(true);
} catch (err) {
logError(`Web Push failed event=${event} user=${userId}: ${err instanceof Error ? err.message : err}`);
return false;
}
}
private async deliverTo(
row: PushSubscriptionRow,
plaintext: Buffer,
publicKey: string,
sign: VapidSigner,
urgency: Urgency,
event: string,
): Promise<boolean> {
const host = hostOf(row.endpoint);
if (row.vapid_public_key !== publicKey) {
// Subscribed against a key this server no longer signs with, so the push
// service would refuse every message. Until the browser subscribes again
// with the current key there is nothing to send to.
this.subscriptions.deleteById(row.id);
logInfo(`Web Push dropped a device subscribed with a previous server key user=${row.user_id} host=${host}`);
return false;
}
if (!isPushServiceEndpoint(row.endpoint)) {
this.subscriptions.deleteById(row.id);
logError(`Web Push dropped a device whose endpoint is not a known push service user=${row.user_id} host=${host}`);
return false;
}
try {
const p256dh = decodeBase64Url(row.p256dh);
const auth = decodeBase64Url(row.auth);
if (!p256dh || !auth) throw new Error('stored subscription keys are not base64url');
const body = encryptPushMessage(plaintext, { p256dh, auth });
// maxRedirects 0: a push service answers, it does not redirect, and a
// redirect would carry the VAPID token somewhere it was not minted for.
// bypassInternalIpAllowed keeps private addresses closed even on an
// install that opened ALLOW_INTERNAL_NETWORK for its own services.
const res = await safeFetchFollow(
row.endpoint,
{
method: 'POST',
headers: {
TTL: String(PUSH_TTL_SECONDS),
Urgency: urgency,
'Content-Encoding': 'aes128gcm',
'Content-Type': 'application/octet-stream',
Authorization: sign(row.endpoint),
},
body: new Uint8Array(body),
signal: AbortSignal.timeout(PUSH_TIMEOUT_MS),
},
{ maxRedirects: 0, bypassInternalIpAllowed: true },
);
return await this.settle(row, res, host, event);
} catch (err) {
this.subscriptions.recordFailure(row.id);
if (err instanceof SsrfBlockedError) {
logError(
`Web Push blocked by SSRF guard event=${event} user=${row.user_id} host=${host} reason=${err.message}`,
);
} else {
logError(
`Web Push failed event=${event} user=${row.user_id} host=${host}: ${err instanceof Error ? err.message : err}`,
);
}
return false;
}
}
private async settle(row: PushSubscriptionRow, res: Response, host: string, event: string): Promise<boolean> {
if (res.ok) {
discardBody(res);
this.subscriptions.recordSuccess(row.id);
logInfo(`Web Push sent event=${event} user=${row.user_id} host=${host}`);
return true;
}
const { text } = await readCappedText(res, ERROR_BODY_MAX_BYTES).catch(() => ({ text: '' }));
if (res.status === 404 || res.status === 410) {
this.subscriptions.deleteById(row.id);
logInfo(`Web Push removed an expired device (HTTP ${res.status}) user=${row.user_id} host=${host}`);
return false;
}
if (res.status === 403) {
// Either the subscription was made for a different key, or the push
// service rejects the token itself (Apple's BadJwtToken), which is a
// configuration problem and not the device's. Only a run of refusals
// with no success between them removes the row; the reason is logged
// every time so the second case can be told apart.
const failures = this.subscriptions.recordFailure(row.id);
if (failures >= FORBIDDEN_FAILURES_BEFORE_REMOVAL) {
this.subscriptions.deleteById(row.id);
logError(
`Web Push removed a device after ${failures} failed sends in a row ending in HTTP 403 ` +
`user=${row.user_id} host=${host}: ${text}`,
);
} else {
logError(
`Web Push HTTP 403 event=${event} user=${row.user_id} host=${host} ` +
`(failure ${failures} of ${FORBIDDEN_FAILURES_BEFORE_REMOVAL} before removal): ${text}`,
);
}
return false;
}
this.subscriptions.recordFailure(row.id);
logError(`Web Push HTTP ${res.status} event=${event} user=${row.user_id} host=${host}: ${text}`);
return false;
}
}
+268
View File
@@ -0,0 +1,268 @@
/**
* Web Push routes e2e: /api/notifications/push/* and the push test send
* through the real JwtAuthGuard, the Zod pipe and the real providers on a temp
* SQLite db. Only the outbound POST (safeFetchFollow) is replaced.
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
import request from 'supertest';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import { createECDH } from 'node:crypto';
import { Test } from '@nestjs/testing';
import { seedUser, sessionCookie } from './harness';
// The harness db (users for the guard) plus the two tables push reads, built
// inside the factory; the test reaches it through the mocked module.
vi.mock('../../src/db/database', async () => {
const { createTempDb } = await import('./harness');
const db = createTempDb();
db.exec('CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);');
// Same DDL as migration 244.
db.exec(`CREATE TABLE push_subscriptions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
endpoint TEXT NOT NULL UNIQUE,
p256dh TEXT NOT NULL,
auth TEXT NOT NULL,
vapid_public_key TEXT NOT NULL,
user_agent TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_success_at TEXT,
failure_count INTEGER NOT NULL DEFAULT 0
);`);
return { db, closeDb: () => {}, reinitialize: () => {} };
});
const { safeFetchFollow } = vi.hoisted(() => ({ safeFetchFollow: vi.fn() }));
vi.mock('../../src/utils/ssrfGuard', async (importOriginal) => ({
...(await importOriginal<typeof import('../../src/utils/ssrfGuard')>()),
safeFetchFollow,
}));
import { db } from '../../src/db/database';
import { DatabaseModule } from '../../src/nest/database/database.module';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { NotificationsModule } from '../../src/nest/notifications/notifications.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
const ENDPOINT = 'https://fcm.googleapis.com/fcm/send/e2e-device';
function subscription(endpoint = ENDPOINT) {
const ua = createECDH('prime256v1');
ua.generateKeys();
return {
endpoint,
expirationTime: null,
keys: { p256dh: ua.getPublicKey('base64url'), auth: Buffer.alloc(16, 3).toString('base64url') },
};
}
function rows() {
return db
.prepare('SELECT user_id, endpoint, vapid_public_key, user_agent FROM push_subscriptions ORDER BY id')
.all() as {
user_id: number;
endpoint: string;
vapid_public_key: string;
user_agent: string | null;
}[];
}
describe('Web Push e2e (real auth guard + temp SQLite)', () => {
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
async function build() {
const moduleRef = await Test.createTestingModule({
imports: [DatabaseModule, RealtimeModule, NotificationsModule],
}).compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalPipes(new ZodValidationPipe());
nest.useGlobalFilters(new TrekExceptionFilter());
await nest.init();
return nest;
}
beforeAll(async () => {
seedUser(db, { id: 1, email: 'one@example.test' });
seedUser(db, { id: 2, email: 'two@example.test' });
app = await build();
server = app.getHttpServer();
});
beforeEach(() => {
db.prepare('DELETE FROM push_subscriptions').run();
safeFetchFollow.mockReset();
});
afterAll(async () => {
await app.close();
});
it('401 on every push route without a session cookie', async () => {
expect((await request(server).get('/api/notifications/push/public-key')).status).toBe(401);
expect(
(await request(server).post('/api/notifications/push/subscriptions').send({ subscription: subscription() }))
.status,
).toBe(401);
expect(
(await request(server).delete('/api/notifications/push/subscriptions').send({ endpoint: ENDPOINT })).status,
).toBe(401);
});
it('GET public-key: the pair exists from bootstrap on, so the route only reads it', async () => {
const stored = db.prepare("SELECT value FROM app_settings WHERE key = 'web_push_vapid_public_key'").get() as {
value: string;
};
const res = await request(server).get('/api/notifications/push/public-key').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual({ publicKey: stored.value });
const raw = Buffer.from(res.body.publicKey, 'base64url');
expect(raw.length).toBe(65);
expect(raw[0]).toBe(0x04);
});
it('POST subscriptions: 200 with the device count, stored against the served key', async () => {
const { body: key } = await request(server)
.get('/api/notifications/push/public-key')
.set('Cookie', sessionCookie(1));
const res = await request(server)
.post('/api/notifications/push/subscriptions')
.set('Cookie', sessionCookie(1))
.set('User-Agent', 'e2e-browser/1.0')
.send({ subscription: subscription() });
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true, devices: 1 });
expect(rows()).toEqual([
{ user_id: 1, endpoint: ENDPOINT, vapid_public_key: key.publicKey, user_agent: 'e2e-browser/1.0' },
]);
});
it('POST subscriptions: the same browser subscribing for another account moves to it', async () => {
await request(server)
.post('/api/notifications/push/subscriptions')
.set('Cookie', sessionCookie(1))
.send({ subscription: subscription() });
const res = await request(server)
.post('/api/notifications/push/subscriptions')
.set('Cookie', sessionCookie(2))
.send({ subscription: subscription() });
expect(res.body).toEqual({ success: true, devices: 1 });
expect(rows().map((r) => r.user_id)).toEqual([2]);
});
it('POST subscriptions: 400 with the bespoke message for a host that is not a push service', async () => {
const res = await request(server)
.post('/api/notifications/push/subscriptions')
.set('Cookie', sessionCookie(1))
.send({ subscription: subscription('https://example.com/collect') });
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'Push endpoint is not a known push service' });
expect(rows()).toEqual([]);
});
it('POST subscriptions: 400 from the contract when the keys are missing', async () => {
const res = await request(server)
.post('/api/notifications/push/subscriptions')
.set('Cookie', sessionCookie(1))
.send({ subscription: { endpoint: ENDPOINT } });
expect(res.status).toBe(400);
expect(res.body.error).toEqual(expect.stringContaining('keys'));
});
it('DELETE subscriptions: only the owner removes the endpoint, and a repeat is still 200', async () => {
await request(server)
.post('/api/notifications/push/subscriptions')
.set('Cookie', sessionCookie(1))
.send({ subscription: subscription() });
const stranger = await request(server)
.delete('/api/notifications/push/subscriptions')
.set('Cookie', sessionCookie(2))
.send({ endpoint: ENDPOINT });
expect(stranger.status).toBe(200);
expect(rows()).toHaveLength(1);
const owner = await request(server)
.delete('/api/notifications/push/subscriptions')
.set('Cookie', sessionCookie(1))
.send({ endpoint: ENDPOINT });
expect(owner.status).toBe(200);
expect(owner.body).toEqual({ success: true });
expect(rows()).toEqual([]);
const again = await request(server)
.delete('/api/notifications/push/subscriptions')
.set('Cookie', sessionCookie(1))
.send({ endpoint: ENDPOINT });
expect(again.status).toBe(200);
});
it('DELETE subscriptions: 400 without an endpoint', async () => {
const res = await request(server)
.delete('/api/notifications/push/subscriptions')
.set('Cookie', sessionCookie(1))
.send({});
expect(res.status).toBe(400);
});
it('POST test/push: sends the test message to the caller’s devices through the SSRF-guarded fetch', async () => {
const none = await request(server).post('/api/notifications/test/push').set('Cookie', sessionCookie(1));
expect(none.status).toBe(200);
expect(none.body).toEqual({ success: false, error: 'Channel is not configured for this user' });
await request(server)
.post('/api/notifications/push/subscriptions')
.set('Cookie', sessionCookie(1))
.send({ subscription: subscription() });
safeFetchFollow.mockResolvedValue({ ok: true, status: 201, body: null, headers: { get: () => null } });
const res = await request(server).post('/api/notifications/test/push').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true });
expect(safeFetchFollow).toHaveBeenCalledWith(
ENDPOINT,
expect.objectContaining({
method: 'POST',
headers: expect.objectContaining({ 'Content-Encoding': 'aes128gcm' }),
}),
{ maxRedirects: 0, bypassInternalIpAllowed: true },
);
});
it('a stored private key that no longer decrypts turns push off with a 503 and is never replaced', async () => {
const readKey = (key: string) =>
(db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string }).value;
const unreadable = 'enc:v1:bm90IGEgY2lwaGVydGV4dA';
const publicKey = readKey('web_push_vapid_public_key');
const ciphertext = readKey('web_push_vapid_private_key');
await request(server)
.post('/api/notifications/push/subscriptions')
.set('Cookie', sessionCookie(1))
.send({ subscription: subscription() });
db.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(unreadable, 'web_push_vapid_private_key');
try {
const key = await request(server).get('/api/notifications/push/public-key').set('Cookie', sessionCookie(1));
expect(key.status).toBe(503);
expect(key.body).toEqual({ error: 'Web Push is currently unavailable on this server' });
const sub = await request(server)
.post('/api/notifications/push/subscriptions')
.set('Cookie', sessionCookie(1))
.send({ subscription: subscription(`${ENDPOINT}-second`) });
expect(sub.status).toBe(503);
const test = await request(server).post('/api/notifications/test/push').set('Cookie', sessionCookie(1));
expect(test.status).toBe(200);
expect(test.body).toEqual({ success: false, error: 'Web Push is currently unavailable on this server' });
expect(safeFetchFollow).not.toHaveBeenCalled();
// The device registered before stays, and neither stored row was touched.
expect(rows().map((r) => r.endpoint)).toEqual([ENDPOINT]);
expect(readKey('web_push_vapid_public_key')).toBe(publicKey);
expect(readKey('web_push_vapid_private_key')).toBe(unreadable);
} finally {
db.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(ciphertext, 'web_push_vapid_private_key');
}
const back = await request(server).get('/api/notifications/push/public-key').set('Cookie', sessionCookie(1));
expect(back.body).toEqual({ publicKey });
});
});
+12 -3
View File
@@ -5,13 +5,16 @@ import { NotificationPreferencesService } from '../../src/nest/notifications/not
import { NotificationsService } from '../../src/nest/notifications/notifications.service';
import { NtfyService } from '../../src/nest/notifications/transports/ntfy.service';
import { WebhookService } from '../../src/nest/notifications/transports/webhook.service';
import { WebPushService } from '../../src/nest/notifications/transports/web-push.service';
import { PushSubscriptionsService } from '../../src/nest/notifications/push/push-subscriptions.service';
import { VapidKeysService } from '../../src/nest/notifications/push/vapid-keys.service';
/**
* A NotificationsService wired the way Nest wires it.
*
* The domain takes six providers since the fold, and eight places used to build
* it by hand — every added constructor parameter was an eight-file diff. One
* helper keeps that at one.
* The domain takes seven providers since Web Push joined, and eight places used
* to build it by hand: every added constructor parameter was an eight-file
* diff. One helper keeps that at one.
*/
export function makeNotificationsService(dbs: DatabaseService, realtime = new RealtimeService()): NotificationsService {
const mailer = new MailerService(dbs);
@@ -22,9 +25,15 @@ export function makeNotificationsService(dbs: DatabaseService, realtime = new Re
new WebhookService(dbs),
new NtfyService(dbs),
new NotificationPreferencesService(dbs, mailer),
makeWebPushService(dbs),
);
}
/** The Web Push transport over its two providers, on the same connection. */
export function makeWebPushService(dbs: DatabaseService): WebPushService {
return new WebPushService(new VapidKeysService(dbs), new PushSubscriptionsService(dbs));
}
/** The preferences half on its own, over the same connection. */
export function makeNotificationPreferencesService(dbs: DatabaseService): NotificationPreferencesService {
return new NotificationPreferencesService(dbs, new MailerService(dbs));
+1
View File
@@ -108,6 +108,7 @@ const RESET_TABLES = [
'visited_countries',
'bucket_list',
// Notifications & audit
'push_subscriptions',
'notification_channel_preferences',
'notifications',
'audit_log',
@@ -81,3 +81,62 @@ describe('the Places and Amap switches in the templates', () => {
}
});
});
describe('the Web Push keys in the templates', () => {
// All optional, since TREK keeps a generated pair in its database; an
// operator who wants their own pair has to find the names somewhere.
const documented = ['VAPID_PUBLIC_KEY', 'VAPID_PRIVATE_KEY', 'VAPID_SUBJECT'];
it('.env.example and docker-compose.yml document every one of them', () => {
for (const name of documented) {
expect(envExample).toContain(`# ${name}=`);
expect(compose).toContain(`# - ${name}=`);
}
});
it('the Helm ConfigMap passes through the public key and the subject', () => {
for (const name of ['VAPID_PUBLIC_KEY', 'VAPID_SUBJECT']) {
expect(helmValues).toContain(`# ${name}:`);
expect(helmConfigMap).toContain(`${name}: {{ .Values.env.${name} | quote }}`);
}
});
it('no template promises an admin address as the push contact, since TREK never sends one on its own', () => {
const subjectDocs = [
envExample.split(/\r?\n/).find((l) => l.includes('# VAPID_SUBJECT=')),
compose.split(/\r?\n/).find((l) => l.includes('- VAPID_SUBJECT=')),
helmValues.slice(helmValues.indexOf('# VAPID_SUBJECT:')).split(/\r?\n\r?\n/)[0],
];
for (const doc of subjectDocs) {
expect(doc).toContain('APP_URL');
expect(doc).not.toContain('ADMIN_EMAIL');
}
});
it('no template says a broken pair is ignored, since push is off until it is fixed and no stored pair stands in', () => {
// The Helm comment wraps, so its lines are joined back into one sentence first.
const helmPrivateKey = helmValues
.slice(helmValues.indexOf('# Optional Web Push key pair, private half'), helmValues.indexOf(' VAPID_PRIVATE_KEY: ""'))
.replace(/\s*\n\s*#\s*/g, ' ');
const privateKeyDocs = [
envExample.split(/\r?\n/).find((l) => l.includes('# VAPID_PRIVATE_KEY=')),
compose.split(/\r?\n/).find((l) => l.includes('- VAPID_PRIVATE_KEY=')),
helmPrivateKey,
];
for (const doc of privateKeyDocs) {
expect(doc).toContain('turns push off');
expect(doc).not.toContain('ignored');
expect(doc).not.toContain('keeps working');
}
});
it('the Helm chart carries the private key in the Secret, never in the ConfigMap', () => {
const name = 'VAPID_PRIVATE_KEY';
expect(helmValues).toContain(` ${name}: ""`);
expect(helmSecret).toContain(`${name}: {{ .Values.secretEnv.${name} | b64enc | quote }}`);
expect(helmSecret).toContain(`${name}: {{ .Values.secretEnv.${name} }}`);
expect(helmDeployment).toContain(`- name: ${name}\n valueFrom:\n secretKeyRef:`);
expect(helmDeployment).toContain(`key: ${name}\n optional: true`);
expect(helmConfigMap).not.toContain(name);
});
});
+16 -1
View File
@@ -16,6 +16,7 @@ import {
deriveBackup,
deriveNet,
derivePaths,
derivePush,
deriveAll,
} from '../../../src/app-config/derive';
@@ -277,7 +278,7 @@ describe('deriveAll', () => {
expect(env.demo.enabled).toBe(true);
for (const ns of [
'app', 'http', 'session', 'demo', 'adminBootstrap', 'oidc', 'smtp', 'mcp',
'plugins', 'webauthn', 'integrations', 'backup', 'db', 'paths', 'net',
'plugins', 'webauthn', 'integrations', 'backup', 'db', 'paths', 'net', 'push',
] as const) {
expect(env[ns]).toBeDefined();
}
@@ -309,3 +310,17 @@ describe('deriveMaps', () => {
}
});
});
describe('derivePush', () => {
it('passes the VAPID_* values through trimmed, blank counting as unset', () => {
expect(derivePush({})).toEqual({ vapidPublicKey: undefined, vapidPrivateKey: undefined, vapidSubject: undefined });
expect(
derivePush({ VAPID_PUBLIC_KEY: ' BPub ', VAPID_PRIVATE_KEY: 'priv', VAPID_SUBJECT: ' mailto:ops@example.com ' }),
).toEqual({ vapidPublicKey: 'BPub', vapidPrivateKey: 'priv', vapidSubject: 'mailto:ops@example.com' });
expect(derivePush({ VAPID_PUBLIC_KEY: ' ', VAPID_SUBJECT: '' })).toEqual({
vapidPublicKey: undefined,
vapidPrivateKey: undefined,
vapidSubject: undefined,
});
});
});
@@ -3,6 +3,10 @@ import { describe, it, expect } from 'vitest';
import {
csvList,
csvListFiltered,
decodeBase64Url,
isP256PrivateKey,
isUncompressedP256Key,
isVapidSubject,
nonNegativeIntOr,
numberOr,
parseBool,
@@ -176,3 +180,37 @@ describe('parseLinkLocalAllowList (ALLOW_LINK_LOCAL_IPS)', () => {
}
});
});
describe('Web Push key material', () => {
it('decodeBase64Url refuses anything outside the base64url alphabet instead of skipping it', () => {
expect(decodeBase64Url('AQID')).toEqual(Buffer.from([1, 2, 3]));
expect(decodeBase64Url(' AQID ')).toEqual(Buffer.from([1, 2, 3]));
expect(decodeBase64Url('AQI=')).toEqual(Buffer.from([1, 2]));
expect(decodeBase64Url('-_8')).toEqual(Buffer.from([0xfb, 0xff]));
for (const value of ['', 'AQ+D', 'AQ/D', 'AQ ID', 'AQ=D', 'AQ===']) {
expect(decodeBase64Url(value), value).toBeNull();
}
});
it('isUncompressedP256Key and isP256PrivateKey check the sizes the Web Push tools print', () => {
const point = Buffer.concat([Buffer.from([0x04]), Buffer.alloc(64, 1)]).toString('base64url');
expect(isUncompressedP256Key(point)).toBe(true);
const compressed = Buffer.concat([Buffer.from([0x02]), Buffer.alloc(64, 1)]).toString('base64url');
expect(isUncompressedP256Key(compressed)).toBe(false);
expect(isUncompressedP256Key(Buffer.alloc(33, 4).toString('base64url'))).toBe(false);
expect(isP256PrivateKey(Buffer.alloc(32, 9).toString('base64url'))).toBe(true);
expect(isP256PrivateKey(Buffer.alloc(31, 9).toString('base64url'))).toBe(false);
expect(isP256PrivateKey('not base64url!')).toBe(false);
});
it('isVapidSubject accepts a mailto: address or an https: URL and nothing else', () => {
const accepted = ['mailto:ops@example.com', 'MAILTO:ops@example.com', 'https://trek.example.com', ' https://x.test/c '];
for (const ok of accepted) {
expect(isVapidSubject(ok), ok).toBe(true);
}
const refused = ['ops@example.com', 'mailto:', 'mailto:no-at-sign', 'mailto:a b@example.com', 'http://x.test', 'not a url'];
for (const bad of refused) {
expect(isVapidSubject(bad), bad).toBe(false);
}
});
});
+118 -1
View File
@@ -1,6 +1,31 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import type { z } from 'zod';
import { validateEnvAtBoot, readEnv } from '../../../src/app-config/env';
import { validateEnvAtBoot, readEnv, SECRET_ENV_KEYS } from '../../../src/app-config/env';
import { envSchema } from '../../../src/app-config/env.schema';
const schemaShape: Record<string, z.ZodType> = envSchema.shape;
/**
* A value no check of the schema accepts (not a number, URL, boolean, duration,
* language or base64url key), and one that names its variable, so a leak is
* traceable to the key it came from.
*/
const probe = (key: string): string => `probe+${key}/not valid=`;
/** Everything one boot check printed and threw. */
function bootReport(raw: Record<string, string>): { printed: string; thrown: string } {
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
let thrown = '';
try {
validateEnvAtBoot(raw);
} catch (err) {
thrown = err instanceof Error ? err.message : String(err);
}
const printed = error.mock.calls.map((c) => c.join(' ')).join('\n');
error.mockRestore();
return { printed, thrown };
}
describe('validateEnvAtBoot', () => {
afterEach(() => {
@@ -58,6 +83,98 @@ describe('validateEnvAtBoot', () => {
expect(() => validateEnvAtBoot({ ALLOW_LINK_LOCAL_IPS: '' })).not.toThrow();
});
it('checks the VAPID_* shapes and lets a well-formed set through', () => {
// The application server pair from RFC 8291 Appendix A, in the form the Web Push tools print.
const publicKey = 'BP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8';
const privateKey = 'yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw';
expect(() =>
validateEnvAtBoot({
VAPID_PUBLIC_KEY: publicKey,
VAPID_PRIVATE_KEY: privateKey,
VAPID_SUBJECT: 'mailto:ops@example.com',
}),
).not.toThrow();
expect(() => validateEnvAtBoot({ VAPID_SUBJECT: 'https://trek.example.com' })).not.toThrow();
// Whether the halves belong together is checked where they are used, not here.
expect(() => validateEnvAtBoot({ VAPID_PRIVATE_KEY: privateKey })).not.toThrow();
vi.spyOn(console, 'error').mockImplementation(() => {});
expect(() => validateEnvAtBoot({ VAPID_PUBLIC_KEY: privateKey })).toThrow();
expect(() => validateEnvAtBoot({ VAPID_PUBLIC_KEY: `A${publicKey.slice(1)}` })).toThrow();
expect(() => validateEnvAtBoot({ VAPID_PRIVATE_KEY: publicKey })).toThrow();
expect(() => validateEnvAtBoot({ VAPID_PRIVATE_KEY: 'yfWPiYE+n46HLnH0KqZOF1fJJU3MYrct3AELtAQ/oRw' })).toThrow();
expect(() => validateEnvAtBoot({ VAPID_SUBJECT: 'ops@example.com' })).toThrow();
expect(() => validateEnvAtBoot({ VAPID_SUBJECT: 'http://trek.example.com' })).toThrow();
});
it('never prints the value of a secret variable, only its name and the problem', () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
// 43 characters like a real key, with one character base64url does not have.
const leakedPrivateKey = 'yfWPiYE+n46HLnH0KqZOF1fJJU3MYrct3AELtAQ/oRw';
expect(() => validateEnvAtBoot({ VAPID_PRIVATE_KEY: leakedPrivateKey, PORT: 'not-a-port' })).toThrow(
/2 problems/,
);
const report = error.mock.calls.map((c) => c.join(' ')).join('\n');
expect(report).toContain('VAPID_PRIVATE_KEY=***: must be a base64url-encoded P-256 private key');
expect(report).not.toContain(leakedPrivateKey);
expect(report).not.toContain('yfWPiYE');
// Everything else keeps its value, which is what makes a typo findable.
expect(report).toContain('PORT="not-a-port"');
});
it('never prints any secret variable, whether or not its own check refuses the value', () => {
// A broken PORT guarantees a report, so every secret gets its chance to leak into it.
const { printed, thrown } = bootReport({
...Object.fromEntries([...SECRET_ENV_KEYS].map((key) => [key, probe(key)])),
PORT: 'not-a-port',
});
expect(thrown).toMatch(/Invalid environment configuration/);
expect(printed).toContain('PORT="not-a-port"');
let refused = 0;
for (const key of SECRET_ENV_KEYS) {
expect(printed, key).not.toContain(probe(key));
expect(thrown, key).not.toContain(probe(key));
if (!schemaShape[key].safeParse(probe(key)).success) {
refused += 1;
expect(printed, key).toContain(` - ${key}=***: `);
}
}
// The masking only proves itself on a variable the schema refuses.
expect(refused).toBeGreaterThan(0);
});
it('still prints the value of every variable that is not a secret', () => {
const open = Object.keys(schemaShape).filter((key) => !SECRET_ENV_KEYS.has(key));
const { printed } = bootReport(Object.fromEntries(open.map((key) => [key, probe(key)])));
// Free-form variables accept anything, so only the checked ones show up.
const refused = open.filter((key) => !schemaShape[key].safeParse(probe(key)).success);
expect(refused).toContain('VAPID_PUBLIC_KEY');
for (const key of refused) expect(printed, key).toContain(` - ${key}=${JSON.stringify(probe(key))}: `);
expect(printed.split('\n').filter((line) => line.startsWith(' - '))).toHaveLength(refused.length);
});
it('knows every secret-looking variable of the schema as a secret, and nothing the schema does not know', () => {
// A new variable with a word in its name that suggests a credential lands
// here and has to be decided on. Whole words, so OVERPASS_URL and
// WEBAUTHN_RP_ID do not count.
const looksSecret = (key: string): boolean =>
/(^|_)(SECRET|PASS(WORD|PHRASE)?|TOKEN|KEY|APIKEY|CREDENTIALS?|PRIVATE|LICEN[CS]E|WEBHOOK|AUTH|DSN|SALT)(_|$)/.test(key);
const notSecret = new Set([
'VAPID_PUBLIC_KEY', // the public half, which every subscribing browser receives
'TREK_PLUGIN_ALLOW_PRIVATE_EGRESS', // a switch about private networks, not a private value
]);
const schemaKeys = Object.keys(schemaShape);
const flagged = schemaKeys.filter((key) => looksSecret(key) && !notSecret.has(key));
expect(flagged.length).toBeGreaterThan(5);
for (const key of flagged) expect(SECRET_ENV_KEYS.has(key), key).toBe(true);
for (const key of SECRET_ENV_KEYS) expect(schemaKeys, key).toContain(key);
for (const key of notSecret) {
expect(schemaKeys, key).toContain(key);
expect(looksSecret(key), key).toBe(true);
expect(SECRET_ENV_KEYS.has(key), key).toBe(false);
}
});
it('treats blank values as unset (defaults apply, no error)', () => {
expect(() => validateEnvAtBoot({ DEMO_MODE: '', PORT: ' ', TZ: '' })).not.toThrow();
});
@@ -95,6 +95,19 @@ describe('migrate-encryption.ts app_settings parity', () => {
}
});
// VapidKeysService stores the Web Push signing key with encrypt_api_key.
// Missed by a rotation it no longer decrypts, and push stays off on every
// device until the old key is back.
it('ROTPAR-012: rotates the stored Web Push private key', () => {
const vapid = fs.readFileSync(
path.join(SERVER_ROOT, 'src', 'nest', 'notifications', 'push', 'vapid-keys.service.ts'),
'utf8',
);
expect(vapid).toContain("VAPID_PRIVATE_KEY_SETTING = 'web_push_vapid_private_key'");
expect(vapid).toContain('encrypt_api_key(keys.privateKey)');
expect(appSettingsLoop).toContain("'web_push_vapid_private_key'");
});
it('ROTPAR-003: the canonical list is not empty, so ROTPAR-001 cannot pass vacuously', () => {
expect(INSTANCE_API_KEY_NAMES.length).toBeGreaterThan(0);
});
@@ -80,6 +80,86 @@ describe('globalMiddleware request-log redaction', () => {
expect(redact({ accessKeyId: 'ak-1', tokenCount: 5 })).toEqual({ accessKeyId: 'ak-1', tokenCount: 5 });
});
it('hides the Web Push subscription body: the endpoint capability URL and both keys', () => {
// POST /api/notifications/push/subscriptions, as PushSubscription.toJSON() hands it over.
expect(
redact({
subscription: {
endpoint: 'https://fcm.googleapis.com/fcm/send/device-capability',
expirationTime: null,
keys: { p256dh: 'BNcRdreALRFXTkOOUHK1EtK2wtaz5Ry4YfYCA', auth: 'tBHItJI5svbpez7KI4CCXg' },
},
}),
).toEqual({
subscription: {
endpoint: '[REDACTED]',
expirationTime: null,
keys: { p256dh: '[REDACTED]', auth: '[REDACTED]' },
},
});
});
it('hides the subscription the service worker posts again after the browser renewed it', () => {
// sw-push.js on pushsubscriptionchange: the same route and shape, and a renewed
// subscription may carry a real expiry instead of null.
expect(
redact({
subscription: {
endpoint: 'https://updates.push.services.mozilla.com/wpush/v2/renewed-capability',
expirationTime: 1767225600000,
keys: { p256dh: 'BOr1renewedPublicKey', auth: 'renewedAuthSecret' },
},
}),
).toEqual({
subscription: {
endpoint: '[REDACTED]',
expirationTime: 1767225600000,
keys: { p256dh: '[REDACTED]', auth: '[REDACTED]' },
},
});
});
it('hides the endpoint of a subscription that arrives without its keys', () => {
// The route refuses this body with a 400, but the request is logged all the same.
expect(
redact({ subscription: { endpoint: 'https://fcm.googleapis.com/fcm/send/keyless', expirationTime: null } }),
).toEqual({ subscription: { endpoint: '[REDACTED]', expirationTime: null } });
expect(redact({ subscription: { endpoint: 'https://fcm.googleapis.com/fcm/send/lone' } })).toEqual({
subscription: { endpoint: '[REDACTED]' },
});
expect(
redact({ subscription: { endpoint: 'https://fcm.googleapis.com/fcm/send/odd-keys', keys: 'not-an-object' } }),
).toEqual({ subscription: { endpoint: '[REDACTED]', keys: 'not-an-object' } });
});
it('hides the endpoint of the body that forgets a push device', () => {
// DELETE /api/notifications/push/subscriptions (logout, switching push off, the worker's renewal).
expect(redact({ endpoint: 'https://web.push.apple.com/QGx-device' })).toEqual({ endpoint: '[REDACTED]' });
expect(redact({ Endpoint: 'https://web.push.apple.com/QGx-device' })).toEqual({ Endpoint: '[REDACTED]' });
});
it('keeps an endpoint that is an ordinary setting readable, like the S3 backend URL', () => {
expect(
redact({ endpoint: 'http://127.0.0.1:9000', bucket: 'trek', region: 'us-east-1', secretAccessKey: 'sk' }),
).toEqual({ endpoint: 'http://127.0.0.1:9000', bucket: 'trek', region: 'us-east-1', secretAccessKey: '[REDACTED]' });
expect(redact({ endpoint: 'https://s3.example.com', forcePathStyle: true })).toEqual({
endpoint: 'https://s3.example.com',
forcePathStyle: true,
});
});
it('decides p256dh and auth by name wherever they appear, and nothing near them by accident', () => {
// Only the push subscription sends either field today; an `auth` anywhere
// else would carry credentials too. The fields around them stay readable.
expect(redact({ p256dh: 'BPub', Auth: 'secret', auth_method: 'basic', author: 'Ada' })).toEqual({
p256dh: '[REDACTED]',
Auth: '[REDACTED]',
auth_method: 'basic',
author: 'Ada',
});
expect(redact({ auth: { user: 'mailer', pass: 'hunter2' } })).toEqual({ auth: '[REDACTED]' });
});
it('passes non-object values through untouched', () => {
expect(redact('plain string')).toBe('plain string');
expect(redact(42)).toBe(42);
@@ -607,6 +607,20 @@ const pv = (id: number): number =>
const mcpTokenCount = (id: number): number =>
(testDb.prepare('SELECT COUNT(*) AS n FROM mcp_tokens WHERE user_id = ?').get(id) as { n: number }).n;
const addPushDevice = (userId: number, endpoint: string): void => {
testDb
.prepare(
"INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth, vapid_public_key) VALUES (?, ?, 'p', 'a', 'k')",
)
.run(userId, endpoint);
};
const pushDeviceCount = (id: number): number =>
(testDb.prepare('SELECT COUNT(*) AS n FROM push_subscriptions WHERE user_id = ?').get(id) as { n: number }).n;
const passwordHash = (id: number): string =>
(testDb.prepare('SELECT password_hash FROM users WHERE id = ?').get(id) as { password_hash: string }).password_hash;
describe('admin password reset revokes what an intruder already holds', () => {
it('ADMIN-SVC-080 — setting a password bumps password_version, so existing cookies stop working', () => {
// An admin sets somebody else's password for one reason: the account is
@@ -630,15 +644,49 @@ describe('admin password reset revokes what an intruder already holds', () => {
expect(mcpTokenCount(user.id)).toBe(0);
});
it('ADMIN-SVC-081b: and forgets the push devices, which outlive every session, of that user only', () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
addPushDevice(user.id, 'https://fcm.googleapis.com/fcm/send/intruder');
addPushDevice(user.id, 'https://web.push.apple.com/owner');
addPushDevice(other.id, 'https://fcm.googleapis.com/fcm/send/bystander');
updateUser(String(user.id), { password: 'ANewStrongPass123!' });
expect(pushDeviceCount(user.id)).toBe(0);
expect(pushDeviceCount(other.id)).toBe(1);
});
it('ADMIN-SVC-081c: drops them in the same transaction as the password, so a failure leaves the account as it was', () => {
const { user } = createUser(testDb);
const before = pv(user.id);
const hashBefore = passwordHash(user.id);
testDb.prepare("INSERT INTO mcp_tokens (user_id, token_hash, token_prefix, name) VALUES (?, 'hash', 'trek_ab', 'cli')").run(user.id);
addPushDevice(user.id, 'https://fcm.googleapis.com/fcm/send/intruder');
testDb.exec("CREATE TRIGGER boom BEFORE DELETE ON push_subscriptions BEGIN SELECT RAISE(ABORT, 'boom'); END");
try {
expect(() => updateUser(String(user.id), { password: 'ANewStrongPass123!' })).toThrow('boom');
} finally {
testDb.exec('DROP TRIGGER boom');
}
expect(pv(user.id)).toBe(before);
expect(passwordHash(user.id)).toBe(hashBefore);
expect(mcpTokenCount(user.id)).toBe(1);
expect(pushDeviceCount(user.id)).toBe(1);
});
it('ADMIN-SVC-082 — renaming a user touches neither, so an ordinary edit stays ordinary', () => {
const { user } = createUser(testDb);
const before = pv(user.id);
testDb.prepare("INSERT INTO mcp_tokens (user_id, token_hash, token_prefix, name) VALUES (?, 'hash', 'trek_ab', 'cli')").run(user.id);
addPushDevice(user.id, 'https://fcm.googleapis.com/fcm/send/renamed');
updateUser(String(user.id), { username: 'renamed' });
expect(pv(user.id)).toBe(before);
expect(mcpTokenCount(user.id)).toBe(1);
expect(pushDeviceCount(user.id)).toBe(1);
});
});
@@ -108,6 +108,19 @@ const svc = new AuthService(
new AllowedFileTypesService(new DatabaseService(testDb)),
);
/** A Web Push device row; the password paths only care whose it is. */
function addPushDevice(userId: number, endpoint: string): void {
testDb
.prepare(
"INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth, vapid_public_key) VALUES (?, ?, 'p', 'a', 'k')",
)
.run(userId, endpoint);
}
function pushDeviceCount(userId: number): number {
return (testDb.prepare('SELECT COUNT(*) c FROM push_subscriptions WHERE user_id = ?').get(userId) as { c: number }).c;
}
// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------
@@ -495,6 +508,51 @@ describe('changePassword — session invalidation', () => {
expect(decoded.remember).toBe(true);
expect(decoded.exp - decoded.iat).toBe(2592000); // remember window survives the change
});
it('AUTH-DB-036e: forgets every push device of the user, and only of that user', () => {
const { user, password } = createUser(testDb);
const { user: other } = createUser(testDb);
addPushDevice(user.id, 'https://fcm.googleapis.com/fcm/send/mine-1');
addPushDevice(user.id, 'https://web.push.apple.com/mine-2');
addPushDevice(other.id, 'https://fcm.googleapis.com/fcm/send/theirs');
const result = svc.changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' });
expect(result.success).toBe(true);
expect(pushDeviceCount(user.id)).toBe(0);
expect(pushDeviceCount(other.id)).toBe(1);
});
it('AUTH-DB-036f: a refused change keeps the push devices', () => {
const { user } = createUser(testDb);
addPushDevice(user.id, 'https://fcm.googleapis.com/fcm/send/mine');
const result = svc.changePassword(user.id, user.email, { current_password: 'wrong', new_password: 'New1234!' });
expect(result.status).toBe(401);
expect(pushDeviceCount(user.id)).toBe(1);
});
it('AUTH-DB-036g: drops the push devices in the same transaction as the password change, so a failure changes nothing', () => {
const { user, password } = createUser(testDb);
tokens.createMcpToken(user.id, 'cli');
addPushDevice(user.id, 'https://fcm.googleapis.com/fcm/send/mine');
testDb.exec("CREATE TRIGGER boom BEFORE DELETE ON push_subscriptions BEGIN SELECT RAISE(ABORT, 'boom'); END");
try {
expect(() =>
svc.changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' }),
).toThrow('boom');
} finally {
testDb.exec('DROP TRIGGER boom');
}
expect(pvOf(user.id)).toBe(0);
expect(mcpCount(user.id)).toBe(1);
expect(pushDeviceCount(user.id)).toBe(1);
// The new hash rolled back as well, so the old password is still the one that counts.
expect(svc.changePassword(user.id, user.email, { current_password: password, new_password: 'New1234!' }).success)
.toBe(true);
});
});
// ---------------------------------------------------------------------------
@@ -918,6 +976,42 @@ describe('resetPassword', () => {
.toEqual({ error: 'This reset link has already been used', status: 400 });
});
it('AUTH-DB-082b: forgets every push device of the user along with the MCP tokens', () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
tokens.createMcpToken(user.id, 'cli');
addPushDevice(user.id, 'https://fcm.googleapis.com/fcm/send/mine');
addPushDevice(other.id, 'https://fcm.googleapis.com/fcm/send/theirs');
const issued = svc.requestPasswordReset(user.email, null);
expect(svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!' }))
.toEqual({ success: true, userId: user.id });
expect((testDb.prepare('SELECT COUNT(*) c FROM mcp_tokens WHERE user_id = ?').get(user.id) as { c: number }).c).toBe(0);
expect(pushDeviceCount(user.id)).toBe(0);
expect(pushDeviceCount(other.id)).toBe(1);
});
it('AUTH-DB-082c: drops the push devices in the same transaction that burns the link, so a failure keeps the link', () => {
const { user } = createUser(testDb);
addPushDevice(user.id, 'https://fcm.googleapis.com/fcm/send/mine');
const issued = svc.requestPasswordReset(user.email, null);
testDb.exec("CREATE TRIGGER boom BEFORE DELETE ON push_subscriptions BEGIN SELECT RAISE(ABORT, 'boom'); END");
try {
expect(() => svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!' })).toThrow('boom');
} finally {
testDb.exec('DROP TRIGGER boom');
}
expect(pushDeviceCount(user.id)).toBe(1);
const row = testDb.prepare('SELECT password_version FROM users WHERE id = ?').get(user.id) as { password_version: number };
expect(row.password_version).toBe(0);
// Nothing was burned, so the same link still completes the reset.
expect(svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!' }))
.toEqual({ success: true, userId: user.id });
expect(pushDeviceCount(user.id)).toBe(0);
});
it('AUTH-DB-083: bespoke 400s for missing/unknown/expired tokens', () => {
expect(svc.resetPassword({ new_password: 'Fresh123!' })).toEqual({ error: 'Reset token is required', status: 400 });
expect(svc.resetPassword({ token: 't' })).toEqual({ error: 'New password is required', status: 400 });
@@ -2,7 +2,7 @@
* Unit tests for the external notification channel registry.
* Covers CHREG-001 to CHREG-008.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
listChannels,
getChannel,
@@ -18,14 +18,22 @@ import { registerBuiltinChannels } from '../../../src/nest/notifications/channel
import type { MailerService } from '../../../src/nest/notifications/mailer/mailer.service';
import type { NtfyService } from '../../../src/nest/notifications/transports/ntfy.service';
import type { WebhookService } from '../../../src/nest/notifications/transports/webhook.service';
import type { WebPushService } from '../../../src/nest/notifications/transports/web-push.service';
// The built-ins take their transports as an argument now; these cases only care
// that the three ids land in the registry with the right privileges, so the
// that the four ids land in the registry with the right privileges, so the
// transports are stubs.
const pushStub = {
isAvailable: vi.fn(() => true),
hasDevices: vi.fn((userId: number) => userId === 7),
sendToUser: vi.fn(async () => true),
sendTest: vi.fn(async () => ({ success: true })),
};
const stubTransports = {
mailer: { isSmtpConfigured: () => true, getUserEmail: () => null } as unknown as MailerService,
webhook: { getUserWebhookUrl: () => null, getAdminWebhookUrl: () => null } as unknown as WebhookService,
ntfy: { getUserNtfyConfig: () => null, getAdminNtfyConfig: () => ({ server: null, topic: null, token: null }) } as unknown as NtfyService,
push: pushStub as unknown as WebPushService,
};
function fakeChannel(id: string, over: Partial<ExternalChannel> = {}): ExternalChannel {
@@ -52,8 +60,8 @@ afterEach(() => {
});
describe('channelRegistry', () => {
it('CHREG-001 — the three built-in external channels are registered; in-app is not', () => {
expect(listChannels().map(c => c.id)).toEqual(['email', 'webhook', 'ntfy']);
it('CHREG-001: the four built-in external channels are registered; in-app is not', () => {
expect(listChannels().map(c => c.id)).toEqual(['email', 'webhook', 'ntfy', 'push']);
expect(getChannel('inapp')).toBeUndefined();
});
@@ -71,14 +79,14 @@ describe('channelRegistry', () => {
expect(getChannel('plugin:gotify')).toBeDefined();
live = false;
expect(getChannel('plugin:gotify')).toBeUndefined();
expect(listChannels().map(c => c.id)).toEqual(['email', 'webhook', 'ntfy']);
expect(listChannels().map(c => c.id)).toEqual(['email', 'webhook', 'ntfy', 'push']);
});
it('CHREG-004 — a throwing plugin source cannot take notifications down', () => {
setPluginChannelSource(() => {
throw new Error('runtime exploded');
});
expect(listChannels().map(c => c.id)).toEqual(['email', 'webhook', 'ntfy']);
expect(listChannels().map(c => c.id)).toEqual(['email', 'webhook', 'ntfy', 'push']);
});
it('CHREG-005 — a plugin can never claim a built-in id', () => {
@@ -92,12 +100,50 @@ describe('channelRegistry', () => {
expect(getChannel('email')?.bypassesActiveToggleForAdminEvents).toBe(true);
expect(getChannel('webhook')?.bypassesActiveToggleForAdminEvents).toBeUndefined();
expect(getChannel('ntfy')?.bypassesActiveToggleForAdminEvents).toBeUndefined();
expect(getChannel('push')?.bypassesActiveToggleForAdminEvents).toBeUndefined();
});
it('CHREG-007 — webhook and ntfy deliver the admin-global copy; email does not', () => {
expect(getChannel('webhook')?.supportsAdminGlobal).toBe(true);
expect(getChannel('ntfy')?.supportsAdminGlobal).toBe(true);
expect(getChannel('email')?.supportsAdminGlobal).toBeUndefined();
expect(getChannel('push')?.supportsAdminGlobal).toBeUndefined();
expect(getChannel('push')?.sendGlobal).toBeUndefined();
});
it('CHREG-008b: push carries every user event, but neither admin-scoped ones nor synology_session_cleared', () => {
const push = getChannel('push')!;
expect(push.source).toBe('builtin');
expect(push.labelKey).toBe('settings.notificationPreferences.push');
for (const event of ['trip_invite', 'collab_message', 'trip_reminder', 'plugin_notification'] as const) {
expect(push.supportsEvent(event)).toBe(true);
}
expect(push.supportsEvent('version_available')).toBe(false);
expect(push.supportsEvent('replica_failure')).toBe(false);
expect(push.supportsEvent('synology_session_cleared')).toBe(false);
});
it('CHREG-008c: push is configured for a user with a device and hands sends and tests to the transport', async () => {
const push = getChannel('push')!;
expect(push.isConfiguredFor(7)).toBe(true);
expect(push.isConfiguredFor(8)).toBe(false);
await push.sendToUser(7, MSG);
expect(pushStub.sendToUser).toHaveBeenCalledWith(7, MSG);
await expect(push.test!(7)).resolves.toEqual({ success: true });
expect(pushStub.sendTest).toHaveBeenCalledWith(7);
});
it('CHREG-008d: push is ready only while it can sign, and hides meanwhile; a plugin cannot claim that', () => {
const push = getChannel('push')!;
expect(push.hiddenWhileInstanceUnconfigured).toBe(true);
expect(push.isInstanceConfigured!()).toBe(true);
pushStub.isAvailable.mockReturnValueOnce(false);
expect(push.isInstanceConfigured!()).toBe(false);
// Email keeps its column without SMTP, as before.
expect(getChannel('email')?.hiddenWhileInstanceUnconfigured).toBeUndefined();
setPluginChannelSource(() => [fakeChannel('plugin:gotify', { hiddenWhileInstanceUnconfigured: true })]);
expect(getChannel('plugin:gotify')?.hiddenWhileInstanceUnconfigured).toBeUndefined();
});
it('CHREG-008 — built-ins carry every event except synology_session_cleared', () => {
@@ -122,6 +168,6 @@ describe('channelRegistry', () => {
setPluginChannelSource(() => [boom]);
await expect(getChannel('plugin:boom')!.sendToUser(1, MSG)).rejects.toThrow('nope');
// and the registry is unharmed
expect(listChannels()).toHaveLength(4);
expect(listChannels()).toHaveLength(5);
});
});
@@ -43,10 +43,16 @@ import { registerBuiltinChannels } from '../../../src/nest/notifications/channel
import { NtfyService } from '../../../src/nest/notifications/transports/ntfy.service';
import { WebhookService } from '../../../src/nest/notifications/transports/webhook.service';
import { __resetChannelsForTest } from '../../../src/nest/notifications/channel-registry';
import { makeWebPushService } from '../../helpers/notifications';
const dbs = new DatabaseService(testDb);
const mailer = new MailerService(dbs);
registerBuiltinChannels({ mailer, webhook: new WebhookService(dbs), ntfy: new NtfyService(dbs) });
registerBuiltinChannels({
mailer,
webhook: new WebhookService(dbs),
ntfy: new NtfyService(dbs),
push: makeWebPushService(dbs),
});
const svc = new NotificationPreferencesService(dbs, mailer);
// Legacy free-function names bound to the service, so the moved cases read as before.
@@ -0,0 +1,276 @@
/**
* Web Push subscriptions: what the browser may hand over (PUSHSUB-CHK-*) and
* the table behind it (PUSHSUB-*), on the real schema including migration 244.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
import { createECDH } from 'node:crypto';
import { MAX_PUSH_ENDPOINT_LENGTH, pushUnsubscribeRequestSchema } from '@trek/shared';
// One :memory: connection per file, created inside the factory so nothing has
// to be hoisted above the imports; the tests reach it through the mocked module.
vi.mock('../../../../src/db/database', async () => {
const { default: Database } = await import('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
return {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
});
vi.mock('../../../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { db as testDb } from '../../../../src/db/database';
import { createTables } from '../../../../src/db/schema';
import { runMigrations } from '../../../../src/db/migrations';
import { resetTestDb } from '../../../helpers/test-db';
import { createUser } from '../../../helpers/factories';
import { DatabaseService } from '../../../../src/nest/database/database.service';
import {
MAX_PUSH_DEVICES_PER_USER,
PushSubscriptionsService,
} from '../../../../src/nest/notifications/push/push-subscriptions.service';
import {
PUSH_SUBSCRIPTION_ERRORS,
checkPushEndpoint,
checkPushSubscription,
isPushServiceEndpoint,
type CheckedPushSubscription,
} from '../../../../src/nest/notifications/push/push-subscription.helpers';
const subs = new PushSubscriptionsService(new DatabaseService(testDb));
function browserKeys() {
const ua = createECDH('prime256v1');
ua.generateKeys();
return { p256dh: ua.getPublicKey('base64url'), auth: Buffer.from('0123456789abcdef').toString('base64url') };
}
function checked(endpoint: string): CheckedPushSubscription {
const result = checkPushSubscription({ endpoint, keys: browserKeys() });
if ('error' in result) throw new Error(result.error);
return result.value;
}
const FCM = 'https://fcm.googleapis.com/fcm/send/device-1';
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
describe('checkPushEndpoint / checkPushSubscription', () => {
it('PUSHSUB-CHK-001: accepts the push services browsers use', () => {
for (const endpoint of [
FCM,
'https://android.googleapis.com/gcm/send/x',
'https://updates.push.services.mozilla.com/wpush/v2/gAAAA',
'https://push.services.mozilla.com/wpush/v1/x',
'https://web.push.apple.com/QGx9',
'https://api.push.apple.com/3/device/x',
'https://wns2-par02p.notify.windows.com/w/?token=BQYAAA',
]) {
expect(checkPushEndpoint(endpoint), endpoint).toBe('ok');
expect(isPushServiceEndpoint(endpoint)).toBe(true);
}
});
it('PUSHSUB-CHK-002: refuses anything that is not a plain https URL', () => {
for (const endpoint of [
'not a url',
'http://fcm.googleapis.com/fcm/send/x',
'https://user:pw@fcm.googleapis.com/fcm/send/x',
'https://fcm.googleapis.com:8443/fcm/send/x',
`https://fcm.googleapis.com/${'a'.repeat(MAX_PUSH_ENDPOINT_LENGTH)}`,
]) {
expect(checkPushEndpoint(endpoint), endpoint).toBe('endpoint');
}
});
it('PUSHSUB-CHK-002b: takes an endpoint exactly as long as the contract allows, and not one character more', () => {
const base = 'https://fcm.googleapis.com/fcm/send/';
const longest = `${base}${'a'.repeat(MAX_PUSH_ENDPOINT_LENGTH - base.length)}`;
// The contract and the check share one limit, so a device that could register can also be sent to and removed.
expect(pushUnsubscribeRequestSchema.safeParse({ endpoint: longest }).success).toBe(true);
expect(checkPushEndpoint(longest)).toBe('ok');
expect(checkPushEndpoint(`${longest}a`)).toBe('endpoint');
});
it('PUSHSUB-CHK-003: refuses hosts that are not push services, including lookalikes', () => {
for (const endpoint of [
'https://example.com/push',
'https://127.0.0.1/push',
'https://fcm.googleapis.com.evil.test/x',
'https://evilnotify.windows.com/x',
'https://.notify.windows.com/x',
'https://push.apple.com/x',
]) {
expect(checkPushEndpoint(endpoint), endpoint).not.toBe('ok');
}
expect(checkPushSubscription({ endpoint: 'https://example.com/push', keys: browserKeys() })).toEqual({
ok: false,
error: PUSH_SUBSCRIPTION_ERRORS.service,
});
expect(checkPushSubscription({ endpoint: 'http://fcm.googleapis.com/x', keys: browserKeys() })).toEqual({
ok: false,
error: PUSH_SUBSCRIPTION_ERRORS.endpoint,
});
});
it('PUSHSUB-CHK-004: wants a p256dh on the curve and a 16-byte auth secret', () => {
const keys = browserKeys();
const offCurve = Buffer.from(keys.p256dh, 'base64url');
offCurve[64] ^= 0x01;
for (const p256dh of [
'!!!',
Buffer.alloc(65, 4).toString('base64url'),
offCurve.toString('base64url'),
keys.auth,
]) {
expect(checkPushSubscription({ endpoint: FCM, keys: { ...keys, p256dh } })).toEqual({
ok: false,
error: PUSH_SUBSCRIPTION_ERRORS.p256dh,
});
}
for (const auth of ['!!!', Buffer.alloc(8).toString('base64url')]) {
expect(checkPushSubscription({ endpoint: FCM, keys: { ...keys, auth } })).toEqual({
ok: false,
error: PUSH_SUBSCRIPTION_ERRORS.auth,
});
}
});
it('PUSHSUB-CHK-005: hands the keys back canonical, without padding', () => {
const keys = browserKeys();
const result = checkPushSubscription({
endpoint: FCM,
keys: { p256dh: `${keys.p256dh}=`, auth: `${keys.auth}==` },
});
expect(result).toEqual({ ok: true, value: { endpoint: FCM, p256dh: keys.p256dh, auth: keys.auth } });
});
});
describe('PushSubscriptionsService', () => {
it('PUSHSUB-001: stores a subscription with the key it was made for and counts devices', () => {
const { user } = createUser(testDb);
const sub = checked(FCM);
expect(subs.hasAny(user.id)).toBe(false);
expect(subs.upsert(user.id, sub, 'server-key', 'Mozilla/5.0')).toBe(1);
const [row] = subs.listForUser(user.id);
expect(row).toMatchObject({
user_id: user.id,
endpoint: FCM,
p256dh: sub.p256dh,
auth: sub.auth,
vapid_public_key: 'server-key',
user_agent: 'Mozilla/5.0',
failure_count: 0,
last_success_at: null,
});
expect(subs.hasAny(user.id)).toBe(true);
expect(subs.countForUser(user.id)).toBe(1);
});
it('PUSHSUB-002: subscribing again refreshes the same row instead of adding one', () => {
const { user } = createUser(testDb);
subs.upsert(user.id, checked(FCM), 'old-key');
const [before] = subs.listForUser(user.id);
subs.recordFailure(before.id);
const fresh = checked(FCM);
expect(subs.upsert(user.id, fresh, 'new-key', null)).toBe(1);
const [after] = subs.listForUser(user.id);
expect(after.id).toBe(before.id);
expect(after).toMatchObject({
p256dh: fresh.p256dh,
vapid_public_key: 'new-key',
failure_count: 0,
user_agent: null,
});
});
it('PUSHSUB-003: a browser shared by two accounts belongs to whoever subscribed on it last', () => {
const { user: first } = createUser(testDb);
const { user: second } = createUser(testDb);
subs.upsert(first.id, checked(FCM), 'k');
expect(subs.upsert(second.id, checked(FCM), 'k')).toBe(1);
expect(subs.countForUser(first.id)).toBe(0);
expect(subs.listForUser(second.id).map((r) => r.endpoint)).toEqual([FCM]);
});
it('PUSHSUB-004: caps the devices per user and drops the one registered longest ago', () => {
const { user } = createUser(testDb);
for (let i = 0; i < MAX_PUSH_DEVICES_PER_USER; i++) {
subs.upsert(user.id, checked(`https://fcm.googleapis.com/fcm/send/d${i}`), 'k');
}
// Same second for every row; the id breaks the tie, so d0 is the oldest.
// d0 subscribing again renews it, which leaves d1 as the oldest.
testDb.prepare("UPDATE push_subscriptions SET created_at = '2026-01-01 00:00:00'").run();
subs.upsert(user.id, checked('https://fcm.googleapis.com/fcm/send/d0'), 'k');
expect(subs.upsert(user.id, checked('https://fcm.googleapis.com/fcm/send/new'), 'k')).toBe(
MAX_PUSH_DEVICES_PER_USER,
);
const endpoints = subs.listForUser(user.id).map((r) => r.endpoint);
expect(endpoints).toContain('https://fcm.googleapis.com/fcm/send/d0');
expect(endpoints).toContain('https://fcm.googleapis.com/fcm/send/new');
expect(endpoints).not.toContain('https://fcm.googleapis.com/fcm/send/d1');
});
it('PUSHSUB-005: a user can only remove their own endpoint', () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
subs.upsert(owner.id, checked(FCM), 'k');
expect(subs.removeForUser(other.id, FCM)).toBe(false);
expect(subs.countForUser(owner.id)).toBe(1);
expect(subs.removeForUser(owner.id, FCM)).toBe(true);
expect(subs.countForUser(owner.id)).toBe(0);
});
it('PUSHSUB-006: success resets the failure count, failures add up, deleteById removes the row', () => {
const { user } = createUser(testDb);
subs.upsert(user.id, checked(FCM), 'k');
const [row] = subs.listForUser(user.id);
expect(subs.recordFailure(row.id)).toBe(1);
expect(subs.recordFailure(row.id)).toBe(2);
expect(subs.listForUser(user.id)[0].failure_count).toBe(2);
subs.recordSuccess(row.id);
const [after] = subs.listForUser(user.id);
expect(after.failure_count).toBe(0);
expect(after.last_success_at).not.toBeNull();
expect(subs.recordFailure(row.id)).toBe(1);
subs.deleteById(row.id);
expect(subs.hasAny(user.id)).toBe(false);
// A failure recorded for a row another send already removed changes nothing.
expect(subs.recordFailure(row.id)).toBe(0);
});
it('PUSHSUB-007: cuts a long user agent and the rows go with the user', () => {
const { user } = createUser(testDb);
subs.upsert(user.id, checked(FCM), 'k', 'x'.repeat(1000));
expect(subs.listForUser(user.id)[0].user_agent).toHaveLength(256);
testDb.prepare('DELETE FROM users WHERE id = ?').run(user.id);
expect(testDb.prepare('SELECT COUNT(*) AS n FROM push_subscriptions').get()).toEqual({ n: 0 });
});
it('PUSHSUB-008: migration 244 created the table with its user index', () => {
const index = testDb
.prepare("SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'push_subscriptions'")
.all() as { name: string }[];
expect(index.map((i) => i.name)).toContain('idx_push_subscriptions_user');
});
});
@@ -0,0 +1,116 @@
/**
* PushController parity (PUSHCTL-*): status codes, bodies and the bespoke 400
* strings of /api/notifications/push, over stubbed providers.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HttpException } from '@nestjs/common';
import { HTTP_CODE_METADATA } from '@nestjs/common/constants';
import { createECDH } from 'node:crypto';
import { PushController } from '../../../../src/nest/notifications/push/push.controller';
import { PUSH_SUBSCRIPTION_ERRORS } from '../../../../src/nest/notifications/push/push-subscription.helpers';
import type { PushSubscriptionsService } from '../../../../src/nest/notifications/push/push-subscriptions.service';
import {
PUSH_UNAVAILABLE_ERROR,
PushUnavailableError,
type VapidKeysService,
} from '../../../../src/nest/notifications/push/vapid-keys.service';
import type { User } from '../../../../src/types';
const keys = { getPublicKey: vi.fn((): string => 'server-public-key') };
const subscriptions = { upsert: vi.fn(() => 2), removeForUser: vi.fn(() => true) };
const controller = new PushController(
keys as unknown as VapidKeysService,
subscriptions as unknown as PushSubscriptionsService,
);
const user = { id: 5 } as User;
function subscription(endpoint = 'https://fcm.googleapis.com/fcm/send/abc') {
const ua = createECDH('prime256v1');
ua.generateKeys();
return {
endpoint,
expirationTime: null,
keys: { p256dh: ua.getPublicKey('base64url'), auth: Buffer.alloc(16, 1).toString('base64url') },
};
}
function thrown(fn: () => unknown): HttpException {
try {
fn();
} catch (err) {
return err as HttpException;
}
throw new Error('expected a throw');
}
beforeEach(() => {
vi.clearAllMocks();
});
describe('PushController', () => {
it('PUSHCTL-001: GET public-key answers the key browsers subscribe with', () => {
expect(controller.publicKey()).toEqual({ publicKey: 'server-public-key' });
});
it('PUSHCTL-002: POST subscriptions stores the checked subscription against the current key and answers 200', () => {
const sub = subscription();
expect(controller.subscribe(user, { subscription: sub }, 'Firefox/130')).toEqual({ success: true, devices: 2 });
expect(subscriptions.upsert).toHaveBeenCalledWith(
5,
{ endpoint: sub.endpoint, p256dh: sub.keys.p256dh, auth: sub.keys.auth },
'server-public-key',
'Firefox/130',
);
expect(Reflect.getMetadata(HTTP_CODE_METADATA, PushController.prototype.subscribe)).toBe(200);
});
it('PUSHCTL-003: POST subscriptions answers the bespoke 400 and stores nothing', () => {
const err = thrown(() => controller.subscribe(user, { subscription: subscription('https://example.com/collect') }));
expect(err).toBeInstanceOf(HttpException);
expect(err.getStatus()).toBe(400);
expect(err.getResponse()).toEqual({ error: PUSH_SUBSCRIPTION_ERRORS.service });
expect(subscriptions.upsert).not.toHaveBeenCalled();
});
it('PUSHCTL-004: DELETE subscriptions removes only the caller’s endpoint and is idempotent', () => {
expect(controller.unsubscribe(user, { endpoint: 'https://fcm.googleapis.com/fcm/send/abc' })).toEqual({
success: true,
});
expect(subscriptions.removeForUser).toHaveBeenCalledWith(5, 'https://fcm.googleapis.com/fcm/send/abc');
subscriptions.removeForUser.mockReturnValueOnce(false);
expect(controller.unsubscribe(user, { endpoint: 'https://fcm.googleapis.com/fcm/send/gone' })).toEqual({
success: true,
});
expect(Reflect.getMetadata(HTTP_CODE_METADATA, PushController.prototype.unsubscribe)).toBe(200);
});
it('PUSHCTL-005: while the stored key pair is unusable, public-key and subscribe answer 503 and store nothing', () => {
keys.getPublicKey.mockImplementation(() => {
throw new PushUnavailableError();
});
try {
const fromKey = thrown(() => controller.publicKey());
expect(fromKey.getStatus()).toBe(503);
expect(fromKey.getResponse()).toEqual({ error: PUSH_UNAVAILABLE_ERROR });
const fromSubscribe = thrown(() => controller.subscribe(user, { subscription: subscription() }));
expect(fromSubscribe.getStatus()).toBe(503);
expect(fromSubscribe.getResponse()).toEqual({ error: PUSH_UNAVAILABLE_ERROR });
expect(subscriptions.upsert).not.toHaveBeenCalled();
// A device can still be forgotten.
expect(controller.unsubscribe(user, { endpoint: 'https://fcm.googleapis.com/fcm/send/abc' })).toEqual({
success: true,
});
} finally {
keys.getPublicKey.mockImplementation(() => 'server-public-key');
}
});
it('PUSHCTL-006: any other key failure is not dressed up as a 503', () => {
keys.getPublicKey.mockImplementationOnce(() => {
throw new Error('database is locked');
});
expect(() => controller.publicKey()).toThrow('database is locked');
});
});
@@ -0,0 +1,438 @@
/**
* Where the server's VAPID identity comes from (VKEY-*): the environment pair
* when it is complete and consistent, else a pair generated once into
* app_settings with the private half encrypted. Push is off, with every row
* left as it was, while the pair it would sign with cannot be used: a stored
* pair is never regenerated, and a broken environment pair falls back on
* neither a stored nor a new one. And the `sub` contact.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest';
// One :memory: connection per file, created inside the factory so nothing has
// to be hoisted above the imports; the tests reach it through the mocked module.
vi.mock('../../../../src/db/database', async () => {
const { default: Database } = await import('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
return {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
});
vi.mock('../../../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
const { logInfo, logError } = vi.hoisted(() => ({ logInfo: vi.fn(), logError: vi.fn() }));
vi.mock('../../../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo,
logDebug: vi.fn(),
logError,
logWarn: vi.fn(),
}));
import { db as testDb } from '../../../../src/db/database';
import { createTables } from '../../../../src/db/schema';
import { runMigrations } from '../../../../src/db/migrations';
import { resetTestDb } from '../../../helpers/test-db';
import { DatabaseService } from '../../../../src/nest/database/database.service';
import { decrypt_api_key, encrypt_api_key } from '../../../../src/nest/common/crypto/apiKeyCrypto';
import {
FALLBACK_VAPID_SUBJECT,
PushUnavailableError,
VAPID_PRIVATE_KEY_SETTING,
VAPID_PUBLIC_KEY_SETTING,
VapidKeysService,
} from '../../../../src/nest/notifications/push/vapid-keys.service';
import { generateVapidKeyPair, isVapidKeyPair } from '../../../../src/nest/notifications/push/web-push-crypto';
const dbs = new DatabaseService(testDb);
/** An enc:v1: value the current ENCRYPTION_KEY cannot open. */
const UNREADABLE = 'enc:v1:bm90IGEgY2lwaGVydGV4dA';
function setting(key: string): string | undefined {
return (testDb.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined)
?.value;
}
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
logInfo.mockClear();
logError.mockClear();
for (const name of [
'VAPID_PUBLIC_KEY',
'VAPID_PRIVATE_KEY',
'VAPID_SUBJECT',
'APP_URL',
'ALLOWED_ORIGINS',
'ADMIN_EMAIL',
]) {
vi.stubEnv(name, '');
}
});
afterEach(() => {
vi.unstubAllEnvs();
});
afterAll(() => {
testDb.close();
});
describe('VapidKeysService key pair', () => {
it('VKEY-001: generates the pair once, the private half encrypted, and keeps serving it', () => {
const svc = new VapidKeysService(dbs);
const keys = svc.getKeys();
expect(keys.source).toBe('database');
expect(isVapidKeyPair(keys.publicKey, keys.privateKey)).toBe(true);
expect(setting(VAPID_PUBLIC_KEY_SETTING)).toBe(keys.publicKey);
const stored = setting(VAPID_PRIVATE_KEY_SETTING)!;
expect(stored.startsWith('enc:v1:')).toBe(true);
expect(decrypt_api_key(stored)).toBe(keys.privateKey);
expect(logInfo).toHaveBeenCalledTimes(1);
// Another instance over the same database (a restart) reads the same pair.
const again = new VapidKeysService(dbs);
expect(again.getKeys()).toEqual(keys);
expect(svc.getPublicKey()).toBe(keys.publicKey);
expect(setting(VAPID_PRIVATE_KEY_SETTING)).toBe(stored);
expect(logInfo).toHaveBeenCalledTimes(1);
});
it('VKEY-001b: a pair another instance stored between the first look and the write is the one used', () => {
const theirs = generateVapidKeyPair();
const svc = new VapidKeysService(dbs);
const transaction = dbs.transaction.bind(dbs);
const spy = vi.spyOn(dbs, 'transaction').mockImplementationOnce((fn) => {
testDb
.prepare('INSERT INTO app_settings (key, value) VALUES (?, ?), (?, ?)')
.run(VAPID_PUBLIC_KEY_SETTING, theirs.publicKey, VAPID_PRIVATE_KEY_SETTING, encrypt_api_key(theirs.privateKey));
return transaction(fn);
});
try {
expect(svc.getKeys()).toEqual({ ...theirs, source: 'database' });
expect(setting(VAPID_PUBLIC_KEY_SETTING)).toBe(theirs.publicKey);
expect(logInfo).not.toHaveBeenCalled();
} finally {
spy.mockRestore();
}
});
it('VKEY-002: bootstrap creates the pair, so the public-key GET only reads', () => {
new VapidKeysService(dbs).onApplicationBootstrap();
expect(setting(VAPID_PUBLIC_KEY_SETTING)).toBeTruthy();
expect(setting(VAPID_PRIVATE_KEY_SETTING)).toBeTruthy();
});
it('VKEY-003: a bootstrap failure is logged, not thrown', () => {
const broken = {
get: () => {
throw new Error('no such table: app_settings');
},
} as unknown as DatabaseService;
expect(() => new VapidKeysService(broken).onApplicationBootstrap()).not.toThrow();
expect(logError).toHaveBeenCalledWith(expect.stringContaining('no such table'));
});
it('VKEY-004: a consistent pair in the environment wins and the database is left alone', () => {
const pair = generateVapidKeyPair();
// Padding on the way in is fine; the key handed to browsers has none.
vi.stubEnv('VAPID_PUBLIC_KEY', `${pair.publicKey}=`);
vi.stubEnv('VAPID_PRIVATE_KEY', pair.privateKey);
const keys = new VapidKeysService(dbs).getKeys();
expect(keys).toEqual({ ...pair, source: 'env' });
expect(setting(VAPID_PUBLIC_KEY_SETTING)).toBeUndefined();
expect(logError).not.toHaveBeenCalled();
});
it('VKEY-005: a mismatched environment pair turns push off, reported once, and the stored pair is not used', () => {
const stored = new VapidKeysService(dbs).getKeys();
const ciphertext = setting(VAPID_PRIVATE_KEY_SETTING);
vi.stubEnv('VAPID_PUBLIC_KEY', generateVapidKeyPair().publicKey);
vi.stubEnv('VAPID_PRIVATE_KEY', generateVapidKeyPair().privateKey);
const svc = new VapidKeysService(dbs);
expect(() => svc.getKeys()).toThrow(PushUnavailableError);
expect(() => svc.getPublicKey()).toThrow(PushUnavailableError);
expect(svc.isAvailable()).toBe(false);
expect(logError).toHaveBeenCalledTimes(1);
expect(logError).toHaveBeenCalledWith(
expect.stringContaining('Web Push is off: VAPID_PUBLIC_KEY does not belong to VAPID_PRIVATE_KEY'),
);
// Both stored rows are exactly as they were, for when the variables go again.
expect(setting(VAPID_PUBLIC_KEY_SETTING)).toBe(stored.publicKey);
expect(setting(VAPID_PRIVATE_KEY_SETTING)).toBe(ciphertext);
expect(logInfo).toHaveBeenCalledTimes(1);
});
it('VKEY-006: half a pair in the environment turns push off over a stored pair, and is reported again after a fix and relapse', () => {
const stored = new VapidKeysService(dbs).getKeys();
const ciphertext = setting(VAPID_PRIVATE_KEY_SETTING);
const pair = generateVapidKeyPair();
const svc = new VapidKeysService(dbs);
vi.stubEnv('VAPID_PRIVATE_KEY', pair.privateKey);
expect(() => svc.getKeys()).toThrow(PushUnavailableError);
expect(svc.isAvailable()).toBe(false);
expect(logError).toHaveBeenCalledTimes(1);
expect(logError).toHaveBeenCalledWith(expect.stringContaining('VAPID_PRIVATE_KEY is set without its other half'));
vi.stubEnv('VAPID_PUBLIC_KEY', pair.publicKey);
expect(svc.getKeys()).toEqual({ ...pair, source: 'env' });
// An existingSecret rotated without the private half: the devices hold the
// environment key, so signing with the stored pair would drop every one.
vi.stubEnv('VAPID_PRIVATE_KEY', '');
expect(() => svc.getKeys()).toThrow(PushUnavailableError);
expect(svc.isAvailable()).toBe(false);
expect(logError).toHaveBeenCalledTimes(2);
expect(logError).toHaveBeenLastCalledWith(
expect.stringContaining('VAPID_PUBLIC_KEY is set without its other half'),
);
expect(setting(VAPID_PUBLIC_KEY_SETTING)).toBe(stored.publicKey);
expect(setting(VAPID_PRIVATE_KEY_SETTING)).toBe(ciphertext);
// Both variables removed on purpose: the stored pair, as on any install without them.
vi.stubEnv('VAPID_PUBLIC_KEY', '');
expect(svc.getKeys()).toEqual(stored);
});
it('VKEY-006b: an install that only ran on the environment pair generates nothing when that pair breaks', () => {
const pair = generateVapidKeyPair();
vi.stubEnv('VAPID_PUBLIC_KEY', pair.publicKey);
vi.stubEnv('VAPID_PRIVATE_KEY', pair.privateKey);
const svc = new VapidKeysService(dbs);
svc.onApplicationBootstrap();
expect(svc.isAvailable()).toBe(true);
// An existingSecret without the private half: the variable is simply gone.
vi.stubEnv('VAPID_PRIVATE_KEY', '');
new VapidKeysService(dbs).onApplicationBootstrap();
expect(svc.isAvailable()).toBe(false);
expect(() => svc.getKeys()).toThrow(PushUnavailableError);
expect(setting(VAPID_PUBLIC_KEY_SETTING)).toBeUndefined();
expect(setting(VAPID_PRIVATE_KEY_SETTING)).toBeUndefined();
expect(logInfo).not.toHaveBeenCalled();
// Once per instance, with what to do and without the key.
expect(logError).toHaveBeenCalledTimes(2);
const line = logError.mock.calls[0][0] as string;
expect(line).toContain('Web Push is off: VAPID_PUBLIC_KEY is set without its other half');
expect(line).toContain('Set both variables');
expect(line).not.toContain(pair.publicKey);
// Halves that do not belong together are refused the same way.
vi.stubEnv('VAPID_PRIVATE_KEY', generateVapidKeyPair().privateKey);
expect(svc.isAvailable()).toBe(false);
expect(logError).toHaveBeenLastCalledWith(
expect.stringContaining('Web Push is off: VAPID_PUBLIC_KEY does not belong to VAPID_PRIVATE_KEY'),
);
expect(setting(VAPID_PUBLIC_KEY_SETTING)).toBeUndefined();
// The pair fixed: the same key as before, so every device receives again as it was.
vi.stubEnv('VAPID_PRIVATE_KEY', pair.privateKey);
expect(svc.getKeys()).toEqual({ ...pair, source: 'env' });
});
it('VKEY-006c: a broken environment pair over an unusable stored pair names the variables and touches no row', () => {
new VapidKeysService(dbs).getKeys();
testDb.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(UNREADABLE, VAPID_PRIVATE_KEY_SETTING);
vi.stubEnv('VAPID_PUBLIC_KEY', generateVapidKeyPair().publicKey);
const svc = new VapidKeysService(dbs);
expect(() => svc.getKeys()).toThrow(PushUnavailableError);
expect(() => svc.getKeys()).toThrow(PushUnavailableError);
expect(setting(VAPID_PRIVATE_KEY_SETTING)).toBe(UNREADABLE);
// The variables are what push would sign with, so they are what the log names.
expect(logError).toHaveBeenCalledTimes(1);
expect(logError).toHaveBeenCalledWith(
expect.stringContaining('Web Push is off: VAPID_PUBLIC_KEY is set without its other half'),
);
});
it('VKEY-007: a stored private key that no longer decrypts is kept, and push is off until the key is back', () => {
const svc = new VapidKeysService(dbs);
const original = svc.getKeys();
const ciphertext = setting(VAPID_PRIVATE_KEY_SETTING)!;
// What a restore under a different ENCRYPTION_KEY looks like from here.
testDb.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(UNREADABLE, VAPID_PRIVATE_KEY_SETTING);
logInfo.mockClear();
const broken = new VapidKeysService(dbs);
expect(() => broken.getKeys()).toThrow(PushUnavailableError);
expect(() => broken.getPublicKey()).toThrow(PushUnavailableError);
// Nothing was replaced: both rows are exactly as they were.
expect(setting(VAPID_PUBLIC_KEY_SETTING)).toBe(original.publicKey);
expect(setting(VAPID_PRIVATE_KEY_SETTING)).toBe(UNREADABLE);
expect(logInfo).not.toHaveBeenCalled();
// Said once, with the way out, and without any key material.
expect(logError).toHaveBeenCalledTimes(1);
const line = logError.mock.calls[0][0] as string;
expect(line).toContain('cannot be decrypted with the current ENCRYPTION_KEY');
expect(line).not.toContain(original.publicKey);
expect(line).not.toContain(UNREADABLE);
expect(line).not.toContain(ciphertext);
// The right key again (here: the original ciphertext back) brings the same pair back.
testDb.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(ciphertext, VAPID_PRIVATE_KEY_SETTING);
expect(broken.getKeys()).toEqual(original);
});
it('VKEY-008: half a stored pair is not completed with a new pair either', () => {
const publicKey = generateVapidKeyPair().publicKey;
testDb.prepare('INSERT INTO app_settings (key, value) VALUES (?, ?)').run(VAPID_PUBLIC_KEY_SETTING, publicKey);
expect(() => new VapidKeysService(dbs).getKeys()).toThrow(PushUnavailableError);
expect(setting(VAPID_PUBLIC_KEY_SETTING)).toBe(publicKey);
expect(setting(VAPID_PRIVATE_KEY_SETTING)).toBeUndefined();
expect(logError).toHaveBeenCalledWith(expect.stringContaining('only one half of the stored VAPID key pair'));
expect(logError).toHaveBeenCalledWith(expect.not.stringContaining(publicKey));
});
it('VKEY-008b: only the private half stored counts as incomplete too', () => {
const { privateKey } = generateVapidKeyPair();
testDb
.prepare('INSERT INTO app_settings (key, value) VALUES (?, ?)')
.run(VAPID_PRIVATE_KEY_SETTING, encrypt_api_key(privateKey));
expect(() => new VapidKeysService(dbs).getKeys()).toThrow(PushUnavailableError);
expect(setting(VAPID_PUBLIC_KEY_SETTING)).toBeUndefined();
});
it('VKEY-008c: halves that decrypt but do not belong together are refused, not replaced', () => {
const stored = generateVapidKeyPair();
testDb
.prepare('INSERT INTO app_settings (key, value) VALUES (?, ?), (?, ?)')
.run(
VAPID_PUBLIC_KEY_SETTING,
stored.publicKey,
VAPID_PRIVATE_KEY_SETTING,
encrypt_api_key(generateVapidKeyPair().privateKey),
);
expect(() => new VapidKeysService(dbs).getKeys()).toThrow(PushUnavailableError);
expect(setting(VAPID_PUBLIC_KEY_SETTING)).toBe(stored.publicKey);
expect(logError).toHaveBeenCalledWith(expect.stringContaining('does not belong to the stored public key'));
});
it('VKEY-008d: an unusable pair is reported once per state, and again after it was fixed and broke again', () => {
const svc = new VapidKeysService(dbs);
svc.getKeys();
const ciphertext = setting(VAPID_PRIVATE_KEY_SETTING)!;
testDb.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(UNREADABLE, VAPID_PRIVATE_KEY_SETTING);
for (let i = 0; i < 3; i++) expect(() => svc.getKeys()).toThrow(PushUnavailableError);
expect(logError).toHaveBeenCalledTimes(1);
testDb.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(ciphertext, VAPID_PRIVATE_KEY_SETTING);
svc.getKeys();
testDb.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(UNREADABLE, VAPID_PRIVATE_KEY_SETTING);
expect(() => svc.getKeys()).toThrow(PushUnavailableError);
expect(logError).toHaveBeenCalledTimes(2);
});
it('VKEY-008e: bootstrap over an unusable pair logs the reason once and does not throw', () => {
new VapidKeysService(dbs).getKeys();
testDb.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(UNREADABLE, VAPID_PRIVATE_KEY_SETTING);
logError.mockClear();
expect(() => new VapidKeysService(dbs).onApplicationBootstrap()).not.toThrow();
expect(logError).toHaveBeenCalledTimes(1);
expect(logError).toHaveBeenCalledWith(expect.stringContaining('Web Push is off'));
});
it('VKEY-008f: a consistent environment pair still works while the stored one is unusable', () => {
new VapidKeysService(dbs).getKeys();
testDb.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(UNREADABLE, VAPID_PRIVATE_KEY_SETTING);
const pair = generateVapidKeyPair();
vi.stubEnv('VAPID_PUBLIC_KEY', pair.publicKey);
vi.stubEnv('VAPID_PRIVATE_KEY', pair.privateKey);
const svc = new VapidKeysService(dbs);
expect(svc.getKeys()).toEqual({ ...pair, source: 'env' });
expect(svc.isAvailable()).toBe(true);
// The stored rows are still exactly what was there.
expect(setting(VAPID_PRIVATE_KEY_SETTING)).toBe(UNREADABLE);
});
it('VKEY-008g: isAvailable only reads: it creates nothing, and never touches an unusable pair', () => {
const svc = new VapidKeysService(dbs);
// Neither row yet: available, since the next send or subscribe creates the
// pair, but nothing is written now (the preference matrix GET asks this).
expect(svc.isAvailable()).toBe(true);
expect(setting(VAPID_PUBLIC_KEY_SETTING)).toBeUndefined();
expect(setting(VAPID_PRIVATE_KEY_SETTING)).toBeUndefined();
expect(logInfo).not.toHaveBeenCalled();
const { publicKey } = svc.getKeys();
expect(svc.isAvailable()).toBe(true);
testDb.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(UNREADABLE, VAPID_PRIVATE_KEY_SETTING);
expect(svc.isAvailable()).toBe(false);
expect(svc.isAvailable()).toBe(false);
expect(setting(VAPID_PUBLIC_KEY_SETTING)).toBe(publicKey);
expect(setting(VAPID_PRIVATE_KEY_SETTING)).toBe(UNREADABLE);
expect(logError).toHaveBeenCalledTimes(1);
});
it('VKEY-008h: isAvailable turns any other failure into a logged false', () => {
const svc = new VapidKeysService(dbs);
const spy = vi.spyOn(dbs, 'get').mockImplementationOnce(() => {
throw new Error('database is locked');
});
expect(svc.isAvailable()).toBe(false);
expect(logError).toHaveBeenCalledWith(expect.stringContaining('database is locked'));
spy.mockRestore();
expect(svc.isAvailable()).toBe(true);
});
});
describe('VapidKeysService subject', () => {
const svc = new VapidKeysService(dbs);
it('VKEY-009: VAPID_SUBJECT comes first', () => {
vi.stubEnv('VAPID_SUBJECT', 'mailto:push@example.test');
vi.stubEnv('APP_URL', 'https://trek.example.test');
expect(svc.getSubject()).toBe('mailto:push@example.test');
});
it('VKEY-010: then APP_URL, when it is public https', () => {
vi.stubEnv('APP_URL', ' https://trek.example.test/ ');
expect(svc.getSubject()).toBe('https://trek.example.test');
});
it('VKEY-010b: never an ALLOWED_ORIGINS entry, which can be another site allowed to call the API', () => {
vi.stubEnv('ALLOWED_ORIGINS', 'https://companion.example.test,https://trek.example.test');
expect(svc.getSubject()).toBe(FALLBACK_VAPID_SUBJECT);
vi.stubEnv('APP_URL', 'https://trek.example.test');
expect(svc.getSubject()).toBe('https://trek.example.test');
});
it('VKEY-010c: an APP_URL that does not parse is no candidate', () => {
vi.stubEnv('APP_URL', 'not a url');
expect(svc.getSubject()).toBe(FALLBACK_VAPID_SUBJECT);
});
it('VKEY-011: never the bootstrap admin address, which would travel to every push service', () => {
vi.stubEnv('ADMIN_EMAIL', 'admin@example.test');
vi.stubEnv('APP_URL', 'https://trek.example.test');
expect(svc.getSubject()).toBe('https://trek.example.test');
vi.stubEnv('APP_URL', 'http://trek.lan');
expect(svc.getSubject()).toBe(FALLBACK_VAPID_SUBJECT);
});
it('VKEY-012: then the project URL when the instance URL is plain http or localhost', () => {
vi.stubEnv('APP_URL', 'http://trek.lan');
expect(svc.getSubject()).toBe(FALLBACK_VAPID_SUBJECT);
vi.stubEnv('APP_URL', 'https://localhost:3000');
expect(svc.getSubject()).toBe(FALLBACK_VAPID_SUBJECT);
});
it('VKEY-013: and never a subject Apple would refuse, even when one is configured', () => {
vi.stubEnv('VAPID_SUBJECT', 'push@example.test'); // not mailto:, not https: (boot would have refused it)
expect(svc.getSubject()).toBe(FALLBACK_VAPID_SUBJECT);
vi.stubEnv('APP_URL', 'https://trek.example.test');
expect(svc.getSubject()).toBe('https://trek.example.test');
});
});
@@ -0,0 +1,211 @@
/**
* RFC 8291 message encryption and RFC 8292 VAPID headers (WPCRYPTO-*).
*
* The encryption is pinned twice: byte for byte against the worked example in
* RFC 8291 Appendix A, and by a decrypt written here from the receiving side,
* the way a browser unwraps the message, for fresh keys and salts.
*/
import { describe, it, expect } from 'vitest';
import { createDecipheriv, createECDH, createPublicKey, hkdfSync, type ECDH } from 'node:crypto';
import jwt from 'jsonwebtoken';
import {
MAX_PUSH_PLAINTEXT_BYTES,
PUSH_RECORD_SIZE,
VAPID_TOKEN_TTL_SECONDS,
createVapidSigner,
derivePublicKey,
encryptPushMessage,
generateVapidKeyPair,
isP256Point,
isVapidKeyPair,
} from '../../../../src/nest/notifications/push/web-push-crypto';
const b64 = (value: string) => Buffer.from(value, 'base64url');
// RFC 8291 Appendix A.
const RFC = {
plaintext: b64('V2hlbiBJIGdyb3cgdXAsIEkgd2FudCB0byBiZSBhIHdhdGVybWVsb24'),
asPublic: 'BP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8',
asPrivate: b64('yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw'),
uaPublic: b64('BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4'),
uaPrivate: b64('q1dXpw3UpT5VOmu_cf_v6ih07Aems3njxI-JWgLcM94'),
salt: b64('DGv6ra1nlYgDCS1FRnbzlw'),
auth: b64('BTBZMqHH6r4Tts7J_aSIgg'),
// Section 5, the message body as sent (the three lines of the RFC joined).
body:
'DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27ml' +
'mlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A_yl95bQpu6cVPT' +
'pK4Mqgkf1CXztLVBSt2Ks3oZwbuwXPXLWyouBWLVWGNWQexSgSxsj_Qulcy4a-fN',
};
/** The receiving side of RFC 8291, independent of the module under test. */
function decrypt(body: Buffer, ua: ECDH, auth: Buffer): { plaintext: Buffer; rs: number; keyId: Buffer } {
const salt = body.subarray(0, 16);
const rs = body.readUInt32BE(16);
const idlen = body[20];
const keyId = body.subarray(21, 21 + idlen);
const record = body.subarray(21 + idlen);
const secret = ua.computeSecret(keyId);
const keyInfo = Buffer.concat([Buffer.from('WebPush: info\0'), ua.getPublicKey(), keyId]);
const ikm = Buffer.from(hkdfSync('sha256', secret, auth, keyInfo, 32));
const cek = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16));
const nonce = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12));
const decipher = createDecipheriv('aes-128-gcm', cek, nonce);
decipher.setAuthTag(record.subarray(record.length - 16));
const padded = Buffer.concat([decipher.update(record.subarray(0, record.length - 16)), decipher.final()]);
let end = padded.length - 1;
while (end >= 0 && padded[end] === 0) end--;
expect(padded[end]).toBe(0x02); // the last-record delimiter
return { plaintext: padded.subarray(0, end), rs, keyId };
}
function browser() {
const ua = createECDH('prime256v1');
ua.generateKeys();
const auth = Buffer.from('0123456789abcdef');
return { ua, keys: { p256dh: ua.getPublicKey(), auth } };
}
describe('encryptPushMessage', () => {
it('WPCRYPTO-001: reproduces the RFC 8291 Appendix A message byte for byte', () => {
const body = encryptPushMessage(
RFC.plaintext,
{ p256dh: RFC.uaPublic, auth: RFC.auth },
{ salt: RFC.salt, senderPrivateKey: RFC.asPrivate },
);
expect(body.toString('base64url')).toBe(RFC.body);
});
it('WPCRYPTO-002: the RFC message decrypts with the user agent key, which checks the reference decrypt too', () => {
const ua = createECDH('prime256v1');
ua.setPrivateKey(RFC.uaPrivate);
const { plaintext, rs, keyId } = decrypt(b64(RFC.body), ua, RFC.auth);
expect(plaintext.toString('utf8')).toBe('When I grow up, I want to be a watermelon');
expect(rs).toBe(4096);
expect(keyId.toString('base64url')).toBe(RFC.asPublic);
});
it('WPCRYPTO-003: a real message round-trips, with a fresh salt and sender key every time', () => {
const { ua, keys } = browser();
const message = Buffer.from(JSON.stringify({ title: 'Trip reminder: Kyōto', body: 'Tomorrow 🚄' }));
const first = encryptPushMessage(message, keys);
const second = encryptPushMessage(message, keys);
expect(decrypt(first, ua, keys.auth).plaintext.equals(message)).toBe(true);
expect(decrypt(second, ua, keys.auth).plaintext.equals(message)).toBe(true);
expect(first.subarray(0, 16).equals(second.subarray(0, 16))).toBe(false);
expect(first.subarray(21, 86).equals(second.subarray(21, 86))).toBe(false);
});
it('WPCRYPTO-004: the largest allowed plaintext still fits one 4096-byte record', () => {
const { ua, keys } = browser();
const message = Buffer.alloc(MAX_PUSH_PLAINTEXT_BYTES, 'a');
const body = encryptPushMessage(message, keys);
expect(body.length).toBe(PUSH_RECORD_SIZE);
expect(decrypt(body, ua, keys.auth).plaintext.length).toBe(MAX_PUSH_PLAINTEXT_BYTES);
expect(() => encryptPushMessage(Buffer.alloc(MAX_PUSH_PLAINTEXT_BYTES + 1), keys)).toThrow(
/does not fit one record/,
);
});
it('WPCRYPTO-005: refuses keys it cannot encrypt for', () => {
const { keys } = browser();
const offCurve = Buffer.from(keys.p256dh);
offCurve[64] ^= 0x01;
expect(() => encryptPushMessage(Buffer.from('x'), { ...keys, p256dh: offCurve })).toThrow(/p256dh/);
expect(() => encryptPushMessage(Buffer.from('x'), { ...keys, auth: Buffer.alloc(8) })).toThrow(/auth secret/);
expect(() => encryptPushMessage(Buffer.from('x'), keys, { salt: Buffer.alloc(4) })).toThrow(/salt/);
});
});
describe('key helpers', () => {
it('WPCRYPTO-006: generates a full-length pair whose halves belong together', () => {
for (let i = 0; i < 20; i++) {
const pair = generateVapidKeyPair();
const pub = b64(pair.publicKey);
expect(pub.length).toBe(65);
expect(pub[0]).toBe(0x04);
expect(b64(pair.privateKey).length).toBe(32);
expect(isVapidKeyPair(pair.publicKey, pair.privateKey)).toBe(true);
}
});
it('WPCRYPTO-007: tells a pair from two unrelated halves, and rejects what is not a key', () => {
const a = generateVapidKeyPair();
const b = generateVapidKeyPair();
expect(isVapidKeyPair(a.publicKey, b.privateKey)).toBe(false);
expect(isVapidKeyPair('not base64url!', a.privateKey)).toBe(false);
expect(derivePublicKey('short')).toBeNull();
expect(derivePublicKey(Buffer.alloc(32).toString('base64url'))).toBeNull(); // zero is no scalar
expect(derivePublicKey(a.privateKey)?.toString('base64url')).toBe(a.publicKey);
});
it('WPCRYPTO-008: isP256Point wants an uncompressed point that is on the curve', () => {
const { keys } = browser();
expect(isP256Point(keys.p256dh)).toBe(true);
const offCurve = Buffer.from(keys.p256dh);
offCurve[40] ^= 0xff;
expect(isP256Point(offCurve)).toBe(false);
expect(isP256Point(Buffer.concat([Buffer.from([0x03]), keys.p256dh.subarray(1)]))).toBe(false);
expect(isP256Point(keys.p256dh.subarray(0, 33))).toBe(false);
});
});
describe('createVapidSigner', () => {
const pair = generateVapidKeyPair();
const pub = b64(pair.publicKey);
const verifyKey = createPublicKey({
key: {
kty: 'EC',
crv: 'P-256',
x: pub.subarray(1, 33).toString('base64url'),
y: pub.subarray(33).toString('base64url'),
},
format: 'jwk',
});
function parse(header: string) {
const m = /^vapid t=([^,]+), k=(.+)$/.exec(header);
expect(m).not.toBeNull();
return { token: m![1], k: m![2] };
}
it('WPCRYPTO-009: builds `vapid t=<ES256 JWT>, k=<public key>` for the endpoint origin', () => {
const now = Date.UTC(2026, 8, 24, 12, 0, 0);
const sign = createVapidSigner(pair, 'mailto:ops@example.test', () => now);
const { token, k } = parse(sign('https://fcm.googleapis.com/fcm/send/abc:def'));
expect(k).toBe(pair.publicKey);
const claims = jwt.verify(token, verifyKey, {
algorithms: ['ES256'],
clockTimestamp: now / 1000,
}) as jwt.JwtPayload;
expect(claims).toEqual({
aud: 'https://fcm.googleapis.com',
exp: now / 1000 + VAPID_TOKEN_TTL_SECONDS,
sub: 'mailto:ops@example.test',
});
expect(VAPID_TOKEN_TTL_SECONDS).toBeLessThanOrEqual(24 * 60 * 60);
const [header, , signature] = token.split('.');
expect(JSON.parse(b64(header).toString('utf8'))).toEqual({ alg: 'ES256', typ: 'JWT' });
// JOSE r||s, not DER: the form push services verify.
expect(b64(signature).length).toBe(64);
});
it('WPCRYPTO-010: signs once per origin and separately for another push service', () => {
const sign = createVapidSigner(pair, 'https://trek.example.test');
const a = sign('https://updates.push.services.mozilla.com/wpush/v2/one');
const b = sign('https://updates.push.services.mozilla.com/wpush/v2/two');
const c = sign('https://web.push.apple.com/QGx');
expect(a).toBe(b);
expect(c).not.toBe(a);
const claims = jwt.decode(parse(c).token) as jwt.JwtPayload;
expect(claims.aud).toBe('https://web.push.apple.com');
});
it('WPCRYPTO-011: refuses a malformed key pair up front', () => {
expect(() => createVapidSigner({ publicKey: 'abc', privateKey: pair.privateKey }, 'mailto:a@b.test')).toThrow(
/malformed/,
);
});
});
@@ -0,0 +1,302 @@
/**
* Web Push inside the dispatcher (WPDISP-*): the admin switch, the per-user
* Push column, admin-scoped events, the preference matrix, the generic test
* route, and all of them while the key pair cannot be used, stored or from
* VAPID_*. Real NotificationsService and real SQL; safeFetchFollow is the edge.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest';
import { createECDH } from 'node:crypto';
// One :memory: connection per file, created inside the factory so nothing has
// to be hoisted above the imports; the tests reach it through the mocked module.
vi.mock('../../../../src/db/database', async () => {
const { default: Database } = await import('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
return {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
});
vi.mock('../../../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
const { safeFetchFollow, logError } = vi.hoisted(() => ({ safeFetchFollow: vi.fn(), logError: vi.fn() }));
vi.mock('../../../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo: vi.fn(),
logDebug: vi.fn(),
logError,
logWarn: vi.fn(),
}));
vi.mock('../../../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
vi.mock('../../../../src/utils/ssrfGuard', () => {
class SsrfBlockedError extends Error {}
return { SsrfBlockedError, safeFetchFollow };
});
import { db as testDb } from '../../../../src/db/database';
import { createTables } from '../../../../src/db/schema';
import { runMigrations } from '../../../../src/db/migrations';
import { resetTestDb } from '../../../helpers/test-db';
import { createAdmin, createUser, disableNotificationPref, setNotificationChannels } from '../../../helpers/factories';
import { makeNotificationPreferencesService, makeNotificationsService } from '../../../helpers/notifications';
import { DatabaseService } from '../../../../src/nest/database/database.service';
import { PushSubscriptionsService } from '../../../../src/nest/notifications/push/push-subscriptions.service';
import {
PUSH_UNAVAILABLE_ERROR,
VAPID_PRIVATE_KEY_SETTING,
VapidKeysService,
} from '../../../../src/nest/notifications/push/vapid-keys.service';
import { checkPushSubscription } from '../../../../src/nest/notifications/push/push-subscription.helpers';
import { generateVapidKeyPair } from '../../../../src/nest/notifications/push/web-push-crypto';
const dbs = new DatabaseService(testDb);
const notifications = makeNotificationsService(dbs);
const prefs = makeNotificationPreferencesService(dbs);
const subscriptions = new PushSubscriptionsService(dbs);
const keys = new VapidKeysService(dbs);
function addDevice(userId: number, endpoint = `https://fcm.googleapis.com/fcm/send/u${userId}`): string {
const ua = createECDH('prime256v1');
ua.generateKeys();
const checked = checkPushSubscription({
endpoint,
keys: { p256dh: ua.getPublicKey('base64url'), auth: Buffer.alloc(16, 7).toString('base64url') },
});
if ('error' in checked) throw new Error(checked.error);
subscriptions.upsert(userId, checked.value, keys.getPublicKey());
return endpoint;
}
function invite(targetId: number, actorId: number) {
return notifications.send({
event: 'trip_invite',
actorId,
params: { trip: 'Lisbon', actor: 'bob@example.test', invitee: 'alice', tripId: '12' },
scope: 'user',
targetId,
});
}
const pushedTo = () => safeFetchFollow.mock.calls.map((c) => c[0] as string);
/** What a restore under a different ENCRYPTION_KEY leaves behind: a private key that no longer opens. */
const UNREADABLE = 'enc:v1:bm90IGEgY2lwaGVydGV4dA';
function breakStoredPrivateKey(): void {
testDb.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(UNREADABLE, VAPID_PRIVATE_KEY_SETTING);
}
const pushColumn = (userId: number) =>
prefs.getPreferencesMatrix(userId, 'user').channels.find((c) => c.id === 'push');
const storedKeyRows = () =>
testDb.prepare("SELECT key, value FROM app_settings WHERE key LIKE 'web_push_vapid_%' ORDER BY key").all();
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
safeFetchFollow.mockReset();
safeFetchFollow.mockResolvedValue({ ok: true, status: 201, body: null, headers: { get: () => null } });
logError.mockClear();
});
afterEach(() => {
vi.unstubAllEnvs();
});
afterAll(() => {
testDb.close();
});
describe('Web Push in NotificationsService.send()', () => {
it('WPDISP-001: goes out once the admin enabled push and the user has a device', async () => {
const { user } = createUser(testDb);
const { user: actor } = createUser(testDb);
const endpoint = addDevice(user.id);
setNotificationChannels(testDb, 'push');
await invite(user.id, actor.id);
expect(pushedTo()).toEqual([endpoint]);
});
it('WPDISP-002: stays quiet while the admin has not enabled push', async () => {
const { user } = createUser(testDb);
const { user: actor } = createUser(testDb);
addDevice(user.id);
setNotificationChannels(testDb, 'email');
await invite(user.id, actor.id);
expect(safeFetchFollow).not.toHaveBeenCalled();
});
it('WPDISP-003: respects the user switching the event off in the Push column', async () => {
const { user } = createUser(testDb);
const { user: actor } = createUser(testDb);
addDevice(user.id);
setNotificationChannels(testDb, 'push');
disableNotificationPref(testDb, user.id, 'trip_invite', 'push');
await invite(user.id, actor.id);
expect(safeFetchFollow).not.toHaveBeenCalled();
});
it('WPDISP-004: never carries an admin-scoped event', async () => {
const { user: admin } = createAdmin(testDb);
addDevice(admin.id);
setNotificationChannels(testDb, 'push');
await notifications.send({
event: 'version_available',
actorId: null,
params: { version: '9.9.9' },
scope: 'admin',
targetId: 0,
});
expect(safeFetchFollow).not.toHaveBeenCalled();
});
});
describe('Web Push in the preference matrix', () => {
it('WPDISP-005: the user matrix gets a Push column, active by the admin switch, configured by a device', () => {
const { user } = createUser(testDb);
let push = prefs.getPreferencesMatrix(user.id, 'user').channels.find((c) => c.id === 'push');
expect(push).toMatchObject({
source: 'builtin',
labelKey: 'settings.notificationPreferences.push',
active: false,
configured: false,
});
setNotificationChannels(testDb, 'email,push');
addDevice(user.id);
push = prefs.getPreferencesMatrix(user.id, 'user').channels.find((c) => c.id === 'push');
expect(push).toMatchObject({ active: true, configured: true });
expect(prefs.getActiveChannels()).toEqual(['email', 'push']);
expect(prefs.getPreferencesMatrix(user.id, 'user').implemented_combos['trip_invite']).toContain('push');
});
it('WPDISP-006: the admin matrix has no Push column, since push never carries admin events', () => {
const { user: admin } = createAdmin(testDb);
const matrix = prefs.getPreferencesMatrix(admin.id, 'admin', 'admin');
expect(matrix.channels.map((c) => c.id)).toEqual(['inapp', 'email', 'webhook', 'ntfy']);
expect(matrix.implemented_combos['version_available']).not.toContain('push');
expect(matrix.preferences['version_available']).not.toHaveProperty('push');
});
});
describe('POST /api/notifications/test/push, through the registry', () => {
it('WPDISP-007: refuses a user without a device and sends to one with', async () => {
const { user } = createUser(testDb);
await expect(notifications.testChannel(user.id, 'push')).resolves.toEqual({
success: false,
error: 'Channel is not configured for this user',
});
const endpoint = addDevice(user.id);
await expect(notifications.testChannel(user.id, 'push')).resolves.toEqual({ success: true });
expect(pushedTo()).toEqual([endpoint]);
});
});
describe('Web Push while the stored key pair cannot be used', () => {
it('WPDISP-008: a send skips push without an error while in-app and webhook still go out', async () => {
const { user } = createUser(testDb);
const { user: actor } = createUser(testDb);
const endpoint = addDevice(user.id);
testDb
.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'webhook_url', ?)")
.run(user.id, 'https://hooks.example.test/trek');
setNotificationChannels(testDb, 'webhook,push');
breakStoredPrivateKey();
await expect(invite(user.id, actor.id)).resolves.toBeUndefined();
expect(pushedTo()).toEqual(['https://hooks.example.test/trek']);
const inApp = testDb.prepare('SELECT COUNT(*) AS n FROM notifications WHERE recipient_id = ?').get(user.id) as {
n: number;
};
expect(inApp.n).toBe(1);
// The device is kept for when the key is back, and nothing failed on the way.
expect(subscriptions.listForUser(user.id).map((r) => r.endpoint)).toEqual([endpoint]);
expect(logError).not.toHaveBeenCalledWith(expect.stringContaining('dispatch failed'));
expect(logError).not.toHaveBeenCalledWith(expect.stringContaining('Web Push failed'));
});
it('WPDISP-009: the matrix stops offering push, so the card and the column go, and both come back with the key', () => {
const { user } = createUser(testDb);
setNotificationChannels(testDb, 'email,push');
addDevice(user.id);
const ciphertext = (
testDb.prepare('SELECT value FROM app_settings WHERE key = ?').get(VAPID_PRIVATE_KEY_SETTING) as { value: string }
).value;
breakStoredPrivateKey();
expect(pushColumn(user.id)).toMatchObject({ active: false, configured: true });
// Only push: email keeps its column, SMTP or not, as it always has.
expect(prefs.getPreferencesMatrix(user.id, 'user').channels.find((c) => c.id === 'email')?.active).toBe(true);
testDb.prepare('UPDATE app_settings SET value = ? WHERE key = ?').run(ciphertext, VAPID_PRIVATE_KEY_SETTING);
expect(pushColumn(user.id)).toMatchObject({ active: true, configured: true });
});
it('WPDISP-009b: reading the matrix while neither key row exists writes nothing, and push is still offered', () => {
const { user } = createUser(testDb);
setNotificationChannels(testDb, 'email,push');
addDevice(user.id);
// What deleting both rows to start over leaves under a running server.
testDb.prepare("DELETE FROM app_settings WHERE key LIKE 'web_push_vapid_%'").run();
expect(pushColumn(user.id)).toMatchObject({ active: true, configured: true });
expect(storedKeyRows()).toEqual([]);
});
it('WPDISP-010: the test send says push is unavailable and sends nothing', async () => {
const { user } = createUser(testDb);
addDevice(user.id);
breakStoredPrivateKey();
await expect(notifications.testChannel(user.id, 'push')).resolves.toEqual({
success: false,
error: PUSH_UNAVAILABLE_ERROR,
});
expect(safeFetchFollow).not.toHaveBeenCalled();
});
});
describe('Web Push while the VAPID_* pair is broken and an older pair is stored', () => {
it('WPDISP-011: nothing is sent, the device and both rows stay, the column goes, and all of it returns with the variables', async () => {
const { user } = createUser(testDb);
const { user: actor } = createUser(testDb);
setNotificationChannels(testDb, 'push');
// The first start without VAPID_* stored a pair; the operator then brought their own.
keys.getPublicKey();
const stored = storedKeyRows();
const pair = generateVapidKeyPair();
vi.stubEnv('VAPID_PUBLIC_KEY', pair.publicKey);
vi.stubEnv('VAPID_PRIVATE_KEY', pair.privateKey);
const endpoint = addDevice(user.id);
// A typo or a rotated Secret: still a valid 32-byte key, so boot is fine.
vi.stubEnv('VAPID_PRIVATE_KEY', generateVapidKeyPair().privateKey);
await expect(invite(user.id, actor.id)).resolves.toBeUndefined();
expect(safeFetchFollow).not.toHaveBeenCalled();
expect(subscriptions.listForUser(user.id).map((r) => [r.endpoint, r.vapid_public_key])).toEqual([
[endpoint, pair.publicKey],
]);
expect(storedKeyRows()).toEqual(stored);
expect(pushColumn(user.id)).toMatchObject({ active: false, configured: true });
vi.stubEnv('VAPID_PRIVATE_KEY', pair.privateKey);
expect(pushColumn(user.id)).toMatchObject({ active: true, configured: true });
await invite(user.id, actor.id);
expect(pushedTo()).toEqual([endpoint]);
});
});
@@ -0,0 +1,528 @@
/**
* The Web Push transport (WPUSH-*): what goes over the wire, what each push
* service answer does to the table, and the payload the worker receives
* (WPUSH-PAY-*). safeFetchFollow is the boundary; the database is real.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
import { HttpException } from '@nestjs/common';
import { createDecipheriv, createECDH, hkdfSync, type ECDH } from 'node:crypto';
// One :memory: connection per file, created inside the factory so nothing has
// to be hoisted above the imports; the tests reach it through the mocked module.
vi.mock('../../../../src/db/database', async () => {
const { default: Database } = await import('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
return {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
});
vi.mock('../../../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
const { logInfo, logError, safeFetchFollow } = vi.hoisted(() => ({
logInfo: vi.fn(),
logError: vi.fn(),
safeFetchFollow: vi.fn(),
}));
vi.mock('../../../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo,
logDebug: vi.fn(),
logError,
logWarn: vi.fn(),
}));
vi.mock('../../../../src/utils/ssrfGuard', () => {
class SsrfBlockedError extends Error {
constructor(message: string) {
super(message);
this.name = 'SsrfBlockedError';
}
}
return { SsrfBlockedError, safeFetchFollow };
});
import { db as testDb } from '../../../../src/db/database';
import { createTables } from '../../../../src/db/schema';
import { runMigrations } from '../../../../src/db/migrations';
import { resetTestDb } from '../../../helpers/test-db';
import { createUser } from '../../../helpers/factories';
import { DatabaseService } from '../../../../src/nest/database/database.service';
import { SsrfBlockedError } from '../../../../src/utils/ssrfGuard';
import { PushSubscriptionsService } from '../../../../src/nest/notifications/push/push-subscriptions.service';
import {
PUSH_UNAVAILABLE_ERROR,
VAPID_PRIVATE_KEY_SETTING,
VAPID_PUBLIC_KEY_SETTING,
VapidKeysService,
} from '../../../../src/nest/notifications/push/vapid-keys.service';
import { PushController } from '../../../../src/nest/notifications/push/push.controller';
import { checkPushSubscription } from '../../../../src/nest/notifications/push/push-subscription.helpers';
import { generateVapidKeyPair } from '../../../../src/nest/notifications/push/web-push-crypto';
import {
FORBIDDEN_FAILURES_BEFORE_REMOVAL,
MAX_PUSH_PAYLOAD_BYTES,
WebPushService,
buildPushPayload,
samePagePath,
} from '../../../../src/nest/notifications/transports/web-push.service';
import { ALL_EVENT_TYPES, type ChannelMessage } from '../../../../src/nest/notifications/notification-events';
const dbs = new DatabaseService(testDb);
const keys = new VapidKeysService(dbs);
const subscriptions = new PushSubscriptionsService(dbs);
const push = new WebPushService(keys, subscriptions);
const MSG: ChannelMessage = {
event: 'collab_message',
title: 'New message in "Lisbon"',
body: 'alice: see you at the station',
navigateTarget: '/trips/12',
url: 'https://trek.example.test/trips/12',
};
interface Device {
endpoint: string;
ua: ECDH;
auth: Buffer;
}
function subscribe(userId: number, endpoint: string): Device {
const ua = createECDH('prime256v1');
ua.generateKeys();
const auth = Buffer.from('fedcba9876543210');
const checked = checkPushSubscription({
endpoint,
keys: { p256dh: ua.getPublicKey('base64url'), auth: auth.toString('base64url') },
});
if ('error' in checked) throw new Error(checked.error);
subscriptions.upsert(userId, checked.value, keys.getPublicKey());
return { endpoint, ua, auth };
}
/** The browser's side of RFC 8291, to read what was actually sent. */
function open(body: Uint8Array, device: Device): unknown {
const buf = Buffer.from(body);
const salt = buf.subarray(0, 16);
const keyId = buf.subarray(21, 21 + buf[20]);
const record = buf.subarray(21 + buf[20]);
const secret = device.ua.computeSecret(keyId);
const info = Buffer.concat([Buffer.from('WebPush: info\0'), device.ua.getPublicKey(), keyId]);
const ikm = Buffer.from(hkdfSync('sha256', secret, device.auth, info, 32));
const cek = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16));
const nonce = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12));
const decipher = createDecipheriv('aes-128-gcm', cek, nonce);
decipher.setAuthTag(record.subarray(record.length - 16));
const padded = Buffer.concat([decipher.update(record.subarray(0, record.length - 16)), decipher.final()]);
return JSON.parse(padded.subarray(0, padded.lastIndexOf(0x02)).toString('utf8'));
}
function reply(status: number, text = '') {
return {
ok: status >= 200 && status < 300,
status,
body: null,
headers: { get: () => null },
text: async () => text,
};
}
function rows(userId: number) {
return subscriptions.listForUser(userId);
}
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
safeFetchFollow.mockReset();
logInfo.mockClear();
logError.mockClear();
});
afterAll(() => {
testDb.close();
});
describe('WebPushService delivery', () => {
it('WPUSH-001: posts one encrypted, VAPID-signed message through the SSRF guard', async () => {
const { user } = createUser(testDb);
const device = subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/abc');
safeFetchFollow.mockResolvedValue(reply(201));
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(true);
expect(safeFetchFollow).toHaveBeenCalledTimes(1);
const [url, init, options] = safeFetchFollow.mock.calls[0];
expect(url).toBe(device.endpoint);
expect(options).toEqual({ maxRedirects: 0, bypassInternalIpAllowed: true });
expect(init.method).toBe('POST');
expect(init.signal).toBeInstanceOf(AbortSignal);
expect(init.headers).toMatchObject({
TTL: '86400',
Urgency: 'normal',
'Content-Encoding': 'aes128gcm',
'Content-Type': 'application/octet-stream',
});
expect(init.headers.Authorization).toMatch(
new RegExp(`^vapid t=[\\w-]+\\.[\\w-]+\\.[\\w-]+, k=${keys.getPublicKey()}$`),
);
expect(open(init.body, device)).toEqual({
title: MSG.title,
body: MSG.body,
url: '/trips/12',
tag: 'collab_message:/trips/12',
});
const [row] = rows(user.id);
expect(row.last_success_at).not.toBeNull();
expect(row.failure_count).toBe(0);
});
it('WPUSH-002: date-bound events go out with high urgency', async () => {
const { user } = createUser(testDb);
subscribe(user.id, 'https://web.push.apple.com/QGx');
safeFetchFollow.mockResolvedValue(reply(201));
await push.sendToUser(user.id, { ...MSG, event: 'trip_reminder' });
expect(safeFetchFollow.mock.calls[0][1].headers.Urgency).toBe('high');
});
it('WPUSH-003: 404 and 410 mean the browser is gone, and the row goes with it', async () => {
const { user } = createUser(testDb);
subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/expired');
subscribe(user.id, 'https://updates.push.services.mozilla.com/wpush/v2/revoked');
safeFetchFollow.mockImplementation(async (url: string) => reply(url.includes('expired') ? 404 : 410));
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
expect(rows(user.id)).toEqual([]);
expect(logError).not.toHaveBeenCalled();
});
it('WPUSH-004: a first 403 with Apple’s BadJwtToken keeps the device, counts it and logs the reason', async () => {
// Apple answers 403 for a token it rejects, which is the server's problem
// (subject, clock, key), not a sign the device is gone.
const { user } = createUser(testDb);
subscribe(user.id, 'https://web.push.apple.com/QGx');
safeFetchFollow.mockResolvedValue(reply(403, '{"reason":"BadJwtToken"}'));
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
expect(rows(user.id)).toHaveLength(1);
expect(rows(user.id)[0].failure_count).toBe(1);
const line = logError.mock.calls[0][0] as string;
expect(line).toContain('HTTP 403');
expect(line).toContain('BadJwtToken');
expect(line).toContain('host=web.push.apple.com');
// The endpoint is a capability URL: the log names the host only.
expect(line).not.toContain('/QGx');
});
it(`WPUSH-004b: the device goes after ${FORBIDDEN_FAILURES_BEFORE_REMOVAL} failed sends in a row ending in 403`, async () => {
const { user } = createUser(testDb);
subscribe(user.id, 'https://web.push.apple.com/QGx');
safeFetchFollow.mockResolvedValue(reply(403, '{"reason":"BadJwtToken"}'));
for (let i = 1; i < FORBIDDEN_FAILURES_BEFORE_REMOVAL; i++) {
await push.sendToUser(user.id, MSG);
expect(rows(user.id)[0].failure_count).toBe(i);
}
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
expect(rows(user.id)).toEqual([]);
expect(logError).toHaveBeenLastCalledWith(expect.stringContaining('removed a device'));
expect(logError).toHaveBeenLastCalledWith(expect.stringContaining('BadJwtToken'));
});
it('WPUSH-004c: a success between refusals starts the count over', async () => {
const { user } = createUser(testDb);
subscribe(user.id, 'https://web.push.apple.com/QGx');
safeFetchFollow.mockResolvedValue(reply(403, '{"reason":"BadJwtToken"}'));
for (let i = 1; i < FORBIDDEN_FAILURES_BEFORE_REMOVAL; i++) await push.sendToUser(user.id, MSG);
safeFetchFollow.mockResolvedValueOnce(reply(201));
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(true);
expect(rows(user.id)[0].failure_count).toBe(0);
await push.sendToUser(user.id, MSG);
expect(rows(user.id)).toHaveLength(1);
expect(rows(user.id)[0].failure_count).toBe(1);
});
it('WPUSH-005: any other failure keeps the row, counts it and logs the capped body', async () => {
const { user } = createUser(testDb);
subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/busy');
safeFetchFollow.mockResolvedValue(reply(503, `overloaded ${'x'.repeat(5000)}`));
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
expect(rows(user.id)[0].failure_count).toBe(1);
const line = logError.mock.calls[0][0] as string;
expect(line).toContain('HTTP 503');
expect(line.length).toBeLessThan(1300);
// A body that cannot be read changes nothing but the log text.
safeFetchFollow.mockResolvedValueOnce({
...reply(500),
text: async () => {
throw new Error('stream reset');
},
});
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
expect(rows(user.id)[0].failure_count).toBe(2);
expect(logError).toHaveBeenLastCalledWith(expect.stringMatching(/HTTP 500 .*host=fcm\.googleapis\.com: $/));
});
it('WPUSH-006: a refused or failed request is a failure, never a throw', async () => {
const { user } = createUser(testDb);
subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/a');
safeFetchFollow.mockRejectedValueOnce(new SsrfBlockedError('Requests to private addresses are not allowed'));
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
expect(logError).toHaveBeenLastCalledWith(expect.stringContaining('blocked by SSRF guard'));
safeFetchFollow.mockRejectedValueOnce(new Error('The operation was aborted due to timeout'));
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
expect(logError).toHaveBeenLastCalledWith(expect.stringContaining('timeout'));
expect(rows(user.id)[0].failure_count).toBe(2);
});
it('WPUSH-007: one device getting it is enough', async () => {
const { user } = createUser(testDb);
subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/ok');
subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/down');
safeFetchFollow.mockImplementation(async (url: string) => reply(url.endsWith('/ok') ? 201 : 500));
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(true);
// Both hosts are the same origin, so one token served both requests.
const [a, b] = safeFetchFollow.mock.calls.map((c) => c[1].headers.Authorization);
expect(a).toBe(b);
});
it('WPUSH-008: a row made for a previous server key is dropped without a request', async () => {
const { user } = createUser(testDb);
subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/old');
testDb.prepare("UPDATE push_subscriptions SET vapid_public_key = 'previous-key'").run();
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
expect(safeFetchFollow).not.toHaveBeenCalled();
expect(rows(user.id)).toEqual([]);
});
it('WPUSH-009: a row whose host is not a push service any more is dropped without a request', async () => {
const { user } = createUser(testDb);
subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/x');
subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/y');
testDb
.prepare("UPDATE push_subscriptions SET endpoint = 'https://attacker.example.test/collect' WHERE endpoint LIKE '%/x'")
.run();
testDb.prepare("UPDATE push_subscriptions SET endpoint = 'not a url' WHERE endpoint LIKE '%/y'").run();
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
expect(safeFetchFollow).not.toHaveBeenCalled();
expect(rows(user.id)).toEqual([]);
expect(logError).toHaveBeenCalledWith(expect.stringContaining('host=attacker.example.test'));
// Not even a URL: the log still has something to name instead of the value.
expect(logError).toHaveBeenCalledWith(expect.stringContaining('not a known push service user'));
expect(logError).toHaveBeenCalledWith(expect.stringContaining('host=invalid-endpoint'));
});
it('WPUSH-010: broken stored keys count as a failure for that row', async () => {
const { user } = createUser(testDb);
subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/x');
testDb.prepare("UPDATE push_subscriptions SET auth = '***'").run();
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
expect(safeFetchFollow).not.toHaveBeenCalled();
expect(rows(user.id)[0].failure_count).toBe(1);
});
it('WPUSH-011: nothing to send to is simply false', async () => {
const { user } = createUser(testDb);
expect(push.hasDevices(user.id)).toBe(false);
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
expect(safeFetchFollow).not.toHaveBeenCalled();
});
it('WPUSH-012: a failure before any request (no key pair) is logged and false', async () => {
const { user } = createUser(testDb);
subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/x');
const spy = vi.spyOn(keys, 'getKeys').mockImplementationOnce(() => {
throw new Error('database is locked');
});
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
expect(logError).toHaveBeenCalledWith(expect.stringContaining('database is locked'));
spy.mockRestore();
});
it('WPUSH-012b: while the stored key pair cannot be used nothing is sent and every device stays', async () => {
const { user } = createUser(testDb);
subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/x');
const publicKey = keys.getPublicKey();
// A restore under a different ENCRYPTION_KEY: the ciphertext no longer opens.
testDb
.prepare("UPDATE app_settings SET value = 'enc:v1:bm90IGEgY2lwaGVydGV4dA' WHERE key = ?")
.run(VAPID_PRIVATE_KEY_SETTING);
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
expect(safeFetchFollow).not.toHaveBeenCalled();
expect(rows(user.id)).toHaveLength(1);
expect(rows(user.id)[0].vapid_public_key).toBe(publicKey);
expect(rows(user.id)[0].failure_count).toBe(0);
expect(push.isAvailable()).toBe(false);
// The test send says why instead of a bare failure, and sends nothing either.
await expect(push.sendTest(user.id)).resolves.toEqual({ success: false, error: PUSH_UNAVAILABLE_ERROR });
expect(safeFetchFollow).not.toHaveBeenCalled();
});
it('WPUSH-012c: an install that only ran on VAPID_* generates nothing when that pair breaks, and keeps every device', async () => {
const pair = generateVapidKeyPair();
vi.stubEnv('VAPID_PUBLIC_KEY', pair.publicKey);
vi.stubEnv('VAPID_PRIVATE_KEY', pair.privateKey);
try {
const { user } = createUser(testDb);
subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/x');
subscribe(user.id, 'https://web.push.apple.com/y');
// An existingSecret without the private half: the variable is simply gone.
vi.stubEnv('VAPID_PRIVATE_KEY', '');
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
await expect(push.sendTest(user.id)).resolves.toEqual({ success: false, error: PUSH_UNAVAILABLE_ERROR });
expect(push.isAvailable()).toBe(false);
expect(safeFetchFollow).not.toHaveBeenCalled();
expect(testDb.prepare("SELECT key FROM app_settings WHERE key LIKE 'web_push_vapid_%'").all()).toEqual([]);
expect(rows(user.id).map((row) => row.vapid_public_key)).toEqual([pair.publicKey, pair.publicKey]);
// The Secret fixed: the same devices receive again, nobody turns push on again.
vi.stubEnv('VAPID_PRIVATE_KEY', pair.privateKey);
safeFetchFollow.mockResolvedValue(reply(201));
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(true);
expect(safeFetchFollow).toHaveBeenCalledTimes(2);
expect(rows(user.id)).toHaveLength(2);
} finally {
vi.unstubAllEnvs();
}
});
it('WPUSH-012d: a broken VAPID_* pair over a pair stored from before sends nothing, keeps every device and serves no key', async () => {
// The first start without VAPID_* stored a pair; the operator then brought their own.
const storedKey = keys.getPublicKey();
const pair = generateVapidKeyPair();
vi.stubEnv('VAPID_PUBLIC_KEY', pair.publicKey);
vi.stubEnv('VAPID_PRIVATE_KEY', pair.privateKey);
const controller = new PushController(keys, subscriptions);
try {
const { user } = createUser(testDb);
subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/x');
subscribe(user.id, 'https://web.push.apple.com/y');
// An existingSecret rotated without the private half.
vi.stubEnv('VAPID_PRIVATE_KEY', '');
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(false);
await expect(push.sendTest(user.id)).resolves.toEqual({ success: false, error: PUSH_UNAVAILABLE_ERROR });
expect(push.isAvailable()).toBe(false);
expect(safeFetchFollow).not.toHaveBeenCalled();
// Signing with the stored pair would have dropped both rows; they stay on the environment key.
expect(rows(user.id).map((row) => row.vapid_public_key)).toEqual([pair.publicKey, pair.publicKey]);
expect(testDb.prepare('SELECT value FROM app_settings WHERE key = ?').get(VAPID_PUBLIC_KEY_SETTING)).toEqual({
value: storedKey,
});
// Browsers are not handed the stored key to subscribe again with either.
let refusal: unknown = null;
try {
controller.publicKey();
} catch (err) {
refusal = err;
}
expect(refusal).toBeInstanceOf(HttpException);
expect((refusal as HttpException).getStatus()).toBe(503);
// The Secret fixed: the same rows receive again, and the key served is the one they hold.
vi.stubEnv('VAPID_PRIVATE_KEY', pair.privateKey);
safeFetchFollow.mockResolvedValue(reply(201));
await expect(push.sendToUser(user.id, MSG)).resolves.toBe(true);
expect(safeFetchFollow).toHaveBeenCalledTimes(2);
expect(rows(user.id)).toHaveLength(2);
expect(controller.publicKey()).toEqual({ publicKey: pair.publicKey });
} finally {
vi.unstubAllEnvs();
}
});
it('WPUSH-013: the test send reports success and failure like the other channels', async () => {
const { user } = createUser(testDb);
const device = subscribe(user.id, 'https://fcm.googleapis.com/fcm/send/x');
safeFetchFollow.mockResolvedValueOnce(reply(201));
expect(push.isAvailable()).toBe(true);
await expect(push.sendTest(user.id)).resolves.toEqual({ success: true });
const sent = open(safeFetchFollow.mock.calls[0][1].body, device);
expect(sent).toMatchObject({ title: 'Test Notification', url: '/settings?tab=notifications' });
// Only chat collapses; a second test is a second notification.
expect(sent).not.toHaveProperty('tag');
safeFetchFollow.mockResolvedValueOnce(reply(500));
await expect(push.sendTest(user.id)).resolves.toEqual({
success: false,
error: 'Failed to send push notification',
});
});
});
describe('buildPushPayload', () => {
const size = (p: unknown) => Buffer.byteLength(JSON.stringify(p), 'utf8');
it('WPUSH-PAY-001: passes a short message through; chat collapses per trip', () => {
expect(buildPushPayload(MSG)).toEqual({
title: MSG.title,
body: MSG.body,
url: '/trips/12',
tag: 'collab_message:/trips/12',
});
// Without a trip to collapse on there is no tag at all, never one for every chat everywhere.
expect(buildPushPayload({ ...MSG, navigateTarget: undefined })).toEqual({
title: MSG.title,
body: MSG.body,
});
});
it('WPUSH-PAY-001b: every other event has no tag, so two of them never replace each other', () => {
const others = ALL_EVENT_TYPES.filter((event) => event !== 'collab_message');
expect(others.length).toBeGreaterThan(5);
for (const event of others) {
const payload = buildPushPayload({ ...MSG, event });
expect(payload, event).toEqual({ title: MSG.title, body: MSG.body, url: '/trips/12' });
expect(payload, event).not.toHaveProperty('tag');
}
});
it('WPUSH-PAY-002: cuts a long body at a character boundary until the payload fits', () => {
const payload = buildPushPayload({ ...MSG, body: '🚄'.repeat(5000) });
expect(size(payload)).toBeLessThanOrEqual(MAX_PUSH_PAYLOAD_BYTES);
expect(size(payload)).toBeGreaterThan(MAX_PUSH_PAYLOAD_BYTES - 8);
expect(payload.body.endsWith('…')).toBe(true);
expect(payload.body.slice(0, -1)).toMatch(/^(🚄)+$/u);
});
it('WPUSH-PAY-003: characters JSON has to escape are counted as what they cost', () => {
const payload = buildPushPayload({ ...MSG, title: '\u0001'.repeat(500), body: '"\u0002'.repeat(3000) });
expect(size(payload)).toBeLessThanOrEqual(MAX_PUSH_PAYLOAD_BYTES);
expect(Array.from(payload.title)).toHaveLength(120);
expect(payload.body.length).toBeGreaterThan(0);
});
it('WPUSH-PAY-004: only same-origin paths reach the worker', () => {
expect(samePagePath('/trips/5')).toBe('/trips/5');
expect(samePagePath('/admin?tab=storage')).toBe('/admin?tab=storage');
for (const target of [
'https://evil.test/x',
'//evil.test/x',
'/\\evil.test',
'trips/5',
'/trips/5 x',
`/${'a'.repeat(300)}`,
'',
undefined,
]) {
expect(samePagePath(target), String(target)).toBeUndefined();
}
expect(buildPushPayload({ ...MSG, navigateTarget: 'https://evil.test/' })).not.toHaveProperty('url');
});
});