/** * Firebase Cloud Messaging for Cotton Calling on Android (12 Nov 2026): the * HTTP v1 API, authorised by the owner's service account (FCM_SERVICE_ACCOUNT, * its JSON key, a Worker secret the coordinator sets). An RS256 JWT of the * account is traded at Google's token endpoint for an access token, kept 50 * minutes (Google gives an hour). * * A ring is a high-priority data message `{ kind: "ring", room, video }` that * lives 45 s, the ring's own length; a stop is `{ kind: "stop", room, stop }`. * Data values are strings, and none of them is a number to call or a name. */ import { isProduction, type Env } from "../env.ts"; import { refuse } from "../http.ts"; import { frameData, type PushDevice, type PushOutcome, type PushPayload } from "./push.ts"; export const FCM_HOST = "https://fcm.googleapis.com"; export const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token"; export const FCM_SCOPE = "https://www.googleapis.com/auth/firebase.messaging"; /** An access token is used for 50 minutes of its hour. */ export const ACCESS_LIFE_MS = 50 * 60 * 1000; interface ServiceAccount { client_email: string; private_key: string; project_id?: string; } const access = new Map(); function b64url(bytes: Uint8Array | string): string { const raw = typeof bytes === "string" ? bytes : String.fromCharCode(...bytes); return btoa(raw).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } export function account(env: Env): ServiceAccount | null { if (!env.FCM_SERVICE_ACCOUNT) return null; try { const parsed = JSON.parse(env.FCM_SERVICE_ACCOUNT) as Partial; return parsed.client_email && parsed.private_key ? (parsed as ServiceAccount) : null; } catch { return null; } } /** The FCM project: FCM_PROJECT_ID, else the service account's own. */ export function project(env: Env, sa: ServiceAccount): string | null { return env.FCM_PROJECT_ID ?? sa.project_id ?? null; } /** The hosts, a test Worker's fakes standing for Google's; refused in production. */ export function fcmHosts(env: Pick): { send: string; token: string } { const send = env.FCM_URL?.replace(/\/+$/, ""); const token = env.FCM_TOKEN_URL; if ((send || token) && isProduction(env as Env)) refuse(503, "fcm_misconfigured", "FCM_URL and FCM_TOKEN_URL are for a test Worker's fake FCM, never production"); return { send: send ?? FCM_HOST, token: token ?? GOOGLE_TOKEN_URL }; } export function canPushAndroid(env: Env): boolean { const sa = account(env); return sa !== null && project(env, sa) !== null; } /** The service account's assertion: RS256 over `{ iss, scope, aud, iat, exp }`. */ export async function assertion(sa: ServiceAccount, aud: string, now: number): Promise { const body = sa.private_key.replace(/-----(BEGIN|END) PRIVATE KEY-----/g, "").replace(/\s+/g, ""); const der = Uint8Array.from(atob(body), (c) => c.charCodeAt(0)); const key = await crypto.subtle.importKey("pkcs8", der, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["sign"]); const iat = Math.floor(now / 1000); const head = b64url(JSON.stringify({ alg: "RS256", typ: "JWT" })); const claims = b64url(JSON.stringify({ iss: sa.client_email, scope: FCM_SCOPE, aud, iat, exp: iat + 3600 })); const signature = new Uint8Array(await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, new TextEncoder().encode(`${head}.${claims}`))); return `${head}.${claims}.${b64url(signature)}`; } /** The access token, traded once and reused for ACCESS_LIFE_MS. */ export async function accessToken(env: Env, now: number = Date.now()): Promise { const sa = account(env); if (!sa) return null; const held = access.get(sa.client_email); if (held && now - held.at < ACCESS_LIFE_MS) return held.token; const { token: url } = fcmHosts(env); const res = await fetch(url, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: await assertion(sa, GOOGLE_TOKEN_URL, now) }).toString(), }); if (!res.ok) return null; const answer = (await res.json()) as { access_token?: string }; if (!answer.access_token) return null; access.set(sa.client_email, { token: answer.access_token, at: now }); return answer.access_token; } export function forgetAccessToken(): void { access.clear(); } /** The message a payload is, as FCM v1 takes it. */ export function message(token: string, payload: PushPayload): Record { const data = frameData(payload); return { message: { token, data, android: { priority: "HIGH", ttl: "45s" } } }; } /** One data message to one Android phone. Nothing of the token or payload is logged. */ export async function pushFcm(env: Env, device: PushDevice, payload: PushPayload): Promise { const sa = account(env); const id = sa ? project(env, sa) : null; if (!sa || !id) return "failed"; let res: Response; try { const bearer = await accessToken(env); if (!bearer) return "failed"; res = await fetch(`${fcmHosts(env).send}/v1/projects/${encodeURIComponent(id)}/messages:send`, { method: "POST", headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json" }, body: JSON.stringify(message(device.token, payload)), }); } catch { return "failed"; } if (res.ok) return "sent"; if (res.status === 401) forgetAccessToken(); const error = await res.json().then( (b) => (b as { error?: { status?: string; details?: { errorCode?: string }[] } }).error, () => undefined, ); const code = error?.details?.find((d) => d.errorCode)?.errorCode; if (res.status === 404 || code === "UNREGISTERED" || (res.status === 400 && (error?.status === "INVALID_ARGUMENT" || code === "INVALID_ARGUMENT"))) return "gone"; return "failed"; }