/** * Web push for pie nights. Adapted from @kody/kody-factory (src/push/send.ts). * * The VAPID JWT is signed by Kody with the `webPush` signing credential * (ES256), so the private key never enters this code. Payloads are encrypted * per RFC 8291 in ./push-crypto.ts. Only known push service hosts are * contacted, and a 404 or 410 from the push service drops that device. */ import { credential } from 'kody:runtime' import { encryptPushPayload } from './push-crypto.ts' import { getPushPublicKey, listPushSubs, removePushSub, type PushSub } from './store.ts' export const PUSH_HOSTS = ['fcm.googleapis.com', 'updates.push.services.mozilla.com', 'web.push.apple.com'] as const /** Hosts for the signing credential (one wildcard level for Windows/Edge). */ export const PUSH_CREDENTIAL_HOSTS = [...PUSH_HOSTS, '*.notify.windows.com'] export function isAllowedEndpoint(endpoint: string): boolean { try { const u = new URL(endpoint) if (u.protocol !== 'https:' || u.username || u.password || u.port) return false return (PUSH_HOSTS as readonly string[]).includes(u.hostname) || /^[a-z0-9-]+\.notify\.windows\.com$/.test(u.hostname) } catch { return false } } const B64URL = /^[A-Za-z0-9_-]+$/ /** Validate a browser PushSubscription JSON. */ export function parseSubscription(body: unknown): { ok: true; endpoint: string; p256dh: string; auth: string } | { ok: false; error: string } { const raw = (body && typeof body === 'object' ? body : {}) as { endpoint?: unknown; keys?: { p256dh?: unknown; auth?: unknown } } const endpoint = String(raw.endpoint ?? '') const p256dh = String(raw.keys?.p256dh ?? '') const auth = String(raw.keys?.auth ?? '') if (endpoint.length > 1000 || !isAllowedEndpoint(endpoint)) return { ok: false, error: 'This browser’s push service is not supported.' } if (!B64URL.test(p256dh) || p256dh.length < 80 || p256dh.length > 100) return { ok: false, error: 'That push subscription looks broken. Try again?' } if (!B64URL.test(auth) || auth.length < 16 || auth.length > 32) return { ok: false, error: 'That push subscription looks broken. Try again?' } return { ok: true, endpoint, p256dh, auth } } export type PushMessage = { title: string; body: string; path: string; tag?: string } type SignClient = { sign: (input: Record) => Promise } type Deps = { sign: (host: string, claims: Record) => Promise; fetch: typeof fetch } const realDeps: Deps = { async sign(host, claims) { const c = (await credential('webPush')) as unknown as SignClient return c.sign({ type: 'jwt', algorithm: 'ES256', host, header: { typ: 'JWT' }, claims }) }, fetch: (input, init) => fetch(input, init), } let deps: Deps = realDeps export function setPushDepsForTests(next: Partial | null) { deps = next ? { ...realDeps, ...next } : realDeps } function clip(text: string, max: number) { const t = text.replace(/\s+/g, ' ').trim() return t.length > max ? `${t.slice(0, max - 1)}…` : t } export function pushPayload(msg: PushMessage): string { const path = msg.path.startsWith('/') && !msg.path.startsWith('//') ? msg.path.slice(0, 300) : '/' return JSON.stringify({ title: clip(msg.title, 120) || 'Pie Night', body: clip(msg.body, 300), path, ...(msg.tag ? { tag: msg.tag.slice(0, 64) } : {}) }) } async function sendOne(sub: PushSub, payload: Uint8Array, publicKey: string, subject: string, jwts: Map) { if (!isAllowedEndpoint(sub.endpoint)) return { ok: false, gone: true } const url = new URL(sub.endpoint) let jwt = jwts.get(url.origin) if (!jwt) { jwt = await deps.sign(url.hostname, { aud: url.origin, exp: Math.floor(Date.now() / 1000) + 12 * 3600, sub: subject }) jwts.set(url.origin, jwt) } const body = await encryptPushPayload({ p256dh: sub.p256dh, auth: sub.auth }, payload) const res = await deps.fetch(sub.endpoint, { method: 'POST', headers: { TTL: '43200', Urgency: 'normal', 'Content-Encoding': 'aes128gcm', 'Content-Type': 'application/octet-stream', Authorization: `vapid t=${jwt}, k=${publicKey}`, // The body is ciphertext: never let the gateway scan it for secret placeholders. 'x-kody-secret-resolution': 'headers-only', }, body, }) if (res.status === 404 || res.status === 410) return { ok: false, gone: true } return { ok: res.status >= 200 && res.status < 300, gone: false, status: res.status } } export type PushResult = { sent: number; failed: number; removed: number; skipped?: string } /** * Notify every device following one event (or only its hosts). Skips the * device that made the change. Never throws, so a push problem never fails a * pie write. */ export async function notifyEvent(slug: string, msg: PushMessage, opts: { subject: string; hostsOnly?: boolean; exceptEndpoint?: string; onlyEndpoint?: string } = { subject: '' }): Promise { const result: PushResult = { sent: 0, failed: 0, removed: 0 } try { const publicKey = await getPushPublicKey() if (!publicKey) return { ...result, skipped: 'push is not set up' } const subs = (await listPushSubs(slug, { hostsOnly: opts.hostsOnly })).filter((s) => s.endpoint !== opts.exceptEndpoint && (!opts.onlyEndpoint || s.endpoint === opts.onlyEndpoint)) if (!subs.length) return { ...result, skipped: 'nobody is following' } const payload = new TextEncoder().encode(pushPayload(msg)) const jwts = new Map() for (let i = 0; i < subs.length; i += 6) { const batch = subs.slice(i, i + 6) const outcomes = await Promise.allSettled(batch.map((s) => sendOne(s, payload, publicKey, opts.subject, jwts))) for (let k = 0; k < outcomes.length; k++) { const o = outcomes[k]! if (o.status === 'fulfilled' && o.value.ok) result.sent++ else if (o.status === 'fulfilled' && o.value.gone) { result.removed++ await removePushSub(slug, batch[k]!.endpoint) } else result.failed++ } } } catch (error) { console.warn('pie-night push failed', error instanceof Error ? error.message.slice(0, 200) : error) } return result }