/** * Apple VoIP push, sent by the Worker straight to APNs (Cotton Calling, * 12 Nov 2026): a sleeping phone rings because PushKit wakes it. * * Token-based: one ES256 JWT `{alg, kid}{iss, iat}` signed with the owner's * .p8 key (APNS_KEY, a Worker secret the coordinator sets; never in code or a * test), reused for 40 minutes — Apple refuses a token older than an hour and * one renewed more often than every twenty minutes. * * The payload never names the caller: `{ room, video }` to ring, `{ room, * stop }` to stop. The phone asks its own object who is calling, so Apple * learns which device was woken and when, never by whom. */import { isProduction, typeEnv } from"../env.ts";import { refuse } from"../http.ts";importtype { PushDevice, PushOutcome, PushPayload } from"./push.ts";exportconst APNS_PRODUCTION = "https://api.push.apple.com";exportconst APNS_SANDBOX = "https://api.sandbox.push.apple.com";/** A token is renewed after 40 minutes: inside Apple's hour, outside its twenty-minute floor. */exportconst TOKEN_LIFE_MS = 40 * 60 * 1000;/** The host a device's push goes to; APNS_URL (a test Worker's fake APNs) stands for both, refused in production. */exportfunction apnsHost(env: Pick<Env, "APNS_URL" | "ENV_LABEL">, sandbox: boolean): string {const fake = env.APNS_URL?.replace(/\/+$/, "");if (fake) {if (isProduction(env asEnv)) refuse(503, "apns_misconfigured", "APNS_URL is for a test Worker's fake APNs, never production");return fake; }return sandbox ? APNS_SANDBOX : APNS_PRODUCTION;}/** Whether this Worker can push at all: the key, its id and the team. */exportfunction canPush(env: Env): boolean {returnBoolean(env.APNS_KEY && env.APNS_KEY_ID && env.APNS_TEAM_ID);}const tokens = newMap<string, { jwt: string; at: number }>();function b64url(bytes: Uint8Array | string): string {const raw = typeof bytes === "string" ? bytes : String.fromCharCode(...bytes);return btoa(raw).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}/** The .p8 file Apple hands out is a PKCS#8 PEM of a P-256 key. */exportasyncfunction importP8(pem: string): Promise<CryptoKey> {const body = pem.replace(/-----(BEGIN|END) PRIVATE KEY-----/g, "").replace(/\s+/g, "");const der = Uint8Array.from(atob(body), (c) => c.charCodeAt(0));return crypto.subtle.importKey("pkcs8", der, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);}/** The provider token, made once and reused for TOKEN_LIFE_MS. */exportasyncfunction providerToken(env: Env, now: number = Date.now()): Promise<string> {const cacheKey = `${env.APNS_TEAM_ID}.${env.APNS_KEY_ID}`;const held = tokens.get(cacheKey);if (held && now - held.at < TOKEN_LIFE_MS) return held.jwt;const key = await importP8(env.APNS_KEY ?? "");const head = b64url(JSON.stringify({ alg: "ES256", kid: env.APNS_KEY_ID }));const claims = b64url(JSON.stringify({ iss: env.APNS_TEAM_ID, iat: Math.floor(now / 1000) }));// WebCrypto's ECDSA signature is r‖s, which is what JWS ES256 wants.const signature = newUint8Array(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, newTextEncoder().encode(`${head}.${claims}`)));const jwt = `${head}.${claims}.${b64url(signature)}`; tokens.set(cacheKey, { jwt, at: now });return jwt;}/** Forget the held provider token (a test's clock moves; Apple said ExpiredProviderToken). */exportfunction forgetProviderToken(): void { tokens.clear();}/** One VoIP push to one device. Nothing of the token or the payload is logged. */exportasyncfunction pushVoip(env: Env, device: PushDevice, payload: PushPayload): Promise<PushOutcome> {if (!canPush(env)) return"failed";const jwt = await providerToken(env);let res: Response;try { res = await fetch(`${apnsHost(env, device.sandbox)}/3/device/${encodeURIComponent(device.token)}`, { method: "POST", headers: { authorization: `bearer ${jwt}`,"apns-topic": `${device.topic}.voip`,"apns-push-type": "voip","apns-priority": "10","apns-expiration": "0","content-type": "application/json", }, body: JSON.stringify(payload), }); } catch {return"failed"; }if (res.ok) return"sent";if (res.status === 410) return"gone";const reason = await res.json().then((b) => (b as { reason?: string }).reason, () => undefined);if (reason === "ExpiredProviderToken") forgetProviderToken();return reason === "BadDeviceToken" || reason === "Unregistered" ? "gone" : "failed";}