|
| 1 | +/// <reference types="@sveltejs/kit" /> |
| 2 | +/// <reference lib="webworker" /> |
| 3 | + |
| 4 | +// The push service worker. The browser decrypts II's sealed ping before `push` |
| 5 | +// fires, so the payload is just the routing origin (`{"o":"<origin>"}`). The |
| 6 | +// worker pulls the real content from the dApp as the user's per-app identity |
| 7 | +// and renders it; anything missing — no credential, an expired one, an |
| 8 | +// unreachable canister — falls back to a generic notification. It has no |
| 9 | +// `fetch` handler, so it never intercepts requests on the auth origin. |
| 10 | + |
| 11 | +import { Actor, HttpAgent, type Identity } from "@icp-sdk/core/agent"; |
| 12 | +import { IDL } from "@icp-sdk/core/candid"; |
| 13 | +import { Principal } from "@icp-sdk/core/principal"; |
| 14 | +import { |
| 15 | + cacheCanister, |
| 16 | + loadCachedCanister, |
| 17 | + loadNotificationCredential, |
| 18 | + notificationIdentity, |
| 19 | +} from "$lib/utils/notifications/pullCredential"; |
| 20 | + |
| 21 | +const sw = self as unknown as ServiceWorkerGlobalScope; |
| 22 | + |
| 23 | +// Re-resolve origin -> canister at most this often; a stale entry refreshes |
| 24 | +// lazily on the next push (or immediately on a pull failure). |
| 25 | +const CANISTER_TTL_MS = 24 * 60 * 60 * 1000; |
| 26 | +// Bound resolve + pull so a slow dApp can't blow the push handler's budget; on |
| 27 | +// timeout the generic notification still shows. |
| 28 | +const PULL_TIMEOUT_MS = 8_000; |
| 29 | + |
| 30 | +// Provisional pull interface: the dApp returns the pending notifications for |
| 31 | +// the authenticated caller. Finalized alongside the client crate. |
| 32 | +interface PulledNotification { |
| 33 | + title: string; |
| 34 | + body: [] | [string]; |
| 35 | +} |
| 36 | +interface PullService { |
| 37 | + ii_pending_notifications: () => Promise<PulledNotification[]>; |
| 38 | +} |
| 39 | +const pullIdl: IDL.InterfaceFactory = ({ IDL }) => |
| 40 | + IDL.Service({ |
| 41 | + ii_pending_notifications: IDL.Func( |
| 42 | + [], |
| 43 | + [IDL.Vec(IDL.Record({ title: IDL.Text, body: IDL.Opt(IDL.Text) }))], |
| 44 | + ["query"], |
| 45 | + ), |
| 46 | + }); |
| 47 | + |
| 48 | +sw.addEventListener("install", () => sw.skipWaiting()); |
| 49 | +sw.addEventListener("activate", (event) => event.waitUntil(sw.clients.claim())); |
| 50 | + |
| 51 | +sw.addEventListener("push", (event) => { |
| 52 | + event.waitUntil(handlePush(event.data?.json())); |
| 53 | +}); |
| 54 | + |
| 55 | +sw.addEventListener("notificationclick", (event) => { |
| 56 | + const origin = (event.notification.data as { origin?: string } | null) |
| 57 | + ?.origin; |
| 58 | + event.notification.close(); |
| 59 | + event.waitUntil(openApp(origin)); |
| 60 | +}); |
| 61 | + |
| 62 | +const handlePush = async (payload: unknown): Promise<void> => { |
| 63 | + const origin = originOf(payload); |
| 64 | + const pulled = |
| 65 | + origin === undefined |
| 66 | + ? [] |
| 67 | + : await withTimeout(pull(origin), PULL_TIMEOUT_MS, []); |
| 68 | + |
| 69 | + if (pulled.length === 0) { |
| 70 | + await sw.registration.showNotification(appName(origin), { |
| 71 | + body: "You have a new notification.", |
| 72 | + icon: "/favicon.svg", |
| 73 | + tag: "ii-notification", |
| 74 | + data: { origin }, |
| 75 | + }); |
| 76 | + return; |
| 77 | + } |
| 78 | + await Promise.all( |
| 79 | + pulled.map((notification) => |
| 80 | + sw.registration.showNotification(notification.title, { |
| 81 | + body: notification.body[0], |
| 82 | + icon: "/favicon.svg", |
| 83 | + data: { origin }, |
| 84 | + }), |
| 85 | + ), |
| 86 | + ); |
| 87 | +}; |
| 88 | + |
| 89 | +const originOf = (payload: unknown): string | undefined => { |
| 90 | + if (payload !== null && typeof payload === "object" && "o" in payload) { |
| 91 | + const origin = (payload as { o: unknown }).o; |
| 92 | + return typeof origin === "string" ? origin : undefined; |
| 93 | + } |
| 94 | + return undefined; |
| 95 | +}; |
| 96 | + |
| 97 | +const appName = (origin: string | undefined): string => { |
| 98 | + if (origin === undefined) return "Internet Identity"; |
| 99 | + try { |
| 100 | + return new URL(origin).host; |
| 101 | + } catch { |
| 102 | + return "Internet Identity"; |
| 103 | + } |
| 104 | +}; |
| 105 | + |
| 106 | +const pull = async (origin: string): Promise<PulledNotification[]> => { |
| 107 | + const record = await loadNotificationCredential(origin); |
| 108 | + if (record === undefined || record.expiresAtMillis <= Date.now()) { |
| 109 | + return []; |
| 110 | + } |
| 111 | + const identity = await notificationIdentity(record); |
| 112 | + const canisterId = await resolveCanister(origin, false); |
| 113 | + if (canisterId === undefined) { |
| 114 | + return []; |
| 115 | + } |
| 116 | + try { |
| 117 | + return await pullFrom(canisterId, identity, record.host); |
| 118 | + } catch { |
| 119 | + // The cached canister may be stale (the dApp changed its id). Re-resolve |
| 120 | + // from the well-known and retry once, but only if it actually moved. |
| 121 | + const fresh = await resolveCanister(origin, true); |
| 122 | + if (fresh === undefined || fresh.toText() === canisterId.toText()) { |
| 123 | + return []; |
| 124 | + } |
| 125 | + return pullFrom(fresh, identity, record.host).catch(() => []); |
| 126 | + } |
| 127 | +}; |
| 128 | + |
| 129 | +const pullFrom = async ( |
| 130 | + canisterId: Principal, |
| 131 | + identity: Identity, |
| 132 | + host: string, |
| 133 | +): Promise<PulledNotification[]> => { |
| 134 | + const agent = await HttpAgent.create({ |
| 135 | + identity, |
| 136 | + host, |
| 137 | + shouldFetchRootKey: isLocalHost(host), |
| 138 | + }); |
| 139 | + const actor = Actor.createActor<PullService>(pullIdl, { agent, canisterId }); |
| 140 | + return actor.ii_pending_notifications(); |
| 141 | +}; |
| 142 | + |
| 143 | +// The canister comes from the consented origin's own well-known, never from the |
| 144 | +// ping (a forged ping can only name an origin II already sealed for). It's cached |
| 145 | +// and reused within a TTL; a stale entry is re-resolved here or on a pull failure. |
| 146 | +const resolveCanister = async ( |
| 147 | + origin: string, |
| 148 | + forceRefresh: boolean, |
| 149 | +): Promise<Principal | undefined> => { |
| 150 | + if (!forceRefresh) { |
| 151 | + const cached = await loadCachedCanister(origin); |
| 152 | + if ( |
| 153 | + cached !== undefined && |
| 154 | + cached.resolvedAtMillis + CANISTER_TTL_MS > Date.now() |
| 155 | + ) { |
| 156 | + return principalOf(cached.canisterId); |
| 157 | + } |
| 158 | + } |
| 159 | + const fetched = await fetchSenderCanister(origin); |
| 160 | + if (fetched !== undefined) { |
| 161 | + await cacheCanister(origin, fetched.toText()); |
| 162 | + } |
| 163 | + return fetched; |
| 164 | +}; |
| 165 | + |
| 166 | +const fetchSenderCanister = async ( |
| 167 | + origin: string, |
| 168 | +): Promise<Principal | undefined> => { |
| 169 | + try { |
| 170 | + const response = await fetch( |
| 171 | + `${origin}/.well-known/ii-notification-senders`, |
| 172 | + ); |
| 173 | + if (!response.ok) return undefined; |
| 174 | + const doc: unknown = await response.json(); |
| 175 | + const senders = |
| 176 | + doc !== null && typeof doc === "object" && "senders" in doc |
| 177 | + ? (doc as { senders: unknown }).senders |
| 178 | + : undefined; |
| 179 | + const first = Array.isArray(senders) ? senders[0] : undefined; |
| 180 | + return typeof first === "string" ? principalOf(first) : undefined; |
| 181 | + } catch { |
| 182 | + return undefined; |
| 183 | + } |
| 184 | +}; |
| 185 | + |
| 186 | +const principalOf = (text: string): Principal | undefined => { |
| 187 | + try { |
| 188 | + return Principal.fromText(text); |
| 189 | + } catch { |
| 190 | + return undefined; |
| 191 | + } |
| 192 | +}; |
| 193 | + |
| 194 | +// Resolves to `fallback` if `promise` rejects or outlives `ms` — a slow or |
| 195 | +// failing pull must never leave the push handler without a notification. |
| 196 | +const withTimeout = <T>( |
| 197 | + promise: Promise<T>, |
| 198 | + ms: number, |
| 199 | + fallback: T, |
| 200 | +): Promise<T> => |
| 201 | + Promise.race([ |
| 202 | + promise.catch(() => fallback), |
| 203 | + new Promise<T>((resolve) => setTimeout(() => resolve(fallback), ms)), |
| 204 | + ]); |
| 205 | + |
| 206 | +const isLocalHost = (host: string): boolean => |
| 207 | + host.includes("localhost") || host.includes("127.0.0.1"); |
| 208 | + |
| 209 | +const openApp = async (origin: string | undefined): Promise<void> => { |
| 210 | + const url = origin ?? "/"; |
| 211 | + const windows = await sw.clients.matchAll({ type: "window" }); |
| 212 | + const existing = windows.find((client) => client.url.startsWith(url)); |
| 213 | + if (existing !== undefined) { |
| 214 | + await existing.focus(); |
| 215 | + return; |
| 216 | + } |
| 217 | + await sw.clients.openWindow(url); |
| 218 | +}; |
0 commit comments