- compose.yaml runs only the app by default; Caddy moved to the
'standalone' profile (the panel brings its own Caddy and routes).
- No env_file: every setting is ${VAR:-default} in compose.yaml, so it
can be set from the panel's Environment tab (or .env standalone).
- VAPID keys are generated on first start and kept in the data volume;
the push subject defaults to https://<site domain>. gen-vapid.ts removed.
- PUSH_DISABLED=1 turns push off.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
124 lines
5.2 KiB
TypeScript
124 lines
5.2 KiB
TypeScript
// Web Push sender: VAPID (RFC 8292) + aes128gcm payload encryption
|
|
// (RFC 8291), using only node:crypto. The payload is just { g: groupId };
|
|
// the service worker fetches and decrypts the actual events itself, so the
|
|
// push service never sees content (SPEC.md §7.7).
|
|
import { createCipheriv, createECDH, createPrivateKey, hkdfSync, randomBytes, sign } from 'node:crypto';
|
|
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
import { join } from 'node:path';
|
|
import type { PushSub } from './db.ts';
|
|
|
|
const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString('base64url');
|
|
const fromB64u = (s: string) => Buffer.from(s, 'base64url');
|
|
|
|
/** Push services we deliver to. Anything else is refused, so a registered
|
|
* "endpoint" can't make the server send requests to arbitrary hosts. */
|
|
const ALLOWED_PUSH_HOSTS = [
|
|
'fcm.googleapis.com',
|
|
'updates.push.services.mozilla.com',
|
|
'push.services.mozilla.com',
|
|
'web.push.apple.com',
|
|
'notify.windows.com',
|
|
];
|
|
|
|
export function isAllowedEndpoint(endpoint: string): boolean {
|
|
let u: URL;
|
|
try {
|
|
u = new URL(endpoint);
|
|
} catch {
|
|
return false;
|
|
}
|
|
if (u.protocol !== 'https:' || u.port !== '') return false;
|
|
return ALLOWED_PUSH_HOSTS.some((h) => u.hostname === h || u.hostname.endsWith(`.${h}`));
|
|
}
|
|
|
|
export function generateVapidKeys(): { publicKey: string; privateKey: string } {
|
|
const ecdh = createECDH('prime256v1');
|
|
ecdh.generateKeys();
|
|
return { publicKey: b64u(ecdh.getPublicKey()), privateKey: b64u(ecdh.getPrivateKey()) };
|
|
}
|
|
|
|
/**
|
|
* VAPID keys from the environment if both are set, otherwise generated once
|
|
* and kept in the data directory, so push works without any configuration.
|
|
* Deleting vapid.json rotates them (and invalidates every subscription).
|
|
*/
|
|
export function loadVapidKeys(dataDir: string, envPublic: string, envPrivate: string): { publicKey: string; privateKey: string; source: string } {
|
|
if (envPublic && envPrivate) return { publicKey: envPublic, privateKey: envPrivate, source: 'environment' };
|
|
const file = join(dataDir, 'vapid.json');
|
|
if (existsSync(file)) {
|
|
const k = JSON.parse(readFileSync(file, 'utf8'));
|
|
if (typeof k.publicKey === 'string' && typeof k.privateKey === 'string') return { ...k, source: file };
|
|
}
|
|
const k = generateVapidKeys();
|
|
writeFileSync(file, JSON.stringify(k), { mode: 0o600, flag: 'wx' });
|
|
return { ...k, source: `${file} (new)` };
|
|
}
|
|
|
|
export interface Vapid {
|
|
publicKey: string;
|
|
privateKey: string;
|
|
subject: string;
|
|
}
|
|
|
|
function vapidAuthHeader(endpoint: string, v: Vapid): string {
|
|
const pub = fromB64u(v.publicKey);
|
|
const key = createPrivateKey({
|
|
key: { kty: 'EC', crv: 'P-256', d: v.privateKey, x: b64u(pub.subarray(1, 33)), y: b64u(pub.subarray(33, 65)) },
|
|
format: 'jwk',
|
|
});
|
|
const header = b64u(Buffer.from(JSON.stringify({ typ: 'JWT', alg: 'ES256' })));
|
|
const claims = b64u(
|
|
Buffer.from(JSON.stringify({ aud: new URL(endpoint).origin, exp: Math.floor(Date.now() / 1000) + 12 * 3600, sub: v.subject })),
|
|
);
|
|
const sig = sign('sha256', Buffer.from(`${header}.${claims}`), { key, dsaEncoding: 'ieee-p1363' });
|
|
return `vapid t=${header}.${claims}.${b64u(sig)}, k=${v.publicKey}`;
|
|
}
|
|
|
|
/** RFC 8291 aes128gcm encryption of `plaintext` for one subscription. */
|
|
export function encryptPayload(sub: Pick<PushSub, 'p256dh' | 'auth'>, plaintext: Buffer): Buffer {
|
|
const uaPublic = fromB64u(sub.p256dh);
|
|
const authSecret = fromB64u(sub.auth);
|
|
const ecdh = createECDH('prime256v1');
|
|
const asPublic = ecdh.generateKeys();
|
|
const shared = ecdh.computeSecret(uaPublic);
|
|
const keyInfo = Buffer.concat([Buffer.from('WebPush: info\0'), uaPublic, asPublic]);
|
|
const ikm = Buffer.from(hkdfSync('sha256', shared, authSecret, keyInfo, 32));
|
|
const salt = randomBytes(16);
|
|
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 cipher = createCipheriv('aes-128-gcm', cek, nonce);
|
|
// 0x02 = padding delimiter for the last (only) record.
|
|
const body = Buffer.concat([cipher.update(Buffer.concat([plaintext, Buffer.from([2])])), cipher.final(), cipher.getAuthTag()]);
|
|
const rs = Buffer.alloc(4);
|
|
rs.writeUInt32BE(4096);
|
|
return Buffer.concat([salt, rs, Buffer.from([asPublic.length]), asPublic, body]);
|
|
}
|
|
|
|
/** Send one push. Returns 'gone' if the subscription should be deleted. */
|
|
export async function sendPush(sub: PushSub, payload: object, v: Vapid): Promise<'ok' | 'gone' | 'error'> {
|
|
if (!isAllowedEndpoint(sub.endpoint)) return 'gone';
|
|
try {
|
|
const res = await fetch(sub.endpoint, {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: vapidAuthHeader(sub.endpoint, v),
|
|
'Content-Encoding': 'aes128gcm',
|
|
'Content-Type': 'application/octet-stream',
|
|
TTL: String(24 * 3600),
|
|
Urgency: 'normal',
|
|
},
|
|
body: encryptPayload(sub, Buffer.from(JSON.stringify(payload))),
|
|
redirect: 'error',
|
|
signal: AbortSignal.timeout(15_000),
|
|
});
|
|
if (res.status === 404 || res.status === 410) return 'gone';
|
|
if (!res.ok) {
|
|
console.error(`push: ${new URL(sub.endpoint).hostname} HTTP ${res.status}`);
|
|
return 'error';
|
|
}
|
|
return 'ok';
|
|
} catch (e) {
|
|
console.error(`push: ${(e as Error).message}`);
|
|
return 'error';
|
|
}
|
|
}
|