/** * Cotton Calling on a person's object (12 Nov 2026): the routes a phone calls * on its own object, the ring one object hands another, and the four small * tables that hold what the Worker needs to route a call and nothing more. * The wire is the calling protocol written into the build session's report * (kept outside the repository); the room is src/calling/room.ts. * * THE TABLES are the Worker's own, never a kit's: never synced, never read by * an assistant, never another object's. * - `call_device`: this object's phones' VoIP push tokens, one per device, * written by that device's credential alone and dropped at its sign-out. * - `call_block`: the numbers the owner blocked, as HMAC-SHA256 under this * object's own call key (`call_key`), never the number. * - `call_ring`: a ring being delivered now — the room, the devices rung, the * caller's number to show them. Gone when the room ends, or two minutes on. * - `call_can`: what each phone said it speaks (`{ t: "hello", can }` as its chat * socket opens, or `can` with its push token). A phone that said nothing is * rung exactly as before CALLS FIX 1 (CALLS FIX 2). * - `call_told`: a missed call kept for one phone that speaks it, sealed for * that phone's chat key (never the number in the clear), for a day, told at * most once. * - `call_hit`: the hour's counts for the limits — this object's own devices' * starts, and the rings arriving keyed by HMAC of the caller's object. Rows * over an hour old go at every use. * * THE HOP. A start answers the caller at once, before the Directory is asked: * the answer is the same whether or not the number has Cotton. Off the * answer, the caller's object finds the number's object and asks it, by RPC * (no outside request reaches an RPC), to ring. That object may drop the ring * — blocked, over its limit, no phone with a token — and says nothing back: * the caller learns of a ring only from a device's accept, decline or busy. */ import { directory } from "../directory.ts"; import type { Env } from "../env.ts"; import { json, readJson, refuse } from "../http.ts"; import { normalizePhone } from "../protocol.ts"; import { canRing, frameData, PLATFORMS, push, type Platform, type PushDevice, type PushPayload } from "./push.ts"; import { callRoom, canOf, MEMBERS_MAX, newRoomId, RING_FOR_MS, type Invited, type StopReason } from "./room.ts"; import { iceServers } from "./turn.ts"; import { sealFor, type RingHint } from "../chat/seal.ts"; import * as gate from "../chat/gate.ts"; export const SCHEMA = ` CREATE TABLE IF NOT EXISTS call_device (device_id TEXT PRIMARY KEY, platform TEXT NOT NULL, token TEXT NOT NULL, topic TEXT NOT NULL, sandbox INTEGER NOT NULL, updated_at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS call_block (key TEXT PRIMARY KEY, created_at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS call_ring (room TEXT PRIMARY KEY, member TEXT NOT NULL, devices TEXT NOT NULL, video INTEGER NOT NULL, from_number TEXT NOT NULL, created_at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS call_hit (who TEXT NOT NULL, at INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS call_hit_by_who ON call_hit (who, at); CREATE TABLE IF NOT EXISTS call_key (id INTEGER PRIMARY KEY CHECK (id = 1), secret TEXT NOT NULL); CREATE TABLE IF NOT EXISTS call_can (device_id TEXT PRIMARY KEY, can TEXT NOT NULL, at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS call_told (room TEXT NOT NULL, device_id TEXT NOT NULL, box TEXT NOT NULL, reason TEXT NOT NULL, at INTEGER NOT NULL, ended INTEGER NOT NULL, PRIMARY KEY (room, device_id)); `; /** * Columns call_ring gained after it was first made: the group, for a ring sealed again; the phones that acked it; the * phones waiting for a push should their ack not come (`[{ id, at }]`, so an alarm finds them after a restart). * CALLS FIX 1's `call_missed` (the caller's number unsealed for a month) never shipped and goes. */ export function migrate(sql: SqlStorage): void { const have = new Set(sql.exec<{ name: string }>("PRAGMA table_info(call_ring)").toArray().map((c) => c.name)); if (!have.has("group_id")) sql.exec("ALTER TABLE call_ring ADD COLUMN group_id TEXT"); if (!have.has("acked")) sql.exec("ALTER TABLE call_ring ADD COLUMN acked TEXT NOT NULL DEFAULT '[]'"); if (!have.has("waiting")) sql.exec("ALTER TABLE call_ring ADD COLUMN waiting TEXT NOT NULL DEFAULT '[]'"); sql.exec("DROP TABLE IF EXISTS call_missed"); } /** What a phone says it speaks: `ring_ack` (it acks each ring frame, takes a late ring and a missed call kept for it). */ export const CAN = ["ring_ack"] as const; /** A phone's own starts in an hour; over it the start is refused, which says nothing about whom it called. */ export const STARTS_PER_HOUR = 30; /** Rings from one caller this object takes in ten minutes, and from everyone in an hour; the rest are dropped unsaid. */ export const RINGS_PER_CALLER_10_MIN = 5; export const RINGS_PER_HOUR = 30; /** A ring nobody ended is swept after this. */ export const RING_KEPT_MS = 2 * 60_000; /** * A ring handed to a socket is not proof the phone rang (a socket the object still holds can belong to a phone that is * gone): the phone acks the frame (`{ t: "ring_ack", room }`), and a phone that has not within this is pushed as well. */ export const RING_ACK_MS = 2_000; /** How long a ring stays live for a phone that opens its socket late: the room's own ring (room.ts `RING_FOR_MS`). */ export const RING_LIVE_MS = 45_000; /** A missed call a phone was not told of is kept for its next socket this long: a day (sealed for that phone alone). */ export const MISSED_KEPT_MS = 24 * 3_600_000; /** The stops that leave a missed call: nobody here answered (a ring answered or declined on another phone does not). */ const MISSED_STOPS: ReadonlySet = new Set(["missed", "cancelled"]); /** The apps a push token may be for: Cotton Calling, Cotton Chat (calls moved into Chat, 19 Nov 2026) and their development builds. */ export const TOPICS = ["com.cottondb.calling", "com.cottondb.calling.dev", "com.cottondb.messages", "com.cottondb.messages.dev"]; const HOUR = 3_600_000; const ROOM = /^[0-9a-f]{32}$/; /** A Cotton group's id (cotton-core chat/group.rs `is_group_id`). */ const GROUP = /^[0-9a-f]{32}$/; /** An APNs token is hex; an FCM registration token is base64url-ish with a colon. */ const PUSH_TOKEN: Record = { ios: /^[0-9a-fA-F]{32,200}$/, android: /^[A-Za-z0-9_:-]{32,4096}$/ }; export interface CallHost { sql: SqlStorage; env: Env; /** This object's slug, as the Directory and the rooms name it. */ slug: string; ownerPhone: string | null; waitUntil(work: Promise): void; /** The chat sockets a device of this owner holds open (src/chat/chat.ts): a ring goes there too, push or none. */ sockets?(deviceId: string): WebSocket[]; /** The object's alarm comes by `at` (the push a phone's missing ack calls for, should the object restart before). */ wake?(at: number): void; } export interface Ring { room: string; /** The room's member this ring is for. */ member: string; /** The inviter's number, shown to the callee's phones through this object. */ from: string; fromSlug: string; video: boolean; /** The Cotton group the call was placed from (its random id), sealed into the ring's box so the ring names the group. */ group?: string | null; } /** The routes under /v1/calls, for a phone signed in on this object; null for any other path. */ export async function route(host: CallHost, deviceId: string | null, request: Request, url: URL): Promise { const path = url.pathname; if (path !== "/v1/calls" && !path.startsWith("/v1/calls/")) return null; if (!deviceId) refuse(401, "sign_in", "calls are placed from a signed-in phone"); const method = request.method; sweep(host.sql); if (method === "POST" && path === "/v1/calls") return start(host, deviceId, await readJson(request)); if (method === "GET" && path === "/v1/calls/ice") return json(await iceServers(host.env, deviceId)); // A ring or a stop that came by push, acked as one that came over the socket is (CALLS FIX 2, M3). if (method === "POST" && path === "/v1/calls/ack") { const room = (await readJson(request)).room; if (typeof room !== "string" || !ROOM.test(room)) refuse(400, "bad_room", "room: the call's room id"); ringAck(host, deviceId, room); return json({ ok: true }); } if (path === "/v1/calls/device") { if (method === "POST") { const body = await readJson(request); // A phone that rings by push alone says what it speaks with its token, as one with a socket says it in `hello`. if (body.can !== undefined) hello(host, deviceId, body.can); return putDevice(host.sql, deviceId, body); } if (method === "DELETE") { forgetDevice(host.sql, deviceId); return json({ ok: true }); } } if (method === "POST" && (path === "/v1/calls/block" || path === "/v1/calls/unblock")) { const number = numberOf((await readJson(request)).number); const key = await keyOf(host.sql, number); if (path === "/v1/calls/block") host.sql.exec("INSERT OR IGNORE INTO call_block (key, created_at) VALUES (?, ?)", key, new Date().toISOString()); else host.sql.exec("DELETE FROM call_block WHERE key = ?", key); return json({ ok: true }); } if (method === "GET" && path === "/v1/calls/blocked") return json({ blocked: await blocked(host.sql, numberOf(url.searchParams.get("number"))) }); const status = /^\/v1\/calls\/([0-9a-f]{32})\/status$/.exec(path); if (method === "GET" && status) return callStatus(host, status[1]!); const action = /^\/v1\/calls\/([0-9a-f]{32})\/(join|enter|decline|end|invite)$/.exec(path); if (method === "POST" && action) { const room = action[1]!; // The body is read whole on every action, so the request is done with before the answer goes. const text = await request.text(); if (action[2] === "join") return join(host, deviceId, room, canOf(said(text).can)); if (action[2] === "enter") return enter(host, deviceId, room, canOf(said(text).can)); if (action[2] === "invite") return invite(host, deviceId, room, said(text).to); if (action[2] === "decline") { await callRoom(host.env, room).decline(host.slug, deviceId, said(text).busy === true); return json({ ok: true }); } await callRoom(host.env, room).hangUp(host.slug, deviceId); return json({ ok: true }); } refuse(404, "not_found", `nothing answers ${method} ${path}`); } /** A phone places a call to one person or several: a room, its credential, the ICE servers; the rings go off this answer. */ async function start(host: CallHost, deviceId: string, body: Record): Promise { const to = numbersOf(body.to); if (!host.ownerPhone) refuse(409, "no_owner", "this object has no number to call from"); const ownerPhone = host.ownerPhone; const invitees = to.filter((n) => n !== ownerPhone); if (!invitees.length) refuse(400, "bad_number", "a call needs someone else's number"); const group = groupOf(body.group); // First contact: each callee new to this owner costs one of their new numbers, before anything is looked up // (src/chat/gate.ts); a group's call is a member's word. Their object rings only for someone its owner accepted. await gate.firstContacts(host, invitees, group ? "member" : "one"); starts(host, deviceId, invitees.length); const room = newRoomId(); const video = body.video === true; const opened = await callRoom(host.env, room).init({ room, callerSlug: host.slug, callerNumber: ownerPhone, callerDevice: deviceId, video, invitees, group, can: canOf(body.can) }); const ice = await iceServers(host.env, room); ringAll(host, room, opened.members, ownerPhone, video, group); // `me` and `mode` are what the phone's core reads (crates/cotton-core/src/calling/wire.rs `Started`). return json({ room, me: "caller", mode: group || invitees.length > 1 ? "sfu" : "p2p", ...(group ? { group } : {}), credential: opened.credential, members: opened.members, iceServers: ice.iceServers, ttl: ice.ttl, ringFor: RING_FOR_MS / 1000 }); } /** A phone in the call invites more people; a one-to-one that gains a third moves to the SFU. */ async function invite(host: CallHost, deviceId: string, room: string, to: unknown): Promise { const numbers = numbersOf(to); await gate.firstContacts(host, numbers, "one"); starts(host, deviceId, numbers.length); const answer = await callRoom(host.env, room).invite(host.slug, deviceId, numbers); if (!answer) refuse(404, "not_in_call", "this phone is not in that call"); if ("full" in answer) refuse(409, "too_many_members", `a call holds at most ${MEMBERS_MAX} people`); ringAll(host, room, answer.members, answer.from, answer.video); return json({ ok: true, members: answer.members }); } /** Each number rung counts as one of this phone's starts. */ function starts(host: CallHost, deviceId: string, rung: number): void { const who = `out:${deviceId}`; if (count(host.sql, who, HOUR) + rung > STARTS_PER_HOUR) refuse(429, "too_many_calls", "Too many calls from this phone in the last hour; try again later."); for (let i = 0; i < rung; i += 1) hit(host.sql, who); } function ringAll(host: CallHost, room: string, members: Invited[], from: string, video: boolean, group: string | null = null): void { for (const member of members) host.waitUntil(ringOut(host, { room, member: member.id, from, fromSlug: host.slug, video, ...(group ? { group } : {}) }, member.number)); } /** A group's id as a start names it, or null; anything else is refused. */ function groupOf(raw: unknown): string | null { if (raw === undefined || raw === null) return null; if (typeof raw !== "string" || !GROUP.test(raw)) refuse(400, "bad_group", "group: a Cotton group's id, 32 hex"); return raw; } /** The number's object is found and asked to ring; whatever it does is not this object's to know. */ async function ringOut(host: CallHost, ring: Ring, to: string): Promise { try { const slug = await directory(host.env).lookup(to); if (!slug || slug === host.slug) return; await host.env.BUSINESS.get(host.env.BUSINESS.idFromName(slug), { locationHint: "apac" }).callRing(ring); } catch { // A ring that could not be handed over reads as one nobody answered. } } /** * Another object's ring arriving here: dropped unsaid when the caller is * blocked or over the limits, or no phone here has a push token; else every * phone is pushed `{ room, video, box }` (`box`: the caller sealed for that * phone's chat key) and the room told whom it rang. */ export async function ringIn(host: CallHost, ring: Ring): Promise { if (!ROOM.test(ring.room)) return; sweep(host.sql); if (await blocked(host.sql, ring.from)) return; // Rung only by someone this owner accepted, or a member of the group the ring names (src/chat/gate.ts): a stranger's // ring goes nowhere and is told nothing, as a number nobody holds. if (!(await gate.admits(host.sql, ring.from, ring.group && GROUP.test(ring.group) ? ring.group : null))) return; const who = `in:${await mac(host.sql, ring.fromSlug)}`; const fromThem = count(host.sql, who, 10 * 60_000); const fromAll = host.sql.exec<{ n: number }>("SELECT count(*) AS n FROM call_hit WHERE who LIKE 'in:%' AND at >= ?", Date.now() - HOUR).one().n; hit(host.sql, who); if (fromThem >= RINGS_PER_CALLER_10_MIN || fromAll >= RINGS_PER_HOUR) return; const devices = devicesOf(host.sql); // A phone with its chat socket open is rung over it too: one whose push token never came (no Play services, an // emulator: the Android chat walk's second emulator never rang) rings while the app is open. const open = openDevices(host); const pushable = devices.length > 0 && canRing(host.env, devices.map((d) => d.platform)); const group = ring.group && GROUP.test(ring.group) ? ring.group : null; if (!pushable && !open.length) { // No phone to ring now. Kept only when a phone here speaks the new way: one that opens its socket while the ring is // live rings for the rest (`redeliver` tells the room then), and a missed call is kept for it if none does. A phone // that never said so is rung as before: not at all. if (speakers(host.sql).length && (await callRoom(host.env, ring.room).waiting(ring.member, host.slug))) { host.sql.exec("INSERT OR REPLACE INTO call_ring (room, member, devices, video, from_number, created_at, group_id, acked, waiting) VALUES (?, ?, '[]', ?, ?, ?, ?, '[]', '[]')", ring.room, ring.member, ring.video ? 1 : 0, ring.from, Date.now(), group); } return; } const ids = [...new Set([...(pushable ? devices.map((d) => d.deviceId) : []), ...open])]; const rungAt = Date.now(); host.sql.exec("INSERT OR REPLACE INTO call_ring (room, member, devices, video, from_number, created_at, group_id, acked, waiting) VALUES (?, ?, ?, ?, ?, ?, ?, '[]', '[]')", ring.room, ring.member, JSON.stringify(ids), ring.video ? 1 : 0, ring.from, rungAt, group); if (!(await callRoom(host.env, ring.room).ringing(ring.member, host.slug, ids))) { host.sql.exec("DELETE FROM call_ring WHERE room = ?", ring.room); return; } const byId = new Map(devices.map((d) => [d.deviceId, d])); const waiting: string[] = []; await Promise.all( ids.map(async (id) => { const box = await sealedFor(host.sql, id, ring.room, ring.from, ring.video, group); // A phone that speaks the new way is told when the ring began, so one that hears it late starts it there. const payload: PushPayload = { room: ring.room, video: ring.video, ...(box ? { box } : {}), ...(speaks(host.sql, id) ? { at: rungAt } : {}) }; const device = byId.get(id); // Over its open socket when it has one (at once, and the same box), else by push: as on main for a phone that // has not said it acks. One that has is pushed as well unless its ack comes within RING_ACK_MS (CALLS FIX 1). if (frameTo(host, id, payload)) { if (device && pushable && speaks(host.sql, id)) waiting.push(id); return; } if (device && pushable) await pushAll(host, [device], payload); }), ); if (waiting.length) { const at = Date.now() + RING_ACK_MS; host.sql.exec("UPDATE call_ring SET waiting = ? WHERE room = ?", JSON.stringify(waiting.map((id) => ({ id, at }))), ring.room); // Pushed by whichever comes first: this object, still awake 2 s on, or its alarm after a restart. host.wake?.(at); host.waitUntil(new Promise((resolve) => setTimeout(resolve, RING_ACK_MS)).then(() => pushWaiting(host))); } } /** Phones whose ack did not come in time are pushed, once; a ring that ended, or an ack, takes a phone off the list. */ export async function pushWaiting(host: CallHost): Promise { const now = Date.now(); const rows = host.sql.exec<{ room: string; video: number; from_number: string; group_id: string | null; acked: string; waiting: string; created_at: number }>( "SELECT room, video, from_number, group_id, acked, waiting, created_at FROM call_ring WHERE waiting != '[]'").toArray(); const byId = new Map(devicesOf(host.sql).map((d) => [d.deviceId, d])); for (const r of rows) { const acked = new Set(JSON.parse(r.acked) as string[]); const all = JSON.parse(r.waiting) as { id: string; at: number }[]; const due = all.filter((w) => w.at <= now); if (!due.length) continue; // Off the list before any await: a second pass never pushes the same phone twice. host.sql.exec("UPDATE call_ring SET waiting = ? WHERE room = ?", JSON.stringify(all.filter((w) => w.at > now)), r.room); for (const w of due) { const device = byId.get(w.id); if (acked.has(w.id) || !device) continue; const box = await sealedFor(host.sql, w.id, r.room, r.from_number, r.video === 1, r.group_id); await pushAll(host, [device], { room: r.room, video: r.video === 1, ...(box ? { box } : {}), at: r.created_at }); } } } /** When the next phone waiting for its ack is due a push; null when none waits. */ export function nextWaiting(sql: SqlStorage): number | null { let next: number | null = null; for (const r of sql.exec<{ waiting: string }>("SELECT waiting FROM call_ring WHERE waiting != '[]'").toArray()) { for (const w of JSON.parse(r.waiting) as { at: number }[]) next = next === null ? w.at : Math.min(next, w.at); } return next; } /** A phone said what it speaks: kept, so it is rung the new way from now on (CALLS FIX 2). */ export function hello(host: CallHost, deviceId: string, can: unknown): boolean { const said = Array.isArray(can) ? can.filter((c): c is string => typeof c === "string" && (CAN as readonly string[]).includes(c)) : []; if (!said.length) return false; host.sql.exec("INSERT INTO call_can (device_id, can, at) VALUES (?, ?, ?) ON CONFLICT (device_id) DO UPDATE SET can = excluded.can, at = excluded.at", deviceId, JSON.stringify(said), Date.now()); return true; } /** Whether the phone said it acks rings (and so takes a late ring and a missed call kept for it). */ function speaks(sql: SqlStorage, deviceId: string): boolean { const row = sql.exec<{ can: string }>("SELECT can FROM call_can WHERE device_id = ?", deviceId).toArray()[0]; return !!row && (JSON.parse(row.can) as string[]).includes("ring_ack"); } /** The phones here that said they speak the new way and still hold a chat key (a phone whose chat device went is not one). */ function speakers(sql: SqlStorage): string[] { try { return sql.exec<{ device_id: string; can: string }>("SELECT c.device_id, c.can FROM call_can c JOIN chat_device d ON d.device_id = c.device_id").toArray().filter((r) => (JSON.parse(r.can) as string[]).includes("ring_ack")).map((r) => r.device_id); } catch { return []; } } /** What a chat socket's `{ t: "hello", can }` says the phone speaks; null for any other frame. */ export function helloOf(text: string): string[] | null { if (!text.includes("hello")) return null; try { const frame = JSON.parse(text) as { t?: unknown; can?: unknown }; return frame.t === "hello" && Array.isArray(frame.can) ? frame.can.filter((c): c is string => typeof c === "string") : null; } catch { return null; } } /** Who is calling, sealed for this phone's chat key: the ring (or its missed stop) names them, and the push service reads nothing. */ async function sealedFor(sql: SqlStorage, deviceId: string, room: string, from: string, video: boolean, group: string | null): Promise { const key = chatKeyOf(sql, deviceId); const hint: RingHint = { v: 1, ring: room, from, video, ...(group ? { group } : {}) }; return key ? await sealFor(key, hint) : null; } /** The room a chat socket's `{ t: "ring_ack", room }` names; null for any other frame. */ export function ringAckOf(text: string): string | null { if (!text.includes("ring_ack")) return null; try { const frame = JSON.parse(text) as { t?: unknown; room?: unknown }; return frame.t === "ring_ack" && typeof frame.room === "string" ? frame.room : null; } catch { return null; } } /** * A phone's ack (`{ t: "ring_ack", room }` over its socket, or POST /v1/calls/ack for what came by push): it has the * ring (it rings: no push follows, and a socket opening later does not ring it again), or it has the stop (its * missed call is not kept for it). */ export function ringAck(host: CallHost, deviceId: string, room: string): void { if (!ROOM.test(room)) return; const row = host.sql.exec<{ acked: string }>("SELECT acked FROM call_ring WHERE room = ?", room).toArray()[0]; if (row) { const acked = new Set(JSON.parse(row.acked) as string[]).add(deviceId); host.sql.exec("UPDATE call_ring SET acked = ? WHERE room = ?", JSON.stringify([...acked]), room); } host.sql.exec("DELETE FROM call_told WHERE room = ? AND device_id = ?", room, deviceId); } /** * A phone that speaks the new way said so as its chat socket opened (`hello`): a ring still live rings it for the rest * (a phone launched 38 s into the ring, or one whose earlier frame went to a socket that was gone), and each missed * call kept for it is told, as a missed call (`kind: "missed"`: it writes the row and rings nothing), until the phone * acks it or a day passes. A phone that never said hello is never called here. */ export async function redeliver(host: CallHost, deviceId: string): Promise { sweep(host.sql); const now = Date.now(); const rings = host.sql.exec<{ room: string; member: string; devices: string; video: number; from_number: string; group_id: string | null; acked: string; created_at: number }>( "SELECT room, member, devices, video, from_number, group_id, acked, created_at FROM call_ring WHERE created_at >= ?", now - RING_LIVE_MS).toArray(); for (const r of rings) { if ((JSON.parse(r.acked) as string[]).includes(deviceId)) continue; const devices = JSON.parse(r.devices) as string[]; if (!devices.includes(deviceId)) { // The room lets in only the phones it was told rang: this one is told now, or its join is refused. if (!(await callRoom(host.env, r.room).ringing(r.member, host.slug, [deviceId]))) continue; host.sql.exec("UPDATE call_ring SET devices = ? WHERE room = ?", JSON.stringify([...devices, deviceId]), r.room); } const box = await sealedFor(host.sql, deviceId, r.room, r.from_number, r.video === 1, r.group_id); frameTo(host, deviceId, { room: r.room, video: r.video === 1, ...(box ? { box } : {}), at: r.created_at }); } const told = host.sql.exec<{ room: string; box: string; reason: string; at: number; ended: number }>( "SELECT room, box, reason, at, ended FROM call_told WHERE device_id = ? ORDER BY ended", deviceId).toArray(); // Each is told as a missed call and kept until the phone acks it (its ring_ack for the frame): a frame handed to a // socket is not proof either (CALLS FIX 3). A second telling writes nothing new: the core never rewrites a row. for (const m of told) frameTo(host, deviceId, { room: m.room, stop: m.reason, box: m.box, at: m.at, ended: m.ended }, "missed"); } /** Devices of this owner with a chat socket open now. */ function openDevices(host: CallHost): string[] { if (!host.sockets) return []; try { const ids = host.sql.exec<{ device_id: string }>("SELECT device_id FROM chat_device").toArray().map((r) => r.device_id); return ids.filter((id) => host.sockets!(id).length > 0); } catch { return []; } } /** * A ring or its stop handed to a device's open chat sockets, as the FCM data * message says it (`{ t: "ring", kind: "ring", room, video: "1"|"0", box? }`, * `{ t: "ring", kind: "stop", room, stop }`), so the phone's one seam takes it. * True when a socket took it. */ function frameTo(host: CallHost, deviceId: string, payload: PushPayload, kind: "stop" | "missed" = "stop"): boolean { const frame = JSON.stringify({ t: "ring", ...frameData(payload, kind) }); let handed = false; for (const ws of host.sockets?.(deviceId) ?? []) { try { ws.send(frame); handed = true; } catch { // Closing: the push, if it has one. } } return handed; } /** A device's published chat key, when it has one (src/chat/chat.ts `chat_device`). */ function chatKeyOf(sql: SqlStorage, deviceId: string): string | null { try { return sql.exec<{ public_key: string }>("SELECT public_key FROM chat_device WHERE device_id = ?", deviceId).toArray()[0]?.public_key ?? null; } catch { return null; } } /** * The room ended or was answered: the ring goes, and the phones still ringing are stopped. A phone that never said it * speaks the new way is stopped exactly as on main: over its socket, else by push, `{ room, stop }`. One that did is * stopped the same way, and on a missed call the stop names who called (sealed for it) and when, so it writes its * Missed row even if it never heard the ring; and a missed call is kept for each such phone the stop did not reach * and that has not acked it: kept until that phone acks it or a day passes, and given again each time its socket says * hello. A push the push service accepted is not proof the phone has it (Apple's go with expiration 0, Google's live * 45 s), so it never counts as told (CALLS FIX 3). */ export async function stopRing(host: CallHost, room: string, stop: StopReason | null, except: string | null): Promise { const row = host.sql.exec<{ devices: string; from_number: string; video: number; group_id: string | null; created_at: number; acked: string }>("SELECT devices, from_number, video, group_id, created_at, acked FROM call_ring WHERE room = ?", room).toArray()[0]; if (!row) return; host.sql.exec("DELETE FROM call_ring WHERE room = ?", room); if (!stop) return; const missed = MISSED_STOPS.has(stop); const at = row.created_at; const ended = Date.now(); const rung = new Set((JSON.parse(row.devices) as string[]).filter((id) => id !== except)); const acked = new Set(JSON.parse(row.acked) as string[]); const byId = new Map(devicesOf(host.sql).map((d) => [d.deviceId, d])); const boxes = new Map(); const boxOf = async (id: string) => { if (!boxes.has(id)) boxes.set(id, (await sealedFor(host.sql, id, room, row.from_number, row.video === 1, row.group_id)) ?? ""); return boxes.get(id) || null; }; await Promise.all( [...rung].map(async (id) => { const box = missed && speaks(host.sql, id) ? await boxOf(id) : null; const payload: PushPayload = speaks(host.sql, id) ? { room, stop, ...(box ? { box, at, ended } : {}) } : { room, stop }; // A phone rung over its socket is stopped over it; the rest by push. A phone that speaks the new way and never // acked the ring's frame (its socket may be one it left; it was pushed the ring after RING_ACK_MS) is pushed the // stop as well, so the ring it was pushed ends (CALLS FIX 3). const framed = frameTo(host, id, payload); if (framed && !(speaks(host.sql, id) && !acked.has(id))) return; const device = byId.get(id); if (device) await pushAll(host, [device], payload); }), ); if (!missed) return; // Kept for each phone that speaks the new way until it acks it (CALLS FIX 3): neither a socket that took the stop // nor a push the push service accepted proves the phone has it. for (const id of speakers(host.sql)) { if (id === except) continue; const box = await boxOf(id); if (!box) continue; host.sql.exec("INSERT OR IGNORE INTO call_told (room, device_id, box, reason, at, ended) VALUES (?, ?, ?, ?, ?, ?)", room, id, box, stop, at, ended); } } /** A rung phone joins: who is calling, and its own credential for the room. */ async function join(host: CallHost, deviceId: string, room: string, can: string[] = []): Promise { const row = host.sql.exec<{ member: string; devices: string; video: number; from_number: string }>("SELECT member, devices, video, from_number FROM call_ring WHERE room = ?", room).toArray()[0]; if (!row || !(JSON.parse(row.devices) as string[]).includes(deviceId)) refuse(404, "not_ringing", "this call is not ringing here"); const joined = await callRoom(host.env, room).join(row.member, host.slug, deviceId, can); if (!joined) refuse(404, "not_ringing", "this call is not ringing here"); const ice = await iceServers(host.env, room); // `me` is the member id the phone's core reads (`Joined`); the mode comes on the socket, as the room says it when it opens. return json({ room, member: row.member, me: row.member, from: row.from_number, video: row.video === 1, ...(joined.group ? { group: joined.group } : {}), credential: joined.credential, iceServers: ice.iceServers, ttl: ice.ttl }); } /** * A phone of a group call's member comes in late, or back: no ring needed, * the room checks this object is one of its members. The same answer as a * join, so the phone goes on as from an accepted ring. */ async function enter(host: CallHost, deviceId: string, room: string, can: string[] = []): Promise { const entered = await callRoom(host.env, room).enter(host.slug, host.ownerPhone ?? "", deviceId, can); if (entered === "here") refuse(409, "in_call_elsewhere", "You're in this call on another phone."); if (!entered) refuse(404, "no_call", "This call has ended."); const ice = await iceServers(host.env, room); return json({ room, member: entered.member, me: entered.member, from: entered.from, video: entered.video, group: entered.group, mode: "sfu", credential: entered.credential, iceServers: ice.iceServers, ttl: ice.ttl }); } /** Whether a call this object is a member of goes on, and who is in it: a call it is no member of reads as over. */ async function callStatus(host: CallHost, room: string): Promise { const status = await callRoom(host.env, room).status(host.slug, host.ownerPhone ?? ""); return json(status ?? { live: false }); } /** A device's sign-out, or its own DELETE: its push token goes. */ export function forgetDevice(sql: SqlStorage, deviceId: string): void { sql.exec("DELETE FROM call_device WHERE device_id = ?", deviceId); // What it said it speaks and what was kept for it go too (CALLS FIX 3): a signed-out phone collects no missed calls // and keeps no ring alive for a phone that is not there. A phone still in use says hello again as its socket opens. sql.exec("DELETE FROM call_can WHERE device_id = ?", deviceId); sql.exec("DELETE FROM call_told WHERE device_id = ?", deviceId); } function putDevice(sql: SqlStorage, deviceId: string, body: Record): Response { const platform = body.platform as Platform; if (!PLATFORMS.includes(platform)) refuse(400, "bad_platform", `platform: one of ${PLATFORMS.join(", ")}`); const token = typeof body.token === "string" ? body.token.trim() : ""; if (!PUSH_TOKEN[platform].test(token)) refuse(400, "bad_token", platform === "ios" ? "token: the VoIP push token as hex" : "token: the FCM registration token"); let topic = ""; if (platform === "ios") { if (typeof body.topic !== "string" || !TOPICS.includes(body.topic)) refuse(400, "bad_topic", `topic: one of ${TOPICS.join(", ")}`); topic = body.topic; } sql.exec( "INSERT INTO call_device (device_id, platform, token, topic, sandbox, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (device_id) DO UPDATE SET platform = excluded.platform, token = excluded.token, topic = excluded.topic, sandbox = excluded.sandbox, updated_at = excluded.updated_at", deviceId, platform, platform === "ios" ? token.toLowerCase() : token, topic, platform === "ios" && body.sandbox === true ? 1 : 0, new Date().toISOString(), ); return json({ ok: true }); } async function pushAll(host: CallHost, devices: (PushDevice & { deviceId: string })[], payload: PushPayload): Promise { const outcomes = await Promise.all(devices.map((d) => push(host.env, d, payload))); outcomes.forEach((outcome, i) => { if (outcome === "gone") forgetDevice(host.sql, devices[i]!.deviceId); }); } function devicesOf(sql: SqlStorage): (PushDevice & { deviceId: string })[] { return sql .exec<{ device_id: string; platform: Platform; token: string; topic: string; sandbox: number }>("SELECT device_id, platform, token, topic, sandbox FROM call_device ORDER BY device_id") .toArray() .map((r) => ({ deviceId: r.device_id, platform: r.platform, token: r.token, topic: r.topic, sandbox: r.sandbox === 1 })); } /** A small JSON body, or nothing when it is empty or not an object. */ export function said(text: string): Record { try { const parsed: unknown = text.trim() ? JSON.parse(text) : {}; return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record) : {}; } catch { return {}; } } /** One number or several (at most eight), each international, without repeats. */ function numbersOf(raw: unknown): string[] { const list = Array.isArray(raw) ? raw : [raw]; if (!list.length || list.length > MEMBERS_MAX - 1) refuse(400, "bad_number", `call one to ${MEMBERS_MAX - 1} numbers`); return [...new Set(list.map(numberOf))]; } export function numberOf(raw: unknown): string { const number = typeof raw === "string" ? normalizePhone(raw) : null; if (!number) refuse(400, "bad_number", "use an international phone number starting with +"); return number; } export async function blocked(sql: SqlStorage, number: string): Promise { return sql.exec("SELECT 1 FROM call_block WHERE key = ?", await keyOf(sql, number)).toArray().length > 0; } export function keyOf(sql: SqlStorage, number: string): Promise { return mac(sql, `number:${number}`); } /** HMAC-SHA256 under this object's call key, made on first use: what the Worker keeps in a number's place. */ export async function mac(sql: SqlStorage, text: string): Promise { let secret = sql.exec<{ secret: string }>("SELECT secret FROM call_key WHERE id = 1").toArray()[0]?.secret; if (!secret) { secret = btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))); sql.exec("INSERT OR IGNORE INTO call_key (id, secret) VALUES (1, ?)", secret); secret = sql.exec<{ secret: string }>("SELECT secret FROM call_key WHERE id = 1").one().secret; } const key = await crypto.subtle.importKey("raw", Uint8Array.from(atob(secret), (c) => c.charCodeAt(0)), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); const signed = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(text))); return btoa(String.fromCharCode(...signed)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } /** Old rings, hits and kept missed calls go: at every calls request, socket hello, and the object's alarm (CALLS FIX 3). */ export function sweep(sql: SqlStorage): void { sql.exec("DELETE FROM call_hit WHERE at < ?", Date.now() - HOUR); sql.exec("DELETE FROM call_ring WHERE created_at < ?", Date.now() - RING_KEPT_MS); sql.exec("DELETE FROM call_told WHERE ended < ?", Date.now() - MISSED_KEPT_MS); } export function count(sql: SqlStorage, who: string, within: number): number { return sql.exec<{ n: number }>("SELECT count(*) AS n FROM call_hit WHERE who = ? AND at >= ?", who, Date.now() - within).one().n; } export function hit(sql: SqlStorage, who: string): void { sql.exec("INSERT INTO call_hit (who, at) VALUES (?, ?)", who, Date.now()); }