Cotton code
919 lines · 55.8 KB · TypeScriptRaw
/** * THE CIRCLE (TRUSTED RECOVERY BUILD 1, step 4; assets/design/shared/TRUSTED-RECOVERY.md): getting back in with the * help of people a person trusts, so that neither they nor this object can open anything alone. * * The phone that holds the vault mints R and wraps the vault key under a key R gives (the `recovery` row of kind * `circle`, as every way back in). R = H ⊕ Q. This object keeps H. Q is shared among n helpers any k of n (1 of 1, or * 2 of 3; crates/cotton-core recovery_code.rs `circle_pieces`), each piece sealed on the phone to that helper's pinned * sharing key and kept in the helper's own object. A new device gets H only after WAIT_MS that every device of the * person and every helper hears about and any of them can stop, and gets Q only from k helpers who each checked the * device by six digits worked out on both phones (`help_sas`). Helpers are named by their account (their object's * slug), never by a number that could move. * * The person's own signed-in devices (never a token): *   POST /v1/recovery/circle/set     { setup, salt, kdf, auth_hash, wrapped, vmk_version, k, held, members: [{ number, *                                    name?, box }] } → { setup, live: false }   `setup` is minted by the phone: each box *                                    is sealed bound to it and the helper's place (`circle_context`)   by a device that holds the vault. Each box goes *                                    to its helper's object; this one keeps none. An earlier circle, and a trusted person *                                    of the one-helper scheme, are let go (their objects told). *   POST /v1/recovery/circle/retire  → { retired }   by a device that holds the vault *   POST /v1/recovery/circle/start   { device_key, name? } → { request, ends_at }   a new device (signed in by SMS); *                                    one open at a time, STARTS_PER_MONTH in 30 days, none while a Stop's pause holds *   GET  /v1/recovery/circle/request → { state, request, ends_at, k, members: [{ index, name, commit?, nonce_b?, *                                    reveal?, approved }], held?, pieces? }   for the device that started it; `held` and *                                    the k wrapped `pieces` only once the wait is over with k approvals (released once) *   POST /v1/recovery/circle/commit  { index, commit }   the device starts a compare with one helper (a later commit *                                    replaces one not yet approved: an app that restarted compares again) *   POST /v1/recovery/circle/reveal  { index, nonce }   once that helper's nonce is set; it must hash to the commit *   POST /v1/recovery/circle/stop    {} → { stopped }   any device of the person; one that holds the vault also pauses *                                    the circle for PAUSE_MS * The helpers' devices, on their own object: *   GET  /v1/recovery/circle/held    → { held: [{ account, number, name, setup, index, accepted, box }] } *   POST /v1/recovery/circle/accept  { account, setup } | /decline → { ok } *   GET  /v1/recovery/circle/asks    → { asks: [{ request, account, number, name, index, device_key, commit?, nonce_b?, *                                    reveal?, ends_at, setup, box }] } *   POST /v1/recovery/circle/open    { request, account, nonce } → { nonce }   set once per commit *   POST /v1/recovery/circle/approve { request, account, sealed }   only once revealed: the helper's piece wrapped to *                                    the device's key *   POST /v1/recovery/circle/stop-for { request, account }   a helper stops it * Anyone with the link the SMS carries (open host, no bearer): GET and POST /v1/recovery/stop/<database id>/<token>. * * A trusted person of the one-helper scheme (src/recovery.ts, kind `trusted`) keeps working, unchanged, until the * person sets up a circle: nobody loses their way back in through the upgrade. */import { json, readJson, refuse } from "./http.ts";import { helpCommit, noteFlow, shortId } from "./recovery.ts";export const SCHEMA = `CREATE TABLE IF NOT EXISTS recovery_circle (id INTEGER PRIMARY KEY CHECK (id IN (1, 2)), setup TEXT NOT NULL, k INTEGER NOT NULL, n INTEGER NOT NULL, held TEXT NOT NULL, made_by TEXT, at INTEGER NOT NULL, wrap TEXT);CREATE TABLE IF NOT EXISTS recovery_part_stop (request TEXT NOT NULL, idx INTEGER NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (request, idx));CREATE TABLE IF NOT EXISTS recovery_tell (id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, target TEXT NOT NULL, payload TEXT NOT NULL, tries INTEGER NOT NULL, next_at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS recovery_circle_member (setup TEXT NOT NULL, idx INTEGER NOT NULL, account TEXT NOT NULL, number TEXT NOT NULL, name TEXT, accepted_at INTEGER, declined_at INTEGER, gone_at INTEGER, PRIMARY KEY (setup, idx));CREATE TABLE IF NOT EXISTS recovery_request (id TEXT PRIMARY KEY, setup TEXT NOT NULL, device TEXT NOT NULL, device_key TEXT NOT NULL, name TEXT, started_at INTEGER NOT NULL, ends_at INTEGER NOT NULL, state TEXT NOT NULL, stopped_by TEXT, stopped_at INTEGER, released_at INTEGER, approved_any INTEGER, texted INTEGER);CREATE TABLE IF NOT EXISTS recovery_compare (request TEXT NOT NULL, idx INTEGER NOT NULL, commit_hash TEXT NOT NULL, nonce_b TEXT, reveal TEXT, sealed TEXT, approved_at INTEGER, at INTEGER NOT NULL, PRIMARY KEY (request, idx));CREATE TABLE IF NOT EXISTS recovery_pause (id INTEGER PRIMARY KEY CHECK (id = 1), until INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS recovery_stop_link (token_hash TEXT PRIMARY KEY, request TEXT NOT NULL, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS recovery_circle_held (account TEXT NOT NULL, setup TEXT NOT NULL, number TEXT NOT NULL, name TEXT, idx INTEGER NOT NULL, box TEXT NOT NULL, accepted_at INTEGER, declined_at INTEGER, at INTEGER NOT NULL, live INTEGER, PRIMARY KEY (account, setup));CREATE TABLE IF NOT EXISTS recovery_circle_in (request TEXT NOT NULL, account TEXT NOT NULL, setup TEXT NOT NULL, idx INTEGER NOT NULL, device_key TEXT NOT NULL, commit_hash TEXT, nonce_b TEXT, reveal TEXT, state TEXT NOT NULL, ends_at INTEGER NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (request, account));`;/** The wait between a start and the release of the object's half (TRUSTED-RECOVERY.md §5: 48 hours). */export const WAIT_MS = 48 * 60 * 60 * 1000;/** * Starts allowed the person in 30 days, counting only those that reached at least one helper's approval (BUILD 3, * review 2): a device that proved nothing but the SMS code cannot use up the owner's recoveries. */export const STARTS_PER_MONTH = 3;/** Starts, and Stops, one device that holds no vault key may make in 30 days: its own allowance, not the person's. */export const DEVICE_STARTS_PER_MONTH = 3;export const DEVICE_STOPS_PER_MONTH = 3;/** Pending pieces a helper keeps for one person beside the live one (a lost drop message must not pile them up). */const PENDING_KEPT = 2;/** How long a Stop from a device that holds the vault pauses the circle. */export const PAUSE_MS = 7 * 24 * 60 * 60 * 1000;const MONTH = 30 * 24 * 60 * 60 * 1000;/** The shapes a circle may take: k of n. */const SHAPES: Record<number, number> = { 1: 1, 2: 3 };const B64URL = /^[A-Za-z0-9_-]+$/;const KEY32 = /^[A-Za-z0-9_-]{43}$/;/** Another person's object, as the circle travels between them (src/business.ts). */export interface CirclePeer {  circleKept(from: From, kept: { setup: string; index: number; box: string; live?: string | null }): Promise<void>;  /** The person's circle went live: that setup's piece is the one their way back in counts on. */  circleLive(from: From, live: { setup: string }): Promise<void>;  /** A helper's object let a piece go that the person may count on (BUILD 3, review 1): the count goes down. */  circleLost(from: From, lost: { setup: string }): Promise<void>;  circleDropped(from: From, dropped: { setup?: string }): Promise<void>;  circleAccepted(from: From, answer: { setup: string; accepted: boolean }): Promise<void>;  circleRequested(from: From, request: { request: string; setup: string; index: number; device_key: string; ends_at: number }): Promise<void>;  circleCommitted(from: From, compare: { request: string; commit: string }): Promise<void>;  circleOpened(from: From, opened: { request: string; nonce: string }): Promise<void>;  circleRevealed(from: From, revealed: { request: string; nonce: string }): Promise<void>;  circleApproved(from: From, approved: { request: string; sealed: string }): Promise<void>;  circleStopped(from: From, stopped: { request: string; by: "person" | "helper" | "link" }): Promise<void>;  circleStopFor(from: From, stop: { request: string }): Promise<void>;  circleGone(from: From): Promise<void>;}/** Who a message between objects is from: their account (object slug) and their number now. */export interface From {  account: string;  number: string;}export interface CircleHost {  sql: SqlStorage;  now: () => number;  /** This person's own account and number. */  me: From;  isPeer: (number: string) => Promise<boolean>;  /** The account (object slug) of a number, or null when it is on no Cotton object. */  accountOf: (number: string) => Promise<string | null>;  /** The object of an account. */  peer: (account: string) => CirclePeer;  holdsVault: (deviceId: string) => boolean;  /** Every device of this person told (a push), but `except`. */  tellDevices: (what: "started" | "stopped" | "weak", except: string | null) => Promise<void>;  /** This person told by SMS, with the Stop link, where SMS is set up; answers whether it went. */  textStop: (link: string) => Promise<boolean>;  /** The open host's address and this database's id, to make the Stop link. */  linkBase: () => string | null;  /** The one-helper scheme's rows let go at once (src/recovery.ts `retireTrustedRows`), as a live circle replaces it: the helper to tell. */  retireTrustedRows: () => string | null;  /** That helper told to let the half go, after. */  tellTrustedDropped: (helper: string) => Promise<void>;  /** Whether a device signed in only by SMS in the last two days (no vault held): it is told no helper's number. */  freshDevice: (deviceId: string) => boolean;  /** The circle's wrap of the vault key checked (salt, stretch, auth hash, wrap, version), and written as kind `circle`. */  checkWrap: (body: Record<string, unknown>) => void;  writeWrap: (device: string, body: Record<string, unknown>) => void;}export interface CircleCaller {  deviceId: string | null;  owner: boolean;  token: boolean;}/** * An earlier build's circle table allowed one row (id 1) and had no `wrap`: rebuilt once, keeping its row, so a pending * circle (id 2) can stand beside the live one (TRUSTED RECOVERY BUILD 2, review M2). *//** Columns BUILD 3 added to tables an earlier build of this branch made. */const ADDED: Record<string, string[]> = {  recovery_request: ["approved_any INTEGER", "texted INTEGER"],  recovery_circle_held: ["live INTEGER"],};export function migrate(sql: SqlStorage): void {  for (const [table, columns] of Object.entries(ADDED)) {    const have = new Set(sql.exec<{ name: string }>(`PRAGMA table_info(${table})`).toArray().map((c) => c.name));    if (!have.size) continue;    for (const column of columns) if (!have.has(column.split(" ")[0]!)) sql.exec(`ALTER TABLE ${table} ADD COLUMN ${column}`);  }  const made = sql.exec<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'recovery_circle'").toArray()[0]?.sql ?? "";  if (!made || made.includes("id IN (1, 2)")) return;  sql.exec("ALTER TABLE recovery_circle RENAME TO recovery_circle_was");  sql.exec("CREATE TABLE recovery_circle (id INTEGER PRIMARY KEY CHECK (id IN (1, 2)), setup TEXT NOT NULL, k INTEGER NOT NULL, n INTEGER NOT NULL, held TEXT NOT NULL, made_by TEXT, at INTEGER NOT NULL, wrap TEXT)");  sql.exec("INSERT INTO recovery_circle (id, setup, k, n, held, made_by, at) SELECT id, setup, k, n, held, made_by, at FROM recovery_circle_was");  sql.exec("DROP TABLE recovery_circle_was");}export async function route(host: CircleHost, caller: CircleCaller, request: Request, url: URL): Promise<Response | null> {  const path = url.pathname;  if (!path.startsWith("/v1/recovery/circle")) return null;  if (!caller.deviceId) refuse(401, "sign_in", "a way back in is asked from a signed-in device");  if (!caller.owner || caller.token) refuse(403, "owner_only", "only the person's own devices reach their way back in");  const device = caller.deviceId;  // Only a build that speaks the compare knows the circle.  noteFlow(host.sql, device, 2, host.now());  const m = request.method;  const body = m === "POST" ? await readJson(request) : {};  switch (`${m} ${path}`) {    case "POST /v1/recovery/circle/set":      return json(await set(host, device, body));    case "POST /v1/recovery/circle/retire":      return json(await retire(host, device));    case "POST /v1/recovery/circle/start":      return json(await start(host, device, body));    case "GET /v1/recovery/circle/request":      return json(requestOf(host, device));    case "POST /v1/recovery/circle/commit":      return json(await commit(host, device, body));    case "POST /v1/recovery/circle/reveal":      return json(await reveal(host, device, body));    case "POST /v1/recovery/circle/stop":      return json(await stopByPerson(host, device));    case "GET /v1/recovery/circle/held":      return json(heldHere(host));    case "POST /v1/recovery/circle/accept":      return json(await answerHolding(host, body, true));    case "POST /v1/recovery/circle/decline":      return json(await answerHolding(host, body, false));    case "GET /v1/recovery/circle/asks":      return json(asksHere(host));    case "POST /v1/recovery/circle/open":      return json(await openAsk(host, body));    case "POST /v1/recovery/circle/approve":      return json(await approveAsk(host, body));    case "POST /v1/recovery/circle/stop-for":      return json(await stopForPerson(host, body));  }  refuse(404, "not_found", `nothing answers ${m} ${path}`);}// ── The person's side ──interface Circle {  setup: string;  k: number;  n: number;  held: string;  [key: string]: SqlStorageValue;}interface Member {  idx: number;  account: string;  number: string;  name: string | null;  accepted_at: number | null;  declined_at: number | null;  gone_at: number | null;  [key: string]: SqlStorageValue;}/** The live circle (id 1). */function circle(host: Pick<CircleHost, "sql">): Circle | null {  return host.sql.exec<Circle>("SELECT setup, k, n, held FROM recovery_circle WHERE id = 1").toArray()[0] ?? null;}/** A circle set but not yet live (id 2): it replaces the live one, and the one-helper setup, only once k accepted. */function pending(host: Pick<CircleHost, "sql">): (Circle & { wrap: string | null; made_by: string | null }) | null {  return host.sql.exec<Circle & { wrap: string | null; made_by: string | null }>("SELECT setup, k, n, held, wrap, made_by FROM recovery_circle WHERE id = 2").toArray()[0] ?? null;}function members(host: Pick<CircleHost, "sql">, setup: string): Member[] {  return host.sql.exec<Member>("SELECT idx, account, number, name, accepted_at, declined_at, gone_at FROM recovery_circle_member WHERE setup = ? ORDER BY idx", setup).toArray();}/** Whether a circle can open: at least k helpers accepted and still with this person. */export function live(host: Pick<CircleHost, "sql">): boolean {  const c = circle(host);  return c !== null && members(host, c.setup).filter((m) => m.accepted_at && !m.gone_at && !m.declined_at).length >= Number(c.k);}/** What every device of the person reads of the circle, for `GET /v1/recovery`: never H, never a box. */export function summary(host: CircleHost, device: string | null = null): Record<string, unknown> | null {  const c = circle(host);  const p = pending(host);  if (!c && !p) return null;  // A device signed in only by SMS in the last two days is told no helper's number (TRUSTED RECOVERY BUILD 2, LOW).  const fresh = device !== null && host.freshDevice(device);  const listed = (setup: string) =>    members(host, setup).map((m) => ({      index: Number(m.idx),      account: m.account,      ...(fresh ? {} : { number: m.number }),      name: m.name,      state: m.gone_at ? "gone" : m.declined_at ? "declined" : m.accepted_at ? "accepted" : "asked",    }));  const pendingPart = p ? { pending: { setup: p.setup, k: Number(p.k), n: Number(p.n), members: listed(p.setup) } } : {};  if (!c) return { live: false, k: Number(p!.k), n: Number(p!.n), members: [], ...pendingPart };  const open = openRequest(host);  const pause = host.sql.exec<{ until: number }>("SELECT until FROM recovery_pause WHERE id = 1").toArray()[0];  return {    setup: c.setup,    k: Number(c.k),    n: Number(c.n),    live: live(host),    members: listed(c.setup),    ...pendingPart,    ...(open ? { request: { id: open.id, started_at: Number(open.started_at), ends_at: Number(open.ends_at), name: open.name, state: open.state } } : {}),    ...(pause && Number(pause.until) > host.now() ? { paused_until: Number(pause.until) } : {}),  };}async function set(host: CircleHost, device: string, body: Record<string, unknown>): Promise<{ setup: string; live: boolean }> {  if (!host.holdsVault(device)) refuse(403, "vault_not_held", "only a device that holds the vault sets a way back in");  const k = body.k;  if (typeof k !== "number" || !(k in SHAPES)) refuse(400, "bad_shape", "k is 1 (with one helper) or 2 (with three)");  const n = SHAPES[k]!;  const list = body.members;  if (!Array.isArray(list) || list.length !== n) refuse(400, "bad_members", `${k} of ${n}: name ${n} helper${n === 1 ? "" : "s"}`);  const held = body.held;  if (typeof held !== "string" || !KEY32.test(held)) refuse(400, "bad_held", "held is this object's 32-byte half, base64url");  host.checkWrap(body);  const chosen: { number: string; name: string | null; box: string; account: string }[] = [];  for (const entry of list as Record<string, unknown>[]) {    const number = entry?.number;    if (typeof number !== "string" || !/^\+\d{6,16}$/.test(number) || number === host.me.number) refuse(400, "bad_helper", "each helper is one of your people's numbers");    if (chosen.some((c) => c.number === number)) refuse(400, "bad_helper", "each helper is a different person");    if (!(await host.isPeer(number))) refuse(403, "not_your_person", "Only one of your people, someone you both accepted on Cotton, can help you back in.");    const box = entry.box;    if (typeof box !== "string" || !box.startsWith("p1:") || !B64URL.test(box.slice(3)) || box.length > 600) refuse(400, "bad_box", "box is the helper's piece sealed to their sharing key");    const account = await host.accountOf(number);    if (!account) refuse(404, "helper_not_on_cotton", "That person is not on Cotton.");    chosen.push({ number, name: typeof entry.name === "string" ? entry.name.slice(0, 80) : null, box, account });  }  const setup = body.setup;  if (typeof setup !== "string" || !B64URL.test(setup) || setup.length < 22 || setup.length > 64) refuse(400, "bad_setup", "setup is the circle's id the phone minted, 16 to 48 bytes base64url");  if (circle(host)?.setup === setup || pending(host)?.setup === setup) refuse(409, "circle_setup_used", "That circle is set already.");  const at = host.now();  // Nothing that stands is touched until the new circle is live (TRUSTED RECOVERY BUILD 2, review M2). The boxes go to  // their helpers first; if one does not take it, those that did let it go again and nothing here changes.  const took: string[] = [];  try {    for (const [index, c] of chosen.entries()) {      await host.peer(c.account).circleKept(host.me, { setup, index, box: c.box, live: circle(host)?.setup ?? null });      took.push(c.account);    }  } catch (error) {    console.error("cottondb: circle set: a helper's object did not take its piece", error instanceof Error ? error.message : "unknown");    for (const account of took) await host.peer(account).circleDropped(host.me, { setup }).catch(() => undefined);    refuse(502, "circle_unset", "One of the people you chose could not be reached. Nothing was changed: try again.");  }  // A circle set earlier and not yet live is replaced; its helpers let their pieces go (after, best effort).  const was = pending(host);  const wasMembers = was ? members(host, was.setup) : [];  if (was) {    host.sql.exec("DELETE FROM recovery_circle_member WHERE setup = ?", was.setup);    host.sql.exec("DELETE FROM recovery_circle WHERE id = 2");  }  host.sql.exec("INSERT INTO recovery_circle (id, setup, k, n, held, made_by, at, wrap) VALUES (2, ?, ?, ?, ?, ?, ?, ?)", setup, k, n, held, device, at, JSON.stringify(wrapOf(body)));  for (const [index, c] of chosen.entries()) {    host.sql.exec("INSERT INTO recovery_circle_member (setup, idx, account, number, name) VALUES (?, ?, ?, ?, ?)", setup, index, c.account, c.number, c.name);  }  for (const m of wasMembers) await host.peer(m.account).circleDropped(host.me, { setup: was!.setup }).catch(() => undefined);  return { setup, live: false };}/** The wrap fields of a set, kept with the pending circle until it goes live. */function wrapOf(body: Record<string, unknown>): Record<string, unknown> {  const out: Record<string, unknown> = {};  for (const key of ["salt", "kdf", "auth_hash", "wrapped", "vmk_version", "code_enc"]) if (body[key] !== undefined) out[key] = body[key];  return out;}/** * The pending circle goes live, in one step, once k of its helpers accepted (TRUSTED RECOVERY BUILD 2, review M2): its * wrap becomes the `circle` way back in, the circle before it and the one-helper setup go, any request on the old one * stops. Their helpers are told after (best effort: an old piece alone opens nothing, and the old wrap is gone). */async function promote(host: CircleHost): Promise<void> {  const p = pending(host);  if (!p) return;  const accepted = members(host, p.setup).filter((m) => m.accepted_at && !m.gone_at && !m.declined_at).length;  if (accepted < Number(p.k)) return;  const old = circle(host);  const oldMembers = old ? members(host, old.setup).filter((m) => !m.gone_at) : [];  if (old) {    host.sql.exec("UPDATE recovery_request SET state = 'stopped', stopped_by = 'retired', stopped_at = ? WHERE state = 'waiting'", host.now());    host.sql.exec("DELETE FROM recovery_compare");    host.sql.exec("DELETE FROM recovery_circle_member WHERE setup = ?", old.setup);    host.sql.exec("DELETE FROM recovery_circle WHERE id = 1");  }  host.sql.exec("UPDATE recovery_circle SET id = 1, wrap = NULL WHERE id = 2");  host.writeWrap(p.made_by ?? "", p.wrap ? (JSON.parse(p.wrap) as Record<string, unknown>) : {});  const trustedHelper = host.retireTrustedRows();  for (const m of members(host, p.setup)) if (!m.gone_at) await host.peer(m.account).circleLive(host.me, { setup: p.setup }).catch(() => undefined);  for (const m of oldMembers) await host.peer(m.account).circleDropped(host.me, { setup: old!.setup }).catch(() => undefined);  if (trustedHelper) await host.tellTrustedDropped(trustedHelper).catch(() => undefined);}/** The circle let go: its helpers' objects told to let their pieces go, its rows gone, any open request stopped. */async function dropCircle(host: CircleHost): Promise<void> {  const c = circle(host);  if (!c) return;  for (const m of members(host, c.setup)) if (!m.gone_at) await host.peer(m.account).circleDropped(host.me, { setup: c.setup });  host.sql.exec("UPDATE recovery_request SET state = 'stopped', stopped_by = 'retired', stopped_at = ? WHERE state = 'waiting'", host.now());  host.sql.exec("DELETE FROM recovery_compare");  host.sql.exec("DELETE FROM recovery_circle_member WHERE setup = ?", c.setup);  host.sql.exec("DELETE FROM recovery_circle WHERE id = 1");}async function retire(host: CircleHost, device: string): Promise<{ retired: boolean }> {  if (!host.holdsVault(device)) refuse(403, "vault_not_held", "only a device that holds the vault retires a way back in");  const had = circle(host) !== null || pending(host) !== null;  const p = pending(host);  if (p) {    const was = members(host, p.setup);    host.sql.exec("DELETE FROM recovery_circle_member WHERE setup = ?", p.setup);    host.sql.exec("DELETE FROM recovery_circle WHERE id = 2");    for (const m of was) await host.peer(m.account).circleDropped(host.me, { setup: p.setup }).catch(() => undefined);  }  await dropCircle(host);  host.sql.exec("DELETE FROM recovery WHERE kind = 'circle'");  return { retired: had };}interface RequestRow {  id: string;  setup: string;  device: string;  device_key: string;  name: string | null;  started_at: number;  ends_at: number;  state: string;  released_at: number | null;  [key: string]: SqlStorageValue;}function openRequest(host: Pick<CircleHost, "sql">): RequestRow | null {  return host.sql.exec<RequestRow>("SELECT * FROM recovery_request WHERE state = 'waiting' ORDER BY started_at DESC LIMIT 1").toArray()[0] ?? null;}async function start(host: CircleHost, device: string, body: Record<string, unknown>): Promise<{ request: string; ends_at: number; texted: boolean }> {  const c = circle(host);  if (!c && pending(host)) refuse(409, "circle_not_live", "Not enough of the people you chose can help yet.");  if (!c) refuse(404, "circle_none", "Nobody is set to help you back in.");  if (!live(host)) refuse(409, "circle_not_live", "Not enough of the people you chose can help yet.");  const key = body.device_key;  if (typeof key !== "string" || !KEY32.test(key)) refuse(400, "bad_device_key", "device_key is this device's vault key, 32 bytes base64url");  const now = host.now();  const pause = host.sql.exec<{ until: number }>("SELECT until FROM recovery_pause WHERE id = 1").toArray()[0];  if (pause && Number(pause.until) > now) refuse(429, "circle_paused", "Getting back in with help was stopped from one of your devices. Try again later.");  if (openRequest(host)) refuse(409, "circle_request_open", "Getting back in is already under way.");  // BUILD 3, review 2: the device that starts holds no vault key (it is the one that needs recovery), so its starts count  // against its own allowance. The person's own count holds only starts that reached a helper's approval.  const mine = host.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM recovery_request WHERE device = ? AND started_at > ?", device, now - MONTH).one();  if (Number(mine.n) >= DEVICE_STARTS_PER_MONTH) refuse(429, "circle_wait_device", "This phone started getting back in too often this month.");  const counted = host.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM recovery_request WHERE started_at > ? AND approved_any = 1", now - MONTH).one();  if (Number(counted.n) >= STARTS_PER_MONTH) refuse(429, "circle_wait", "Getting back in with help was started too often this month.");  const id = crypto.randomUUID();  const endsAt = now + WAIT_MS;  host.sql.exec(    "INSERT INTO recovery_request (id, setup, device, device_key, name, started_at, ends_at, state) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting')",    id, c.setup, device, key, typeof body.name === "string" ? body.name.slice(0, 80) : null, now, endsAt,  );  for (const m of members(host, c.setup)) {    if (m.accepted_at && !m.gone_at && !m.declined_at) await host.peer(m.account).circleRequested(host.me, { request: id, setup: c.setup, index: Number(m.idx), device_key: key, ends_at: endsAt });  }  await host.tellDevices("started", device);  const base = host.linkBase();  let texted = false;  if (base) {    const token = randomToken();    host.sql.exec("INSERT INTO recovery_stop_link (token_hash, request, at) VALUES (?, ?, ?)", await sha256(token), id, now);    texted = await host.textStop(`${base}/${token}`).catch(() => false);  }  host.sql.exec("UPDATE recovery_request SET texted = ? WHERE id = ?", texted ? 1 : 0, id);  // Whether the text with the Stop link went (none where no Twilio Messaging Service is set up): the device says so.  return { request: id, ends_at: endsAt, texted };}function requestOf(host: CircleHost, device: string): Record<string, unknown> {  const r = host.sql.exec<RequestRow>("SELECT * FROM recovery_request WHERE device = ? ORDER BY started_at DESC LIMIT 1", device).toArray()[0];  const c = circle(host);  if (!r || !c || r.setup !== c.setup) return { state: "none" };  const compares = host.sql.exec<{ idx: number; commit_hash: string; nonce_b: string | null; reveal: string | null; sealed: string | null; approved_at: number | null }>(    "SELECT idx, commit_hash, nonce_b, reveal, sealed, approved_at FROM recovery_compare WHERE request = ?", r.id,  ).toArray();  const byIndex = new Map(compares.map((x) => [Number(x.idx), x]));  const out_ = partsStopped(host, r.id);  const list = members(host, c.setup).filter((m) => m.accepted_at && !m.declined_at).map((m) => {    const x = byIndex.get(Number(m.idx));    return {      index: Number(m.idx),      // The device that started is fresh by nature: a name the person gave, never a number (review LOW).      name: m.name ?? "",      ...(m.gone_at ? { gone: true } : {}),      ...(out_.has(Number(m.idx)) ? { stopped: true } : {}),      ...(x ? { commit: x.commit_hash } : {}),      ...(x?.nonce_b ? { nonce_b: x.nonce_b } : {}),      ...(x?.reveal ? { reveal: x.reveal } : {}),      approved: Boolean(x?.approved_at),    };  });  // AUDIT D: only a helper who can still help counts: one the person since removed or blocked (gone), or who stepped  // out of this request, no longer does, whatever they approved before.  const standing = new Set(members(host, c.setup).filter((m) => m.accepted_at && !m.declined_at && !m.gone_at && !out_.has(Number(m.idx))).map((m) => Number(m.idx)));  const approved = compares.filter((x) => x.approved_at && x.sealed && standing.has(Number(x.idx)));  const now = host.now();  let state = r.state;  if (state === "waiting" && now >= Number(r.ends_at)) state = approved.length >= Number(c.k) ? "ready" : "waiting";  const out: Record<string, unknown> = { state, request: r.id, setup: r.setup, ends_at: Number(r.ends_at), k: Number(c.k), members: list };  if (state === "ready" || state === "released") {    // Released to the device that started it alone, after the wait, with k helpers' pieces wrapped to its key.    if (state === "ready") host.sql.exec("UPDATE recovery_request SET state = 'released', released_at = ? WHERE id = ?", now, r.id);    out.state = "released";    out.held = c.held;    out.pieces = approved.slice(0, Number(c.k)).map((x) => ({ index: Number(x.idx), sealed: x.sealed }));  }  return out;}function waitingFor(host: CircleHost, device: string): { r: RequestRow; c: Circle } {  const r = openRequest(host);  const c = circle(host);  if (!r || !c || r.device !== device || r.setup !== c.setup) refuse(404, "circle_not_waiting", "Getting back in is not under way on this device.");  return { r, c };}function memberAt(host: CircleHost, setup: string, index: unknown): Member {  if (typeof index !== "number" || !Number.isInteger(index)) refuse(400, "bad_index", "index is the helper's place in the circle");  const m = members(host, setup).find((x) => Number(x.idx) === index);  if (!m || !m.accepted_at || m.declined_at || m.gone_at) refuse(404, "circle_no_helper", "That person cannot help now.");  return m;}async function commit(host: CircleHost, device: string, body: Record<string, unknown>): Promise<{ ok: true }> {  const { r, c } = waitingFor(host, device);  const m = memberAt(host, c.setup, body.index);  const hash = body.commit;  if (typeof hash !== "string" || !KEY32.test(hash)) refuse(400, "bad_commit", "commit is 32 bytes, base64url");  if (partsStopped(host, r.id).has(Number(m.idx))) refuse(409, "circle_part_stopped", "That person stepped out of this one.");  const was = host.sql.exec<{ approved_at: number | null }>("SELECT approved_at FROM recovery_compare WHERE request = ? AND idx = ?", r.id, m.idx).toArray()[0];  if (was?.approved_at) refuse(409, "circle_approved", "That person has helped already.");  host.sql.exec("INSERT OR REPLACE INTO recovery_compare (request, idx, commit_hash, nonce_b, reveal, sealed, approved_at, at) VALUES (?, ?, ?, NULL, NULL, NULL, NULL, ?)", r.id, m.idx, hash, host.now());  await host.peer(m.account).circleCommitted(host.me, { request: r.id, commit: hash });  return { ok: true };}async function reveal(host: CircleHost, device: string, body: Record<string, unknown>): Promise<{ ok: true }> {  const { r, c } = waitingFor(host, device);  const m = memberAt(host, c.setup, body.index);  const x = host.sql.exec<{ commit_hash: string; nonce_b: string | null; reveal: string | null }>("SELECT commit_hash, nonce_b, reveal FROM recovery_compare WHERE request = ? AND idx = ?", r.id, m.idx).toArray()[0];  if (!x?.nonce_b) refuse(409, "help_not_opened", "That person has not opened your ask yet.");  const nonce = body.nonce;  if (typeof nonce !== "string" || !KEY32.test(nonce) || (await helpCommit({ account: host.me.number, setup: r.setup, index: Number(m.idx), request: r.id }, r.device_key, nonce)) !== x.commit_hash) refuse(400, "wrong_reveal", "That does not match what this device committed to.");  if (x.reveal && x.reveal !== nonce) refuse(409, "help_revealed", "This compare was revealed already.");  host.sql.exec("UPDATE recovery_compare SET reveal = ? WHERE request = ? AND idx = ?", nonce, r.id, m.idx);  await host.peer(m.account).circleRevealed(host.me, { request: r.id, nonce });  return { ok: true };}/** A request stopped: its pieces dropped, every helper and device told. */async function stop(host: CircleHost, r: RequestRow, by: "person" | "vault" | "helpers" | "link", device: string | null): Promise<void> {  host.sql.exec("UPDATE recovery_request SET state = 'stopped', stopped_by = ?, stopped_at = ? WHERE id = ?", by === "person" ? `device:${device}` : by === "vault" ? `vault:${device}` : by, host.now(), r.id);  host.sql.exec("DELETE FROM recovery_compare WHERE request = ?", r.id);  host.sql.exec("DELETE FROM recovery_stop_link WHERE request = ?", r.id);  for (const m of members(host, r.setup)) if (!m.gone_at) await host.peer(m.account).circleStopped(host.me, { request: r.id, by: by === "helpers" ? "helper" : by === "vault" ? "person" : by });  await host.tellDevices("stopped", null);}async function stopByPerson(host: CircleHost, device: string): Promise<{ stopped: boolean }> {  const r = openRequest(host);  if (!r) return { stopped: false };  const vault = host.holdsVault(device);  // BUILD 3, review 2: a device that holds the vault key always stops, and it never counts. One that proved nothing  // but the SMS code stops within its own allowance.  if (!vault) {    const mine = host.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM recovery_request WHERE stopped_by = ? AND stopped_at > ?", `device:${device}`, host.now() - MONTH).one();    if (Number(mine.n) >= DEVICE_STOPS_PER_MONTH) refuse(429, "circle_stop_wait", "This phone stopped getting back in too often this month.");  }  await stop(host, r, vault ? "vault" : "person", device);  // A Stop from a device that holds the vault means the person has their key: the circle rests a week.  if (vault) host.sql.exec("INSERT OR REPLACE INTO recovery_pause (id, until) VALUES (1, ?)", host.now() + PAUSE_MS);  return { stopped: true };}/** The SMS link's Stop (open host, no bearer): the token is the whole proof, and it stops only its own request. */export async function stopByLink(host: CircleHost, token: string): Promise<boolean> {  if (typeof token !== "string" || !B64URL.test(token) || token.length < 20 || token.length > 64) return false;  const link = host.sql.exec<{ request: string }>("SELECT request FROM recovery_stop_link WHERE token_hash = ?", await sha256(token)).toArray()[0];  if (!link) return false;  const r = host.sql.exec<RequestRow>("SELECT * FROM recovery_request WHERE id = ? AND state = 'waiting'", link.request).toArray()[0];  if (!r) return false;  await stop(host, r, "link", null);  return true;}// ── Between objects, on the person's side ──function memberByAccount(host: CircleHost, account: string): { c: Circle; m: Member } | null {  const c = circle(host);  if (!c) return null;  const m = members(host, c.setup).find((x) => x.account === account);  return m ? { c, m } : null;}export async function accepted(host: CircleHost, from: From, answer: { setup: string; accepted: boolean }): Promise<void> {  const setup = typeof answer?.setup === "string" ? answer.setup : "";  const which = [circle(host), pending(host)].find((x) => x?.setup === setup);  if (!which) return;  const m = members(host, setup).find((x) => x.account === from.account);  if (!m || m.gone_at) return;  const was = live(host);  if (answer.accepted) host.sql.exec("UPDATE recovery_circle_member SET accepted_at = ?, declined_at = NULL WHERE setup = ? AND idx = ?", host.now(), setup, m.idx);  else host.sql.exec("UPDATE recovery_circle_member SET declined_at = ? WHERE setup = ? AND idx = ?", host.now(), setup, m.idx);  if (pending(host)?.setup === setup) await promote(host);  await sayIfWeak(host, was);}/** The parts of a request its helpers stepped out of. */function partsStopped(host: Pick<CircleHost, "sql">, request: string): Set<number> {  return new Set(host.sql.exec<{ idx: number }>("SELECT idx FROM recovery_part_stop WHERE request = ?", request).toArray().map((x) => Number(x.idx)));}export function opened(host: CircleHost, from: From, o: { request: string; nonce: string }): void {  const found = memberByAccount(host, from.account);  if (!found || typeof o?.nonce !== "string" || !KEY32.test(o.nonce)) return;  host.sql.exec("UPDATE recovery_compare SET nonce_b = ? WHERE request = ? AND idx = ? AND nonce_b IS NULL AND approved_at IS NULL", o.nonce, o.request, found.m.idx);}export function approved(host: CircleHost, from: From, a: { request: string; sealed: string }): void {  const found = memberByAccount(host, from.account);  if (!found || found.m.gone_at || typeof a?.sealed !== "string" || a.sealed.length > 600) return;  const r = openRequest(host);  if (!r || r.id !== a.request) return;  host.sql.exec("UPDATE recovery_compare SET sealed = ?, approved_at = ? WHERE request = ? AND idx = ? AND reveal IS NOT NULL AND approved_at IS NULL", a.sealed, host.now(), r.id, found.m.idx);  // It reached a helper's approval: from now on it counts against the person's own starts.  host.sql.exec("UPDATE recovery_request SET approved_any = 1 WHERE id = ? AND EXISTS (SELECT 1 FROM recovery_compare WHERE request = ? AND approved_at IS NOT NULL)", r.id, r.id);}/** * A helper stepped out of a request (their Stop, or three wrong codes on their phone): only their part ends (review * M3). The request goes on with the others; only if too few are left to reach k does it end, and then it does not * count against the person's starts. */export async function stopFor(host: CircleHost, from: From, s: { request: string }): Promise<void> {  const found = memberByAccount(host, from.account);  const r = openRequest(host);  if (!found || !r || r.id !== s.request) return;  host.sql.exec("INSERT OR IGNORE INTO recovery_part_stop (request, idx, at) VALUES (?, ?, ?)", r.id, found.m.idx, host.now());  host.sql.exec("DELETE FROM recovery_compare WHERE request = ? AND idx = ? AND approved_at IS NULL", r.id, found.m.idx);  const out = partsStopped(host, r.id);  const left = members(host, found.c.setup).filter((m) => m.accepted_at && !m.gone_at && !m.declined_at && !out.has(Number(m.idx))).length;  if (left < Number(found.c.k)) await stop(host, r, "helpers", null);}/** A helper can help no more (they removed or blocked this person, or deleted their account). */export async function gone(host: CircleHost, from: From): Promise<void> {  const was = live(host);  const found = memberByAccount(host, from.account);  if (found && !found.m.gone_at) host.sql.exec("UPDATE recovery_circle_member SET gone_at = ? WHERE setup = ? AND idx = ?", host.now(), found.c.setup, found.m.idx);  await sayIfWeak(host, was);}/** The circle was live and is no longer (fewer than k can help): every device of the person is told (BUILD 3, review 1). */async function sayIfWeak(host: CircleHost, was: boolean): Promise<void> {  if (was && !live(host)) await host.tellDevices("weak", null).catch(() => undefined);}/** * A helper's object let a piece go that the person may count on (BUILD 3, review 1): a pending setup's helper counts as * declined; a live one's as gone, so `live` stays true to what helpers hold, and the person is told if it fell short. */export async function lost(host: CircleHost, from: From, l: { setup: string }): Promise<void> {  const setup = typeof l?.setup === "string" ? l.setup : "";  const was = live(host);  const m = members(host, setup).find((x) => x.account === from.account);  if (!m) return;  if (pending(host)?.setup === setup) host.sql.exec("UPDATE recovery_circle_member SET declined_at = ? WHERE setup = ? AND idx = ? AND declined_at IS NULL", host.now(), setup, m.idx);  else if (circle(host)?.setup === setup) host.sql.exec("UPDATE recovery_circle_member SET gone_at = ? WHERE setup = ? AND idx = ? AND gone_at IS NULL", host.now(), setup, m.idx);  await sayIfWeak(host, was);}// ── The helper's side ──interface Holding {  account: string;  setup: string;  number: string;  name: string | null;  idx: number;  box: string;  accepted_at: number | null;  declined_at: number | null;  [key: string]: SqlStorageValue;}/** * A person hands this helper a piece. Kept per setup (review M2), with the person's live setup marked as they say it * now: the piece of a setup the person's object calls live is never dropped here (BUILD 3, review 1). Only pending * pieces are capped: beyond PENDING_KEPT the oldest pending goes, and the person's object is told, so it never counts it. */export async function kept(host: CircleHost, from: From, k: { setup: string; index: number; box: string; live?: string | null }): Promise<void> {  if (!(await host.isPeer(from.number)) || typeof k?.box !== "string" || !k.box.startsWith("p1:") || k.box.length > 600) return;  const keptLive = host.sql.exec<{ live: number | null }>("SELECT live FROM recovery_circle_held WHERE account = ? AND setup = ?", from.account, k.setup).toArray()[0]?.live ?? null;  host.sql.exec("INSERT OR REPLACE INTO recovery_circle_held (account, setup, number, idx, box, at, live) VALUES (?, ?, ?, ?, ?, ?, ?)", from.account, k.setup, from.number, k.index, k.box, host.now(), keptLive);  if (typeof k.live === "string") markLive(host, from.account, k.live);  const extra = host.sql    .exec<{ setup: string }>("SELECT setup FROM recovery_circle_held WHERE account = ? AND (live IS NULL OR live = 0) ORDER BY at DESC LIMIT -1 OFFSET ?", from.account, PENDING_KEPT)    .toArray();  for (const { setup } of extra) {    host.sql.exec("DELETE FROM recovery_circle_held WHERE account = ? AND setup = ?", from.account, setup);    host.sql.exec("DELETE FROM recovery_circle_in WHERE account = ? AND setup = ?", from.account, setup);    await host.peer(from.account).circleLost(host.me, { setup }).catch(() => undefined);  }}/** The person's live setup, as they say it: that piece is marked live, and none other of theirs. */function markLive(host: CircleHost, account: string, setup: string): void {  host.sql.exec("UPDATE recovery_circle_held SET live = CASE WHEN setup = ? THEN 1 ELSE 0 END WHERE account = ?", setup, account);}export function liveNow(host: CircleHost, from: From, l: { setup: string }): void {  if (typeof l?.setup === "string") markLive(host, from.account, l.setup);}/** The person let a piece go: only that setup's piece and asks (BUILD 3, LOW), or all of theirs when no setup is named. */export function dropped(host: CircleHost, from: From, d: { setup?: string }): void {  if (d?.setup) {    host.sql.exec("DELETE FROM recovery_circle_held WHERE account = ? AND setup = ?", from.account, d.setup);    host.sql.exec("DELETE FROM recovery_circle_in WHERE account = ? AND setup = ?", from.account, d.setup);    return;  }  host.sql.exec("DELETE FROM recovery_circle_held WHERE account = ?", from.account);  host.sql.exec("DELETE FROM recovery_circle_in WHERE account = ?", from.account);}function heldHere(host: CircleHost): { held: Record<string, unknown>[] } {  const rows = host.sql.exec<Holding>("SELECT * FROM recovery_circle_held WHERE declined_at IS NULL ORDER BY at").toArray();  return { held: rows.map((h) => ({ account: h.account, number: h.number, setup: h.setup, index: Number(h.idx), accepted: Boolean(h.accepted_at), box: h.box })) };}async function answerHolding(host: CircleHost, body: Record<string, unknown>, accept: boolean): Promise<{ ok: true }> {  const account = typeof body.account === "string" ? body.account : refuse(400, "bad_account", "account: whose circle");  const setup = typeof body.setup === "string" ? body.setup : refuse(400, "bad_setup", "setup: which circle");  const h = host.sql.exec<Holding>("SELECT * FROM recovery_circle_held WHERE account = ? AND setup = ?", account, setup).toArray()[0];  if (!h) refuse(404, "circle_not_held", "Nothing is kept here for that person.");  if (accept) host.sql.exec("UPDATE recovery_circle_held SET accepted_at = ?, declined_at = NULL WHERE account = ? AND setup = ?", host.now(), account, setup);  else host.sql.exec("DELETE FROM recovery_circle_held WHERE account = ? AND setup = ?", account, setup);  await host.peer(account).circleAccepted(host.me, { setup, accepted: accept });  return { ok: true };}export function requested(host: CircleHost, from: From, q: { request: string; setup: string; index: number; device_key: string; ends_at: number }): void {  const h = host.sql.exec<Holding>("SELECT * FROM recovery_circle_held WHERE account = ? AND setup = ? AND accepted_at IS NOT NULL", from.account, q?.setup).toArray()[0];  if (!h || Number(h.idx) !== q.index || !KEY32.test(q.device_key ?? "")) return;  host.sql.exec(    "INSERT OR IGNORE INTO recovery_circle_in (request, account, setup, idx, device_key, state, ends_at, at) VALUES (?, ?, ?, ?, ?, 'waiting', ?, ?)",    q.request, from.account, q.setup, q.index, q.device_key, q.ends_at, host.now(),  );}export function committed(host: CircleHost, from: From, c: { request: string; commit: string }): void {  if (!KEY32.test(c?.commit ?? "")) return;  host.sql.exec("UPDATE recovery_circle_in SET commit_hash = ?, nonce_b = NULL, reveal = NULL WHERE request = ? AND account = ? AND state = 'waiting'", c.commit, c.request, from.account);}export async function revealed(host: CircleHost, from: From, r: { request: string; nonce: string }): Promise<void> {  const row = host.sql.exec<{ device_key: string; setup: string; idx: number; commit_hash: string | null; nonce_b: string | null; reveal: string | null }>(    "SELECT device_key, setup, idx, commit_hash, nonce_b, reveal FROM recovery_circle_in WHERE request = ? AND account = ? AND state = 'waiting'", r?.request, from.account,  ).toArray()[0];  if (!row || !row.commit_hash || !row.nonce_b || row.reveal || !KEY32.test(r.nonce ?? "")) return;  if ((await helpCommit({ account: from.number, setup: row.setup, index: Number(row.idx), request: r.request }, row.device_key, r.nonce)) !== row.commit_hash) return;  host.sql.exec("UPDATE recovery_circle_in SET reveal = ? WHERE request = ? AND account = ?", r.nonce, r.request, from.account);}export function stopped(host: CircleHost, from: From, s: { request: string }): void {  host.sql.exec("UPDATE recovery_circle_in SET state = 'stopped' WHERE request = ? AND account = ?", s?.request, from.account);}function asksHere(host: CircleHost): { asks: Record<string, unknown>[] } {  const rows = host.sql    .exec<{ request: string; account: string; setup: string; idx: number; device_key: string; commit_hash: string | null; nonce_b: string | null; reveal: string | null; ends_at: number; number: string; box: string }>(      "SELECT i.request, i.account, i.setup, i.idx, i.device_key, i.commit_hash, i.nonce_b, i.reveal, i.ends_at, h.number, h.box FROM recovery_circle_in i JOIN recovery_circle_held h ON h.account = i.account AND h.setup = i.setup WHERE i.state = 'waiting' AND i.ends_at > ? - 86400000 ORDER BY i.at",      host.now(),    )    .toArray();  return {    asks: rows.map((x) => ({      request: x.request,      account: x.account,      number: x.number,      setup: x.setup,      index: Number(x.idx),      device_key: x.device_key,      ends_at: Number(x.ends_at),      ...(x.commit_hash ? { commit: x.commit_hash } : {}),      ...(x.nonce_b ? { nonce_b: x.nonce_b } : {}),      ...(x.reveal ? { reveal: x.reveal } : {}),      box: x.box,    })),  };}function askRow(host: CircleHost, body: Record<string, unknown>): { request: string; account: string; commit_hash: string | null; nonce_b: string | null; reveal: string | null } {  const request = typeof body.request === "string" ? body.request : refuse(400, "bad_request", "request: which ask");  const account = typeof body.account === "string" ? body.account : refuse(400, "bad_account", "account: whose ask");  const row = host.sql.exec<{ request: string; account: string; commit_hash: string | null; nonce_b: string | null; reveal: string | null }>(    "SELECT request, account, commit_hash, nonce_b, reveal FROM recovery_circle_in WHERE request = ? AND account = ? AND state = 'waiting'", request, account,  ).toArray()[0];  if (!row) refuse(404, "help_not_waiting", "That ask is no longer waiting.");  return row;}async function openAsk(host: CircleHost, body: Record<string, unknown>): Promise<{ nonce: string }> {  const row = askRow(host, body);  if (!row.commit_hash) refuse(409, "help_not_committed", "Their new device has not started the compare yet.");  if (row.nonce_b) return { nonce: row.nonce_b };  const nonce = body.nonce;  if (typeof nonce !== "string" || !KEY32.test(nonce)) refuse(400, "bad_nonce", "nonce is 32 bytes, base64url");  host.sql.exec("UPDATE recovery_circle_in SET nonce_b = ? WHERE request = ? AND account = ?", nonce, row.request, row.account);  await host.peer(row.account).circleOpened(host.me, { request: row.request, nonce });  return { nonce };}async function approveAsk(host: CircleHost, body: Record<string, unknown>): Promise<{ ok: true }> {  const row = askRow(host, body);  if (!row.reveal) refuse(409, "help_not_compared", "Compare the code on their new device first.");  const sealed = body.sealed;  if (typeof sealed !== "string" || sealed.length > 600 || !/^[A-Za-z0-9_:.-]+$/.test(sealed)) refuse(400, "bad_sealed", "sealed is the piece wrapped to the asking device's key");  host.sql.exec("UPDATE recovery_circle_in SET state = 'approved' WHERE request = ? AND account = ?", row.request, row.account);  await host.peer(row.account).circleApproved(host.me, { request: row.request, sealed });  return { ok: true };}async function stopForPerson(host: CircleHost, body: Record<string, unknown>): Promise<{ ok: true }> {  const row = askRow(host, body);  host.sql.exec("UPDATE recovery_circle_in SET state = 'stopped' WHERE request = ? AND account = ?", row.request, row.account);  await host.peer(row.account).circleStopFor(host.me, { request: row.request });  return { ok: true };}// ── Leaving (step 2's rule, for the circle) ──/** This person and `number` stopped being each other's people: either side's half of the circle lets go. */export async function forgetPerson(host: CircleHost, number: string): Promise<void> {  // Everything here first (BUILD 3, LOW): Remove and Block always complete; each other object is told after, and a  // telling that fails is kept and tried again (`retryTells`).  const helped = host.sql.exec<{ account: string }>("SELECT DISTINCT account FROM recovery_circle_held WHERE number = ?", number).toArray();  const tells: Tell[] = [];  for (const { account } of helped) {    host.sql.exec("DELETE FROM recovery_circle_held WHERE account = ?", account);    host.sql.exec("DELETE FROM recovery_circle_in WHERE account = ?", account);    tells.push({ kind: "circleGone", target: account });  }  for (const c of [circle(host), pending(host)]) {    if (!c) continue;    for (const m of members(host, c.setup)) {      if (m.number === number && !m.gone_at) {        host.sql.exec("UPDATE recovery_circle_member SET gone_at = ? WHERE setup = ? AND idx = ?", host.now(), c.setup, m.idx);        tells.push({ kind: "circleDropped", target: m.account, setup: c.setup });      }    }  }  for (const t of tells) await tell(host, t);}/** One word to another object the person's own act owes it. */interface Tell {  kind: "circleGone" | "circleDropped";  target: string;  setup?: string;}async function tell(host: CircleHost, t: Tell): Promise<void> {  try {    if (t.kind === "circleGone") await host.peer(t.target).circleGone(host.me);    else await host.peer(t.target).circleDropped(host.me, { setup: t.setup });  } catch (error) {    console.error("cottondb: circle: another object was not told; kept to try again", error instanceof Error ? error.message : "unknown");    host.sql.exec("INSERT INTO recovery_tell (kind, target, payload, tries, next_at) VALUES (?, ?, ?, 0, ?)", t.kind, t.target, JSON.stringify({ setup: t.setup ?? null }), host.now() + 60_000);  }}/** The tellings kept, tried again with a growing wait; after a week one is let go (an old piece alone opens nothing). */export async function retryTells(host: CircleHost): Promise<void> {  const due = host.sql.exec<{ id: number; kind: string; target: string; payload: string; tries: number }>("SELECT id, kind, target, payload, tries FROM recovery_tell WHERE kind LIKE 'circle%' AND next_at <= ? ORDER BY id LIMIT 20", host.now()).toArray();  for (const r of due) {    const setup = (JSON.parse(r.payload) as { setup: string | null }).setup ?? undefined;    try {      if (r.kind === "circleGone") await host.peer(r.target).circleGone(host.me);      else await host.peer(r.target).circleDropped(host.me, { setup });      host.sql.exec("DELETE FROM recovery_tell WHERE id = ?", r.id);    } catch {      const tries = Number(r.tries) + 1;      if (tries > 12) host.sql.exec("DELETE FROM recovery_tell WHERE id = ?", r.id);      else host.sql.exec("UPDATE recovery_tell SET tries = ?, next_at = ? WHERE id = ?", tries, host.now() + Math.min(24 * 3_600_000, 60_000 * 2 ** tries), r.id);    }  }}/** * The account is being erased: everyone this one helps is told, and this one's helpers let their pieces go. Each is * asked on its own and marked once told, so a retry asks only the rest; answers the accounts not told (the erase asks * again with its back-off and, after a day, records them in the receipt). */export async function leave(host: CircleHost): Promise<string[]> {  const notTold: string[] = [];  for (const { account } of host.sql.exec<{ account: string }>("SELECT DISTINCT account FROM recovery_circle_held").toArray()) {    try {      await host.peer(account).circleGone(host.me);      host.sql.exec("DELETE FROM recovery_circle_held WHERE account = ?", account);      host.sql.exec("DELETE FROM recovery_circle_in WHERE account = ?", account);    } catch (error) {      console.error("cottondb: account delete: a person helped back in did not take word", error instanceof Error ? error.message : "unknown");      notTold.push(await shortId(account));    }  }  for (const c of [circle(host), pending(host)]) {    if (!c) continue;    for (const m of members(host, c.setup)) {      if (m.gone_at) continue;      try {        await host.peer(m.account).circleDropped(host.me, { setup: c.setup });        host.sql.exec("UPDATE recovery_circle_member SET gone_at = ? WHERE setup = ? AND idx = ?", host.now(), c.setup, m.idx);      } catch (error) {        console.error("cottondb: account delete: a helper did not take word", error instanceof Error ? error.message : "unknown");        notTold.push(await shortId(m.account));      }    }  }  if (!notTold.length) {    host.sql.exec("DELETE FROM recovery_circle_member WHERE setup IN (SELECT setup FROM recovery_circle WHERE id = 2)");    host.sql.exec("DELETE FROM recovery_circle WHERE id = 2");    await dropCircle(host);  }  return notTold;}// ── Small things ──async function sha256(text: string): Promise<string> {  return toB64(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))));}function randomToken(): string {  return toB64(crypto.getRandomValues(new Uint8Array(24)));}function toB64(bytes: Uint8Array): string {  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}