/** * One call's signalling room (Cotton Calling, 12 Nov 2026): a Durable Object * per call, named by a random room id, holding WebSockets with hibernation. * It decides who is in the call and in what state, and carries what the * phones say to each other. The media never comes here. * * TWO MODES. A call between two people is `p2p`: the room carries offer, * answer and ICE candidates and the media goes phone to phone over WebRTC, * end to end by DTLS-SRTP. A call that rings several people, or a one-to-one * that gains a third member, is `sfu` (and stays so): each member pushes its * tracks to Cloudflare's SFU and pulls the others' through the room * (src/calling/sfu.ts). GROUP MEDIA IS NOT END TO END: the SFU can read it * until frame encryption is added; the opaque `e2ee` relay is its hook. * * MEMBERS. The one who started is `caller`; each invitee `m1`, `m2`… with * its number and a state: invited, ringing, joined, left, declined, no_answer, * busy. `ringing` is the room's alone — others see `invited` — because a ring * that reached a phone says the number has Cotton. A socket is one member's * device, tagged `/`; a member's other phones ring on their * own sockets until one accepts. * * WHAT IT HOLDS, AND FOR HOW LONG. For the call's life: the members' numbers * and objects, the device ids, the credentials' hashes, each member's SFU * session and track names, and a one-to-one caller's signals held until * someone accepts. `e2ee` frames are relayed and never kept. When the call * ends every row goes (`deleteAll`) and every socket closes: a finished call * leaves nothing here. The history is the phones' to write, sealed. * * THE DEADLINES. Each member has 45 s to answer its ring; a one-to-one has * 30 s to connect; a dropped member 30 s to come back. One alarm is set to the * earliest; when it fires, every deadline at or before that one is due — an * alarm never fires early, so its firing is the deadline passing. * * WHAT THE CALLER CAN LEARN. Nothing a callee's object does reaches the room * until a device accepts, declines or says busy: a number with no Cotton, a * phone switched off, a blocked caller and a ring the callee's limit dropped * all read `invited`, then `no_answer` at 45 s. */ import { DurableObject } from "cloudflare:workers"; import type { Env } from "../env.ts"; import { sfuOf, type LocalTrack, type RemoteTrack, type Sfu } from "./sfu.ts"; export const RING_FOR_MS = 45_000; export const CONNECT_FOR_MS = 30_000; export const RECONNECT_FOR_MS = 30_000; /** Nine members: the one who calls and eight invited. */ export const MEMBERS_MAX = 9; /** Speaking marks relayed a second per member, at most. */ export const SPEAKING_PER_SECOND = 4; /** The caller's frames held before anyone accepts: an offer and its candidates fit many times over. */ const HELD_MAX = 200; const FRAME_MAX = 64 * 1024; export type Mode = "p2p" | "sfu"; export type MemberState = "invited" | "ringing" | "joined" | "left" | "declined" | "no_answer" | "busy"; export type EndReason = | "hung_up" | "remote_hung_up" | "declined" | "declined_elsewhere" | "busy" | "no_answer" | "cancelled" | "missed" | "answered_elsewhere" | "failed" | "lost"; /** The reasons a member's other phones are stopped with: the ones a push says. */ export type StopReason = "answered_elsewhere" | "declined_elsewhere" | "cancelled" | "missed"; interface Member { id: string; number: string; state: MemberState; /** The member's object, once its ring reached it. Never sent to a phone. */ slug: string | null; /** The devices rung for this member. */ rung: string[]; /** Its object holds the ring with no phone rung yet (none had a token or a socket): stopped as a ringing member is, so a missed call is kept for the phone that opens later (CALLS FIX 2). */ waits?: boolean; /** The device in the call. */ device: string | null; audio: boolean; video: boolean; speaking: boolean; /** When this member's ring runs out. */ answerBy: number | null; /** When this member's media or socket dropped. */ lostAt: number | null; everJoined: boolean; sfuSession: string | null; tracks: { name: string; kind?: string }[]; /** The tracks this member's session has pulled, `:`: each is pulled once (a second pull of the same track made Cloudflare offer it again, and the phone's answer then matched the wrong offer). */ pulled?: string[]; /** The times of the last speaking marks relayed. */ spoke: number[]; /** What this member's phone says it can show (Take notes: `notes`, the mark). */ can?: string[]; /** Taking notes now (CONTRACT.md "Take notes"). */ notes?: boolean; } interface Call { room: string; mode: Mode; video: boolean; /** A one-to-one's phase; a group call is `live` once someone joins the caller. */ phase: "ringing" | "connecting" | "live"; members: Member[]; /** sha256 hex of each credential's secret → its member and device. */ credentials: Record; held: Record[]; connectBy: number | null; /** A Cotton group's random id, when the call was placed from one: always `sfu`, and its members may come in late. */ group?: string | null; } export interface Started { credential: string; } export interface Invited { id: string; number: string; } /** A member's phone let in late (`enter`): what `join` answers, and the room's own words. */ export interface Entered extends Started { member: string; from: string; video: boolean; group: string | null; } /** What a member's object is told of a call it is in (`status`). */ export interface Status { live: boolean; video: boolean; group: string | null; /** The numbers in the call now. */ joined: string[]; /** This member's own state. */ you: Exclude; } /** What phones are told of a member. */ export interface MemberView { id: string; number: string; state: Exclude; audio: boolean; video: boolean; speaking: boolean; /** Taking notes (CONTRACT.md "Take notes"): every phone shows the mark. */ notes: boolean; /** What the member's phone can show: `notes`. */ can: string[]; } /** What a phone may say it can show: the Take notes mark. */ export const CAN = ["notes"]; /** A phone's `can`, kept to the words the room knows. */ export function canOf(raw: unknown): string[] { return Array.isArray(raw) ? [...new Set(raw.filter((x): x is string => typeof x === "string" && CAN.includes(x)))] : []; } const CREDENTIAL = /^ccr_([0-9a-f]{32})_([A-Za-z0-9_-]{32,})$/; /** The room a credential names, or null. */ export function roomOf(credential: string | null): string | null { return credential ? (CREDENTIAL.exec(credential)?.[1] ?? null) : null; } /** A fresh room id: 128 random bits as lowercase hex. */ export function newRoomId(): string { return hex(crypto.getRandomValues(new Uint8Array(16))); } /** The room's object. */ export function callRoom(env: Env, room: string): DurableObjectStub { return env.CALLROOM.get(env.CALLROOM.idFromName(room), { locationHint: "apac" }); } function hex(bytes: Uint8Array): string { return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join(""); } function b64url(bytes: Uint8Array): string { return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } async function sha256(text: string): Promise { return hex(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)))); } const tag = (member: string, device: string): string => `${member}/${device}`; function untag(value: string | undefined): { member: string; device: string } | null { if (!value) return null; const at = value.indexOf("/"); return at < 0 ? null : { member: value.slice(0, at), device: value.slice(at + 1) }; } function newMember(id: string, number: string, state: MemberState, video: boolean, now: number): Member { return { id, number, state, slug: null, rung: [], device: null, audio: true, video, speaking: false, answerBy: state === "invited" ? now + RING_FOR_MS : null, lostAt: null, everJoined: state === "joined", sfuSession: null, tracks: [], spoke: [] }; } function view(member: Member): MemberView { return { id: member.id, number: member.number, state: member.state === "ringing" ? "invited" : member.state, audio: member.audio, video: member.video, speaking: member.speaking, notes: member.notes === true, can: member.can ?? [] }; } const pending = (m: Member): boolean => m.state === "invited" || m.state === "ringing"; /** How long a member's next SFU pull or push waits for its answer to the last offer before going anyway. */ export const SFU_ANSWER_MS = 10_000; export class CallRoom extends DurableObject { /** The SFU a test hands in place of the Worker's own. */ sfu: Sfu | null = null; /** Each member's SFU operations, one after another (see sfuInTurn). */ private sfuTurns = new Map>(); /** A member's offer still unanswered: its next pull or push waits on it (see sfuInTurn). */ private sfuAwaiting = new Map; done: () => void }>(); /** Members whose session has pushed (from this object's waking: a pull after it is never held). */ private sfuPushed = new Set(); /** Pulls that came before their member's push, held for it (see sfuInTurn). */ private sfuHeld = new Map }[]>(); // ── what the objects ask (RPC) ───────────────────────────────────────── /** The caller's object opens the room with its invitees; the caller's credential is answered. */ async init(args: { room: string; callerSlug: string; callerNumber: string; callerDevice: string; video: boolean; invitees: string[]; group?: string | null; can?: string[] }): Promise { if (await this.load()) throw new Error("the room is already open"); const now = Date.now(); const caller = newMember("caller", args.callerNumber, "joined", args.video, now); caller.can = canOf(args.can); caller.slug = args.callerSlug; caller.device = args.callerDevice; const invitees = args.invitees.slice(0, MEMBERS_MAX - 1).map((number, i) => newMember(`m${i + 1}`, number, "invited", args.video, now)); // A group's call is the SFU's from the start, whatever its size: anyone of it may come in later. const group = args.group ?? null; const call: Call = { room: args.room, mode: group || invitees.length > 1 ? "sfu" : "p2p", video: args.video, phase: "ringing", members: [caller, ...invitees], credentials: {}, held: [], connectBy: null, group }; const credential = await this.mint(call, "caller", args.callerDevice); await this.save(call); await this.schedule(call); return { credential, members: invitees.map((m) => ({ id: m.id, number: m.number })) }; } /** A joined member's phone invites more people; null when that phone is not in the call. */ async invite(slug: string, device: string, numbers: string[]): Promise<{ members: Invited[]; from: string; video: boolean } | { full: true } | null> { const call = await this.load(); const inviter = call?.members.find((m) => m.state === "joined" && m.slug === slug && m.device === device); if (!call || !inviter) return null; const active = call.members.filter((m) => m.state === "joined" || pending(m)); const fresh = [...new Set(numbers)].filter((n) => !active.some((m) => m.number === n)); if (active.length + fresh.length > MEMBERS_MAX) return { full: true }; const now = Date.now(); const added = fresh.map((number, i) => newMember(`m${call.members.length + i}`, number, "invited", call.video, now)); call.members.push(...added); if (call.mode === "p2p" && active.length + added.length > 2) { // A third member moves the call to the SFU, and it stays there. call.mode = "sfu"; call.held = []; call.connectBy = null; if (call.phase === "connecting") call.phase = "live"; this.toJoined(call, { t: "mode", mode: "sfu" }); } for (const member of added) this.toJoined(call, { t: "member", member: view(member) }); await this.save(call); return { members: added.map((m) => ({ id: m.id, number: m.number })), from: inviter.number, video: call.video }; } /** A member's object rang these devices. */ async ringing(member: string, slug: string, devices: string[]): Promise { const call = await this.load(); const m = call?.members.find((x) => x.id === member); if (!call || !m || !pending(m) || (m.slug !== null && m.slug !== slug)) return false; m.slug = slug; m.state = "ringing"; m.rung = [...new Set([...m.rung, ...devices])]; await this.save(call); return true; } /** * The member's object holds the ring though no phone of it could be rung yet: the room keeps whose object it is, so * the ring's end reaches it (a missed call kept for the phone that opens). The member's state is not changed: nothing * rang, and the caller is not told otherwise. */ async waiting(member: string, slug: string): Promise { const call = await this.load(); const m = call?.members.find((x) => x.id === member); if (!call || !m || !pending(m) || (m.slug !== null && m.slug !== slug)) return false; m.slug = slug; m.waits = true; await this.save(call); return true; } /** A rung device's own credential, minted while its member still rings; null after. */ async join(member: string, slug: string, device: string, can: string[] = []): Promise<(Started & { group: string | null }) | null> { const call = await this.load(); const m = call?.members.find((x) => x.id === member); if (!call || !m || m.state !== "ringing" || m.slug !== slug || !m.rung.includes(device)) return null; m.can = canOf(can); const credential = await this.mint(call, m.id, device); await this.save(call); return { credential, group: call.group ?? null }; } /** * A member comes in late, or back after leaving, from one of its phones: a * group call only, a member of it only (by its object, or by its number for * one whose ring never reached it). The phone is put to ringing, so the * accept on its socket follows as a ring's does. Null when the call is over * or this is no member of it; `"here"` when it is in the call on another phone. */ async enter(slug: string, number: string, device: string, can: string[] = []): Promise { const call = await this.load(); if (!call || call.mode !== "sfu" || !call.group) return null; const m = call.members.find((x) => x.slug === slug) ?? call.members.find((x) => x.slug === null && x.number === number); if (!m) return null; const back = m.state === "joined" && m.device === device; if (m.state === "joined" && !back && m.lostAt === null) return "here"; if (!back) { // In afresh: what it pushed before is gone with the session it had. const was = m.state === "joined"; m.state = "ringing"; m.slug = slug; m.device = null; m.lostAt = null; m.answerBy = Date.now() + RING_FOR_MS; m.sfuSession = null; m.pulled = []; this.sfuPushed.delete(m.id); m.tracks = []; m.notes = false; if (was) this.toJoined(call, { t: "member", member: view(m) }); } m.rung = [...new Set([...m.rung, device])]; m.can = canOf(can); const credential = await this.mint(call, m.id, device); await this.save(call); await this.schedule(call); const caller = call.members.find((x) => x.id === "caller")!; return { credential, member: m.id, from: caller.number, video: call.video, group: call.group }; } /** What a member's object is told of the call: null when it is over or this is no member of it. */ async status(slug: string, number: string): Promise { const call = await this.load(); if (!call) return null; const m = call.members.find((x) => x.slug === slug) ?? call.members.find((x) => x.slug === null && x.number === number); if (!m) return null; const joined = call.members.filter((x) => x.state === "joined"); return { live: call.phase === "live" || joined.length > 1, video: call.video, group: call.group ?? null, joined: joined.map((x) => x.number), you: view(m).state }; } /** A rung device declined (or was busy) without joining. */ async decline(slug: string, device: string, busy: boolean): Promise { const call = await this.load(); const m = call?.members.find((x) => x.state === "ringing" && x.slug === slug && x.rung.includes(device)); if (!call || !m) return false; await this.refuseRing(call, m, device, busy); return true; } /** A hang-up from a phone whose socket is down. */ async hangUp(slug: string, device: string): Promise { const call = await this.load(); const m = call?.members.find((x) => x.slug === slug && (x.device === device || (x.state === "ringing" && x.rung.includes(device)))); if (!call || !m) return false; await this.leave(call, m, device); return true; } // ── the sockets ──────────────────────────────────────────────────────── override async fetch(request: Request): Promise { if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") return new Response("a call room speaks WebSocket", { status: 426 }); const match = CREDENTIAL.exec((request.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "")); const call = await this.load(); if (!match || !call || match[1] !== call.room) return Response.json({ code: "no_call", message: "this call has ended" }, { status: 410 }); const holder = call.credentials[await sha256(match[2]!)]; if (!holder) return Response.json({ code: "invalid_credential", message: "not a credential of this call" }, { status: 401 }); const m = call.members.find((x) => x.id === holder.member)!; const inCall = m.state === "joined" && m.device === holder.device; const ringingHere = m.state === "ringing" && m.rung.includes(holder.device); if (!inCall && !ringingHere) return Response.json({ code: "no_call", message: "not in this call" }, { status: 410 }); const name = tag(m.id, holder.device); for (const old of this.ctx.getWebSockets(name)) { old.serializeAttachment({ closed: true }); old.close(4000, "replaced"); } const pair = new WebSocketPair(); this.ctx.acceptWebSocket(pair[1], [name]); if (ringingHere) { this.send(pair[1], { t: "state", state: "ringing_in", at: Date.now() }); } else if (m.lostAt !== null) { // A socket back after a drop is that member back. m.lostAt = null; await this.save(call); await this.schedule(call); this.welcome(call, m, pair[1]); if (call.mode === "p2p") this.toJoined(call, { t: "state", state: "live", at: Date.now() }); else this.toJoined(call, { t: "member", member: view(m) }, m.id); } else { this.welcome(call, m, pair[1]); } return new Response(null, { status: 101, webSocket: pair[0] }); } override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise { if (typeof message !== "string" || message.length > FRAME_MAX) return; let frame: Record; try { const parsed: unknown = JSON.parse(message); if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return; frame = parsed as Record; } catch { return; } const holder = untag(this.ctx.getTags(ws)[0]); if (!holder) return; if (frame.t === "ping") return this.send(ws, { t: "pong" }); const call = await this.load(); const m = call?.members.find((x) => x.id === holder.member); if (!call || !m) return; const inCall = m.state === "joined" && m.device === holder.device; if (m.state === "ringing") { if (frame.t === "accept") return this.accept(call, m, holder.device); if (frame.t === "decline" || frame.t === "busy") return this.refuseRing(call, m, holder.device, frame.t === "busy"); if (frame.t === "end" || frame.t === "leave") return this.refuseRing(call, m, holder.device, false); return; } if (!inCall) return; switch (frame.t) { case "signal": return this.signal(call, m, frame); case "media": return this.media(call, m, frame.state); case "mute": if (typeof frame.audio === "boolean") m.audio = frame.audio; if (typeof frame.video === "boolean") m.video = frame.video; await this.save(call); return this.toJoined(call, { t: "member", member: view(m) }); case "speaking": return this.speaking(call, m, frame.on === true); case "sfu": return this.sfuInTurn(m.id, ws, frame); case "e2ee": return this.relayOpaque(call, m, frame); case "notes": return this.notes(call, m, ws, frame.on === true); case "hello": return this.toJoined(call, { ...frame, from: m.id }, m.id); case "end": case "leave": return this.leave(call, m, holder.device); default: return; } } override async webSocketClose(ws: WebSocket): Promise { const name = this.ctx.getTags(ws)[0]; const holder = untag(name); // A socket the room closed itself (the call over for it) is no drop. if ((ws.deserializeAttachment() as { closed?: boolean } | null)?.closed) return; const call = await this.load(); const m = call?.members.find((x) => x.id === holder?.member); if (!call || !m || !holder || m.state !== "joined" || m.device !== holder.device) return; // A replaced socket is not a drop: its successor is already open. if (this.ctx.getWebSockets(name).some((other) => other !== ws)) return; await this.drop(call, m); } override async webSocketError(ws: WebSocket): Promise { await this.webSocketClose(ws); } /** The earliest deadline passed, and every one at or before it. */ override async alarm(): Promise { const call = await this.load(); if (!call) return; const due = this.nextDue(call); if (due === null) return; if (call.connectBy !== null && call.connectBy <= due) return this.end(call, () => "failed", null); for (const m of call.members) { if (pending(m) && m.answerBy !== null && m.answerBy <= due) { if (call.mode === "p2p") return this.end(call, (who) => (who === "caller" ? "no_answer" : "missed"), "missed"); await this.settle(call, m, "no_answer", "missed", () => "missed"); } else if (m.state === "joined" && m.lostAt !== null && m.lostAt + RECONNECT_FOR_MS <= due) { if (call.mode === "p2p") return this.end(call, () => "lost", null); this.closeMember(m, () => "lost"); m.state = "left"; m.lostAt = null; this.notesGone(m); this.toJoined(call, { t: "member", member: view(m) }); } } if (await this.endedIfDone(call)) return; await this.save(call); await this.schedule(call); } // ── the rules ────────────────────────────────────────────────────────── /** A joined member's socket opens: its state, the mode, who is here, and the tracks already pushed. */ private welcome(call: Call, m: Member, ws: WebSocket): void { this.send(ws, { t: "state", state: this.stateFor(call, m), at: Date.now() }); if (call.mode === "sfu") this.send(ws, { t: "mode", mode: "sfu" }); this.send(ws, { t: "roster", members: call.members.map(view) }); for (const other of call.members) if (other.id !== m.id && other.state === "joined" && other.tracks.length) this.send(ws, { t: "tracks", member: other.id, tracks: other.tracks }); } private stateFor(call: Call, m: Member): string { if (call.phase === "ringing") return "ringing_out"; if (call.mode === "p2p" && call.members.some((x) => x.lostAt !== null)) return "reconnecting"; return m.lostAt !== null ? "reconnecting" : call.phase; } private async signal(call: Call, m: Member, frame: Record): Promise { if (call.mode !== "p2p" || !["offer", "answer", "ice", "restart"].includes(String(frame.kind))) return; const relayed: Record = { t: "signal", from: m.id, kind: frame.kind }; for (const key of ["sdp", "candidate", "mid", "mline"]) if (frame[key] !== undefined) relayed[key] = frame[key]; const other = call.members.find((x) => x.id !== m.id && x.state === "joined"); if (!other) { // Held for the phone that accepts; nobody else sees the caller's offer. if (m.id === "caller" && call.phase === "ringing" && call.held.length < HELD_MAX) { call.held.push(relayed); await this.save(call); } return; } this.toMember(other, relayed); } private async accept(call: Call, m: Member, device: string): Promise { m.state = "joined"; m.device = device; m.everJoined = true; m.answerBy = null; await this.notesStopFor(call, m); const at = Date.now(); // This member's other phones stop ringing: on their sockets now, and by a stop push. this.closeMember(m, () => "answered_elsewhere", device); if (call.mode === "p2p") { call.phase = "connecting"; call.connectBy = at + CONNECT_FOR_MS; const held = call.held; call.held = []; await this.save(call); await this.schedule(call); this.toJoined(call, { t: "state", state: "connecting", at }); this.toMember(m, { t: "roster", members: call.members.map(view) }); for (const frame of held) this.toMember(m, frame); } else { const first = call.phase === "ringing"; call.phase = "live"; await this.save(call); await this.schedule(call); for (const ws of this.ctx.getWebSockets(tag(m.id, device))) this.welcome(call, m, ws); if (first) this.toJoined(call, { t: "state", state: "live", at }, m.id); this.toJoined(call, { t: "member", member: view(m) }, m.id); } await this.stopMember(call, m, "answered_elsewhere", device); } /** A decline or busy from a ringing phone: a one-to-one ends; in a group that member is out. */ private async refuseRing(call: Call, m: Member, device: string, busy: boolean): Promise { const said: EndReason = busy ? "busy" : "declined"; if (call.mode === "p2p") { return this.end(call, (who, dev) => (who === "caller" || dev === device ? said : "declined_elsewhere"), "declined_elsewhere", device); } await this.settle(call, m, busy ? "busy" : "declined", "declined_elsewhere", (dev) => (dev === device ? said : "declined_elsewhere"), device); if (await this.endedIfDone(call)) return; await this.save(call); await this.schedule(call); } /** A ringing member's ring ends as `state`: its sockets closed, its other phones stopped, everyone told. */ private async settle(call: Call, m: Member, state: MemberState, stop: StopReason, reason: (device: string) => EndReason, except?: string): Promise { m.state = state; m.answerBy = null; this.closeMember(m, reason); await this.stopMember(call, m, stop, except); this.toJoined(call, { t: "member", member: view(m) }); } private async media(call: Call, m: Member, state: unknown): Promise { if (state === "connected") { const wasLost = m.lostAt !== null; m.lostAt = null; if (call.mode === "p2p" && (call.phase === "connecting" || wasLost)) { call.phase = "live"; call.connectBy = null; await this.save(call); await this.schedule(call); this.toJoined(call, { t: "state", state: "live", at: Date.now() }); } else if (wasLost) { await this.save(call); await this.schedule(call); this.toJoined(call, { t: "member", member: view(m) }); } } else if (state === "disconnected") { await this.drop(call, m); } else if (state === "failed" && call.mode === "p2p" && call.phase === "connecting") { await this.end(call, () => "failed", null); } } /** A member's media or socket dropped: the others are told, and it has 30 s to come back. */ private async drop(call: Call, m: Member): Promise { // Before a one-to-one is live, the connecting deadline stands. if (m.lostAt !== null || (call.mode === "p2p" && call.phase !== "live")) return; m.lostAt = Date.now(); await this.save(call); await this.schedule(call); if (call.mode === "p2p") this.toJoined(call, { t: "state", state: "reconnecting", at: Date.now() }); else this.toJoined(call, { t: "member", member: view(m) }, m.id); } private async speaking(call: Call, m: Member, on: boolean): Promise { const now = Date.now(); m.spoke = m.spoke.filter((at) => now - at < 1000); if (m.spoke.length >= SPEAKING_PER_SECOND) return; m.spoke.push(now); m.speaking = on; await this.save(call); this.toJoined(call, { t: "speaking", member: m.id, on }, m.id); } /** * Take notes (CONTRACT.md "Take notes"): a member starts or stops. A start * is refused, to that phone alone, while any member in the call cannot show * the mark; else everyone in the call is told by the member frame, and the * note-taker's phone starts only when its own frame comes back. */ private async notes(call: Call, m: Member, ws: WebSocket, on: boolean): Promise { if (on) { const blind = call.members.filter((x) => x.state === "joined" && !(x.can ?? []).includes("notes")); if (blind.length) return this.send(ws, { t: "notes", refused: "cannot_show", members: blind.map((x) => x.id) }); } if ((m.notes === true) === on) return; m.notes = on; await this.save(call); this.toJoined(call, { t: "member", member: view(m) }); } /** A member out of the call takes no notes (its member frame says so). */ private notesGone(m: Member): void { m.notes = false; } /** A member joined who cannot show the mark: notes stop for the call, and each note-taker is told who. */ private async notesStopFor(call: Call, joiner: Member): Promise { if ((joiner.can ?? []).includes("notes")) return; for (const taker of call.members.filter((x) => x.notes === true && x.state === "joined")) { taker.notes = false; this.toMember(taker, { t: "notes", stopped: "cannot_show", member: joiner.id }); this.toJoined(call, { t: "member", member: view(taker) }); } } /** An `e2ee` frame, opaque: handed on to one member or every other, never read, never kept. */ private relayOpaque(call: Call, m: Member, frame: Record): void { const relayed = { t: "e2ee", from: m.id, epoch: frame.epoch, data: frame.data }; if (typeof frame.to === "string") { const to = call.members.find((x) => x.id === frame.to && x.state === "joined"); if (to) this.toMember(to, relayed); return; } this.toJoined(call, relayed, m.id); } /** * One member's SFU operations in the order they came, each on the call as the one before left it. A joining phone * sends its push and its pull together; run side by side, each found no session and made its own, so the phone * was answered from one session and offered from another, and refused the offer (walk on dev, 23 Nov 2026). */ private sfuInTurn(member: string, ws: WebSocket, frame: Record): Promise { const run = async () => { const call = await this.load(); const m = call?.members.find((x) => x.id === member && x.state === "joined"); if (call && m) await this.sfuOp(call, m, ws, frame); }; // The phone's answer to an offer goes at once, past the turns: the next pull waits on it. if (frame.op === "renegotiate") { return run().finally(() => this.sfuAnswered(member)); } // A pull before this member's own push is held until the push is done (or SFU_ANSWER_MS): Cloudflare's offer of // the others' tracks, made on a session the phone has not yet pushed to, is refused by the phone ("Failed to set // remote audio description send parameters for m-section with mid='0'"), and its push is then refused (406). if (frame.op === "pull" && !this.sfuPushed.has(member)) { return this.load().then((call) => { const m = call?.members.find((x) => x.id === member); if (m?.sfuSession && m.tracks.length) this.sfuPushed.add(member); if (this.sfuPushed.has(member)) return this.sfuInTurn(member, ws, frame); this.sfuHold(member, ws, frame); }); } return this.sfuQueue(member, frame, run); } private sfuHold(member: string, ws: WebSocket, frame: Record): void { const held = this.sfuHeld.get(member) ?? []; held.push({ ws, frame }); this.sfuHeld.set(member, held); if (held.length === 1) setTimeout(() => this.sfuRelease(member), SFU_ANSWER_MS); } private sfuQueue(member: string, frame: Record, run: () => Promise): Promise { const before = this.sfuTurns.get(member) ?? Promise.resolve(); const next = before.then(async () => { // Cloudflare refuses a session's next pull (406) until its last offer is answered (launch-ios on dev, 23 Nov // 2026): a pull or push waits for this member's renegotiate, or SFU_ANSWER_MS, whichever is first. await this.sfuAwaiting.get(member)?.promise; await run(); if (frame.op === "push") { this.sfuPushed.add(member); this.sfuRelease(member); } }); const settled = next.catch(() => {}); this.sfuTurns.set(member, settled); void settled.then(() => { if (this.sfuTurns.get(member) === settled) this.sfuTurns.delete(member); }); return next; } /** The pulls held for this member's push go on, in the order they came. */ private sfuRelease(member: string): void { const held = this.sfuHeld.get(member); if (!held) return; this.sfuHeld.delete(member); this.sfuPushed.add(member); for (const { ws, frame } of held) void this.sfuInTurn(member, ws, frame); } /** This member now owes the SFU an answer to an offer: its next pull or push waits for it. */ private sfuOwes(member: string): void { this.sfuAnswered(member); let done = () => {}; const promise = new Promise((resolve) => { done = resolve; }); const timer = setTimeout(() => this.sfuAnswered(member), SFU_ANSWER_MS); this.sfuAwaiting.set(member, { promise, done: () => { clearTimeout(timer); done(); } }); } private sfuAnswered(member: string): void { const owed = this.sfuAwaiting.get(member); this.sfuAwaiting.delete(member); owed?.done(); } private async sfuOp(call: Call, m: Member, ws: WebSocket, frame: Record): Promise { if (call.mode !== "sfu") return; const sfu = this.sfu ?? sfuOf(this.env); if (!sfu) return this.send(ws, { t: "error", code: "sfu_unavailable" }); try { if (frame.op === "push" && typeof frame.sdp === "string" && Array.isArray(frame.tracks)) { const tracks = (frame.tracks as Record[]).filter((t) => typeof t.mid === "string" && typeof t.name === "string").map((t): LocalTrack => ({ mid: String(t.mid), name: String(t.name), kind: typeof t.kind === "string" ? t.kind : undefined })); if (!m.sfuSession) m.sfuSession = (await sfu.newSession()).sessionId; const answer = await sfu.push(m.sfuSession, frame.sdp, tracks); for (const t of tracks) if (!m.tracks.some((held) => held.name === t.name)) m.tracks.push(t.kind ? { name: t.name, kind: t.kind } : { name: t.name }); await this.save(call); this.send(ws, { t: "sfu", op: "answer", sdp: answer.sdp }); this.toJoined(call, { t: "tracks", member: m.id, tracks: m.tracks }, m.id); } else if (frame.op === "pull" && Array.isArray(frame.tracks)) { const wanted: RemoteTrack[] = []; for (const t of frame.tracks as Record[]) { const owner = call.members.find((x) => x.id === t.member && x.state === "joined"); if (owner?.sfuSession && owner.tracks.some((held) => held.name === t.name)) wanted.push({ sessionId: owner.sfuSession, name: String(t.name) }); } // A track this session already has is not pulled again: a phone that asks twice for one offer (the iPhone on // dev, 23 Nov 2026, two pulls 5 ms apart) got two offers, answered the first, and lost its media. const had = new Set(m.pulled ?? []); const fresh = wanted.filter((w) => !had.has(`${w.sessionId}:${w.name}`)).filter((w, i, all) => all.findIndex((x) => x.sessionId === w.sessionId && x.name === w.name) === i); wanted.length = 0; wanted.push(...fresh); if (!wanted.length) return; if (!m.sfuSession) { m.sfuSession = (await sfu.newSession()).sessionId; await this.save(call); } const pulled = await sfu.pull(m.sfuSession, wanted); m.pulled = [...(m.pulled ?? []), ...wanted.map((w) => `${w.sessionId}:${w.name}`)]; await this.save(call); // Each track the offer brings, by its mid and whose it is: one person's voice is one track, kept apart. const tracks = pulled.tracks.flatMap((t) => { const owner = call.members.find((x) => x.sfuSession === t.sessionId); return owner && t.mid ? [{ mid: t.mid, member: owner.id, name: t.name }] : []; }); if (pulled.sdp) { if (pulled.renegotiate) this.sfuOwes(m.id); this.send(ws, { t: "sfu", op: "offer", sdp: pulled.sdp, tracks }); } } else if (frame.op === "renegotiate" && typeof frame.sdp === "string" && m.sfuSession) { await sfu.renegotiate(m.sfuSession, frame.sdp); } else if (frame.op === "close" && Array.isArray(frame.mids) && m.sfuSession) { await sfu.close(m.sfuSession, (frame.mids as unknown[]).filter((x): x is string => typeof x === "string")); } } catch (error) { // Which operation, and the SFU's words (no person's data: Cloudflare's status and error text), so a phone's log // says what failed (the walk on dev, 23 Nov 2026, saw only that something had). const detail = error instanceof Error ? error.message.slice(0, 300) : "unknown"; console.warn(`call ${call.room}: sfu ${String(frame.op)} failed: ${detail}`); this.send(ws, { t: "error", code: "sfu_failed", op: typeof frame.op === "string" ? frame.op : "unknown", detail }); } } /** * A member hangs up. A ringing phone's hang-up is a decline. In a * one-to-one, the caller's before anyone answers is a cancel, else the end * for both; in a group the member leaves and the others go on. */ private async leave(call: Call, m: Member, device: string): Promise { if (m.state === "ringing") return this.refuseRing(call, m, device, false); if (m.state !== "joined") return; if (call.mode === "p2p") { if (call.phase === "ringing") return this.end(call, () => "cancelled", "cancelled"); return this.end(call, (who) => (who === m.id ? "hung_up" : "remote_hung_up"), null); } // The caller leaving before anyone answered is a cancel. const alone = !call.members.some((x) => x.id !== m.id && x.everJoined); m.state = "left"; m.lostAt = null; this.notesGone(m); this.closeMember(m, () => (alone && m.id === "caller" ? "cancelled" : "hung_up")); this.toJoined(call, { t: "member", member: view(m) }); if (await this.endedIfDone(call)) return; await this.save(call); await this.schedule(call); } /** A group call ends when fewer than two are in it and nobody is still being rung, or nobody is in it at all. */ private async endedIfDone(call: Call): Promise { if (call.mode === "p2p") return false; const joined = call.members.filter((m) => m.state === "joined"); const ringing = call.members.some(pending); if (joined.length >= 2 || (joined.length === 1 && ringing)) return false; const answered = call.members.some((m) => m.id !== "caller" && m.everJoined); const invitees = call.members.filter((m) => m.id !== "caller"); const alone: EndReason = answered ? "remote_hung_up" : invitees.every((m) => m.state === "declined") ? "declined" : invitees.every((m) => m.state === "declined" || m.state === "busy") ? "busy" : "no_answer"; await this.end(call, (who) => (call.members.find((m) => m.id === who)?.state === "joined" ? alone : "cancelled"), "cancelled"); return true; } /** * The end: every row gone, every socket told its reason and closed, and * each rung member's object told (with a stop push for its phones still * ringing). */ private async end(call: Call, reasonFor: (member: string, device: string) => EndReason, ringStop: StopReason | null, except?: string): Promise { // The rows go first: nothing that runs while the objects are told can find the call again. await this.ctx.storage.deleteAlarm(); await this.ctx.storage.deleteAll(); for (const ws of this.ctx.getWebSockets()) { const holder = untag(this.ctx.getTags(ws)[0]); this.send(ws, { t: "ended", reason: holder ? reasonFor(holder.member, holder.device) : "hung_up" }); this.close(ws); } for (const m of call.members) if (m.id !== "caller" && m.slug) await this.stopMember(call, m, m.state === "ringing" || (m.waits && pending(m)) ? ringStop : null, except ?? m.device ?? undefined); } private closeMember(m: Member, reason: (device: string) => EndReason, keep?: string): void { for (const ws of this.ctx.getWebSockets()) { const holder = untag(this.ctx.getTags(ws)[0]); if (!holder || holder.member !== m.id || holder.device === keep) continue; this.send(ws, { t: "ended", reason: reason(holder.device) }); this.close(ws); } } private async stopMember(call: Call, m: Member, stop: StopReason | null, except?: string): Promise { if (!m.slug || m.id === "caller") return; try { const object = this.env.BUSINESS.get(this.env.BUSINESS.idFromName(m.slug), { locationHint: "apac" }); await object.callStop(call.room, stop, except ?? null); } catch { // The member's object answers at its next sweep: a ring it holds goes after two minutes. } } private nextDue(call: Call): number | null { const dues: number[] = []; if (call.connectBy !== null) dues.push(call.connectBy); for (const m of call.members) { if (pending(m) && m.answerBy !== null) dues.push(m.answerBy); if (m.state === "joined" && m.lostAt !== null) dues.push(m.lostAt + RECONNECT_FOR_MS); } return dues.length ? Math.min(...dues) : null; } private async schedule(call: Call): Promise { const due = this.nextDue(call); if (due === null) await this.ctx.storage.deleteAlarm(); else await this.ctx.storage.setAlarm(due); } private async mint(call: Call, member: string, device: string): Promise { const secret = b64url(crypto.getRandomValues(new Uint8Array(32))); // One credential a device: a second join replaces the first. for (const [hash, holder] of Object.entries(call.credentials)) if (holder.member === member && holder.device === device) delete call.credentials[hash]; call.credentials[await sha256(secret)] = { member, device }; return `ccr_${call.room}_${secret}`; } /** To every joined member's phone in the call, but `except`. */ private toJoined(call: Call, frame: Record, except?: string): void { for (const m of call.members) if (m.state === "joined" && m.id !== except) this.toMember(m, frame); } private toMember(m: Member, frame: Record): void { if (m.device) for (const ws of this.ctx.getWebSockets(tag(m.id, m.device))) this.send(ws, frame); } private close(ws: WebSocket): void { try { ws.serializeAttachment({ closed: true }); ws.close(1000, "ended"); } catch { // Already closed. } } private send(ws: WebSocket, frame: Record): void { try { ws.send(JSON.stringify(frame)); } catch { // A socket closing as it is written to: its close says the rest. } } private async load(): Promise { return (await this.ctx.storage.get("call")) ?? null; } private async save(call: Call): Promise { await this.ctx.storage.put("call", call); } }