Cotton code
98 lines · 4.5 KB · TypeScriptRaw
/** * 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, type Env } from "../env.ts";import { refuse } from "../http.ts";import type { PushDevice, PushOutcome, PushPayload } from "./push.ts";export const APNS_PRODUCTION = "https://api.push.apple.com";export const APNS_SANDBOX = "https://api.sandbox.push.apple.com";/** A token is renewed after 40 minutes: inside Apple's hour, outside its twenty-minute floor. */export const 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. */export function apnsHost(env: Pick<Env, "APNS_URL" | "ENV_LABEL">, sandbox: boolean): string {  const fake = env.APNS_URL?.replace(/\/+$/, "");  if (fake) {    if (isProduction(env as Env)) 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. */export function canPush(env: Env): boolean {  return Boolean(env.APNS_KEY && env.APNS_KEY_ID && env.APNS_TEAM_ID);}const tokens = new Map<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. */export async function 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. */export async function 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 = new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, new TextEncoder().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). */export function forgetProviderToken(): void {  tokens.clear();}/** One VoIP push to one device. Nothing of the token or the payload is logged. */export async function 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";}