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
+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');
});
});