/** * The directory: one Durable Object for the whole Worker, holding which * database each phone number owns (owner, 26 Oct 2026: Cotton opens to * everyone; a number signs up and gets its own object). A number's first * sign-in on the open host makes its database here — a fresh id, its object * named `p-<id>` and made from the personal kit, the number its owner — * and every later one finds it. A token names its database * (`ctn_<id>_…`, `ctd_<id>_…`), and the directory says which object that is. * * The only guards (owner, 26 Oct 2026) are counted here per IP over the last * hour: at most SIGN_UPS_PER_HOUR databases made and ATTEMPTS_PER_HOUR * sign-in calls (asking for a code and proving one alike). A refusal crosses * the RPC boundary as a value, since an RPC error keeps only its message. * * The open host's OAuth clients live here too (src/oauth.ts): a client * registers before any number is typed, so no person's object can hold it, * and one registration serves every person. At most REGISTRATIONS_PER_HOUR * are made per IP an hour. * * Businesses are not here: they keep their slug routing (src/index.ts). */import { FROZEN_CALL } from"./restore.ts";import * as space from"./space.ts";import { DurableObject } from"cloudflare:workers";import { CHALLENGE_SECONDS as PASSKEY_CHALLENGE_SECONDS, newChallenge as passkeyChallenge, REFUSED as PASSKEY_REFUSED } from"./passkey.ts";import { fromBase64Url } from"./vault.ts";import { ASK_TTL_SECONDS, ASKS_PER_HOUR, newAskId, NOBODY, POLL_SECONDS, typeAskState, typeDeviceKind } from"./approval.ts";importtype { Env } from"./env.ts";import { DIGEST, keyCheck, keyOfDigest, numberDigest, numberKeyOf } from"./number_key.ts";importtype { Client } from"./oauth.ts";import { FORGET_AFTER_MS } from"./account_delete.ts";import { countKinds, typeVaultKeyPage, typeVaultKeyReport } from"./vault_key_check.ts";exportconst SIGN_UPS_PER_HOUR = 5;exportconst ATTEMPTS_PER_HOUR = 20;/** * Sign-in calls from every network together in an hour (ROUTES-AUDIT 7, 23 Nov 2026): a ceiling on the codes Twilio * can be made to send, whichever door they are asked at. SIGN_IN_ATTEMPTS_GLOBAL_PER_HOUR raises it (the dev Worker). */exportconst GLOBAL_ATTEMPTS_PER_HOUR = 50_000;exportconst REGISTRATIONS_PER_HOUR = 30;/** SMS codes one number may be sent in a day, wherever it asks (AUDIT A H2): above an object's own hourly count. */exportconst SMS_PER_NUMBER_PER_DAY = 10;/** * SMS codes sent in a day, every number together, before sending stops until the day's oldest fall out (AUDIT A H2): * the spend ceiling. The Worker var SMS_PER_DAY changes it. At 80% and at the ceiling a line starting * `cottondb: ALERT sms` is logged. */exportconst SMS_PER_DAY = 1_000;/** * The hour's limits, as the Worker's vars raise them: the development Worker * (`env.dev`) is signed into by every walk on every Mac behind one office IP, * so it carries SIGN_IN_ATTEMPTS_PER_HOUR and SIGN_UPS_PER_HOUR of its own; * production keeps the constants. A var that is not a whole number is ignored. */exportfunction limitsFor(env: Pick<Env, "SIGN_IN_ATTEMPTS_PER_HOUR" | "SIGN_UPS_PER_HOUR" | "SIGN_IN_ATTEMPTS_GLOBAL_PER_HOUR">): { attempts: number; signUps: number; everywhere: number } {const whole = (value: string | undefined, fallback: number): number => {if (value === undefined || !/^\d+$/.test(value)) return fallback;returnNumber(value); };return { attempts: whole(env.SIGN_IN_ATTEMPTS_PER_HOUR, ATTEMPTS_PER_HOUR), signUps: whole(env.SIGN_UPS_PER_HOUR, SIGN_UPS_PER_HOUR), everywhere: whole(env.SIGN_IN_ATTEMPTS_GLOBAL_PER_HOUR, GLOBAL_ATTEMPTS_PER_HOUR) };}/** * The block an address is counted by (AUDIT A H3): an IPv6 address by its first 64 bits (one machine or one home * holds a /64 whole, so counting single addresses counted nothing), an IPv4 address as itself. */exportfunction blockOf(ip: string): string {if (!ip.includes(":")) return ip;const [head = "", tail = ""] = ip.toLowerCase().split("::");const front = head ? head.split(":") : [];const back = tail ? tail.split(":") : [];const groups = ip.includes("::") ? [...front, ...Array(Math.max(0, 8 - front.length - back.length)).fill("0"), ...back] : front;return`${groups.slice(0, 4).map((g) => g.replace(/^0+(?=.)/, "")).join(":")}::/64`;}/** The `hit` row that counts every network together. */const EVERYWHERE = "*";/** Every object is placed in Asia Pacific (owner, 26 Oct 2026). */exportconst REGION = "apac";const SCHEMA = `CREATE TABLE IF NOT EXISTS database ( id TEXT PRIMARY KEY, slug TEXT NOT NULL UNIQUE, phone TEXT UNIQUE, region TEXT NOT NULL, created_at TEXT NOT NULL, provisioned INTEGER NOT NULL DEFAULT 0);CREATE TABLE IF NOT EXISTS hit (ip TEXT NOT NULL, kind TEXT NOT NULL, at INTEGER NOT NULL);-- AUDIT A H2: each SMS code sent, by the number's key (never the number), for a day.CREATE TABLE IF NOT EXISTS sms_sent (k TEXT NOT NULL, at INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS sms_sent_by_k ON sms_sent (k, at);CREATE INDEX IF NOT EXISTS sms_sent_by_at ON sms_sent (at);CREATE INDEX IF NOT EXISTS hit_by_ip ON hit (ip, kind, at);CREATE TABLE IF NOT EXISTS approval_route (id TEXT PRIMARY KEY, slug TEXT, phone TEXT NOT NULL, expires_at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS passkey_challenge (id TEXT PRIMARY KEY, challenge TEXT NOT NULL, expires_at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS oauth_client (id TEXT PRIMARY KEY, name TEXT, redirect_uris TEXT NOT NULL, created_at TEXT NOT NULL);CREATE TABLE IF NOT EXISTS directory_meta (name TEXT PRIMARY KEY, value TEXT NOT NULL);CREATE TABLE IF NOT EXISTS known_slug (slug TEXT PRIMARY KEY, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS circle_invite_code (code TEXT PRIMARY KEY, slug TEXT NOT NULL, ends_at INTEGER NOT NULL);-- AUDIT D: every new link sweeps the ended codes; without this, each one read every code of every account.CREATE INDEX IF NOT EXISTS circle_invite_code_ends ON circle_invite_code (ends_at);-- Own-domain mail (src/mail): which object a domain's mail goes to, and whose a sent mail was (its bounce names only its id).CREATE TABLE IF NOT EXISTS mail_domain (domain TEXT PRIMARY KEY, slug TEXT NOT NULL, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS mail_sent (message_id TEXT PRIMARY KEY, slug TEXT NOT NULL, at INTEGER NOT NULL);-- SNAPSHOTS 1 (src/snapshots.ts): each account's snapshot key, kept here, never in its object or beside its copies; deleted with the account.CREATE TABLE IF NOT EXISTS snapshot_key (slug TEXT PRIMARY KEY, key TEXT NOT NULL, created_at TEXT NOT NULL);CREATE TABLE IF NOT EXISTS referral (friend TEXT PRIMARY KEY, referrer TEXT NOT NULL, at INTEGER NOT NULL, counted_at INTEGER);CREATE INDEX IF NOT EXISTS referral_by_referrer ON referral (referrer);CREATE TABLE IF NOT EXISTS active14 (slug TEXT PRIMARY KEY, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS inviter_named (friend TEXT PRIMARY KEY, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS waiting (key TEXT NOT NULL, slug TEXT NOT NULL, ticket TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (key, slug));CREATE TABLE IF NOT EXISTS erased (id TEXT PRIMARY KEY, slug TEXT NOT NULL, started_at TEXT NOT NULL, finished_at TEXT, receipt TEXT);CREATE TABLE IF NOT EXISTS deleting (id TEXT PRIMARY KEY, asked_at TEXT NOT NULL, erase_at TEXT NOT NULL, state TEXT NOT NULL, changed_at TEXT NOT NULL);`;/** * Numbers one database may wait for at once (an invite sent, a message waiting, an ask), and how long a wait lasts. * The new numbers a person may pick each day are counted by their own object (src/chat/chat.ts `picked`). */exportconst WAITS_MAX = 500;exportconst WAIT_MS = 180 * 24 * 3_600_000;/** What waits for a number that joined: the object whose owner waits, and the ticket it knows the wait by. */exportinterfaceWaiter { slug: string; ticket: string;}exportinterfaceRefusal { status: number; code: string; message: string;}exporttypeAnswer<T> = { ok: T } | { refused: Refusal };exportinterfaceEntry { databaseId: string; slug: string;}/** The object a new database lives in: its id under a letter, so it is a slug the Worker can name. */exportfunction slugFor(databaseId: string): string {return`p-${databaseId}`;}/** The directory's one object. */exportfunction directory(env: Env): DurableObjectStub<Directory> {return env.DIRECTORY.get(env.DIRECTORY.idFromName("directory"), { locationHint: REGION });}/** The sweep asks after a deletion this long after it should have moved (DELETE ACCOUNT 1), and soon is the least wait. */exportconst SWEEP_LATE_MS = 60 * 60 * 1000;exportconst SWEEP_SOON_MS = 10 * 60 * 1000;/** Knocks at one deletion before the sweep leaves it to an admin (an hour apart: a day). */exportconst MAX_KNOCKS = 24;const KNOCK_SCHEMA = "CREATE TABLE IF NOT EXISTS sweep_knock (id TEXT PRIMARY KEY, n INTEGER NOT NULL, at INTEGER NOT NULL)";/** Each account's word on its ways back in (TRUSTED RECOVERY BUILD 2, H1): counts only, for when flow 1 can go. */const RECOVERY_FLOW_SCHEMA = "CREATE TABLE IF NOT EXISTS recovery_flow (id TEXT PRIMARY KEY, old_setup INTEGER NOT NULL, flow1 INTEGER NOT NULL, flow2 INTEGER NOT NULL, at INTEGER NOT NULL)";/** Codes to delete an account with, per number an hour, whether or not the number is on Cotton. */const DELETE_CODES_PER_HOUR = 5;exportclassDirectoryextendsDurableObject<Env> {privatereadonly sql: SqlStorage;privatereadonly limits: { attempts: number; signUps: number; everywhere: number };/** The number key, once the migration has run; null when the Worker's VAULT_KEY is missing or no longer the one the keys were made with. */private numberKey: CryptoKey | null = null;private keyProblem: string | null = null; constructor(ctx: DurableObjectState, env: Env) {super(ctx, env);this.sql = ctx.storage.sql;this.limits = limitsFor(env);this.sql.exec(SCHEMA);void ctx.blockConcurrencyWhile(() => this.migrate()); }/** * The directory keeps no number in the clear (20 Nov 2026): each row's * number becomes its key (src/number_key.ts) and the clear column is * emptied, in one transaction, so a row is never left with neither. Run at * every start; a row already keyed is not touched, so running it again * changes nothing. The approval routes' numbers (an hour long) go the same way. */async migrate(): Promise<void> {this.numberKey = null;this.keyProblem = null;const columns = [...this.sql.exec("PRAGMA table_info(database)")].map((c) => c.name);if (!columns.includes("phone_key")) this.sql.exec("ALTER TABLE database ADD COLUMN phone_key TEXT");// Bulk discovery is gone (DISCOVERY OFF 1): the "people can find me" mark is erased, not kept.if (columns.includes("findable")) this.sql.exec("ALTER TABLE database DROP COLUMN findable");// And the count of numbers each person asked about, which nothing reads since DISCOVERY OFF 2.this.sql.exec("DROP TABLE IF EXISTS discover_spend");this.sql.exec("CREATE UNIQUE INDEX IF NOT EXISTS database_by_phone_key ON database (phone_key)");const key = await numberKeyOf(this.env);if (!key) {this.keyProblem = "The directory has no number key: the Worker's VAULT_KEY secret is not set.";return; }const check = await keyCheck(key);const held = this.sql.exec<{ value: string }>("SELECT value FROM directory_meta WHERE name = 'key_check'").toArray()[0]?.value;if (held && held !== check) {this.keyProblem = "The directory's number key is not the one its numbers were kept with: VAULT_KEY changed. Nobody can sign in until it is put back.";return; }const clear = this.sql.exec<{ id: string; phone: string }>("SELECT id, phone FROM database WHERE phone IS NOT NULL").toArray();const keyed = awaitPromise.all(clear.map(async (r) => ({ id: r.id, key: await keyOfDigest(key, await numberDigest(r.phone)) })));const routes = this.sql.exec<{ id: string; phone: string }>("SELECT id, phone FROM approval_route WHERE phone LIKE '+%'").toArray();const routed = awaitPromise.all(routes.map(async (r) => ({ id: r.id, key: await keyOfDigest(key, await numberDigest(r.phone)) })));this.ctx.storage.transactionSync(() => {if (!held) this.sql.exec("INSERT INTO directory_meta (name, value) VALUES ('key_check', ?)", check);for (const row of keyed) this.sql.exec("UPDATE database SET phone_key = ?, phone = NULL WHERE id = ?", row.key, row.id);for (const row of routed) this.sql.exec("UPDATE approval_route SET phone = ? WHERE id = ?", row.key, row.id);// An hour's ask counts were kept by number: they go (at most an hour of asks forgotten).this.sql.exec("DELETE FROM hit WHERE ip LIKE 'number:+%'"); });this.numberKey = key; }/** The key the directory keeps for an E.164 number; throws when the directory has no good key (never a second database for a number it cannot find). */privateasync keyOf(phone: string): Promise<string> {returnthis.keyOfDigest(await numberDigest(phone)); }privateasync keyOfDigest(digest: string): Promise<string> {if (!this.numberKey) thrownewError(this.keyProblem ?? "The directory's number key is not ready.");return keyOfDigest(this.numberKey, digest); }/** * A sign-in asks for a code: the database `phone` owns, made now when it * has none. `phone` is already E.164. */async open(phone: string, ip: string): Promise<Answer<Entry & { made: boolean }>> {const busy = this.attempt(ip, true);if (busy) return { refused: busy };// A network past its hour's new accounts is refused for every number, new or not (ROUTES-AUDIT 6): refusing new// numbers alone said which numbers were on Cotton.if (this.count(blockOf(ip), "sign_up") >= this.limits.signUps) return { refused: { status: 429, code: "too_many_sign_ups", message: "Too many new accounts from this network in the last hour; try again later." } };const key = awaitthis.keyOf(phone);let row = this.byKey(key);let made = false;if (!row) {const id = crypto.randomUUID();this.sql.exec("INSERT INTO database (id, slug, phone_key, region, created_at) VALUES (?, ?, ?, ?, ?)", id, slugFor(id), key, REGION, newDate().toISOString());this.hit(blockOf(ip), "sign_up"); row = this.byKey(key)!; made = true; }// AUDIT F (the stranger audit's timing oracle): one call to the object either way, as cheap either way. A new row's// object is prepared (its meta, a few rows; the kit is laid at its first proved code); a made one only answers.// A row whose object was not finished (a failed first try) is finished by the next one; preparing it again changes nothing.if (row.provisioned !== 1) {awaitthis.object(row.slug).prepare({ databaseId: row.id, slug: row.slug, phone });this.sql.exec("UPDATE database SET provisioned = 1 WHERE id = ?", row.id); } else {awaitthis.object(row.slug).ready(); }return { ok: { databaseId: row.id, slug: row.slug, made } }; }/** A sign-in proves its code: the object of `databaseId`, counted against the IP like asking. */ admit(databaseId: string, ip: string): Answer<Entry> {const busy = this.attempt(ip, true);if (busy) return { refused: busy };const entry = this.find(databaseId);if (!entry) return { refused: { status: 404, code: "no_such_database", message: "No database has that id; ask for a code again." } };return { ok: entry }; }/** The object a token's database lives in, or null. Rows never move, so a Worker may keep the answer. */ find(databaseId: string): Entry | null {const row = this.sql.exec<{ id: string; slug: string }>("SELECT id, slug FROM database WHERE id = ? AND provisioned = 1", databaseId).toArray()[0];return row ? { databaseId: row.id, slug: row.slug } : null; }/** * The object a number's database lives in, or null: Cotton Calling's way * from a number to the object to ring. It never makes a database — a call * to a number with no Cotton reads as one nobody answered. */async lookup(phone: string): Promise<string | null> {const key = awaitthis.keyOf(phone);returnthis.sql.exec<{ slug: string }>("SELECT slug FROM database WHERE phone_key = ? AND provisioned = 1", key).toArray()[0]?.slug ?? null; }/** `lookup` by the number's digest (number_key.ts `numberDigest`): what an object asks for someone whose number it keeps only sealed (the Circle, b.4). */async lookupDigest(digest: string): Promise<string | null> {if (!/^[0-9a-f]{64}$/.test(digest)) returnnull;const key = awaitthis.keyOfDigest(digest);returnthis.sql.exec<{ slug: string }>("SELECT slug FROM database WHERE phone_key = ? AND provisioned = 1", key).toArray()[0]?.slug ?? null; }/** * A database made before the directory (the owner's own personal object), * entered by the coordinator with the admin token. Its object must already * say the same database id and owner phone; entering it again changes nothing. *//** * Whether `slug` names an object Cotton made (AUDIT FIX B1, B-6): a database of the directory's (live, or erased, so * its phones are still told it is gone), or a slug the admin token reached (a business, onboarded by the admin). The * front addresses no object for any other slug, so a made-up one makes nothing. */async slugKnown(slug: string): Promise<boolean> {returnthis.sql.exec("SELECT 1 FROM database WHERE slug = ? UNION ALL SELECT 1 FROM erased WHERE slug = ? UNION ALL SELECT 1 FROM known_slug WHERE slug = ? LIMIT 1", slug, slug, slug).toArray().length > 0; }/** A Circle invitation's code and the object that made it (src/chat/circle_invite.ts): kept until it ends. */async circleInviteKeep(code: string, slug: string, endsAt: number): Promise<void> {this.sql.exec("DELETE FROM circle_invite_code WHERE ends_at < ?", Date.now());this.sql.exec("INSERT INTO circle_invite_code (code, slug, ends_at) VALUES (?, ?, ?)", code, slug, endsAt); }/** The object a live invitation code leads to, or null. */async circleInviteFind(code: string): Promise<string | null> {returnthis.sql.exec<{ slug: string }>("SELECT slug FROM circle_invite_code WHERE code = ? AND ends_at > ?", code, Date.now()).toArray()[0]?.slug ?? null; }/** An invitation stopped or used: its code leads nowhere from now on. */async circleInviteDrop(code: string): Promise<void> {this.sql.exec("DELETE FROM circle_invite_code WHERE code = ?", code); }/** A slug the admin token reached: an object the admin makes or keeps (onboarding a business, a database before the directory). */async knowSlug(slug: string): Promise<void> {this.sql.exec("INSERT OR IGNORE INTO known_slug (slug, at) VALUES (?, ?)", slug, Date.now()); }/** * JOBS OUT 4 (the dead-man check): a page of the accounts' objects, by slug after `after`, for the Worker's cron to * ask each one how its alarm stands. Never reads more than `limit` rows (at most 500). */async alarmWatchPage(after: string, limit: number): Promise<string[]> {const n = Math.max(1, Math.min(500, Math.floor(limit)));returnthis.sql.exec<{ slug: string }>("SELECT slug FROM database WHERE slug > ? ORDER BY slug LIMIT ?", after, n).toArray().map((r) => r.slug); }async enter(entry: { databaseId: string; slug: string; phone: string }): Promise<Answer<Entry>> {const key = awaitthis.keyOf(entry.phone);const held = this.sql.exec<{ id: string; slug: string; phone_key: string | null }>("SELECT id, slug, phone_key FROM database WHERE id = ? OR slug = ? OR phone_key = ?", entry.databaseId, entry.slug, key).toArray();if (held.some((r) => r.id !== entry.databaseId || r.slug !== entry.slug || r.phone_key !== key)) {return { refused: { status: 409, code: "taken", message: "That id, object or number is already in the directory under another database." } }; }const meta = awaitthis.object(entry.slug).identity();if (meta.databaseId !== entry.databaseId || meta.ownerPhone !== entry.phone || meta.kind !== "personal") {return { refused: { status: 409, code: "not_that_object", message: `The object ${entry.slug} is not the personal database ${entry.databaseId} owned by that number.` } }; }if (!held.length) this.sql.exec("INSERT INTO database (id, slug, phone_key, region, created_at, provisioned) VALUES (?, ?, ?, ?, ?, 1)", entry.databaseId, entry.slug, key, REGION, newDate().toISOString());return { ok: { databaseId: entry.databaseId, slug: entry.slug } }; }// ── a person deletes their account (src/account_delete.ts) ──────────/** * The number's object, for deleting from the web: never makes one. Counted * per IP as a sign-in is; a number on no database answers null. */async deleting(phone: string, ip: string, asking = false): Promise<Answer<{ slug: string | null }>> {const busy = this.attempt(ip, true);if (busy) return { refused: busy };if (asking) {// Codes to delete with are counted per number here, held or not, so the limit says nothing (ROUTES-AUDIT 6).const who = `delete:${await this.keyOf(phone)}`;if (this.count(who, "delete_code") >= DELETE_CODES_PER_HOUR) return { refused: { status: 429, code: "too_many_codes", message: "Too many codes for this number in the last hour; try again later." } };this.hit(who, "delete_code"); }return { ok: { slug: awaitthis.lookup(phone) } }; }/** * The deleted account's object says it is going: the number's entry goes * (so the number signs up again, empty), with every wait, discovery count * and approval route of its object, and the database id is kept as erased, * so a phone's credential is told the account was deleted. Asked again, * nothing more changes. */async forget(databaseId: string, slug: string): Promise<void> {this.ctx.storage.transactionSync(() => {this.sql.exec("INSERT OR IGNORE INTO erased (id, slug, started_at) VALUES (?, ?, ?)", databaseId, slug, newDate().toISOString());this.sql.exec("UPDATE deleting SET state = 'erased', changed_at = ? WHERE id = ?", newDate().toISOString(), databaseId);this.sql.exec("DELETE FROM database WHERE id = ? OR slug = ?", databaseId, slug);this.sql.exec("DELETE FROM waiting WHERE slug = ?", slug);this.sql.exec("DELETE FROM approval_route WHERE slug = ?", slug);// TRUSTED RECOVERY BUILD 3: the account's word on its ways back in goes with it.this.sql.exec(RECOVERY_FLOW_SCHEMA);this.sql.exec("DELETE FROM recovery_flow WHERE id = ?", databaseId);// DELETE ACCOUNT 1: what else named the object. Their own mail domain stops routing to it (a domain names its// person), the bounces of mail they sent are no longer traced back, their fourteen days and their naming of an// inviter go. A referral either way stays counted for the other person, who keeps the month it earned them, with// this account's side replaced by a random id that names no one.this.sql.exec("DELETE FROM mail_domain WHERE slug = ?", slug);this.sql.exec("DELETE FROM mail_sent WHERE slug = ?", slug);this.sql.exec("DELETE FROM active14 WHERE slug = ?", slug);this.sql.exec("DELETE FROM inviter_named WHERE friend = ?", slug);for (const r ofthis.sql.exec<{ friend: string }>("SELECT friend FROM referral WHERE friend = ?", slug).toArray()) this.sql.exec("UPDATE referral SET friend = ? WHERE friend = ?", `erased-${crypto.randomUUID()}`, r.friend);this.sql.exec("UPDATE referral SET referrer = 'erased' WHERE referrer = ?", slug);// The erase's own knocks count afresh (DELETE ACCOUNT 3): those spent while it waited for its date are not its.this.sql.exec(KNOCK_SCHEMA);this.sql.exec("DELETE FROM sweep_knock WHERE id = ?", databaseId);// Its snapshots' key: whatever copy lingers anywhere no longer reads (SNAPSHOTS 1).this.sql.exec("DELETE FROM snapshot_key WHERE slug = ?", slug);// A Circle invite code it gave out no longer leads to it (publishing checklist, 28 Nov 2026). Its slug stays// known (`known_slug`), so the name is never handed to someone else.this.sql.exec("DELETE FROM circle_invite_code WHERE slug = ?", slug); });// The sweep looks after this erase until it closes (`sweep`).awaitthis.sweepBy(Date.now() + SWEEP_LATE_MS); }/** * Ninety days after the erase (src/account_delete.ts FORGET_AFTER_MS): the receipt stays, under a fresh random id * with no object named, and the deleted database's id is let go, so a credential naming it is one for no account. */ forgetReceipt(databaseId: string): void {const fresh = `r-${crypto.randomUUID()}`;this.ctx.storage.transactionSync(() => {this.sql.exec("UPDATE erased SET id = ?, slug = '' WHERE id = ?", fresh, databaseId);this.sql.exec("UPDATE deleting SET id = ? WHERE id = ?", fresh, databaseId);this.sql.exec("DELETE FROM sweep_knock WHERE id = ?", databaseId); }); }// ── the deletions' sweep (DELETE ACCOUNT 1) ─────────────────────────/** The directory's alarm, set no later than `at`. */privateasync sweepBy(at: number): Promise<void> {const held = awaitthis.ctx.storage.getAlarm();if (held === null || held > at) awaitthis.ctx.storage.setAlarm(at); } override async alarm(): Promise<void> {awaitthis.sweep(); }/** * THE SWEEP ONLY KNOCKS (DELETE ACCOUNT 2). Every deletion the directory holds that should have moved and did not is * asked after at its object (src/business.ts `deleteResume`): "check your own job". It carries no date and no * authority: only the object's own row moves an erase, and with no row the object answers live and nothing is * touched. On the answer: a pending row whose object is live is marked kept; one whose database the directory no * longer holds is marked gone; a pending row takes the object's own date. Each row is knocked at most MAX_KNOCKS * times, an hour apart, so the sweep's alarm always ends. The hour's sign-in counts are thinned too. */async sweep(now = Date.now()): Promise<{ asked: number; failed: number }> {this.sql.exec(KNOCK_SCHEMA);this.sql.exec("DELETE FROM hit WHERE at < ?", now - 3_600_000);const late = newDate(now - SWEEP_LATE_MS).toISOString();const forgetBy = newDate(now - FORGET_AFTER_MS - SWEEP_LATE_MS).toISOString();const knocks: { id: string; slug: string; kind: "pending" | "erased" }[] = [];for (const r ofthis.sql.exec<{ id: string; slug: string | null }>("SELECT d.id, b.slug FROM deleting d LEFT JOIN database b ON b.id = d.id WHERE d.state = 'pending' AND d.erase_at < ?", late).toArray()) {if (r.slug) knocks.push({ id: r.id, slug: r.slug, kind: "pending" });elsethis.sql.exec("UPDATE deleting SET state = 'gone', changed_at = ? WHERE id = ? AND state = 'pending'", newDate(now).toISOString(), r.id); }for (const r ofthis.sql.exec<{ id: string; slug: string }>("SELECT id, slug FROM erased WHERE slug <> '' AND ((finished_at IS NULL AND started_at < ?) OR finished_at < ?)", late, forgetBy).toArray()) { knocks.push({ id: r.id, slug: r.slug, kind: "erased" }); }let asked = 0;let failed = 0;for (const k of knocks) {const held = this.sql.exec<{ n: number; at: number }>("SELECT n, at FROM sweep_knock WHERE id = ?", k.id).toArray()[0];if (held && (held.n >= MAX_KNOCKS || held.at > now - SWEEP_LATE_MS + 60_000)) continue;this.sql.exec("INSERT INTO sweep_knock (id, n, at) VALUES (?, 1, ?) ON CONFLICT (id) DO UPDATE SET n = n + 1, at = excluded.at", k.id, now);// The last knock (DELETE ACCOUNT 3): whatever it answers, the row is marked stuck unless it moved, for an admin to see.const last = (held?.n ?? 0) + 1 >= MAX_KNOCKS; asked += 1;try {const answer = awaitthis.object(k.slug).deleteResume(); console.log(`cottondb: directory sweep: ${k.slug} checked its own deletion: ${answer.phase}`);if (k.kind === "pending" && answer.phase === "live") {this.sql.exec("UPDATE deleting SET state = 'kept', changed_at = ? WHERE id = ? AND state = 'pending'", newDate(now).toISOString(), k.id);this.sql.exec("DELETE FROM sweep_knock WHERE id = ?", k.id); }elseif (k.kind === "pending" && answer.phase === "pending" && Number.isNaN(Date.parse(answer.erase_at ?? ""))) {// A date the object cannot read is never due there: stuck, for an admin (DELETE ACCOUNT 3). console.error(`cottondb: directory sweep: ${k.slug}'s date does not read; marked stuck`);this.stuck(k.id, now); } elseif (k.kind === "pending" && answer.phase === "pending" && answer.erase_at) this.sql.exec("UPDATE deleting SET erase_at = ? WHERE id = ?", answer.erase_at, k.id);elseif (k.kind === "erased" && answer.phase === "live") {// Held as erased, but the object holds no deletion of its own: nothing to do here, said once for an admin. console.error(`cottondb: directory sweep: ${k.slug} is held as erased but its object answers live; no more knocks`);this.stuck(k.id, now); } elseif (last && this.stillDue(k)) this.stuck(k.id, now); } catch (error) { failed += 1;const message = error instanceofError ? error.message : "unknown";// A frozen object (RESTORE 2) says it did not take the knock: it is not counted, and asked again by a later sweep.if (message.startsWith(FROZEN_CALL)) {this.sql.exec("UPDATE sweep_knock SET n = max(0, n - 1) WHERE id = ?", k.id); console.log(`cottondb: directory sweep: ${k.slug} is frozen for a restore; the knock is not counted`);continue; } console.error(`cottondb: directory sweep: ${k.slug} did not answer`, message);if (last) this.stuck(k.id, now); } }awaitthis.planSweep(now);return { asked, failed }; }/** A deletion the sweep leaves to an admin: knocks spent, its directory row says `stuck` (listed by the deletions routes). */private stuck(id: string, now: number): void {this.sql.exec("UPDATE sweep_knock SET n = ? WHERE id = ?", MAX_KNOCKS, id);this.sql.exec("UPDATE deleting SET state = 'stuck', changed_at = ? WHERE id = ?", newDate(now).toISOString(), id); console.error(`cottondb: directory sweep: deletion ${id} left to an admin (stuck)`); }/** Whether what a knock asked after is still to move: a pending row still pending, an erase still open or not yet let go. */private stillDue(k: { id: string; kind: "pending" | "erased" }): boolean {if (k.kind === "pending") returnthis.sql.exec("SELECT 1 FROM deleting WHERE id = ? AND state = 'pending'", k.id).toArray().length > 0;returnthis.sql.exec("SELECT 1 FROM erased WHERE id = ? AND slug <> ''", k.id).toArray().length > 0; }/** * The next sweep: for each row still in the plan (fewer than MAX_KNOCKS knocks), its due time, or an hour after its * last knock when that is later; none when no row is left in it. */privateasync planSweep(now: number): Promise<void> {this.sql.exec(KNOCK_SCHEMA);const dues: { due: string; last: number | null }[] = [ ...this.sql.exec<{ due: string; last: number | null }>("SELECT d.erase_at AS due, k.at AS last FROM deleting d LEFT JOIN sweep_knock k ON k.id = d.id WHERE d.state = 'pending' AND coalesce(k.n, 0) < ?", MAX_KNOCKS).toArray(), ...this.sql.exec<{ due: string; last: number | null }>("SELECT e.started_at AS due, k.at AS last FROM erased e LEFT JOIN sweep_knock k ON k.id = e.id WHERE e.slug <> '' AND e.finished_at IS NULL AND coalesce(k.n, 0) < ?", MAX_KNOCKS).toArray(), ...this.sql .exec<{ due: string; last: number | null }>("SELECT e.finished_at AS due, k.at AS last FROM erased e LEFT JOIN sweep_knock k ON k.id = e.id WHERE e.slug <> '' AND e.finished_at IS NOT NULL AND coalesce(k.n, 0) < ?", MAX_KNOCKS) .toArray() .map((r) => ({ due: newDate(Date.parse(r.due) + FORGET_AFTER_MS).toISOString(), last: r.last })), ];const times = dues.map((d) => Math.max(Date.parse(d.due) + SWEEP_LATE_MS, (d.last ?? 0) + SWEEP_LATE_MS));if (!times.length) returnvoid (awaitthis.ctx.storage.deleteAlarm());awaitthis.ctx.storage.setAlarm(Math.max(Math.min(...times), now + SWEEP_SOON_MS)); }/** * The admin's read-only count (`GET /v1/admin/deletions/check`): each row the directory holds as pending, asked of * its object read only. `live` are rows whose object holds no deletion (a Keep the directory was never told of); * `gone` rows whose database the directory no longer holds. Database ids only: no number. */async checkPending(): Promise<{ pending: number; object_pending: number; live: string[]; gone: string[]; stuck: string[]; other: Record<string, number>; failed: number }> {const rows = this.sql.exec<{ id: string; slug: string | null }>("SELECT d.id, b.slug FROM deleting d LEFT JOIN database b ON b.id = d.id WHERE d.state = 'pending'").toArray();const stuck = this.sql.exec<{ id: string }>("SELECT id FROM deleting WHERE state = 'stuck' ORDER BY changed_at").toArray().map((r) => r.id);const out = { pending: rows.length, object_pending: 0, live: [] as string[], gone: [] as string[], stuck, other: {} asRecord<string, number>, failed: 0 };for (const r of rows) {if (!r.slug) { out.gone.push(r.id);continue; }try {const phase = awaitthis.object(r.slug).deleteStanding();if (phase === "live") out.live.push(r.id);elseif (phase === "pending") out.object_pending += 1;else out.other[phase] = (out.other[phase] ?? 0) + 1; } catch { out.failed += 1; } }return out; }/** The founder row check over every database, a page at a time (KEPT FOUR 3 LOW): counts and kinds only, never an id. */async checkVaultKeys(from: number, limit: number): Promise<VaultKeyPage> {const rows = this.sql.exec<{ slug: string }>("SELECT slug FROM database ORDER BY id LIMIT ? OFFSET ?", limit, from).toArray();const out: VaultKeyPage = { objects: 0, flagged: 0, failed: 0, kinds: {}, next: rows.length === limit ? from + limit : null };for (const r of rows) {try {const report = awaitthis.object(r.slug).vaultKeyStanding(); out.objects += 1;if (report.flagged) out.flagged += 1; countKinds(out.kinds, report); } catch { out.failed += 1; } }return out; }/** The founder row check of ONE database, called by its id: the object's whole report, or null when none is held. */async checkVaultKeysOf(databaseId: string): Promise<VaultKeyReport | null> {const slug = this.sql.exec<{ slug: string }>("SELECT slug FROM database WHERE id = ?", databaseId).toArray()[0]?.slug;return slug ? awaitthis.object(slug).vaultKeyStanding() : null; }/** * SNAPSHOTS 1: an account's snapshot key (32 random bytes, base64), made the first time it is asked with `make`; null * when none is kept and none is to be made. Only the account's own object asks, by its slug. */ snapshotKey(slug: string, make: boolean): string | null {const held = this.sql.exec<{ key: string }>("SELECT key FROM snapshot_key WHERE slug = ?", slug).toArray()[0];if (held) return held.key;if (!make) returnnull;const bytes = crypto.getRandomValues(newUint8Array(32));let raw = "";for (const b of bytes) raw += String.fromCharCode(b);const key = btoa(raw);this.sql.exec("INSERT INTO snapshot_key (slug, key, created_at) VALUES (?, ?, ?)", slug, key, newDate().toISOString());return key; }/** SNAPSHOTS 1, for tests and the account delete's check: whether a slug's snapshot key is kept. */ snapshotKeyKept(slug: string): boolean {returnthis.sql.exec("SELECT 1 FROM snapshot_key WHERE slug = ?", slug).toArray().length > 0; }/** * An account set to be deleted (src/account_delete.ts): the number stays on its database for the thirty days, * so signing in again is this account; only the counts below read this. Asked again, the first date stands. */async deletingSet(databaseId: string, _slug: string, askedAt: string, eraseAt: string): Promise<void> {// Asked again after a Keep (DELETE ACCOUNT 2): pending again, with the new dates, and knocked afresh.this.sql.exec(KNOCK_SCHEMA);this.sql.exec("INSERT INTO deleting (id, asked_at, erase_at, state, changed_at) VALUES (?, ?, ?, 'pending', ?) ON CONFLICT (id) DO UPDATE SET asked_at = excluded.asked_at, erase_at = excluded.erase_at, state = 'pending', changed_at = excluded.changed_at WHERE deleting.state <> 'pending'", databaseId, askedAt, eraseAt, askedAt, );this.sql.exec("DELETE FROM sweep_knock WHERE id = ?", databaseId);// The sweep looks in an hour after the date, in case the object's own alarm was lost.awaitthis.sweepBy(Date.parse(eraseAt) + SWEEP_LATE_MS); }/** * Whether an account (its object's slug) is no longer one the directory holds: asked by a helper's object about the * accounts it holds pieces for, so pieces for an erased person go (TRUSTED RECOVERY BUILD 3). Objects only. */ accountGone(slug: string): boolean {if (typeof slug !== "string" || !slug) returnfalse;returnthis.sql.exec("SELECT 1 FROM database WHERE slug = ?", slug).toArray().length === 0; }/** An account's object says where its ways back in stand (src/recovery.ts `flowReport`): counts, no number. */ recoveryFlow(databaseId: string, report: { old_setup: boolean; flow1: number; flow2: number }): void {this.sql.exec(RECOVERY_FLOW_SCHEMA);this.sql.exec("INSERT INTO recovery_flow (id, old_setup, flow1, flow2, at) VALUES (?, ?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET old_setup = excluded.old_setup, flow1 = excluded.flow1, flow2 = excluded.flow2, at = excluded.at", databaseId, report.old_setup ? 1 : 0, Math.max(0, Math.floor(report.flow1)), Math.max(0, Math.floor(report.flow2)), Date.now(), ); }/** * The owner's count (`GET /v1/admin/recovery/flows`): accounts with a one-helper setup still standing, devices that * last spoke each flow, and accounts with any device on flow 1. Counts only: no id, number or date of anyone's. */ recoveryFlowCounts(): { accounts: number; old_setup: number; accounts_with_flow1: number; devices: { flow1: number; flow2: number } } {this.sql.exec(RECOVERY_FLOW_SCHEMA);const r = this.sql.exec<{ accounts: number; old_setup: number | null; with1: number | null; flow1: number | null; flow2: number | null }>("SELECT COUNT(*) AS accounts, SUM(old_setup) AS old_setup, SUM(flow1 > 0) AS with1, SUM(flow1) AS flow1, SUM(flow2) AS flow2 FROM recovery_flow", ).one();return { accounts: Number(r.accounts), old_setup: Number(r.old_setup ?? 0), accounts_with_flow1: Number(r.with1 ?? 0), devices: { flow1: Number(r.flow1 ?? 0), flow2: Number(r.flow2 ?? 0) } }; }/** * RESTORE 2, dev and test only (src/restore.ts): an erased account put back by point-in-time recovery. Its id leaves * `erased` and `deleting`, and its number's entry comes back on the same database (as `enter` makes it, which checks * the object says the same id and owner). On live, delete means delete: refused. */async restoredAfterErase(entry: { databaseId: string; slug: string; phone: string }, deletion?: { asked_at: string; erase_at: string }): Promise<boolean> {if (this.env.ENV_LABEL !== "dev" && this.env.ENV_LABEL !== "test") returnfalse;this.ctx.storage.transactionSync(() => {this.sql.exec("DELETE FROM erased WHERE id = ?", entry.databaseId);this.sql.exec("DELETE FROM deleting WHERE id = ?", entry.databaseId);// Put back to a moment in its thirty days (RESTORE 2 SERVER 2, M3): the deletion pending again, its dates as they were.if (deletion) this.sql.exec("INSERT INTO deleting (id, asked_at, erase_at, state, changed_at) VALUES (?, ?, ?, 'pending', ?)", entry.databaseId, deletion.asked_at, deletion.erase_at, newDate().toISOString()); });const entered = awaitthis.enter(entry);return"ok"in entered; }/** The person kept it in the thirty days. */ deletingKept(databaseId: string): void {this.sql.exec("UPDATE deleting SET state = 'kept', changed_at = ? WHERE id = ? AND state = 'pending'", newDate().toISOString(), databaseId);this.sql.exec(KNOCK_SCHEMA);this.sql.exec("DELETE FROM sweep_knock WHERE id = ?", databaseId); }/** * The operator's count (owner, 22 Nov 2026: no manual step, no request to approve): by day, how many accounts * were set for deletion, kept and erased, and how many are set now. Counts only: no id, number or date of anyone's. */ deletingCounts(days = 30): { now_pending: number; stuck: number; days: { day: string; set: number; kept: number; erased: number }[] } {const nowPending = this.sql.exec<{ n: number }>("SELECT count(*) AS n FROM deleting WHERE state = 'pending'").one().n;const stuck = this.sql.exec<{ n: number }>("SELECT count(*) AS n FROM deleting WHERE state = 'stuck'").one().n;const rows = this.sql .exec<{ day: string; set: number; kept: number; erased: number }>(`SELECT day, sum(set_) AS "set", sum(kept) AS kept, sum(erased) AS erased FROM ( SELECT substr(asked_at, 1, 10) AS day, 1 AS set_, 0 AS kept, 0 AS erased FROM deleting UNION ALL SELECT substr(changed_at, 1, 10), 0, 1, 0 FROM deleting WHERE state = 'kept' UNION ALL SELECT substr(changed_at, 1, 10), 0, 0, 1 FROM deleting WHERE state = 'erased' ) WHERE day >= date('now', ?) GROUP BY day ORDER BY day DESC`,`-${days} days`, ) .toArray();return { now_pending: nowPending, stuck, days: rows }; }/** The finished deletion's receipt (counts and dates only), kept by database id. */ closed(databaseId: string, receipt: { finished_at: string | null }): void {this.sql.exec("UPDATE erased SET finished_at = ?, receipt = ? WHERE id = ?", receipt.finished_at, JSON.stringify(receipt), databaseId);// Its knocks go with it: the next ones, ninety days on, count afresh.this.sql.exec(KNOCK_SCHEMA);this.sql.exec("DELETE FROM sweep_knock WHERE id = ?", databaseId); }/** Whether a database id was deleted by its person: a credential naming it is told so. */ wasErased(databaseId: string): boolean {returnthis.sql.exec<{ n: number }>("SELECT count(*) AS n FROM erased WHERE id = ?", databaseId).one().n > 0; }/** A deleted database's receipt, or null. */ receipt(databaseId: string): { id: string; started_at: string; finished_at: string | null; receipt: unknown } | null {const row = this.sql.exec<{ id: string; started_at: string; finished_at: string | null; receipt: string | null }>("SELECT id, started_at, finished_at, receipt FROM erased WHERE id = ?", databaseId).toArray()[0];return row ? { id: row.id, started_at: row.started_at, finished_at: row.finished_at, receipt: row.receipt ? JSON.parse(row.receipt) : null } : null; }// ── a sign-in approved from another device (src/approval.ts) ──────────/** * A device asks to be approved for `phone`. Never makes a database: a * number with none, or an object that refuses the ask, still gets an ask * of the same shape, which waits and expires. Counted per IP like a code * and per number on its own. */async ask(phone: string, deviceId: string, deviceName: string | null, vaultKey: string | null, commit: string, ip: string, deviceKind: DeviceKind | null = null): Promise<Answer<{ ask_id: string; expires_in: number; poll_seconds: number }>> {const busy = this.attempt(ip);if (busy) return { refused: busy };const phoneKey = awaitthis.keyOf(phone);const byNumber = `number:${phoneKey}`;if (this.count(byNumber, "ask") >= ASKS_PER_HOUR) return { refused: { status: 429, code: "too_many_asks", message: "Too many sign-in asks for this number in the last hour; try again later, or send a code." } };this.hit(byNumber, "ask");const now = Math.floor(Date.now() / 1000);this.sql.exec("DELETE FROM approval_route WHERE expires_at < ?", now - 3600);const id = newAskId();const expiresAt = now + ASK_TTL_SECONDS;// A number on no database is held by NOBODY, an object like any other: the same call, the same code answering// every later poll, reveal and claim, so neither the answers nor their timing say whether the number is on Cotton.const slug = (awaitthis.lookup(phone)) ?? NOBODY;this.sql.exec("INSERT INTO approval_route (id, slug, phone, expires_at) VALUES (?, ?, ?, ?)", id, slug, phoneKey, expiresAt);const ask = { id, phone, deviceId, deviceName, deviceKind, vaultKey, commit, createdAt: now, expiresAt };try {if (slug === NOBODY) awaitthis.object(slug).approvalHold(ask);elseawaitthis.object(slug).approvalAsk(ask); } catch (error) {// Said nowhere but the log: the asking device's answer is the same either way. console.error("cottondb: an approval ask did not reach its object", error instanceofError ? error.message : "unknown"); }return { ok: { ask_id: id, expires_in: ASK_TTL_SECONDS, poll_seconds: POLL_SECONDS } }; }/** The asking device reveals its nonce; an ask with no object never had an approver's nonce to answer. */async reveal(askId: string, nonce: string, ip: string): Promise<Answer<{ ok: true }>> {const busy = this.attempt(ip);if (busy) return { refused: busy };const route = this.route(askId);if (!route) return { refused: { status: 404, code: "no_such_ask", message: "No such sign-in ask; ask again." } };if (!route.slug) return { refused: { status: 409, code: "too_early", message: "No device has opened this sign-in ask yet." } };const refused = (awaitthis.object(route.slug).approvalReveal(askId, nonce)) asRefusal | null;return refused ? { refused } : { ok: { ok: true } }; }/** What an ask stands at: an ask with no object waits until it expires. */async askState(askId: string): Promise<Answer<{ state: AskState; nonce_b?: string; challenge?: string; why?: "wrong" }>> {const route = this.route(askId);if (!route) return { refused: { status: 404, code: "no_such_ask", message: "No such sign-in ask; ask again." } };const now = Math.floor(Date.now() / 1000);if (!route.slug) return { ok: { state: route.expires_at < now ? "expired" : "waiting" } };return { ok: awaitthis.object(route.slug).approvalState(askId) }; }/** The asking device claims its credential; an ask with no object was never approved. */async claim(askId: string, sig: string, ip: string): Promise<Answer<Record<string, unknown> & { database_id: string }>> {const busy = this.attempt(ip);if (busy) return { refused: busy };const route = this.route(askId);if (!route) return { refused: { status: 404, code: "no_such_ask", message: "No such sign-in ask; ask again." } };if (!route.slug) return { refused: { status: 409, code: "not_approved", message: "That sign-in has not been approved." } };const answer = (awaitthis.object(route.slug).approvalClaim(askId, sig)) as { refused: Refusal } | { ok: Record<string, unknown> };if ("refused"in answer) return { refused: answer.refused };const databaseId = this.sql.exec<{ id: string }>("SELECT id FROM database WHERE slug = ?", route.slug).toArray()[0]?.id ?? "";return { ok: { ...answer.ok, database_id: databaseId } }; }// ── a Cotton passkey's sign-in (src/passkey.ts) ────────────────────────/** A challenge for a passkey sign-in, before anyone says who they are. Counted per IP like a code. */ passkeyBegin(ip: string): Answer<{ challenge_id: string; challenge: string }> {const busy = this.attempt(ip);if (busy) return { refused: busy };const now = Math.floor(Date.now() / 1000);this.sql.exec("DELETE FROM passkey_challenge WHERE expires_at < ?", now);const id = `ctp_${passkeyChallenge().slice(0, 32)}`;const challenge = passkeyChallenge();this.sql.exec("INSERT INTO passkey_challenge (id, challenge, expires_at) VALUES (?, ?, ?)", id, challenge, now + PASSKEY_CHALLENGE_SECONDS);return { ok: { challenge_id: id, challenge } }; }/** * A passkey signs in: the challenge spent once, the database its user handle names, and the object's check of the * signature. Every refusal past the IP limit is the same one, so nothing says which passkeys or databases exist. */async passkeySignIn(challengeId: string, response: Record<string, unknown>, rpId: string, deviceId: string, ip: string): Promise<Answer<Record<string, unknown> & { database_id: string }>> {const busy = this.attempt(ip);if (busy) return { refused: busy };const now = Math.floor(Date.now() / 1000);const spent = this.sql.exec<{ challenge: string; expires_at: number }>("DELETE FROM passkey_challenge WHERE id = ? RETURNING challenge, expires_at", challengeId).toArray()[0];if (!spent || spent.expires_at < now) return { refused: PASSKEY_REFUSED };const handle = (response.response asRecord<string, unknown> | undefined)?.userHandle;let databaseId = "";try { databaseId = typeof handle === "string" ? newTextDecoder().decode(fromBase64Url(handle)) : ""; } catch {return { refused: PASSKEY_REFUSED }; }const entry = this.find(databaseId);if (!entry) return { refused: PASSKEY_REFUSED };const answer = (awaitthis.object(entry.slug).passkeySignIn({ challenge: spent.challenge, response, rpId, deviceId })) as { refused: Refusal } | { ok: Record<string, unknown> };if ("refused"in answer) return { refused: answer.refused };return { ok: { ...answer.ok, database_id: entry.databaseId } }; }private route(askId: string): { slug: string | null; expires_at: number } | undefined {returnthis.sql.exec<{ slug: string | null; expires_at: number }>("SELECT slug, expires_at FROM approval_route WHERE id = ?", askId).toArray()[0]; }// ── the open host's OAuth clients ──────────────────────────────────────/** A client the open host's registration made, its redirect URIs already checked; refused when `ip` made the hour's limit. */ register(client: Client, ip: string): Answer<Client> {this.sql.exec("DELETE FROM hit WHERE at < ?", Date.now() - 3_600_000);if (this.count(blockOf(ip), "register") >= REGISTRATIONS_PER_HOUR) return { refused: { status: 429, code: "too_many_registrations", message: "too many registrations this hour; try again later" } };this.hit(blockOf(ip), "register");this.sql.exec("INSERT INTO oauth_client (id, name, redirect_uris, created_at) VALUES (?, ?, ?, ?)", client.id, client.name, JSON.stringify(client.redirectUris), newDate().toISOString());return { ok: client }; } client(id: string): Client | null {const row = this.sql.exec<{ id: string; name: string | null; redirect_uris: string }>("SELECT id, name, redirect_uris FROM oauth_client WHERE id = ?", id).toArray()[0];return row ? { id: row.id, name: row.name, redirectUris: JSON.parse(row.redirect_uris) as string[] } : null; }// ── finding people (Cotton Chat, 20 Nov 2026) ──────────────────────────/** * `waiter`'s owner waits for the number behind `digest`: an invite sent, a message waiting, an ask (DISCOVERY OFF 2, * 27 Nov 2026: nobody is found by their number). The wait is kept by the number's key, the waiter and a ticket, * whether or not the number is on Cotton, and it goes when that number's first chat device comes (`joined`), at the * waiter's take-back, or after 180 days. Every check runs before the number is looked up, and both ways take the * same path, so neither the answer, its code nor the cap tells who is on Cotton. Only the waiter's object hears * which object holds the number (`now`), to hand its ask over; its phone never does. */async wait(waiter: string, digest: string): Promise<Answer<{ ticket: string; now: { slug: string } | null }>> {if (!DIGEST.test(digest)) return { refused: { status: 400, code: "bad_digest", message: "digest: a number digest, 64 hex characters" } };const now = Date.now();this.sql.exec("DELETE FROM waiting WHERE at < ?", now - WAIT_MS);const key = awaitthis.keyOfDigest(digest);const held = this.sql.exec<{ ticket: string }>("SELECT ticket FROM waiting WHERE key = ? AND slug = ?", key, waiter).toArray()[0];if (!held && this.sql.exec<{ n: number }>("SELECT count(*) AS n FROM waiting WHERE slug = ?", waiter).one().n >= WAITS_MAX) return { refused: { status: 429, code: "too_many_waits", message: `You can wait for up to ${WAITS_MAX} people at once.` } };const ticket = held?.ticket ?? crypto.randomUUID();this.sql.exec("INSERT INTO waiting (key, slug, ticket, at) VALUES (?, ?, ?, ?) ON CONFLICT (key, slug) DO UPDATE SET at = excluded.at", key, waiter, ticket, now);const row = this.sql.exec<{ slug: string }>("SELECT slug FROM database WHERE phone_key = ? AND provisioned = 1", key).toArray()[0];return { ok: { ticket, now: row && row.slug !== waiter ? { slug: row.slug } : null } }; } unwait(waiter: string, ticket: string): void {this.sql.exec("DELETE FROM waiting WHERE slug = ? AND ticket = ?", waiter, ticket); }/** * A number's object has its first chat device: whoever waited for that * number, each wait gone as it is answered, and whether its owner may be found. */// ── Own-domain mail (src/mail) ──────────────────────────────────────/** A proved domain's mail goes to `slug`'s object; a domain another database holds is refused. */async mailDomainSet(domain: string, slug: string): Promise<Answer<{ domain: string }>> {const held = this.sql.exec<{ slug: string }>("SELECT slug FROM mail_domain WHERE domain = ?", domain).toArray()[0];if (held && held.slug !== slug) return { refused: { status: 409, code: "domain_taken", message: `${domain} is already another person's mail domain here.` } };if (!held) this.sql.exec("INSERT INTO mail_domain (domain, slug, at) VALUES (?, ?, ?)", domain, slug, Date.now());return { ok: { domain } }; }async mailDomainDrop(domain: string, slug: string): Promise<void> {this.sql.exec("DELETE FROM mail_domain WHERE domain = ? AND slug = ?", domain, slug); }/** Whose object a domain's mail goes to, or null. */async mailDomainOf(domain: string): Promise<string | null> {returnthis.sql.exec<{ slug: string }>("SELECT slug FROM mail_domain WHERE domain = ?", domain.toLowerCase()).toArray()[0]?.slug ?? null; }/** A mail sent from `slug`: kept 30 days, for Cloudflare's later word on it. */async mailSent(messageId: string, slug: string): Promise<void> {const now = Date.now();this.sql.exec("INSERT OR REPLACE INTO mail_sent (message_id, slug, at) VALUES (?, ?, ?)", messageId, slug, now);this.sql.exec("DELETE FROM mail_sent WHERE at < ?", now - 30 * 86_400_000); }async mailSentOf(messageId: string): Promise<string | null> {returnthis.sql.exec<{ slug: string }>("SELECT slug FROM mail_sent WHERE message_id = ?", messageId).toArray()[0]?.slug ?? null; }async joined(slug: string, phone: string, counting = false): Promise<{ waiters: Waiter[] }> {const key = awaitthis.keyOf(phone);const mine = this.sql.exec<{ slug: string }>("SELECT slug FROM database WHERE phone_key = ?", key).toArray()[0];if (!mine || mine.slug !== slug) return { waiters: [] };// Who waited for this number first brought this person (SPACE.md): their referrer, once the rules count.// Only a wait made before this number had a database counts: waits are kept for numbers already on Cotton too// (DISCOVERY OFF 2), and this runs at every chat device post, so a member is never "brought" by a wait made after.if (counting || space.modeOf(this.env.SPACE_RULES) !== "off") {const born = Date.parse(this.sql.exec<{ created_at: string }>("SELECT created_at FROM database WHERE slug = ?", slug).toArray()[0]?.created_at ?? "");const first = this.sql.exec<{ slug: string; at: number }>("SELECT slug, at FROM waiting WHERE key = ? AND at >= ? AND slug != ? ORDER BY at LIMIT 1", key, Date.now() - WAIT_MS, slug).toArray()[0];if (first && Number.isFinite(born) && first.at < born) awaitthis.refer(slug, first.slug); }const waiters = this.sql.exec<{ slug: string; ticket: string }>("DELETE FROM waiting WHERE key = ? AND at >= ? RETURNING slug, ticket", key, Date.now() - WAIT_MS).toArray().filter((w) => w.slug !== slug);return { waiters: waiters.map((w) => ({ slug: w.slug, ticket: w.ticket })) }; }// ── space: who brought whom (assets/design/shared/SPACE.md) ──────────────/** `friend` was brought by `referrer`: kept once, for good, when the referrer's account is older and neither is gone. Counted at once when the friend already has its 14 days. */privateasync refer(friend: string, referrer: string): Promise<boolean> {if (friend === referrer) returnfalse;const made = (s: string) => this.sql.exec<{ created_at: string }>("SELECT created_at FROM database WHERE slug = ?", s).toArray()[0]?.created_at ?? null;const [theirs, mine] = [made(referrer), made(friend)];if (!theirs || !mine || theirs >= mine || this.gone(referrer) || this.gone(friend)) returnfalse;if (this.sql.exec("SELECT 1 FROM referral WHERE friend = ?", friend).toArray().length > 0) returnfalse;this.sql.exec("INSERT INTO referral (friend, referrer, at) VALUES (?, ?, ?)", friend, referrer, Date.now());if (this.sql.exec("SELECT 1 FROM active14 WHERE slug = ?", friend).toArray().length > 0) awaitthis.countReferral(friend);returntrue; }/** An account deleted, or on its way to being deleted, brings no one and is counted by no one. */private gone(slug: string): boolean {const id = this.sql.exec<{ id: string }>("SELECT id FROM database WHERE slug = ?", slug).toArray()[0]?.id;if (!id) returntrue;returnthis.sql.exec("SELECT 1 FROM erased WHERE id = ? UNION SELECT 1 FROM deleting WHERE id = ?", id, id).toArray().length > 0; }/** `slug` has used an app on 14 separate days (its object says so once): the referral naming it as the friend counts now. */async spaceActive(slug: string): Promise<void> {this.sql.exec("INSERT OR IGNORE INTO active14 (slug, at) VALUES (?, ?)", slug, Date.now());awaitthis.countReferral(slug); }/** The referral of `friend`, counted when it is not yet: both accounts told their friends. */privateasync countReferral(friend: string): Promise<void> {const row = this.sql.exec<{ referrer: string }>("UPDATE referral SET counted_at = ? WHERE friend = ? AND counted_at IS NULL RETURNING referrer", Date.now(), friend).toArray()[0];if (!row) return;awaitPromise.all([friend, row.referrer].map((s) => this.object(s).spaceFriends(this.friendsOf(s)).catch(() => undefined))); }/** How many friends `slug` has under the rules: those it brought who are counted, and itself once if it was brought and is counted. */ friendsOf(slug: string): number {returnthis.sql.exec<{ n: number }>("SELECT (SELECT count(*) FROM referral WHERE referrer = ? AND counted_at IS NOT NULL) + (SELECT count(*) FROM referral WHERE friend = ? AND counted_at IS NOT NULL) AS n", slug, slug).one().n; }/** * The new person names who invited them (`POST /v1/space/invited-by`): once, within their first 30 days. The * answer is the same whether the number is on Cotton or not (ROUTES-AUDIT 6, 23 Nov 2026): a number nobody holds, * or one newer than theirs, is taken as their one naming all the same and simply counts for nobody, so the route * never says who is on Cotton. Their friends' count (`GET /v1/space`) shows the referral once it counts. */async spaceInvitedBy(friend: string, number: string): Promise<Answer<Record<string, never>>> {const made = this.sql.exec<{ created_at: string }>("SELECT created_at FROM database WHERE slug = ?", friend).toArray()[0]?.created_at;if (!made) return { refused: { status: 404, code: "no_such_database", message: "No account here." } };if (Date.now() - Date.parse(made) > space.NAME_INVITER_MS) return { refused: { status: 409, code: "too_late", message: "Who invited you can be named in your first 30 days." } };const named = this.sql.exec("SELECT 1 FROM referral WHERE friend = ? UNION SELECT 1 FROM inviter_named WHERE friend = ?", friend, friend).toArray().length > 0;if (named) return { refused: { status: 409, code: "already_named", message: "You have already named who invited you." } };const key = awaitthis.keyOf(number);const referrer = this.sql.exec<{ slug: string }>("SELECT slug FROM database WHERE phone_key = ?", key).toArray()[0]?.slug;// Their own number is the one thing they may be told about: they know it already.if (referrer === friend) return { refused: { status: 400, code: "own_number", message: "That is your own number." } };this.sql.exec("INSERT OR IGNORE INTO inviter_named (friend, at) VALUES (?, ?)", friend, Date.now());if (referrer) awaitthis.refer(friend, referrer);return { ok: {} }; }// ── the counts ─────────────────────────────────────────────────────────/** * One SMS code about to go to `phone` (AUDIT A H2), counted here, or the refusal: the number's day * (SMS_PER_NUMBER_PER_DAY) and every number's day (SMS_PER_DAY, the spend ceiling, alerted at 80% and when reached). */async smsAllowed(phone: string): Promise<Refusal | null> {const now = Date.now();const day = now - 24 * 3_600_000;this.sql.exec("DELETE FROM sms_sent WHERE at < ?", day);const ceiling = /^\d+$/.test(this.env.SMS_PER_DAY ?? "") ? Number(this.env.SMS_PER_DAY) : SMS_PER_DAY;const all = this.sql.exec<{ n: number }>("SELECT count(*) AS n FROM sms_sent").one().n;if (all >= ceiling) { console.error(`cottondb: ALERT sms: the day's ceiling of ${ceiling} codes is reached; no code is sent until the oldest are a day old`);return { status: 503, code: "codes_paused", message: "Codes can't be sent right now; try again later." }; }const k = awaitthis.keyOf(phone);const perNumber = /^\d+$/.test(this.env.SMS_PER_NUMBER_PER_DAY ?? "") ? Number(this.env.SMS_PER_NUMBER_PER_DAY) : SMS_PER_NUMBER_PER_DAY;if (this.sql.exec<{ n: number }>("SELECT count(*) AS n FROM sms_sent WHERE k = ?", k).one().n >= perNumber) return { status: 429, code: "too_many_codes", message: "too many codes for this number today; try again tomorrow" };this.sql.exec("INSERT INTO sms_sent (k, at) VALUES (?, ?)", k, now);if (all + 1 === Math.ceil(ceiling * 0.8)) console.error(`cottondb: ALERT sms: ${all + 1} codes sent in a day, 80% of the ceiling of ${ceiling}`);returnnull; }/** * One sign-in call from `ip`, or the refusal when the hour already holds the attempts limit. Counted by the * address's block (AUDIT A H3: an IPv6 address by its /64, which one machine holds whole). Only a call that reaches * Twilio (`toll`: a code sent or checked) counts toward, and is held by, every network's hour; that is a circuit * breaker far above real use, so no stranger can switch sign-in off with calls that cost nothing. The approval from * another device and passkeys never reach Twilio and are never held by it. */private attempt(ip: string, toll = false): Refusal | null {this.sql.exec("DELETE FROM hit WHERE at < ?", Date.now() - 3_600_000);const block = blockOf(ip);if (this.count(block, "attempt") >= this.limits.attempts) return { status: 429, code: "too_many_attempts", message: "Too many sign-in attempts from this network in the last hour; try again later." };if (toll && this.count(EVERYWHERE, "attempt") >= this.limits.everywhere) { console.error(`cottondb: ALERT sign-in: ${this.limits.everywhere} code sends and checks in an hour across every network; codes held until the hour's oldest fall out`);return { status: 429, code: "too_many_attempts", message: "Too many sign-in attempts in the last hour; try again later." }; }this.hit(block, "attempt");if (toll) this.hit(EVERYWHERE, "attempt");returnnull; }/** * A sign-in call at an object's own door (`/b/<slug>/v1/code`, `/v1/sign-in`, its connect page), counted as one at * the open host's is (ROUTES-AUDIT 7, 23 Nov 2026): the network's hour and every network's together. */async signInGate(ip: string | null): Promise<Refusal | null> {if (ip) returnthis.attempt(ip, true);// No network named (never on Cloudflare, which always says it; a test's own call): every network's hour alone.this.sql.exec("DELETE FROM hit WHERE at < ?", Date.now() - 3_600_000);if (this.count(EVERYWHERE, "attempt") >= this.limits.everywhere) return { status: 429, code: "too_many_attempts", message: "Too many sign-in attempts in the last hour; try again later." };this.hit(EVERYWHERE, "attempt");returnnull; }private count(ip: string, kind: string): number {returnthis.sql.exec<{ n: number }>("SELECT count(*) AS n FROM hit WHERE ip = ? AND kind = ? AND at >= ?", ip, kind, Date.now() - 3_600_000).one().n; }private hit(ip: string, kind: string): void {this.sql.exec("INSERT INTO hit (ip, kind, at) VALUES (?, ?, ?)", ip, kind, Date.now()); }private byKey(key: string): { id: string; slug: string; provisioned: number } | undefined {returnthis.sql.exec<{ id: string; slug: string; provisioned: number }>("SELECT id, slug, provisioned FROM database WHERE phone_key = ?", key).toArray()[0]; }private object(slug: string) {returnthis.env.BUSINESS.get(this.env.BUSINESS.idFromName(slug), { locationHint: REGION }); }}