Cotton code
133 lines · 7.5 KB · TypeScriptRaw
/** * Cotton Calling's two outside services, against fakes: the TURN relay's two * adapters behind one interface, and the APNs VoIP sender's token, hosts and * outcomes. No real key, secret or Apple host is reached. */import { env } from "cloudflare:test";import { afterEach, describe, expect, it, vi } from "vitest";import { APNS_PRODUCTION, APNS_SANDBOX, apnsHost, forgetProviderToken, providerToken, pushVoip, TOKEN_LIFE_MS } from "../src/calling/apns.ts";import { message } from "../src/calling/fcm.ts";import { frameData, type PushPayload } from "../src/calling/push.ts";import pushData from "./fixtures/call-push-data.json";import { cloudflareTurn, coturn, DEFAULT_STUN, iceServers, providerOf, type TurnProvider } from "../src/calling/turn.ts";import type { Env } from "../src/env.ts";import { fakes } from "./calling.ts";afterEach(() => {  vi.restoreAllMocks();});function refusal(fn: () => unknown): string {  try {    fn();  } catch (error) {    return (error as { code: string }).code;  }  return "answered";}describe("Cloudflare Realtime TURN", () => {  it("mints a call's credentials with one POST of the key's token, answered as ICE servers after STUN", async () => {    const world = fakes();    const turn = cloudflareTurn({ CF_TURN_KEY_ID: "synthetic-key-id", CF_TURN_API_TOKEN: "synthetic-api-token", CF_TURN_URL: "https://turn-api.test", ENV_LABEL: "test" });    const answer = await iceServers(env, "room-1", turn);    expect(world.turnCalls).toEqual([{ url: "https://turn-api.test/v1/turn/keys/synthetic-key-id/credentials/generate-ice-servers", authorization: "Bearer synthetic-api-token", body: { ttl: 3600 } }]);    expect(answer).toEqual({      iceServers: [{ urls: [DEFAULT_STUN] }, { urls: ["turn:turn.test:3478?transport=udp", "turns:turn.test:5349?transport=tcp"], username: "minted-user", credential: "minted-pass" }],      ttl: 3600,      relay: true,    });  });  it("reads the older single-server answer too", async () => {    const world = fakes();    world.turnAnswer = { iceServers: { urls: "turn:turn.test:3478", username: "u", credential: "c" } };    const turn = cloudflareTurn({ CF_TURN_KEY_ID: "k", CF_TURN_API_TOKEN: "t", CF_TURN_URL: "https://turn-api.test", ENV_LABEL: "test" });    expect(await turn.servers(60, "x")).toEqual([{ urls: ["turn:turn.test:3478"], username: "u", credential: "c" }]);  });  it("is never pointed at a fake in production", () => {    expect(refusal(() => cloudflareTurn({ CF_TURN_KEY_ID: "k", CF_TURN_API_TOKEN: "t", CF_TURN_URL: "https://turn-api.test", ENV_LABEL: "production" }))).toBe("turn_misconfigured");  });});describe("a self-hosted coturn", () => {  it("is handed time-limited credentials coturn checks by the same HMAC-SHA1 of its static-auth-secret", async () => {    const now = Date.UTC(2026, 10, 12, 12, 0, 0);    const [server] = await coturn({ COTURN_SECRET: "synthetic-static-auth-secret", COTURN_URLS: "turn:relay.test:3478, turns:relay.test:5349" }, () => now).servers(3600, "room-2");    const expiry = now / 1000 + 3600;    expect(server!.urls).toEqual(["turn:relay.test:3478", "turns:relay.test:5349"]);    expect(server!.username).toBe(`${expiry}:room-2`);    const key = await crypto.subtle.importKey("raw", new TextEncoder().encode("synthetic-static-auth-secret"), { name: "HMAC", hash: "SHA-1" }, false, ["verify"]);    const mac = Uint8Array.from(atob(server!.credential!), (c) => c.charCodeAt(0));    expect(mac.length).toBe(20);    expect(await crypto.subtle.verify("HMAC", key, mac, new TextEncoder().encode(`${expiry}:room-2`))).toBe(true);  });  it("is the relay when the vars say coturn, and none is when its secret or URLs are missing", () => {    const base = env as Env;    expect(providerOf({ ...base, TURN_PROVIDER: "coturn", COTURN_SECRET: "s", COTURN_URLS: "turn:relay.test:3478" })).not.toBeNull();    expect(providerOf({ ...base, TURN_PROVIDER: "coturn", COTURN_SECRET: "s" })).toBeNull();    expect(providerOf({ ...base, TURN_PROVIDER: "cloudflare", CF_TURN_KEY_ID: "k", CF_TURN_API_TOKEN: "t" })).not.toBeNull();    expect(providerOf(base)).toBeNull();  });  it("leaves STUN alone, said, when the relay fails", async () => {    const broken: TurnProvider = { servers: () => Promise.reject(new Error("down")) };    expect(await iceServers({ ...(env as Env), STUN_URLS: "stun:a.test:3478,stun:b.test:3478" }, "x", broken)).toEqual({ iceServers: [{ urls: ["stun:a.test:3478", "stun:b.test:3478"] }], ttl: 3600, relay: false });  });});describe("the APNs VoIP sender", () => {  it("goes to Apple's production or sandbox host by the device, and to a fake only off production", () => {    expect(apnsHost({ ENV_LABEL: "production" }, false)).toBe(APNS_PRODUCTION);    expect(apnsHost({ ENV_LABEL: "production" }, true)).toBe(APNS_SANDBOX);    expect(apnsHost({ ENV_LABEL: "test", APNS_URL: "https://apns.test/" }, true)).toBe("https://apns.test");    expect(refusal(() => apnsHost({ ENV_LABEL: "production", APNS_URL: "https://apns.test" }, false))).toBe("apns_misconfigured");  });  it("signs one provider token and reuses it for forty minutes", async () => {    forgetProviderToken();    const at = Date.UTC(2026, 10, 12, 9, 0, 0);    const first = await providerToken(env as Env, at);    expect(await providerToken(env as Env, at + TOKEN_LIFE_MS - 1)).toBe(first);    const renewed = await providerToken(env as Env, at + TOKEN_LIFE_MS);    expect(renewed).not.toBe(first);    const claims = JSON.parse(atob(renewed.split(".")[1]!.replace(/-/g, "+").replace(/_/g, "/"))) as { iss: string; iat: number };    expect(claims).toEqual({ iss: "TESTTEAM01", iat: (at + TOKEN_LIFE_MS) / 1000 });    forgetProviderToken();  });  it("says a token Apple no longer knows is gone, and any other refusal failed", async () => {    const world = fakes();    const device = (token: string) => ({ platform: "ios" as const, token, topic: "com.cottondb.calling", sandbox: false });    world.refuse.set("d1", { status: 410 });    world.refuse.set("d2", { status: 400, reason: "BadDeviceToken" });    world.refuse.set("d3", { status: 500, reason: "InternalServerError" });    const e = env as Env;    expect(await pushVoip(e, device("d0"), { room: "r", video: false })).toBe("sent");    expect(await pushVoip(e, device("d1"), { room: "r", video: false })).toBe("gone");    expect(await pushVoip(e, device("d2"), { room: "r", stop: "missed" })).toBe("gone");    expect(await pushVoip(e, device("d3"), { room: "r", stop: "missed" })).toBe("failed");    expect(world.pushes.every((p) => p.verified && p.headers["apns-topic"] === "com.cottondb.calling.voip")).toBe(true);    // A Worker without the key pushes nothing.    expect(await pushVoip({ ...e, APNS_KEY: undefined }, device("d0"), { room: "r", video: false })).toBe("failed");    expect(world.pushes.length).toBe(4);  });});// CALLS FIX 3: the FCM data message (and the socket frame) for each payload, as Android reads it (the shared fixture// test/fixtures/call-push-data.json, which CallPushTest.kt reads too).describe("the call push data Android reads", () => {  for (const c of pushData.cases) {    it(c.name, () => {      const sent = message("invented-fcm-token", c.payload as PushPayload) as { message: { data: Record<string, string> } };      expect(sent.message.data).toEqual(c.data);      expect(frameData(c.payload as PushPayload)).toEqual(c.data);    });  }  it("a missed call kept for a phone is told over its socket as kind missed", () => {    expect(frameData({ room: "0123456789abcdef0123456789abcdef", stop: "missed", box: "c1:sealed", at: 1, ended: 2 }, "missed").kind).toBe("missed");  });});