/** * Web push subscriptions, stored per Kody user (the app visitor's verified * `user_id`). One entry per device. Endpoints and keys are not secrets, but * they are only shown back to their own user, and never in full. */ import { loadJson, saveJson } from '../lib/storage.ts' export const PUSH_SUBS_KEY = 'factory:push-subs:v1' export const PUSH_LOG_KEY = 'factory:push-log:v1' const MAX_PER_USER = 10 const LOG_LIMIT = 50 export type PushSubscriptionRecord = { id: string endpoint: string p256dh: string auth: string label: string createdAt: string lastOkAt?: string lastError?: string } export type PushUser = { username: string; subs: PushSubscriptionRecord[] } type PushSubsDoc = { users: Record } export type PushLogEntry = { at: string kind: string title: string cardId?: string sent: number failed: number removed: number detail?: string } /** Push service hosts the factory will post to. Anything else is refused. */ export const PUSH_HOSTS = ['fcm.googleapis.com', 'updates.push.services.mozilla.com', 'web.push.apple.com'] as const 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. Returns the parts or why not. */ export function parseSubscription(raw: unknown): { ok: true; endpoint: string; p256dh: string; auth: string } | { ok: false; error: string } { const r = (raw && typeof raw === 'object' ? raw : {}) as { endpoint?: unknown; keys?: { p256dh?: unknown; auth?: unknown } } const endpoint = typeof r.endpoint === 'string' ? r.endpoint.trim() : '' const p256dh = typeof r.keys?.p256dh === 'string' ? r.keys.p256dh : '' const auth = typeof r.keys?.auth === 'string' ? r.keys.auth : '' if (!endpoint || endpoint.length > 1000) return { ok: false, error: 'subscription endpoint is missing or too long' } if (!isAllowedEndpoint(endpoint)) return { ok: false, error: 'subscription endpoint is not a known push service' } if (!B64URL.test(p256dh) || p256dh.length < 80 || p256dh.length > 100) return { ok: false, error: 'subscription p256dh key is invalid' } if (!B64URL.test(auth) || auth.length < 16 || auth.length > 32) return { ok: false, error: 'subscription auth secret is invalid' } return { ok: true, endpoint, p256dh, auth } } async function loadDoc(): Promise { const doc = await loadJson(PUSH_SUBS_KEY, { users: {} }) return doc && typeof doc.users === 'object' && doc.users ? doc : { users: {} } } export async function listUserSubs(userId: string): Promise { return (await loadDoc()).users[userId]?.subs ?? [] } /** Every subscription, with its user id. */ export async function listAllSubs(): Promise> { const doc = await loadDoc() return Object.entries(doc.users).flatMap(([userId, u]) => u.subs.map((s) => ({ ...s, userId }))) } export async function upsertSub(userId: string, username: string, sub: { endpoint: string; p256dh: string; auth: string }, label: string, now = new Date().toISOString()) { const doc = await loadDoc() const user = doc.users[userId] ?? { username, subs: [] } user.username = username const existing = user.subs.find((s) => s.endpoint === sub.endpoint) if (existing) { existing.p256dh = sub.p256dh existing.auth = sub.auth existing.label = label delete existing.lastError } else { user.subs.unshift({ id: `push_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`, ...sub, label, createdAt: now }) user.subs = user.subs.slice(0, MAX_PER_USER) } doc.users[userId] = user await saveJson(PUSH_SUBS_KEY, doc) return user.subs.find((s) => s.endpoint === sub.endpoint)! } export async function removeSub(userId: string, match: { endpoint?: string; id?: string }): Promise { const doc = await loadDoc() const user = doc.users[userId] if (!user) return false const before = user.subs.length user.subs = user.subs.filter((s) => s.endpoint !== match.endpoint && s.id !== match.id) if (user.subs.length === before) return false await saveJson(PUSH_SUBS_KEY, doc) return true } /** Record delivery results: drop gone subscriptions, stamp ok and error. */ export async function applyResults(results: Array<{ userId: string; id: string; ok: boolean; gone: boolean; error?: string }>, now = new Date().toISOString()) { if (!results.length) return const doc = await loadDoc() for (const r of results) { const user = doc.users[r.userId] if (!user) continue if (r.gone) { user.subs = user.subs.filter((s) => s.id !== r.id) continue } const s = user.subs.find((x) => x.id === r.id) if (!s) continue if (r.ok) { s.lastOkAt = now delete s.lastError } else s.lastError = (r.error ?? 'failed').slice(0, 200) } await saveJson(PUSH_SUBS_KEY, doc) } export async function appendPushLog(entry: PushLogEntry) { const log = await loadJson<{ entries: PushLogEntry[] }>(PUSH_LOG_KEY, { entries: [] }) const entries = Array.isArray(log.entries) ? log.entries : [] entries.unshift(entry) await saveJson(PUSH_LOG_KEY, { entries: entries.slice(0, LOG_LIMIT) }) } export async function listPushLog(limit = 20): Promise { const log = await loadJson<{ entries: PushLogEntry[] }>(PUSH_LOG_KEY, { entries: [] }) return (Array.isArray(log.entries) ? log.entries : []).slice(0, limit) } /** Short, non-identifying label for an endpoint (host only). */ export function endpointHost(endpoint: string): string { try { return new URL(endpoint).hostname } catch { return 'unknown' } }