Cotton code
107 lines · 5.1 KB · TypeScriptRaw
/** * The ICE servers a call is handed (Cotton Calling, 12 Nov 2026): STUN always, * then a TURN relay for the calls that cannot connect directly. Which relay is * one small interface, so a self-hosted coturn is a config change: * * - `TURN_PROVIDER=cloudflare` (the default): Cloudflare Realtime TURN mints *   short-lived credentials per call from the key's API token. * - `TURN_PROVIDER=coturn`: coturn's static-auth-secret, the TURN REST *   convention: the username is `<unix expiry>:<user>`, the credential *   base64(HMAC-SHA1(secret, username)), so coturn checks it with no call back. * * A Worker with no relay configured answers STUN alone: a call between two * phones behind symmetric NATs then fails as `failed`, never silently relayed * somewhere else. */import { isProduction, type Env } from "../env.ts";import { refuse } from "../http.ts";export interface IceServer {  urls: string[];  username?: string;  credential?: string;}export interface TurnProvider {  servers(ttl: number, user: string): Promise<IceServer[]>;}/** How long a minted credential lives: a longer call fetches again on its next ICE restart. */export const ICE_TTL_SECONDS = 3600;export const DEFAULT_STUN = "stun:stun.cloudflare.com:3478";const CLOUDFLARE_TURN = "https://rtc.live.cloudflare.com";function list(value: string | undefined): string[] {  return (value ?? "").split(",").map((s) => s.trim()).filter(Boolean);}/** Cloudflare Realtime TURN: one POST per call, answered `{ iceServers: [...] }` (or the older `{ iceServers: {...} }`). */export function cloudflareTurn(env: Pick<Env, "CF_TURN_KEY_ID" | "CF_TURN_API_TOKEN" | "CF_TURN_URL" | "ENV_LABEL">): TurnProvider {  const base = env.CF_TURN_URL?.replace(/\/+$/, "");  if (base && isProduction(env as Env)) refuse(503, "turn_misconfigured", "CF_TURN_URL is for a test Worker's fake relay, never production");  return {    async servers(ttl) {      const res = await fetch(`${base ?? CLOUDFLARE_TURN}/v1/turn/keys/${encodeURIComponent(env.CF_TURN_KEY_ID ?? "")}/credentials/generate-ice-servers`, {        method: "POST",        headers: { authorization: `Bearer ${env.CF_TURN_API_TOKEN ?? ""}`, "content-type": "application/json" },        body: JSON.stringify({ ttl }),      });      if (!res.ok) throw new Error(`the relay answered ${res.status}`);      const body = (await res.json()) as { iceServers?: unknown };      const raw = Array.isArray(body.iceServers) ? body.iceServers : body.iceServers ? [body.iceServers] : [];      return raw.map(serverOf).filter((s): s is IceServer => s !== null);    },  };}function serverOf(raw: unknown): IceServer | null {  if (!raw || typeof raw !== "object") return null;  const r = raw as Record<string, unknown>;  const urls = (Array.isArray(r.urls) ? r.urls : [r.urls]).filter((u): u is string => typeof u === "string");  if (!urls.length) return null;  const server: IceServer = { urls };  if (typeof r.username === "string") server.username = r.username;  if (typeof r.credential === "string") server.credential = r.credential;  return server;}/** coturn with `use-auth-secret` / `static-auth-secret`: credentials made here, checked there by the same HMAC. */export function coturn(env: Pick<Env, "COTURN_SECRET" | "COTURN_URLS">, now: () => number = Date.now): TurnProvider {  return {    async servers(ttl, user) {      const urls = list(env.COTURN_URLS);      if (!urls.length || !env.COTURN_SECRET) return [];      const username = `${Math.floor(now() / 1000) + ttl}:${user}`;      return [{ urls, username, credential: await coturnCredential(env.COTURN_SECRET, username) }];    },  };}export async function coturnCredential(secret: string, username: string): Promise<string> {  const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-1" }, false, ["sign"]);  const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(username)));  return btoa(String.fromCharCode(...mac));}/** The relay the Worker's vars name, or null when none is configured. */export function providerOf(env: Env): TurnProvider | null {  const which = env.TURN_PROVIDER ?? "cloudflare";  if (which === "coturn") return env.COTURN_SECRET && list(env.COTURN_URLS).length ? coturn(env) : null;  if (which === "cloudflare") return env.CF_TURN_KEY_ID && env.CF_TURN_API_TOKEN ? cloudflareTurn(env) : null;  return null;}/** * STUN first, then the relay's servers. A relay that fails leaves STUN alone, * said by `relay: false`, so a phone can tell a call that may not connect. */export async function iceServers(env: Env, user: string, provider: TurnProvider | null = providerOf(env)): Promise<{ iceServers: IceServer[]; ttl: number; relay: boolean }> {  const stun: IceServer = { urls: list(env.STUN_URLS).length ? list(env.STUN_URLS) : [DEFAULT_STUN] };  if (!provider) return { iceServers: [stun], ttl: ICE_TTL_SECONDS, relay: false };  try {    const relayed = await provider.servers(ICE_TTL_SECONDS, user);    return { iceServers: [stun, ...relayed], ttl: ICE_TTL_SECONDS, relay: relayed.length > 0 };  } catch {    return { iceServers: [stun], ttl: ICE_TTL_SECONDS, relay: false };  }}