Cotton code
321 lines · 16.6 KB · TypeScriptRaw
/** * Cotton Calling's tests' world: people signed up on the open host with * synthetic numbers, a fake APNs that checks each push's JWT against the run's * own key (vitest.config.ts makes it fresh), a fake Cloudflare TURN, and phone * sockets that keep every frame they are sent. No call leaves the test. */import { env, runDurableObjectAlarm, runInDurableObject, SELF } from "cloudflare:test";import { expect, vi } from "vitest";import type { CallRoom } from "../src/calling/room.ts";export const OPEN = "https://cottondb.com";export const TOPIC = "com.cottondb.calling.dev";type Body = Record<string, unknown>;export async function open<T = Body>(method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<{ status: number; body: T }> {  const res = await SELF.fetch(`${OPEN}${path}`, { method, headers: { "content-type": "application/json", ...headers }, body: body === undefined ? undefined : JSON.stringify(body) });  const text = await res.text();  return { status: res.status, body: (text ? JSON.parse(text) : null) as T };}export const bearer = (token: string): Record<string, string> => ({ authorization: `Bearer ${token}` });let ips = 0;/** A number's sign-in on the open host from one phone: its device credential. */export async function signUp(phone: string, device: string): Promise<string> {  ips += 1;  const ip = { "cf-connecting-ip": `198.18.${Math.floor(ips / 250)}.${ips % 250}` };  const code = await open<{ challenge_id: string; database_id: string }>("POST", "/v1/code", { phone, device_id: device }, ip);  expect(code.status, JSON.stringify(code.body)).toBe(200);  const signed = await open<{ credential: string }>("POST", "/v1/sign-in", { database_id: code.body.database_id, challenge_id: code.body.challenge_id, code: "123456", device_id: device }, ip);  expect(signed.status, JSON.stringify(signed.body)).toBe(200);  return signed.body.credential;}/** * The owner of `credential` accepts `number` (an add from Your people): only someone the callee accepted rings them, * the first contact gate (src/chat/gate.ts, DISCOVERY OFF 3). */export async function acquaint(credential: string, number: string): Promise<void> {  const res = await open("POST", "/v1/chat/accept", { number }, bearer(credential));  expect(res.status, JSON.stringify(res.body)).toBe(200);}/** An iPhone's VoIP token given to its object. */export async function register(credential: string, token: string, sandbox = true): Promise<void> {  const res = await open("POST", "/v1/calls/device", { platform: "ios", token, topic: TOPIC, sandbox }, bearer(credential));  expect(res.status, JSON.stringify(res.body)).toBe(200);}/** An Android phone's FCM registration token given to its object. */export async function registerAndroid(credential: string, token: string): Promise<void> {  const res = await open("POST", "/v1/calls/device", { platform: "android", token }, bearer(credential));  expect(res.status, JSON.stringify(res.body)).toBe(200);}export interface Started {  room: string;  credential: string;  members: { id: string; number: string }[];  iceServers: { urls: string[] }[];  ttl: number;  ringFor: number;}export async function call(credential: string, to: string | string[], video = false): Promise<Started> {  const res = await open<Started>("POST", "/v1/calls", { to, video }, bearer(credential));  expect(res.status, JSON.stringify(res.body)).toBe(200);  return res.body;}export interface Joined {  room: string;  member: string;  from: string;  video: boolean;  credential: string;}export async function join(credential: string, room: string): Promise<{ status: number; body: Joined & { code?: string } }> {  return open<Joined & { code?: string }>("POST", `/v1/calls/${room}/join`, {}, bearer(credential));}// ── the fake APNs and TURN ───────────────────────────────────────────────export interface Push {  host: string;  /** FCM's whole message, for an Android push. */  message?: Body;  token: string;  headers: Record<string, string>;  body: Body;  verified: boolean;}export class Fakes {  pushes: Push[] = [];  /** A token APNs answers with this status (and reason) instead of 200. */  refuse = new Map<string, { status: number; reason?: string }>();  turnCalls: { url: string; authorization: string | null; body: Body }[] = [];  /** The tokens FCM's token endpoint traded, each with whether its assertion verified. */  fcmTokens: { verified: boolean; claims: Body }[] = [];  /** The fake SFU: every call made of it, and the sessions it made. */  sfuCalls: { method: string; path: string; authorization: string | null; body: Body }[] = [];  sfuSessions = 0;  /** How long the fake SFU takes to answer: as Cloudflare's does, long enough for a phone's next frame to come in. */  sfuDelayMs = 0;  /** A path the fake SFU refuses (400), as Cloudflare refuses a bad renegotiation. */  sfuRefuse: string | null = null;  turnAnswer: unknown = { iceServers: [{ urls: ["turn:turn.test:3478?transport=udp", "turns:turn.test:5349?transport=tcp"], username: "minted-user", credential: "minted-pass" }] };  ringsFor(room: string): Push[] {    return this.pushes.filter((p) => p.body.room === room && p.body.stop === undefined);  }  stopsFor(room: string): Push[] {    return this.pushes.filter((p) => p.body.room === room && p.body.stop !== undefined);  }}/** Every outside fetch the Worker makes, answered here: APNs at apns.test, Cloudflare TURN at turn-api.test. */export function fakes(): Fakes {  const world = new Fakes();  const real = globalThis.fetch;  vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {    const request = new Request(input, init);    const url = new URL(request.url);    if (url.hostname === "apns.test") {      const token = decodeURIComponent(url.pathname.replace("/3/device/", ""));      const headers = Object.fromEntries(request.headers.entries());      const text = await request.text();      const verified = await verifies(headers.authorization ?? "");      world.pushes.push({ host: url.hostname, token, headers, body: JSON.parse(text) as Body, verified });      // What APNs itself refuses (Apple, "Handling notification responses from APNs"), so a push the real service      // would not deliver is never answered 200 here (FAKES AUDIT, 24 Nov 2026).      const apns = (status: number, reason: string) => {        console.warn(`fake APNs refused ${type} to ${topic}: ${status} ${reason}`);        return new Response(JSON.stringify({ reason }), { status });      };      const type = headers["apns-push-type"];      const topic = headers["apns-topic"] ?? "";      const payload = JSON.parse(text) as { aps?: Record<string, unknown> };      if (!verified) return apns(403, "InvalidProviderToken");      if (!topic) return apns(400, "MissingTopic");      if (!["alert", "background", "voip"].includes(type ?? "")) return apns(400, "InvalidPushType");      // A VoIP push goes to the app's .voip topic and nothing else does.      if ((type === "voip") !== topic.endsWith(".voip")) return apns(400, "DeviceTokenNotForTopic");      // A background push is priority 5, carries content-available and no alert.      if (type === "background" && (headers["apns-priority"] !== "5" || payload.aps?.["content-available"] !== 1 || "alert" in (payload.aps ?? {}))) return apns(400, "BadPriority");      if (new TextEncoder().encode(text).length > (type === "voip" ? 5120 : 4096)) return apns(413, "PayloadTooLarge");      const refused = world.refuse.get(token);      if (refused) return new Response(JSON.stringify({ reason: refused.reason ?? "Unregistered" }), { status: refused.status });      return new Response(null, { status: 200, headers: { "apns-id": crypto.randomUUID() } });    }    if (url.hostname === "oauth.test") {      const form = new URLSearchParams(await request.text());      const jwt = form.get("assertion") ?? "";      world.fcmTokens.push({ verified: form.get("grant_type") === "urn:ietf:params:oauth:grant-type:jwt-bearer" && (await verifiesRs256(jwt)), claims: claimsOf(jwt) });      return Response.json({ access_token: `synthetic-access-${world.fcmTokens.length}`, expires_in: 3600, token_type: "Bearer" });    }    if (url.hostname === "fcm.test") {      const raw = await request.text();      const message = (JSON.parse(raw) as { message: Body }).message;      const token = String(message.token);      world.pushes.push({ host: url.hostname, token, headers: Object.fromEntries(request.headers.entries()), body: message.data as Body, message, verified: request.headers.get("authorization")?.startsWith("Bearer synthetic-access-") === true });      // What FCM v1 itself refuses: an access token it never minted, a data value that is not a string, a      // message over 4096 bytes (FAKES AUDIT, 24 Nov 2026).      const fcm = (code: number, status: string, why: string) => {        console.warn(`fake FCM refused: ${code} ${status} ${why}`);        return Response.json({ error: { code, status, message: why } }, { status: code });      };      if (!request.headers.get("authorization")?.startsWith("Bearer synthetic-access-")) return fcm(401, "UNAUTHENTICATED", "Request had invalid authentication credentials.");      const data = (message.data ?? {}) as Record<string, unknown>;      const notString = Object.keys(data).find((k) => typeof data[k] !== "string");      if (notString !== undefined) return fcm(400, "INVALID_ARGUMENT", `Invalid value at 'message.data[${notString}].value' (TYPE_STRING)`);      if (new TextEncoder().encode(JSON.stringify(data)).length > 4096) return fcm(400, "INVALID_ARGUMENT", "Message is too big");      const refused = world.refuse.get(token);      if (refused) return Response.json({ error: { code: refused.status, status: refused.status === 404 ? "NOT_FOUND" : "INVALID_ARGUMENT", details: [{ "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError", errorCode: refused.reason ?? "UNREGISTERED" }] } }, { status: refused.status });      return Response.json({ name: `projects/synthetic-calling/messages/${crypto.randomUUID()}` });    }    if (url.hostname === "sfu.test") {      if (world.sfuDelayMs) await new Promise((done) => setTimeout(done, world.sfuDelayMs));      const text = await request.text();      const body = (text ? JSON.parse(text) : {}) as Body;      const path = url.pathname.replace("/v1/apps/synthetic-sfu-app", "");      world.sfuCalls.push({ method: request.method, path, authorization: request.headers.get("authorization"), body });      if (world.sfuRefuse && path.includes(world.sfuRefuse)) return Response.json({ errorCode: "invalid_request", errorDescription: "synthetic refusal" }, { status: 400 });      if (path === "/sessions/new") return Response.json({ sessionId: `sfu-session-${++world.sfuSessions}` });      const session = path.split("/")[2];      if (path.endsWith("/tracks/new")) {        const tracks = (body.tracks as Body[]) ?? [];        if (tracks.every((t) => t.location === "local")) return Response.json({ sessionDescription: { type: "answer", sdp: `answer-for-${session}` }, tracks });        // Cloudflare answers each pulled track with the mid it was given in this session.        const placed = tracks.map((t, i) => ({ ...t, mid: String(100 + i) }));        return Response.json({ sessionDescription: { type: "offer", sdp: `offer-for-${session}` }, tracks: placed, requiresImmediateRenegotiation: true });      }      return Response.json({});    }    if (url.hostname === "turn-api.test") {      world.turnCalls.push({ url: request.url, authorization: request.headers.get("authorization"), body: (await request.json()) as Body });      return Response.json(world.turnAnswer);    }    return real(input, init);  });  return world;}/** Whether a push's `bearer <jwt>` is an ES256 JWT over this run's key, with the team and key id the Worker holds. */async function verifies(authorization: string): Promise<boolean> {  const jwt = authorization.replace(/^bearer /, "");  const [head, claims, signature] = jwt.split(".");  if (!head || !claims || !signature) return false;  const decode = (part: string): Uint8Array => Uint8Array.from(atob(part.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));  const header = JSON.parse(new TextDecoder().decode(decode(head))) as Body;  const body = JSON.parse(new TextDecoder().decode(decode(claims))) as Body;  if (header.alg !== "ES256" || header.kid !== "TESTKEY001" || body.iss !== "TESTTEAM01" || typeof body.iat !== "number") return false;  const jwk = JSON.parse((env as unknown as { APNS_TEST_PUBLIC: string }).APNS_TEST_PUBLIC) as JsonWebKey;  const key = await crypto.subtle.importKey("jwk", jwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);  return crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key, decode(signature), new TextEncoder().encode(`${head}.${claims}`));}function claimsOf(jwt: string): Body {  try {    return JSON.parse(atob(jwt.split(".")[1]!.replace(/-/g, "+").replace(/_/g, "/"))) as Body;  } catch {    return {};  }}/** Whether the service account's assertion is RS256 over this run's key. */async function verifiesRs256(jwt: string): Promise<boolean> {  const [head, claims, signature] = jwt.split(".");  if (!head || !claims || !signature) return false;  const decode = (part: string): Uint8Array => Uint8Array.from(atob(part.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));  const jwk = JSON.parse((env as unknown as { FCM_TEST_PUBLIC: string }).FCM_TEST_PUBLIC) as JsonWebKey;  const key = await crypto.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);  return crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, decode(signature), new TextEncoder().encode(`${head}.${claims}`));}// ── the phones' sockets ──────────────────────────────────────────────────export class Phone {  frames: Body[] = [];  closed = false;  readonly ws: WebSocket;  constructor(ws: WebSocket) {    this.ws = ws;    ws.addEventListener("message", (event) => this.frames.push(JSON.parse(String(event.data)) as Body));    ws.addEventListener("close", () => {      this.closed = true;    });  }  send(frame: Body): void {    this.ws.send(JSON.stringify(frame));  }  /** The first frame matching, waited for. */  async next(match: Body): Promise<Body> {    let found: Body | undefined;    await vi.waitFor(() => {      found = this.frames.find((frame) => Object.entries(match).every(([k, v]) => JSON.stringify(frame[k]) === JSON.stringify(v)));      if (!found) throw new Error(`no frame like ${JSON.stringify(match)} in ${JSON.stringify(this.frames)}`);    }, { timeout: 3000, interval: 10 });    return found!;  }  states(): unknown[] {    return this.frames.filter((f) => f.t === "state").map((f) => f.state);  }  async ended(): Promise<unknown> {    return (await this.next({ t: "ended" })).reason;  }}/** A phone's socket on a call, opened with its room credential in the header. */export async function socket(credential: string): Promise<Phone> {  const res = await SELF.fetch(`${OPEN}/v1/calls/socket`, { headers: { upgrade: "websocket", authorization: `Bearer ${credential}` } });  expect(res.status).toBe(101);  const ws = res.webSocket!;  ws.accept();  return new Phone(ws);}/** The socket's refusal, when it is refused. */export async function refusedSocket(credential: string): Promise<number> {  const res = await SELF.fetch(`${OPEN}/v1/calls/socket`, { headers: { upgrade: "websocket", authorization: `Bearer ${credential}` } });  return res.status;}export function room(id: string): DurableObjectStub<CallRoom> {  return env.CALLROOM.get(env.CALLROOM.idFromName(id));}/** The room's deadline passing. */export async function deadline(id: string): Promise<void> {  await runDurableObjectAlarm(room(id));}/** What the room still keeps: nothing, once a call has ended. */export async function kept(id: string): Promise<number> {  return runInDurableObject(room(id), async (_instance, state) => (await state.storage.list()).size);}/** Wait until the callee's phones were pushed for this room (the ring goes off the caller's answer). */export async function rung(world: Fakes, id: string, count = 1): Promise<Push[]> {  await vi.waitFor(() => {    if (world.ringsFor(id).length < count) throw new Error(`rung ${world.ringsFor(id).length} of ${count}`);  }, { timeout: 3000, interval: 10 });  return world.ringsFor(id);}/** Let the ring hop finish when nothing will come of it. */export async function settle(): Promise<void> {  await new Promise((resolve) => setTimeout(resolve, 150));}