/** * Send web push messages to stored subscriptions. * * The VAPID JWT is signed by Kody with the `webPush` signing credential * (ES256). The private key never enters this code. Payloads are encrypted per * RFC 8291 in `./crypto.ts`. Only known push service hosts are contacted. * A 404 or 410 from the push service removes that subscription. */ import { credential } from 'kody:runtime' import { loadSettings } from '../lib/settings.ts' import { encryptPushPayload } from './crypto.ts' import { appendPushLog, applyResults, isAllowedEndpoint, listAllSubs, listUserSubs, type PushSubscriptionRecord } from './store.ts' export type PushMessage = { title: string body: string /** Path inside the factory app, for example `/cards/wi_123`. */ path: string tag?: string cardId?: string kind: string } export type PushSendResult = { ok: boolean sent: number failed: number removed: number skipped?: string errors: 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 } /** JSON the service worker reads. Kept small; push services cap payloads near 4 KB. */ 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) || 'Kody Factory', body: clip(msg.body, 400), path, ...(msg.tag ? { tag: msg.tag.slice(0, 64) } : {}), ...(msg.cardId ? { cardId: msg.cardId.slice(0, 64) } : {}), }) } async function sendOne(sub: PushSubscriptionRecord, payload: Uint8Array, publicKey: string, subject: string, jwtCache: Map) { if (!isAllowedEndpoint(sub.endpoint)) return { ok: false, gone: true, error: 'endpoint not allowed' } const url = new URL(sub.endpoint) const aud = url.origin let jwt = jwtCache.get(aud) if (!jwt) { jwt = await deps.sign(url.hostname, { aud, exp: Math.floor(Date.now() / 1000) + 12 * 3600, sub: subject }) jwtCache.set(aud, jwt) } const body = await encryptPushPayload({ p256dh: sub.p256dh, auth: sub.auth }, payload) const res = await deps.fetch(sub.endpoint, { method: 'POST', headers: { TTL: '86400', Urgency: 'high', '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, error: `HTTP ${res.status}` } if (res.status >= 200 && res.status < 300) return { ok: true, gone: false } const text = (await res.text().catch(() => '')).slice(0, 120) return { ok: false, gone: false, error: `HTTP ${res.status}${text ? ` ${text}` : ''}` } } /** * Send one message. `userId` limits it to that user's devices (the test * button); otherwise every subscribed device gets it. Never throws. */ export async function sendPush(msg: PushMessage, opts: { userId?: string; dryRun?: boolean } = {}): Promise { const result: PushSendResult = { ok: true, sent: 0, failed: 0, removed: 0, errors: [] } try { const settings = await loadSettings() if (!settings.webPushVapidPublicKey) return { ...result, ok: false, skipped: 'web push is not configured (webPushVapidPublicKey is empty)' } const subs = opts.userId ? (await listUserSubs(opts.userId)).map((s) => ({ ...s, userId: opts.userId! })) : await listAllSubs() if (!subs.length) return { ...result, skipped: 'no subscribed devices' } if (opts.dryRun) return { ...result, skipped: `dry run: would send to ${subs.length} device(s)` } const payload = new TextEncoder().encode(pushPayload(msg)) const jwtCache = new Map() const outcomes: Array<{ userId: string; id: string; ok: boolean; gone: boolean; error?: string }> = [] for (const sub of subs) { try { const r = await sendOne(sub, payload, settings.webPushVapidPublicKey, settings.webPushSubject, jwtCache) outcomes.push({ userId: sub.userId, id: sub.id, ...r }) } catch (error) { outcomes.push({ userId: sub.userId, id: sub.id, ok: false, gone: false, error: error instanceof Error ? error.message.slice(0, 200) : 'send failed' }) } } for (const o of outcomes) { if (o.ok) result.sent++ else if (o.gone) result.removed++ else { result.failed++ if (o.error) result.errors.push(o.error) } } result.ok = result.failed === 0 await applyResults(outcomes) await appendPushLog({ at: new Date().toISOString(), kind: msg.kind, title: clip(msg.title, 120), ...(msg.cardId ? { cardId: msg.cardId } : {}), sent: result.sent, failed: result.failed, removed: result.removed, ...(result.errors[0] ? { detail: result.errors[0] } : {}) }) return result } catch (error) { const detail = error instanceof Error ? error.message.slice(0, 200) : 'push failed' console.warn(`factory web push failed: ${detail}`) return { ...result, ok: false, errors: [detail] } } }