// 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 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()) }; } 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, 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'; } }