/** * The selective forwarding unit a group call's media goes through (Cotton * Calling, 12 Nov 2026), behind one small interface like the TURN relay's. * The one adapter is Cloudflare Realtime SFU: each member is one SFU session; * a member pushes its tracks to its session and pulls the others' tracks by * (session, track name). The app secret never leaves the Worker; a member's * session id lives in the room for the call's life only. * * GROUP MEDIA IS NOT END TO END. It is DTLS-SRTP between each phone and the * SFU, so Cloudflare's SFU can read it, until frame encryption is added (the * room's opaque `e2ee` relay is the hook for it). A one-to-one call never * comes here: it stays peer to peer, end to end. */ import { isProduction, type Env } from "../env.ts"; import { refuse } from "../http.ts"; export interface LocalTrack { mid: string; name: string; kind?: string; } export interface RemoteTrack { sessionId: string; name: string; } /** A pulled track as the SFU placed it in this session: its mid, and whose session and name it is. */ export interface PulledTrack { mid: string | null; sessionId: string; name: string; } export interface Sfu { newSession(): Promise<{ sessionId: string }>; /** A member's offer with its local tracks; the SFU's answer. */ push(sessionId: string, sdp: string, tracks: LocalTrack[]): Promise<{ sdp: string }>; /** Other members' tracks into this session; an offer to answer when the SFU must renegotiate. */ pull(sessionId: string, tracks: RemoteTrack[]): Promise<{ sdp: string | null; renegotiate: boolean; tracks: PulledTrack[] }>; /** The member's answer to the SFU's offer. */ renegotiate(sessionId: string, sdp: string): Promise; close(sessionId: string, mids: string[]): Promise; } const CLOUDFLARE_SFU = "https://rtc.live.cloudflare.com"; /** Cloudflare Realtime SFU over its HTTPS API. */ export function cloudflareSfu(env: Pick): Sfu { const fake = env.CF_SFU_URL?.replace(/\/+$/, ""); if (fake && isProduction(env as Env)) refuse(503, "sfu_misconfigured", "CF_SFU_URL is for a test Worker's fake SFU, never production"); const base = `${fake ?? CLOUDFLARE_SFU}/v1/apps/${encodeURIComponent(env.CF_SFU_APP_ID ?? "")}`; const call = async (method: string, path: string, body?: unknown): Promise => { const res = await fetch(`${base}${path}`, { method, headers: { authorization: `Bearer ${env.CF_SFU_APP_SECRET ?? ""}`, "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), }); if (!res.ok) throw new Error(`the SFU answered ${res.status} to ${method} ${path}: ${(await res.text()).slice(0, 200)}`); const text = await res.text(); return (text ? JSON.parse(text) : {}) as T; }; type Described = { sessionDescription?: { type?: string; sdp?: string }; requiresImmediateRenegotiation?: boolean; tracks?: { mid?: string; sessionId?: string; trackName?: string }[] }; return { async newSession() { const answer = await call<{ sessionId?: string }>("POST", "/sessions/new"); if (!answer.sessionId) throw new Error("the SFU made no session"); return { sessionId: answer.sessionId }; }, async push(sessionId, sdp, tracks) { const answer = await call("POST", `/sessions/${encodeURIComponent(sessionId)}/tracks/new`, { sessionDescription: { type: "offer", sdp }, tracks: tracks.map((t) => ({ location: "local", mid: t.mid, trackName: t.name })), }); return { sdp: answer.sessionDescription?.sdp ?? "" }; }, async pull(sessionId, tracks) { const answer = await call("POST", `/sessions/${encodeURIComponent(sessionId)}/tracks/new`, { tracks: tracks.map((t) => ({ location: "remote", sessionId: t.sessionId, trackName: t.name })), }); // Each pulled track comes back with the mid it was given here, the same order as asked. const placed = (answer.tracks ?? []).map((t, i) => ({ mid: t.mid ?? null, sessionId: t.sessionId ?? tracks[i]?.sessionId ?? "", name: t.trackName ?? tracks[i]?.name ?? "" })); return { sdp: answer.sessionDescription?.sdp ?? null, renegotiate: answer.requiresImmediateRenegotiation === true, tracks: placed }; }, async renegotiate(sessionId, sdp) { await call("PUT", `/sessions/${encodeURIComponent(sessionId)}/renegotiate`, { sessionDescription: { type: "answer", sdp } }); }, async close(sessionId, mids) { await call("PUT", `/sessions/${encodeURIComponent(sessionId)}/tracks/close`, { tracks: mids.map((mid) => ({ mid })), force: false }); }, }; } /** The SFU this Worker is configured for, or null: a group call then carries signalling but no media. */ export function sfuOf(env: Env): Sfu | null { return env.CF_SFU_APP_ID && env.CF_SFU_APP_SECRET ? cloudflareSfu(env) : null; }