// Empty Web Push messages need VAPID authentication but no payload encryption. // The worker shows a generic alert; private event/payment details stay in the inbox. export function validPushEndpoint(value: string): boolean { try { const url = new URL(value); return value.length <= 2048 && url.protocol === "https:" && !url.username && !url.password && !url.port && !url.hash && ( url.hostname === "fcm.googleapis.com" || url.hostname === "updates.push.services.mozilla.com" || url.hostname.endsWith(".notify.windows.com") || url.hostname === "web.push.apple.com" ); } catch { return false; } } function base64url(bytes: Uint8Array): string { return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } export async function sendPush(endpoint: string, env: Record): Promise<"sent" | "expired" | "failed"> { if (!validPushEndpoint(endpoint)) return "expired"; try { const key = await crypto.subtle.importKey("jwk", JSON.parse(env.PUSH_VAPID_PRIVATE_JWK!), { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]); const encode = (value: unknown) => base64url(new TextEncoder().encode(JSON.stringify(value))); const unsigned = `${encode({ typ: "JWT", alg: "ES256" })}.${encode({ aud: new URL(endpoint).origin, exp: Math.floor(Date.now() / 1000) + 3600, sub: env.PUSH_VAPID_SUBJECT, })}`; const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, new TextEncoder().encode(unsigned)); const response = await fetch(endpoint, { method: "POST", headers: { Authorization: `vapid t=${unsigned}.${base64url(new Uint8Array(signature))}, k=${env.PUSH_VAPID_PUBLIC_KEY}`, TTL: "86400", Urgency: "normal", }, redirect: "error", signal: AbortSignal.timeout(2000), }); if (response.status === 404 || response.status === 410) return "expired"; return response.ok ? "sent" : "failed"; } catch { return "failed"; } } export const serviceWorkerSource = ` self.addEventListener('install', () => self.skipWaiting()); self.addEventListener('activate', event => event.waitUntil(self.clients.claim())); self.addEventListener('push', event => { event.waitUntil(self.registration.showNotification('Lunchtime update', { body: 'Open Lunchtime to see the latest event update.', data: { url: '/#notifications' } })); }); self.addEventListener('notificationclick', event => { event.notification.close(); event.waitUntil((async () => { const url = new URL('/#notifications', self.location.origin).href; const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }); const existing = windows.find(client => new URL(client.url).origin === self.location.origin); if (existing) { await existing.navigate(url); await existing.focus(); } else { await self.clients.openWindow(url); } })()); }); `;