Cotton code
1040 lines · 56.5 KB · TypeScriptRaw
/** * SEND (owner, 13 Nov 2026): a person gives a copy of something they own to * one of their people. A copy lands in the other person's Cotton and is * theirs; it is never shared (Share, one thing both see and change, is * another feature and nothing here stands in its way: a send names no * record of the sender's once it is kept). * * WHO. Only one of your people: a person on Cotton whom you and they have * accepted. That is Cotton chat's acceptance (src/chat/chat.ts `chat_peer`), * the one relationship: each object holds the numbers its owner accepted, so * the sender's object checks its own before a send leaves, and the * receiver's checks its own before one is held. Either side removing the * other (`POST /v1/chat/remove`, or a block) stops sends both ways. A block * is chat's and Calling's `call_block`. Unknown, blocked, removed and over a * limit look the same to the sender: the send is answered as made, and * nothing more is ever said of it. * * SEALED ALL THE WAY (ruling R5, 15 Nov 2026). The object * never reads what is sent. The SENDER'S PHONE lays the payload from its own * plain copy (the kit's `send` shape through the one rule, crates/cotton-rules * send.rs `send.contents`), seals it to the receiver's sharing key * (cotton-core seal/share.rs, a `p1:` box bound to `send:<id>`), and posts * the box with only its outside: the root's table and the media keys it * names (bytes the object weighs itself). The RECEIVER'S PHONE opens the box, * plans the landing over its own copy (`send.held`, `send.keep`), asks its * object to copy the bytes, and writes the rows itself, sealed under its own * data key like any write. The objects route ciphertext and copy opaque bytes. * * SHARING KEYS. Each phone posts its person's sharing key's public half here * (`POST /v1/send/key`); the sender's phone asks its object for a person's * (`GET /v1/send/key?number`), which asks theirs. Their object answers only a * person they accepted and have not blocked; anyone else, and a number not on * Cotton, is answered a key made from the number under this object's own key: * stable, and looking like any other, so a lookup never says who is on Cotton. * * HOW IT LANDS. The receiver's object holds the offer (`send_in`), outside * every kit table: nothing joins the receiver's records until Keep. The * phone draws it in the chat thread from `GET /v1/send/inbox`. Keep copies * the bytes R2 to R2 (both objects' media live in the one MEDIA bucket, so * the receiver's object reads the sender's path and writes its own: a COPY, * never a reference, so each object's deletions stay its own and no count * spans two objects), then makes the rows in one write. A trusted person's * sends are kept as they arrive. Decline deletes the offer: nothing stays. * Undo removes every record one send made, or every record one person sent * in a day. * * HELD BYTES. The sender's object pins each media key a send names * (`send_hold`) until the send is kept, declined or expired, so a record * erased meanwhile keeps its bytes for the copy: `dropMedia` leaves a held * key in its list and takes it on a later pass. An offer unkept after * EXPIRES_DAYS goes on both objects and its hold with it. * * SIZES. A send counts against the RECEIVER's media cap, at Keep: past it the * Keep is refused in words saying what it needs and what is free. Copies of * up to COPY.inline run inside the Keep; a larger one (a film) runs on the * object's alarm in parts (`send_copy`), resumable, and the rows land when * the last byte has. */import * as handover from "../handover.ts";import * as chat from "../chat/chat.ts";import * as gate from "../chat/gate.ts";import { directory } from "../directory.ts";import type { Env } from "../env.ts";import { json, readJson, refuse, Refused } from "../http.ts";import { blocked, keyOf, mac, numberOf } from "../calling/calls.ts";import { bucketKey, type MediaBudget } from "../media.ts";import type { Engine, Outcome } from "../engine.ts";import { col, type Store } from "../store.ts";export const SCHEMA = `CREATE TABLE IF NOT EXISTS send_out (id TEXT PRIMARY KEY, peer TEXT NOT NULL, title TEXT NOT NULL, root_table TEXT NOT NULL, root_id TEXT NOT NULL, bytes INTEGER NOT NULL, state TEXT NOT NULL, at INTEGER NOT NULL, answered_at INTEGER);CREATE TABLE IF NOT EXISTS send_hold (send_id TEXT NOT NULL, key TEXT NOT NULL, folder INTEGER NOT NULL, PRIMARY KEY (send_id, key));CREATE TABLE IF NOT EXISTS send_in (id TEXT PRIMARY KEY, peer TEXT NOT NULL, peer_slug TEXT NOT NULL, payload TEXT NOT NULL, title TEXT NOT NULL, root_table TEXT NOT NULL, bytes INTEGER NOT NULL, state TEXT NOT NULL, at INTEGER NOT NULL, landed_table TEXT, landed_id TEXT, kept_at INTEGER, tell INTEGER NOT NULL DEFAULT 0);CREATE INDEX IF NOT EXISTS send_in_by_peer ON send_in (peer, at);CREATE TABLE IF NOT EXISTS send_copy (send_id TEXT NOT NULL, src TEXT NOT NULL, dest TEXT NOT NULL, bytes INTEGER NOT NULL, upload TEXT, parts TEXT NOT NULL DEFAULT '[]', done INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (send_id, dest));CREATE TABLE IF NOT EXISTS send_trust (key TEXT PRIMARY KEY, at TEXT NOT NULL);CREATE TABLE IF NOT EXISTS send_hit (who TEXT NOT NULL, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS send_key (id INTEGER PRIMARY KEY CHECK (id = 1), public_key TEXT NOT NULL, at TEXT NOT NULL);CREATE TABLE IF NOT EXISTS send_sign_key (id INTEGER PRIMARY KEY CHECK (id = 1), public_key TEXT NOT NULL, at TEXT NOT NULL);`;/** An offer nobody kept goes after two weeks, on both objects, and its held bytes with it. */export const EXPIRES_DAYS = 14;export const EXPIRES_MS = EXPIRES_DAYS * 24 * 3_600_000;/** Sends one object makes in an hour. */export const SENDS_PER_HOUR = 30;/** Sends one object takes from one person in a day; the rest are dropped unsaid. */export const FROM_PEER_DAY = 100;/** A payload's JSON at most: a list of two thousand records fits. */export const PAYLOAD_MAX = 4 * 1024 * 1024;/** * How copies run: up to `inline` bytes in all inside the Keep, more on the * alarm; a file over `part` bytes in parts of that size (R2's floor is * 5 MB), at most `perPass` parts each alarm pass. A test lowers them in * place, as it lowers an object's caps. */export const COPY = { inline: 64 * 1024 * 1024, part: 64 * 1024 * 1024, perPass: 8 };/** A picture a phone may read from an offer before Keep (a cover, a poster). */export const PREVIEW_MAX = 20 * 1024 * 1024;const HOUR = 3_600_000;const DAY = 24 * HOUR;const ID = /^[A-Za-z0-9_-]{8,64}$/;/** * What the object keeps of a send: its outside, and the box the sender's * phone sealed to the receiver's sharing key. Nothing in it is a value a * person wrote: a send's title, its records and its sender's name are all * inside the box. */interface Sealed {  format: typeof SEALED_FORMAT;  version: 1;  id: string;  /** `p1:` box: the cotton.send payload sealed to the receiver's sharing key, bound to `send:<id>`. */  box: string;  /** The root record's table, for the thread's row and Undo; never its id. */  root: { table: string };  /** The media keys the payload names and what each weighs, as the sender's object weighed them. */  files: { key: string; bytes: number; folder?: boolean }[];  bytes: number;  /** The database the records were written in: their media keys start `<it>/`. */  source_database: string;}export const SEALED_FORMAT = "cotton.send.sealed";/** A box's prefix: anything else is not a sealed send. */const BOX = /^p1:[A-Za-z0-9_-]+$/;const TABLE = /^[a-z][a-z0-9_]{0,63}$/;const KEY = /^[A-Za-z0-9_-]{43}$/;/** At most this many media keys in one send. */const FILES_MAX = 2000;/** A copy the receiver's phone asks for at Keep: a key the send names, to a key under this object's database. */interface Copy {  from: string;  to: string;  bytes: number;  folder?: boolean;}/** What one object hands another. */export interface SendDelivery {  from: string;  fromSlug: string;  sealed: Sealed;}/** What the receiver's object tells the sender's: delivered, kept or declined (only as far as the receiver lets it). */export interface SendAnswer {  from: string;  id: string;  state: "delivered" | "kept" | "declined";}export interface SendHost {  sql: SqlStorage;  env: Env;  store: Store;  slug: string;  databaseId: string | null;  ownerPhone: string | null;  timezone: string;  /** The object's table definitions as written. */  tables(): Record<string, unknown>[];  budget(): MediaBudget;  /** One write: a version, the engine, its outcome. */  write<T>(fn: (engine: Engine, version: number, outcome: Outcome) => T): T;  waitUntil(work: Promise<unknown>): void;  /** Every open chat socket of this object's phones: told a send arrived. */  sockets(): WebSocket[];}// ── the routes ──────────────────────────────────────────────────────────/** The routes under /v1/send, for a phone signed in on this object; null for any other path. */export async function route(host: SendHost, deviceId: string | null, request: Request, url: URL): Promise<Response | null> {  const path = url.pathname;  if (!path.startsWith("/v1/send/")) return null;  if (!deviceId) refuse(401, "sign_in", "a send is made from a signed-in phone");  const method = request.method;  sweep(host);  if (method === "GET" && (path === "/v1/send/people" || path === "/v1/send/offer")) return json({ people: await people(host) });  if (method === "POST" && path === "/v1/send/key") {    const body = await readJson(request);    putKey(host.sql, body.key);    // The person's signing key's public half (Ed25519), beside the sharing key: what a shared space's records are signed with.    if (body.sign !== undefined) putSignKey(host.sql, body.sign);    return json({ ok: true });  }  if (method === "GET" && path === "/v1/send/key") {    const number = numberOf(url.searchParams.get("number"));    const key = await keyFor(host, number);    // THE CIRCLE's safety number (PEOPLE-DESIGN c "Check"): the signing key beside the sharing key, behind the same gate.    return json({ key, sign: await signFor(host, number), me: host.ownerPhone });  }  if (method === "POST" && path === "/v1/send/weigh") return json({ files: await weighAll(host, (await readJson(request)).files) });  if (method === "POST" && path === "/v1/send/make") return json(await make(host, await readJson(request)));  if (method === "GET" && path === "/v1/send/inbox") return json(await inbox(host));  if (method === "POST" && path === "/v1/send/keep") {    const body = await readJson(request);    return json(await keep(host, idOf(body.id), body.tell === true, body));  }  if (method === "POST" && path === "/v1/send/landed") {    const body = await readJson(request);    landed(host.sql, idOf(body.id), body.root);    return json({ ok: true });  }  if (method === "POST" && path === "/v1/send/decline") {    const body = await readJson(request);    await decline(host, idOf(body.id), body.tell === true);    return json({ ok: true });  }  if (method === "POST" && path === "/v1/send/undo") return json(await undo(host, await readJson(request)));  if (method === "POST" && path === "/v1/send/trust") {    const body = await readJson(request);    await trust(host, numberOf(body.number), body.trusted !== false);    return json({ ok: true });  }  const preview = /^\/v1\/send\/([A-Za-z0-9_-]{8,64})\/media$/.exec(path);  if (method === "GET" && preview) return media(host, preview[1]!, url.searchParams.get("key") ?? "", url.searchParams.get("whole") === "1");  refuse(404, "not_found", `nothing answers ${method} ${path}`);}// ── sharing keys ────────────────────────────────────────────────────────/** `POST /v1/send/key {key}`: a phone posts its person's sharing key (the public half; every phone of the person posts the same one). */function putKey(sql: SqlStorage, key: unknown): void {  if (typeof key !== "string" || !KEY.test(key)) refuse(400, "bad_key", "key: the sharing key's public half, 32 bytes base64url");  sql.exec("INSERT INTO send_key (id, public_key, at) VALUES (1, ?, ?) ON CONFLICT (id) DO UPDATE SET public_key = excluded.public_key, at = excluded.at", key, new Date().toISOString());}function putSignKey(sql: SqlStorage, key: unknown): void {  if (typeof key !== "string" || !KEY.test(key)) refuse(400, "bad_key", "sign: the signing key's public half, 32 bytes base64url");  sql.exec("INSERT INTO send_sign_key (id, public_key, at) VALUES (1, ?, ?) ON CONFLICT (id) DO UPDATE SET public_key = excluded.public_key, at = excluded.at", key, new Date().toISOString());}/** This person's own keys as their phones posted them (a shared space reads them from here, never from whoever adds them). */export function ownKeys(sql: SqlStorage): { share: string | null; sign: string | null } {  return { share: ownKey(sql), sign: sql.exec<{ public_key: string }>("SELECT public_key FROM send_sign_key WHERE id = 1").toArray()[0]?.public_key ?? null };}/** This person's sharing key, as their phones posted it; null before any did. */function ownKey(sql: SqlStorage): string | null {  return sql.exec<{ public_key: string }>("SELECT public_key FROM send_key WHERE id = 1").toArray()[0]?.public_key ?? null;}/** * `GET /v1/send/key?number`: the sharing key of one of this person's people, * asked of their object. A number that is not one of this person's people is * refused as a send to them is; one whose object does not answer (not on * Cotton, blocked this person, never accepted them, posted no key) is * answered a made-up key, so the answer never says which. */async function keyFor(host: SendHost, number: string): Promise<string> {  if (number === host.ownerPhone) refuse(400, "bad_number", "a send goes to someone else");  if (!(await isPeer(host.sql, number)) || (await blocked(host.sql, number))) refuse(403, "not_your_person", "You can send only to one of your people: someone you both accepted on Cotton.");  if (!host.ownerPhone) refuse(409, "no_owner", "this object has no number to send from");  // THE CIRCLE (b.4): a number that now leads to another account than the one accepted gets nothing sealed to a person.  if (!(await chat.stillTheirs(host, number))) return madeUp(host.sql, number);  try {    const slug = await directory(host.env).lookup(number);    if (slug && slug !== host.slug) {      const key = await peer(host.env, slug).sendKey(host.ownerPhone);      if (typeof key === "string" && KEY.test(key)) return key;      // One of their people whose phone has not posted its key yet: said so, as only someone they accepted is told.      if (key === NOT_YET) refuse(409, "send_key_not_yet", "Their phone has not opened Cotton since you connected. Try again once they have.");    }  } catch (error) {    if (error instanceof Refused) throw error;    // Answered as a number nobody holds.  }  return madeUp(host.sql, number);}/** Another object asks for this person's sharing key on behalf of `from`: answered only to one of this person's people, else made up. */export async function keyAsked(host: Pick<SendHost, "sql" | "ownerPhone">, from: string): Promise<string> {  let number: string;  try {    number = numberOf(from);  } catch {    return madeUp(host.sql, String(from));  }  const key = ownKey(host.sql);  if (number === host.ownerPhone || !(await isPeer(host.sql, number)) || (await blocked(host.sql, number))) return madeUp(host.sql, number);  // One of this person's people, before any phone of theirs posted its key: told it is not there yet, never a key  // nobody can open (walk send-sealed: a page sealed to a made-up key arrived and was never drawn).  return key ?? NOT_YET;}/** * A person's signing key (Ed25519, posted beside the sharing key), asked of their object as `keyFor` asks the sharing * key and behind the same gate (called after it, so a number that is not one of this person's people was refused * already). Null while their phone has posted none; made up for an object that does not answer. */async function signFor(host: SendHost, number: string): Promise<string | null> {  if (!(await chat.stillTheirs(host, number))) return madeUp(host.sql, `sign:${number}`);  try {    const slug = await directory(host.env).lookup(number);    if (slug && slug !== host.slug) {      const sign = await peer(host.env, slug).sendSignKey(host.ownerPhone!);      if (sign === NOT_YET) return null;      if (typeof sign === "string" && KEY.test(sign)) return sign;    }  } catch (error) {    if (error instanceof Refused) throw error;  }  return madeUp(host.sql, `sign:${number}`);}/** Another object asks this person's signing key on behalf of `from`: as `keyAsked`, only to one of this person's people, else made up. */export async function signAsked(host: Pick<SendHost, "sql" | "ownerPhone">, from: string): Promise<string> {  let number: string;  try {    number = numberOf(from);  } catch {    return madeUp(host.sql, `sign:${String(from)}`);  }  if (number === host.ownerPhone || !(await isPeer(host.sql, number)) || (await blocked(host.sql, number))) return madeUp(host.sql, `sign:${number}`);  return ownKeys(host.sql).sign ?? NOT_YET;}/** What `keyAsked` answers one of this person's people while no phone has posted the key. */export const NOT_YET = "not_yet";/** A key made from a number under this object's own secret: stable, and shaped like a real X25519 public key. */async function madeUp(sql: SqlStorage, number: string): Promise<string> {  const text = await mac(sql, `send-fake-key:${number}`);  const bytes = Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/") + "="), (c) => c.charCodeAt(0));  bytes[31] = bytes[31]! & 0x7f;  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}/** * One of this person's people, as an offer names them: their number, their * name where the object holds one it can read, whether they are trusted, and * whether they are still waiting: added here but not (or no longer) adding * this person back, so nothing sent to them is held (Add a person, 14 Nov * 2026). A person who blocked or removed this one waits like one who never * added them: the two look the same. */export interface SendPerson {  /** Null once the row keeps only its sealed copy (b.4 step B). */  number: string | null;  /** The number and name sealed to the owner's arrival key (chat.ts `reseal`), when the row has the copy. */  sealed?: string;  name: string | null;  trusted: boolean;  waiting: boolean;}/** * This person's people: everyone they accepted on Cotton (chat's `chat_peer`, * which keeps each number beside its key) and have not blocked, the latest * accepted first. The object answers it, not the phone: an app with no chat * tool (Books) keeps no thread to name them by, and the Cotton threads that * would are sealed on the phone that wrote them. A name is the one the * object can read: a Cotton thread's contact or title held in the clear. */async function people(host: SendHost): Promise<SendPerson[]> {  const out: SendPerson[] = [];  for (const person of (await chat.peopleOf(host)).people) {    // A person whose row keeps only its sealed copy (b.4 step B) goes out with it: the phone reads number and name from it.    const key = chat.rowKeyOf.get(person)!;    const trusted = host.sql.exec("SELECT 1 FROM send_trust WHERE key = ?", key).toArray().length > 0;    out.push({ number: person.number, name: (person.number ? nameOf(host, person.number) : null) ?? person.name, trusted, waiting: person.waiting, ...(person.sealed ? { sealed: person.sealed } : {}) });  }  return out;}/** A person's name as the object holds it in the clear: their Cotton thread's contact, else its title; none where those rows are sealed or absent. */function nameOf(host: SendHost, number: string): string | null {  const [thread] = host.store.select("thread", [{ sql: `${col("external_key")} = ?`, args: [`cotton:${number}`] }, { sql: `${col("trashed_at")} IS NULL`, args: [] }], "id", 1);  if (!thread) return null;  const contact = typeof thread.data.contact_id === "string" ? host.store.get("message_contact", thread.data.contact_id) : null;  return [contact?.data.display_name, thread.data.title].find((n): n is string => typeof n === "string" && n.trim() !== "") ?? null;}// ── making a send ───────────────────────────────────────────────────────/** `POST /v1/send/weigh {files: [{key, folder?}]}`: what each media key weighs in this object's store (the phone's `send.contents` asks it), null for one it does not hold. */async function weighAll(host: SendHost, raw: unknown): Promise<{ key: string; folder: boolean; bytes: number | null }[]> {  if (!Array.isArray(raw) || raw.length > FILES_MAX) refuse(400, "bad_files", `files: at most ${FILES_MAX} media keys`);  const out: { key: string; folder: boolean; bytes: number | null }[] = [];  for (const f of raw as Record<string, unknown>[]) {    if (!f || typeof f.key !== "string") refuse(400, "bad_files", "files: each a {key, folder?}");    const folder = f.folder === true;    out.push({ key: f.key, folder, bytes: await weigh(host, f.key, folder) });  }  return out;}/** * `POST /v1/send/make {id, to, box, table, files}`: the send leaves for one * of this person's people, sealed. The object reads nothing of it but its * outside, weighs the media keys it names itself (each must be this * database's own), and answers the same whatever then happens to it. A send * in the clear (`{table, id}` alone, an older phone) is refused by name. */async function make(host: SendHost, body: Record<string, unknown>): Promise<Record<string, unknown>> {  if (!host.ownerPhone || !host.databaseId) refuse(409, "no_owner", "this object has no number to send from");  const to = numberOf(body.to);  if (to === host.ownerPhone) refuse(400, "bad_number", "a send goes to someone else");  if (typeof body.box !== "string") refuse(400, "send_sealed_only", "A send is sealed on the phone to the person it goes to: this phone needs an update.");  const box = BOX.test(body.box) && body.box.length <= PAYLOAD_MAX ? body.box : refuse(400, "bad_box", "box: the payload sealed to the receiver's sharing key (p1:)");  const id = typeof body.id === "string" && ID.test(body.id) ? body.id : refuse(400, "bad_id", "id: the send's own id, 8 to 64 letters, digits, - or _");  const table = typeof body.table === "string" && TABLE.test(body.table) ? body.table : refuse(400, "bad_table", "table: the sent record's table");  if (!host.tables().some((t) => String(t.id) === table)) refuse(400, "bad_table", "table: the sent record's table");  if (!Array.isArray(body.files) || body.files.length > FILES_MAX) refuse(400, "bad_files", `files: at most ${FILES_MAX} media keys`);  if (!(await isPeer(host.sql, to))) refuse(403, "not_your_person", "You can send only to one of your people: someone you both accepted on Cotton.");  if (await blocked(host.sql, to)) refuse(403, "not_your_person", "You can send only to one of your people: someone you both accepted on Cotton.");  if (host.sql.exec("SELECT 1 FROM send_out WHERE id = ?", id).toArray().length) refuse(409, "sent_already", "a send with this id has left already");  const who = "send-out";  if (hits(host.sql, who, HOUR) >= SENDS_PER_HOUR) refuse(429, "too_many_sends", "You have sent a lot in the last hour; try again later.");  const files: Sealed["files"] = [];  const seen = new Set<string>();  for (const f of body.files as Record<string, unknown>[]) {    const key = typeof f?.key === "string" && f.key.startsWith(`${host.databaseId}/`) ? f.key : refuse(400, "bad_files", "files: each a media key of this database");    const folder = f.folder === true;    if (seen.has(`${folder}:${key}`)) continue;    seen.add(`${folder}:${key}`);    const bytes = await weigh(host, key, folder);    if (bytes === null) refuse(400, "missing_media", "A file this send names is not in your Cotton.");    files.push({ key, bytes, ...(folder ? { folder: true } : {}) });  }  const bytes = files.reduce((n, f) => n + f.bytes, 0);  hit(host.sql, who);  const at = Date.now();  host.sql.exec("INSERT INTO send_out (id, peer, title, root_table, root_id, bytes, state, at) VALUES (?, ?, '', ?, '', ?, 'offered', ?)", id, to, table, bytes, at);  for (const file of files) host.sql.exec("INSERT OR IGNORE INTO send_hold (send_id, key, folder) VALUES (?, ?, ?)", id, file.key, file.folder ? 1 : 0);  const sealed: Sealed = { format: SEALED_FORMAT, version: 1, id, box, root: { table }, files, bytes, source_database: host.databaseId };  host.waitUntil(handOver(host, to, { from: host.ownerPhone, fromSlug: host.slug, sealed }));  return { id, at, bytes, state: "offered" };}/** * A film's original lies in its folder under * `original/`: the owner's own file, kept for the Mac. A send carries the * stream the receiver plays, never the original: a folder is weighed and * copied without it. */const ORIGINAL_FOLDER = "original/";/** Whether a file of a folder travelling whole stays home: its original's pieces and index. */function staysHome(folder: string, key: string): boolean {  return key.slice(folder.length).startsWith(ORIGINAL_FOLDER);}/** A media key's bytes in this object's store (a folder's: every file under the key's folder, its original aside), or null. */async function weigh(host: SendHost, key: string, folder: boolean): Promise<number | null> {  let at: string;  try {    at = bucketKey(key, host.databaseId ?? "", host.slug);  } catch {    return null;  }  if (!folder) return (await host.env.MEDIA.head(at))?.size ?? null;  const dir = at.slice(0, at.lastIndexOf("/") + 1);  let total = 0;  let cursor: string | undefined;  for (;;) {    const page = await host.env.MEDIA.list({ prefix: dir, ...(cursor ? { cursor } : {}) });    for (const o of page.objects) if (!staysHome(dir, o.key)) total += o.size;    if (!page.truncated) break;    cursor = page.cursor;  }  return total > 0 ? total : null;}/** The send's box to the number's object: found by the directory; what it does with it is not this object's to know. */async function handOver(host: SendHost, to: string, delivery: SendDelivery): Promise<void> {  try {    const slug = await directory(host.env).lookup(to);    if (!slug || slug === host.slug) return;    await peer(host.env, slug).sendDeliver(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, "send", to, delivery);    // Else: a send that could not be handed over reads as one never kept.  }}// ── arriving ────────────────────────────────────────────────────────────/** A delivery's sealed send, when it reads as one: its outside's shape only, never its box. */function sealedOf(raw: unknown): Sealed | null {  if (!raw || typeof raw !== "object") return null;  const s = raw as Record<string, unknown>;  if (s.format !== SEALED_FORMAT || s.version !== 1 || typeof s.id !== "string" || !ID.test(s.id)) return null;  if (typeof s.box !== "string" || !BOX.test(s.box) || s.box.length > PAYLOAD_MAX) return null;  const root = s.root as { table?: unknown } | undefined;  if (typeof root?.table !== "string" || !TABLE.test(root.table)) return null;  if (typeof s.source_database !== "string" || !Array.isArray(s.files) || s.files.length > FILES_MAX) return null;  const files: Sealed["files"] = [];  for (const f of s.files as Record<string, unknown>[]) {    if (!f || typeof f.key !== "string" || !f.key.startsWith(`${s.source_database}/`) || !Number.isInteger(f.bytes) || (f.bytes as number) < 0) return null;    files.push({ key: f.key, bytes: f.bytes as number, ...(f.folder === true ? { folder: true } : {}) });  }  const bytes = files.reduce((n, f) => n + f.bytes, 0);  return { format: SEALED_FORMAT, version: 1, id: s.id, box: s.box, root: { table: root.table }, files, bytes, source_database: s.source_database };}/** * Another object's send arriving: dropped unsaid unless its sender is one of * this person's people (accepted, not blocked) and under the limits; else * held as an offer and the phones' sockets told. A trusted person's send is * kept by the receiver's phone as it arrives (only a phone can open it). */export async function deliverIn(host: SendHost, delivery: SendDelivery): Promise<void> {  sweep(host);  let from: string;  try {    from = numberOf(delivery.from);  } catch {    return;  }  if (from === host.ownerPhone || (await blocked(host.sql, from)) || !(await isPeer(host.sql, from))) return;  const sealed = sealedOf(delivery.sealed);  if (!sealed) return;  if (host.sql.exec("SELECT 1 FROM send_in WHERE id = ?", sealed.id).toArray().length) return;  const who = `send-in:${await mac(host.sql, `send:${delivery.fromSlug}`)}`;  if (hits(host.sql, who, DAY) >= FROM_PEER_DAY) return;  hit(host.sql, who);  host.sql.exec(    "INSERT INTO send_in (id, peer, peer_slug, payload, title, root_table, bytes, state, at) VALUES (?, ?, ?, ?, '', ?, ?, 'offered', ?)",    sealed.id,    from,    delivery.fromSlug,    JSON.stringify(sealed),    sealed.root.table,    sealed.bytes,    Date.now(),  );  host.waitUntil(answer(host, delivery.fromSlug, sealed.id, "delivered"));  for (const ws of host.sockets()) {    try {      ws.send(JSON.stringify({ t: "send", id: sealed.id }));    } catch {      // A socket closing as it was told: the inbox says it next time.    }  }}/** The sender's object hears what became of its send. */export function answeredIn(host: Pick<SendHost, "sql">, answer: SendAnswer): void {  const row = host.sql.exec<{ peer: string; state: string }>("SELECT peer, state FROM send_out WHERE id = ?", answer.id).toArray()[0];  if (!row || row.peer !== answer.from || row.state === "undone" || row.state === "expired") return;  const order = ["offered", "delivered", "kept", "declined"];  if (order.indexOf(answer.state) <= order.indexOf(row.state) && !(row.state === "delivered" && answer.state !== "delivered")) return;  host.sql.exec("UPDATE send_out SET state = ?, answered_at = ? WHERE id = ?", answer.state, Date.now(), answer.id);  // Kept or declined, the copy is done with this object's bytes.  if (answer.state !== "delivered") host.sql.exec("DELETE FROM send_hold WHERE send_id = ?", answer.id);}async function answer(host: SendHost, slug: string, id: string, state: SendAnswer["state"]): Promise<void> {  if (!host.ownerPhone) return;  try {    await peer(host.env, slug).sendAnswered({ from: host.ownerPhone, id, state });  } catch {    // The sender learns nothing more.  }}// ── what a phone reads ──────────────────────────────────────────────────/** * `GET /v1/send/inbox`: what arrived (offered, keeping or kept) and what this * person sent. An arrival carries its box for the phone to open (its title, * card, records and sender's name are inside), its size and whether it fits. */async function inbox(host: SendHost): Promise<Record<string, unknown>> {  const left = host.budget().left - reserved(host.sql);  const trusted = new Set<string>();  for (const { peer } of host.sql.exec<{ peer: string }>("SELECT DISTINCT peer FROM send_in").toArray()) if (await isTrusted(host.sql, peer)) trusted.add(peer);  const incoming = host.sql    .exec<{ id: string; peer: string; payload: string; bytes: number; state: string; at: number; landed_table: string | null; landed_id: string | null }>(      "SELECT id, peer, payload, bytes, state, at, landed_table, landed_id FROM send_in ORDER BY at, id",    )    .toArray()    .flatMap((r) => {      const sealed = sealedOf(JSON.parse(r.payload));      if (!sealed) return [];      const copying = r.state === "keeping" ? progress(host.sql, r.id) : null;      return [        {          id: r.id,          from: r.peer,          trusted: trusted.has(r.peer),          table: sealed.root.table,          bytes: r.bytes,          state: r.state,          at: r.at,          expires_at: r.at + EXPIRES_MS,          fits: r.bytes <= left,          ...(r.bytes > left && r.state === "offered" ? { words: fullWords(r.bytes, left) } : {}),          ...(copying ? { copied: copying } : {}),          ...(r.state === "kept" && r.landed_id ? { landed: { table: r.landed_table, id: r.landed_id } } : {}),          box: sealed.box,          files: sealed.files,          source_database: sealed.source_database,        },      ];    });  const outgoing = host.sql    .exec<{ id: string; peer: string; root_table: string; bytes: number; state: string; at: number }>("SELECT id, peer, root_table, bytes, state, at FROM send_out ORDER BY at, id")    .toArray()    .map((r) => ({ id: r.id, to: r.peer, table: r.root_table, bytes: r.bytes, state: r.state, at: r.at, expires_at: r.at + EXPIRES_MS }));  return { me: host.ownerPhone, in: incoming, out: outgoing };}/** * `GET /v1/send/<id>/media?key=`: a picture an offer names, read from the * sender's store before Keep (the phone draws the card); `whole=1`, any file * it names, whole: a file the sender sealed under their own key, which the * receiver's phone opens with the key the box carried and seals again under * its own at Keep (the bytes the object passes are sealed either way). */async function media(host: SendHost, id: string, key: string, whole = false): Promise<Response> {  const row = host.sql.exec<{ payload: string; peer_slug: string }>("SELECT payload, peer_slug FROM send_in WHERE id = ?", id).toArray()[0];  if (!row) refuse(404, "not_found", "no such send");  const sealed = sealedOf(JSON.parse(row.payload));  const file = sealed?.files.find((f) => f.key === key && !f.folder);  if (!sealed || !file || (!whole && file.bytes > PREVIEW_MAX)) refuse(404, "not_found", "the send names no such picture");  const found = await host.env.MEDIA.get(senderPath(sealed, row.peer_slug, key));  if (!found) refuse(404, "not_found", "the sender's copy has gone");  return new Response(found.body, { headers: { "content-type": found.httpMetadata?.contentType ?? "application/octet-stream", "cache-control": "private, max-age=3600" } });}// ── keep, decline, undo, trust ──────────────────────────────────────────/** * `POST /v1/send/keep {id, tell?, copies, root}`: the receiver's phone opened * the box and planned the landing over its own copy (`send.keep`); the * object copies the bytes it asks (each from a key the send names, to a key * under this database), inline or on the alarm when large, and the send is * kept once they have. The phone writes the rows itself, sealed under its own * data key; `root` (ids only) is what the thread's card opens. `tell` (the * phone's read-receipt switch) lets the sender learn it was kept. */export async function keep(host: SendHost, id: string, tell: boolean, body: Record<string, unknown> = {}): Promise<Record<string, unknown>> {  const row = host.sql.exec<{ peer: string; peer_slug: string; payload: string; state: string; landed_table: string | null; landed_id: string | null }>("SELECT peer, peer_slug, payload, state, landed_table, landed_id FROM send_in WHERE id = ?", id).toArray()[0];  if (!row) refuse(404, "not_found", "That send is not here any more: it was declined, or it expired.");  if (row.state === "kept") return { state: "kept", landed: { table: row.landed_table, id: row.landed_id } };  if (row.state === "keeping") return { state: "keeping", copied: progress(host.sql, id) };  if (!(await isPeer(host.sql, row.peer)) || (await blocked(host.sql, row.peer))) refuse(403, "not_your_person", "This came from someone who is no longer one of your people.");  const sealed = sealedOf(JSON.parse(row.payload));  if (!sealed) refuse(404, "not_found", "That send is not here any more: it was declined, or it expired.");  const root = body.root as { table?: unknown; id?: unknown } | undefined;  if (typeof root?.table !== "string" || !TABLE.test(root.table) || typeof root.id !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/.test(root.id)) refuse(400, "bad_root", "root: the landed root's {table, id}");  const copies = copiesOf(host, sealed, body.copies);  // What the copies add: a key already holding its bytes adds nothing.  let grows = 0;  for (const copy of copies) {    const at = bucketKey(copy.to, host.databaseId ?? "", host.slug);    const held = copy.folder ? null : await host.env.MEDIA.head(at);    if (!held || held.size !== copy.bytes) grows += copy.bytes;  }  const left = host.budget().left - reserved(host.sql);  if (grows > left) refuse(413, host.budget().full?.code ?? "object_full", host.budget().full?.words ?? fullWords(grows, left));  host.sql.exec("UPDATE send_in SET tell = ?, landed_table = ?, landed_id = ? WHERE id = ?", tell ? 1 : 0, root.table, root.id, id);  for (const copy of copies) {    host.sql.exec(      "INSERT OR IGNORE INTO send_copy (send_id, src, dest, bytes) VALUES (?, ?, ?, ?)",      id,      copy.folder ? folderOf(senderPath(sealed, row.peer_slug, copy.from)) : senderPath(sealed, row.peer_slug, copy.from),      copy.folder ? folderOf(bucketKey(copy.to, host.databaseId ?? "", host.slug)) : bucketKey(copy.to, host.databaseId ?? "", host.slug),      copy.bytes,    );  }  host.sql.exec("UPDATE send_in SET state = 'keeping' WHERE id = ?", id);  if (grows <= COPY.inline) {    await copyPass(host, id, Infinity);    return finish(host, id) ?? { state: "keeping", copied: progress(host.sql, id) };  }  return { state: "keeping", copied: progress(host.sql, id) };}/** The copies a Keep asks, each checked: from a key the send names (a folder's by its flag), to a key of this database. */function copiesOf(host: SendHost, sealed: Sealed, raw: unknown): Copy[] {  if (raw === undefined) return [];  if (!Array.isArray(raw) || raw.length > FILES_MAX) refuse(400, "bad_copies", "copies: the bytes the landing copies");  const named = new Map(sealed.files.map((f) => [`${f.folder ? "d" : "f"}:${f.key}`, f]));  return (raw as Record<string, unknown>[]).map((c) => {    const folder = c?.folder === true;    const file = typeof c?.from === "string" ? named.get(`${folder ? "d" : "f"}:${c.from}`) : undefined;    if (!file || typeof c.to !== "string" || !c.to.startsWith(`${host.databaseId ?? ""}/`)) refuse(400, "bad_copies", "copies: each from a file the send names, to a key of this database");    try {      bucketKey(c.to, host.databaseId ?? "", host.slug);    } catch {      refuse(400, "bad_copies", "copies: each to a key of this database");    }    return { from: file.key, to: c.to, bytes: file.bytes, ...(folder ? { folder: true } : {}) };  });}/** `POST /v1/send/landed {id, root}`: the receiver's phone wrote a kept send's rows; its root's id (ids only) is what the card opens on every phone. */function landed(sql: SqlStorage, id: string, root: unknown): void {  const r = root as { table?: unknown; id?: unknown } | undefined;  if (typeof r?.table !== "string" || !TABLE.test(r.table) || typeof r.id !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/.test(r.id)) refuse(400, "bad_root", "root: the landed root's {table, id}");  sql.exec("UPDATE send_in SET landed_table = ?, landed_id = ? WHERE id = ? AND state = 'kept'", r.table, r.id, id);}/** A send whose bytes have all copied is kept: its rows are the receiver's phone's to write (`fresh`: this call kept it, so the phone that asked writes them). */function finish(host: SendHost, id: string): Record<string, unknown> | null {  if (host.sql.exec("SELECT 1 FROM send_copy WHERE send_id = ? AND done = 0", id).toArray().length) return null;  const row = host.sql.exec<{ peer_slug: string; tell: number; landed_table: string | null; landed_id: string | null }>("SELECT peer_slug, tell, landed_table, landed_id FROM send_in WHERE id = ? AND state = 'keeping'", id).toArray()[0];  if (!row) return null;  host.sql.exec("UPDATE send_in SET state = 'kept', kept_at = ? WHERE id = ?", Date.now(), id);  host.sql.exec("DELETE FROM send_copy WHERE send_id = ?", id);  if (row.tell === 1) host.waitUntil(answer(host, row.peer_slug, id, "kept"));  return { state: "kept", fresh: true, landed: { table: row.landed_table, id: row.landed_id } };}/** * Copies still to make, part by part, at most `parts` parts this pass: a * file at most COPY.part goes whole; a larger one goes in parts of a * multipart upload kept in `send_copy` (its upload id and each part's etag), * so a pass that stops carries on where it stopped. A folder copies each * file under it. Each finished copy counts against this object's media. */export async function copyPass(host: SendHost, id: string | null, parts: number): Promise<{ more: boolean }> {  let left = parts;  const rows = host.sql    .exec<{ send_id: string; src: string; dest: string; bytes: number; upload: string | null; parts: string }>(      id === null ? "SELECT send_id, src, dest, bytes, upload, parts FROM send_copy WHERE done = 0 ORDER BY send_id" : "SELECT send_id, src, dest, bytes, upload, parts FROM send_copy WHERE done = 0 AND send_id = ?",      ...(id === null ? [] : [id]),    )    .toArray();  for (const copy of rows) {    if (left <= 0) return { more: true };    if (copy.src.endsWith("/")) {      // A folder: each file under it, whole or in parts, by the same rule.      let cursor: string | undefined;      for (;;) {        const page = await host.env.MEDIA.list({ prefix: copy.src, ...(cursor ? { cursor } : {}) });        for (const o of page.objects) if (!staysHome(copy.src, o.key)) left -= await copyOne(host, o.key, copy.dest + o.key.slice(copy.src.length), o.size);        if (!page.truncated) break;        cursor = page.cursor;      }      host.sql.exec("UPDATE send_copy SET done = 1 WHERE send_id = ? AND dest = ?", copy.send_id, copy.dest);      continue;    }    const head = await host.env.MEDIA.head(copy.src);    if (!head) {      // The sender's bytes went (a send outlived its hold): the copy is refused, the offer stays to say so.      host.sql.exec("UPDATE send_in SET state = 'offered' WHERE id = ?", copy.send_id);      host.sql.exec("DELETE FROM send_copy WHERE send_id = ?", copy.send_id);      continue;    }    if (head.size <= COPY.part) {      left -= await copyOne(host, copy.src, copy.dest, head.size);      host.sql.exec("UPDATE send_copy SET done = 1 WHERE send_id = ? AND dest = ?", copy.send_id, copy.dest);      continue;    }    const held = await host.env.MEDIA.head(copy.dest);    if (held && held.size === head.size) {      host.sql.exec("UPDATE send_copy SET done = 1 WHERE send_id = ? AND dest = ?", copy.send_id, copy.dest);      continue;    }    const upload = copy.upload ? host.env.MEDIA.resumeMultipartUpload(copy.dest, copy.upload) : await host.env.MEDIA.createMultipartUpload(copy.dest, { httpMetadata: head.httpMetadata });    if (!copy.upload) host.sql.exec("UPDATE send_copy SET upload = ? WHERE send_id = ? AND dest = ?", upload.uploadId, copy.send_id, copy.dest);    const done = JSON.parse(copy.parts) as { partNumber: number; etag: string }[];    const total = Math.ceil(head.size / COPY.part);    while (done.length < total && left > 0) {      const n = done.length + 1;      const offset = (n - 1) * COPY.part;      const length = Math.min(COPY.part, head.size - offset);      const part = await host.env.MEDIA.get(copy.src, { range: { offset, length } });      if (!part) break;      const uploaded = await upload.uploadPart(n, await part.arrayBuffer());      done.push({ partNumber: n, etag: uploaded.etag });      host.sql.exec("UPDATE send_copy SET parts = ? WHERE send_id = ? AND dest = ?", JSON.stringify(done), copy.send_id, copy.dest);      left -= 1;    }    if (done.length === total) {      await upload.complete(done);      host.budget().add(head.size - (held?.size ?? 0));      host.sql.exec("UPDATE send_copy SET done = 1 WHERE send_id = ? AND dest = ?", copy.send_id, copy.dest);    }  }  const more = host.sql.exec("SELECT 1 FROM send_copy WHERE done = 0").toArray().length > 0;  return { more };}/** One file whole, unless the destination holds its bytes already; the parts it took (one). */async function copyOne(host: SendHost, src: string, dest: string, size: number): Promise<number> {  const held = await host.env.MEDIA.head(dest);  if (held && held.size === size) return 0;  const object = await host.env.MEDIA.get(src);  if (!object) return 0;  await host.env.MEDIA.put(dest, await object.arrayBuffer(), { httpMetadata: object.httpMetadata });  host.budget().add(size - (held?.size ?? 0));  return 1;}/** * Whether Send's pass has anything to do (JOBS OUT 5, the step job's `owes`): an offer or a send out past its time, a * Keep still copying, a copy not done. Each read stops at its first row. */export function owes(sql: SqlStorage): boolean {  const old = Date.now() - EXPIRES_MS;  const any = (query: string, ...args: SqlStorageValue[]) => sql.exec(`${query} LIMIT 1`, ...args).toArray().length > 0;  return (    any("SELECT 1 FROM send_in WHERE state = 'keeping'") ||    any("SELECT 1 FROM send_copy WHERE done = 0") ||    any("SELECT 1 FROM send_in WHERE state = 'offered' AND at < ?", old) ||    any("SELECT 1 FROM send_out WHERE state IN ('offered', 'delivered') AND at < ?", old) ||    any("SELECT 1 FROM send_in WHERE state IN ('kept', 'undone') AND at < ?", Date.now() - 2 * EXPIRES_MS)  );}/** The alarm's send pass: offers past their time go, copies carry on, and kept sends land. */export async function alarmPass(host: SendHost): Promise<{ more: boolean }> {  sweep(host);  const copied = await copyPass(host, null, COPY.perPass);  for (const { id } of host.sql.exec<{ id: string }>("SELECT id FROM send_in WHERE state = 'keeping'").toArray()) finish(host, id);  return copied;}/** `POST /v1/send/decline {id, tell?}`: the offer goes, and nothing of it stays. */async function decline(host: SendHost, id: string, tell: boolean): Promise<void> {  const row = host.sql.exec<{ peer: string; peer_slug: string; state: string }>("SELECT peer, peer_slug, state FROM send_in WHERE id = ?", id).toArray()[0];  if (!row) return;  if (row.state === "kept") refuse(409, "kept", "This is kept already; Undo removes what it brought.");  await dropCopies(host, id);  host.sql.exec("DELETE FROM send_in WHERE id = ?", id);  if (tell) host.waitUntil(answer(host, row.peer_slug, id, "declined"));}/** A send's part-copied bytes go: an upload begun is aborted, a file already copied but not landed is deleted. */async function dropCopies(host: SendHost, id: string): Promise<void> {  for (const copy of host.sql.exec<{ dest: string; upload: string | null; done: number }>("SELECT dest, upload, done FROM send_copy WHERE send_id = ?", id).toArray()) {    if (copy.upload && !copy.done) await host.env.MEDIA.resumeMultipartUpload(copy.dest, copy.upload).abort().catch(() => undefined);  }  host.sql.exec("DELETE FROM send_copy WHERE send_id = ?", id);}/** * `POST /v1/send/undo {id}` removes every record one send made here; * `{from, day}` every record that person sent on that day (YYYY-MM-DD in * this object's zone). A record that was already held is never touched: it * was the person's before the send. */async function undo(host: SendHost, body: Record<string, unknown>): Promise<{ removed: number; state?: string }> {  if (typeof body.id === "string") {    const out = host.sql.exec<{ peer: string; state: string }>("SELECT peer, state FROM send_out WHERE id = ?", idOf(body.id)).toArray()[0];    if (out) return { removed: 0, state: await takeBack(host, body.id, out) };  }  // Rows of a sealed table are the phone's to undo: their send_id is sealed here.  const tables = host.tables().filter((t) => t.send && !t.seal && t.sealed !== true).map((t) => String(t.id));  let match: (data: Record<string, unknown>) => boolean;  let column: string;  let equals: string;  if (typeof body.id === "string") {    const id = idOf(body.id);    column = "send_id";    equals = id;    match = () => true;  } else {    const from = numberOf(body.from);    const day = typeof body.day === "string" && /^\d{4}-\d{2}-\d{2}$/.test(body.day) ? body.day : refuse(400, "bad_day", "day: YYYY-MM-DD");    column = "sent_by_number";    equals = from;    match = (data) => typeof data.sent_at === "string" && localDay(data.sent_at, host.timezone) === day;  }  let removed = 0;  const sends = new Set<string>();  host.write((engine, version, outcome) => {    for (const table of tables) {      for (const row of host.store.list(table, { column, equals })) {        if (!match(row.data)) continue;        engine.delete(row, version, outcome);        if (typeof row.data.send_id === "string") sends.add(row.data.send_id);        removed += 1;      }    }  });  for (const id of sends) host.sql.exec("UPDATE send_in SET state = 'undone' WHERE id = ?", id);  return { removed };}/** * A send this person made, taken back by its Undo: the offer goes from the * receiver's object and its hold from this one. Once kept it is theirs, and * stays: Undo says so. */async function takeBack(host: SendHost, id: string, out: { peer: string; state: string }): Promise<string> {  if (out.state === "kept") refuse(409, "kept", "They have kept it already: it is theirs now.");  if (out.state !== "offered" && out.state !== "delivered") return out.state;  host.sql.exec("UPDATE send_out SET state = 'undone', answered_at = ? WHERE id = ?", Date.now(), id);  host.sql.exec("DELETE FROM send_hold WHERE send_id = ?", id);  if (host.ownerPhone) {    const from = host.ownerPhone;    host.waitUntil(      (async () => {        try {          const slug = await directory(host.env).lookup(out.peer);          if (slug && slug !== host.slug) await peer(host.env, slug).sendTakenBack({ from, id });        } catch {          // Unheard, the offer expires on its own; its bytes are no longer held.        }      })(),    );  }  return "undone";}/** The sender took a send back: an offer not yet kept goes from here, part-copied bytes with it. */export async function takenBackIn(host: SendHost, from: string, id: string): Promise<void> {  const row = host.sql.exec<{ peer: string; state: string }>("SELECT peer, state FROM send_in WHERE id = ?", id).toArray()[0];  if (!row || row.peer !== from || (row.state !== "offered" && row.state !== "keeping")) return;  await dropCopies(host, id);  host.sql.exec("DELETE FROM send_in WHERE id = ?", id);}/** `POST /v1/send/trust {number, trusted}`: sends from this person are kept as they arrive. Only one of this person's people can be trusted. */async function trust(host: SendHost, number: string, trusted: boolean): Promise<void> {  const key = await keyOf(host.sql, number);  if (!trusted) {    host.sql.exec("DELETE FROM send_trust WHERE key = ?", key);    return;  }  if (!(await isPeer(host.sql, number))) refuse(403, "not_your_person", "Only one of your people can be trusted.");  host.sql.exec("INSERT OR IGNORE INTO send_trust (key, at) VALUES (?, ?)", key, new Date().toISOString());}/** * A person removed from this person's people, or blocked: their trust goes, * every offer from them goes, and each send to them is closed (its hold * released). What was kept stays: it is this person's. */export async function forgetPerson(host: SendHost, number: string): Promise<void> {  host.sql.exec("DELETE FROM send_trust WHERE key = ?", await keyOf(host.sql, number));  for (const { id } of host.sql.exec<{ id: string }>("SELECT id FROM send_in WHERE peer = ? AND state IN ('offered', 'keeping')", number).toArray()) {    await dropCopies(host, id);    host.sql.exec("DELETE FROM send_in WHERE id = ?", id);  }  for (const { id } of host.sql.exec<{ id: string }>("SELECT id FROM send_out WHERE peer = ? AND state IN ('offered', 'delivered')", number).toArray()) {    host.sql.exec("UPDATE send_out SET state = 'expired' WHERE id = ?", id);    host.sql.exec("DELETE FROM send_hold WHERE send_id = ?", id);  }}// ── the sender's held bytes ─────────────────────────────────────────────/** Whether a key or a folder `dropMedia` would delete is held by an open send: it waits for the send to close. */export function holds(sql: SqlStorage, keyOrFolder: string): boolean {  for (const { key, folder } of sql.exec<{ key: string; folder: number }>("SELECT key, folder FROM send_hold").toArray()) {    const dir = key.slice(0, key.lastIndexOf("/") + 1);    if (key === keyOrFolder) return true;    if (keyOrFolder.endsWith("/") && key.startsWith(keyOrFolder)) return true;    if (folder === 1 && keyOrFolder.startsWith(dir)) return true;  }  return false;}// ── small things ────────────────────────────────────────────────────────/** Offers past their time go on this object, and sends past theirs close. */function sweep(host: Pick<SendHost, "sql">): void {  const old = Date.now() - EXPIRES_MS;  for (const { id } of host.sql.exec<{ id: string }>("SELECT id FROM send_in WHERE state = 'offered' AND at < ?", old).toArray()) host.sql.exec("DELETE FROM send_in WHERE id = ?", id);  for (const { id } of host.sql.exec<{ id: string }>("SELECT id FROM send_out WHERE state IN ('offered', 'delivered') AND at < ?", old).toArray()) {    host.sql.exec("UPDATE send_out SET state = 'expired' WHERE id = ?", id);    host.sql.exec("DELETE FROM send_hold WHERE send_id = ?", id);  }  // A kept or undone offer is the thread's to remember after a month; what it landed stays the person's.  host.sql.exec("DELETE FROM send_in WHERE state IN ('kept', 'undone') AND at < ?", Date.now() - 2 * EXPIRES_MS);  host.sql.exec("DELETE FROM send_hit WHERE at < ?", Date.now() - DAY);}/** Bytes promised to copies not made yet: a second Keep counts the first's. */function reserved(sql: SqlStorage): number {  return sql.exec<{ n: number | null }>("SELECT sum(bytes) AS n FROM send_copy WHERE done = 0").one().n ?? 0;}function progress(sql: SqlStorage, id: string): { bytes: number; done: number } {  const rows = sql.exec<{ bytes: number; done: number; parts: string }>("SELECT bytes, done, parts FROM send_copy WHERE send_id = ?", id).toArray();  const done = rows.reduce((n, r) => n + (r.done ? r.bytes : Math.min(r.bytes, (JSON.parse(r.parts) as unknown[]).length * COPY.part)), 0);  return { bytes: rows.reduce((n, r) => n + r.bytes, 0), done };}/** The folder a file of a folder copy lives in, ending in /: a film's, under its master playlist. */function folderOf(path: string): string {  return path.slice(0, path.lastIndexOf("/") + 1);}function senderPath(sealed: Sealed, slug: string, key: string): string {  const prefix = `${sealed.source_database}/`;  if (!key.startsWith(prefix)) refuse(400, "bad_payload", "the send names media of another database");  return `${slug}/${key.slice(prefix.length)}`;}function fullWords(needs: number, left: number): string {  return `This needs ${size(needs)} and your Cotton has ${size(Math.max(0, left))} free.`;}export function size(bytes: number): string {  if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;  if (bytes >= 1024 ** 2) return `${Math.round(bytes / 1024 ** 2)} MB`;  return `${Math.max(1, Math.round(bytes / 1024))} KB`;}function localDay(iso: string, zone: string): string {  return new Intl.DateTimeFormat("en-CA", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date(iso));}/** One of this person's people: accepted and not blocked (src/chat/gate.ts `isPerson`, the one rule; the trusted person's, src/recovery.ts). */export async function isPersonOf(sql: SqlStorage, number: string): Promise<boolean> {  try {    return await gate.isPerson(sql, numberOf(number));  } catch {    return false;  }}/** Accepted by this owner, blocked or not (src/chat/gate.ts). */async function isPeer(sql: SqlStorage, number: string): Promise<boolean> {  return gate.accepted(sql, number);}async function isTrusted(sql: SqlStorage, number: string): Promise<boolean> {  return sql.exec("SELECT 1 FROM send_trust WHERE key = ?", await keyOf(sql, number)).toArray().length > 0;}function hits(sql: SqlStorage, who: string, within: number): number {  return sql.exec<{ n: number }>("SELECT count(*) AS n FROM send_hit WHERE who = ? AND at >= ?", who, Date.now() - within).one().n;}function hit(sql: SqlStorage, who: string): void {  sql.exec("INSERT INTO send_hit (who, at) VALUES (?, ?)", who, Date.now());}function idOf(raw: unknown): string {  return typeof raw === "string" && ID.test(raw) ? raw : refuse(400, "bad_id", "id: the send's id");}function peer(env: Env, slug: string): DurableObjectStub<import("../business.ts").Business> {  return env.BUSINESS.get(env.BUSINESS.idFromName(slug), { locationHint: "apac" });}