Cotton code
1872 lines · 106.6 KB · TypeScriptRaw
/** * Cotton to Cotton messages on a person's object (12 Nov 2026): the routes a * phone calls on its own object, the hop one object makes to another, the * envelopes held for each device until it takes them, and the socket that * hands them over while a phone is open. The wire is in the build session's report * (kept outside the repository); the phone's half is cotton-core `chat`. * * THE WORKER NEVER SEES TEXT. A phone seals every envelope on the phone, once * for each device that should read it (each of the other person's devices and * each of the sender's own other devices), with the key that device published * here (`c1:` boxes, cotton-core chat/seal.rs). What arrives is a map of * opaque boxes by device handle; the object routes them by handle and never * opens one: no key that could is ever on the Worker. * * WHAT IT SEES, then, is the envelope's outside: who writes to whom (the two * numbers, which routing needs), when, its kind (message, receipt, typing or * change: a reaction, edit or delete inside the box), * its client id, and each box's size. It keeps a box only until the device it * is for takes it (and thirty days at most), and an id only for a week, to * drop a resend. * * THE TABLES are the Worker's own, never a kit's, as Calling's are: * - `chat_device`: each of this object's phones' chat public key (X25519, *   base64url) and its alert push token. Dropped at the phone's sign-out. * - `chat_held`: the boxes waiting for each device, with the other number, *   the kind, the client id and the time. * - `chat_seen`: ids already taken, for a week: a resend is dropped. A *   re-send after a ratchet reset (`resend: true`, SEALING.md) is the one *   exception, kept here under `resend:<handle>:<id>` and `in-resend:…`: once *   for each device, never twice. * - `chat_peer`: the numbers the owner accepted (by writing to them, or by *   accepting their request), keyed by HMAC under the object's call key, each *   with its number: Send names this person's people from it (src/send/send.ts), *   since the Cotton threads that would name them are sealed on the phone; *   and the name their ask carried, when they were accepted from one. * - `chat_ask`: people who added this owner by number from Account's Your *   people (14 Nov 2026) and wait for an answer, each with the account name *   they volunteered by asking. An ask needs no chat app: it is delivered *   object to object at the add, dropped when the asker is blocked, already *   accepted, or over the strangers' limits, and goes at accept, refuse, *   block or the asker's remove. * - `chat_ask_refused`: askers whose request the owner deleted (DISCOVERY OFF 2, *   27 Nov 2026): their asks are dropped unsaid until the owner accepts them, so *   deleting a request never lets the same asker alert again. * - `chat_pick`: the new numbers this owner reached, by key, with when: at most *   NEW_NUMBERS_PER_HOUR and NEW_NUMBERS_PER_DAY (gate.ts `firstContacts`). * - `chat_file`: the pictures this object's phones put in the chat file *   store (R2 `chat-files/<id>`, ciphertext sealed on the phone with a key *   that travels inside the message), each dropped thirty days on. * - `chat_group` (Cotton groups, 20 Nov 2026): the groups this owner is in, by *   the group's random id, each with its members keyed by HMAC under the *   object's call key, as `chat_peer` keys them. The owner's phone says who is *   in each (it folds the group's sealed log, cotton-core chat/group.rs); the *   object uses it only to take a member's envelopes as a friend's rather *   than a stranger's request. It holds no name, no picture, no message, and *   the object makes no group decision of its own: a group is its members' *   phones' agreement, never a row here. * The block list is Calling's `call_block`: one list, so a number blocked for * calls is blocked for messages and the other way round. The limits count in * Calling's `call_hit`. * * THE PRIVACY RULE is Calling's: an unknown number, a number on Cotton that * blocked you, and one that is over its limit look the same to the sender. A * keys lookup for a number nobody holds answers one device with a key made * from the number under this object's own key: stable, and looking like any * other. A send is answered the same whatever happens to it. The sender learns * a message arrived only from the recipient's own receipt. * * FIRST CONTACT goes through one gate (gate.ts, DISCOVERY OFF 3): every route * here that reaches a number counts it there before any lookup, and an * object hands sealed words and key material only to and from someone its * owner accepted (or a member of a group its owner's phone named). A * stranger reaches this owner by an ask alone. */import * as handover from "../handover.ts";import { directory } from "../directory.ts";import { numberDigest } from "../number_key.ts";import { devWorker, type Env } from "../env.ts";import { json, readJson, refuse } from "../http.ts";import { blocked, count, hit, keyOf, mac, numberOf } from "../calling/calls.ts";import { PLATFORMS, type Platform } from "../calling/push.ts";import { normalizePhone } from "../protocol.ts";import { alert, CHAT_TOPICS, nudge } from "./push.ts";import * as agents from "./agents.ts";import * as gate from "./gate.ts";import * as circleInvite from "./circle_invite.ts";import { sealValueAtArrival } from "../arrival.ts";export const SCHEMA = `CREATE TABLE IF NOT EXISTS chat_device (device_id TEXT PRIMARY KEY, public_key TEXT NOT NULL, platform TEXT, token TEXT, topic TEXT, sandbox INTEGER NOT NULL DEFAULT 0, updated_at TEXT NOT NULL);CREATE TABLE IF NOT EXISTS chat_held (device_id TEXT NOT NULL, kind TEXT NOT NULL, id TEXT NOT NULL, peer TEXT NOT NULL, out INTEGER NOT NULL, request INTEGER NOT NULL, box TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (device_id, kind, id));CREATE INDEX IF NOT EXISTS chat_held_by_at ON chat_held (device_id, at);CREATE TABLE IF NOT EXISTS chat_seen (key TEXT PRIMARY KEY, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS chat_peer (key TEXT PRIMARY KEY, number TEXT, at TEXT NOT NULL);CREATE TABLE IF NOT EXISTS chat_file (id TEXT PRIMARY KEY, bytes INTEGER NOT NULL, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS chat_ask (key TEXT PRIMARY KEY, number TEXT NOT NULL, name TEXT, at TEXT NOT NULL);CREATE TABLE IF NOT EXISTS chat_ask_refused (key TEXT PRIMARY KEY, at TEXT NOT NULL);CREATE TABLE IF NOT EXISTS chat_pick (key TEXT PRIMARY KEY, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS chat_ticket (hash TEXT PRIMARY KEY, device_id TEXT NOT NULL, until INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS chat_blocked (key TEXT PRIMARY KEY, number TEXT NOT NULL, name TEXT, was TEXT, was_at TEXT, at TEXT NOT NULL);CREATE TABLE IF NOT EXISTS chat_waiting (number TEXT PRIMARY KEY, ticket TEXT NOT NULL, state TEXT NOT NULL, at TEXT NOT NULL);CREATE TABLE IF NOT EXISTS chat_group (group_id TEXT NOT NULL, key TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (group_id, key));CREATE TABLE IF NOT EXISTS chat_profile_file (id TEXT PRIMARY KEY, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS chat_dev_refuse (one INTEGER PRIMARY KEY CHECK (one = 1), left INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS chat_prekey (device_id TEXT NOT NULL, key TEXT NOT NULL, sig TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (device_id, key));CREATE TABLE IF NOT EXISTS chat_fake_claim (handle TEXT PRIMARY KEY, n INTEGER NOT NULL);`;/** The chat tables made, and a `chat_peer` made before it kept numbers given its column (its rows name nobody until they are accepted again). */export function ready(sql: SqlStorage): void {  sql.exec(SCHEMA);  const columns = [...sql.exec("PRAGMA table_info(chat_peer)")].map((c) => c.name);  if (!columns.includes("number")) sql.exec("ALTER TABLE chat_peer ADD COLUMN number TEXT");  if (!columns.includes("name")) sql.exec("ALTER TABLE chat_peer ADD COLUMN name TEXT");  // THE CIRCLE's server half (PEOPLE-DESIGN b.4): the other account's object, bound the first time they add back, and  // when their account was erased ("left Cotton"). A number that later leads to another object is "changed".  if (!columns.includes("slug")) sql.exec("ALTER TABLE chat_peer ADD COLUMN slug TEXT");  if (!columns.includes("left_at")) sql.exec("ALTER TABLE chat_peer ADD COLUMN left_at TEXT");  // b.4: each Circle row's number and name sealed to the owner's arrival key (`sealed`, "a2:"), beside the clear ones.  for (const table of ["chat_peer", "chat_ask", "chat_blocked"]) {    const has = [...sql.exec(`PRAGMA table_info(${table})`)].map((c) => c.name);    if (!has.includes("sealed")) sql.exec(`ALTER TABLE ${table} ADD COLUMN sealed TEXT`);    // b.4 step B: the number's digest (number_key.ts), which the directory routes by, so a row can drop its clear number.    if (!has.includes("digest")) sql.exec(`ALTER TABLE ${table} ADD COLUMN digest TEXT`);  }  // Cotton groups (20 Nov 2026): a held envelope names the group it was said in.  const held = [...sql.exec("PRAGMA table_info(chat_held)")].map((c) => c.name);  if (!held.includes("group_id")) sql.exec("ALTER TABLE chat_held ADD COLUMN group_id TEXT");  // The c2 box (assets/design/chat/SEALING.md): a device's Olm identity, its signing key and the  // signature binding both to its chat key, and its fallback key. Null on a device that speaks c1 alone.  const device = [...sql.exec("PRAGMA table_info(chat_device)")].map((c) => c.name);  for (const column of ["c2_identity", "c2_signing", "c2_sig", "c2_fallback", "c2_fallback_sig"]) {    if (!device.includes(column)) sql.exec(`ALTER TABLE chat_device ADD COLUMN ${column} TEXT`);  }  // An agent in a chat (23 Nov 2026): what a device opens beyond messages, and the agents' own tables (agents.ts).  agents.ready(sql);}/** What every Circle row's sealed copy is bound to (cotton-core `seal::arrival::open_arrival_value`'s id). */export const CIRCLE_BOX = "circle-person";/** The account's own switch (object meta) for dropping clear numbers from new Circle rows; the Worker's is env CIRCLE_SEALED_ONLY. */export const CIRCLE_SEALED_ONLY = "circle_sealed_only";type CircleTable = "chat_peer" | "chat_ask" | "chat_blocked";/** A dropped clear number: chat_peer's column takes NULL, chat_ask's and chat_blocked's (NOT NULL) an empty text. */const NO_NUMBER = (table: CircleTable): string | null => (table === "chat_peer" ? null : "");/** * THE CIRCLE, SEALED (PEOPLE-DESIGN b.4): a row's number and name sealed to the owner's arrival key beside the clear * ones, written after each change to the row, one row by its key, with the number's digest the directory routes by. * Only his phones open the sealed copy. With no arrival key handed yet the row keeps only its clear copy, as before. * Step B: with the switch on (`only`), once the sealed copy is written the row's clear number and name go; a row whose * clear number has gone is never sealed again from here (the object cannot read it), and keeps the copy it has. */export async function reseal(host: Pick<ChatHost, "sql" | "arrival">, table: CircleTable, key: string): Promise<void> {  const row = host.sql.exec<{ number: string | null; name: string | null }>(`SELECT number, name FROM ${table} WHERE key = ?`, key).toArray()[0];  if (!row?.number) return;  host.sql.exec(`UPDATE ${table} SET digest = ? WHERE key = ?`, await numberDigest(row.number), key);  const to = host.arrival?.();  if (!to) return;  const sealed = await sealValueAtArrival(to.pub, to.databaseId, CIRCLE_BOX, JSON.stringify({ number: row.number, name: row.name ?? null }));  host.sql.exec(`UPDATE ${table} SET sealed = ? WHERE key = ?`, sealed, key);  if (to.only) host.sql.exec(`UPDATE ${table} SET number = ?, name = NULL WHERE key = ?`, NO_NUMBER(table), key);}/** * STEP C (PEOPLE-DESIGN b.4): rows written before the object held the arrival key, or before the switch, sealed now: * at most `most` a call, the coordinator's alone (admin `POST /v1/admin/circle/seal`). Without `apply` it only counts. * With `drop`, a row that has its sealed copy also loses its clear number and name. Each call reads at most `most` * rows of each Circle table, never the database's rows. */export async function convertCircle(host: Pick<ChatHost, "sql" | "arrival">, o: { apply: boolean; drop: boolean; most: number }): Promise<{ arrival: boolean; tables: Record<string, { toSeal: number; clear: number; done: number }> }> {  const to = host.arrival?.();  const tables: Record<string, { toSeal: number; clear: number; done: number }> = {};  for (const table of ["chat_peer", "chat_ask", "chat_blocked"] as const) {    const toSeal = host.sql.exec<{ n: number }>(`SELECT count(*) AS n FROM ${table} WHERE number IS NOT NULL AND number != '' AND (sealed IS NULL OR digest IS NULL)`).one().n;    const clear = host.sql.exec<{ n: number }>(`SELECT count(*) AS n FROM ${table} WHERE number IS NOT NULL AND number != ''`).one().n;    let done = 0;    if (o.apply && to) {      const keys = host.sql.exec<{ key: string }>(`SELECT key FROM ${table} WHERE number IS NOT NULL AND number != '' AND (sealed IS NULL OR digest IS NULL ${o.drop ? "OR 1" : ""}) LIMIT ?`, o.most).toArray();      const sealer = { sql: host.sql, arrival: () => ({ ...to, only: o.drop }) };      for (const { key } of keys) {        await reseal(sealer, table, key);        done++;      }    }    tables[table] = { toSeal, clear, done };  }  return { arrival: !!to, tables };}/** * A row moving from one Circle table to another (an ask accepted, someone blocked) whose source keeps only its sealed * copy: the copy and digest go with it, since the object cannot seal again what it cannot read, and the target drops * its clear number too. False when the source still has its clear number (the caller reseals as usual). */async function carry(host: Pick<ChatHost, "sql" | "arrival">, from: CircleTable, to: CircleTable, key: string): Promise<boolean> {  const src = host.sql.exec<{ number: string | null; sealed: string | null; digest: string | null }>(`SELECT number, sealed, digest FROM ${from} WHERE key = ?`, key).toArray()[0];  if (!src || src.number || !src.sealed) return false;  host.sql.exec(`UPDATE ${to} SET sealed = ?, digest = ?, number = ?, name = NULL WHERE key = ?`, src.sealed, src.digest, NO_NUMBER(to), key);  return true;}/** A block taken back puts the row back where it was: its sealed copy follows. */async function resealBoth(host: Pick<ChatHost, "sql" | "arrival">, key: string): Promise<void> {  await reseal(host, "chat_peer", key);  await reseal(host, "chat_ask", key);}/** A number accepted: one of this person's people, its number kept beside its key. */async function accept(sql: SqlStorage, number: string, at: string): Promise<void> {  // A row that keeps only its sealed copy (b.4 step B) keeps it: its number is not written back in the clear.  sql.exec("INSERT INTO chat_peer (key, number, at) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET number = CASE WHEN chat_peer.number IS NULL AND chat_peer.sealed IS NOT NULL THEN NULL ELSE excluded.number END", await keyOf(sql, number), number, at);}// `change` (Cotton Chat, 19 Nov 2026): a reaction, an edit or a delete of a// message already sent, sealed like the rest; the object sees only the kind.// Held and taken as a receipt is: never an alert, and only between people// who accepted each other.// `group` (Cotton groups, 20 Nov 2026): a change to a group's members, name or// picture, sealed like a message: the object sees only that a group changed.export const KINDS = ["message", "receipt", "typing", "change", "group"] as const;export type Kind = (typeof KINDS)[number];/** A phone's own messages in an hour; over it the send is refused, which says nothing about whom it wrote to. */export const MESSAGES_PER_HOUR = 300;/** A phone's keys lookups in an hour: enough to write to anyone, too few to walk the numbers. */export const LOOKUPS_PER_HOUR = 120;/** A message's refusal when its boxes miss a device it would reach now (the phone asks the keys again). */export const STALE_DEVICES = "stale_devices";/** Messages this object takes from one accepted person in ten minutes; the rest are dropped unsaid. */export const FROM_PEER_10_MIN = 120;/** Asks from one stranger in an hour (a stranger's message is taken as their ask), until the owner accepts them. */export const FROM_STRANGER_HOUR = gate.ASKS_FROM_ONE_HOUR;/** Asks from all strangers together in an hour. */export const FROM_STRANGERS_HOUR = gate.ASKS_FROM_ALL_HOUR;/** At most this many boxes in one envelope: a person's devices and the sender's own. */export const BOXES_MAX = 16;/** A box's length at most: a message's words and a picture's key, never the picture. */export const BOX_MAX = 64 * 1024;/** A sealed picture at most: the core's 16 MB plain, its nonce and tag. */export const FILE_MAX = 16 * 1024 * 1024 + 64;/** Pictures a phone puts up in an hour. */export const FILES_PER_HOUR = 200;/** People in one group at most (cotton-core chat/group.rs MEMBERS_MAX): the fan-out a group envelope carries. */export const GROUP_MEMBERS_MAX = 64;/** A group envelope's boxes together at most: 64 people's devices with their words. */export const GROUP_SEND_MAX = 8 * 1024 * 1024;/** Changes to which groups this object takes members from, in an hour. */export const GROUP_CHANGES_PER_HOUR = 120;/** Groups one object is in at most. */export const GROUPS_MAX = 500;/** A box nobody took is dropped after thirty days; an id is remembered a week. */export const HELD_MS = 30 * 24 * 3_600_000;export const SEEN_MS = 7 * 24 * 3_600_000;const HOUR = 3_600_000;const ID = /^[A-Za-z0-9_-]{8,64}$/;const HANDLE = /^[A-Za-z0-9_-]{22}$/;const BOX = /^c[12]:[A-Za-z0-9_-]+$/;const SIG = /^[A-Za-z0-9_-]{86}$/;/** One-time keys one device keeps here at most. */export const PREKEYS_MAX = 100;/** Keys a phone publishes in one call at most. */export const PREKEYS_PER_CALL = 100;/** One-time keys a phone claims in an hour (one per device it starts a session with): a group of 64 is a few dozen. */export const CLAIMS_PER_HOUR = 300;const GROUP = /^[0-9a-f]{32}$/;const PUSH_TOKEN: Record<Platform, RegExp> = { ios: /^[0-9a-fA-F]{32,200}$/, android: /^[A-Za-z0-9_:-]{32,4096}$/ };export interface ChatHost {  sql: SqlStorage;  env: Env;  slug: string;  /** This object's database id: a socket ticket names it, so the open host finds the object without a device credential. */  databaseId: string | null;  ownerPhone: string | null;  waitUntil(work: Promise<unknown>): void;  /** The open chat sockets of one of this object's devices. */  sockets(deviceId: string): WebSocket[];  /** A person removed or blocked: what Send holds from and for them goes (src/send/send.ts `forgetPerson`). */  forget?(number: string): Promise<void>;  /** The space rules count friends for this account (SPACE.md): who waited for it first is its referrer. */  spaceCounting?(): boolean;  /** The owner's own account name, which an ask carries to the person added; null when they gave none. */  ownerName?(): string | null;  /** Take a socket for a device, hibernating. */  accept(socket: WebSocket, deviceId: string): void;  /** The owner's arrival key and database id, once a phone handed the key (the Circle's sealed copies, b.4). */  arrival?(): { pub: Uint8Array; databaseId: string; only?: boolean } | null;}/** One device a sender can seal for: its handle (never its id), its public key, and its c2 record when it speaks c2. */export interface ChatKey {  device: string;  key: string;  c2?: C2Record;}/** What a c2 device publishes beside its chat key (cotton-core chat/ratchet.rs `Record`): the phone checks the signature. */export interface C2Record {  identity: string;  signing: string;  sig: string;}/** One one-time key (or the fallback key, `fallback: true`) and its signature by the device's signing key. */export interface Prekey {  key: string;  sig: string;  fallback?: boolean;}/** What one object hands another: the outside of an envelope and the boxes for that object's devices. */export interface Delivery {  from: string;  fromSlug: string;  id: string;  kind: Kind;  at: number;  boxes: Record<string, string>;  /** The group it was said in, if any. */  group?: string | null;  /** A message sent again for the one device whose ratchet lost it (its only box): taken once for that device. */  resend?: boolean;}/** One held envelope as a phone takes it. */export interface Item {  id: string;  kind: Kind;  /** The other person's number: the sender's, or, on a copy of this person's own message, the recipient's. */  peer: string;  /** This person's own message, sent from another of their devices. */  out: boolean;  /** A stranger's first messages, until the owner accepts or blocks them. */  request: boolean;  box: string;  at: number;  /** The group it was said in; null for a one-to-one envelope. On this person's own copy of a group envelope `peer` is their own number. */  group: string | null;}/** The routes under /v1/chat, for a phone signed in on this object; null for any other path. */export async function route(host: ChatHost, deviceId: string | null, request: Request, url: URL): Promise<Response | null> {  const path = url.pathname;  if (path !== "/v1/chat" && !path.startsWith("/v1/chat/")) return null;  const method = request.method;  if (!deviceId) refuse(401, "sign_in", "messages are sent from a signed-in phone");  sweep(host.sql);  host.waitUntil(sweepFiles(host).catch(() => undefined));  if (path === "/v1/chat/device") {    if (method === "POST") {      const answer = putDevice(host.sql, deviceId, await readJson(request));      // This number can now be written to: whoever waited for it is told, off the request.      host.waitUntil(joined(host).catch(() => undefined));      return answer;    }    if (method === "DELETE") {      forgetDevice(host, deviceId);      return json({ ok: true });    }  }  if (method === "POST" && path === "/v1/chat/socket") return json({ ticket: await mintTicket(host, deviceId) });  if (method === "POST" && path === "/v1/chat/prekeys") return json(publishPrekeys(host.sql, deviceId, await readJson(request)));  if (method === "POST" && path === "/v1/chat/prekeys/claim") return json(await claimPrekeys(host, deviceId, await readJson(request)));  if (method === "GET" && path === "/v1/chat/keys") return json({ me: host.ownerPhone, ...(await keys(host, deviceId, numberOf(url.searchParams.get("number")))) });  if (method === "POST" && path === "/v1/chat/keys") return json({ me: host.ownerPhone, ...(await manyKeys(host, deviceId, (await readJson(request)).numbers)) });  if (method === "POST" && path === "/v1/chat/group/send") return json(await sendGroup(host, deviceId, await readJson(request)));  if (method === "POST" && path === "/v1/chat/group") return json(await joinGroup(host, await readJson(request)));  if (method === "PUT" && path === "/v1/chat/files") return json(await putFile(host, deviceId, request));  const file = /^\/v1\/chat\/files\/([0-9a-f]{32})$/.exec(path);  if (method === "GET" && file) return getFile(host.env, file[1]!);  if (method === "POST" && path === "/v1/chat/send") return json(await send(host, deviceId, await readJson(request)));  // `asks` (21 Nov 2026, a key older phones never read): who asks to chat, so Chat shows each as a message request.  if (method === "POST" && path === "/v1/chat/dev/refuse-next" && devServer(host.env)) return json(refuseNext(host.sql, (await readJson(request)).count));  // `prekeys` (c2, 21 Nov 2026, a key older phones never read): how many one-time keys this device has left here.  if (method === "GET" && path === "/v1/chat/inbox") return json({ me: host.ownerPhone, items: held(host.sql, deviceId), asks: asksOf(host.sql), ...prekeysLeft(host.sql, deviceId) });  if (method === "POST" && path === "/v1/chat/ack") {    take(host.sql, deviceId, (await readJson(request)).items);    return json({ ok: true });  }  // THE CIRCLE'S INVITATION LINK (circle_invite.ts): made, stopped and listed by his phone; redeemed by theirs.  if (method === "POST" && path === "/v1/chat/circle/invite") return json(await circleInvite.make(host, await readJson(request)));  if (method === "POST" && path === "/v1/chat/circle/invite/stop") return json(await circleInvite.stop(host, await readJson(request)));  if (method === "GET" && path === "/v1/chat/circle/invites") return json(circleInvite.standing(host));  if (method === "POST" && path === "/v1/chat/circle/redeem") {    const answer = await circleInvite.redeem(      host,      await readJson(request),      async (number) => {        await decide(host, "accept", number);        // The inviter holds this person already: the ask over finds them accepted, so both are in.        host.waitUntil(askOver(host, number));      },      (slug) => peer(host.env, slug),    );    return json(answer);  }  const said = /^\/v1\/chat\/(accept|refuse|block|unblock|remove)$/.exec(path);  if (method === "POST" && said) {    const number = numberOf((await readJson(request)).number);    // An add from Your people reaches a number: through the gate (free when they ask this owner, so accepting a    // stranger's request costs no new number).    if (said[1] === "accept") {      addable(host, number);      await gate.firstContact(host, number, "one");    }    await decide(host, said[1] as "accept" | "refuse" | "block" | "unblock" | "remove", number);    // The ask goes off this request: the answer is the same, in the same time, whether or not the number is on Cotton.    if (said[1] === "accept") host.waitUntil(askOver(host, number));    return json({ ok: true });  }  if (method === "GET" && path === "/v1/chat/people") return json(await peopleOf(host));  // RETIRED (DISCOVERY OFF 1, 27 Nov 2026: no bulk contact discovery). A build already on a phone still asks: it is  // answered with nothing found and nothing left, never an error, and its "may be found" switch reads off and changes  // nothing. Nothing it sends is read.  if (method === "POST" && path === "/v1/chat/discover") return json({ found: [], left: 0 });  if (path === "/v1/chat/findable") {    if (method === "GET") return json({ me: host.ownerPhone, findable: false, left: 0 });    if (method === "POST") return json({ findable: false });  }  if (path === "/v1/chat/wait") {    const number = numberOf((await readJson(request)).number);    if (method === "POST") return json(await waitFor(host, number));    if (method === "DELETE") {      await unwait(host, number);      return json({ ok: true });    }  }  if (method === "GET" && path === "/v1/chat/reach") return json(reachOf(host.sql));  if (method === "PUT" && path === "/v1/chat/profile-picture") return json(await putProfilePicture(host, deviceId, request));  const profileFile = /^\/v1\/chat\/profile-pictures\/([0-9a-f]{32})$/.exec(path);  if (method === "GET" && profileFile) return getStored(host.env, `chat-profile/${profileFile[1]!}`);  refuse(404, "not_found", `nothing answers ${method} ${path}`);}/** A phone publishes its chat key (and, when it has one, the token its alerts go to). */function putDevice(sql: SqlStorage, deviceId: string, body: Record<string, unknown>): Response {  const publicKey = typeof body.publicKey === "string" ? body.publicKey : "";  if (!isPublicKey(publicKey)) refuse(400, "bad_key", "publicKey: the device's X25519 public key, 32 bytes as base64url");  let platform: Platform | null = null;  let token: string | null = null;  let topic: string | null = null;  if (body.token !== undefined && body.token !== null) {    platform = body.platform as Platform;    if (!PLATFORMS.includes(platform)) refuse(400, "bad_platform", `platform: one of ${PLATFORMS.join(", ")}`);    token = typeof body.token === "string" ? body.token.trim() : "";    if (!PUSH_TOKEN[platform].test(token)) refuse(400, "bad_token", platform === "ios" ? "token: the APNs token as hex" : "token: the FCM registration token");    if (platform === "ios") {      if (typeof body.topic !== "string" || !CHAT_TOPICS.includes(body.topic)) refuse(400, "bad_topic", `topic: one of ${CHAT_TOPICS.join(", ")}`);      topic = body.topic;      token = token.toLowerCase();    }  }  // A device that says nothing of c2 speaks c1 alone: what it published before goes, and a phone that spoke c2 with it  // refuses to fall back (cotton-core chat/ratchet.rs pins). A new chat key starts its keys afresh.  const c2 = body.c2 === undefined || body.c2 === null ? null : c2Of(body.c2);  const was = sql.exec<{ public_key: string; c2_identity: string | null }>("SELECT public_key, c2_identity FROM chat_device WHERE device_id = ?", deviceId).toArray()[0];  if (!c2 || (was && (was.public_key !== publicKey || was.c2_identity !== c2.record.identity))) sql.exec("DELETE FROM chat_prekey WHERE device_id = ?", deviceId);  sql.exec(    "INSERT INTO chat_device (device_id, public_key, platform, token, topic, sandbox, updated_at, c2_identity, c2_signing, c2_sig, c2_fallback, c2_fallback_sig) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (device_id) DO UPDATE SET public_key = excluded.public_key, platform = excluded.platform, token = excluded.token, topic = excluded.topic, sandbox = excluded.sandbox, updated_at = excluded.updated_at, c2_identity = excluded.c2_identity, c2_signing = excluded.c2_signing, c2_sig = excluded.c2_sig, c2_fallback = COALESCE(excluded.c2_fallback, CASE WHEN excluded.c2_identity IS chat_device.c2_identity THEN chat_device.c2_fallback END), c2_fallback_sig = COALESCE(excluded.c2_fallback_sig, CASE WHEN excluded.c2_identity IS chat_device.c2_identity THEN chat_device.c2_fallback_sig END)",    deviceId,    publicKey,    platform,    token,    topic,    platform === "ios" && body.sandbox === true ? 1 : 0,    new Date().toISOString(),    c2?.record.identity ?? null,    c2?.record.signing ?? null,    c2?.record.sig ?? null,    c2?.fallback?.key ?? null,    c2?.fallback?.sig ?? null,  );  // What this phone's core opens beyond messages: an agent's acts are held only for a phone that says so (agents.ts).  agents.keepCan(sql, deviceId, body.can);  if (c2?.prekeys.length) addPrekeys(sql, deviceId, c2.prekeys);  return json({ ok: true, ...prekeysLeft(sql, deviceId) });}/** A device's c2 record as it publishes it: `{ identity, signing, sig, fallback?, prekeys? }`. */function c2Of(raw: unknown): { record: C2Record; fallback: Prekey | null; prekeys: Prekey[] } {  const c2 = raw as Record<string, unknown>;  if (!c2 || typeof c2 !== "object" || !isKeyText(c2.identity) || !isKeyText(c2.signing) || typeof c2.sig !== "string" || !SIG.test(c2.sig)) {    refuse(400, "bad_c2", "c2: { identity, signing, sig }, keys as 32 bytes and the signature as 64, base64url");  }  const fallback = c2.fallback === undefined || c2.fallback === null ? null : prekeyOf(c2.fallback);  const prekeys = c2.prekeys === undefined ? [] : prekeysOf(c2.prekeys);  return { record: { identity: c2.identity as string, signing: c2.signing as string, sig: c2.sig as string }, fallback, prekeys };}function prekeyOf(raw: unknown): Prekey {  const p = raw as Record<string, unknown>;  if (!p || typeof p !== "object" || !isKeyText(p.key) || typeof p.sig !== "string" || !SIG.test(p.sig)) refuse(400, "bad_prekey", "a key: { key, sig }, 32 bytes and 64, base64url");  return { key: p.key as string, sig: p.sig as string };}function prekeysOf(raw: unknown): Prekey[] {  if (!Array.isArray(raw) || raw.length > PREKEYS_PER_CALL) refuse(400, "bad_prekeys", `prekeys: at most ${PREKEYS_PER_CALL} keys`);  return (raw as unknown[]).map(prekeyOf);}function isKeyText(value: unknown): value is string {  return typeof value === "string" && isPublicKey(value);}/** One-time keys kept for a device, the oldest dropped past PREKEYS_MAX. */function addPrekeys(sql: SqlStorage, deviceId: string, prekeys: Prekey[]): void {  const at = Date.now();  for (const [n, p] of prekeys.entries()) sql.exec("INSERT OR IGNORE INTO chat_prekey (device_id, key, sig, at) VALUES (?, ?, ?, ?)", deviceId, p.key, p.sig, at + n);  sql.exec("DELETE FROM chat_prekey WHERE device_id = ? AND key NOT IN (SELECT key FROM chat_prekey WHERE device_id = ? ORDER BY at DESC LIMIT ?)", deviceId, deviceId, PREKEYS_MAX);}/** How many one-time keys a c2 device has left here; nothing for a c1 one. */function prekeysLeft(sql: SqlStorage, deviceId: string): { prekeys?: number } {  const device = sql.exec<{ c2_identity: string | null }>("SELECT c2_identity FROM chat_device WHERE device_id = ?", deviceId).toArray()[0];  if (!device?.c2_identity) return {};  return { prekeys: sql.exec<{ n: number }>("SELECT count(*) AS n FROM chat_prekey WHERE device_id = ?", deviceId).one().n };}/** `POST /v1/chat/prekeys { prekeys, fallback? }`: a c2 device tops up its one-time keys (and turns its fallback over). */function publishPrekeys(sql: SqlStorage, deviceId: string, body: Record<string, unknown>): { ok: true; prekeys: number } {  const device = sql.exec<{ c2_identity: string | null }>("SELECT c2_identity FROM chat_device WHERE device_id = ?", deviceId).toArray()[0];  if (!device?.c2_identity) refuse(409, "no_c2", "publish this device's c2 record first (POST /v1/chat/device)");  addPrekeys(sql, deviceId, prekeysOf(body.prekeys ?? []));  if (body.fallback !== undefined && body.fallback !== null) {    const fallback = prekeyOf(body.fallback);    sql.exec("UPDATE chat_device SET c2_fallback = ?, c2_fallback_sig = ? WHERE device_id = ?", fallback.key, fallback.sig, deviceId);  }  return { ok: true, prekeys: prekeysLeft(sql, deviceId).prekeys ?? 0 };}/** * `POST /v1/chat/prekeys/claim { number, devices }`: one one-time key for each of these devices of `number` (this * person's own number for their other phones), each taken off its shelf as it goes, or its fallback key when none is * left. A number nobody holds answers its made-up device's, as a keys lookup does; so does an account that has not * accepted this owner (DISCOVERY OFF 3): its keys never leave for a stranger, so they cannot be drained to tell it * from a made-up one, and no accepted person may take more than gate.CLAIMS_FROM_ONE_HOUR of them in an hour. */async function claimPrekeys(host: ChatHost, deviceId: string, body: Record<string, unknown>): Promise<{ prekeys: Record<string, Prekey> }> {  const number = numberOf(body.number);  const handles = Array.isArray(body.devices) ? body.devices.filter((h): h is string => typeof h === "string" && HANDLE.test(h)) : [];  if (!handles.length || handles.length > BOXES_MAX) refuse(400, "bad_devices", `devices: one to ${BOXES_MAX} device handles`);  const who = `chat-claim:${deviceId}`;  if (count(host.sql, who, HOUR) + handles.length > CLAIMS_PER_HOUR) refuse(429, "too_many_claims", "Too many new sessions from this phone in the last hour; try again later.");  for (let n = 0; n < handles.length; n++) hit(host.sql, who);  if (number === host.ownerPhone) return { prekeys: await claimHere(host, handles, deviceId) };  // A claim is a group member's word: free for this owner's people and group members, else one of their new numbers.  await gate.firstContact(host, number, "member");  let prekeys: Record<string, Prekey> = {};  try {    const slug = await directory(host.env).lookup(number);    // The other object hands one-time keys only to someone its owner accepted or named in a group (gate.claimAdmits);    // anyone else gets nothing, and is answered below as a number nobody holds is.    if (slug && slug !== host.slug && host.ownerPhone) prekeys = await peer(host.env, slug).chatClaim(handles, host.ownerPhone);  } catch {    prekeys = {};  }  if (!Object.keys(prekeys).length) {    for (const [i, fake] of (await madeUpDevices(host, number)).entries()) {      if (handles.includes(fake.device)) prekeys[fake.device] = await madeUpClaimed(host, number, i, fake.device);    }  }  return { prekeys };}/** * Another object's claim of this owner's one-time keys for `from`: only someone this owner accepted or named in a * group, under their hourly share (gate.claimAdmits); anyone else gets nothing, and their object answers as for a * number nobody holds. */export async function claimAsked(host: Pick<ChatHost, "sql">, handles: string[], from: string): Promise<Record<string, Prekey>> {  let who: string;  try {    who = numberOf(from);  } catch {    return {};  }  if (!(await gate.claimAdmits(host.sql, who, handles.length))) return {};  return claimHere(host, handles);}/** Another object asks this owner's devices' keys for `from`: given only to someone this owner accepted or named in a group (gate.admitsAny). */export async function keysAsked(host: Pick<ChatHost, "sql">, from: string): Promise<ChatKey[]> {  let who: string;  try {    who = numberOf(from);  } catch {    return [];  }  if (!(await gate.admitsAny(host.sql, who))) return [];  return (await ownKeys(host)).map(sealable);}/** This object's devices' one-time keys, one each, taken as they go (`except`: the asking phone itself). */export async function claimHere(host: Pick<ChatHost, "sql">, handles: string[], except?: string): Promise<Record<string, Prekey>> {  const out: Record<string, Prekey> = {};  const rows = host.sql.exec<{ device_id: string; c2_fallback: string | null; c2_fallback_sig: string | null }>("SELECT device_id, c2_fallback, c2_fallback_sig FROM chat_device WHERE c2_identity IS NOT NULL").toArray();  for (const row of rows) {    if (row.device_id === except) continue;    const handle = await handleOf(host.sql, row.device_id);    if (!handles.includes(handle)) continue;    const taken = host.sql.exec<{ key: string; sig: string }>("DELETE FROM chat_prekey WHERE device_id = ? AND key = (SELECT key FROM chat_prekey WHERE device_id = ? ORDER BY at LIMIT 1) RETURNING key, sig", row.device_id, row.device_id).toArray()[0];    if (taken) out[handle] = { key: taken.key, sig: taken.sig };    else if (row.c2_fallback && row.c2_fallback_sig) out[handle] = { key: row.c2_fallback, sig: row.c2_fallback_sig, fallback: true };  }  return out;}/** A device's sign-out, or its own DELETE: its key, its token, what waits for it and its sockets go. */export function forgetDevice(host: Pick<ChatHost, "sql" | "sockets">, deviceId: string): void {  host.sql.exec("DELETE FROM chat_device WHERE device_id = ?", deviceId);  host.sql.exec("DELETE FROM chat_prekey WHERE device_id = ?", deviceId);  host.sql.exec("DELETE FROM chat_held WHERE device_id = ?", deviceId);  for (const ws of host.sockets(deviceId)) {    try {      ws.close(1000, "signed_out");    } catch {      // Already gone.    }  }}/** * The keys to seal for when writing to `number`: theirs (by the hop), and this * person's own other devices. A number nobody holds answers one made-up device. */async function keys(host: ChatHost, deviceId: string, number: string): Promise<{ devices: ChatKey[]; own: ChatKey[] }> {  const own = (await ownKeys(host)).filter((k) => k.deviceId !== deviceId).map(sealable);  // The person's own devices are theirs to know: asking them reveals nobody and is not counted, so a phone asks them  // afresh each time it tells its other phones something (a read), and one signed in a minute ago is told too.  if (number === host.ownerPhone) return { devices: [], own };  await gate.firstContact(host, number, "member");  const who = `chat-keys:${deviceId}`;  if (count(host.sql, who, HOUR) >= LOOKUPS_PER_HOUR) refuse(429, "too_many_lookups", "Too many lookups from this phone in the last hour; try again later.");  hit(host.sql, who);  return { devices: await theirDevices(host, number), own };}/** * `number`'s devices as this owner may seal for them: the real ones only when their owner accepted this owner (or * named them in a group: gate.admitsAny, asked on that object), else the made-up ones a number nobody holds answers. */async function theirDevices(host: ChatHost, number: string): Promise<ChatKey[]> {  return (await devicesNow(host, number)) ?? (await madeUpDevices(host, number));}/** The devices a message to `number` reaches now, as `keys` answers them; null when that could not be asked (the send goes on). */async function devicesNow(host: ChatHost, number: string): Promise<ChatKey[] | null> {  try {    const slug = await directory(host.env).lookup(number);    if (slug === host.slug) return [];    const devices = slug && host.ownerPhone ? await peer(host.env, slug).chatKeys(host.ownerPhone) : [];    return devices.length ? devices : await madeUpDevices(host, number);  } catch {    return null;  }}/** This object's devices' keys, each under its handle. */export async function ownKeys(host: Pick<ChatHost, "sql">): Promise<(ChatKey & { deviceId: string })[]> {  const rows = host.sql    .exec<{ device_id: string; public_key: string; c2_identity: string | null; c2_signing: string | null; c2_sig: string | null }>("SELECT device_id, public_key, c2_identity, c2_signing, c2_sig FROM chat_device ORDER BY device_id")    .toArray();  return Promise.all(    rows.map(async (r) => ({      deviceId: r.device_id,      device: await handleOf(host.sql, r.device_id),      key: r.public_key,      ...(r.c2_identity && r.c2_signing && r.c2_sig ? { c2: { identity: r.c2_identity, signing: r.c2_signing, sig: r.c2_sig } } : {}),    })),  );}/** A device as a sender sees it: its handle, its key, its c2 record when it has one. */export function sealable({ device, key, c2 }: ChatKey): ChatKey {  return c2 ? { device, key, c2 } : { device, key };}/** A phone sends one envelope: kept for its own other devices, handed to the other person's object for theirs. *//** Whether this Worker is the dev server or the test pool: the only places a walk may ask it to misbehave. */export function devServer(env: Pick<Env, "ENV_LABEL">): boolean {  return devWorker(env);}/** Messages a walk asked this owner's object to refuse, at most at once. */const DEV_REFUSE_MAX = 5;/** * `POST /v1/chat/dev/refuse-next { count? }` (dev server only, * 21 Nov 2026): the next `count` (1, at most 5) messages this owner sends are * refused as a meant refusal is, so a walk sees a failed message and its * Retry on a real phone. Anywhere else the route does not exist. */function refuseNext(sql: SqlStorage, raw: unknown): { left: number } {  const n = raw === undefined ? 1 : typeof raw === "number" && Number.isInteger(raw) && raw >= 0 && raw <= DEV_REFUSE_MAX ? raw : refuse(400, "bad_count", `count: 0 to ${DEV_REFUSE_MAX}`);  sql.exec("INSERT INTO chat_dev_refuse (one, left) VALUES (1, ?) ON CONFLICT (one) DO UPDATE SET left = excluded.left", n);  return { left: n };}/** A message refused because a walk asked it (dev server only): one fewer left. */function devRefusal(host: ChatHost, kind: Kind): void {  if (kind !== "message" || !devServer(host.env)) return;  const row = host.sql.exec<{ left: number }>("UPDATE chat_dev_refuse SET left = left - 1 WHERE one = 1 AND left > 0 RETURNING left").toArray()[0];  if (row) refuse(400, "dev_refused", "The dev server refused this message, as the walk asked.");}async function send(host: ChatHost, deviceId: string, body: Record<string, unknown>): Promise<{ ok: true; id: string; at: number }> {  if (!host.ownerPhone) refuse(409, "no_owner", "this object has no number to write from");  const to = numberOf(body.to);  if (to === host.ownerPhone) refuse(400, "bad_number", "a message needs someone else's number");  const id = typeof body.id === "string" && ID.test(body.id) ? body.id : refuse(400, "bad_id", "id: the message's own id, 8 to 64 letters, digits, - or _");  const kind = KINDS.includes(body.kind as Kind) ? (body.kind as Kind) : refuse(400, "bad_kind", `kind: one of ${KINDS.join(", ")}`);  devRefusal(host, kind);  const boxes = boxesOf(body.boxes);  const group = groupOf(body.group);  if (body.resend === true) return resend(host, deviceId, to, id, kind, boxes, group);  const seenKey = `out:${deviceId}:${kind}:${id}`;  const seen = host.sql.exec<{ at: number }>("SELECT at FROM chat_seen WHERE key = ?", seenKey).toArray()[0];  // A resend of an envelope already taken is answered as the first was, and goes nowhere.  if (seen) return { ok: true, id, at: seen.at };  // First contact: a number new to this owner costs one of their new numbers, before anything is looked up. A word to  // one member of a group (`group`) is a member's; anything else one to one. (A message to someone who has not  // accepted this owner reaches them as this owner's ask, never as sealed words: gate.ts.)  await gate.firstContact(host, to, group ? "member" : "one");  if (kind === "message") {    const who = `chat-out:${deviceId}`;    if (count(host.sql, who, HOUR) >= MESSAGES_PER_HOUR) refuse(429, "too_many_messages", "Too many messages from this phone in the last hour; try again later.");    hit(host.sql, who);  }  const own = await ownKeys(host);  // A message is sealed for every device it would reach now. A phone keeps the keys a few minutes (the lookups are  // limited), so one that signed in since would never get it: refused, and the phone asks the keys again and seals  // again. The devices are the ones /v1/chat/keys answers (a number on no object: its one made-up device), so this  // says nothing that route does not.  // Only a phone that says it seals again (`check: true`, cores from 20 Nov 2026) is refused: an older one would  // count the refusal as a failed try and keep its old keys.  if (kind === "message" && !group && body.check === true) {    const theirs = await devicesNow(host, to);    const missing = (theirs ?? []).some((k) => !(k.device in boxes)) || own.some((k) => k.deviceId !== deviceId && !(k.device in boxes));    if (missing) refuse(409, STALE_DEVICES, "The devices to seal for have changed; ask their keys again.");  }  const at = Date.now();  if (kind !== "typing") host.sql.exec("INSERT OR IGNORE INTO chat_seen (key, at) VALUES (?, ?)", seenKey, at);  // Writing to someone accepts them: their answers are never a request. A word to one member of a group (a receipt, a change) does not.  if (kind === "message" && !group) {    await accept(host.sql, to, new Date(at).toISOString());    await reseal(host, "chat_peer", await keyOf(host.sql, to));  }  const mine = new Map(own.filter((k) => k.deviceId !== deviceId).map((k) => [k.device, k.deviceId]));  const theirs: Record<string, string> = {};  for (const [handle, box] of Object.entries(boxes)) {    const ownDevice = mine.get(handle);    if (ownDevice) await land(host, ownDevice, { id, kind, peer: to, out: true, request: false, box, at, group });    else if (!own.some((k) => k.device === handle)) theirs[handle] = box;  }  if (Object.keys(theirs).length) host.waitUntil(handOver(host, to, { from: host.ownerPhone, fromSlug: host.slug, id, kind, at, boxes: theirs, group }));  return { ok: true, id, at };}/** * A message sent again after a ratchet reset (SEALING.md, "A session lost on * one side"): one device of the recipient (or one of the sender's own) said * the box it got opened nothing, on a fresh session, and the sender's phone * seals the same message again for that device alone. Taken only for a * message this object already sent (its id is in `chat_seen`), with exactly * one box, for a device the message reaches; once for each (device, id), from * whichever of the owner's phones asks first, and it carries the first send's * time so it lands in its place. A second try is answered as the first and * goes nowhere. */async function resend(host: ChatHost, deviceId: string, to: string, id: string, kind: Kind, boxes: Record<string, string>, group: string | null): Promise<{ ok: true; id: string; at: number }> {  if (kind !== "message" || group) refuse(400, "bad_resend", "Only a one-to-one message is sent again.");  const entries = Object.entries(boxes);  if (entries.length !== 1) refuse(400, "bad_resend", "A message is sent again to one device: one box.");  const [handle, box] = entries[0]!;  // The first send's time; a GLOB over this object's own sends, since any of its phones may be the one re-sending.  const first = host.sql.exec<{ at: number }>("SELECT at FROM chat_seen WHERE key GLOB ? ORDER BY at LIMIT 1", `out:*:message:${id}`).toArray()[0];  if (!first) refuse(409, "not_sent", "Only a message already sent can be sent again.");  const own = await ownKeys(host);  const ownDevice = own.find((k) => k.device === handle && k.deviceId !== deviceId);  if (!ownDevice) {    if (own.some((k) => k.device === handle)) refuse(400, "bad_resend", "A phone does not send to itself.");    const theirs = await devicesNow(host, to);    if (theirs && !theirs.some((k) => k.device === handle)) refuse(409, STALE_DEVICES, "That device no longer reads this chat.");  }  const seenKey = `resend:${handle}:${id}`;  if (host.sql.exec("SELECT 1 FROM chat_seen WHERE key = ?", seenKey).toArray().length) return { ok: true, id, at: first.at };  const who = `chat-out:${deviceId}`;  if (count(host.sql, who, HOUR) >= MESSAGES_PER_HOUR) refuse(429, "too_many_messages", "Too many messages from this phone in the last hour; try again later.");  hit(host.sql, who);  host.sql.exec("INSERT OR IGNORE INTO chat_seen (key, at) VALUES (?, ?)", seenKey, Date.now());  if (ownDevice) {    // The box it could not open goes, if it still waits: this one replaces it.    host.sql.exec("DELETE FROM chat_held WHERE device_id = ? AND kind = ? AND id = ?", ownDevice.deviceId, kind, id);    await land(host, ownDevice.deviceId, { id, kind, peer: to, out: true, request: false, box, at: first.at, group: null });  } else {    host.waitUntil(handOver(host, to, { from: host.ownerPhone!, fromSlug: host.slug, id, kind, at: first.at, boxes: { [handle]: box }, resend: true }));  }  return { ok: true, id, at: first.at };}/** * A phone says one thing in a group (Cotton groups, 20 Nov 2026): one * envelope, its boxes by member, sealed on the phone once for each device of * each member it holds in the group, and its own other devices' copies. * Each member's boxes go to that member's object as a one-to-one envelope * would, naming the group; who is in the group is the phone's to say, and * nothing here keeps it. Writing in a group accepts nobody as one's people. */async function sendGroup(host: ChatHost, deviceId: string, body: Record<string, unknown>): Promise<{ ok: true; id: string; at: number }> {  if (!host.ownerPhone) refuse(409, "no_owner", "this object has no number to write from");  const id = typeof body.id === "string" && ID.test(body.id) ? body.id : refuse(400, "bad_id", "id: the message's own id, 8 to 64 letters, digits, - or _");  const kind = KINDS.includes(body.kind as Kind) && body.kind !== "typing" ? (body.kind as Kind) : refuse(400, "bad_kind", "kind: message, receipt, change or group");  const group = groupOf(body.group) ?? refuse(400, "bad_group", "group: the group's id, 32 hex digits");  const raw = body.to;  if (!raw || typeof raw !== "object" || Array.isArray(raw)) refuse(400, "bad_to", "to: each member's number and the boxes sealed for their devices");  const entries = Object.entries(raw as Record<string, unknown>);  if (entries.length > GROUP_MEMBERS_MAX) refuse(400, "bad_to", `to: at most ${GROUP_MEMBERS_MAX} members`);  const to: [string, Record<string, string>][] = [];  let size = 0;  for (const [number, boxes] of entries) {    const checked = boxesOf(boxes);    size += Object.values(checked).reduce((n, b) => n + b.length, 0);    const member = numberOf(number);    if (member !== host.ownerPhone) to.push([member, checked]);  }  const own = body.own === undefined || body.own === null ? {} : boxesOf(body.own);  size += Object.values(own).reduce((n, b) => n + b.length, 0);  if (size > GROUP_SEND_MAX) refuse(413, "too_large", "This group message is too large to send.");  if (!to.length && !Object.keys(own).length) refuse(400, "bad_to", "to: at least one member, or this person's own devices");  const seenKey = `out:${deviceId}:${kind}:${id}`;  const seen = host.sql.exec<{ at: number }>("SELECT at FROM chat_seen WHERE key = ?", seenKey).toArray()[0];  if (seen) return { ok: true, id, at: seen.at };  // Each member new to this owner (not one of their people, nor in a group with them) costs one of their new numbers, all or none.  await gate.firstContacts(host, to.map(([member]) => member), "member");  if (kind === "message" || kind === "group") {    const who = `chat-out:${deviceId}`;    if (count(host.sql, who, HOUR) >= MESSAGES_PER_HOUR) refuse(429, "too_many_messages", "Too many messages from this phone in the last hour; try again later.");    hit(host.sql, who);  }  const ownNow = await ownKeys(host);  // As one to one: a message sealed for devices that have changed (a member's, or this person's own, phone signed in  // since) is refused, and the phone asks the keys again and seals again.  if (kind === "message" && body.check === true) {    const stale = await Promise.all(to.map(async ([member, boxes]) => ((await devicesNow(host, member)) ?? []).some((k) => !(k.device in boxes))));    if (stale.some(Boolean) || ownNow.some((k) => k.deviceId !== deviceId && !(k.device in own))) refuse(409, STALE_DEVICES, "The devices to seal for have changed; ask their keys again.");  }  const at = Date.now();  host.sql.exec("INSERT OR IGNORE INTO chat_seen (key, at) VALUES (?, ?)", seenKey, at);  const mine = new Map(ownNow.filter((k) => k.deviceId !== deviceId).map((k) => [k.device, k.deviceId]));  for (const [handle, box] of Object.entries(own)) {    const ownDevice = mine.get(handle);    if (ownDevice) await land(host, ownDevice, { id, kind, peer: host.ownerPhone, out: true, request: false, box, at, group });  }  for (const [member, boxes] of to) host.waitUntil(handOver(host, member, { from: host.ownerPhone, fromSlug: host.slug, id, kind, at, boxes, group }));  return { ok: true, id, at };}/** * The owner's phone says who is in a group this owner is in (its members' * numbers), or, with none, that the owner is no longer in it. Envelopes from * its members are then a friend's, not a stranger's request, and what they * already sent here stops being one. The answer says nothing of any number. */async function joinGroup(host: ChatHost, body: Record<string, unknown>): Promise<{ ok: true }> {  const group = groupOf(body.group) ?? refuse(400, "bad_group", "group: the group's id, 32 hex digits");  const raw = Array.isArray(body.members) ? body.members : refuse(400, "bad_members", "members: the group's members' numbers, none when this owner left it");  if (raw.length > GROUP_MEMBERS_MAX) refuse(400, "bad_members", `members: at most ${GROUP_MEMBERS_MAX}`);  const members = [...new Set(raw.map((n) => numberOf(n)))].filter((n) => n !== host.ownerPhone);  const who = "chat-group";  if (count(host.sql, who, HOUR) >= GROUP_CHANGES_PER_HOUR) refuse(429, "too_many_changes", "Too many group changes from this phone in the last hour; try again later.");  hit(host.sql, who);  const known = host.sql.exec("SELECT 1 FROM chat_group WHERE group_id = ? LIMIT 1", group).toArray().length > 0;  if (!known && members.length) {    const groups = host.sql.exec<{ n: number }>("SELECT count(DISTINCT group_id) AS n FROM chat_group").one().n;    if (groups >= GROUPS_MAX) refuse(409, "too_many_groups", `This account is in ${GROUPS_MAX} groups already.`);  }  host.sql.exec("DELETE FROM chat_group WHERE group_id = ?", group);  const at = new Date().toISOString();  for (const number of members) host.sql.exec("INSERT OR IGNORE INTO chat_group (group_id, key, at) VALUES (?, ?, ?)", group, await keyOf(host.sql, number), at);  if (members.length) {    // What its members already sent is no longer a request.    for (const number of members) host.sql.exec("UPDATE chat_held SET request = 0 WHERE group_id = ? AND peer = ?", group, number);  } else {    host.sql.exec("DELETE FROM chat_held WHERE group_id = ? AND request = 1", group);  }  return { ok: true };}function groupOf(raw: unknown): string | null {  if (raw === undefined || raw === null) return null;  return typeof raw === "string" && GROUP.test(raw) ? raw : refuse(400, "bad_group", "group: the group's id, 32 hex digits");}/** * The keys to seal for when writing to several numbers at once (a group's * members): each number's devices, as `GET /v1/chat/keys` answers it, a * made-up device for a number nobody holds, and this person's own other * devices. A number this phone asked in the last hour costs nothing again; a * new one counts against the same hourly limit a single lookup does, so a * batch walks the numbers no faster than one lookup at a time. */async function manyKeys(host: ChatHost, deviceId: string, raw: unknown): Promise<{ peers: Record<string, ChatKey[]>; own: ChatKey[] }> {  const list = Array.isArray(raw) ? raw : refuse(400, "bad_numbers", "numbers: the numbers to seal for");  if (!list.length || list.length > GROUP_MEMBERS_MAX) refuse(400, "bad_numbers", `numbers: one to ${GROUP_MEMBERS_MAX}`);  const numbers = [...new Set(list.map((n) => numberOf(n)))];  const who = `chat-keys:${deviceId}`;  const fresh: string[] = [];  for (const number of numbers) {    if (number === host.ownerPhone) continue;    if (count(host.sql, `chat-key:${deviceId}:${await keyOf(host.sql, number)}`, HOUR) === 0) fresh.push(number);  }  await gate.firstContacts(host, numbers, "member");  if (fresh.length && count(host.sql, who, HOUR) + fresh.length > LOOKUPS_PER_HOUR) refuse(429, "too_many_lookups", "Too many lookups from this phone in the last hour; try again later.");  for (const number of fresh) {    hit(host.sql, who);    hit(host.sql, `chat-key:${deviceId}:${await keyOf(host.sql, number)}`);  }  const own = (await ownKeys(host)).filter((k) => k.deviceId !== deviceId).map(sealable);  const peers: Record<string, ChatKey[]> = {};  await Promise.all(    numbers      .filter((n) => n !== host.ownerPhone)      .map(async (number) => {        peers[number] = await theirDevices(host, number);      }),  );  return { peers, own };}/** The number's object is found and handed its boxes; whatever it does with them is not this object's to know. */async function handOver(host: ChatHost, to: string, delivery: Delivery): Promise<void> {  try {    const slug = await directory(host.env).lookup(to);    if (!slug || slug === host.slug) return;    await peer(host.env, slug).chatDeliver(delivery);  } catch (error) {    // Refused as "try again" (a frozen account): kept and tried again on this object's alarm (src/handover.ts).    if (handover.retryable(error)) handover.keep(host.sql, "chat", to, delivery);    // Else: an envelope that could not be handed over reads as one never read.  }}/** * Another object's envelope arriving here: dropped unsaid when its sender is * blocked or over the limits, or it was taken already; else held for each of * this object's devices it carries a box for, handed to their open sockets, * and a phone with none open is told "New message". * * Only from someone this owner accepted, or a member of the group it names as * this owner's phone said it (gate.admits, DISCOVERY OFF 3). Anyone else's box * never reaches a phone here, so no phone ever answers a sender it has not * accepted (not even "unreadable"); a stranger's one-to-one message is taken * as their ask instead, under the asks' rules (gate.askAdmits), and nothing * else of theirs is kept. */export async function deliverIn(host: ChatHost, delivery: Delivery): Promise<void> {  sweep(host.sql);  if (!KINDS.includes(delivery.kind) || !ID.test(delivery.id)) return;  const from = numberOf(delivery.from);  if (from === host.ownerPhone) return;  if (await blocked(host.sql, from)) return;  let group: string | null;  try {    group = groupOf(delivery.group);  } catch {    return;  }  // Someone this owner waited for wrote: they are on Cotton, and they wrote to this owner.  if (delivery.kind === "message" && !group && (await gate.accepted(host.sql, from))) reached(host, from);  if (!(await gate.admits(host.sql, from, group))) {    // Sealed words from someone this owner never accepted: none reach a phone. A one-to-one message is their ask.    if (delivery.kind === "message" && !group && delivery.resend !== true) await askIn(host, { from, name: null });    return;  }  const sender = await mac(host.sql, `chat:${delivery.fromSlug}`);  if (delivery.resend === true) return resendIn(host, delivery, from, sender);  const seenKey = `in:${sender}:${delivery.kind}:${delivery.id}`;  if (host.sql.exec("SELECT 1 FROM chat_seen WHERE key = ?", seenKey).toArray().length) return;  if (delivery.kind === "message" || delivery.kind === "group") {    const who = `chat-in:${sender}`;    const over = count(host.sql, who, 10 * 60_000) >= FROM_PEER_10_MIN;    hit(host.sql, who);    if (over) return;  }  let boxes: Record<string, string>;  try {    boxes = boxesOf(delivery.boxes);  } catch {    return;  }  if (delivery.kind !== "typing") host.sql.exec("INSERT OR IGNORE INTO chat_seen (key, at) VALUES (?, ?)", seenKey, Date.now());  const own = await ownKeys(host);  const at = typeof delivery.at === "number" && Number.isFinite(delivery.at) ? delivery.at : Date.now();  for (const device of own) {    const box = boxes[device.device];    if (box) await land(host, device.deviceId, { id: delivery.id, kind: delivery.kind, peer: from, out: false, request: false, box, at, group });  }}/** * A message re-sent for one of this object's devices after its ratchet lost * the first box: its one box, for a device here, held for that device alone, * once. Anything else is dropped unsaid. */async function resendIn(host: ChatHost, delivery: Delivery, from: string, sender: string): Promise<void> {  if (delivery.kind !== "message" || delivery.group) return;  let boxes: Record<string, string>;  try {    boxes = boxesOf(delivery.boxes);  } catch {    return;  }  const entries = Object.entries(boxes);  if (entries.length !== 1) return;  const [handle, box] = entries[0]!;  const device = (await ownKeys(host)).find((k) => k.device === handle);  if (!device) return;  const seenKey = `in-resend:${sender}:${handle}:${delivery.id}`;  if (host.sql.exec("SELECT 1 FROM chat_seen WHERE key = ?", seenKey).toArray().length) return;  // Counted as any message from them is: a re-send never gets past a limit the first send would not.  const who = `chat-in:${sender}`;  const over = count(host.sql, who, 10 * 60_000) >= FROM_PEER_10_MIN;  hit(host.sql, who);  if (over) return;  host.sql.exec("INSERT OR IGNORE INTO chat_seen (key, at) VALUES (?, ?)", seenKey, Date.now());  host.sql.exec("DELETE FROM chat_held WHERE device_id = ? AND kind = ? AND id = ?", device.deviceId, delivery.kind, delivery.id);  const at = typeof delivery.at === "number" && Number.isFinite(delivery.at) ? delivery.at : Date.now();  await land(host, device.deviceId, { id: delivery.id, kind: delivery.kind, peer: from, out: false, request: false, box, at, group: null });}/** * One box reaching one of this object's devices: typing goes to its open * sockets alone; the rest is held until it is taken, handed to its sockets, * and a message to a phone with none open is an alert. */async function land(host: ChatHost, deviceId: string, item: Item): Promise<void> {  const sockets = host.sockets(deviceId);  if (item.kind !== "typing") {    host.sql.exec(      "INSERT OR IGNORE INTO chat_held (device_id, kind, id, peer, out, request, box, at, group_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",      deviceId,      item.kind,      item.id,      item.peer,      item.out ? 1 : 0,      item.request ? 1 : 0,      item.box,      item.at,      item.group,    );  }  const frame = JSON.stringify({ t: "envelope", item });  let handed = false;  for (const ws of sockets) {    try {      ws.send(frame);      handed = true;    } catch {      // A socket closing as it was sent to: the item stays held.    }  }  // A message to a phone with no socket open is an alert; this person's own read on another phone, a silent nudge (its notification goes).  const readElsewhere = item.kind === "receipt" && item.out;  if (handed || (item.kind !== "message" && !readElsewhere)) return;  const device = host.sql.exec<{ platform: Platform | null; token: string | null; topic: string | null; sandbox: number }>("SELECT platform, token, topic, sandbox FROM chat_device WHERE device_id = ?", deviceId).toArray()[0];  if (!device?.platform || !device.token) return;  const to = { platform: device.platform, token: device.token, topic: device.topic ?? "", sandbox: device.sandbox === 1 };  const outcome = readElsewhere ? await nudge(host.env, to) : await alert(host.env, to, item);  if (outcome === "gone") host.sql.exec("UPDATE chat_device SET token = NULL, platform = NULL, topic = NULL WHERE device_id = ?", deviceId);}/** What waits for one device, oldest first. */export function held(sql: SqlStorage, deviceId: string): Item[] {  return sql    .exec<{ id: string; kind: Kind; peer: string; out: number; request: number; box: string; at: number; group_id: string | null }>("SELECT id, kind, peer, out, request, box, at, group_id FROM chat_held WHERE device_id = ? ORDER BY at, rowid", deviceId)    .toArray()    .map((r) => ({ id: r.id, kind: r.kind, peer: r.peer, out: r.out === 1, request: r.request === 1, box: r.box, at: r.at, group: r.group_id ?? null }));}/** A device took these: they go from its queue, and only its. */export function take(sql: SqlStorage, deviceId: string, raw: unknown): void {  const items = Array.isArray(raw) ? raw : [];  for (const item of items.slice(0, 500)) {    const id = (item as { id?: unknown })?.id;    const kind = (item as { kind?: unknown })?.kind;    if (typeof id === "string" && typeof kind === "string") sql.exec("DELETE FROM chat_held WHERE device_id = ? AND kind = ? AND id = ?", deviceId, kind, id);  }}/** Adds a phone makes in an hour: enough to add one's people by number, too few to ask the numbers in bulk. */export const ACCEPTS_PER_HOUR = 60;/** The new-number limits live in the gate (gate.ts); kept here by name for what reads them from chat. */export const NEW_NUMBERS_PER_HOUR = gate.NEW_NUMBERS_PER_HOUR;export const NEW_NUMBERS_PER_DAY = gate.NEW_NUMBERS_PER_DAY;/** An ask's name at most, in characters. */const ASK_NAME_MAX = 80;/** * A number the owner may add as one of their people (Account's Your people, * 14 Nov 2026, from any Cotton app): never their own, said in plain words. * Nothing here says whether the number is on Cotton: any valid number is * added and waits, and becomes a connection only when its owner adds back * (one who joins Cotton later included). Accepting a stranger's request * passes the same way. */function addable(host: ChatHost, number: string): void {  if (number === host.ownerPhone) refuse(400, "own_number", "That is your own number. Add someone else's.");  const who = "chat-accept";  if (count(host.sql, who, HOUR) >= ACCEPTS_PER_HOUR) refuse(429, "too_many_adds", "Too many people added from this phone in the last hour; try again later.");  hit(host.sql, who);}/** The ask an add leaves with the number's object, if Cotton holds one: found by the directory, and nothing said back. */async function askOver(host: ChatHost, number: string): Promise<void> {  if (!host.ownerPhone) return;  try {    const slug = await directory(host.env).lookup(number);    if (!slug || slug === host.slug) return;    await peer(host.env, slug).chatAskIn({ from: host.ownerPhone, name: host.ownerName?.() ?? null });  } catch {    // An ask that could not be handed over reads as one never answered.  }}/** What one object hands another at an add: the asker's number and the account name they volunteer by asking. */export interface Ask {  from: string;  name: string | null;}/** An ask arrives: held for the owner's answer, unless the asker is blocked, already accepted, or over the strangers' limits. */export async function askIn(host: ChatHost, ask: Ask): Promise<void> {  let from: string;  try {    from = numberOf(ask.from);  } catch {    return;  }  if (from === host.ownerPhone || (await blocked(host.sql, from))) return;  if (await gate.accepted(host.sql, from)) {    // Someone this owner waited for added them back (accepted their ask): they can be written to now.    reached(host, from);    return;  }  // Blocked, a request the owner deleted (until they accept), or over the strangers' limits: dropped unsaid.  if (!(await gate.askAdmits(host, from))) return;  const key = await keyOf(host.sql, from);  const name = typeof ask.name === "string" && ask.name.trim() ? ask.name.trim().slice(0, ASK_NAME_MAX) : null;  const known = host.sql.exec("SELECT 1 FROM chat_ask WHERE key = ?", key).toArray().length > 0;  host.sql.exec("INSERT INTO chat_ask (key, number, name, at) VALUES (?, ?, ?, ?) ON CONFLICT (key) DO UPDATE SET name = COALESCE(excluded.name, chat_ask.name), at = excluded.at", key, from, name, new Date().toISOString());  await reseal(host, "chat_ask", key);  // A new ask is a message request in Chat: the owner's phones are woken to show it (an ask asked again is not news).  if (!known) await askTold(host);}/** Who asks to chat with this owner, the latest first: their number, the name their ask carried, and when. */export function asksOf(sql: SqlStorage): { number: string | null; name: string | null; at: string; sealed?: string }[] {  return sql.exec<{ number: string; name: string | null; at: string; sealed: string | null }>("SELECT number, name, at, sealed FROM chat_ask ORDER BY at DESC, number").toArray().map((a) => ({ number: a.number || null, name: a.name ?? null, at: a.at, ...(a.sealed ? { sealed: a.sealed } : {}) }));}/** * Every phone of this owner told that someone asks: an open socket a frame * `{ t: "ask" }` (the phone reads its inbox, which lists the asks), a phone * with none an alert as a stranger's request gets one, "New message" and * nothing else. Nothing of the ask is in either. */async function askTold(host: ChatHost): Promise<void> {  const frame = JSON.stringify({ t: "ask" });  const devices = host.sql.exec<{ device_id: string; platform: Platform | null; token: string | null; topic: string | null; sandbox: number }>("SELECT device_id, platform, token, topic, sandbox FROM chat_device").toArray();  await Promise.all(    devices.map(async (device) => {      let handed = false;      for (const ws of host.sockets(device.device_id)) {        try {          ws.send(frame);          handed = true;        } catch {          // Closing: the alert below, or the inbox at the phone's next pass.        }      }      if (handed || !device.platform || !device.token) return;      const outcome = await alert(host.env, { platform: device.platform, token: device.token, topic: device.topic ?? "", sandbox: device.sandbox === 1 });      if (outcome === "gone") host.sql.exec("UPDATE chat_device SET token = NULL, platform = NULL, topic = NULL WHERE device_id = ?", device.device_id);    }),  );}/** The asker took their add back: their ask goes. */export async function askWithdrawn(host: ChatHost, from: string): Promise<void> {  const number = normalizePhone(from);  if (number) host.sql.exec("DELETE FROM chat_ask WHERE key = ?", await keyOf(host.sql, number));}/** The owner's add taken back from the other person's object, off the request. */async function withdrawAsk(host: ChatHost, number: string): Promise<void> {  if (!host.ownerPhone) return;  try {    const slug = await directory(host.env).lookup(number);    if (slug && slug !== host.slug) await peer(host.env, slug).chatAskWithdrawn(host.ownerPhone);  } catch {    // Unheard, the ask stays until they answer it; accepting it then makes nobody a connection the owner removed only on one side.  }}/** What reading this owner's people needs of an object. */type Lookup = Pick<ChatHost, "sql" | "env" | "slug" | "ownerPhone" | "arrival">;/** One of this owner's people: their number, the name their ask carried (if any), and whether they are still waiting to add this owner back. */export interface Person {  /** Null once the row keeps only its sealed copy (b.4 step B): his phone reads the number from `sealed`. */  number: string | null;  name: string | null;  waiting: boolean;  /** Their account was erased (they told this object as it went): "left Cotton". */  left?: true;  /** The number now leads to another account than the one they were accepted as: nothing goes to it. */  changed?: true;  /** Their number and name sealed to the owner's arrival key (b.4), when the object holds the copy. */  sealed?: string;}/** * `GET /v1/chat/people`: this owner's people, everyone they accepted and have * not blocked, the latest first, each saying whether they wait (have not * added this owner back: never added, removed or blocked look the same); and * who asks, the latest first, by number and the name their ask carried; and * (added 15 Nov 2026, a key older phones never read) who the owner blocked, * the latest first, so a block can be taken back from Your people. Nothing * here is asked of a blocked person's object. */export async function peopleOf(host: Lookup): Promise<{ people: Person[]; asking: { number: string | null; name: string | null; at: string }[]; blocked: Blocked[] }> {  // Someone unblocked elsewhere (Calling's unblock keeps only the key) goes back where they were before reading on.  for (const { key } of host.sql.exec<{ key: string }>("SELECT key FROM chat_blocked WHERE key NOT IN (SELECT key FROM call_block)").toArray()) {    restore(host.sql, key);    await resealBoth(host, key);  }  const owner = host.ownerPhone ? await numberDigest(host.ownerPhone) : null;  const people: Person[] = [];  type Row = { key: string; number: string | null; name: string | null; slug: string | null; left_at: string | null; sealed: string | null; digest: string | null };  // His people only: a row with neither a number nor a sealed copy (made before rows kept numbers) names nobody.  const peers = host.sql.exec<Row>("SELECT key, number, name, slug, left_at, sealed, digest FROM chat_peer WHERE number IS NOT NULL OR sealed IS NOT NULL ORDER BY at DESC, number").toArray();  const rows = new Map<Person, Row>();  for (const row of peers) {    if ((row.number && row.number === host.ownerPhone) || (owner && row.digest === owner)) continue;    if (host.sql.exec("SELECT 1 FROM call_block WHERE key = ?", row.key).toArray().length) continue;    const person: Person = { number: row.number || null, name: row.name ?? null, waiting: true, ...(row.sealed ? { sealed: row.sealed } : {}) };    people.push(person);    rows.set(person, row);    rowKeyOf.set(person, row.key);  }  await Promise.all(    people.map(async (person) => {      const was = rows.get(person)!;      const now = await standing(host, was);      if (was.slug && now.slug !== was.slug) {        // Erased, or the number now another account's: "left Cotton" when they told us, else the number changed hands.        if (now.slug) person.changed = true;        else person.left = true;        return;      }      if (was.left_at && !now.slug) {        person.left = true;        return;      }      person.waiting = !now.adds;      // Bound the first time they add back: from then on the number alone never decides who they are.      if (now.adds && now.slug && !was.slug) host.sql.exec("UPDATE chat_peer SET slug = ? WHERE key = ? AND slug IS NULL", now.slug, was.key);    }),  );  const asking = asksOf(host.sql);  const held = host.sql    .exec<{ number: string; name: string | null; at: string; sealed: string | null }>("SELECT number, name, at, sealed FROM chat_blocked WHERE key IN (SELECT key FROM call_block) ORDER BY at DESC, number")    .toArray()    .map((b) => ({ number: b.number || null, name: b.name ?? null, at: b.at, ...(b.sealed ? { sealed: b.sealed } : {}) }));  return { people, asking, blocked: held };}/** One person the owner blocked from a chat route: their number, the name they had here, and when. Their object is never asked anything. */export interface Blocked {  /** Null once the row keeps only its sealed copy (b.4 step B). */  number: string | null;  name: string | null;  at: string;  sealed?: string;}/** Each listed person's row key (this object's HMAC of the number), for the object's own lookups; never sent out. */export const rowKeyOf = new WeakMap<Person, string>();/** A block taken back: the person returns to where they were before it (one of the owner's people, or asking), else to nobody. */function restore(sql: SqlStorage, key: string): void {  const row = sql.exec<{ number: string; name: string | null; was: string | null; was_at: string | null; sealed: string | null; digest: string | null }>("SELECT number, name, was, was_at, sealed, digest FROM chat_blocked WHERE key = ?", key).toArray()[0];  sql.exec("DELETE FROM chat_blocked WHERE key = ?", key);  if (!row?.was_at) return;  // The sealed copy and digest go back with the row: one that keeps no clear number cannot be sealed again here.  if (row.was === "person") sql.exec("INSERT OR IGNORE INTO chat_peer (key, number, name, at, sealed, digest) VALUES (?, ?, ?, ?, ?, ?)", key, row.number || null, row.name, row.was_at, row.sealed, row.digest);  if (row.was === "asking") sql.exec("INSERT OR IGNORE INTO chat_ask (key, number, name, at, sealed, digest) VALUES (?, ?, ?, ?, ?, ?)", key, row.number ?? "", row.name, row.was_at, row.sealed, row.digest);}/** The object `number` leads to now, and whether its owner has this owner among their people. */async function standing(host: Lookup, who: { number: string | null; digest: string | null }): Promise<{ slug: string | null; adds: boolean }> {  if (!host.ownerPhone) return { slug: null, adds: false };  try {    const slug = await leadsTo(host, who);    if (!slug || slug === host.slug) return { slug: null, adds: false };    return { slug, adds: await peer(host.env, slug).chatAccepts(host.ownerPhone) };  } catch {    return { slug: null, adds: false };  }}/** The object a Circle row's person leads to now: by its digest when it keeps one, else its clear number (an older row). */async function leadsTo(host: Pick<Lookup, "env">, who: { number: string | null; digest: string | null }): Promise<string | null> {  if (who.digest) return directory(host.env).lookupDigest(who.digest);  return who.number ? directory(host.env).lookup(who.number) : null;}/** * Whether `number` still leads to the account it was accepted as (b.4 hardening): true while no object was bound yet * or the directory leads to the same one. A number that now leads elsewhere gets nothing that is sealed to a person. */export async function stillTheirs(host: Lookup, number: string): Promise<boolean> {  const row = host.sql.exec<{ slug: string | null }>("SELECT slug FROM chat_peer WHERE key = ?", await keyOf(host.sql, number)).toArray()[0];  if (!row?.slug) return true;  try {    return (await directory(host.env).lookup(number)) === row.slug;  } catch {    return false;  }}/** Their account is being erased: their object says so before the directory lets the number go ("left Cotton"). */export async function goneIn(host: Pick<ChatHost, "sql">, from: string): Promise<void> {  let number: string;  try {    number = numberOf(from);  } catch {    return;  }  host.sql.exec("UPDATE chat_peer SET left_at = ? WHERE key = ?", new Date().toISOString(), await keyOf(host.sql, number));  host.sql.exec("DELETE FROM chat_ask WHERE key = ?", await keyOf(host.sql, number));}/** This account is being erased: every one of its people's objects is told, best effort, while the number is still this account's. */export async function tellGone(host: Lookup): Promise<number> {  if (!host.ownerPhone) return 0;  let told = 0;  for (const { number, slug, digest } of host.sql.exec<{ number: string | null; slug: string | null; digest: string | null }>("SELECT number, slug, digest FROM chat_peer WHERE number IS NOT NULL OR digest IS NOT NULL").toArray()) {    try {      const to = slug ?? (await leadsTo(host, { number, digest }));      if (!to || to === host.slug) continue;      await peer(host.env, to).chatGone(host.ownerPhone);      told++;    } catch {      // Not told: they see "waiting" until the number leads nowhere, then "left Cotton".    }  }  return told;}/** Whether this object's owner has `number` among their people: accepted, and not blocked. Another object asks it by RPC (Send's waiting). */export async function accepts(sql: SqlStorage, number: string): Promise<boolean> {  return gate.isPerson(sql, number);}/** * The owner's answer to a person: accept their request, refuse it (what they * sent goes), block them, unblock, or remove them from their people (Send, * 13 Nov 2026: no longer accepted, so no send goes either way, and what Send * held from or for them goes; a later message from them is a request again). */async function decide(host: ChatHost, what: "accept" | "refuse" | "block" | "unblock" | "remove", number: string): Promise<void> {  const key = await keyOf(host.sql, number);  if (what === "remove" || what === "block") await unwait(host, number);  if (what === "remove") {    host.sql.exec("DELETE FROM chat_peer WHERE key = ?", key);    host.sql.exec("DELETE FROM chat_ask WHERE key = ?", key);    await host.forget?.(number);    host.waitUntil(withdrawAsk(host, number));    return;  }  if (what === "accept") {    await accept(host.sql, number, new Date().toISOString());    // Accepted from their ask, the name it carried names them: its clear name, or its sealed copy when that is all it keeps.    host.sql.exec("UPDATE chat_peer SET name = (SELECT name FROM chat_ask WHERE key = ?) WHERE key = ? AND name IS NULL", key, key);    if (!(await carry(host, "chat_ask", "chat_peer", key))) await reseal(host, "chat_peer", key);    host.sql.exec("DELETE FROM chat_ask WHERE key = ?", key);    host.sql.exec("DELETE FROM chat_ask_refused WHERE key = ?", key);    host.sql.exec("UPDATE chat_held SET request = 0 WHERE peer = ?", number);    return;  }  if (what === "unblock") {    host.sql.exec("DELETE FROM call_block WHERE key = ?", key);    restore(host.sql, key);    return;  }  if (what === "block") {    // Kept to list them under Blocked and to return them where they were at Unblock: one of the owner's people, or asking.    const peer = host.sql.exec<{ name: string | null; at: string }>("SELECT name, at FROM chat_peer WHERE key = ?", key).toArray()[0];    const ask = host.sql.exec<{ name: string | null; at: string }>("SELECT name, at FROM chat_ask WHERE key = ?", key).toArray()[0];    const was = peer ? "person" : ask ? "asking" : null;    const kept = host.sql.exec("SELECT 1 FROM chat_blocked WHERE key = ?", key).toArray()[0];    // Blocked again while blocked, the first block's record stands.    if (!kept || !(await blocked(host.sql, number))) {      host.sql.exec(        "INSERT OR REPLACE INTO chat_blocked (key, number, name, was, was_at, at) VALUES (?, ?, ?, ?, ?, ?)",        key, number, peer?.name ?? ask?.name ?? null, was, peer?.at ?? ask?.at ?? null, new Date().toISOString(),      );      if (!(await carry(host, peer ? "chat_peer" : "chat_ask", "chat_blocked", key))) await reseal(host, "chat_blocked", key);    }  }  // Refused or blocked, what a request brought goes from every device here, and their ask; a block is Calling's too.  host.sql.exec("DELETE FROM chat_held WHERE peer = ? AND request = 1", number);  host.sql.exec("DELETE FROM chat_ask WHERE key = ?", key);  if (what === "refuse") host.sql.exec("INSERT OR IGNORE INTO chat_ask_refused (key, at) VALUES (?, ?)", key, new Date().toISOString());  if (what === "block") {    host.sql.exec("INSERT OR IGNORE INTO call_block (key, created_at) VALUES (?, ?)", key, new Date().toISOString());    host.sql.exec("DELETE FROM chat_peer WHERE key = ?", key);    await host.forget?.(number);  }}/** * A phone puts up one sealed picture: its bytes are the core's `cf1` file, * which the Worker cannot open; the answer is the id the message carries. * Any signed-in Cotton phone that knows the id may take it back: the id is * 128 random bits and what it fetches is ciphertext. */async function putFile(host: ChatHost, deviceId: string, request: Request): Promise<{ file: string }> {  const bytes = new Uint8Array(await request.arrayBuffer());  if (bytes.length < 3 + 12 + 16 || bytes.length > FILE_MAX || bytes[0] !== 0x63 || bytes[1] !== 0x66 || bytes[2] !== 0x31) refuse(400, "bad_file", "a chat file is the phone's sealed cf1 file, 16 MB at most");  const who = `chat-files:${deviceId}`;  if (count(host.sql, who, HOUR) >= FILES_PER_HOUR) refuse(429, "too_many_files", "Too many pictures from this phone in the last hour; try again later.");  hit(host.sql, who);  const file = [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, "0")).join("");  await host.env.MEDIA.put(`chat-files/${file}`, bytes, { httpMetadata: { contentType: "application/octet-stream" } });  host.sql.exec("INSERT INTO chat_file (id, bytes, at) VALUES (?, ?, ?)", file, bytes.length, Date.now());  return { file };}async function getFile(env: Env, file: string): Promise<Response> {  return getStored(env, `chat-files/${file}`);}async function getStored(env: Env, key: string): Promise<Response> {  const found = await env.MEDIA.get(key);  if (!found) refuse(404, "not_found", "no such file, or it has gone");  return new Response(found.body, { headers: { "content-type": "application/octet-stream", "cache-control": "private, max-age=86400" } });}/** The object's pictures over thirty days old leave the store. */export async function sweepFiles(host: Pick<ChatHost, "sql" | "env">): Promise<void> {  const old = host.sql.exec<{ id: string }>("SELECT id FROM chat_file WHERE at < ? LIMIT 100", Date.now() - HELD_MS).toArray();  if (!old.length) return;  await host.env.MEDIA.delete(old.map((r) => `chat-files/${r.id}`));  for (const r of old) host.sql.exec("DELETE FROM chat_file WHERE id = ?", r.id);}/** How long a socket ticket opens a socket for: the core asks, the app opens at once. */export const TICKET_TTL_MS = 60_000;/** A socket ticket names the database its object keeps (the open host routes by it) and a secret only that object knows by its hash. */export const TICKET = /^cts_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})_([A-Za-z0-9_-]{43})$/;/** The database a socket ticket names, or null. */export function ticketDatabase(token: string | null): string | null {  return token ? (TICKET.exec(token)?.[1] ?? null) : null;}/** One socket's ticket for a signed-in device: kept by its hash, one use, a minute. */async function mintTicket(host: Pick<ChatHost, "sql" | "databaseId">, deviceId: string): Promise<string> {  if (!host.databaseId) refuse(409, "no_database", "this object keeps no database id to name in a ticket");  if (!host.sql.exec("SELECT 1 FROM chat_device WHERE device_id = ?", deviceId).toArray().length) refuse(409, "no_key", "publish this phone's chat key first (POST /v1/chat/device)");  const now = Date.now();  host.sql.exec("DELETE FROM chat_ticket WHERE until < ?", now);  const secret = b64url(crypto.getRandomValues(new Uint8Array(32)));  host.sql.exec("INSERT INTO chat_ticket (hash, device_id, until) VALUES (?, ?, ?)", await sha256(secret), deviceId, now + TICKET_TTL_MS);  return `cts_${host.databaseId}_${secret}`;}/** The device a ticket was minted for, the ticket spent; a refusal for one not this object's, spent or late. */async function ticketHolder(sql: SqlStorage, token: string | null): Promise<string> {  const secret = token ? TICKET.exec(token)?.[2] : undefined;  if (!secret) refuse(401, "sign_in", "a chat socket opens with a ticket (POST /v1/chat/socket)");  const hash = await sha256(secret);  const row = sql.exec<{ device_id: string; until: number }>("SELECT device_id, until FROM chat_ticket WHERE hash = ?", hash).toArray()[0];  sql.exec("DELETE FROM chat_ticket WHERE hash = ?", hash);  if (!row || row.until < Date.now()) refuse(401, "sign_in", "this chat ticket is spent or late: ask for another");  return row.device_id;}function bearerOf(request: Request): string | null {  const header = request.headers.get("authorization");  return header?.startsWith("Bearer ") ? header.slice("Bearer ".length).trim() : null;}function b64url(bytes: Uint8Array): string {  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}async function sha256(text: string): Promise<string> {  return [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)))].map((b) => b.toString(16).padStart(2, "0")).join("");}/** The socket's path: opened with a ticket, before the object reads any credential (src/business.ts). */export const SOCKET_PATH = "/v1/chat/socket";/** * A socket opened with its ticket, never the device's credential: the phone's * core asks for one (POST, signed in Rust) and the app opens the WebSocket * with it. A ticket opens one socket, for its device, within a minute. */export async function openSocket(host: ChatHost, request: Request): Promise<Response> {  return socket(host, await ticketHolder(host.sql, bearerOf(request)), request);}/** A phone's socket on its own object: everything held for it, then each envelope as it lands. */function socket(host: ChatHost, deviceId: string, request: Request): Response {  if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") refuse(426, "upgrade_required", "the chat socket is a WebSocket");  if (!host.sql.exec("SELECT 1 FROM chat_device WHERE device_id = ?", deviceId).toArray().length) refuse(409, "no_key", "publish this phone's chat key first (POST /v1/chat/device)");  const pair = new WebSocketPair();  const [client, server] = [pair[0], pair[1]];  host.accept(server, deviceId);  for (const item of held(host.sql, deviceId)) server.send(JSON.stringify({ t: "envelope", item }));  return new Response(null, { status: 101, webSocket: client });}/** A frame from a phone's socket: an ack takes what it names, a ping is answered. */export function frameIn(sql: SqlStorage, deviceId: string, ws: WebSocket, text: string): void {  let frame: { t?: unknown; items?: unknown };  try {    frame = JSON.parse(text) as typeof frame;  } catch {    return;  }  if (frame.t === "ack") take(sql, deviceId, frame.items);  else if (frame.t === "ping") ws.send(JSON.stringify({ t: "pong" }));}/** The tag a chat socket carries: its device. */export const SOCKET_TAG = "chat:";function peer(env: Env, slug: string): DurableObjectStub<import("../business.ts").Business> {  return env.BUSINESS.get(env.BUSINESS.idFromName(slug), { locationHint: "apac" });}function boxesOf(raw: unknown): Record<string, string> {  if (!raw || typeof raw !== "object" || Array.isArray(raw)) refuse(400, "bad_boxes", "boxes: the sealed copies by device handle");  const entries = Object.entries(raw as Record<string, unknown>);  if (!entries.length || entries.length > BOXES_MAX) refuse(400, "bad_boxes", `boxes: one to ${BOXES_MAX} sealed copies`);  for (const [handle, box] of entries) {    if (!HANDLE.test(handle) || typeof box !== "string" || !BOX.test(box) || box.length > BOX_MAX) refuse(400, "bad_boxes", "boxes: each a device handle and its c1: or c2: box");  }  return Object.fromEntries(entries) as Record<string, string>;}/** A device's handle: what a sender seals for, never its id. */async function handleOf(sql: SqlStorage, deviceId: string): Promise<string> {  return (await mac(sql, `chat-device:${deviceId}`)).slice(0, 22);}/** The device a number nobody holds answers: its handle and key made from the number under this object's key, the same each time. *//** * What makes a number nobody holds look held (ROUTES-AUDIT 6, 23 Nov 2026): the Worker's own key, the same for every * asking account, so two accounts comparing answers see one made-up device as they see one real one. It was each * asking object's own `call_key`, so the fakes differed by asker while a real account's keys did not. The key is * HMAC-derived from SERVICE_TOKEN_KEY under its own label, never that key itself; a Worker without it keeps the * object's key (a dev Worker with no services). */async function fakeMac(host: Pick<ChatHost, "env" | "sql">, text: string): Promise<string> {  const root = host.env.SERVICE_TOKEN_KEY;  if (!root) return mac(host.sql, text);  const base = await crypto.subtle.importKey("raw", new TextEncoder().encode(root), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);  const derived = new Uint8Array(await crypto.subtle.sign("HMAC", base, new TextEncoder().encode("cotton-chat-made-up-keys:v1")));  const key = await crypto.subtle.importKey("raw", derived, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);  return toB64url(new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(text))));}/** A number nobody holds answers one made-up device, or two for about one number in four: a real account may have several. */async function madeUpDevices(host: Pick<ChatHost, "env" | "sql">, number: string): Promise<ChatKey[]> {  const many = fromB64url(await fakeMac(host, `chat-fake-count:${number}`))[0]! % 4 === 0 ? 2 : 1;  const out: ChatKey[] = [];  for (let i = 0; i < many; i++) out.push(await madeUp(host, number, i));  return out;}/** The made-up device `i` of `number` (the first keeps no index in its labels). */async function madeUp(host: Pick<ChatHost, "env" | "sql">, number: string, i = 0): Promise<ChatKey> {  const of = (what: string) => fakeMac(host, `chat-fake-${what}:${number}${i ? `#${i}` : ""}`);  const bytes = fromB64url(await of("key"));  // A real X25519 public key's top bit is clear; so is this one's.  bytes[31] = bytes[31]! & 0x7f;  const key = toB64url(bytes);  // And it speaks c2 as a phone does: an identity and a signing key made from the number, the record truly signed.  const identity = fromB64url(await of("identity"));  identity[31] = identity[31]! & 0x7f;  const signer = await signerOf(fromB64url(await of("signing")));  const sig = await signer.sign(cat(DEVICE_STATEMENT, bytes, identity));  return { device: (await of("device")).slice(0, 22), key, c2: { identity: toB64url(identity), signing: toB64url(signer.publicRaw), sig: toB64url(sig) } };}/** A one-time key of a made-up device: fresh each claim, as a real one is, and signed by its made-up signing key. */async function madeUpPrekey(host: Pick<ChatHost, "env" | "sql">, number: string, i = 0): Promise<Prekey> {  const of = (what: string) => fakeMac(host, `chat-fake-${what}:${number}${i ? `#${i}` : ""}`);  const identity = fromB64url(await of("identity"));  identity[31] = identity[31]! & 0x7f;  const signer = await signerOf(fromB64url(await of("signing")));  const key = crypto.getRandomValues(new Uint8Array(32));  key[31] = key[31]! & 0x7f;  return { key: toB64url(key), sig: toB64url(await signer.sign(cat(PREKEY_STATEMENT, identity, key))) };}/** * A made-up device's key as a real one is claimed (AUDIT FIX B1, B-3): a one-time key until this asker has claimed as * many as a phone keeps (somewhere between 60 and PREKEYS_MAX, fixed for the number), then its fallback key, the same * every time, as a phone that has not topped up answers. Draining keys no longer tells a made-up number from a real one. */async function madeUpClaimed(host: Pick<ChatHost, "env" | "sql">, number: string, i: number, handle: string): Promise<Prekey> {  const held = host.sql.exec<{ n: number }>("SELECT n FROM chat_fake_claim WHERE handle = ?", handle).toArray()[0]?.n ?? 0;  host.sql.exec("INSERT INTO chat_fake_claim (handle, n) VALUES (?, 1) ON CONFLICT (handle) DO UPDATE SET n = n + 1", handle);  const shelf = 60 + (fromB64url(await fakeMac(host, `chat-fake-shelf:${number}${i ? `#${i}` : ""}`))[0]! % (PREKEYS_MAX - 59));  if (held < shelf) return madeUpPrekey(host, number, i);  const of = (what: string) => fakeMac(host, `chat-fake-${what}:${number}${i ? `#${i}` : ""}`);  const identity = fromB64url(await of("identity"));  identity[31] = identity[31]! & 0x7f;  const signer = await signerOf(fromB64url(await of("signing")));  const key = fromB64url(await of("fallback"));  key[31] = key[31]! & 0x7f;  return { key: toB64url(key), sig: toB64url(await signer.sign(cat(PREKEY_STATEMENT, identity, key))), fallback: true };}const DEVICE_STATEMENT = new TextEncoder().encode("cotton-chat-c2-device");const PREKEY_STATEMENT = new TextEncoder().encode("cotton-chat-c2-prekey");/** PKCS#8's wrapping of a 32-byte Ed25519 seed (RFC 8410). */const ED25519_PKCS8 = Uint8Array.from([0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20]);/** An Ed25519 key from its 32-byte seed: its public half and a signer (cotton-core chat/ratchet.rs checks what it signs). */export async function signerOf(seed: Uint8Array): Promise<{ publicRaw: Uint8Array; sign(message: Uint8Array): Promise<Uint8Array> }> {  const privateKey = await crypto.subtle.importKey("pkcs8", cat(ED25519_PKCS8, seed.slice(0, 32)), { name: "Ed25519" }, true, ["sign"]);  const jwk = (await crypto.subtle.exportKey("jwk", privateKey)) as JsonWebKey;  return { publicRaw: fromB64url(jwk.x!), sign: async (message) => new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, privateKey, message)) };}function cat(...parts: Uint8Array[]): Uint8Array {  const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));  let at = 0;  for (const p of parts) {    out.set(p, at);    at += p.length;  }  return out;}function isPublicKey(value: string): boolean {  if (!/^[A-Za-z0-9_-]{43}$/.test(value)) return false;  try {    return fromB64url(value).length === 32;  } catch {    return false;  }}function fromB64url(text: string): Uint8Array {  const padded = text.replace(/-/g, "+").replace(/_/g, "/");  return Uint8Array.from(atob(padded + "=".repeat((4 - (padded.length % 4)) % 4)), (c) => c.charCodeAt(0));}function toB64url(bytes: Uint8Array): string {  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}function sweep(sql: SqlStorage): void {  sql.exec("DELETE FROM chat_held WHERE at < ?", Date.now() - HELD_MS);  sql.exec("DELETE FROM chat_seen WHERE at < ?", Date.now() - SEEN_MS);}// ── finding people and waiting for them (20 Nov 2026) ───────────────────/** One number this owner waits for: an invite sent, or a message written to someone not found on Cotton. */export interface Waiting {  number: string;  ticket: string;  state: "waiting" | "reached";  at: string;}/** * `POST /v1/chat/wait {number}`: this owner writes to a number Cotton did * not find, so the message waits on their phone (no device to seal for yet). * Writing accepts them, as a sent message does. The directory keeps the wait * until that number's first chat device, or answers at once when the number * is on Cotton: that person gets this owner's ask, as an add from Your people * does, and it stays `waiting` until they accept it. So the answer is * `waiting` whether or not the number is on Cotton: it never says which * (DISCOVERY OFF 1: nobody is found by their number). This is the one lookup * left, one number the person picked, counted in the directory per day. */async function waitFor(host: ChatHost, number: string): Promise<{ state: Waiting["state"] }> {  addable(host, number);  await gate.firstContact(host, number, "one");  const now = new Date().toISOString();  await accept(host.sql, number, now);  await reseal(host, "chat_peer", await keyOf(host.sql, number));  const answer = await directory(host.env).wait(host.slug, await numberDigest(number));  if ("refused" in answer) refuse(answer.refused.status, answer.refused.code, answer.refused.message);  const held = host.sql.exec<{ state: string }>("SELECT state FROM chat_waiting WHERE number = ?", number).toArray()[0];  const state: Waiting["state"] = held?.state === "reached" ? "reached" : "waiting";  host.sql.exec("INSERT INTO chat_waiting (number, ticket, state, at) VALUES (?, ?, ?, ?) ON CONFLICT (number) DO UPDATE SET ticket = excluded.ticket, state = excluded.state", number, answer.ok.ticket, state, now);  if (answer.ok.now) host.waitUntil(askOver(host, number));  return { state };}/** A wait taken back (the chat deleted, the person removed or blocked). */async function unwait(host: ChatHost, number: string): Promise<void> {  const row = host.sql.exec<{ ticket: string }>("DELETE FROM chat_waiting WHERE number = ? RETURNING ticket", number).toArray()[0];  if (row) await directory(host.env).unwait(host.slug, row.ticket).catch(() => undefined);}/** `GET /v1/chat/reach`: the numbers this owner waited for that can now be written to, and those still waited for. */export function reachOf(sql: SqlStorage): { reached: string[]; waiting: string[] } {  const rows = sql.exec<{ number: string; state: string }>("SELECT number, state FROM chat_waiting ORDER BY at").toArray();  return { reached: rows.filter((r) => r.state === "reached").map((r) => r.number), waiting: rows.filter((r) => r.state !== "reached").map((r) => r.number) };}/** A number waited for can be written to now: marked, and this owner's open phones told at once. */function reached(host: ChatHost, number: string): void {  const row = host.sql.exec<{ state: string }>("SELECT state FROM chat_waiting WHERE number = ?", number).toArray()[0];  if (!row || row.state === "reached") return;  host.sql.exec("UPDATE chat_waiting SET state = 'reached' WHERE number = ?", number);  const frame = JSON.stringify({ t: "reach", number });  for (const { device_id } of host.sql.exec<{ device_id: string }>("SELECT device_id FROM chat_device").toArray()) {    for (const ws of host.sockets(device_id)) {      try {        ws.send(frame);      } catch {        // Closing: the phone asks /v1/chat/reach at its next pass.      }    }  }}/** At most one `{ t: "rows" }` per phone in this long: a Mac's import moves the version hundreds of times a minute. */export const ROWS_WINDOW_MS = 1_500;/** What the object remembers of its rows frames, in memory only: losing it at an eviction costs one early frame. */export interface RowsNotice {  /** When each phone was last told. */  told: Map<string, number>;  /** Phones owed a frame at the window's end, by the version to say. */  owed: Map<string, number>;  timer: ReturnType<typeof setTimeout> | null;}export function rowsNotice(): RowsNotice {  return { told: new Map(), owed: new Map(), timer: null };}/** * Rows moved in this person's file (a request that moved the version): every * open phone of theirs but the one that wrote is told `{ t: "rows", v }`, a * few bytes and nothing of what moved, so it pulls now instead of at its next * minute. This is how a change his Mac writes (a WhatsApp message, a vote, a * reaction, a delete) reaches an open Comms in seconds, as a Cotton message * does over this same socket. * * A burst is one frame then one more: a phone told within the last * ROWS_WINDOW_MS is owed a frame at that window's end, saying the newest * version, and is told nothing in between. A phone with no socket open hears * nothing and pulls at its own time; a phone older than this frame passes it * over (it reads only the frames it knows); an object older than this sends * none, and phones pull at their minute as before. */export function rowsMoved(host: Pick<ChatHost, "sql" | "sockets">, notice: RowsNotice, writer: string | null, version: number, now = Date.now()): void {  for (const { device_id } of host.sql.exec<{ device_id: string }>("SELECT device_id FROM chat_device").toArray()) {    if (device_id === writer || !host.sockets(device_id).length) continue;    const told = notice.told.get(device_id);    if (told === undefined || now - told >= ROWS_WINDOW_MS) {      notice.owed.delete(device_id);      tellRows(host, notice, device_id, version, now);    } else {      notice.owed.set(device_id, version);    }  }  if (notice.owed.size && !notice.timer) {    const due = Math.min(...[...notice.owed.keys()].map((d) => (notice.told.get(d) ?? now) + ROWS_WINDOW_MS));    notice.timer = setTimeout(() => {      notice.timer = null;      const at = Date.now();      const owed = [...notice.owed];      notice.owed.clear();      for (const [device, v] of owed) tellRows(host, notice, device, v, at);    }, Math.max(0, due - now));  }}function tellRows(host: Pick<ChatHost, "sockets">, notice: RowsNotice, deviceId: string, version: number, now: number): void {  notice.told.set(deviceId, now);  const frame = JSON.stringify({ t: "rows", v: version });  for (const ws of host.sockets(deviceId)) {    try {      ws.send(frame);    } catch {      // Closing: the phone pulls at its own time.    }  }}/** This owner's number can be written to: everyone who waited for it is told, each by their own object. */async function joined(host: ChatHost): Promise<void> {  if (!host.ownerPhone) return;  const { waiters } = await directory(host.env).joined(host.slug, host.ownerPhone, host.spaceCounting?.() ?? false);  await Promise.all(waiters.map((w) => peer(host.env, w.slug).chatJoined({ ticket: w.ticket }).catch(() => undefined)));}/** * Someone this owner waited for has joined: they are asked (this owner's * number and name, as an add asks) and are reached when they accept. */export async function joinedIn(host: ChatHost, word: { ticket: string }): Promise<void> {  const row = host.sql.exec<{ number: string }>("SELECT number FROM chat_waiting WHERE ticket = ?", String(word.ticket)).toArray()[0];  if (!row) return;  await askOver(host, row.number);}/** * `PUT /v1/chat/profile-picture`: the owner's picture as the people they * write to see it, a `cf1` file sealed on the phone (the key travels inside * each message's box, never here). Unlike a message's pictures it is not * swept at thirty days, since someone may first write to this owner much * later; the one it replaces goes. Counted with the chat files. */async function putProfilePicture(host: ChatHost, deviceId: string, request: Request): Promise<{ file: string }> {  const bytes = new Uint8Array(await request.arrayBuffer());  if (bytes.length < 3 + 12 + 16 || bytes.length > FILE_MAX || bytes[0] !== 0x63 || bytes[1] !== 0x66 || bytes[2] !== 0x31) refuse(400, "bad_file", "a profile picture is the phone's sealed cf1 file, 16 MB at most");  const who = `chat-files:${deviceId}`;  if (count(host.sql, who, HOUR) >= FILES_PER_HOUR) refuse(429, "too_many_files", "Too many pictures from this phone in the last hour; try again later.");  hit(host.sql, who);  const file = [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, "0")).join("");  await host.env.MEDIA.put(`chat-profile/${file}`, bytes, { httpMetadata: { contentType: "application/octet-stream" } });  const old = host.sql.exec<{ id: string }>("SELECT id FROM chat_profile_file").toArray();  if (old.length) await host.env.MEDIA.delete(old.map((r) => `chat-profile/${r.id}`));  host.sql.exec("DELETE FROM chat_profile_file");  host.sql.exec("INSERT INTO chat_profile_file (id, at) VALUES (?, ?)", file, Date.now());  return { file };}/** * The invited person's object hands back his invitation (circle_invite.ts `redeemed`): on a live code and a matching * secret, they become one of this owner's people, named with what they gave, unless this owner blocked them. */export async function circleRedeemed(host: ChatHost, r: { code: string; secret: string; from: string; name: string | null }): Promise<circleInvite.Redeemed | null> {  let from: string;  try {    from = numberOf(r.from);  } catch {    return null;  }  return circleInvite.redeemed(host, { ...r, from }, async (number, name) => {    if (await blocked(host.sql, number)) return false;    await decide(host, "accept", number);    const key = await keyOf(host.sql, number);    const given = typeof name === "string" && name.trim() ? name.trim().slice(0, ASK_NAME_MAX) : null;    if (given) host.sql.exec("UPDATE chat_peer SET name = ? WHERE key = ? AND name IS NULL", given, key);    await reseal(host, "chat_peer", key);    return true;  });}