/** * One business: a Durable Object with its own SQLite, the one front door its * phones, website and scripts come through. * * ROLES ARE DECIDED HERE AND NOWHERE ELSE (owner, 24 Oct 2026): public, * member, staff, owner. A member reads public rows and their own; staff and * the owner read everything; writes are acts, and an act checks the role * before it touches a row. The object decides everything; the phone decides * nothing. */ import { type AlarmWatch, alarmStale } from "./alarm_watch.ts"; import * as blindIndex from "./blind.ts"; import { DurableObject } from "cloudflare:workers"; import { definitionAct } from "./definition_writes.ts"; import { fail, ToolFailure } from "./mcp/context.ts"; import { ACTS, isAct, type ActName } from "./acts.ts"; import * as allowlist from "./allowlist.ts"; import { changeWindow, Journal, MACHINE_WRITERS, trimActs, trimChanges } from "./changes.ts"; import { dataRoute } from "./data_routes.ts"; import * as recurrence from "./recurrence.ts"; import { CREDENTIAL_TTL_SECONDS, grant, issueCode, proveCode, provenAlready, whoIs, type Who } from "./auth.ts"; import * as passkey from "./passkey.ts"; import { Asks, BYTES32, type Ask, type AskState, type Refusal as ApprovalRefusal } from "./approval.ts"; import { definitionProblem, Definitions, etagOf, parseTable, tableProblem, type TableDef } from "./definitions.ts"; import { ruled, sealedSetProblem, toolSealProblem, BLIND_PER_QUERY, blindArg, blindBudget, blindToken, checkSealFields, clearSealed, isSealedColumn, isSealedRow, scrubData, SEAL_FIELDS, sealedColumns } from "./seal.ts"; import { Engine, recordActs, settled, toolRules, type Clock, type Outcome, type RecordAct } from "./engine.ts"; import { devWorker, isProduction, keyDefault, type Env } from "./env.ts"; import { ALARM_BUSY_HEADER, ALARM_RUNNING_HEADER, answerRefusal, BEFORE_HEADER, BEGAN_HEADER, bearer, COLD_HEADER, integer, isAdminToken, json, object, optionalText, randomToken, readJson, refuse, Refused, sha256Hex, text } from "./http.ts"; import { directory } from "./directory.ts"; import { changeIds, type ChangeTrail, type McpCaller, type Sibling, type ToolContext, type Writer } from "./mcp/context.ts"; import { McpServer, unauthorized } from "./mcp/server.ts"; import { say as sayUnlock, windowFor } from "./mcp/tools/window.ts"; import { NOT_EMPTIED_BY_AN_ASSISTANT } from "./mcp/tools/records/bin.ts"; import { resolveTable } from "./mcp/tools/records/table.ts"; import { arrivalPublic, asArrived, sealsAtArrival } from "./arrival_file.ts"; import { admitStream, bucketFolder, bucketKey, crossOrigin, deleteFolder, deleteMedia, drawBytes, drawMedia, dropKey, finishParts, getMedia, isSealedType, kitPicture, mediaBytes, mintStream, missingMedia, putMedia, putPart, SEALED_FILE_TYPE, startParts, storeMedia, storeStream, streamMedia, streamPreflight, type MediaBudget } from "./media.ts"; import { challenge, type Clients, directoryClients, handleOAuth, OAUTH_PATH, PREFIX_HEADER, REFRESHES as OAUTH_REFRESH_TABLE, storeClients, throughDoor, type OAuthHost } from "./oauth.ts"; import { HANDLERS } from "./mcp/tools/index.ts"; import { KITS, PERSONAL } from "./kits.ts"; import * as space from "./space.ts"; import * as plans from "./plans.ts"; import * as confirm from "./connect_confirm.ts"; import { applyChanges, newApplied, type Applied } from "./import/apply.ts"; import { callChanges, callsProblem, type DeviceCall } from "./import/calls.ts"; import { batchProblem, type ImportBatch } from "./import/envelope.ts"; import { EngineRefusal } from "./import/driver.ts"; import { changesProblem, planImport, planMessageChanges, planReplyLinks, type MessageChange } from "./import/messages.ts"; import { originalKeyOf, PhotoReader, photosProblem, planPhotos, type PhotoWork } from "./import/photos.ts"; import { Reader } from "./import/reader.ts"; import { droppedSince, exportDiffers, keepPrompts, PROMPT_DAYS, PROMPTS_KEPT, runErase, tableDropUnderWay, type EraseHost } from "./erase.ts"; import { prunePhotos } from "./photo_prune.ts"; import { addDays, localDate, normalizePhone, RETIRED_TABLES, retiredRefusal, type ActAnswer, type BusinessMeta, type DefinitionsAnswer, type Role, type HeldAnswer, type SignInAnswer, type SyncAnswer } from "./protocol.ts"; import * as spacePerson from "./space/person.ts"; import { spaceObject } from "./space/space.ts"; import { spacesOn } from "./space/switch.ts"; import { STEP_KINDS } from "./jobs/step_job.ts"; import { DEV_INDEX_TOO_BIG, ERASED_KEY, SCHEMA, Store, wire, wirePerson, type Cursor, type FirstAt, type FirstPlan, type FirstSpec, type Person, type Stamps, type StoredRow, type SyncScope, type SyncWindow } from "./store.ts"; import { callerOf, checkMachine, checkScopes, mintSecret, TOKEN_TABLE } from "./tokens.ts"; import * as fan from "./fan.ts"; import * as google from "./google.ts"; import * as calendar from "./google_calendar.ts"; import * as googleWrite from "./google_write.ts"; import * as invite from "./invite.ts"; import * as spotify from "./spotify.ts"; import * as calendarEngine from "./calendar_engine.ts"; import * as artwork from "./artwork.ts"; import * as books from "./books.ts"; import * as bookFile from "./book_file.ts"; import * as classify from "./classify.ts"; import * as kitKeep from "./kit_keep.ts"; import * as retired from "./retired.ts"; import * as fetches from "./fetch.ts"; import * as films from "./films.ts"; import * as meetings from "./meetings.ts"; import { faceProblem } from "./faces.ts"; import * as owner from "./owner.ts"; import * as syncStatus from "./sync_status.ts"; import * as vault from "./vault.ts"; import * as unlock from "./window.ts"; import * as agent from "./agent.ts"; import * as migration from "./seal_migration.ts"; import * as personMerge from "./person_merge.ts"; import * as sealWide from "./seal_wide.ts"; import * as memoryLock from "./memory_lock.ts"; import * as openTablesLock from "./open_tables_lock.ts"; import { isDeviceSealedKind, kindOfKey, tableOfFileKind } from "./table_files.ts"; import * as tokenScopes from "./token_scopes.ts"; import * as restoreOwner from "./restore_owner.ts"; import * as adminDoor from "./admin_door.ts"; import * as keyAllow from "./key_allow.ts"; import * as rowWitness from "./row_witness.ts"; import { vaultKeyCheck, type VaultKeyReport } from "./vault_key_check.ts"; import * as ownerAsks from "./owner_asks.ts"; import { Apply, Capture, RollBack, sealNoted } from "./arrival_seam.ts"; import { ARRIVAL_ROW, isArrivalValue, keyFromText } from "./arrival.ts"; import * as calling from "./calling/calls.ts"; import * as chat from "./chat/chat.ts"; import * as agentChats from "./chat/agents.ts"; import * as send from "./send/send.ts"; import * as mail from "./mail/mail.ts"; import * as mailDns from "./mail/dns.ts"; import * as mailSend from "./mail/send.ts"; import { approvalAlert, mailAlert, recoveryAlert } from "./chat/push.ts"; import * as shared from "./send/shared.ts"; import * as secrets from "./send/secrets.ts"; import * as mailFetch from "./mail/fetch.ts"; import * as mailFetcher from "./mail/fetcher.ts"; import * as mailJob from "./mail/fetch_job.ts"; import * as stepJobs from "./step_jobs.ts"; import type { StepJobMessage, StepKind } from "./jobs/step_job.ts"; import type { MailJobMessage } from "./jobs/mail_job.ts"; import * as mailActs from "./mail/acts.ts"; import * as imap from "./mail/imap.ts"; import * as recovery from "./recovery.ts"; import * as circle from "./recovery_circle.ts"; import * as vaultIdentity from "./vault_identity.ts"; import * as feedback from "./feedback.ts"; import * as accountDelete from "./account_delete.ts"; import * as restore from "./restore.ts"; import * as neverAgain from "./never_again.ts"; import * as handover from "./handover.ts"; import * as snapshots from "./snapshots.ts"; import { deletePrefix } from "./account_delete.ts"; import { unpack as unpackTokens } from "./blind.ts"; import { planFirst } from "./first.ts"; import type { StopReason } from "./calling/room.ts"; const MCP = new McpServer(HANDLERS); /** The kit this Worker ships (src/kit_keep.ts): every personal object is made from it and kept to it. */ /** The personal kit as an object keeps it: its tables as the seal rule makes them (src/seal.ts `ruled`), as a personal object reads its own (Store.definitions). */ // A table or tool held as retired is never laid or given, though the kit still lists it until its definition leaves the tree (TABLE DROP 1). const SERVED_PERSONAL = retired.served(PERSONAL); const RULED_PERSONAL = { ...SERVED_PERSONAL, tables: SERVED_PERSONAL.tables.map(ruled) }; const KIT: kitKeep.Kit = { own: PERSONAL.own, tools: SERVED_PERSONAL.tools, boards: PERSONAL.boards, tables: RULED_PERSONAL.tables, shell: KITS.shell!.boards.map((board) => String(board.id)) }; /** What one object may hold (owner, 26 Oct 2026): its SQLite file, and its media in R2. */ /** The kinds a device seals now that the bucket may still hold plain (`GET /v1/media-plain`): kept chat pictures, sealed since 22 Nov 2026. */ const MEDIA_PLAIN_KINDS = ["messages", "people"]; /** * Per kind a device may say it opens sealed (`opens=messages,people`): the table whose pull reads that kind's files, * where it is noted (messages keeps its table from 22 Nov 2026), and from when devices began to say it. */ const MEDIA_OPENS_KINDS: Record = { messages: { table: "message", noted: "media_opens", since: "2026-11-22T00:00:00.000Z" }, // AVATAR SEAL (MEDIA SEAL FINDINGS (1), 27 Nov 2026): a person's picture, sealed under TFR(person). people: { table: "person", noted: "media_opens_people", since: "2026-11-27T00:00:00.000Z" }, }; const mediaOpensSchema = (noted: string): string => `CREATE TABLE IF NOT EXISTS ${noted} (device_id TEXT PRIMARY KEY, name TEXT NOT NULL, reads INTEGER NOT NULL, opens INTEGER NOT NULL, seen_at TEXT NOT NULL)`; /** A device not seen this long no longer holds a reseal back. */ const MEDIA_OPENS_RECENT_MS = 30 * 86_400_000; /** * The database file's own limit (coordinator, 22 Nov 2026): 9.5 GB, under Cloudflare's hard 10 GB per SQLite * Durable Object, past which every write fails with SQLITE_FULL. The guard stays so a full database refuses a * write in plain words (object_full) and nothing new is lost silently; 9.5e9 is under 10 GB however it is counted. */ export const DATABASE_CAP_BYTES = 9_500_000_000; /** From this fraction of its cap a database says it is filling up: storage_summary's `warning`, the sync answer's `room`. */ export const DATABASE_WARN_FRACTION = 0.8; export const MEDIA_CAP_BYTES = 50 * 1024 ** 3; /** The media bytes an object holds, counted on every PUT (and recounted by the admin). */ const MEDIA_BYTES = "media_bytes"; /** An account's own media limit in bytes (owner, 18 Nov 2026), set by `POST /v1/admin/media/cap`; absent, the limit is the default. */ const MEDIA_CAP = "media_cap"; /** The most an account's own media limit may be. */ const MEDIA_CAP_MOST_BYTES = 8 * 1024 ** 4; /** The table each device publishes its vault key in, and the wrap of the vault master key for it. */ const VAULT_KEY_TABLE = "vault_key"; /** The table that holds the data key's wrap (`dk`) and each sealed table's seal version (`v:`), sealing plan §2.1, §3.2 step 8. */ const SEAL_KEY_TABLE = "seal_key"; /** `seal_key`'s row of the data key's wrap. */ const SEAL_KEY_DK = "dk"; /** `seal_key`'s row id prefix of a sealed table's seal version. */ const SEAL_KEY_VERSION = "v:"; /** The slug the Worker resolved travels on this header. */ export const SLUG_HEADER = "x-cotton-business"; /** A film's stream URL inside an object: `/v1/stream//` (src/media.ts). */ export const STREAM_PATH = /^\/v1\/stream\/([^/]+)\/(.+)$/; /** A path's route family, its plain words only (`/v1/sync`, `/v1/admin/open-tables-lock`): never an id, a key or a token. */ export function routeFamily(path: string): string { const words: string[] = []; for (const segment of path.split("/").filter(Boolean)) { if (!(/^[a-z][a-z_-]{0,39}$/.test(segment) || /^v[0-9]{1,2}$/.test(segment)) || words.length >= 4) break; words.push(segment); } return `/${words.join("/")}`; } /** Messages between a person and the business: a built-in table every business has. */ const MESSAGE_TABLE: Record = { format_version: 1, id: "business_message", name: "Message", plural: "Messages", builtin: true, visibility: "mine(person)", date: "at", columns: [ { key: "name", label: "Message", type: "text", required: true }, { key: "person", label: "Person", type: "link", link_to: "person", required: true }, { key: "from", label: "From", type: "choice", choices: ["member", "staff"], required: true }, { key: "text", label: "Text", type: "longtext", required: true }, { key: "about", label: "About", type: "text" }, { key: "at", label: "At", type: "date", required: true }, ], instructions: "One row per message between a member and the business, newest last. A member sees only their own.", }; interface Caller { role: Role; person: Person | null; admin: boolean; who: Who | null; /** The Cotton MCP token acting, when one is: the change log's actor. */ tokenId?: string; /** What a statement reading records as its reader: the token's name. */ readBy?: string; /** The bearer a Cotton MCP token presented, held for this request alone: a mint by it carries its member to the new token (src/agent.ts). */ presented?: agent.Presented; /** A Cotton MCP token that is an OAuth connector's (it carries a refresh row): with token scopes on it speaks at /mcp alone (src/token_scopes.ts). */ connector?: boolean; /** An act asked from inside an MCP tool (`ctx.act`), not at /v1/act: token scopes' device rule does not apply to it. */ viaMcp?: boolean; /** What the token may read, write and do outside (src/key_allow.ts); null, a key made before allows. */ allow?: keyAllow.Allow | null; } /** How often the object's alarm comes round: the change log's trim. */ const ALARM_EVERY_MS = 60 * 60 * 1000; /** AUDIT F: a database prepared when its number asked for a code, its kit not laid yet (laid at the first proved code). */ const KIT_PENDING = "kit_pending"; /** ALARM DEAD: an alarm this far past stands where the platform stopped retrying it; a request sets it again. */ const ALARM_DEAD_MS = 60_000; /** ALARM DEAD: a dead alarm set again comes this soon. */ const ALARM_REVIVE_MS = 5_000; /** ALARM DEAD: the next alarm the handler sets before any work, in case the work never reaches its own. */ const ALARM_FALLBACK_MS = 60_000; /** After a failed copy of the never-again ledger, background copies wait this long; the alarm tries regardless. */ const LEDGER_BACKOFF_MS = 5 * 60 * 1000; /** Set while an alarm runs (LIVE CPU 3); found at start-up, it names an alarm the platform reset. */ const ALARM_RUNNING = "alarm_running"; /** JOBS OUT 4: when the alarm's last pass began and ended (ISO), for the Worker's dead-man check. */ const ALARM_LAST_BEGAN = "alarm_last_began"; const ALARM_LAST_ENDED = "alarm_last_ended"; /** * LIVE CPU 4: the request-side mark. A request that may carry much work (an act whose args hold REQUEST_MARK_ROWS * items or more, an import, a pass page) is marked under its own key, the mark made durable, before its work; a * start that finds marks logs each (the requests in flight when the object was reset) and clears them. */ /** The route families only a signed-in device reaches: to a caller with no credential, as where no database is, "sign in first". */ /** The Circle's routes and the shares that ride it: never an assistant's token's (CIRCLE GAPS 1). */ export const CIRCLE_FAMILIES = /^\/v1\/(chat|invite|send|shared)(\/|$)/; const SIGNED_FAMILIES = /^\/v1\/(recovery|approvals|passkeys|chat|invite|send|shared|agents|calls)(\/|$)/; const REQUEST_RUNNING = "request_running:"; export const REQUEST_MARK_ROWS = 100; /** JOBS OUT C3: the alarm's bounded jobs that are the storage counting, run by the `storage_count` step job when it is on. */ const STORAGE_COUNT = ["measure", "recount"]; /** The row counts' recount steps one alarm takes, each of `Store.recountChunk` rows in its own transaction. */ /** MEASURE GENTLE: the recount's steps an alarm, each 500 rows read for a date out of their JSON (was 4). */ const RECOUNT_STEPS = 1; /** * MEASURE GENTLE (coordinator for the owner, 26 Nov 2026: on live his object answered every request in 1.7 to 7.5 s, * behind the measure's alarm a second). The bounded jobs an alarm carries on (the measure, the recount, the logs' * trims, the prompts' keep, an order shadow, an order index) wait GENTLE_WAIT_MS between alarms, and BUSY_WAIT_MS * while the object is in use: a request in the last BUSY_FOR_MS, or a phone's pull (a /v1/sync page served then). * Each step is held to about 50 ms of work, counted by what it reads (a Worker's clock stands still through * synchronous work): the measure by its own units (src/storage_measure.ts); the recount by one step of 500 rows (on * the test pool, 4 such steps of mail rows took 0.25 s beside the old measure: one is about 60 ms); the others by the * rows and bytes below, sized as the measure's are (a mail-sized row, about 5,800 bytes, about 18 µs to read). */ const GENTLE_WAIT_MS = 5_000; const BUSY_WAIT_MS = 60_000; const BUSY_FOR_MS = 30_000; /** The change log's trim: entries, and characters of before and after, a step (15 MB, about 50 ms of reading). */ const GENTLE_TRIM = { most: 2_000, chars: 15_000_000 }; /** The act log's trim: lines a step (each up to 4,000 characters). */ const GENTLE_ACTS = 2_500; /** The prompts' keep: prompts a step. */ const GENTLE_PROMPTS = 500; /** An order shadow's filling: rows a step (each read for its value, about 18 µs a mail row). */ const GENTLE_SHADOW_ROWS = 2_500; /** READ COST 4: while the object is in use, a shadow's next fill step comes this long after the last (about 50 ms each). */ const SHADOW_BUSY_MS = 10_000; /** A business's public photos (ROUTES-AUDIT 15): how many an hour, and how many bytes in all. */ const PHOTOS_PER_HOUR = 60; /** AUDIT C 5: the requests one key makes a minute; an object's `key_calls_per_minute` meta sets its own. */ export const KEY_CALLS_PER_MINUTE = 300; const PHOTOS_HELD_BYTES = 2 * 1024 ** 3; const PHOTOS_HOUR = "photos_hour"; const PHOTOS_BYTES = "photos_bytes"; /** Whether a picture's first bytes are its type's. */ function looksLike(head: Uint8Array, type: string): boolean { const at = (offset: number, ...b: number[]) => b.every((x, i) => head[offset + i] === x); const text = (offset: number, s: string) => at(offset, ...[...s].map((c) => c.charCodeAt(0))); switch (type) { case "image/jpeg": return at(0, 0xff, 0xd8, 0xff); case "image/png": return at(0, 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a); case "image/gif": return text(0, "GIF8"); case "image/webp": return text(0, "RIFF") && text(8, "WEBP"); case "image/heic": return text(4, "ftyp"); default: return false; } } /** What the old message and call import routes write (src/import): any of them sealed refuses those routes. */ const CLEAR_IMPORT_TABLES = ["thread", "thread_member", "message", "message_contact", "message_contact_handle", "message_reaction", "call", "person", "person_handle"]; /** A restore from snapshots under way (meta `snapshot_restore`): every part checked first, then laid (M7). */ type SnapshotRestore = { phase: "verify" | "lay"; plan: { kind: "full" | "daily"; stamp: string; prefix: string; parts: { key: string; rows: number; bytes: number; sha256: string }[] }[]; i: number; j: number; version_before: number; max_version: number; restored_to: string; rows: number; checked: number; tables: string[]; }; /** The most R2 folders one media_drop step drops (JOBS OUT M1). */ const MEDIA_DROP_STEP = 10; /** The step-job kinds that are the alarm's sweeps (JOBS OUT W1..): no cheap "is there work", so a run that finds none rests them. */ const SWEEPS = new Set(["changes", "acts", "prompts", "sweeps"]); export class Business extends DurableObject { private readonly store: Store; /** The unlock windows this object holds (src/window.ts): their keys in memory, read back from window_secret after an eviction. */ private readonly unlocks = new unlock.Windows(); /** Your Claude's standing grant (src/agent.ts): members, carriers and wraps; no key is held between calls. */ private readonly agents = new agent.Agents(); /** Each request's signed-in device, once known: the one phone a write's "rows" frame is not sent to (src/chat/chat.ts rowsMoved). */ private readonly writers = new WeakMap(); /** The rows frames' window, phone by phone (src/chat/chat.ts rowsMoved). */ private readonly rows = chat.rowsNotice(); private slug = ""; /** Dev only: where an erase asked with `kill_after` cuts the object off once (src/account_delete.ts `killPoint`). */ private killAt: accountDelete.KillPoint | null = null; /** The caps this object holds to; a test lowers them in place through runInDurableObject. */ readonly caps = { database: DATABASE_CAP_BYTES, media: MEDIA_CAP_BYTES }; constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); this.store = new Store(this.ctx.storage.sql, () => new Date()); // A deleted account's object holds its receipt alone: no table is made again (src/account_delete.ts). if (accountDelete.erased(this.ctx.storage.sql)) return; this.ctx.storage.sql.exec(SCHEMA); // LIVE CPU 3: an alarm the platform reset for its CPU never reaches its end, nor its own log line; its mark says so here. const reset = this.store.meta(ALARM_RUNNING); if (reset) { console.error(`cottondb: ${this.store.meta("slug") ?? "-"} was reset inside an alarm begun ${reset}`); this.store.setMeta(ALARM_RUNNING, null); // The bell: a shadow filling when it happened takes half the rows a step from now on. const halved = this.store.shadowReset(); if (halved !== null) console.error(`cottondb: order shadow steps now ${halved} rows`); } const marks = this.ctx.storage.sql.exec<{ key: string; value: string }>("SELECT key, value FROM meta WHERE key >= ? AND key < ?", REQUEST_RUNNING, `${REQUEST_RUNNING}\uffff`).toArray(); for (const m of marks) { console.error(`cottondb: ${this.store.meta("slug") ?? "-"} was reset inside a request: ${m.value}`); this.store.setMeta(m.key, null); } blindIndex.ready(this.ctx.storage.sql); this.ctx.storage.sql.exec(allowlist.SCHEMA); this.ctx.storage.sql.exec(recovery.SCHEMA); recovery.migrate(this.ctx.storage.sql); circle.migrate(this.ctx.storage.sql); this.ctx.storage.sql.exec(circle.SCHEMA); this.ctx.storage.sql.exec(vaultIdentity.SCHEMA); this.ctx.storage.sql.exec(shared.SCHEMA); this.ctx.storage.sql.exec(spacePerson.SCHEMA); spacePerson.upgrade(this.ctx.storage.sql); this.ctx.storage.sql.exec(unlock.SCHEMA); this.ctx.storage.sql.exec(agent.SCHEMA); this.ctx.storage.sql.exec(memoryLock.SCHEMA); this.ctx.storage.sql.exec(openTablesLock.SCHEMA); this.ctx.storage.sql.exec(tokenScopes.SCHEMA); this.ctx.storage.sql.exec(ownerAsks.SCHEMA); unlock.migrate(this.ctx.storage.sql); this.ctx.storage.sql.exec(migration.SCHEMA); this.ctx.storage.sql.exec(sealWide.SCHEMA); this.ctx.storage.sql.exec(personMerge.SCHEMA); sealWide.seed(this.ctx.storage.sql, new Date().toISOString()); this.ctx.storage.sql.exec(calling.SCHEMA); calling.migrate(this.ctx.storage.sql); chat.ready(this.ctx.storage.sql); this.ctx.storage.sql.exec(send.SCHEMA); this.ctx.storage.sql.exec(invite.SCHEMA); this.ctx.storage.sql.exec(secrets.SCHEMA); this.ctx.storage.sql.exec(mail.SCHEMA); mail.migrate(this.ctx.storage.sql); this.ctx.storage.sql.exec(mailFetch.SCHEMA); this.ctx.storage.sql.exec(mailJob.SCHEMA); this.ctx.storage.sql.exec(stepJobs.SCHEMA); stepJobs.ensureColumns(this.ctx.storage.sql); mailJob.ensureColumns(this.ctx.storage.sql); mailFetch.ensureColumns(this.ctx.storage.sql); this.ctx.storage.sql.exec(feedback.SCHEMA); // RESTORE AUDIT 2: once, every token and device row standing now is adopted as its witness (src/row_witness.ts). rowWitness.adopt(this.ctx.storage.sql, new Date().toISOString(), { get: (k) => this.store.meta(k), set: (k, v) => this.store.setMeta(k, v) }); } /** SLOW READ: whether this instance has answered before (its first answer after a start is a cold one). */ private served = false; /** RESTORE 2: what outlives a restore (src/restore.ts), read once per instance; replaced when a restore route changes it. */ private restoreMarker: Promise | null = null; /** SLOW READ: the bounded jobs the last alarm left with more to do (`more` in alarmPass), "" for none. */ private alarmBusy = ""; /** MEASURE GENTLE: when this instance last took a request, and last served a pull's page (0: not since it started). */ private lastRequestAt = 0; /** JOBS OUT C3: when this instance last took a request that was not a job's call at its door. */ private lastUseAt = 0; private lastPullAt = 0; /** * MEASURE GENTLE 2 (coordinator, 26 Nov 2026): each alarm user's own want, kept here so the next alarm is decided in * one place (the earliest over all wants) and a job that asked for later does nothing when another's want brings the * alarm early. `gentle`: the bounded jobs (one shared want); the others by name. In memory only: a restart runs each * once at its first alarm, which is what it would have done. */ private wants = new Map(); /** The bounded jobs the last alarm that ran them left with more to do, and whose turn is next while in use. */ private gentleOwed: string[] = []; /** LIVE SLOW 2: the bounded jobs the last alarm ran (said as what a request came after). */ private alarmRan = ""; private gentleTurn = 0; /** Tests: the alarm keeps every want and turn as live does (default off in the test Worker, so a test's back-to-back alarms each do their work). */ gentleInTests = false; /** Whether wants and turns apply: always on a real Worker; in the test Worker only when a test asks. */ private paced(): boolean { return this.env.ENV_LABEL !== "test" || this.gentleInTests; } /** Is it `name`'s time (no want kept, or its want reached)? */ private due(name: string, now: number): boolean { if (!this.paced()) return true; const at = this.wants.get(name); return at === undefined || now >= at; } /** MEASURE GENTLE: is the object in use (a request, or a phone's pull, in the last BUSY_FOR_MS)? */ private inUse(now = Date.now()): boolean { return now - this.lastRequestAt < BUSY_FOR_MS || now - this.lastPullAt < BUSY_FOR_MS; } /** LIVE SLOW 2: what this instance did last (a request's route family, or the alarm and its bounded jobs), and when it ended. */ private lastEvent = ""; private lastEventEnded = 0; override async fetch(request: Request): Promise { // LIVE SLOW 2: the object's clock as it begins this request (a Worker's clock moves at each event and I/O), and // what it did just before: the front Worker works out how long the request waited in the object's queue. const began = Date.now(); const before = this.lastEvent ? `${this.lastEvent} ${Math.max(0, began - this.lastEventEnded)} ms ago` : ""; // SLOW READ (26 Nov 2026): what the front Worker needs to say why an answer was slow (src/http.ts `toldSlow`): // a cold instance, an alarm under way when the request arrived, and what the last alarm still had to do. const cold = !this.served; this.served = true; this.lastRequestAt = Date.now(); // JOBS OUT C3: a job's own call at its door is not the object in use (a step job paces itself by real use). if (!new URL(request.url).pathname.includes("/v1/jobs/")) this.lastUseAt = this.lastRequestAt; let alarmSince: string | null = null; try { alarmSince = this.store.meta(ALARM_RUNNING); } catch { // An erased object keeps no meta. } const answer = await this.answer(request); // TRUSTED RECOVERY BUILD 2 (H1): once per wake, and after every call to a way back in, the directory hears where // this account's ways back in stand (counts only), so the owner knows when the earlier flow can go. if (cold || new URL(request.url).pathname.startsWith("/v1/recovery")) { this.ctx.waitUntil(this.reportRecoveryFlow().catch(() => undefined)); // Tellings a Remove or Block owed other objects, and pieces held for people whose account is gone (BUILD 3, LOW). this.ctx.waitUntil(this.recoveryChores().catch(() => undefined)); } // Whatever this request noted in the never-again ledger (an erase, a revoke, a deletion set or kept) is copied out // now, on every path (an answer refused or 410 too); a failed copy never fails the request (src/never_again.ts). // In the background (RESTORE 2 SERVER 4, L1): a person's write never waits on R2, and after a failed copy the next // requests do not try again for a while (the alarm does). if (request.method !== "GET" && request.method !== "HEAD" && neverAgain.waiting(this.ctx.storage.sql)) this.ctx.waitUntil(this.flushNeverAgain("background")); if (request.method === "GET" && new URL(request.url).pathname === "/v1/sync") this.lastPullAt = Date.now(); this.lastEvent = `${request.method} ${routeFamily(new URL(request.url).pathname)}`; this.lastEventEnded = Date.now(); try { answer.headers.set(BEGAN_HEADER, String(began)); if (before) answer.headers.set(BEFORE_HEADER, before); if (cold) answer.headers.set(COLD_HEADER, "1"); if (alarmSince) answer.headers.set(ALARM_RUNNING_HEADER, String(Math.max(0, Math.round((Date.now() - Date.parse(alarmSince)) / 1000)))); if (this.alarmBusy) answer.headers.set(ALARM_BUSY_HEADER, this.alarmBusy); } catch { // An answer whose headers cannot change (a socket's) goes as it is. } // The commit this object runs, on every answer: since 30 Oct 2026 a busy object keeps its old code up to 300 s after // a deploy, and the Worker deploy waits until the owner's says the new one. try { answer.headers.set("cotton-object-build", this.env.BUILD_SHA ?? "unnamed"); } catch { // An answer whose headers cannot change (a socket's) goes as it is. } return answer; } private async answer(request: Request): Promise { try { // RESTORE 2 (src/restore.ts): the restore routes, ahead of every other door; a frozen account answers nobody else. const restoring = await this.restoreDoor(request); if (restoring) return restoring; // The person deleted this account: every request is told so, and nothing of the object runs (src/account_delete.ts). const deleted = accountDelete.job(this.ctx.storage.sql); if (deleted?.phase === "keeping") { // A Keep cut off before it finished (DELETE ACCOUNT 2): finished now, and the request answered as on any live // account; while it cannot finish, said so plainly (the object's own alarm keeps trying). try { await accountDelete.keep(this.deleteHost()); } catch (error) { console.error("cottondb: account delete: finishing a Keep failed; its alarm tries again", error instanceof Error ? error.message : "unknown"); await accountDelete.ensureAlarm(this.deleteHost()); return json({ code: "keeping", message: "Your account is being kept; try again in a moment." }, 503); } if (request.method === "POST" && new URL(request.url).pathname === "/v1/account/keep") return json({ kept: true }); } else if (deleted) { // Its alarm made sure of on every request (DELETE ACCOUNT 1): one the platform gave up on is set again. await accountDelete.ensureAlarm(this.deleteHost()); return (deleted.phase === "pending" ? await this.whileDeleting(request, deleted) : null) ?? accountDelete.deletedAnswer(deleted); } this.slug = request.headers.get(SLUG_HEADER) ?? this.store.meta("slug") ?? ""; // A film's files, fetched by the player with the URL's token alone: nothing else of the object runs for them. if (STREAM_PATH.test(new URL(request.url).pathname)) return await this.stream(request); // A chat socket, opened with the ticket this object minted: no credential of the device's is read (src/chat/chat.ts). if (request.method === "GET" && new URL(request.url).pathname === chat.SOCKET_PATH && this.personal()) return await chat.openSocket(this.chatHost(), request); const before = this.store.version(); // Frozen for a restore (only the admin is let in): the object's own upkeep waits, it writes nothing (M1). const kitMerged = this.store.frozen ? false : this.keepKit(); // A film sends thousands of files and this object answers one request at a time: a file's request never needs the owner's person, whose linking reads every definition until it is done. if (!this.store.frozen && !new URL(request.url).pathname.startsWith("/v1/media/")) await this.keepOwner(); const answer = await this.route(request); // Rows moved: the person's other open phones are told now, so each pulls at once instead of at its next minute (src/chat/chat.ts rowsMoved). if (this.personal() && this.store.version() > before) chat.rowsMoved(this.chatHost(), this.rows, this.writers.get(request) ?? null, this.store.version()); await this.dropMedia(); await this.keepAlarm(); // Row counts being counted again go on at the alarm, never all in one request (src/store.ts). if (this.store.countsPending()) await this.carryOn(); // An index a read asked for is made by the alarm, soon, never in a request (Store.firstIndexes, selectOrdered); a // shadow still filling is filled by it too (READ COST 4: asked on live, the alarm stayed an hour away). await this.shadowsOwed(); // An event laid or changed, or a kit just brought, sets the calendar engine going, off this request. if (this.personal() && (kitMerged || calendarEngine.touched(this.store, before))) this.kickCalendar(); // A book or a film laid or changed sets the artwork engine going, off this request, as the classifier is. if (this.personal() && (kitMerged || artwork.touched(this.store, before))) this.kickArtwork(); // A book laid or changed has its EPUB read for the columns it leaves empty, off this request (src/book_file.ts). if (this.personal() && bookFile.touched(this.store, before)) this.kickBookFiles(); return answer; } catch (error) { return answerRefusal(error); } } // ── RESTORE 2 (src/restore.ts) ───────────────────────────────────────── /** The account's generation, made the first time it is asked, and the moment a restore put it back to, if one did. */ private generationFields(): { generation: string; restored_to?: string } { let generation = this.store.meta(restore.GENERATION); if (!generation) { generation = restore.freshGeneration(); this.store.setMeta(restore.GENERATION, generation); } const restoredTo = this.store.meta(restore.RESTORED_TO); return restoredTo ? { generation, restored_to: restoredTo } : { generation }; } /** The slug a request names (the front Worker sets it), else the one this object keeps. */ private slugOf(request: Request): string { const said = request.headers.get(SLUG_HEADER); if (said) return said; try { return this.store.meta("slug") ?? ""; } catch { return ""; } } /** This object's slug, from the request it is answering or from its meta (an alarm or a call from another object). */ private ownSlug(): string { if (this.slug) return this.slug; try { return this.store.meta("slug") ?? ""; } catch { return ""; } } /** * What outlives a restore. Where the restore routes are off (live) it is never read: no cost, no failure. Where they * are on it is read once per instance; a read that fails is never kept and never taken as frozen: it throws, and is * read again next time (RESTORE 2 SERVER 2, H1). */ private async marker(slug?: string): Promise { if (!restore.restoreRoutesOn(this.env)) return null; const named = slug || this.ownSlug(); if (!named) return null; if (!this.restoreMarker) { const reading = restore.readMarker(this.env.PHOTOS, named); this.restoreMarker = reading; reading.catch(() => { if (this.restoreMarker === reading) this.restoreMarker = null; }); } const marker = await this.restoreMarker; this.store.frozen = marker?.frozen === true; return marker; } private async setMarker(slug: string, marker: restore.Marker | null): Promise { await restore.writeMarker(this.env.PHOTOS, slug, marker); const kept = marker && (marker.frozen || marker.pending) ? marker : null; this.restoreMarker = Promise.resolve(kept); this.store.frozen = kept?.frozen === true; } /** * THE ONE GATE (RESTORE 2 SERVER 2, M1): every way into this object but a phone's request (which `restoreDoor` * answers) begins here: a call from another object, a socket's message, a pass the alarm or another object starts. * Frozen, or unable to say, it throws, so the caller hears "not delivered" and never "delivered". On live it returns * at once, reading nothing. `Store.bump` refuses any row write while frozen too, for work already under way. * `test/restore-gate.test.ts` fails when a new entry point does not begin with it. */ private async frozenGate(): Promise { if (!restore.restoreRoutesOn(this.env)) return; let marker: restore.Marker | null; try { marker = await this.marker(); } catch { throw new Error(`${restore.FROZEN_CALL}: this account could not say whether it is frozen; not delivered, try again`); } if (marker?.frozen) throw new Error(`${restore.FROZEN_CALL}: this account is frozen for a restore; not delivered, try again`); } /** * The ledger's outbox copied to R2 (src/never_again.ts): after a request (in the background), on the alarm, before a * restore. A background copy after a failed one waits `LEDGER_BACKOFF_MS` (RESTORE 2 SERVER 4, L1); the alarm and a * restore always try. Never once the account's erase is under way (past pending or keeping, L2): the files step has * erased `_restore//`, and a copy then would leave a file nothing erases. */ private flushNeverAgain(why: "background" | "now" = "now"): Promise { return this.ledgerTurn(async () => { if (why === "background" && Date.now() - this.ledgerFailedAt < LEDGER_BACKOFF_MS) return; if (!neverAgain.waiting(this.ctx.storage.sql)) return; if (!this.ledgerMayCopy()) return; const slug = this.ownSlug(); if (!slug) return; try { const chunks = await neverAgain.flush(this.env.PHOTOS, slug, this.ctx.storage.sql, () => this.ledgerMayCopy()); if (chunks > 0) this.store.setMetaQuiet(neverAgain.CHUNKS, String(Number(this.store.meta(neverAgain.CHUNKS) ?? "0") + chunks)); this.ledgerFailedAt = 0; } catch (error) { this.ledgerFailedAt = Date.now(); console.error(`cottondb: never-again ${slug}: not copied out yet (${error instanceof Error ? error.message : String(error)}); tried again in ${LEDGER_BACKOFF_MS / 60_000} minutes`); // An idle object gets its ledger copied too (RESTORE 2 SERVER 5): the alarm is set for the back-off's end. const due = this.ledgerFailedAt + LEDGER_BACKOFF_MS; const set = await this.ctx.storage.getAlarm(); if (set === null || set > due) await this.ctx.storage.setAlarm(due); } }); } /** Whether the ledger may be copied out now: never once the account's erase is under way (past pending or keeping, L2). */ private ledgerMayCopy(): boolean { const deleting = accountDelete.job(this.ctx.storage.sql); return !deleting || deleting.phase === "pending" || deleting.phase === "keeping"; } /** * The ledger's one writer (RESTORE 2 SERVER 5): a copy and a fold each wait for the one before, so a fold never * overwrites the chunk count a copy just raised, and two copies never write the same entries (SERVER 3). */ private async ledgerTurn(work: () => Promise): Promise { // A turn before that failed never stops this one. const run = (this.flushing ?? Promise.resolve()).catch(() => undefined).then(work); this.flushing = run; try { await run; } finally { if (this.flushing === run) this.flushing = null; } } /** Until no copy or fold of the ledger is in flight (the deletion's files step waits on it). */ private async ledgerQuiet(): Promise { while (this.flushing) await this.flushing.catch(() => undefined); } private flushing: Promise | null = null; /** When a ledger copy last failed (0: the last one went): background copies wait a while after it. */ private ledgerFailedAt = 0; /** * Work a host hands off after its answer (a hand-over to another account among it). When it is done, a delivery it * kept to try again arms the alarm for its time (RESTORE 2 SERVER 4, L6), not the next hourly pass. */ private background(work: Promise): void { // Armed whatever the work did; a failure still surfaces in waitUntil as before (RESTORE 2 SERVER 5). this.ctx.waitUntil(work.finally(() => this.armHandovers())); } private async armHandovers(): Promise { const due = handover.nextDue(this.ctx.storage.sql); if (due === null) return; const set = await this.ctx.storage.getAlarm(); if (set === null || set > due) await this.ctx.storage.setAlarm(due); } /** Deliveries another account refused as "try again" (frozen), handed over again when due (src/handover.ts). */ private async retryHandovers(): Promise { if (handover.nextDue(this.ctx.storage.sql) === null) return; const methods = { chat: "chatDeliver", send: "sendDeliver", invite: "inviteDeliver", secret: "secretDeliver" } as const; const done = await handover.retryDue(this.ctx.storage.sql, async (kind, to, delivery) => { // AUDIT D: a secret taken back (or its holder removed) while it waited is never handed over late. if (kind === "secret" && !secrets.stillGiven(this.ctx.storage.sql, String((delivery as { share?: unknown }).share ?? ""))) return; const slug = await directory(this.env).lookup(to); if (!slug || slug === this.ownSlug()) return; const peer = this.env.BUSINESS.get(this.env.BUSINESS.idFromName(slug), { locationHint: "apac" }) as unknown as Record Promise>; if (kind === "secret_take") { const take = delivery as { from: string; share: string }; await peer.secretTaken!(take.from, take.share); return; } await peer[methods[kind]]!(delivery); }); if (done.delivered + done.dropped) console.log(`cottondb: handover: ${done.delivered} delivered late, ${done.waiting} waiting, ${done.dropped} given up`); } /** Once a week, on the alarm, the ledger's chunks folded into one (src/never_again.ts `compact`). */ private async compactNeverAgain(): Promise { // Only a ledger of two chunks or more, a week after the last fold: an account with none lists nothing. if (Number(this.store.meta(neverAgain.CHUNKS) ?? "0") < 2) return; const at = Number(this.store.meta(neverAgain.COMPACTED) ?? "0"); if (Date.now() - at < neverAgain.COMPACT_EVERY_MS) return; const slug = this.ownSlug(); if (!slug) return; await this.ledgerTurn(async () => { try { const folded = await neverAgain.compact(this.env.PHOTOS, slug); this.store.setMeta(neverAgain.COMPACTED, String(Date.now())); this.store.setMetaQuiet(neverAgain.CHUNKS, "1"); if (folded > 1) console.log(`cottondb: never-again ${slug}: ${folded} chunks folded into one`); } catch (error) { console.error(`cottondb: never-again ${slug}: not folded (${error instanceof Error ? error.message : String(error)})`); } }); } /** The person set the account to be deleted (`accountDelete.start` wrote it in the ledger): copied out at once. */ private async deletionStarted(started: T): Promise { await this.flushNeverAgain(); return started; } /** * The ledger laid over a restored object (PITR finish, snapshot restore), before it is unfrozen. A Keep the restored * moment held half done is finished first (RESTORE 2 SERVER 3, M3: `keeping` is a Keep in progress, never a deletion). * Then the newest deletion entry decides: a deletion set since stands (its own dates), a Keep since is done properly * (`accountDelete.keep`: the directory and the public links told), and the counts are made again (L). */ private async replayNeverAgain(slug: string): Promise { const sql = this.ctx.storage.sql; if (accountDelete.job(sql)?.phase === "keeping") await accountDelete.keep(this.deleteHost()); const entries = await neverAgain.read(this.env.PHOTOS, slug); const { done, wanted } = neverAgain.replay(sql, entries, (key, value) => this.store.setMetaQuiet(key, value)); const held = accountDelete.job(sql); if (wanted?.kind === "set" && !held) { const e = wanted.entry; sql.exec(accountDelete.SCHEMA); const receipt = { started_at: e.started_at, finished_at: null, by: e.by, records: 0, files: 0, bytes: 0, google: { held: 0, revoked: 0 }, reports: 0 }; sql.exec(`INSERT INTO ${accountDelete.TABLE} (id, phase, started_at, by, database_id, slug, owner_phone, receipt, erase_at) VALUES (1, 'pending', ?, ?, ?, ?, ?, ?, ?)`, e.started_at, e.by, this.store.meta("database_id"), slug, this.store.meta("owner_phone"), JSON.stringify(receipt), e.erase_at); done.deletion = "set"; } else if (wanted?.kind === "keep" && held?.phase === "pending") { await accountDelete.keep(this.deleteHost()); done.deletion = "kept"; } // Rows the ledger erased leave their tables' counts behind: counted again. this.ctx.storage.transactionSync(() => { for (const table of done.tables) this.store.recountTable(table); }); return done; } /** * The restore routes (`/v1/admin/restore`, `/v1/admin/restore/…`), the admin token's alone on the dev and test * Workers, answered ahead of every other door (an erased account's too); then the freeze: while frozen, every * request but the admin token's is answered 503 `account_frozen`. Null: the request goes on. */ private async restoreDoor(request: Request): Promise { const path = new URL(request.url).pathname; const slug = this.slugOf(request); const admin = isAdminToken(this.env, bearer(request)); // The body is read first when answered here: an answer sent while it is unread leaves the runtime a stream it cannot finish. const drained = async (answer: Response): Promise => { if (request.body) await request.arrayBuffer().catch(() => undefined); return answer; }; if (restore.restoreRoutesOn(this.env)) { // The owner's own restore (src/restore_owner.ts): answered ahead of the freeze, so the phone that began it sees it through. if (path === "/v1/restore" || path.startsWith("/v1/restore/")) { if (!slug) refuse(400, "bad_request", "no slug named"); return await this.ownerRestoreRoute(request, path.slice("/v1/restore".length), slug); } if (path === "/v1/admin/restore" || path.startsWith("/v1/admin/restore/")) { if (!admin) refuse(403, "admin_only", "a restore takes the admin token"); if (!slug) refuse(400, "bad_request", "no slug named"); return await this.restoreRoute(request, path.slice("/v1/admin/restore".length), slug); } if (!admin) { let marker: restore.Marker | null; try { marker = await this.marker(slug); } catch { // Never latched, never taken as frozen: asked again on the next request. return await drained(restore.unreadAnswer()); } if (marker?.frozen) return await drained(restore.frozenAnswer()); } } return null; } // ── RESTORE 2, the owner's own restore (src/restore_owner.ts) ────────────────────────────────────────────────── /** One owner step at a time: a phone's step and the alarm's never lay the same part twice. */ private ownerTurn: Promise | null = null; private async ownerTurnRun(work: () => Promise): Promise { const run = (this.ownerTurn ?? Promise.resolve()).catch(() => undefined).then(work); this.ownerTurn = run; try { return await run; } finally { if (this.ownerTurn === run) this.ownerTurn = null; } } /** Only the owner's own phone, signed in with its device credential (src/restore_owner.ts WHO). */ private async ownerDevice(request: Request): Promise { const token = bearer(request); if (!token) refuse(401, "sign_in", "sign in first"); if (isAdminToken(this.env, token) || token.startsWith("ctn_")) refuse(403, "owner_device_only", "only the owner's own phone, signed in, restores this account"); let who: Who | null; try { who = await whoIs(this.store, new Date(), token); } catch (error) { // A sign-in the account's delete ended (every one is, at the tap): the account is being deleted. if (error instanceof Refused && error.code === "credential_revoked" && this.deletionSet()) refuse(409, "account_deleting", "this account is set to be deleted: keep it first"); throw error; } if (!who || who.person.role !== "owner") refuse(403, "owner_device_only", "only the owner's own phone, signed in, restores this account"); return who; } private deletionSet(): boolean { try { return accountDelete.job(this.ctx.storage.sql) !== null; } catch { return false; } } /** Where an owner's restore stands, as every owner route answers it. */ private ownerState(marker: restore.Marker | null): Record { const job = this.metaJson(snapshots.RESTORING); let generation: string | null = null; let restoredTo: string | null = null; try { generation = this.store.meta(restore.GENERATION); restoredTo = this.store.meta(restore.RESTORED_TO); } catch { // an erased object keeps no meta } const stage: restoreOwner.Stage = marker?.owner && job ? (job.phase === "verify" ? "checking" : "laying") : marker?.frozen || marker?.pending || job ? "held" : "none"; const under = marker?.owner && job ? { point: marker.owner.point, to: marker.owner.to, started_at: marker.owner.started_at, rows: job.rows, ...restoreOwner.progressOf(job) } : null; return { stage, restore: under, may_cancel: stage === "checking", generation, restored_to: restoredTo, deleting: this.deletionSet() }; } /** The days the snapshots can put this account back to, newest first. */ private async ownerPoints(slug: string): Promise { const read = async (kind: snapshots.Kind) => { const out: snapshots.Manifest[] = []; for (const stamp of (await this.snapshotCopies(kind, slug)).copies) { const manifest = await this.snapshotManifest(kind, slug, stamp); if (manifest) out.push(manifest); } return out; }; return restoreOwner.pointsOf(await read("full"), await read("daily"), (at) => neverAgain.restorable(at)); } private async ownerRestoreRoute(request: Request, path: string, slug: string): Promise { const method = request.method; // The body read first, whatever is answered: an answer sent while it is unread leaves the runtime a stream it // cannot finish (it threw "Can't read from request stream after response has been sent" under wrangler dev). const body: Record = request.body ? await readJson(request).catch(() => ({}) as Record) : {}; const who = await this.ownerDevice(request); // Read afresh: the marker is the truth (as on the admin's restore routes). this.restoreMarker = null; let marker: restore.Marker | null; try { marker = await this.marker(slug); } catch { return restore.unreadAnswer(); } if (method === "GET" && path === "") { const points = this.deletionSet() ? [] : await this.ownerPoints(slug); const { unready } = restore.devicesSeen(this.ctx.storage.sql, Date.now()); return json({ on: snapshots.snapshotsOn(this.store.meta(snapshots.SWITCH), this.env), points, devices_unready: unready.length, ...this.ownerState(marker) }); } if (method === "GET" && path === "/state") return json(this.ownerState(marker)); if (method === "POST" && path === "/begin") { if (this.deletionSet()) refuse(409, "account_deleting", "this account is set to be deleted: keep it first"); if (marker?.frozen || marker?.pending || this.snapshotRestoring()) return json({ code: "restore_under_way", message: "a restore of this account is under way", ...this.ownerState(marker) }, 409); const point = (await this.ownerPoints(slug)).find((p) => p.id === body.point); if (!point) refuse(404, "no_such_point", "no such day to restore"); if (body.anyway !== true) { const { unready } = restore.devicesSeen(this.ctx.storage.sql, Date.now()); if (unready.length) return json({ code: "devices_without_generation", message: `${unready.length} device(s) active in the last 30 days never sent x-cotton-generation`, devices: unready.length }, 409); } const owner: restoreOwner.Owner = { device: who.deviceId, point: point.id, to: point.to, started_at: new Date().toISOString() }; await this.setMarker(slug, { frozen: true, frozen_at: owner.started_at, reason: "the owner's restore", pending: null, owner }); for (const socket of this.ctx.getWebSockets()) { try { socket.close(4503, "account_frozen"); } catch { // already closing } } try { const begun = await this.snapshotRestoreBegin(slug, { full: point.full, through: point.through, override_devices: true }); if (!begun.ok) throw new Refused(begun.status, "restore_refused", await begun.text()); } catch (error) { // Nothing was changed (BEGIN only checks): the account is unfrozen and the refusal said. await this.setMarker(slug, null); throw error; } // While no phone steps it, the alarm does (src/restore_owner.ts ALARM_STEP_MS). await this.ctx.storage.setAlarm(Date.now() + restoreOwner.ALARM_STEP_MS); console.log(`cottondb: owner restore ${slug}: begun to ${point.to} from ${who.deviceId.slice(0, 8)}`); return json(this.ownerState(await this.marker(slug))); } if (method === "POST" && path === "/step") { if (!marker?.owner) return json(this.ownerState(marker)); return json(await this.ownerTurnRun(() => this.ownerStep(slug))); } if (method === "POST" && path === "/cancel") { return json( await this.ownerTurnRun(async () => { this.restoreMarker = null; const now = await this.marker(slug); const job = this.metaJson(snapshots.RESTORING); if (!now?.owner || !job) refuse(409, "no_restore", "no restore of yours is under way"); if (job.phase === "lay") refuse(409, "restore_laying", "the rows are being laid back: it cannot be taken back now"); this.store.setMeta(snapshots.RESTORING, null); await this.setMarker(slug, null); await this.keepAlarm().catch(() => undefined); console.log(`cottondb: owner restore ${slug}: taken back while checking`); return { ...this.ownerState(null), cancelled: true }; }), ); } refuse(405, "method_not_allowed", "GET /v1/restore, GET /v1/restore/state, POST /v1/restore/begin {point, anyway}, POST /v1/restore/step, POST /v1/restore/cancel"); } /** A few parts more of the owner's restore; at its end the account is unfrozen by itself. Run inside `ownerTurnRun`. */ private async ownerStep(slug: string): Promise> { this.restoreMarker = null; const marker = await this.marker(slug); if (!marker?.owner || !this.snapshotRestoring()) return this.ownerState(marker); const stepped = await this.snapshotRestoreStep(slug, { budget_ms: restoreOwner.STEP_BUDGET_MS }); if (!stepped.ok) throw new Refused(stepped.status, "restore_refused", await stepped.text()); const answer = (await stepped.json()) as { done: boolean; restored_to?: string; generation?: string }; if (!answer.done) { await this.ctx.storage.setAlarm(Date.now() + restoreOwner.ALARM_STEP_MS); return this.ownerState(marker); } await this.setMarker(slug, null); await this.keepAlarm().catch(() => undefined); console.log(`cottondb: owner restore ${slug}: finished, put back to ${answer.restored_to}`); return { ...this.ownerState(null), finished: true }; } /** On the alarm: an owner's restore no phone is stepping is stepped (true), before the freeze holds the alarm. */ private async ownerRestoreAlarm(): Promise { if (!restore.restoreRoutesOn(this.env)) return false; let marker: restore.Marker | null; try { marker = await this.marker(); } catch { return false; } if (!marker?.owner) return false; const slug = this.ownSlug(); try { await this.ownerTurnRun(() => this.ownerStep(slug)); } catch (error) { console.error(`cottondb: owner restore ${slug}: a step failed (${error instanceof Error ? error.message : String(error)}); stepped again later`); await this.ctx.storage.setAlarm(Date.now() + restoreOwner.ALARM_STEP_MS); } return true; } /** The object's version, or 0 when it keeps no meta (an erased object). */ private versionOrZero(): number { try { return this.store.version(); } catch { return 0; } } private liveRows(table?: string | null): number | null { try { const sql = this.ctx.storage.sql; return table ? Number(sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE table_id = ? AND deleted = 0", table).one().n) : Number(sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE deleted = 0").one().n); } catch { return null; } } private async restoreRoute(request: Request, path: string, slug: string): Promise { const method = request.method; const storage = this.ctx.storage as unknown as { getCurrentBookmark?: () => Promise; getBookmarkForTime?: (at: number | Date) => Promise; onNextSessionRestoreBookmark?: (bookmark: string) => Promise; }; const pitr = async (run: () => Promise): Promise => { try { return await run(); } catch (error) { refuse(501, "pitr_unavailable", `point-in-time recovery answered: ${error instanceof Error ? error.message : String(error)}`); } }; // Read afresh on each restore route (they are rare): the marker is the truth, the instance's copy only a cache. this.restoreMarker = null; const marker = await this.marker(slug); // Where it stands: the freeze, a restore asked and not finished, the generation, the version. if (method === "GET" && path === "/state") { let generation: string | null = null; let restoredTo: string | null = null; try { generation = this.store.meta(restore.GENERATION); restoredTo = this.store.meta(restore.RESTORED_TO); } catch { // an erased object keeps no meta } const pending = marker?.pending ? { version_before: marker.pending.version_before, restored_to: marker.pending.restored_to, bookmark_hash: marker.pending.bookmark_hash, erased_before: marker.pending.erased_before, asked_at: marker.pending.asked_at } : null; const seen = restore.devicesSeen(this.ctx.storage.sql, Date.now()); return json({ frozen: marker?.frozen ?? false, frozen_at: marker?.frozen_at ?? null, reason: marker?.reason ?? null, pending, generation, restored_to: restoredTo, version: this.versionOrZero(), rows: this.liveRows(), erased: accountDelete.job(this.ctx.storage.sql) !== null, devices: seen.devices, devices_unready: seen.unready.map((d) => d.device) }); } if (method === "GET" && path === "/bookmark") { if (!storage.getCurrentBookmark || !storage.getBookmarkForTime) refuse(501, "pitr_unavailable", "this runtime has no point-in-time recovery"); const params = new URL(request.url).searchParams; const at = params.get("at"); const now = await pitr(() => storage.getCurrentBookmark!()); const then = at ? await pitr(() => storage.getBookmarkForTime!(new Date(at))) : null; const table = params.get("table"); const rows = table && /^[a-z_][a-z0-9_]*$/.test(table) ? this.liveRows(table) : null; return json({ now, at_now: new Date().toISOString(), ...(then ? { at, bookmark: then } : {}), version: this.versionOrZero(), ...(rows === null ? {} : { table, rows }) }); } if (method === "POST" && path === "/freeze") { const body = await readJson(request).catch(() => ({}) as Record); const reason = typeof body.reason === "string" ? body.reason.slice(0, 200) : null; await this.setMarker(slug, { frozen: true, frozen_at: marker?.frozen_at ?? new Date().toISOString(), reason: reason ?? marker?.reason ?? null, pending: marker?.pending ?? null }); // Every open socket closed with the same word (RESTORE-2-CONTRACT.md 5); they reopen once the account answers. for (const socket of this.ctx.getWebSockets()) { try { socket.close(4503, "account_frozen"); } catch { // already closing } } console.log(`cottondb: restore ${slug}: frozen`); return json({ frozen: true }); } if (method === "POST" && path === "/unfreeze") { if (marker?.pending) refuse(409, "restore_unfinished", "a restore was asked and not finished: POST /v1/admin/restore/finish (or /cancel if it never landed) first"); if (this.snapshotRestoring()) refuse(409, "restore_unfinished", "a restore from snapshots is under way: finish it (POST /v1/admin/snapshots/restore/step) or cancel it (POST /v1/admin/snapshots/restore/cancel) first"); await this.setMarker(slug, null); await this.keepAlarm().catch(() => undefined); console.log(`cottondb: restore ${slug}: unfrozen`); return json({ frozen: false }); } if (method === "POST" && path === "/export") { // Today's live rows, as stored, one page a call: ask again with `after` until `done` (src/restore.ts). restore.mustBeFrozen(marker); // An erased object holds no rows: nothing to keep. if (accountDelete.job(this.ctx.storage.sql)) return json({ done: true, erased: true, manifest: { rows: 0, parts: [] } }); const body = await readJson(request).catch(() => ({}) as Record); const stamp = typeof body.stamp === "string" && /^[0-9TZ:.-]{10,40}$/.test(body.stamp) ? body.stamp : new Date().toISOString().replace(/[:.]/g, "-"); const after = typeof body.after === "string" && body.after.includes("/") ? { table: body.after.slice(0, body.after.indexOf("/")), id: body.after.slice(body.after.indexOf("/") + 1) } : null; const part = Number.isInteger(body.part) ? Number(body.part) : 1; // Sealed like a snapshot, under the account's snapshot key and bound to its place, and kept where the R2 // lifecycle rule ends it (L5; SNAPSHOTS.md): the account delete erases the prefix and forgets the key. const keys = (await this.snapshotKey(true))!; const prefix = `${restore.EXPORTS}${slug}/${stamp}/`; const { rows, more } = this.store.livePage(after, 20_000); const bytes = await snapshots.sealPart(keys, snapshots.aadOf(slug, "export", stamp, part), rows.map((r) => JSON.stringify(wire(r, true)))); const sha = await snapshots.sha256(bytes); await this.env.MEDIA.put(`${prefix}part-${String(part).padStart(5, "0")}.bin`, bytes, { customMetadata: { rows: String(rows.length), sha256: sha } }); const last = rows[rows.length - 1]; if (more && last) return json({ stamp, part, rows: rows.length, sha256: sha, done: false, after: `${last.table}/${last.id}`, next_part: part + 1 }); const listed = await this.env.MEDIA.list({ prefix, include: ["customMetadata"] }); const parts = listed.objects.filter((o) => o.key.endsWith(".bin")).map((o) => ({ key: o.key.slice(prefix.length), rows: Number(o.customMetadata?.rows ?? 0), sha256: o.customMetadata?.sha256 ?? null })); const manifest = { stamp, version: this.versionOrZero(), generation: this.store.meta(restore.GENERATION), parts, rows: parts.reduce((a, p) => a + p.rows, 0), written_at: new Date().toISOString() }; await this.env.MEDIA.put(`${prefix}manifest.json`, JSON.stringify(manifest), { httpMetadata: { contentType: "application/json" } }); return json({ stamp, part, rows: rows.length, sha256: sha, done: true, manifest }); } if (method === "POST" && path === "") { restore.mustBeFrozen(marker); if (marker?.pending) refuse(409, "restore_unfinished", "a restore was asked and not finished: POST /v1/admin/restore/finish first"); if (!storage.onNextSessionRestoreBookmark) refuse(501, "pitr_unavailable", "this runtime has no point-in-time recovery"); const body = await readJson(request); const bookmark = text(body.bookmark, "bookmark"); const restoredTo = text(body.restored_to, "restored_to"); if (Number.isNaN(Date.parse(restoredTo))) refuse(400, "bad_request", "restored_to is the moment the bookmark stands for (ISO)"); // The ledger covers 40 days (src/never_again.ts KEEP_MS): no restore reaches further back. `restored_to` is the // caller's word: Cloudflare gives no time for a bookmark (it is opaque; RESTORE 2 SERVER 5 asked). The bound holds // without it: point-in-time recovery reaches back 30 days at most, so no bookmark it takes is older than 40. if (!neverAgain.restorable(restoredTo)) refuse(409, "too_old", "a restore reaches back at most 40 days: the never-again ledger covers no more"); this.devicesReady(body); const hash = await restore.bookmarkHash(bookmark); // The ledger copied out first (M5): the restore rolls the outbox back with everything else. await this.flushNeverAgain(); if (neverAgain.waiting(this.ctx.storage.sql)) refuse(503, "try_again", "the never-again ledger could not be copied out; nothing was restored"); // The sentinel (M2): written now, after any moment a bookmark can name, so a restore that lands takes it away. const sentinel = restore.freshGeneration(); this.ctx.storage.sql.exec(restore.SENTINEL_SQL); this.ctx.storage.sql.exec("INSERT OR REPLACE INTO restore_sentinel (id, token) VALUES (1, ?)", sentinel); const deleted = accountDelete.job(this.ctx.storage.sql); // An erased object has no version left: the receipt keeps the one it had reached (L3). const versionBefore = Math.max(this.versionOrZero(), deleted?.receipt.last_version ?? 0); // Written down outside the object first: the restore rolls the object back past all of it. const pending = { version_before: versionBefore, generation: restore.freshGeneration(), restored_to: new Date(restoredTo).toISOString(), bookmark_hash: hash, erased_before: deleted !== null, asked_at: new Date().toISOString(), sentinel }; await this.setMarker(slug, { ...marker!, pending }); let undo: string; try { undo = await pitr(() => storage.onNextSessionRestoreBookmark!(bookmark)); } catch (error) { await this.setMarker(slug, { ...marker!, pending: null }); throw error; } console.log(`cottondb: restore ${slug}: to bookmark ${hash} (${pending.restored_to}); version before ${pending.version_before}`); // The restore lands when the object restarts: after this answer has gone (Cloudflare's docs: ctx.abort()). setTimeout(() => this.ctx.abort("point-in-time restore"), 50); return json({ restoring_to: hash, restored_to: pending.restored_to, version_before: pending.version_before, undo }); } if (method === "POST" && path === "/cancel") { // A restore asked that never landed (the sentinel is still here): the ask is taken back, nothing else changes. const pending = marker?.pending; if (!pending) refuse(409, "no_restore", "no restore was asked"); if (!restore.sentinelHeld(this.ctx.storage.sql, pending.sentinel)) refuse(409, "restore_landed", "the restore has landed: POST /v1/admin/restore/finish"); this.ctx.storage.sql.exec("DELETE FROM restore_sentinel"); await this.setMarker(slug, { ...marker!, pending: null }); // The restore armed for the next start is disarmed (RESTORE 2 SERVER 3): there is no call to take it back, so the // object is armed instead with its state as it is now and restarted at once. It is frozen: nothing is written // between this bookmark and the restart, so the restart restores exactly this. let disarmed = false; if (storage.getCurrentBookmark && storage.onNextSessionRestoreBookmark) { try { const now = await storage.getCurrentBookmark(); await storage.onNextSessionRestoreBookmark(now); disarmed = true; setTimeout(() => this.ctx.abort("a restore taken back: restarting on the bookmark of now"), 50); } catch (error) { console.error(`cottondb: restore ${slug}: could not disarm (${error instanceof Error ? error.message : String(error)})`); } } console.log(`cottondb: restore ${slug}: the ask to ${pending.bookmark_hash} taken back; disarmed ${disarmed}`); return json({ cancelled: true, disarmed }); } if (method === "POST" && path === "/finish") { restore.mustBeFrozen(marker); const pending = marker?.pending; if (!pending) refuse(409, "no_restore", "no restore was asked"); // M2: the sentinel written just before the restore must be gone; still here, the restore has not landed. if (restore.sentinelHeld(this.ctx.storage.sql, pending.sentinel)) refuse(409, "not_restored_yet", "the restore has not landed (wait for the restart and ask again, or POST /v1/admin/restore/cancel)"); const done = await this.afterRestore(slug, pending.version_before, pending.generation, pending.restored_to, pending.erased_before, "restored"); await this.setMarker(slug, { ...marker!, pending: null }); console.log(`cottondb: restore ${slug}: finished at version ${done.version}; deletion ${done.deletion?.phase ?? "none"}; ledger ${JSON.stringify(done.ledger)}`); return json({ ...done, generation: pending.generation, restored_to: pending.restored_to, rows: this.liveRows(), erased_before: pending.erased_before }); } refuse(405, "method_not_allowed", "GET /state, GET /bookmark [?at=][&table=], POST /freeze {reason}, POST /export {stamp, part, after}, POST / {bookmark, restored_to}, POST /finish, POST /cancel, POST /unfreeze"); } /** * A restore reaches the phones only through the generation they send: refused while any device active in the last * 30 days (or signed in and never seen) has never sent `x-cotton-generation`, unless `override_devices: true`. */ private devicesReady(body: Record): void { if (body.override_devices === true) return; const { unready } = restore.devicesSeen(this.ctx.storage.sql, Date.now()); if (unready.length) refuse(409, "devices_without_generation", `${unready.length} device(s) active in the last 30 days never sent x-cotton-generation (${unready.map((d) => d.device.slice(0, 8)).join(", ")}): their queued writes would land on the restored history. Wait for them to update, or say override_devices: true`); } /** * What every restore does once the earlier state is in place, before it is unfrozen (PITR finish, snapshot restore): * the ledger replayed (M5), the version raised past anything a phone saw and a new generation (RESTORE 2), the * snapshot chain restarted with a new full copy (M6), and a deletion the restored moment held kept as it was, dates * included, and said (M3). The admin is told all of it. */ private async afterRestore(slug: string, versionBefore: number, generation: string, restoredTo: string, erasedBefore: boolean, outbox: "restored" | "live"): Promise<{ version: number; ledger: neverAgain.Replayed; deletion: { phase: string; started_at: string; erase_at: string | null } | null; relinked: boolean }> { const sql = this.ctx.storage.sql; // A point-in-time restore brings back an outbox copied out before it (in the ledger already): its copies go. A // restore from snapshots leaves the outbox alone: anything noted meanwhile is copied out first. if (outbox === "restored") sql.exec("DROP TABLE IF EXISTS never_again_outbox"); else { await this.flushNeverAgain(); if (neverAgain.waiting(sql)) refuse(503, "try_again", "the never-again ledger could not be copied out; step again"); } sql.exec("DROP TABLE IF EXISTS restore_sentinel"); const ledger = await this.replayNeverAgain(slug); const version = Math.max(versionBefore, this.versionOrZero()) + restore.VERSION_MARGIN; this.ctx.storage.transactionSync(() => { this.store.setMetaQuiet("version", String(version)); this.store.setMetaQuiet(restore.GENERATION, generation); this.store.setMetaQuiet(restore.RESTORED_TO, restoredTo); // M6: never resume a copy half written before the restore; the next copy is a full one. this.store.setMetaQuiet(snapshots.JOB, null); this.store.setMetaQuiet(snapshots.LAST, null); }); this.snapshotKeyCache = null; const held = accountDelete.job(sql); const databaseId = this.store.meta("database_id"); const phone = this.store.meta("owner_phone"); let relinked = false; if (held) { // M3: the restored moment had a deletion set: it stands as it was, dates included. Signed out, the public links // gone, the directory counting it, and its alarm set for its date (or now, for an erase already under way). sql.exec("UPDATE sessions SET revoked = 1"); await this.env.PHOTOS.put(accountDelete.marker(slug), ""); if (databaseId) { if (erasedBefore && phone && held.phase === "pending" && held.eraseAt) relinked = await directory(this.env).restoredAfterErase({ databaseId, slug, phone }, { asked_at: held.startedAt, erase_at: held.eraseAt }); else if (held.eraseAt) await directory(this.env).deletingSet(databaseId, slug, held.startedAt, held.eraseAt); } await this.ctx.storage.setAlarm(held.phase === "pending" && held.eraseAt ? Math.max(Date.now(), Date.parse(held.eraseAt)) : Date.now()); } else if (erasedBefore) { // An erased account put back (dev only): its deletion marker and its number's entry come back too. await this.env.PHOTOS.delete(accountDelete.marker(slug)); if (databaseId && phone) relinked = await directory(this.env).restoredAfterErase({ databaseId, slug, phone }); } return { version, ledger, deletion: held ? { phase: held.phase, started_at: held.startedAt, erase_at: held.eraseAt } : null, relinked }; } // ── SNAPSHOTS 1 (src/snapshots.ts) ───────────────────────────────────── private metaJson(key: string): T | null { const raw = this.store.meta(key); if (!raw) return null; try { return JSON.parse(raw) as T; } catch { return null; } } /** The account's snapshot keys, asked of the directory once per instance (L5), never on every step. */ private snapshotKeyCache: { slug: string; keys: snapshots.Keys } | null = null; private async snapshotKey(make: boolean): Promise { const slug = this.ownSlug(); if (this.snapshotKeyCache?.slug === slug) return this.snapshotKeyCache.keys; const raw = await directory(this.env).snapshotKey(slug, make); if (!raw) return null; const keys = await snapshots.importKey(raw); this.snapshotKeyCache = { slug, keys }; return keys; } /** Whether a restore from snapshots is under way (meta; an erased object holds none). */ private snapshotRestoring(): boolean { try { return this.store.meta(snapshots.RESTORING) !== null; } catch { return false; } } /** On the alarm: a few parts of a copy that is due or under way; the alarm comes back soon while one is. */ private async snapshotAlarm(): Promise { // The slug from meta (M4): an object woken only by its alarm has answered no request and knows no `this.slug`. const slug = this.ownSlug(); if (!snapshots.snapshotsOn(this.store.meta(snapshots.SWITCH), this.env) || !slug) return; try { const step = await this.snapshotStep(8_000); if ("done" in step && step.done === false) { const set = await this.ctx.storage.getAlarm(); if (set === null || set > Date.now() + 5_000) await this.ctx.storage.setAlarm(Date.now() + 5_000); } else if ("done" in step && step.job.kind === "full") { // The daily after a full is due at once (L2): come back for it soon. const set = await this.ctx.storage.getAlarm(); if (set === null || set > Date.now() + 5_000) await this.ctx.storage.setAlarm(Date.now() + 5_000); } } catch (error) { console.error(`cottondb: snapshot ${slug}: ${error instanceof Error ? error.message : String(error)}`); } } /** Writes parts of the copy under way (or starts the one due, or `force`) for up to `budgetMs`. */ private async snapshotStep(budgetMs: number, force?: snapshots.Kind): Promise<{ idle: true } | { done: boolean; job: snapshots.Job; manifest?: snapshots.Manifest }> { // Never while a restore from snapshots lays rows: it would copy half an account. if (this.snapshotRestoring()) return { idle: true }; const slug = this.ownSlug(); let job = this.metaJson(snapshots.JOB); const last = this.metaJson(snapshots.LAST) ?? {}; if (!job) { const kind = force ?? snapshots.due(last, Date.now()); if (!kind) return { idle: true }; const now = new Date(); job = { kind, stamp: snapshots.stampOf(now), base: kind === "full" ? 0 : snapshots.baseOf(last), upto: this.store.version(), cursor: null, part: 0, rows: 0, bytes: 0, started_at: now.toISOString() }; this.store.setMeta(snapshots.JOB, JSON.stringify(job)); } const keys = (await this.snapshotKey(true))!; const prefix = snapshots.snapshotPrefix(job.kind, slug, job.stamp); const started = Date.now(); while (Date.now() - started < budgetMs) { const { lines, cursor } = snapshots.page(this.ctx.storage.sql, job, snapshots.ROWS_PER_PART); if (lines.length > 0) { const part = job.part + 1; const bytes = await snapshots.sealPart(keys, snapshots.aadOf(slug, job.kind, job.stamp, part), lines.map((l) => JSON.stringify(l))); await this.env.MEDIA.put(`${prefix}part-${String(part).padStart(5, "0")}.bin`, bytes, { customMetadata: { rows: String(lines.length), sha256: await snapshots.sha256(bytes) } }); job.part = part; job.rows += lines.length; job.bytes += bytes.length; } job.cursor = cursor; this.store.setMeta(snapshots.JOB, JSON.stringify(job)); if (cursor === null) { const parts: snapshots.PartInfo[] = []; let listCursor: string | undefined; do { const listed = await this.env.MEDIA.list({ prefix, include: ["customMetadata"], ...(listCursor ? { cursor: listCursor } : {}) }); for (const o of listed.objects) if (o.key.endsWith(".bin")) parts.push({ key: o.key.slice(prefix.length), rows: Number(o.customMetadata?.rows ?? 0), bytes: o.size, sha256: o.customMetadata?.sha256 ?? "" }); listCursor = listed.truncated ? listed.cursor : undefined; } while (listCursor); parts.sort((a, b) => a.key.localeCompare(b.key)); const manifest = await snapshots.signManifest(keys, { kind: job.kind, stamp: job.stamp, slug, base: job.base, upto: job.upto, rows: job.rows, bytes: job.bytes, parts, started_at: job.started_at, written_at: new Date().toISOString(), format: "ndjson.gz.aes256gcm+aad" }); await this.env.MEDIA.put(`${prefix}manifest.json`, JSON.stringify(manifest), { httpMetadata: { contentType: "application/json" } }); last[job.kind] = { stamp: job.stamp, upto: job.upto, at: job.started_at }; this.store.setMeta(snapshots.LAST, JSON.stringify(last)); this.store.setMeta(snapshots.JOB, null); await this.snapshotsPrune(slug); console.log(`cottondb: snapshot ${slug}: ${job.kind} ${job.stamp} written, ${job.rows} rows, ${job.bytes} bytes, ${job.part} parts`); return { done: true, job, manifest }; } } return { done: false, job }; } /** The stamps of an account's folders of a kind, oldest first (copies or not: see `snapshotCopies`). */ private async snapshotStamps(kind: snapshots.Kind, slug: string): Promise { const base = snapshots.prefixOf(kind, slug); const out: string[] = []; let cursor: string | undefined; do { const listed = await this.env.MEDIA.list({ prefix: base, delimiter: "/", ...(cursor ? { cursor } : {}) }); out.push(...listed.delimitedPrefixes.map((p) => p.slice(base.length, -1))); cursor = listed.truncated ? listed.cursor : undefined; } while (cursor); return out.sort(); } /** The copies of a kind, oldest first: folders with a manifest. A folder without one is not a copy (L5). */ private async snapshotCopies(kind: snapshots.Kind, slug: string): Promise<{ copies: string[]; abandoned: string[] }> { const copies: string[] = []; const abandoned: string[] = []; const running = this.metaJson(snapshots.JOB); for (const stamp of await this.snapshotStamps(kind, slug)) { if (await this.env.MEDIA.head(`${snapshots.snapshotPrefix(kind, slug, stamp)}manifest.json`)) copies.push(stamp); else if (!(running && running.kind === kind && running.stamp === stamp)) abandoned.push(stamp); } return { copies, abandoned }; } /** The 4 newest weeklies and the 7 newest dailies kept, and no daily older than the oldest weekly kept; half-written folders of a copy no longer under way go. */ private async snapshotsPrune(slug: string): Promise { const weekly = await this.snapshotCopies("full", slug); const keptWeekly = weekly.copies.slice(-snapshots.KEEP_WEEKLY); const daily = await this.snapshotCopies("daily", slug); const keptDaily = new Set(daily.copies.slice(-snapshots.KEEP_DAILY).filter((s) => !keptWeekly[0] || s > keptWeekly[0])); const gone = [ ...weekly.copies.filter((s) => !keptWeekly.includes(s)).map((s) => snapshots.snapshotPrefix("full", slug, s)), ...daily.copies.filter((s) => !keptDaily.has(s)).map((s) => snapshots.snapshotPrefix("daily", slug, s)), ...weekly.abandoned.map((s) => snapshots.snapshotPrefix("full", slug, s)), ...daily.abandoned.map((s) => snapshots.snapshotPrefix("daily", slug, s)), ]; for (const prefix of gone) await deletePrefix(this.env.MEDIA, prefix, 10); } private async snapshotManifest(kind: snapshots.Kind, slug: string, stamp: string): Promise { const got = await this.env.MEDIA.get(`${snapshots.snapshotPrefix(kind, slug, stamp)}manifest.json`); if (!got) return null; try { return (await got.json()) as snapshots.Manifest; } catch { return null; } } private async snapshotsAdmin(request: Request, path: string): Promise { const method = request.method; const slug = this.ownSlug(); if (method === "GET" && path === "") { const weekly = await this.snapshotCopies("full", slug); const daily = await this.snapshotCopies("daily", slug); return json({ on: snapshots.snapshotsOn(this.store.meta(snapshots.SWITCH), this.env), job: this.metaJson(snapshots.JOB), last: this.metaJson(snapshots.LAST), weekly: weekly.copies, daily: daily.copies, unfinished: [...weekly.abandoned, ...daily.abandoned], restoring: this.metaJson(snapshots.RESTORING) }); } if (method === "POST" && path === "") { const body = await readJson(request); if (typeof body.on !== "boolean") refuse(400, "bad_request", "on is true or false"); // Off is said by name, so the Worker's SNAPSHOTS_ALL never turns an account back on that the admin switched off. this.store.setMeta(snapshots.SWITCH, body.on ? "on" : "off"); if (!body.on) this.store.setMeta(snapshots.JOB, null); else await this.keepAlarm(); return json({ on: body.on }); } if (method === "GET" && path === "/manifest") { const params = new URL(request.url).searchParams; const kind = params.get("kind") === "daily" ? "daily" : "full"; const manifest = await this.snapshotManifest(kind, slug, params.get("stamp") ?? ""); if (!manifest) refuse(404, "not_found", "no such snapshot"); return json(manifest); } if (method === "POST" && path === "/run") { // Now, for the proof and the operator: the copy under way, or `kind` started. if (this.snapshotRestoring()) refuse(409, "restore_unfinished", "a restore from snapshots is under way"); const body = await readJson(request).catch(() => ({}) as Record); const kind = body.kind === "full" || body.kind === "daily" ? body.kind : undefined; const budget = Number.isInteger(body.budget_ms) ? Math.min(Math.max(Number(body.budget_ms), 1_000), 25_000) : 20_000; return json(await this.snapshotStep(budget, kind)); } if (path.startsWith("/restore/")) { if (!restore.restoreRoutesOn(this.env)) refuse(404, "not_found", "no such route"); const marker = await this.marker(slug); restore.mustBeFrozen(marker); if (marker?.pending) refuse(409, "restore_unfinished", "a point-in-time restore was asked and not finished"); if (method === "POST" && path === "/restore/begin") return await this.snapshotRestoreBegin(slug, await readJson(request)); if (method === "POST" && path === "/restore/step") return await this.snapshotRestoreStep(slug, await readJson(request).catch(() => ({}) as Record)); if (method === "POST" && path === "/restore/cancel") { const job = this.metaJson(snapshots.RESTORING); if (!job) refuse(409, "no_restore", "no restore from snapshots is under way"); if (job.phase === "lay") refuse(409, "restore_laying", "the account's rows were emptied and are being laid back: step again (a part that failed is tried again), or begin a restore from another copy (POST /v1/admin/snapshots/restore/begin), which checks before it empties"); this.store.setMeta(snapshots.RESTORING, null); return json({ cancelled: true }); } } refuse(405, "method_not_allowed", "GET /snapshots, POST /snapshots {on}, GET /snapshots/manifest?kind=&stamp=, POST /snapshots/run {kind, budget_ms}, POST /snapshots/restore/begin {full, through}, POST /snapshots/restore/step, POST /snapshots/restore/cancel"); } /** * A restore from snapshots (dev and test only, on a frozen account). BEGIN changes nothing (M7): the key must be * there, the weekly full named and the dailies after it (up to `through`) must each carry a manifest whose HMAC holds * and which names this account, kind and stamp, must chain (each daily starting at the version the copy before it * ended), and at least one daily must follow the full (L2). STEP then checks EVERY part (its SHA-256 against the * manifest, and its AES-GCM tag over its place) before a single row goes; only then are the rows emptied and laid * back, and the ledger replayed (M5), the chain restarted (M6). Cancel is open until the rows are emptied; unfreeze * is refused until it is done. */ private async snapshotRestoreBegin(slug: string, body: Record): Promise { // One still checking is cancelled first; one already laying (the rows emptied) may be replaced by a new one, which // checks its own parts before it empties again (RESTORE 2 SERVER 3: never empty and frozen with no way forward). if (this.metaJson(snapshots.RESTORING)?.phase === "verify") refuse(409, "restore_unfinished", "a restore from snapshots is still checking its parts: step it to its end, or cancel it"); this.devicesReady(body); const keys = await this.snapshotKey(false); if (!keys) refuse(409, "no_key", "this account keeps no snapshot key: nothing can be opened"); const fullStamp = text(body.full, "full"); const through = typeof body.through === "string" ? body.through : null; const full = await this.snapshotManifest("full", slug, fullStamp); if (!full) refuse(404, "not_found", "no such weekly snapshot"); if (!(await snapshots.manifestHolds(keys, full, slug, "full", fullStamp))) refuse(409, "manifest_refused", `the weekly ${fullStamp}'s manifest is not this account's as written`); if (!neverAgain.restorable(full.started_at)) refuse(409, "too_old", "a restore reaches back at most 40 days: the never-again ledger covers no more"); const plan: SnapshotRestore["plan"] = [{ kind: "full", stamp: full.stamp, prefix: snapshots.snapshotPrefix("full", slug, full.stamp), parts: full.parts }]; let upto = full.upto; let restoredTo = full.started_at; for (const stamp of (await this.snapshotCopies("daily", slug)).copies) { if (stamp <= full.stamp || (through && stamp > through)) continue; const daily = await this.snapshotManifest("daily", slug, stamp); if (!daily || !(await snapshots.manifestHolds(keys, daily, slug, "daily", stamp))) refuse(409, "manifest_refused", `the daily ${stamp}'s manifest is not this account's as written`); if (daily.base !== upto) refuse(409, "chain_broken", `the daily ${stamp} starts at version ${daily.base}, not ${upto}`); plan.push({ kind: "daily", stamp, prefix: snapshots.snapshotPrefix("daily", slug, stamp), parts: daily.parts }); upto = daily.upto; restoredTo = daily.started_at; } if (plan.length < 2) refuse(409, "full_alone", "a full copy alone is a mix of moments: restore needs the daily after it (none is kept yet)"); // The ledger copied out first (M5): the restore replays it from R2. await this.flushNeverAgain(); if (neverAgain.waiting(this.ctx.storage.sql)) refuse(503, "try_again", "the never-again ledger could not be copied out; nothing was changed"); const job: SnapshotRestore = { phase: "verify", plan, i: 0, j: 0, version_before: this.store.version(), max_version: 0, restored_to: restoredTo, rows: 0, checked: 0, tables: [] }; this.store.setMeta(snapshots.RESTORING, JSON.stringify(job)); return json({ snapshots: plan.length, parts: plan.reduce((a, p) => a + p.parts.length, 0), restored_to: restoredTo, upto, phase: "verify" }); } /** Opens one part of the plan, checked: there, its SHA-256 as the manifest says, its tag holding over its place. */ private async snapshotPartOpened(slug: string, entry: SnapshotRestore["plan"][number], j: number, keys: snapshots.Keys): Promise { const info = entry.parts[j]!; const got = await this.env.MEDIA.get(`${entry.prefix}${info.key}`); if (!got) refuse(409, "part_missing", `${entry.prefix}${info.key} is not there`); const bytes = new Uint8Array(await got.arrayBuffer()); if ((await snapshots.sha256(bytes)) !== info.sha256) refuse(409, "part_refused", `${entry.prefix}${info.key}: its SHA-256 is not the manifest's`); const number = Number(/part-(\d+)\.bin$/.exec(info.key)?.[1] ?? NaN); try { return await snapshots.openPart(keys, snapshots.aadOf(slug, entry.kind, entry.stamp, number), bytes); } catch { refuse(409, "part_refused", `${entry.prefix}${info.key}: its seal does not open as this account's ${entry.kind} ${entry.stamp} part ${number}`); } } private async snapshotRestoreStep(slug: string, body: Record): Promise { const job = this.metaJson(snapshots.RESTORING); if (!job) refuse(409, "no_restore", "begin a restore from snapshots first"); const keys = await this.snapshotKey(false); if (!keys) refuse(409, "no_key", "this account keeps no snapshot key"); const budget = Number.isInteger(body.budget_ms) ? Math.min(Number(body.budget_ms), 25_000) : 20_000; const started = Date.now(); const tables = new Set(job.tables); while (job.i < job.plan.length && Date.now() - started < budget) { const entry = job.plan[job.i]!; if (job.j >= entry.parts.length) { job.i += 1; job.j = 0; continue; } const lines = await this.snapshotPartOpened(slug, entry, job.j, keys); if (job.phase === "verify") { job.checked += 1; } else { this.ctx.storage.transactionSync(() => { for (const raw of lines) { const line = JSON.parse(raw) as snapshots.Line; if (this.store.restoreStoredRow(line, line.toks ? unpackTokens(snapshots.unhex(line.toks)) : null)) job.rows += 1; job.max_version = Math.max(job.max_version, Number(line.version)); tables.add(line.table_id); } }); } job.j += 1; job.tables = [...tables]; this.store.setMeta(snapshots.RESTORING, JSON.stringify(job)); } if (job.i < job.plan.length) return json({ done: false, phase: job.phase, checked: job.checked, rows: job.rows, at: { snapshot: job.i, part: job.j } }); if (job.phase === "verify") { // Every part checked: only now are the rows emptied, in one go with the turn to laying them back. this.ctx.storage.transactionSync(() => { for (const table of ["rows", "links", "blind", "blind_row", "row_counts", "change"]) this.ctx.storage.sql.exec(`DELETE FROM ${table}`); this.store.setMeta(snapshots.RESTORING, JSON.stringify({ ...job, phase: "lay", i: 0, j: 0 } satisfies SnapshotRestore)); }); return json({ done: false, phase: "lay", checked: job.checked, rows: 0, at: { snapshot: 0, part: 0 } }); } // Every part laid: counted again, then what every restore does (the ledger, the version, the generation, the chain). this.ctx.storage.transactionSync(() => { for (const table of job.tables) this.store.recountTable(table); }); const restoredTo = new Date(job.restored_to).toISOString(); const generation = restore.freshGeneration(); const done = await this.afterRestore(slug, Math.max(job.version_before, job.max_version), generation, restoredTo, false, "live"); this.store.setMeta(snapshots.RESTORING, null); await this.carryOn(); console.log(`cottondb: snapshot restore ${slug}: ${job.rows} rows laid back, version ${done.version}; ledger ${JSON.stringify(done.ledger)}`); return json({ done: true, rows: job.rows, checked: job.checked, version: done.version, generation, restored_to: restoredTo, ledger: done.ledger, deletion: done.deletion }); } /** An object holding definitions keeps its alarm set: each pass trims the change log. */ private async keepAlarm(): Promise { if (!this.store.holdsDefinitions("table")) return; const set = await this.ctx.storage.getAlarm(); // A window's end or a request's expiry folds into the alarm: the clean-up comes then (the guard never waits for it). const due = this.unlocks.nextDue({ sql: this.ctx.storage.sql, store: this.store }); // A Connect Claude copy waiting for its connection goes at its time, not at the next hourly pass. const pending = this.agents.nextDue({ sql: this.ctx.storage.sql }); // A delivery kept to be tried again (src/handover.ts) is tried at its time. const handing = handover.nextDue(this.ctx.storage.sql); // ALARM DEAD (live, 28 Nov 2026): an alarm more than a minute past stands where the platform stopped retrying it, // and fires no more; "one is set" would keep it so for ever. It is set afresh, a few seconds out. if (set !== null && set < Date.now() - ALARM_DEAD_MS) { console.error(`cottondb: alarm dead ${this.slug}: stood at ${new Date(set).toISOString()}, set again`); await this.ctx.storage.setAlarm(Date.now() + ALARM_REVIVE_MS); return; } const want = Math.min(set ?? Date.now() + ALARM_EVERY_MS, due ?? Infinity, pending ?? Infinity, handing ?? Infinity); if (set === null || want < set) await this.ctx.storage.setAlarm(want); } /** `run`, marked as `what` (durably, before it starts) so a reset inside names it at the next start. */ private async marked(what: string, run: () => Promise | T): Promise { const key = `${REQUEST_RUNNING}${crypto.randomUUID()}`; this.store.setMeta(key, `${what} begun ${new Date().toISOString()}`); await this.ctx.storage.sync(); try { return await run(); } finally { this.store.setMeta(key, null); } } /** The alarm's pass: each repeating todo whose occurrence passed gets its next, the change log is kept to its window, a Google calendar is pulled, and the next pass is set. */ /** * JOBS OUT PROOF: what this instance's alarm did of each step kind's work, and the steps each kind's job ran, since it * started (GET /v1/admin/jobs; scripts/jobs-out-proof.ts reads them). */ private readonly objectDid = new Map(); private readonly jobSteps = new Map(); /** A step job's work done by the account object itself (on its alarm, or after a request), not by the job. */ private didOnObject(kind: string): void { this.objectDid.set(kind, (this.objectDid.get(kind) ?? 0) + 1); } private inJobStep = false; /** READ COST 4: this instance's last alarm and last shadow step, for GET /v1/admin/order-shadow. */ private alarmLast: { began: string; ended: string | null; ran: string; error: string | null } = { began: "", ended: null, ran: "", error: null }; private shadowLast: { at: string; error: string | null } | null = null; override async alarm(): Promise { // An owner's restore no phone is stepping is stepped by the alarm (src/restore_owner.ts), and nothing else runs. if (await this.ownerRestoreAlarm()) return; // A frozen account (RESTORE 2) runs nothing on its alarm, nor one that cannot say: asked again in a minute. try { await this.frozenGate(); } catch { await this.ctx.storage.setAlarm(Date.now() + 60_000); return; } // A deletion under way takes the alarm whole, unmarked: its last step leaves no storage at all (src/account_delete.ts). if (accountDelete.job(this.ctx.storage.sql)) { // Copied before the pass (L2), while the account is still pending or keeping; and after it only when the pass // kept it (the admin hold's Keep on the date): `flushNeverAgain` copies nothing once an erase is under way. await this.flushNeverAgain(); await this.alarmPass(); await this.flushNeverAgain(); return; } // Marked, and the mark made durable, before any work: if the object is reset inside, the next start says so. The // next alarm is set first, in the same durable write (ALARM DEAD): a throw, or a reset for CPU inside, can never // leave the object with no alarm or one the platform has stopped retrying. The pass sets the real next at its end. this.store.setMeta(ALARM_RUNNING, new Date().toISOString()); this.store.setMeta(ALARM_LAST_BEGAN, new Date().toISOString()); await this.ctx.storage.setAlarm(Date.now() + ALARM_FALLBACK_MS); await this.ctx.storage.sync(); this.alarmLast = { began: new Date().toISOString(), ended: null, ran: "", error: null }; try { // Restore's own small work first, each catching its own failures, so a failing pass never holds it back. await this.flushNeverAgain(); await this.compactNeverAgain(); await this.retryHandovers().catch((error: unknown) => console.error(`cottondb: handover: ${error instanceof Error ? error.message : String(error)}`)); await this.alarmPass(); await this.snapshotAlarm(); } catch (error) { // READ COST 4: a pass that throws (a mailbox, a send, a calendar) never leaves the object with no alarm: the // platform's retries end, and a request would set the next only an hour on. Said, and the alarm comes in a minute. const message = error instanceof Error ? error.message : String(error); console.error(`cottondb: alarm failed ${this.slug}: ${message}`); this.alarmLast.error = message; const at = await this.ctx.storage.getAlarm(); const soon = Date.now() + 60_000; if (at === null || at > soon) await this.ctx.storage.setAlarm(soon); } finally { this.store.setMeta(ALARM_RUNNING, null); this.store.setMeta(ALARM_LAST_ENDED, new Date().toISOString()); this.lastEvent = `alarm (${this.alarmRan || "no bounded job"})`; this.lastEventEnded = Date.now(); this.alarmLast.ended = new Date().toISOString(); this.alarmLast.ran = this.alarmRan; } } private async alarmPass(): Promise { // A deletion under way takes the alarm whole until it is done (src/account_delete.ts). if (accountDelete.job(this.ctx.storage.sql)) { const next = await accountDelete.run(this.deleteHost()); if (next !== null) await this.ctx.storage.setAlarm(Date.now() + next); return; } // First, before any longer job: a ring whose phone did not ack its socket frame is pushed now, should the object // have restarted inside the 2 s it waited (calls.ts `pushWaiting`, CALLS FIX 2). await calling.pushWaiting(this.callHost()).catch(() => {}); calling.sweep(this.ctx.storage.sql); const ringDue = calling.nextWaiting(this.ctx.storage.sql); if (ringDue !== null) this.wants.set("calls", ringDue); else this.wants.delete("calls"); // SLOW READ (26 Nov 2026): which bounded jobs still had more to do, said on every answer until the next alarm // (`cotton-alarm-busy`), so the front Worker's slow-answer line names what a read may have waited behind. const busy: string[] = []; // JOBS OUT W4: with its switch on, the timed sweeps are the job's (the watchdog below asks for its run). if (this.store.holdsDefinitions("table") && !this.stepOn("sweeps")) { this.didOnObject("sweeps"); this.runSweeps(); } // MEASURE GENTLE 2: the bounded jobs, each a step of about 50 ms of work, each caught so that a throw in one never // skips the mail, calendar, sends and the re-arm below. While the object is in use (a request or a pull in the last // BUSY_FOR_MS) one job an alarm, in turn; else every job with more to do. Only when their shared want is reached. const now = Date.now(); const inUse = this.inUse(now); const holds = this.store.holdsDefinitions("table"); const wasCounting = this.store.countsPending(); // Each job: its name, whether it can do anything now (a job that cannot is passed over and keeps its place), its step. const orderIndexWaits = () => this.inUse() && !this.store.indexTooBig(); const jobs: Array<[string, () => boolean, () => boolean]> = holds ? ([ ["changes", () => true, () => this.ctx.storage.transactionSync(() => trimChanges(this.store, new Date(), GENTLE_TRIM).more)], ["acts", () => true, () => this.ctx.storage.transactionSync(() => trimActs(this.store, new Date(), GENTLE_ACTS).more)], // The blind index moved one way, a step an alarm, once the account says so (src/blind.ts). ["blind", () => this.store.meta("blind_oneway") === "on" && blindIndex.indexed(this.ctx.storage.sql), () => this.ctx.storage.transactionSync(() => blindIndex.moveStep(this.ctx.storage.sql))], // A session's mirrored prompts kept to their 30 days (src/erase.ts). ["prompts", () => this.personal(), () => this.ctx.storage.transactionSync(() => keepPrompts(this.store, this.ctx.storage.sql, new Date(), GENTLE_PROMPTS).more)], // What a big object holds, measured a bounded step at a time for storage_summary (src/storage_measure.ts). ["measure", () => true, () => this.ctx.storage.transactionSync(() => this.store.measureStorage(new Date()))], // AUDIT D: older rows' list links filled into list_links a page at a time, so a merge seeks instead of reading tables. ["list_links", () => !this.store.listLinksReady(), () => this.ctx.storage.transactionSync(() => this.store.listLinksStep())], // An order index a big table's list asked for (Store.selectOrdered). A CREATE INDEX is one statement and // cannot be split: made only while nobody uses the object; while someone does, it waits, still asked. (A file // too big for any is not held back: buildOrderIndex only drops what was asked, at once.) ["order_index", () => !orderIndexWaits(), () => this.ctx.storage.transactionSync(() => this.store.buildOrderIndex())], // The row counts' recount, its place in meta. ["recount", () => true, () => this.store.carryCounts(RECOUNT_STEPS, (step) => this.ctx.storage.transactionSync(step))], // JOBS OUT W1..: a sweep whose step job is switched on is the job's, never the alarm's (nor owed here); JOBS OUT C3: // the measure and the recount are the storage_count job's. ] as Array<[string, () => boolean, () => boolean]>).filter(([name]) => !(stepJobs.isKind(name) && this.stepOn(name)) && !(STORAGE_COUNT.includes(name) && this.stepOn("storage_count"))) : []; let gentleWait = 0; this.alarmRan = ""; if (!jobs.length) { // No tables, no bounded jobs: no want of theirs is kept (LIVE SLOW 3: one kept here would wake the alarm each second). this.wants.delete("gentle"); this.gentleOwed = []; } else if (this.due("gentle", now)) { const owed = new Set(this.gentleOwed); const ran: string[] = []; const one = (name: string, step: () => boolean): boolean => { this.didOnObject(name === "measure" || name === "recount" ? "storage_count" : name); let left: boolean; try { left = step(); } catch (error) { // Its step is tried again at the bounded jobs' next turn; the rest of this alarm goes on. console.log(`cottondb: alarm job ${name} failed ${this.slug}: ${error instanceof Error ? error.message : String(error)}`); left = true; } ran.push(name); return left; }; if (inUse && this.paced()) { // LIVE SLOW 3, fair turns: one slot an alarm, every job in turn. A job that cannot do anything now is passed // over (keeping what it owed); a job that owed nothing and finds nothing to do does not use the slot either. for (let k = 0; k < jobs.length; k++) { const i = (this.gentleTurn + k) % jobs.length; const [name, ready, step] = jobs[i]!; if (!ready()) continue; const had = owed.has(name); const left = one(name, step); if (left) owed.add(name); else owed.delete(name); if (left || had) { this.gentleTurn = (i + 1) % jobs.length; break; } } } else { for (const [name, ready, step] of jobs) { if (!ready()) continue; if (one(name, step)) owed.add(name); else owed.delete(name); } } // An order index still asked while it waits stays owed. if (orderIndexWaits() && this.store.orderIndexAsked()) owed.add("order_index"); this.alarmRan = ran.join(","); this.gentleOwed = jobs.map(([name]) => name).filter((name) => owed.has(name)); // Their wait counts from the end of this alarm (set below, before the re-arm). gentleWait = this.gentleOwed.length ? (inUse ? BUSY_WAIT_MS : GENTLE_WAIT_MS) : 0; if (!gentleWait) this.wants.delete("gentle"); } // READ COST 4 (live, 28 Nov 2026: shadows asked on the owner's object, no row laid in 3.5 hours): the shadows' fill is // not one of the turns above, where an object always owing other work gave it one alarm in eight; it runs on every // alarm that is its time, one bounded step (GENTLE_SHADOW_ROWS), with its own want: SHADOW_BUSY_MS while in use. // JOBS OUT S1: with its switch on, the step job beside the object fills them (the watchdog asks for a lost run). if (holds && this.store.shadowsFilling() && this.due("shadow", now) && !this.stepOn("order_shadow")) { let left = true; const at = new Date().toISOString(); try { this.didOnObject("order_shadow"); left = this.ctx.storage.transactionSync(() => this.store.shadowStep(GENTLE_SHADOW_ROWS)); this.shadowLast = { at, error: null }; } catch (error) { const message = error instanceof Error ? error.message : String(error); console.log(`cottondb: alarm job order_shadow failed ${this.slug}: ${message}`); this.shadowLast = { at, error: message }; } this.alarmRan = this.alarmRan ? `${this.alarmRan},order_shadow` : "order_shadow"; if (left) this.wants.set("shadow", Date.now() + (inUse ? SHADOW_BUSY_MS : GENTLE_WAIT_MS)); else this.wants.delete("shadow"); } else if (!this.store.shadowsFilling() || this.stepOn("order_shadow")) this.wants.delete("shadow"); if (this.wants.has("shadow")) busy.push("order_shadow"); for (const name of this.gentleOwed) busy.push(name); const recounting = this.gentleOwed.includes("recount"); this.alarmBusy = busy.join(","); if (wasCounting && !recounting && this.store.countsProgress().ready) console.log(`cottondb: row_counts recount ${this.slug}: done, ${this.store.countsProgress().steps} steps`); if (recounting) { const p = this.store.countsProgress(); console.log(`cottondb: row_counts recount ${this.slug}: ${p.left.length} tables left, ${p.left[0]?.table ?? "-"} at ${p.head_rows} rows, ${p.steps} steps`); } // A film folder an erase left that R2 did not take at the time. await this.dropMedia(); // A personal object with a Google grant pulls its calendar on the same alarm, at the pull's own cadence (src/google_calendar.ts). let next = ALARM_EVERY_MS; // JOBS OUT C1: with `jobs.calendar_sync` on, the pull is a step job beside the object (the watchdog below asks for // a run when an account is due) and the alarm only comes at the pull's cadence to watch; off, here as before. if (this.stepOn("calendar_sync")) { // Due now: the watchdog has a run asked for (and looks again in WATCH_EVERY_MS); due later: the alarm comes then. const due = this.calendarDueIn(Date.now()); if (due) next = Math.min(next, Math.max(due, 1000)); } else if (this.personal() && google.readAccounts(this.store).length && !this.calendarPulling) { this.didOnObject("calendar_sync"); const pull = await this.calendarPull(); if (pull !== null) next = Math.min(next, pull); } // A pass that said it has more carries on at CARRY_ON_MS, and does nothing when another's want brings the alarm // sooner (MEASURE GENTLE 2: each job's own want, decided in one place); a pass with nothing owed runs on any alarm // and its own state decides, as before. const carryOn = async (name: string, pass: () => Promise<{ more: boolean } | null | undefined>): Promise => { if (!this.due(name, Date.now())) { // A want set while nobody used the object, which is in use now: it waits as the bounded jobs do (MEASURE GENTLE). const at = this.wants.get(name); if (at !== undefined && this.inUse(Date.now())) this.wants.set(name, Math.max(at, Date.now() + BUSY_WAIT_MS)); return; } let more: boolean; try { more = !!(await pass())?.more; } catch (error) { // LIVE SLOW 3: a throw in one pass skips none of the others nor the re-arm; it is tried again at CARRY_ON_MS. console.log(`cottondb: alarm pass ${name} failed ${this.slug}: ${error instanceof Error ? error.message : String(error)}`); more = true; } // While the object is in use a carry-on waits as the bounded jobs do (MEASURE GENTLE): AUDIT D's walks of changed // rows say more on any busy object, and must not bring the alarm every 30 s while a person uses it. if (more) this.wants.set(name, Date.now() + (this.inUse(Date.now()) ? BUSY_WAIT_MS : calendarEngine.CARRY_ON_MS)); else this.wants.delete(name); }; // The calendar engine's pass rides the same alarm: the backfill carries on soon while events wait. await carryOn("calendar", () => this.calendarPass()); // So does the book files' pass: a book whose EPUB is not read yet, or whose file had not come an hour ago. // With JOBS OUT M3's switch on, the job beside the object reads them (the watchdog below asks for its run). if (!this.stepOn("book_files")) await carryOn("books", () => this.bookFilePass()); else this.wants.delete("books"); // So does the artwork engine's: rows still waiting for a cover or a poster, and a source that failed a day ago. // Send's pass: offers past their time go, a large Keep's copy carries on, and what it copied lands. // JOBS OUT 5: with its switch on, Send's pass runs beside the object (the watchdog below asks for its run). if (this.personal() && !this.stepOn("send")) { // JOBS OUT PROOF: Send's work done by the object itself (only when there was some). if (send.owes(this.ctx.storage.sql)) this.didOnObject("send"); const sends = await send.alarmPass(this.sendHost()); if (sends.more) next = Math.min(next, 1000); } // Cotton's fetcher: each mailbox given to Cotton read for new mail, and its history carried on (src/mail/fetcher.ts). // The test Worker reaches no mail server: its tests run each pass against their own fake one (fetchMailPass). let watching = false; if (this.personal() && this.mailJobsOn()) { // JOBS OUT 1: the account's switch on, no mailbox is read here; the watchdog keeps each one's run on the queue. const look = await mailJob.watchdog(this.jobHost()); if (look !== null) next = Math.min(next, look); } else if (this.personal() && this.env.ENV_LABEL !== "test") { const fetched = await this.fetchMailPass(); if (fetched.next !== null) next = Math.min(next, fetched.next); // A mailbox read up to date is then watched (IDLE) for a window, below, and the alarm comes again at once. watching = mailFetch.accounts(this.ctx.storage.sql).some((a) => a.state === "idle"); } // With JOBS OUT M2's switch on, the job beside the object fills them (the watchdog below asks for its run). if (!this.stepOn("artwork")) await carryOn("artwork", () => this.artworkPass()); else this.wants.delete("artwork"); // JOBS OUT M1: the step jobs switched on are run beside the object; the alarm only asks again for a run the queue lost. if (this.personal()) { const look = await stepJobs.watchdog(this.stepHost()); if (look !== null) next = Math.min(next, look); } const windowDue = this.unlocks.nextDue({ sql: this.ctx.storage.sql, store: this.store }); if (windowDue !== null) next = Math.min(next, Math.max(windowDue - Date.now(), 1000)); const pendingDue = this.agents.nextDue({ sql: this.ctx.storage.sql }); if (pendingDue !== null) next = Math.min(next, Math.max(pendingDue - Date.now(), 1000)); // MEASURE GENTLE 2: every kept want (the bounded jobs' GENTLE_WAIT_MS, or BUSY_WAIT_MS while the object is in use; // the carry-on passes' CARRY_ON_MS) folds in here: the next alarm is the earliest of all. if (gentleWait) this.wants.set("gentle", Date.now() + gentleWait); for (const at of this.wants.values()) next = Math.min(next, Math.max(at - Date.now(), 1000)); // Last, so nothing above waits on it: IDLE on each mailbox read up to date, for one window; then again at once. if (watching) { await this.fetchMailWatch(); next = Math.min(next, 1000); } await this.ctx.storage.setAlarm(Date.now() + next); } /** * JOBS OUT 4, the dead-man check (28 Nov 2026: the owner's alarm stood set in the past for six hours and nothing ran). * Asked by the Worker's cron (src/alarm_watch.ts), never by this object's own alarm: how the alarm stands and when a * pass last began and ended; an alarm missing, or standing more than ALARM_STALE_MS in the past, is set again in * five seconds and said. Reads no table; an object that holds no database is left alone. */ async alarmWatch(now: number = Date.now()): Promise { const at = await this.ctx.storage.getAlarm(); const iso = (ms: number | null) => (ms === null ? null : new Date(ms).toISOString()); const answer: AlarmWatch = { slug: this.slug, alarm_at: iso(at), last_began: this.store.meta(ALARM_LAST_BEGAN), last_ended: this.store.meta(ALARM_LAST_ENDED), running: this.store.meta(ALARM_RUNNING), rearmed: false }; if (!this.store.holdsDefinitions("table") && this.store.meta("kind") === null) return answer; // An account whose own code keeps its alarm, and may leave it unset on purpose, is never re-armed from outside: // a deletion under way (pending, held and kept on its date, erasing, done), an owner's restore, a frozen account. if (accountDelete.job(this.ctx.storage.sql)) return { ...answer, left: "deleting" }; let marker: restore.Marker | null; try { marker = await this.marker(); } catch { return { ...answer, left: "restore_unknown" }; } if (marker?.owner) return { ...answer, left: "restoring" }; if (marker?.frozen) return { ...answer, left: "frozen" }; if (alarmStale(at, now)) { await this.ctx.storage.setAlarm(now + 5_000); answer.rearmed = true; console.log(`cottondb: alarm watch re-armed ${this.slug}: stood at ${iso(at) ?? "none"}, last pass began ${answer.last_began ?? "never"} ended ${answer.last_ended ?? "never"}`); } return answer; } /** The moment and the zone a repeating todo's next occurrence is worked out in. */ private now(engine: Engine): recurrence.Now { return { at: engine.clock.now, zone: this.meta().timezone }; } /** * A new number's personal database, made by the directory (src/directory.ts): * the meta and the whole personal kit — its own tool and tables, its tools * and the shell's boards, so its phone's fan has them — at the * kit's version. An object that already is this database is left as it is. */ async provision(args: { databaseId: string; slug: string; phone: string }): Promise { await this.frozenGate(); await this.prepare(args); if (this.store.meta(KIT_PENDING)) this.finishKit(); } /** * AUDIT F (the stranger audit's timing oracle, 28 Nov 2026): a new number's database as asking for a code needs it, * and no more: its meta (the owner's number, its id), a few rows, so the code's answer takes as long for a number * new to Cotton as for one already on it. The kit is laid by `finishKit` once a code is proved (signIn). An object * that already is this database is left as it is; an erased one is never written. */ async prepare(args: { databaseId: string; slug: string; phone: string }): Promise { await this.frozenGate(); if (accountDelete.erased(this.ctx.storage.sql)) throw new Error(`the object ${args.slug} was erased`); if (this.personal() && this.store.meta("database_id") === args.databaseId) return; if (this.store.meta("kind") !== null || this.store.holdsDefinitions("table")) throw new Error(`the object ${args.slug} already holds another database`); this.slug = args.slug; this.ctx.storage.transactionSync(() => { for (const [key, value] of Object.entries({ name: "Personal", currency: "INR", timezone: "Asia/Kolkata", kind: "personal", owner_phone: args.phone, database_id: args.databaseId, slug: args.slug })) this.store.setMeta(key, value); // Born locked (coordinator, 25 Nov 2026; LOCKS_AT_BIRTH): with Your Claude's standing grant on, memory and the session tables are // sealed from the first row. No grant and no row exist yet, so nothing waits on gate 1 or 2: sealed at once. if (this.env.AGENT_GRANT === "on" && this.env.LOCKS_AT_BIRTH === "on") { const at = new Date().toISOString(); this.store.setMeta(memoryLock.META, JSON.stringify({ on_at: at, by: "birth", sealing_at: at })); this.store.setMeta(openTablesLock.META, JSON.stringify({ on_at: at, by: "birth", sealing_at: at })); } // BORN LOCKED 2 (publishing checklist, 28 Nov 2026): the passwords from the first row, on their own lock. No grant ever // carries their key (agent.ts NEVER), so it waits on no gate and on no grant: LOCKS_AT_BIRTH alone. if (this.env.LOCKS_AT_BIRTH === "on") this.store.setMeta(openTablesLock.SECRET_META, JSON.stringify({ on_at: new Date().toISOString(), by: "birth" })); this.store.setMeta(KIT_PENDING, new Date().toISOString()); this.store.bump(); }); } /** AUDIT F: what the directory asks of a database already made when its number asks for a code: nothing, as cheaply as prepare. */ async ready(): Promise { // At the gate as prepare is (RESTORE 2 SERVER 2, M1), so the two cost the same. await this.frozenGate(); return this.personal(); } /** The whole personal kit laid on a prepared database (its own tool and tables, its tools, the shell's boards), at the kit's version. */ private finishKit(): void { this.install([...KIT.own, ...KIT.tools], KIT.tables, { flavour: "personal", name: "Personal", public_views: {}, fan: null }); this.ctx.storage.transactionSync(() => { this.store.replaceDefinitions("board", KIT.boards); this.store.setMeta(kitKeep.KIT_GIVEN, JSON.stringify(kitKeep.givenBy(KIT))); this.store.setMeta(kitKeep.KIT_LAID, JSON.stringify(kitKeep.laidBy(KIT))); this.store.setMeta(kitKeep.KIT_LAID_TOOLS, JSON.stringify(kitKeep.laidToolsBy(KIT))); this.store.setMeta(kitKeep.KIT_LAID_TABLES, JSON.stringify(kitKeep.laidLooksBy(KIT))); this.store.setMeta(kitKeep.KIT_VERSION, kitKeep.kitVersion(KIT)); this.store.setMeta(KIT_PENDING, null); }); } /** A prepared database (AUDIT F) answers the code steps before its kit is laid; any other door still waits for it. */ private installedOrPending(): void { if (!this.store.holdsDefinitions("table") && !(this.personal() && this.store.meta(KIT_PENDING))) this.refuseAsMissing(); } /** * A personal object takes what the kit this Worker ships brings since the kit * it was last brought to: every tool, board and table it was never given, * and nothing over what it holds (src/kit_keep.ts). One that holds no tables * yet is not made: the kit waits for it. */ private keepKit(): boolean { if (!this.personal()) return false; const version = kitKeep.kitVersion(KIT); if (this.store.meta(kitKeep.KIT_VERSION) === version) return false; if (!this.store.holdsDefinitions("table")) return false; this.ctx.storage.transactionSync(() => { // Held as retired, never served (src/retired.ts, KEEP_RULE 15): out of the served set before the pass reads it; the rows stay. const gone = retired.retiring({ tool: this.store.definitions("tool"), table: this.store.definitions("table") }, retired.readRetired(this.store.meta(retired.KIT_RETIRED))); if (gone.tables.length || gone.tools.length) { this.store.setMeta(retired.KIT_RETIRED, JSON.stringify(gone.retired)); this.store.removeDefinitions("table", gone.tables); this.store.removeDefinitions("tool", gone.tools); console.log(`cottondb: kit keep ${this.slug}: held as retired ${[...gone.tables, ...gone.tools].join(", ")}`); } const held = { tool: this.store.definitions("tool"), board: this.store.definitions("board"), table: this.store.definitions("table") }; const { docs, given, laid, laidTools, laidLooks, notices } = kitKeep.brought( held, KIT, (table) => this.store.held(table), kitKeep.readGiven(this.store.meta(kitKeep.KIT_GIVEN)), kitKeep.readLaid(this.store.meta(kitKeep.KIT_LAID)), kitKeep.readLaid(this.store.meta(kitKeep.KIT_LAID_TOOLS)), kitKeep.readLaidLooks(this.store.meta(kitKeep.KIT_LAID_TABLES)), ); const links = this.definitions().linkColumns(); let changed = 0; for (const kind of ["tool", "board", "table"] as const) if (docs[kind].length) changed += this.store.mergeDefinitions(kind, docs[kind]); if (docs.table.length) { this.definitions(); this.store.relink(links); } if (changed || gone.tables.length || gone.tools.length) this.store.bump(); this.store.setMeta(kitKeep.KIT_GIVEN, JSON.stringify(given)); this.store.setMeta(kitKeep.KIT_LAID, JSON.stringify(laid)); this.store.setMeta(kitKeep.KIT_LAID_TOOLS, JSON.stringify(laidTools)); this.store.setMeta(kitKeep.KIT_LAID_TABLES, JSON.stringify(laidLooks)); // What this keep said (a table look kept as the person edited it), once: the admin export reads it, the log says it. this.store.setMeta(kitKeep.KIT_NOTICES, JSON.stringify(notices)); for (const notice of notices) console.log(`cottondb: kit keep ${this.slug}: ${notice}`); this.store.setMeta(kitKeep.KIT_VERSION, version); this.store.setMeta(kitKeep.RETIRED_PACKAGE_STAMP, null); }); return true; } // ── the calendar engine (src/calendar_engine.ts) ─────────────────────── /** The pass running now, and whether another was asked for while it ran. */ private calendarRunning: Promise | null = null; private calendarAgain = false; /** The embedder kinds are judged with: Workers AI, or on a development object the one named by KIND_EMBEDDINGS_URL; none, and nothing is judged. */ private embedder(): classify.Embedder | null { if (this.env.AI) return classify.workersAi(this.env.AI); if (this.env.KIND_EMBEDDINGS_URL && !isProduction(this.env)) return classify.servedAt(this.env.KIND_EMBEDDINGS_URL); return null; } /** The object as the classifier and the calendar engine write it: one transaction and version a pass, none when nothing changed. */ private classifyHost(): classify.ClassifyHost { return { store: this.store, sql: this.ctx.storage.sql, write: (fn) => this.ctx.storage.transactionSync(() => { const before = this.store.version(); const version = this.store.bump(); const engine = this.engine(); engine.journal = new Journal(this.store, null, "calendar", "act"); const outcome = new Outcome_(); const answer = fn(engine, version, outcome); // A pass that wrote nothing moves no version. if (!outcome.changed.length) this.store.setMeta("version", String(before)); return answer; }), }; } /** * One pass of the calendar engine over a personal object's events; null * where there is none to pass over. A test hands it its own embedder. */ async calendarPass(embedder: classify.Embedder | null = this.embedder()): Promise<(calendarEngine.PassAnswer & { linked: number }) | null> { await this.frozenGate(); if (!this.personal()) return null; const event = this.store.definitions("table").find((t) => t.id === calendarEngine.EVENT); if (!event) return null; this.definitions(); return calendarEngine.pass(this.classifyHost(), calendarEngine.vocabulary(event), embedder); } /** * One pass of the classifier over `table`'s choice column `column` * (src/classify.ts); null where the table's definition carries no * vocabulary for it. The calendar engine runs the event's kind through * its own pass (`calendarPass`), which leaves a moved occurrence to its * master. */ async classifyPass(table: string, column: string, embedder: classify.Embedder | null = this.embedder()): Promise { await this.frozenGate(); const vocab = classify.vocabulary(this.store.definitions("table").find((t) => t.id === table), column); if (!vocab) return null; this.definitions(); return classify.classify(this.classifyHost(), vocab, embedder); } /** The alarm comes round soon: a pass stopped at its bound carries on. */ /** * After a request: an index a read asked for, or a shadow still filling, is the alarm's to make soon (never the * request's); with JOBS OUT S1's switch on, a shadow is the step job's, and a run is asked for instead. */ private async shadowsOwed(): Promise { const filling = this.store.shadowsFilling(); if (filling && this.stepOn("order_shadow")) { await stepJobs.kick(this.stepHost(), "order_shadow").catch((error: unknown) => console.error(`cottondb: order_shadow job ${this.slug}: ${error instanceof Error ? error.message : String(error)}`)); if (this.store.orderIndexAsked()) await this.carryOn(); return; } if (this.store.orderIndexAsked() || filling) await this.carryOn(); } private async carryOn(): Promise { const at = await this.ctx.storage.getAlarm(); const soon = Date.now() + calendarEngine.CARRY_ON_MS; // A dead alarm (past by more than a minute) is set again too (ALARM DEAD). if (at === null || at > soon || at < Date.now() - ALARM_DEAD_MS) await this.ctx.storage.setAlarm(soon); } /** A pass off the request that asked for it: one at a time, and one more when asked while one ran; a pass that stopped at its bound carries on at the alarm. */ private kickCalendar(): void { // The request it rides on was answered: the engine's own refusal is said, never the request's. try { this.startCalendar(); } catch (error) { console.error("cottondb: calendar engine", error instanceof Error ? error.message : String(error)); } } private startCalendar(): void { const host = this.classifyHost(); if (!this.store.definitions("table").some((t) => t.id === calendarEngine.EVENT)) return; // What needs no model is settled in the request itself: the people, and the occurrences' kinds. const people = calendarEngine.linkPeople(host); const embedder = this.embedder(); const event = this.store.definitions("table").find((t) => t.id === calendarEngine.EVENT); if (!embedder || !calendarEngine.judging(host, calendarEngine.vocabulary(event))) { calendarEngine.inherit(host); if (people.more) void this.carryOn(); return; } if (this.calendarRunning) { this.calendarAgain = true; return; } const run = async (): Promise => { do { this.calendarAgain = false; const answer = await this.calendarPass(embedder); if (answer?.more) await this.carryOn(); } while (this.calendarAgain); }; this.calendarRunning = run().finally(() => { this.calendarRunning = null; }); this.ctx.waitUntil(this.calendarRunning); } // ── the artwork engine (src/artwork.ts) ──────────────────────────────── /** The pass running now, and whether another was asked for while it ran. */ private artworkRunning: Promise | null = null; private artworkAgain = false; /** What the artwork engine fetches with: the Worker's own fetch; none where the object is told to fetch nothing (`ARTWORK=off`, the test pool, which has no internet). */ /** A test's stand-in for the outside picture sites (the test Worker has ARTWORK off); never set outside a test. */ private artworkFetch: artwork.Fetcher | null = null; private artworkFetcher(): artwork.Fetcher | null { if (this.artworkFetch) return this.artworkFetch; if (this.env.ARTWORK === "off") return null; return (url, init) => fetch(url, init); } /** The object as the artwork engine writes it: one transaction and version a fill, said as `artwork`; its pictures kept as uploads are. */ private artworkHost(): artwork.ArtworkHost { const databaseId = this.databaseId(); const slug = this.meta().slug; return { store: this.store, sql: this.ctx.storage.sql, databaseId, write: (fn) => this.ctx.storage.transactionSync(() => { const before = this.store.version(); const version = this.store.bump(); const engine = this.engine(); engine.journal = new Journal(this.store, null, "artwork", "act"); const outcome = new Outcome_(); const answer = fn(engine, version, outcome); if (!outcome.changed.length) this.store.setMeta("version", String(before)); return answer; }), keep: async (key, bytes, contentType) => { this.roomToWrite(); // A person's picture the object fetched is sealed as it arrives, to their arrival key (R6 with R2): never kept open. const kept = await asArrived(databaseId, arrivalPublic((table, id) => this.store.get(table, id)), key, bytes, contentType, SEALED_FILE_TYPE); await storeMedia(this.env, bucketKey(key, databaseId, slug), kept.bytes, kept.contentType, this.mediaBudget()); }, }; } /** * One pass of the artwork engine over a personal object's books and films; * null where there is nothing to pass over or nothing to fetch with. A * test hands it its own fetch. */ async artworkPass(fetcher: artwork.Fetcher | null = this.artworkFetcher()): Promise { if (!this.inJobStep) this.didOnObject("artwork"); await this.frozenGate(); if (!this.personal() || !fetcher || !this.store.meta("database_id")) return null; this.definitions(); return artwork.pass(this.artworkHost(), fetcher); } // ── a book's own file (src/book_file.ts) ─────────────────────────────── private bookFileRunning: Promise | null = null; private bookFileAgain = false; /** The object as the book files' pass reads and writes it: a fill in one transaction and version, said as `book_file`; a file read by range from the media. */ private bookFileHost(): bookFile.BookFileHost { const databaseId = this.databaseId(); const slug = this.meta().slug; return { store: this.store, sql: this.ctx.storage.sql, write: (fn) => this.ctx.storage.transactionSync(() => { const before = this.store.version(); const version = this.store.bump(); const engine = this.engine(); engine.journal = new Journal(this.store, null, "book_file", "act"); const outcome = new Outcome_(); const answer = fn(engine, version, outcome); if (!outcome.changed.length) this.store.setMeta("version", String(before)); return answer; }), open: async (key) => { let at: string; try { at = bucketKey(key, databaseId, slug); } catch { throw new bookFile.Unreadable(`${key} is not this database's media`); } const head = await this.env.MEDIA.head(at); if (!head) return null; if (isSealedType(head.httpMetadata?.contentType)) throw new bookFile.Sealed(`${key} is sealed on the person's device`); return { size: head.size, read: async (offset, length) => { const part = await this.env.MEDIA.get(at, { range: { offset, length } }); if (!part) throw new Error(`${key} went from the media while it was read`); return new Uint8Array(await part.arrayBuffer()); }, }; }, }; } /** One pass of the book files over a personal object's books; null where there is nothing to pass over. */ async bookFilePass(now = Date.now()): Promise { if (!this.inJobStep) this.didOnObject("book_files"); await this.frozenGate(); if (!this.personal() || !this.store.meta("database_id")) return null; this.definitions(); return bookFile.pass(this.bookFileHost(), now); } /** A pass off the request that wrote a book: one at a time, one more when asked while one ran; a pass that stopped at its bound carries on at the alarm. */ private kickBookFiles(): void { // JOBS OUT M3: with its switch on, the files are the job's to read; here a run is only asked for. if (this.stepOn("book_files")) { this.ctx.waitUntil(stepJobs.kick(this.stepHost(), "book_files").catch((error: unknown) => console.error("cottondb: book files job", error instanceof Error ? error.message : String(error)))); return; } try { if (!this.store.meta("database_id") || !bookFile.pending(this.bookFileHost())) return; if (this.bookFileRunning) { this.bookFileAgain = true; return; } const run = async (): Promise => { do { this.bookFileAgain = false; const answer = await this.bookFilePass(); if (answer?.more) await this.carryOn(); } while (this.bookFileAgain); }; this.bookFileRunning = run() .catch((error: unknown) => console.error("cottondb: book files", error instanceof Error ? error.message : String(error))) .finally(() => { this.bookFileRunning = null; }); this.ctx.waitUntil(this.bookFileRunning); } catch (error) { // The request it rides on was answered: the pass's own refusal is said, never the request's. console.error("cottondb: book files", error instanceof Error ? error.message : String(error)); } } // ── books (src/books.ts) ─────────────────────────────────────────────── /** What find_book asks Open Library with: the artwork fetcher, or a test's stub set in place through runInDurableObject. */ bookFetcher: artwork.Fetcher | null = null; /** How find_book waits before asking Open Library again: a timer, or a test's own. */ bookWait: books.Wait = books.timer; /** The database's own day, in its own zone: the day a book is started, finished or added. */ private today(engine: Engine): string { return localDate(new Date(engine.clock.now), this.meta().timezone); } /** A books act is the owner's, on a personal database that holds the book table. */ private bookAct(caller: Caller, fn: () => unknown): void { if (!this.personal()) refuse(404, "not_personal", "books live in the personal database"); if (caller.role !== "owner") refuse(403, "owner_only", "only the owner keeps their books"); if (!this.store.definitions("table").some((t) => t.id === books.BOOK)) refuse(404, "no_books", "this database has no book table"); fn(); } /** `find_book` asks Open Library before its write (asking is asynchronous, the write is not); null for any other act. */ private async bookPrepare(caller: Caller, act: string, args: Record): Promise { if (act !== "find_book") return null; const fetcher = this.bookFetcher ?? ((url: string, init?: RequestInit) => fetch(url, init)); // The same gate as the write, before anything is fetched or kept. this.bookAct(caller, () => undefined); this.definitions(); return books.prepareFind(this.artworkHost(), args, fetcher, this.bookWait); } // ── films (src/films.ts) ─────────────────────────────────────────────── /** What find_film asks TMDB with: the Worker's own fetch, or a test's stub set in place through runInDurableObject. */ filmFetcher: artwork.Fetcher | null = null; /** A films act is the owner's, on a personal database that holds the film table. */ private filmAct(caller: Caller, fn: () => unknown): void { if (!this.personal()) refuse(404, "not_personal", "films live in the personal database"); if (caller.role !== "owner") refuse(403, "owner_only", "only the owner keeps their films"); if (!this.store.definitions("table").some((t) => t.id === films.FILM)) refuse(404, "no_films", "this database has no film table"); fn(); } /** `find_film` asks TMDB before its write, and `film_converted` finds its stream in the media (both asynchronous, the write is not); null for any other act. */ private async filmPrepare(caller: Caller, act: string, args: Record): Promise { if (act !== "find_film" && act !== "film_converted") return null; // The same gate as the write, before anything is fetched or kept. this.filmAct(caller, () => undefined); this.definitions(); if (act === "find_film") return films.prepareFind(this.artworkHost(), args, this.filmFetcher ?? ((url: string, init?: RequestInit) => fetch(url, init)), this.env.TMDB_API_KEY); // SERVER 27: a film's files are a kind only the owner's devices write and read (AVATAR SEAL 4), so only they say one // is converted; a token is refused before anything is looked up, the same answer whether the stream is held. if (caller.tokenId) refuse(403, "sealed_kind", "a film's stream is sent by the owner's devices, and only they say it is converted"); const converted = films.convertedArgs(this.store, args, this.databaseId()); if (!(await this.env.MEDIA.head(bucketKey(converted.file, this.databaseId(), this.meta().slug)))) refuse(404, "no_stream", `the media hold no ${converted.file}: send the stream before saying it is converted`); return converted; } // ── fetch (src/fetch.ts) ─────────────────────────────────────────────── /** A fetch act is the owner's (the phone, an assistant over MCP, the Mac's owner token), on a personal database that holds the fetch table. */ private fetchAct(caller: Caller, fn: () => unknown): void { if (!this.personal()) refuse(404, "not_personal", "downloads live in the personal database"); if (caller.role !== "owner") refuse(403, "owner_only", "only the owner fetches links"); if (!this.store.definitions("table").some((t) => t.id === fetches.FETCH)) refuse(404, "no_downloads", "this database has no fetch table"); fn(); } private meetingAct(caller: Caller, fn: () => unknown): void { if (!this.personal()) refuse(404, "not_personal", "recordings live in the personal database"); if (caller.role !== "owner") refuse(403, "owner_only", "only the owner's devices turn recordings into text"); if (!this.store.definitions("table").some((t) => t.id === meetings.MEETING)) refuse(404, "no_meetings", "this database has no meetings table"); fn(); } /** `GET /v1/meetings/waiting?for=mac|phone|service`: the recordings waiting for that transcriber (src/meetings.ts `waiting`), the Mac's poll. */ private meetingsWaiting(caller: Caller, params: URLSearchParams): Response { this.installed(); this.meetingAct(caller, () => undefined); return json({ rows: meetings.waiting(this.store, meetings.transcriberOf(params.get("for"))) }); } /** `GET /v1/fetch/pending[?machine=]`: the queued downloads, oldest first, and those the Mac holds (src/fetch.ts `pending`): the Mac fetcher's poll. */ private fetchPending(caller: Caller, params: URLSearchParams): Response { this.installed(); this.fetchAct(caller, () => undefined); return json(fetches.pending(this.store, params.get("machine")?.trim() || null)); } /** `GET /v1/fetch/again`: the done downloads whose films keep no original, and the counts `pnpm fetch:again` says (src/fetch.ts `againPlan`): ids and counts, never a link or a title. */ private fetchAgainPlan(caller: Caller): Response { this.installed(); this.fetchAct(caller, () => undefined); const defs = this.definitions(); return json(fetches.againPlan(this.store, (table) => Boolean(defs.table(table)))); } /** * `GET /v1/films/pending`: the films and episodes waiting for the Mac * (src/films.ts `pending`), the Mac importer's one read beside the media; * it converts each and says film_converted through the plain `/v1/act`. */ private filmsPending(caller: Caller): Response { if (!this.personal()) refuse(404, "not_personal", "films live in the personal database"); if (caller.role !== "owner") refuse(403, "owner_only", "the films waiting for the Mac are the owner's"); this.installed(); const defs = this.definitions(); return json({ rows: films.pending(this.store, (table) => Boolean(defs.table(table))) }); } /** * `GET /v1/films/subtitles/asked`: the films and episodes the phone asked * subtitles for (src/films.ts `subtitlesAsked`), `film:subtitles --queue`'s * one read before it opens the rows named. */ private filmsSubtitlesAsked(caller: Caller): Response { if (!this.personal()) refuse(404, "not_personal", "films live in the personal database"); if (caller.role !== "owner") refuse(403, "owner_only", "the films asking for subtitles are the owner's"); this.installed(); const defs = this.definitions(); return json({ rows: films.subtitlesAsked(this.store, (table) => Boolean(defs.table(table))) }); } /** * `GET /v1/films/find?id=`: one film or episode by its id or * an id's prefix, with the clear columns it plays from (src/films.ts * `findFilm`), `film:open`'s read before it opens that one row. */ private filmsFind(caller: Caller, params: URLSearchParams): Response { if (!this.personal()) refuse(404, "not_personal", "films live in the personal database"); if (caller.role !== "owner") refuse(403, "owner_only", "the films are the owner's"); this.installed(); const id = (params.get("id") ?? "").trim(); if (id.length < 4) refuse(400, "bad_request", "name the film by its id, or at least its first 4 characters: id="); const defs = this.definitions(); return json({ rows: films.findFilm(this.store, (table) => Boolean(defs.table(table)), id) }); } /** A pass off the request that wrote a book or a film: one at a time, and one more when asked while one ran; a pass that stopped at its bound carries on at the alarm. */ private kickArtwork(): void { // JOBS OUT M2: with its switch on, the pictures are the job's to fetch; here a run is only asked for. if (this.stepOn("artwork")) { this.ctx.waitUntil(stepJobs.kick(this.stepHost(), "artwork").catch((error: unknown) => console.error("cottondb: artwork job", error instanceof Error ? error.message : String(error)))); return; } try { const fetcher = this.artworkFetcher(); if (!fetcher || !this.store.meta("database_id") || !artwork.pending(this.artworkHost())) return; if (this.artworkRunning) { this.artworkAgain = true; return; } const run = async (): Promise => { do { this.artworkAgain = false; const answer = await this.artworkPass(fetcher); if (answer?.more) await this.carryOn(); } while (this.artworkAgain); }; this.artworkRunning = run() .catch((error: unknown) => console.error("cottondb: artwork engine", error instanceof Error ? error.message : String(error))) .finally(() => { this.artworkRunning = null; }); this.ctx.waitUntil(this.artworkRunning); } catch (error) { // The request it rides on was answered: the engine's own refusal is said, never the request's. console.error("cottondb: artwork engine", error instanceof Error ? error.message : String(error)); } } /** * A personal object names its owner as a person in People: the one whose * phone is the sign-in number, made when nobody carries it (src/owner.ts). * Settled before every request it answers, so a merged or binned owner is * followed by the next one. */ /** The store's version when the owner's sealed link was last refused for want of the arrival key (keepOwner). */ private ownerWaits: number | null = null; private async keepOwner(): Promise { if (!this.personal() || !this.store.holdsDefinitions("table")) return; // Linked already, as on nearly every request: nothing below would change it, and reading the definitions costs the object megabytes of parsing. if (owner.linkedOwner(this.store)) return; // Refused for want of the arrival key, and nothing written since: asking again could only be refused again, after // four reads of every definition and a write rolled back (LIVE CPU 2, 23 Nov 2026). Any write, the key's among // them, moves the version, and the next request asks again. if (this.ownerWaits !== null && this.ownerWaits === this.store.version()) return; // People sealed: the owner's person is made sealed at arrival, or waits for the arrival key (src/owner.ts `linkOwnerSealed`). if (this.definitions().table("person")?.seal) { try { await owner.linkOwnerSealed({ store: this.store, defines: (table) => Boolean(this.definitions().table(table)), writeSealed: (fn) => this.writeSealing((engine) => (engine.journal = new Journal(this.store, null, "owner", "act")), fn), }); } catch (error) { if (!(error instanceof Refused && error.code === "no_arrival_key")) throw error; this.ownerWaits = this.store.version(); } return; } owner.linkOwner({ store: this.store, defines: (table) => Boolean(this.definitions().table(table)), write: (fn) => this.ctx.storage.transactionSync(() => { const engine = this.engine(); engine.journal = new Journal(this.store, null, "owner", "act"); fn(engine, this.store.bump(), new Outcome_()); }), }); } /** What the directory checks before it enters an object made before it. */ identity(): { databaseId: string | null; ownerPhone: string | null; kind: string | null } { return { databaseId: this.store.meta("database_id"), ownerPhone: this.store.meta("owner_phone"), kind: this.store.meta("kind") }; } // ── routing ──────────────────────────────────────────────────────────── private async route(request: Request): Promise { const url = new URL(request.url); const path = url.pathname; const method = request.method; if (path.startsWith("/v1/admin/")) return this.admin(request, path.slice("/v1/admin".length)); // STRANGER BLIND (coordinator, 23 Nov 2026): a database that does not exist answers the assistant's connect, its // documents and /mcp as a personal one answers a stranger, so neither says whether a database is there. if (path === "/mcp" && (this.personal() || this.absent())) return this.mcp(request); if (OAUTH_PATH.test(path) && (this.personal() || this.absent())) return handleOAuth(request, path, this.oauthHost(request)); if (method === "POST" && path === "/internal/mcp-call" && this.personal()) return this.forwarded(request); // A background job's door (JOBS OUT 1): its own credential, never a caller's; short answers only (src/mail/fetch_job.ts). // A slug with no personal database answers as a shut door does (JOBS OUT 3, L-d: stranger blind), its body unread. // A step job's door (JOBS OUT M1, src/step_jobs.ts): one bounded step a call, its own credential. if (path.startsWith("/v1/jobs/step/")) { const kind = path.slice("/v1/jobs/step/".length); return json(this.personal() ? await stepJobs.door(this.stepHost(), request, kind) : await stepJobs.shut(this.env, request, kind)); } if (path.startsWith("/v1/jobs/mail/")) return json(this.personal() ? await mailJob.door(this.jobHost(), request, path.slice("/v1/jobs/mail/".length)) : await mailJob.shut(this.env, request, path.slice("/v1/jobs/mail/".length))); // Google's answer comes back in the person's browser, with no bearer: the state it carries is the proof (src/google.ts). // Google's arrival only names the account it goes into; the person's Connect tap (a POST) trades it (src/connect_confirm.ts). if ((method === "GET" || method === "POST") && path === google.CALLBACK_PATH && this.personal()) { const asked = await confirm.callbackUrl(request, url); if (confirm.wantsConfirming(request, asked) && (await google.awaiting(this.store, asked.searchParams.get("state") ?? ""))) { return confirm.confirmPage("Google Calendar", confirm.masked(this.store.meta("owner_phone")), google.CALLBACK_PATH, asked); } return google.callback(this.googleHost(), asked); } // Spotify's the same way (src/spotify.ts). if ((method === "GET" || method === "POST") && path === spotify.CALLBACK_PATH && this.personal()) { const asked = await confirm.callbackUrl(request, url); if (confirm.wantsConfirming(request, asked) && (await spotify.awaiting(this.store, asked.searchParams.get("state") ?? ""))) { return confirm.confirmPage("Spotify", confirm.masked(this.store.meta("owner_phone")), spotify.CALLBACK_PATH, asked); } return spotify.callback(this.spotifyHost(), asked); } if (method === "GET" && path === "/v1/definitions") return this.definitionsAnswer(request); if (method === "POST" && path === "/v1/code") return this.code(request); if (method === "POST" && path === "/v1/sign-in") return this.signIn(request); // The allowlist's change is never locked, so a phone can always undo a lockout: the person key's signature is its guard. // AUDIT B (attacker 1): where no database is, the change is answered as a real door answers a stranger's (STRANGER // BLIND): the same checks, and no person key to hold it against, so nothing is kept. if (method === "POST" && path === "/v1/allowlist" && (this.personal() || this.absent())) return this.changeAllowlist(request); const caller = await this.caller(request); this.writers.set(request, caller.who?.deviceId ?? null); // RESTORE 2 (L4): a write naming the generation its copy is built from is held to it, whatever its route; one naming // none (assistants, tokens, the Mac, an older build) is not. Only once the caller is someone (RESTORE 2 SERVER 3): a // stranger learns nothing from a 409 (RESTORE-2-CONTRACT.md 3). const said = request.headers.get(restore.GENERATION_HEADER); if (said !== null && method !== "GET" && method !== "HEAD" && (caller.who || caller.tokenId || caller.admin)) { let fields: { generation: string; restored_to?: string } | null = null; try { fields = this.generationFields(); } catch { // an erased object keeps no generation: its own door answers } if (fields && said !== fields.generation) { if (request.body) await request.arrayBuffer().catch(() => undefined); return restore.generationMoved(fields.generation, fields.restored_to ?? null); } } // STRANGER BLIND: a personal database's pass and acts are its own people's; to anyone else, as where no database is, // they say only "sign in first" (a pass from nothing used to answer a stranger with the database's version). // So are the families only a signed-in device reaches (ways back in that begin from a phone already signed in, // approvals, passkeys, chat, invitations, sends, shared lists, agents' chats, calls): each refused a caller with no // credential at all in words of its own, which a database that does not exist never said (24 Nov 2026). A caller // that presents a credential of anyone's (`who`, a token) is the family's own to answer. if ((this.personal() || this.absent()) && caller.role === "public" && !caller.who && !caller.tokenId && ((method === "GET" && path === "/v1/sync") || (method === "POST" && path === "/v1/act") || SIGNED_FAMILIES.test(path))) refuse(401, "not_signed_in", "sign in first"); // A token on a device route is noted; with token scopes on it reaches none but /v1/act's mint and revoke (an act is // noted and checked by its name in actAnswer). ROUTES-AUDIT findings 3, 5, 8 and 9. if (caller.tokenId && !(method === "POST" && path === "/v1/act")) { this.noteTokenRoute(caller.tokenId, tokenScopes.routeOf(method, path)); // CIRCLE GAPS 1 (28 Nov 2026): the Circle is the person's own. An assistant's token (an OAuth connection or an // allow-list key), token scopes on or off, never adds, asks, accepts, removes, blocks, invites, redeems, sends or // shares on their behalf, and never reads who is in it: no window opens the Circle, as none opens a device key. if (CIRCLE_FAMILIES.test(path)) refuse(403, "circle_is_theirs", "an assistant does not act in the Circle or share: the person does, from their phone"); // A key that carries what it may do (src/key_allow.ts) reaches no device route, token scopes on or off: its rows // are read and written at /mcp under its list. With outward it may ASK for the three acts on the outside world, // each allowed on the owner's phone (src/owner_asks.ts); without, they are refused too. if (caller.allow) { if (method === "GET" && path.startsWith("/v1/asks/")) return json(ownerAsks.readFor(this.ctx.storage.sql, this.store, decodeURIComponent(path.slice("/v1/asks/".length)), caller.tokenId)); if (caller.allow.outward) { const asked = await this.ownerAsk(caller.tokenId, request, method, path); if (asked) return asked; } else if (ownerAsks.outwardRoute(method, path)) refuse(403, "key_allow", "this key does not act on the outside world: the owner turns outward on for it from the phone"); refuse(403, "key_allow", "this key speaks at /mcp, and at /v1/act for the acts its list allows: no device route"); } if (this.tokenScopesOn()) { // Three acts on the outside world the owner allows on the phone instead (src/owner_asks.ts, finding 8). if (method === "GET" && path.startsWith("/v1/asks/")) return json(ownerAsks.readFor(this.ctx.storage.sql, this.store, decodeURIComponent(path.slice("/v1/asks/".length)), caller.tokenId)); const asked = await this.ownerAsk(caller.tokenId, request, method, path); if (asked) return asked; refuse(403, "token_scopes", tokenScopes.DEVICE_REFUSAL); } } if (method === "POST" && (path === "/v1/asks/allow" || path === "/v1/asks/refuse") && this.personal()) return this.ownerAnswers(caller, request, path); // Keep asked again once the account is kept (a phone's retry after a Keep that finished): kept, nothing to do. if (method === "POST" && path === "/v1/account/keep" && this.personal() && caller.who && !caller.tokenId) return json({ kept: true }); // The person deletes their account, from a signed-in device of theirs, with a fresh code (src/account_delete.ts). if (method === "POST" && accountDelete.DELETE_PATH.test(path) && this.personal()) return this.deleteAccount(caller, request, path); if (method === "GET" && path === "/v1/allowlist" && this.personal()) return this.allowlistAnswer(caller); if (this.importerRoute(caller, method, path)) allowlist.guard(this.ctx.storage.sql, request); if (method === "GET" && path === "/v1/sync") { // A pass page (from nothing, or along a pass's cursor) is marked; a phone's ordinary pull is not. const pass = url.searchParams.has("cursor") || url.searchParams.get("since") === "0"; const answer = pass ? await this.marked(`GET /v1/sync ${url.searchParams.has("cursor") ? "cursor" : "since=0"} limit=${url.searchParams.get("limit") ?? "-"}`, () => this.sync(caller, url.searchParams)) : this.sync(caller, url.searchParams); await this.spaceTell().catch(() => undefined); return answer; } if (method === "GET" && path === "/v1/held") return this.held(caller, url.searchParams); if (method === "GET" && path === "/v1/keys") return json(this.accountKeys(caller)); if (method === "GET" && path === "/v1/landed") return this.landed(caller, url.searchParams); if (method === "GET" && path === "/v1/blind") return this.blind(caller, url.searchParams); if (method === "GET" && path === "/v1/older") return this.older(caller, url.searchParams); if (method === "GET" && path === "/v1/rows") return this.rowsById(caller, url.searchParams); if (method === "GET" && path.startsWith("/v1/data/")) return this.dataAnswer(caller, path, url.searchParams); if (method === "GET" && path === "/v1/bin") return this.bin(caller, url.searchParams); if (method === "GET" && path === "/v1/media-plain" && this.personal()) return this.mediaPlain(caller, url.searchParams); if (method === "GET" && path === "/v1/seal/twins") return this.sealTwins(caller, url.searchParams); if (method === "GET" && path === "/v1/secret/rewrap") return json(await this.secretsToRewrap(caller)); if (method === "POST" && path === "/v1/secret/rewrap") return json(await this.secretsRewrapped(caller, await readJson(request))); // A device that never syncs (the Mac's importer) names itself in the query, once a pass (GET /v1/me). this.fileCaller(caller, url.searchParams, method === "GET" && path === "/v1/me"); if (method === "GET" && path === "/v1/me") return this.me(caller); if (method === "POST" && path === "/v1/sign-out") return this.signOut(caller); // A new device's sign-in asks, decided here by another signed-in device of the same number (src/approval.ts). if (this.personal() && path.startsWith("/v1/approvals")) return this.approvals(caller, request, method, path); // The person's Cotton passkeys, added and removed from a signed-in device (src/passkey.ts). if (this.personal() && (path === "/v1/passkeys" || path.startsWith("/v1/passkeys/"))) return this.passkeys(caller, request, method, path, url); // Cotton Calling's routes, on a personal object, for its own signed-in phones (src/calling/calls.ts). if (this.personal()) { const called = await calling.route(this.callHost(), caller.who?.deviceId ?? null, request, url); if (called) return called; // Cotton to Cotton messages (src/chat/chat.ts): the same phones, the same hop. const chatted = await chat.route(this.chatHost(), caller.who?.deviceId ?? null, request, url); if (chatted) return chatted; // An agent in a chat: the person's phones say which agents are in which chats and hand them what is said (src/chat/agents.ts). const agented = await agentChats.route(this.agentHost(), caller.who?.deviceId ?? null, request, url); if (agented) return agented; // Send: a copy of a record to one of this person's people (src/send/send.ts). const sent = await send.route(this.sendHost(), caller.who?.deviceId ?? null, request, url); if (sent) { // JOBS OUT 5: a send's call (a large Keep, an offer) may leave Send's pass work: its run is asked for now. if (this.stepOn("send")) this.ctx.waitUntil(stepJobs.kick(this.stepHost(), "send").catch((error: unknown) => console.error("cottondb: send job", error instanceof Error ? error.message : String(error)))); return sent; } // Days' invitations between people on Cotton: sealed boxes routed object to object (src/invite.ts). const invited = await invite.route(this.inviteHost(), { deviceId: caller.who?.deviceId ?? null, owner: caller.role === "owner" }, request, url); if (invited) return invited; // Shared lists: sealed on the phones to the list's own key (src/send/shared.ts). const listed = await shared.route(this.sharedHost(), caller.who?.deviceId ?? null, request, url); if (listed) return listed; // Secrets between people: sealed boxes routed object to object (src/send/secrets.ts, keys/CONTRACT.md "The Worker"). const secreted = await secrets.route(this.secretHost(), { deviceId: caller.who?.deviceId ?? null, owner: caller.role === "owner" }, request, url); if (secreted) return secreted; // The circle: getting back in with the help of people the person trusts (src/recovery_circle.ts). const circled = await circle.route(this.circleHost(), { deviceId: caller.who?.deviceId ?? null, owner: caller.role === "owner", token: Boolean(caller.tokenId) }, request, url); if (circled) return circled; // The way back in: a recovery code, a platform key (src/recovery.ts). const recovered = await recovery.route(this.recoveryHost(), { deviceId: caller.who?.deviceId ?? null, owner: caller.role === "owner", token: Boolean(caller.tokenId) }, request, url); if (recovered) return recovered; } if (method === "POST" && path === "/v1/act") { const body = await readJson(request); const big = bulkOf(body); return big ? await this.marked(`POST /v1/act ${big}`, () => this.act(caller, body)) : await this.act(caller, body); } if (method === "POST" && path === "/v1/photos") return this.putPhoto(caller, request); if (method === "POST" && path === "/v1/import/messages") return this.marked("POST /v1/import/messages", async () => this.importMessages(caller, await readJson(request))); if (method === "POST" && path === "/v1/import/message_changes") return this.importMessageChanges(caller, await readJson(request)); if (method === "POST" && path === "/v1/import/calls") return this.importCalls(caller, await readJson(request)); if (method === "POST" && path === "/v1/import/photos") return await this.importPhotos(caller, await readJson(request)); if (method === "GET" && path === "/v1/outbox") return this.outbox(caller, url.searchParams); if (method === "GET" && path === "/v1/space") { if (caller.role !== "owner" || !this.personal()) refuse(403, "owner_only", "only the owner reads their space"); return json(this.spaceAnswer()); } if (method === "POST" && path === "/v1/space/invited-by") { // The new person names who invited them (SPACE.md): once, within their first 30 days, an account older than theirs. if (caller.role !== "owner" || !caller.who || !this.personal()) refuse(403, "owner_only", "only the owner names who invited them"); if (this.spaceMode() === "off") refuse(409, "space_off", "naming who invited you is not open yet"); const { number } = await readJson(request); if (typeof number !== "string" || !/^\+[1-9]\d{6,14}$/.test(number)) refuse(400, "bad_number", "number: the inviter's number, as +"); const said = await directory(this.env).spaceInvitedBy(this.meta().slug, number); if ("refused" in said) refuse(said.refused.status, said.refused.code, said.refused.message); return json({ ok: true }); } if (method === "GET" && path === "/v1/films/pending") return this.filmsPending(caller); if (method === "GET" && path === "/v1/films/subtitles/asked") return this.filmsSubtitlesAsked(caller); if (method === "GET" && path === "/v1/films/find") return this.filmsFind(caller, url.searchParams); if (method === "GET" && path === "/v1/fetch/pending") return this.fetchPending(caller, url.searchParams); if (method === "GET" && path === "/v1/fetch/again") return this.fetchAgainPlan(caller); if (method === "GET" && path === "/v1/meetings/waiting") return this.meetingsWaiting(caller, url.searchParams); if (path === "/v1/media/missing" || path.startsWith("/v1/media/")) return this.media(caller, request, url); if (google.GOOGLE_PATH.test(path) && this.personal()) return this.google(caller, request, path); if (path.startsWith("/v1/mail/") && this.personal()) return this.mailRoute(caller, request, path); if (spotify.SPOTIFY_PATH.test(path) && this.personal()) return this.spotify(caller, request, path); refuse(404, "not_found", `nothing answers ${method} ${path}`); } private async caller(request: Request): Promise { const token = bearer(request); if (isAdminToken(this.env, token)) return { role: "owner", person: null, admin: true, who: null }; if (token?.startsWith("ctn_") && this.personal()) { // A Cotton MCP token: only an owner one acts here (minting, revoking, importing); the rest speak only at /mcp. const mcp = await this.mcpCaller(token); if (!mcp?.scopes.has("owner")) refuse(403, "owner_only", "this token speaks only at /mcp"); this.keyPace(mcp.tokenId); return { role: "owner", person: null, admin: false, who: null, tokenId: mcp.tokenId, presented: { token, hash: await sha256Hex(token) }, connector: this.connectorToken(mcp.tokenId), allow: mcp.allow ?? null }; } const who = await whoIs(this.store, new Date(), token); if (!who) return { role: "public", person: null, admin: false, who: null }; this.seeDevice(who.deviceId, request); return { role: who.person.role, person: who.person, admin: false, who }; } /** When each device was last written as seen, and the header it last sent: kept so a request writes only when either moves. */ private readonly devicesSeen = new Map(); /** A phone's request: its device seen, and the generation it named on a write (src/restore.ts, the phone review's gap). */ private seeDevice(device: string, request: Request): void { const header = request.headers.get(restore.GENERATION_HEADER); const said = header !== null && request.method !== "GET" && request.method !== "HEAD" ? header : null; const now = Date.now(); const held = this.devicesSeen.get(device); if (held && now - held.at < restore.SEEN_EVERY_MS && (said === null || said === held.said)) return; try { restore.noteDevice(this.ctx.storage.sql, device, now, said); this.devicesSeen.set(device, { at: now, said: said ?? held?.said ?? null }); } catch (error) { console.error(`cottondb: device seen: ${error instanceof Error ? error.message : String(error)}`); } } // ── Cotton Calling's hop (src/calling/calls.ts): only an object or a room calls these, by RPC ── /** Another person's object asks this one to ring its phones. */ /** * Whether another person's object reaches this one: not while its account is set to be deleted or erased * (src/account_delete.ts). Its people see it as one that does not take them; a delivery is refused, so the * sender knows it did not land. */ private reachable(): boolean { return this.personal() && !accountDelete.job(this.ctx.storage.sql); } /** A delivery the sender must know did not land (a message, a share, a trusted person's ask): refused. A word that only tells (a ring, a withdrawal, an answer) is dropped quietly instead, so one account in its thirty days never stops a sender telling the rest. */ private refuseWhileDeleting(): void { if (accountDelete.job(this.ctx.storage.sql)) refuse(410, "account_deleted", "This account cannot be reached."); } async callRing(ring: calling.Ring): Promise { await this.frozenGate(); if (this.reachable()) await calling.ringIn(this.callHost(), ring); } /** A room this object rang for ended, or was answered on one of its phones: the others stop. */ async callStop(room: string, stop: StopReason | null, except: string | null): Promise { await this.frozenGate(); await calling.stopRing(this.callHost(), room, stop, except); } // ── Cotton to Cotton messages' hop (src/chat/chat.ts): only another object calls these, by RPC ── /** The keys a sender seals for: this object's phones', each under its handle, to someone its owner accepted (src/chat/gate.ts). */ async chatKeys(from: string): Promise { await this.frozenGate(); if (!this.reachable()) return []; return chat.keysAsked(this.chatHost(), from); } /** One one-time key for each of these devices of this object's (c2, src/chat/chat.ts `claimPrekeys`), taken as it goes, for someone its owner accepted. */ async chatClaim(handles: string[], from: string): Promise> { await this.frozenGate(); // Not while the account is being deleted (AUDIT FIX B1); a blocked or never-accepted asker gets nothing (src/chat/gate.ts). if (!this.reachable() || !Array.isArray(handles)) return {}; return chat.claimAsked(this.chatHost(), handles.filter((h) => typeof h === "string").slice(0, chat.BOXES_MAX), from); } /** Another person's object asks whether this owner has its owner among their people (Send's waiting, src/send/send.ts `people`). */ /** Another person's object says its account is being erased (the Circle's "left Cotton", src/chat/chat.ts `goneIn`). */ async chatGone(from: string): Promise { await this.frozenGate(); if (this.personal()) await chat.goneIn(this.chatHost(), from); } async chatAccepts(number: string): Promise { await this.frozenGate(); if (!this.reachable()) return false; return chat.accepts(this.ctx.storage.sql, number); } /** Another person's object leaves its owner's ask: they added this owner by number (src/chat/chat.ts `chat_ask`). */ async chatAskIn(ask: chat.Ask): Promise { await this.frozenGate(); this.refuseWhileDeleting(); if (this.personal()) await chat.askIn(this.chatHost(), ask); } /** The invited person's object hands back this owner's Circle invitation (src/chat/circle_invite.ts). */ async circleRedeem(r: { code: string; secret: string; from: string; name: string | null }): Promise<{ number: string; name: string | null } | null> { await this.frozenGate(); this.refuseWhileDeleting(); if (!this.personal()) return null; return chat.circleRedeemed(this.chatHost(), r); } /** Another person's object takes its owner's ask back: they removed this owner. */ async chatAskWithdrawn(from: string): Promise { await this.frozenGate(); if (this.reachable()) await chat.askWithdrawn(this.chatHost(), from); } /** Another person's object hands over an envelope's boxes for this object's phones. */ /** Someone this owner waited for has a chat device now (src/chat/chat.ts `joinedIn`). */ async chatJoined(word: { ticket: string }): Promise { await this.frozenGate(); if (this.reachable()) await chat.joinedIn(this.chatHost(), word); } async chatDeliver(delivery: chat.Delivery): Promise { await this.frozenGate(); this.refuseWhileDeleting(); if (this.personal()) await chat.deliverIn(this.chatHost(), delivery); } // ── A shaken report (src/feedback.ts): only the open door and another object call these, by RPC ── /** The open door asks whose device credential a report came with: this personal object's owner, by number and name, or null. */ /** Whether this object vouches for a credential reading a published database (src/published.ts): any live sign-in here. */ async publishedReader(token: string): Promise { await this.frozenGate(); try { return (await whoIs(this.store, new Date(), token)) !== null; } catch { return false; } } async feedbackSender(token: string): Promise { await this.frozenGate(); if (!this.reachable()) return null; try { const who = await whoIs(this.store, new Date(), token); if (!who || who.person.role !== "owner") return null; return { number: who.person.phone, name: who.person.name }; } catch { return null; } } /** A report for Cotton's own database: written here when this is that object, the owner told. */ async feedbackIn(ask: feedback.FeedbackAsk): Promise { await this.frozenGate(); this.slug = this.store.meta("slug") ?? feedback.FEEDBACK_SLUG; return feedback.take(this.feedbackHost(), ask); } /** The Cotton object says a report came in: this owner's phones are told. Whether one was pushed. */ async feedbackAlert(alert: feedback.FeedbackAlert): Promise { await this.frozenGate(); if (!this.reachable()) return false; return feedback.alertPhones(this.ctx.storage.sql, this.env, alert); } private feedbackHost(): feedback.FeedbackHost { return { sql: this.ctx.storage.sql, env: this.env, slug: this.store.meta("slug") ?? this.slug, kind: this.store.meta("kind"), ownerPhone: this.store.meta("owner_phone"), defines: (table) => Boolean(this.definitions().table(table)), held: (id) => this.store.any(feedback.TABLE, id) !== null, write: (fn) => this.ctx.storage.transactionSync(() => { const version = this.store.bump(); const engine = this.engine(); engine.journal = new Journal(this.store, null, "feedback", "act"); return fn(engine, version, new Outcome_()); }), salt: () => { const held = this.store.meta("feedback_salt"); if (held) return held; const made = randomToken(16); this.store.setMeta("feedback_salt", made); return made; }, tellOwner: async (number, alert) => { const slug = await directory(this.env).lookup(number); if (!slug || slug === this.slug) return false; const owner = this.env.BUSINESS.get(this.env.BUSINESS.idFromName(slug), { locationHint: "apac" }) as unknown as { feedbackAlert(a: feedback.FeedbackAlert): Promise }; return owner.feedbackAlert(alert); }, }; } // ── Days' invitations (src/invite.ts): only another object calls this, by RPC ── /** One of this person's people hands over an invitation, its calling off, or an answer, sealed. */ async inviteDeliver(delivery: invite.InviteDelivery): Promise { await this.frozenGate(); this.refuseWhileDeleting(); if (this.personal()) await invite.deliverIn(this.inviteHost(), delivery); } private inviteHost(): invite.InviteHost { return { sql: this.ctx.storage.sql, env: this.env, slug: this.store.meta("slug") ?? this.slug, ownerPhone: this.store.meta("owner_phone"), waitUntil: (work) => this.background(work), }; } // ── Send's hop (src/send/send.ts): only another object calls these, by RPC ── /** Another person's object hands over a send for this person. */ async sendDeliver(delivery: send.SendDelivery): Promise { await this.frozenGate(); this.refuseWhileDeleting(); if (this.personal()) await send.deliverIn(this.sendHost(), delivery); } /** The receiver's object says what became of a send this person made. */ /** Another person's object asks this person's sharing key for its owner: answered only to one of this person's people, else a made-up key (src/send/send.ts `keyAsked`). */ async sendKey(from: string): Promise { await this.frozenGate(); if (!this.reachable()) return null; return send.keyAsked(this.sendHost(), from); } /** Another person's object asks this person's signing key (the Circle's safety number): as `sendKey` (src/send/send.ts `signAsked`). */ async sendSignKey(from: string): Promise { await this.frozenGate(); if (!this.reachable()) return null; return send.signAsked(this.sendHost(), from); } async sendAnswered(answer: send.SendAnswer): Promise { await this.frozenGate(); if (this.reachable()) send.answeredIn(this.sendHost(), answer); } /** The sender's object took back a send it made to this person. */ async sendTakenBack(taken: { from: string; id: string }): Promise { await this.frozenGate(); if (this.reachable()) await send.takenBackIn(this.sendHost(), taken.from, taken.id); } /** A trusted person's half, parked here by one of this person's people (src/recovery.ts). */ async helpKept(from: string, box: string): Promise { await this.frozenGate(); return this.reachable() ? recovery.helpKept(this.recoveryHost(), from, box) : false; } /** One of this person's people asks for help back in from a new device. */ async helpAsked(from: string, ask: { id: string; device_key: string; code?: string; commit?: string }): Promise { await this.frozenGate(); this.refuseWhileDeleting(); if (this.personal()) await recovery.helpAsked(this.recoveryHost(), from, ask); } /** The person this one trusts set their nonce on an ask from a new device of this person. */ async helpOpened(from: string, opened: { id: string; nonce: string }): Promise { await this.frozenGate(); if (this.reachable()) recovery.helpOpened(this.recoveryHost(), from, opened); } /** The person who helped this one back in can help no more (src/recovery.ts `helpGone`). */ async helpGone(from: string): Promise { await this.frozenGate(); if (this.reachable()) recovery.helpGone(this.recoveryHost(), from); } /** One of this person's people no longer counts on them to help them back in: the half kept goes. */ async helpDropped(from: string): Promise { await this.frozenGate(); if (this.reachable()) recovery.helpDropped(this.recoveryHost(), from); } /** * A device signed in only by SMS in the last two days (TRUSTED RECOVERY BUILD 2, review LOW): its first credential * is that young, and its own vault_key row holds no wrap (no other device approved it, no way back in opened yet). */ private freshDevice(deviceId: string): boolean { const first = this.ctx.storage.sql.exec<{ at: number | null }>("SELECT MIN(issued_at) AS at FROM sessions WHERE device_id = ?", deviceId).one().at; const young = first !== null && Number(first) * 1000 > Date.now() - 48 * 60 * 60 * 1000; const holds = this.store.list(VAULT_KEY_TABLE, { column: "device_id", equals: deviceId }).some((r) => Boolean(r.data.wrapped_vmk)); return young && !holds; } /** * The ways back in's chores, on wake and after recovery calls: tellings kept from a Remove or Block tried again, and, * once a day, pieces this person holds for someone whose account the directory no longer has let go. The directory * is asked about those accounts alone, by id (BUILD 3, LOW). */ private async recoveryChores(): Promise { if (!this.personal()) return; await recovery.retryTells(this.recoveryHost()); await circle.retryTells(this.circleHost()); const day = new Date().toISOString().slice(0, 10); if (this.store.meta("recovery_swept") === day) return; this.store.setMeta("recovery_swept", day); const dir = directory(this.env); for (const { account } of this.ctx.storage.sql.exec<{ account: string }>("SELECT DISTINCT account FROM recovery_circle_held").toArray()) { if (await dir.accountGone(account)) circle.dropped(this.circleHost(), { account, number: "" }, {}); } for (const { peer } of this.ctx.storage.sql.exec<{ peer: string }>("SELECT peer FROM recovery_help_held").toArray()) { if ((await dir.lookup(peer).catch(() => "?")) === null) recovery.helpDropped(this.recoveryHost(), peer); } } /** This account's ways back in, as counts, told the directory when they changed (src/recovery.ts `flowReport`). */ private async reportRecoveryFlow(): Promise { if (!this.personal()) return; const databaseId = this.store.meta("database_id"); if (!databaseId) return; const report = recovery.flowReport({ sql: this.ctx.storage.sql, now: () => Date.now() }); const said = JSON.stringify(report); if (this.store.meta("recovery_flow_told") === said) return; await directory(this.env).recoveryFlow(databaseId, report); this.store.setMeta("recovery_flow_told", said); } /** The erase's directory step: the people this one helps, and this one's helper, are told (src/recovery.ts `leave`). */ private async leaveRecovery(): Promise { return [...(await recovery.leave(this.recoveryHost())), ...(await circle.leave(this.circleHost()))]; } // ── The circle's hop (src/recovery_circle.ts): only another object calls these, by RPC ── async circleLive(from: circle.From, live: { setup: string }): Promise { await this.frozenGate(); if (this.reachable()) circle.liveNow(this.circleHost(), from, live); } async circleLost(from: circle.From, lost: { setup: string }): Promise { await this.frozenGate(); if (this.reachable()) await circle.lost(this.circleHost(), from, lost); } async circleKept(from: circle.From, kept: { setup: string; index: number; box: string; live?: string | null }): Promise { await this.frozenGate(); if (this.reachable()) await circle.kept(this.circleHost(), from, kept); } async circleDropped(from: circle.From, dropped: { setup?: string }): Promise { await this.frozenGate(); if (this.reachable()) circle.dropped(this.circleHost(), from, dropped); } async circleAccepted(from: circle.From, answer: { setup: string; accepted: boolean }): Promise { await this.frozenGate(); if (this.reachable()) await circle.accepted(this.circleHost(), from, answer); } async circleRequested(from: circle.From, request: { request: string; setup: string; index: number; device_key: string; ends_at: number }): Promise { await this.frozenGate(); if (!this.reachable()) return; circle.requested(this.circleHost(), from, request); this.ctx.waitUntil(this.tellCircleDevices("help", null).catch(() => undefined)); } async circleCommitted(from: circle.From, compare: { request: string; commit: string }): Promise { await this.frozenGate(); if (this.reachable()) circle.committed(this.circleHost(), from, compare); } async circleOpened(from: circle.From, opened: { request: string; nonce: string }): Promise { await this.frozenGate(); if (this.reachable()) circle.opened(this.circleHost(), from, opened); } async circleRevealed(from: circle.From, revealed: { request: string; nonce: string }): Promise { await this.frozenGate(); if (this.reachable()) await circle.revealed(this.circleHost(), from, revealed); } async circleApproved(from: circle.From, approved: { request: string; sealed: string }): Promise { await this.frozenGate(); if (this.reachable()) circle.approved(this.circleHost(), from, approved); } async circleStopped(from: circle.From, stopped: { request: string; by: "person" | "helper" | "link" }): Promise { await this.frozenGate(); if (this.reachable()) circle.stopped(this.circleHost(), from, stopped); } async circleStopFor(from: circle.From, stop: { request: string }): Promise { await this.frozenGate(); if (this.reachable()) await circle.stopFor(this.circleHost(), from, stop); } async circleGone(from: circle.From): Promise { await this.frozenGate(); if (this.reachable()) await circle.gone(this.circleHost(), from); } /** The SMS link's Stop, from the open host (src/open.ts): the token is the whole proof. */ async recoveryStopByLink(token: string): Promise { await this.frozenGate(); if (!this.personal()) return false; return circle.stopByLink(this.circleHost(), token); } /** A push to every device of the person that takes one, but `except` (src/chat/push.ts `recoveryAlert`). */ private async tellCircleDevices(what: "started" | "stopped" | "help" | "weak", except: string | null): Promise { const devices = this.ctx.storage.sql .exec<{ device_id: string; platform: "ios" | "android" | null; token: string | null; topic: string | null; sandbox: number }>("SELECT device_id, platform, token, topic, sandbox FROM chat_device WHERE device_id != ?", except ?? "") .toArray(); await Promise.all( devices.map(async (d) => { if (!d.platform || !d.token) return; const outcome = await recoveryAlert(this.env, { platform: d.platform, token: d.token, topic: d.topic ?? "", sandbox: d.sandbox === 1 }, what); if (outcome === "gone") this.ctx.storage.sql.exec("UPDATE chat_device SET token = NULL, platform = NULL, topic = NULL WHERE device_id = ?", d.device_id); }), ); } /** A plain text to this person's number with the Stop link, where a Twilio Messaging Service is set up. */ private async textStop(link: string): Promise { const to = this.store.meta("owner_phone"); const { TWILIO_ACCOUNT_SID: sid, TWILIO_AUTH_TOKEN: auth, TWILIO_MESSAGING_SID: service } = this.env; if (!to || !sid || !auth || !service) return false; const body = new URLSearchParams({ To: to, MessagingServiceSid: service, Body: `Cotton: someone asked to open your account on a new phone. If it wasn't you, stop it: ${link}` }); const res = await fetch(`https://api.twilio.com/2010-04-01/Accounts/${sid}/Messages.json`, { method: "POST", headers: { authorization: `Basic ${btoa(`${sid}:${auth}`)}`, "content-type": "application/x-www-form-urlencoded" }, body, }).catch(() => null); return Boolean(res?.ok); } private circleHost(): circle.CircleHost { const slug = this.store.meta("slug") ?? this.slug; return { sql: this.ctx.storage.sql, now: () => Date.now(), me: { account: slug, number: this.store.meta("owner_phone") ?? "" }, isPeer: (number) => send.isPersonOf(this.ctx.storage.sql, number), accountOf: async (number) => { const found = await directory(this.env).lookup(number).catch(() => null); return found && found !== slug ? found : null; }, peer: (account) => this.env.BUSINESS.get(this.env.BUSINESS.idFromName(account), { locationHint: "apac" }) as unknown as circle.CirclePeer, holdsVault: (deviceId) => this.store.list(VAULT_KEY_TABLE, { column: "device_id", equals: deviceId }).some((r) => Boolean(r.data.wrapped_vmk)), tellDevices: (what, except) => this.tellCircleDevices(what, except), textStop: (link) => this.textStop(link), linkBase: () => { const host = this.env.OPEN_HOST; const databaseId = this.store.meta("database_id"); return host && databaseId ? `https://${host}/v1/recovery/stop/${databaseId}` : null; }, retireTrustedRows: () => recovery.retireTrustedRows(this.ctx.storage.sql), tellTrustedDropped: (helper) => recovery.tellTrustedDropped(this.recoveryHost(), helper), freshDevice: (deviceId) => this.freshDevice(deviceId), checkWrap: (body) => recovery.checkWrap("circle", body), writeWrap: (device, body) => void recovery.writeWrap(this.recoveryHost(), "circle", device, body), }; } /** A new device of one of this person's people revealed its nonce on an ask this person helps with. */ async helpRevealed(from: string, revealed: { id: string; nonce: string }): Promise { await this.frozenGate(); if (this.reachable()) await recovery.helpRevealed(this.recoveryHost(), from, revealed); } /** The person this one trusts answered an ask. */ async helpAnswered(from: string, answer: { id: string; sealed?: string; decline?: boolean; legacy?: boolean }): Promise { await this.frozenGate(); if (this.reachable()) recovery.helpAnswered(this.recoveryHost(), from, answer); } private recoveryHost(): recovery.RecoveryHost { return { sql: this.ctx.storage.sql, now: () => Date.now(), ownerPhone: this.store.meta("owner_phone"), isPeer: (number) => send.isPersonOf(this.ctx.storage.sql, number), peerObject: async (number) => { const slug = await directory(this.env).lookup(number).catch(() => null); if (!slug || slug === (this.store.meta("slug") ?? this.slug)) return null; return this.env.BUSINESS.get(this.env.BUSINESS.idFromName(slug), { locationHint: "apac" }) as unknown as recovery.HelpPeer; }, holdsVault: (deviceId) => this.store.list(VAULT_KEY_TABLE, { column: "device_id", equals: deviceId }).some((r) => Boolean(r.data.wrapped_vmk)), circle: (device) => circle.summary(this.circleHost(), device), freshDevice: (deviceId) => this.freshDevice(deviceId), }; } private secretHost(): secrets.SecretHost { return { sql: this.ctx.storage.sql, env: this.env, slug: this.store.meta("slug") ?? this.slug, ownerPhone: this.store.meta("owner_phone"), now: () => Date.now(), waitUntil: (work) => this.background(work) }; } // ── Secrets' hop (src/send/secrets.ts): only another object calls these, by RPC ── /** One of this person's people gives them a secret. */ async secretDeliver(delivery: secrets.SecretDelivery): Promise { await this.frozenGate(); this.refuseWhileDeleting(); if (this.personal()) await secrets.deliverIn(this.secretHost(), delivery); } /** The giver's object replaced the value of a secret it gave this person. */ async secretUpdated(from: string, share: string, value: string, version: number): Promise { await this.frozenGate(); if (this.reachable()) await secrets.updatedIn(this.secretHost(), from, share, value, version); } /** The giver's object took back a secret it gave this person. */ async secretTaken(from: string, share: string): Promise { await this.frozenGate(); if (this.reachable()) secrets.takenIn(this.secretHost(), from, share); } /** The holder's object counted an open of a secret this person gave. */ async secretOpened(from: string, share: string, opens: number, at: number): Promise { await this.frozenGate(); if (this.reachable()) secrets.openedIn(this.secretHost(), from, share, opens, at); } /** One of this person's people asks them for a secret. */ async secretAsked(from: string, ask: string, box: string): Promise { await this.frozenGate(); this.refuseWhileDeleting(); if (this.personal()) await secrets.askedIn(this.secretHost(), from, ask, box); } /** One of this person's people took back an ask they sent. */ async secretAskWithdrawn(from: string, ask: string): Promise { await this.frozenGate(); if (this.reachable()) secrets.askWithdrawnIn(this.secretHost(), from, ask); } /** The person an ask went to answered it. */ async secretAskAnswered(from: string, ask: string, state: "shared" | "no"): Promise { await this.frozenGate(); if (this.reachable()) secrets.askAnsweredIn(this.secretHost(), from, ask, state); } private sharedHost(): shared.SharedHost { return { sql: this.ctx.storage.sql, env: this.env, slug: this.store.meta("slug") ?? this.slug, ownerPhone: this.store.meta("owner_phone") }; } // ── Shared lists' hop (src/send/shared.ts): only another object calls these, by RPC ── /** A member's object reads one of this person's lists for its owner. */ async sharedRead(from: string, id: string, key: string | null = null): Promise { await this.frozenGate(); return this.reachable() ? shared.readAsked(this.sharedHost(), from, id, typeof key === "string" ? key : null) : null; } /** A member's object writes or takes an item of one of this person's lists. */ async sharedPut(from: string, id: string, item: string, sealed: string | null): Promise { await this.frozenGate(); return this.reachable() ? shared.putAsked(this.sharedHost(), from, id, item, sealed) : false; } /** A member's object changes the membership of one of this person's lists. */ async sharedState(from: string, id: string, state: unknown): Promise { await this.frozenGate(); return this.reachable() ? shared.stateAsked(this.sharedHost(), from, id, state) : false; } /** The founder's object says this person is in, or out of, one of their lists. */ async sharedJoined(from: string, id: string, joined: boolean): Promise { await this.frozenGate(); if (this.reachable()) await shared.joinedIn(this.sharedHost(), from, id, joined); } // ── Shared spaces (src/space/): the door and the spaces call these, by RPC; the space never lives here ── private spacePersonHost(): spacePerson.PersonHost { return { sql: this.ctx.storage.sql, ownerPhone: this.store.meta("owner_phone"), databaseId: this.store.meta("database_id"), ownerName: this.store.people().find((p) => p.role === "owner")?.name ?? null, left: () => this.mediaBudget().left, }; } /** The door asks whose device credential this is: the owner's number, or null (any other sign-in, or none). */ async spaceCaller(token: string): Promise<{ number: string } | null> { await this.frozenGate(); if (!this.reachable()) return null; try { const who = await whoIs(this.store, new Date(), token); if (!who || who.person.role !== "owner" || !who.person.phone) return null; return { number: who.person.phone }; } catch { return null; } } /** The spaces this person is in. */ async spacesIn(): Promise<{ space: string; at: number; app: string }[]> { await this.frozenGate(); return this.reachable() ? spacePerson.spacesIn(this.spacePersonHost()) : []; } /** A space asks which of these numbers are this person's people (accepted both ways, not blocked). */ async spacePeers(numbers: string[]): Promise { await this.frozenGate(); return this.reachable() ? spacePerson.peers(this.spacePersonHost(), numbers) : []; } /** A space asks to take this person in: their database and the keys their own phones posted, or why not. */ async spaceJoin(space: string, from: string, founding: boolean, serial: number, app?: string): Promise { await this.frozenGate(); if (!this.reachable() || !spacesOn()) return { refused: "not_your_person" }; return spacePerson.join(this.spacePersonHost(), space, from, founding, serial, app); } /** A space says this person is out of it. */ async spaceLeft(space: string, serial: number): Promise { await this.frozenGate(); if (accountDelete.erased(this.ctx.storage.sql)) return true; spacePerson.left(this.spacePersonHost(), space, serial); return true; } /** A space counts bytes this person added (or refunds them) against their space. */ async spaceCharge(space: string, delta: number): Promise { await this.frozenGate(); // An erased account has nothing left to count: a refund owed to it is settled. if (accountDelete.erased(this.ctx.storage.sql)) return delta < 0; if (!this.reachable() || (delta > 0 && !spacesOn())) { // A refund still lands while the account waits out its thirty days: nothing is left counted to it. if (delta < 0 && this.personal()) return spacePerson.charge(this.spacePersonHost(), space, delta); return false; } return spacePerson.charge(this.spacePersonHost(), space, delta); } /** * At the account's erase, BEFORE the directory lets the number go: each space this person is in is told their * database is gone (the space outlives them). Answers the ids of those that did not take it, so the erase asks them again. */ private async leaveSpaces(): Promise { const database = this.store.meta("database_id"); const held = spacePerson.spacesIn(this.spacePersonHost()); if (!database) return []; // Every space asked, each on its own: the ones that did not take it are answered, to be asked again (DELETE ACCOUNT 2). const notTold: string[] = []; for (const { space } of held) { try { await spaceObject(this.env, space).gone(database); this.ctx.storage.sql.exec("DELETE FROM space_in WHERE space = ?", space); } catch (error) { console.error(`cottondb: account delete: space ${space} did not take word of the erase`, error instanceof Error ? error.message : "unknown"); notTold.push(space); } } return notTold; } private sendHost(): send.SendHost { return { sql: this.ctx.storage.sql, env: this.env, store: this.store, slug: this.store.meta("slug") ?? this.slug, databaseId: this.store.meta("database_id"), ownerPhone: this.store.meta("owner_phone"), timezone: this.meta().timezone, tables: () => this.store.definitions("table"), budget: () => this.mediaBudget(), write: (fn) => this.ctx.storage.transactionSync(() => { const version = this.store.bump(); const engine = this.engine(); engine.journal = new Journal(this.store, null, "send", "act"); return fn(engine, version, new Outcome_()); }), waitUntil: (work) => this.background(work), sockets: () => this.ctx.getWebSockets().filter((ws) => this.ctx.getTags(ws).some((t) => t.startsWith(chat.SOCKET_TAG))), }; } override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise { try { await this.frozenGate(); } catch { // Frozen for a restore: the frame is not taken and the phone told to come back (RESTORE 2, M1). try { ws.close(4503, "account_frozen"); } catch { // already closed } return; } const tag = this.ctx.getTags(ws).find((t) => t.startsWith(chat.SOCKET_TAG)); if (!tag || typeof message !== "string") return; const deviceId = tag.slice(chat.SOCKET_TAG.length); // A ring's ack and a phone's hello are the calls' (calls.ts `ringAck`, `hello`); every other frame is chat's. const ack = calling.ringAckOf(message); if (ack) return calling.ringAck(this.callHost(), deviceId, ack); const can = calling.helloOf(message); if (can) { // A phone that says it speaks the new way is rung the new way from now on: a ring still live, or a missed call // kept for it, reaches it now (calls.ts `redeliver`). One that never says hello is rung as before. if (calling.hello(this.callHost(), deviceId, can)) await calling.redeliver(this.callHost(), deviceId).catch(() => {}); return; } chat.frameIn(this.ctx.storage.sql, deviceId, ws, message); } override async webSocketClose(ws: WebSocket, code: number): Promise { try { ws.close(code === 1005 ? 1000 : code, "closed"); } catch { // Already closed. } } private chatHost(): chat.ChatHost { return { sql: this.ctx.storage.sql, env: this.env, slug: this.store.meta("slug") ?? this.slug, databaseId: this.store.meta("database_id"), ownerPhone: this.store.meta("owner_phone"), waitUntil: (work) => this.background(work), spaceCounting: () => this.spaceMode() !== "off", forget: async (number) => { await send.forgetPerson(this.sendHost(), number); // The ways back in let go here at once; telling other objects never fails Remove or Block (BUILD 3, LOW). await recovery.forgetPerson(this.recoveryHost(), number).catch((e) => console.error("cottondb: recovery forget", e instanceof Error ? e.message : "unknown")); await circle.forgetPerson(this.circleHost(), number).catch((e) => console.error("cottondb: circle forget", e instanceof Error ? e.message : "unknown")); }, ownerName: () => { const phone = this.store.meta("owner_phone"); return (phone && this.store.personByPhone(phone)?.name?.trim()) || null; }, sockets: (deviceId) => this.ctx.getWebSockets(`${chat.SOCKET_TAG}${deviceId}`), accept: (socket, deviceId) => this.ctx.acceptWebSocket(socket, [`${chat.SOCKET_TAG}${deviceId}`]), arrival: () => { const pub = keyFromText(this.store.get("seal_key", ARRIVAL_ROW)?.data.pub); const databaseId = this.store.meta("database_id"); // b.4 step B: a new Circle row keeps no clear number once sealed, for every account (the Worker's switch) or this one (its own). const only = this.env.CIRCLE_SEALED_ONLY === "on" || this.store.meta(chat.CIRCLE_SEALED_ONLY) === "on"; return pub && databaseId ? { pub, databaseId, only } : null; }, }; } private agentHost(): agentChats.AgentHost { return { sql: this.ctx.storage.sql, env: this.env, ownerPhone: this.store.meta("owner_phone"), sockets: (deviceId) => this.ctx.getWebSockets(`${chat.SOCKET_TAG}${deviceId}`), waitUntil: (work) => this.background(work), }; } private callHost(): calling.CallHost { return { sql: this.ctx.storage.sql, env: this.env, slug: this.store.meta("slug") ?? this.slug, ownerPhone: this.store.meta("owner_phone"), waitUntil: (work) => this.background(work), sockets: (deviceId) => this.ctx.getWebSockets(`${chat.SOCKET_TAG}${deviceId}`), wake: (at) => this.ctx.waitUntil( (async () => { const set = await this.ctx.storage.getAlarm(); if (set === null || at < set) await this.ctx.storage.setAlarm(at); })(), ), }; } /** * The admin token (true). An owner token (false) only on the dev and test Workers, only to a builder's few routes * (src/admin_door.ts DEV_OWNER_ROUTES), and not once the account's token scopes are on. Anything else is refused: * on live every /v1/admin route takes the admin token alone, token scopes on or off (NEXT-ADMIN-KEYS part 1). */ private async requireAdmin(request: Request, path = ""): Promise { const token = bearer(request); if (isAdminToken(this.env, token)) return true; if (token?.startsWith("ctn_") && this.personal()) { const mcp = await this.mcpCaller(token); if (mcp?.scopes.has("owner")) { this.noteTokenRoute(mcp.tokenId, tokenScopes.routeOf(request.method, `/v1/admin${path}`)); // ADMIN KEYS 4: a key that carries a list reaches no admin route, dev included. if (adminDoor.ownerReaches(this.env, request.method, path) && !this.tokenScopesOn() && !mcp.allow) return false; } } refuse(403, "admin_only", "this needs the admin token"); } /** * An act by a token, noted; with token scopes on: at /v1/act only mint and revoke, and only by a token pasted by hand; * from /mcp or /v1/act no mint or revoke by a connector, no mint of the owner scope or without an end, and no direct * write of a credential or key table (src/token_scopes.ts). */ private tokenAct(caller: Caller, act: string, args: Record): void { if (!caller.viaMcp) this.noteTokenRoute(caller.tokenId!, tokenScopes.routeOf("POST", "/v1/act", act)); // SERVER 27 H1: `import: true` logs a write only as having happened, so it is never undone; it is the Mac importer's, // which writes with its device credential. A token never says it, on any act, token scopes on or off. if (args.import === true) refuse(403, "owner_only", "only the owner's own devices write as an import"); // ADMIN KEYS 1b: who may do what is never a token's to change, token scopes on or off, at /v1/act and by run_act alike // (both pass here): no role given (set_role made another phone an owner), no key minted, no grant or window // answered, and no write of a table that holds keys, credentials, devices or grants. // The two exceptions, the coordinator's calls: an owner-scope key mints a lane token, or the Macs' machines producer // (tokenScopes.keyMintRefusal), and nothing else. if (act === "mint_token") { const minter = this.store.get(TOKEN_TABLE, caller.tokenId!); const scopes = Array.isArray(minter?.data.scopes) ? (minter!.data.scopes as string[]) : []; // A connector (an OAuth connection: someone's Claude) mints nothing, as token scopes always said; a pasted key does. const why = caller.connector ? "mint_token changes who may do what: the owner does it from their own device, never a key; a connection mints nothing" : tokenScopes.keyMintRefusal(scopes, args); if (why) refuse(403, "access_act", why); } else if (tokenScopes.ACCESS_ACTS.has(act)) refuse(403, "access_act", `${act} changes who may do what: the owner does it from their own device, never a key`); if (tokenScopes.TABLE_WRITE_ACTS.has(act) && typeof args.table === "string" && tokenScopes.PROTECTED.has(args.table)) { refuse(403, "access_act", `${args.table} holds who may do what (keys, credentials, devices, grants): a key never writes it`); } // ADMIN KEYS 2: a key that carries its list runs only the acts whose tables it may write, and an outward act only // with outward (src/key_allow.ts), at /v1/act and from inside a tool alike, token scopes on or off. const shut = keyAllow.actRefusal(caller.allow ?? null, act, args); if (shut) refuse(403, "key_allow", shut); if (!this.tokenScopesOn()) return; if (!caller.viaMcp && (caller.connector || !tokenScopes.TOKEN_ACTS.has(act))) refuse(403, "token_scopes", tokenScopes.DEVICE_REFUSAL); if (tokenScopes.TOKEN_ACTS.has(act) && caller.connector) refuse(403, "token_scopes", "a connected assistant does not mint or revoke tokens: the owner does, from a phone"); } /** reset and erase with token scopes on: `confirm` must name this database's id; reset never on the live Worker. */ /** What the erase act needs of this object (src/erase.ts EraseHost). */ private eraseHost(): EraseHost { const databaseId = this.store.meta("database_id"); const slug = this.meta().slug; const budget = this.mediaBudget(); return { sql: this.ctx.storage.sql, store: this.store, defs: this.definitions(), databaseId, bucketKey: (key) => { if (!databaseId) return null; try { return bucketKey(key, databaseId, slug); } catch { return null; } }, held: (key) => send.holds(this.ctx.storage.sql, key), drop: async (at) => { const object = await this.env.MEDIA.head(at); if (!object) return null; await this.env.MEDIA.delete(at); return object.size; }, counted: (bytes) => budget.add(-bytes), transaction: (fn) => this.ctx.storage.transactionSync(fn), now: () => new Date(), }; } private async gateWipe(request: Request, what: string, refuseLive: boolean): Promise { if (refuseLive && this.env.ENV_LABEL === "production") refuse(403, "token_scopes", `${what} is never run on the live Worker`); const body = await readJson(request.clone()); const id = this.store.meta("database_id"); if (!id || body.confirm !== id) refuse(400, "confirm_database", `${what} takes confirm: this database's id`); } /** Token scopes (src/token_scopes.ts): on for this personal database while its meta is set. */ private tokenScopesOn(): boolean { return this.personal() && tokenScopes.readSwitch(this.store.meta(tokenScopes.META)) !== null; } /** Note that a token reached a route, switch on or off: the switch's gate reads them. */ private noteTokenRoute(tokenId: string, route: string): void { this.ctx.storage.sql.exec("INSERT INTO token_route (token_id, route, last_at) VALUES (?, ?, ?) ON CONFLICT (token_id, route) DO UPDATE SET last_at = excluded.last_at", tokenId, route, new Date().toISOString()); } /** The gate: every token in use, the routes it was seen on, and whether each stays open to it with the switch on. */ private tokenHolders(excuse: ReadonlySet, since: string | null = null): { ready: boolean; on: tokenScopes.Switch | null; since: string | null; holders: tokenScopes.Holder[] } { const now = Date.now(); const seen = new Map(); // `since`: only the routes seen from then on count (a script moved off a token, its old routes behind it). for (const r of this.ctx.storage.sql.exec<{ token_id: string; route: string; last_at: string }>("SELECT token_id, route, last_at FROM token_route WHERE last_at >= ?", since ?? "").toArray()) { (seen.get(r.token_id) ?? seen.set(r.token_id, []).get(r.token_id)!).push({ route: r.route, last_at: r.last_at }); } const holders: tokenScopes.Holder[] = []; for (const row of this.store.scan(TOKEN_TABLE)) { const d = row.data; const str = (v: unknown) => (typeof v === "string" && v ? v : null); const scopes = Array.isArray(d.scopes) ? (d.scopes as unknown[]).map(String) : []; const t: tokenScopes.TokenSeen = { id: row.id, name: String(d.name ?? ""), scopes, last_used_at: str(d.last_used_at), created_at: row.created_at, expires_at: str(d.expires_at), revoked_at: str(d.revoked_at), connector: this.connectorToken(row.id) }; if (!tokenScopes.inUse(t, now)) continue; holders.push(tokenScopes.holderOf(t, seen.get(row.id) ?? [], excuse)); } holders.sort((a, b) => String(b.last_used_at ?? "").localeCompare(String(a.last_used_at ?? "")) || a.token_id.localeCompare(b.token_id)); return { ready: holders.every((h) => h.verdict !== "would_lose"), on: tokenScopes.readSwitch(this.store.meta(tokenScopes.META)), since, holders }; } /** The importer's routes the allowlist locks: every import, and a media PUT or HEAD by a credential that is not a phone's (the admin token, a minted token, or a device filed as a Mac). */ private importerRoute(caller: Caller, method: string, path: string): boolean { if (path.startsWith("/v1/import/")) return true; if (!path.startsWith("/v1/media/") || (method !== "PUT" && method !== "HEAD")) return false; if (caller.admin || caller.tokenId) return true; return caller.who ? syncStatus.ownDevice(this.store, caller.who.deviceId)?.data.platform === "mac" : false; } /** Whether a minted token is an OAuth connector's: those carry a refresh row, and stay unlocked until the connector's addresses are known (plan Q20). */ private connectorToken(tokenId: string): boolean { return this.store.list(OAUTH_REFRESH_TABLE, { column: "token", equals: tokenId }).length > 0; } /** `GET /v1/allowlist`: the owner reads the list a change replaces. */ private allowlistAnswer(caller: Caller): Response { if (caller.role !== "owner") refuse(403, "owner_only", "only the owner reads the allowlist"); return json({ list: allowlist.held(this.ctx.storage.sql) }); } /** The person key's public half (base64url) under this fingerprint, or null. */ private personKey(fingerprint: string): string | null { const row = this.store.get(allowlist.PERSON_KEY_TABLE, fingerprint); const publicKey = row?.data.public_key; return typeof publicKey === "string" && publicKey.startsWith(fingerprint) ? publicKey : null; } /** What src/window.ts may touch: the object's SQL and rows, WINDOW_KEY, the person key, and a write in one transaction. */ private windowHost(): unlock.WindowHost { return { sql: this.ctx.storage.sql, store: this.store, databaseId: this.store.meta("database_id") ?? "", key: unlock.windowKey(this.env.WINDOW_KEY), personKey: (fingerprint) => this.personKey(fingerprint), write: (fn) => this.ctx.storage.transactionSync(() => { const version = this.store.bump(); const engine = this.engine(); engine.journal = new Journal(this.store, null, "unlock", "act"); return fn(engine, version, new Outcome_()); }), }; } /** The unlock acts are the owner's own signed-in devices', never a token's nor the admin's: the phone holds the person key, and no server-side way opens a window. */ /** * A token's request the owner must allow (src/owner_asks.ts): kept, its card written, and the token answered 202 * with the ask. Null when the request is not one of the three. */ private async ownerAsk(tokenId: string, request: Request, method: string, path: string): Promise { if (!this.personal()) return null; // Read once and for good: after this the token is answered 202 or refused, and nothing reads the body again. const text = method === "GET" || method === "HEAD" ? "" : await request.text(); let body: Record | null = null; try { const parsed = JSON.parse(text); body = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null; } catch { body = null; } const asked = ownerAsks.askedOf(method, path, body); if (!asked) return null; const name = String(this.store.get("mcp_token", tokenId)?.data.name ?? ""); // Sealed at arrival (LOCK TABLES 1): what the card says goes to the owner's arrival key; no key, no ask. The id and // the time are chosen once, outside, as a sealed write runs twice (src/arrival_seam.ts). const id = crypto.randomUUID(); const at = Date.now(); const row = await this.writeSealing( (engine) => (engine.journal = new Journal(this.store, null, "owner_ask", "act")), (engine, version, outcome) => ownerAsks.ask(this.ctx.storage.sql, this.store, engine, { id: tokenId, name }, { method, path, body: text }, asked, at, version, outcome, id), ); return json({ code: "owner_asked", message: "The owner allows this on their phone. Read GET /v1/asks/ for the answer.", ask_id: row.id, expires_at: row.data.expires_at }, 202); } /** The owner's own device answers an ask: Allow runs the kept request as this device would, once; Refuse drops it. */ private async ownerAnswers(caller: Caller, request: Request, path: string): Promise { if (caller.role !== "owner" || caller.tokenId || caller.admin || !caller.who) refuse(403, "owner_only", "only the owner's own devices answer an assistant's ask"); const askId = String((await readJson(request)).ask_id ?? ""); const kept = ownerAsks.held(this.ctx.storage.sql, this.store, askId, Date.now()); const settle = (patch: Record) => this.ctx.storage.transactionSync(() => { const version = this.store.bump(); const engine = this.engine(); engine.journal = new Journal(this.store, null, "owner_ask", "act"); ownerAsks.settle(this.ctx.storage.sql, engine, this.store.get(ownerAsks.ASK_TABLE, askId) ?? kept.row, patch, version, new Outcome_()); }); const at = new Date().toISOString(); if (path === "/v1/asks/refuse") { settle({ state: "refused", answered_at: at }); return json({ ask_id: askId, state: "refused" }); } // Answered once: the ask leaves waiting before the request runs, so a second Allow finds nothing to run. settle({ state: "allowed", answered_at: at }); const replay = new Request(new URL(kept.path, request.url).toString(), { method: kept.method, headers: { "content-type": "application/json" }, body: kept.body }); let status: number; let answer: unknown; try { const res = kept.path.startsWith("/v1/google/") ? await this.google(caller, replay, kept.path) : await this.mailRoute(caller, replay, kept.path); status = res.status; const words = (await res.text()).slice(0, 2000); try { answer = JSON.parse(words); } catch { answer = words; } } catch (error) { status = error instanceof Refused ? error.status : 500; answer = error instanceof Refused ? { code: error.code, message: error.message } : { code: "failed", message: "the request failed" }; } const state = status < 300 ? "done" : "failed"; const said = typeof answer === "string" ? answer : JSON.stringify(answer); // The token's copy on the object alone; the card's copy sealed at arrival, for the phone. ownerAsks.keepAnswer(this.ctx.storage.sql, askId, String(kept.row.data.token_id ?? ""), said, Date.now()); await this.writeSealing( (engine) => (engine.journal = new Journal(this.store, null, "owner_ask", "act")), (engine, version, outcome) => { const row = this.store.get(ownerAsks.ASK_TABLE, askId); // An ask written open before its table was sealed (waiting across the deploy) is no row to seal at arrival: its // answer stays on the object alone (owner_ask_answer), never in the open row; the card says the state. if (row) engine.update(row, isSealedRow(row.data) ? { state, status, answer: said } : { state, status }, version, outcome); }, ); return json({ ask_id: askId, state, status, answer }); } private unlockDevice(caller: Caller): void { if (!this.personal()) refuse(404, "not_personal", "unlock windows live in the personal database"); if (caller.role !== "owner" || caller.tokenId || caller.admin || !caller.who) refuse(403, "owner_only", "only the owner's own devices answer an unlock request"); } private async changeAllowlist(request: Request): Promise { const absent = this.absent(); const list = await allowlist.change( { sql: this.ctx.storage.sql, databaseId: absent ? "" : this.databaseId(), personKey: (fingerprint) => (absent ? null : this.personKey(fingerprint)), now: new Date(), transact: (fn) => this.ctx.storage.transactionSync(fn), }, await readJson(request), ); return json({ list }); } /** The personal database: a definitions object whose meta says `kind: personal`. It alone serves Cotton MCP and holds tokens and a vault. */ private personal(): boolean { return this.store.meta("kind") === "personal"; } /** No database was ever made here (or its erase has run): no kind and no definitions. */ private absent(): boolean { return this.store.meta("kind") === null && !this.store.holdsDefinitions("table"); } /** A write that would grow a full database is refused; sync, reads and sign-in still answer. */ private roomToWrite(): void { if (this.ctx.storage.sql.databaseSize >= this.caps.database) refuse(413, "object_full", "This database has reached its size limit: it still syncs and reads, but takes nothing new."); } private installed(): void { if (!this.store.holdsDefinitions("table")) this.refuseAsMissing(); } /** * What a database that does not exist answers. A number a personal database does not admit is answered the same * (coordinator, 23 Nov 2026), word for word, so the refusal never tells a stranger that the database is there. */ private refuseAsWrongCode(): never { refuse(401, "invalid_code", "invalid or expired code"); } private refuseAsMissing(): never { refuse(503, "not_onboarded", `the business ${this.slug || ""} has no definitions yet`); } // ── definitions and meta ─────────────────────────────────────────────── /** * Where the memory lock stands (src/memory_lock.ts): off, handing (on, a grant still waits for memory's key) or * sealing. Handing turns to sealing, once and for good, when no live grant that covers memory waits. */ private memoryLockState(): memoryLock.State { if (!this.personal() || !memoryLock.readLock(this.store.meta(memoryLock.META))) return "off"; if (this.memoryLockHanding()) return "handing"; // Sealed once no entry is left open (asked again each time: an entry written open later is sealed by the sweep). return this.anyOpen([memoryLock.MEMORY]) ? "sealing" : "sealed"; } /** * Whether the memory lock is handing: on, and a grant still waits for memory's key. What `definitions()` and gate 2 * ask, on every read: it reads the meta and the grants only, never the rows (LIVE READS, 28 Nov 2026: `anyOpen` on a * sealed table seeks through every one of its rows, and asked on every read it reset the owner's object for CPU). */ private memoryLockHanding(): boolean { if (!this.personal()) return false; const lock = memoryLock.readLock(this.store.meta(memoryLock.META)); if (!lock || lock.sealing_at) return false; if (memoryLock.waiting(this.gateGrants(), this.agents.access(this.store, memoryLock.MEMORY)).length) return true; this.store.setMeta(memoryLock.META, JSON.stringify({ ...lock, sealing_at: new Date().toISOString() })); console.log(`cottondb: memory lock ${this.slug}: every grant holds memory's key; sealing may begin`); return false; } /** Where the open tables lock stands (src/open_tables_lock.ts), as memory's: handing turns to sealing once and for good. */ private openTablesState(): openTablesLock.State { if (!this.personal() || !openTablesLock.readLock(this.store.meta(openTablesLock.META))) return "off"; if (this.openTablesHanding()) return "handing"; return this.anyOpen(openTablesLock.TABLES) ? "sealing" : "sealed"; } /** Whether the open tables lock is handing, as [`memoryLockHanding`]: the meta and the grants only, never the rows. */ private openTablesHanding(): boolean { if (!this.personal()) return false; const lock = openTablesLock.readLock(this.store.meta(openTablesLock.META)); if (!lock || lock.sealing_at) return false; if (openTablesLock.waiting(this.gateGrants(), (t) => this.agents.access(this.store, t)).length) return true; this.store.setMeta(openTablesLock.META, JSON.stringify({ ...lock, sealing_at: new Date().toISOString() })); console.log(`cottondb: open tables lock ${this.slug}: every grant holds every session table's key; sealing may begin`); return false; } /** Whether the passwords' own switch is on (src/open_tables_lock.ts SECRET_META): secret sealed, whatever the other locks. */ private secretLocked(): boolean { return this.personal() && openTablesLock.readLock(this.store.meta(openTablesLock.SECRET_META)) !== null; } /** * Whether a live row of these tables is still open (no sealed_enc): a walk along each table's rows, through every one * when all are sealed. Only the lock's own state asks it (its routes, a sweep), never a read. */ private anyOpen(tables: readonly string[]): boolean { return tables.some((t) => this.ctx.storage.sql.exec("SELECT 1 FROM rows WHERE table_id = ? AND deleted = 0 AND json_extract(data, '$.sealed_enc') IS NULL LIMIT 1", t).toArray().length > 0); } /** Gate 2 of both locks: a device's seal of a locked table's row, refused while a grant still waits for its key. */ private refuseMemoryUnhanded(table: string): void { if (openTablesLock.TABLES.includes(table) && !(table === openTablesLock.SECRET && this.secretLocked()) && this.openTablesHanding()) { const n = openTablesLock.waiting(this.gateGrants(), (t) => this.agents.access(this.store, t)).length; refuse(409, "grant_not_handed", `${table} is not sealed yet: ${n} of Your Claude's grants ${n === 1 ? "waits" : "wait"} for its key, which the owner's phone hands on its next pass; seal it after that`); } if (table !== memoryLock.MEMORY || !this.memoryLockHanding()) return; const n = memoryLock.waiting(this.gateGrants(), this.agents.access(this.store, memoryLock.MEMORY)).length; refuse(409, "grant_not_handed", `memory is not sealed yet: ${n} of Your Claude's grants ${n === 1 ? "waits" : "wait"} for its key, which the owner's phone hands on its next pass; seal it after that`); } /** Gate 1: every live token in use, and whether each can open memory once it is sealed. */ private memoryReaders(excuse: ReadonlySet): { ready: boolean; state: memoryLock.State; readers: memoryLock.Reader[]; open_entries: number; sealed_entries: number; open_why: memoryLock.OpenWhy } { const now = Date.now(); const read = new Map(this.ctx.storage.sql.exec<{ token_id: string; last_at: string }>("SELECT token_id, last_at FROM memory_reader").toArray().map((r) => [r.token_id, r.last_at])); const access = this.agents.access(this.store, memoryLock.MEMORY); const readers: memoryLock.Reader[] = []; for (const row of this.store.scan(TOKEN_TABLE)) { const d = row.data; const str = (v: unknown) => (typeof v === "string" && v ? v : null); const hash = str(d.token_hash); const member = hash ? this.memberOfHash(hash) : null; const seen: memoryLock.TokenSeen = { id: row.id, name: String(d.name ?? ""), last_used_at: str(d.last_used_at), created_at: row.created_at, expires_at: str(d.expires_at), revoked_at: str(d.revoked_at), member }; if (!memoryLock.inUse(seen, now)) continue; readers.push(memoryLock.readerOf(seen, read.get(row.id) ?? null, member ? this.agents.grantOf(this.store, member) : null, access, excuse)); } readers.sort((a, b) => String(b.last_used_at ?? "").localeCompare(String(a.last_used_at ?? "")) || a.token_id.localeCompare(b.token_id)); const count = (sql: string) => this.ctx.storage.sql.exec<{ n: number }>(sql).one().n; return { ready: readers.every((r) => r.verdict === "ready" || r.verdict === "excused"), state: this.memoryLockState(), readers, open_entries: count("SELECT count(*) AS n FROM rows WHERE table_id = 'memory' AND deleted = 0 AND json_extract(data, '$.sealed_enc') IS NULL"), sealed_entries: count("SELECT count(*) AS n FROM rows WHERE table_id = 'memory' AND deleted = 0 AND json_extract(data, '$.sealed_enc') IS NOT NULL"), open_why: memoryLock.openWhy( this.ctx.storage.sql .exec<{ id: string; data: string; created_at: string; updated_at: string }>("SELECT id, data, created_at, updated_at FROM rows WHERE table_id = 'memory' AND deleted = 0 AND json_extract(data, '$.sealed_enc') IS NULL") .toArray() .map((r) => ({ id: r.id, data: JSON.parse(r.data) as Record, created_at: r.created_at, updated_at: r.updated_at })), memoryLock.readLock(this.store.meta(memoryLock.META)), ), }; } /** Gate 1 of the open tables lock: every live token in use, and whether each can open the session tables once sealed. */ private openTablesReaders(excuse: ReadonlySet): { ready: boolean; state: openTablesLock.State; readers: openTablesLock.Reader[]; waiting: openTablesLock.Waiting[]; open_rows: Record; sealed_rows: Record } { const now = Date.now(); const liveTokens = new Map(); const lockOn = openTablesLock.readLock(this.store.meta(openTablesLock.META)) !== null; const read = new Map(this.ctx.storage.sql.exec<{ token_id: string; last_at: string }>("SELECT token_id, last_at FROM open_reader").toArray().map((r) => [r.token_id, r.last_at])); const access = (t: string) => this.agents.access(this.store, t); const readers: openTablesLock.Reader[] = []; for (const row of this.store.scan(TOKEN_TABLE)) { const d = row.data; const str = (v: unknown) => (typeof v === "string" && v ? v : null); const hash = str(d.token_hash); const member = hash ? this.memberOfHash(hash) : null; const seen: memoryLock.TokenSeen = { id: row.id, name: String(d.name ?? ""), last_used_at: str(d.last_used_at), created_at: row.created_at, expires_at: str(d.expires_at), revoked_at: str(d.revoked_at), member }; if (member && !seen.revoked_at && !(seen.expires_at && Date.parse(seen.expires_at) <= now)) liveTokens.set(member, (liveTokens.get(member) ?? 0) + 1); if (!memoryLock.inUse(seen, now)) continue; readers.push(openTablesLock.readerOf(seen, read.get(row.id) ?? null, member ? this.agents.grantOf(this.store, member) : null, access, excuse, lockOn)); } readers.sort((a, b) => String(b.last_used_at ?? "").localeCompare(String(a.last_used_at ?? "")) || a.token_id.localeCompare(b.token_id)); const counts = (sealed: boolean) => Object.fromEntries( openTablesLock.TABLES.map((t) => [t, this.ctx.storage.sql.exec<{ n: number }>(`SELECT count(*) AS n FROM rows WHERE table_id = ? AND deleted = 0 AND json_extract(data, '$.sealed_enc') IS ${sealed ? "NOT " : ""}NULL`, t).one().n]), ); // Gate 2's grants, each with the keys it still lacks (HANDING STUCK, 25 Nov 2026): read-only, so the admin sees why handing holds. const text = (v: unknown) => (typeof v === "string" && v ? v : null); const waiting: openTablesLock.Waiting[] = openTablesLock.waiting(this.gateGrants(), access).map((g) => { const member = text(g.data.member_id); return { grant_id: g.id, member_id: member, client: text(g.data.client), granted_at: text(g.data.granted_at), live_tokens: member ? (liveTokens.get(member) ?? 0) : 0, missing: openTablesLock.missing(g, access) }; }); return { ready: readers.every((r) => r.verdict === "ready" || r.verdict === "excused"), state: this.openTablesState(), readers, waiting, open_rows: counts(false), sealed_rows: counts(true) }; } /** * The parsed definitions this instance last read, and what they were read under (SLOW READ, 26 Nov 2026): every * request parsed every table definition, 1 MB of JSON for a personal object, about three times. Read again whenever * any definition is written (the definitions_version triggers, src/store.ts), or either lock's state or meta moves. */ private parsed: { key: string; defs: Definitions; links: Map; dates: Map } | null = null; private definitions(): Definitions { const handing = this.memoryLockHanding(); const tablesHanding = this.openTablesHanding(); const version = this.store.definitionsVersion(); const key = version === null ? null : JSON.stringify([version, handing, tablesHanding, this.store.meta("kind"), this.store.meta(memoryLock.META), this.store.meta(openTablesLock.META), this.store.meta(openTablesLock.SECRET_META)]); if (key !== null && this.parsed?.key === key) { this.store.setLinkColumns(this.parsed.links); this.store.setDateColumns(this.parsed.dates); return this.parsed.defs; } const opened = (doc: Record) => (({ seal: _seal, ...open }) => open)(doc); const tables = this.store .definitions("table") // Gate 2 (src/memory_lock.ts): while a grant still waits for memory's key, the object treats memory as open. .map((doc) => (handing && doc.id === memoryLock.MEMORY ? opened(doc) : doc)) // The same for the open tables lock's tables (src/open_tables_lock.ts). .map((doc) => (tablesHanding && openTablesLock.TABLES.includes(String(doc.id)) && !(doc.id === openTablesLock.SECRET && this.secretLocked()) ? opened(doc) : doc)) .map(parseTable) .filter((t): t is TableDef => t !== null); const defs = new Definitions(tables); // Every column a held clear list kept clear that these seal is recorded: a phone still holding the older list is // never refused for it (src/seal_wide.ts). sealWide.note(this.ctx.storage.sql, defs.tables.values(), new Date().toISOString()); const links = defs.linkColumns(); const dates = defs.dateColumns(); this.store.setLinkColumns(links); this.store.setDateColumns(dates); this.parsed = key === null ? null : { key, defs, links, dates }; return defs; } private engine(defs = this.definitions(), clock?: Clock): Engine { const tools = this.store.definitions("tool").map(toolRules); const now = new Date(); return new Engine(defs, tools, this.store, clock ?? { now: now.toISOString(), today: localDate(now, this.meta().timezone) }); } private meta(): BusinessMeta { return { slug: this.store.meta("slug") ?? this.slug, name: this.store.meta("name") ?? this.slug, currency: this.store.meta("currency") ?? "INR", timezone: this.store.meta("timezone") ?? "Asia/Kolkata", upi_id: this.store.meta("upi_id"), owner_phone: this.store.meta("owner_phone"), kind: this.personal() ? "personal" : "business", database_id: this.store.meta("database_id"), ...(this.personal() ? { owner_person_id: owner.linkedOwner(this.store), namespace: this.store.meta("namespace") ?? this.store.meta("database_id") } : {}), }; } private async definitionsAnswer(request: Request): Promise { this.installed(); const tools = this.store.definitions("tool"); const tables = this.store.definitions("table"); const flavour = this.store.definitions("flavour")[0] ?? {}; const boards = this.personal() ? this.homeWithEmpty(tools, this.store.definitions("board")) : this.store.definitions("board"); const themes = this.store.definitions("theme"); // ROUTES-AUDIT 6 (23 Nov 2026): a personal database's owner number is said only to a caller it knows (a device of // its own, an owner token, the admin). With no credential, a database id (in any stream link) gave the number. // STRANGER BLIND (coordinator, 23 Nov 2026): to a caller it does not know, a personal database answers what one that // does not exist answers, word for word, so its tables never say it is there. A business's definitions stay public. const known = await this.caller(request).then((c) => c.role !== "public", () => false); if (this.personal() && !known) this.refuseAsMissing(); // AUDIT A H1 (28 Nov 2026): a business's definitions stay public, but a caller it does not know is told nothing // personal: not the owner's number, not the database id. The UPI id stays: it is the business's payment address, // there to be shown to whoever pays. const business: BusinessMeta = known ? this.meta() : { ...this.meta(), owner_phone: null, database_id: null }; const answer: DefinitionsAnswer = { business, tools, tables, flavour, boards, themes, etag: await etagOf([business, tools, tables, flavour, boards, themes]) }; // What a known caller is told differs from a stranger's: theirs is never cached where a stranger could read it. const headers: Record = this.personal() || known ? { "cache-control": "private, max-age=60", vary: "authorization", etag: `"${answer.etag}"` } : { "cache-control": "public, max-age=60", vary: "authorization", etag: `"${answer.etag}"` }; // A phone that holds these definitions already asks with their etag and is told so without the body. const held = request.headers.get("if-none-match"); if (held && held.split(",").some((tag) => tag.trim().replace(/^W\//, "") === `"${answer.etag}"`)) return new Response(null, { status: 304, headers }); return json(answer, 200, headers); } /** * A personal object's boards as served: Home's `tools` part names the tools * whose tables hold no rows, in the kit's order, which the phone's fan deals * after Settings (src/fan.ts). */ private homeWithEmpty(tools: Record[], boards: Record[]): Record[] { const own = new Set(KIT.own.map((t) => String(t.id))); const order = KIT.tools.map((t) => String(t.id)); const empty = fan.emptyTools(tools, order, (t) => !own.has(String(t.id)), (table) => this.store.holdsRows(table)); return boards.map((b) => (b.id === "home" ? fan.withEmpty(b, empty) : b)); } /** A later pass's figures with `again`'s tables counted whole: each one's rows from nothing in place of its rows changed since. */ private againFigures(f: syncStatus.PassFigures, again: string[], q: { since: number; upto: number; scope: SyncScope; windows: SyncWindow[] }): syncStatus.PassFigures { if (again.length === 0) return f; const out = { ...f, tables: { ...f.tables } }; for (const table of again) { const whole = this.store.tableCounts({ ...q, table, since: 0 }); const changed = this.store.tableCounts({ ...q, table }); out.pass += whole.n - changed.n; out.passLive += whole.live - changed.live; if (whole.n > 0) out.tables[table] = [whole.n, 0]; } return out; } /** * The first orders a pass from nothing carries (src/first.ts): every * declared table it holds rows of, from the figures counted as it began. * Null when there is none, and the pass runs as before. */ private firstPlan(figures: syncStatus.PassFigures): { plan: FirstPlan; at: null } | null { const planned = planFirst((t) => figures.tables[t]?.[0] ?? 0, localDate(new Date(), this.meta().timezone), SMALL_TABLE_ROWS); if (planned.length === 0) return null; // Only the tables whose indexes stand come first; the rest wait for the alarm to make theirs (Store.firstIndexes). const specs = this.store.firstIndexes(planned); if (specs.length === 0) return null; const pass = crypto.randomUUID(); const now = Math.floor(Date.now() / 1000); this.store.firstPass(pass, now, now - FIRST_PASS_KEPT_S); return { plan: { pass, small: [], specs, cuts: specs.map(() => null) }, at: null }; } // ── sync ─────────────────────────────────────────────────────────────── /** * `GET /v1/sync?since=[&limit=][&window=
:,…][&tables=
,…]`, then * `GET /v1/sync?cursor=` until an answer carries no `next`. * * A page is at most `limit` rows (default 5000, at most 10000) in change * order, read up to the version the first page saw, so pages never skip a * row however much one import wrote under one version. A pass from nothing * (`since=0`, a fresh install) carries its small tables first, whole, the * fewest rows first, and the big ones after in change order * (`SMALL_TABLE_ROWS`, `Store.changedPage`): people and todos stand whole * in a copy's first minutes, not after its messages. While `next` is * present the answer's `version` is still `since`: the phone holds the new * version only when the last page has landed. A window keeps a table to its * newest days (the phone's window of messages): a live row dated before it, * by the table's `date` column, stays out, now and in every later page. * `tables` keeps the pass to those tables (an app's kit: Cotton Books pulls * its books and highlights, never the owner's whole life; coordinator, * 5 Nov 2026), for every role, inside what the role may read; absent is * every table the role reads. A table the object does not define holds no * rows, so naming one carries nothing. * Every page says the object's clock (`server_time`): the owner's phone * stamps its writes by the time it judges from it, as it did from a Mac's. * * Every page also says how far the pass stands (`total`, `remaining`), and * for a signed-in device writes it on the device's own row, named in * `device` (src/sync_status.ts). */ private sync(caller: Caller, params: URLSearchParams): Response { this.installed(); const defs = this.definitions(); const token = params.get("cursor"); const page = token ? readCursor(token) : null; const since = page ? page.since : integer(params.get("since"), "since", 0); const upto = page ? page.upto : this.store.version(); const asked = page ? page.limit : integer(params.get("limit"), "limit", 5000); if (asked < 1 || asked > 10_000) refuse(400, "bad_request", "limit is 1 to 10000"); // A pass's first page is short, so the phone has every table's figures // in a moment, before the small tables come whole on the next page: the // deck's counter says "0 of 950 todos arriving" while they come (owner, // 2 Nov 2026). Every later page is the size asked. const limit = page ? asked : Math.min(asked, FIRST_PAGE_ROWS); const windows = page ? page.windows : [...this.windows(defs, params.get("window")), ...this.onlys(defs, params.get("only"))]; const tables = page ? (page.tables ?? null) : syncTables(params.get("tables")); const within = (set: Set): Set => (tables ? new Set([...set].filter((t) => tables.includes(t))) : set); const scope: SyncScope = caller.role === "owner" ? tables ? { kind: "tables", whole: new Set(tables), own: new Set(), person: null, except: defs.internalTables() } : { kind: "all", except: defs.internalTables() } : { kind: "tables", whole: within(defs.wholeTables(caller.role)), own: within(caller.role === "member" ? defs.ownTables() : new Set()), person: caller.person?.id ?? null, except: defs.internalTables() }; // TABLES CARRIED AGAIN WHOLE IN A LATER PASS (21 Nov 2026): a phone whose new build keeps a table, or a column // of one, that its copy's cursor went past asks `again=`: those tables come whole first, the rest since // its cursor, so an update never pulls the whole object again. The answer says `again`, so a phone knows this // Worker carried them (an older one would not). const again = page ? (page.again ?? []) : since > 0 ? (syncTables(params.get("again")) ?? []).filter((t) => !defs.internalTables().has(t) && (!tables || tables.includes(t))) : []; const figures = page ? page.figures : this.againFigures(syncStatus.startPass(this.store, { since, upto, scope, windows }), again, { since, upto, scope, windows }); // The tables carried first: decided on a pass's first page, and only for a // pass from nothing; a later pass carries what changed, in change order. // A pass from nothing carries what each app shows first before the long tail (src/first.ts), when a kit // declares it for a table the pass holds; a cursor of a pass begun without a plan goes on without one. const first = page ? (page.first ?? null) : since === 0 ? this.firstPlan(figures) : null; const small = page?.small ?? (since === 0 ? this.store.smallFirst({ since, upto, scope, windows, most: SMALL_TABLE_ROWS }) : again); const floor = page?.floor ?? null; let rows: StoredRow[]; let more: boolean; let firstNext: { plan: FirstPlan; at: FirstAt } | null = null; let resume: Cursor | null = null; if (first) { const plan: FirstPlan = page ? first.plan : { ...first.plan, small: small.filter((t) => !first.plan.specs.some((s) => s.table === t)) }; const got = this.store.firstPage({ since, upto, limit, scope, windows, plan, at: first.at }); ({ rows, more } = got); firstNext = { plan: got.plan, at: got.at }; } else ({ rows, more, resume } = this.store.changedPage({ since, upto, limit, scope, windows, small, floor, after: page?.after ?? null, ...(again.length > 0 ? { wholeSince: 0 } : {}) })); const last = rows[rows.length - 1]; const after = syncStatus.carried(figures, rows); const { total, remaining, done } = syncStatus.standing(after, more); const now = new Date(); const answer: SyncAnswer = { version: more ? since : upto, rows: rows.map((r) => wire(r, caller.role !== "public")), server_time: now.toISOString(), ...this.generationFields(), total, remaining, done, tables: syncStatus.tablesOf(after) }; if (again.length > 0) answer.again = again; // The account's own switches a phone keeps beside its cursor (MAIL ALL ON PHONE: `mail_all`). if (this.store.meta(MAIL_ALL_META) !== null) answer.features = ["mail_all"]; // Whole tables erased since this pass's cursor (src/erase.ts): said on a pass's first page, so the phone retracts what it holds of them before it folds any row. if (!page) { const dropped = droppedSince(this.store, since); if (dropped) answer.dropped = dropped; } if (!more) { const bytes = this.ctx.storage.sql.databaseSize; if (bytes >= this.caps.database * DATABASE_WARN_FRACTION) answer.room = { bytes, cap: this.caps.database, used: Math.round((bytes / this.caps.database) * 10_000) / 10_000 }; // The space for photos and files, once the rules hold and it is 80% used or more (SPACE.md). if (this.personal() && this.spaceMode() === "on") { const held = Number(this.store.meta(MEDIA_BYTES) ?? "0"); const allowed = this.spaceAllowance(); if (held >= allowed * space.SPACE_WARN_FRACTION) answer.space = { bytes: held, allowance: allowed, used: Math.round((held / allowed) * 10_000) / 10_000 }; } // A day of use: an owner's own phone or Mac finished a pass (SPACE.md "Days of use"). if (caller.who && caller.role === "owner" && !caller.admin) this.spaceDay(now); } // A page whose walk stopped at its bound (MAIL SYNC BOUNDED) goes on from there, with or without rows. const goOn = resume ?? (last ? { version: last.version, table: last.table, id: last.id } : null); if (more && (goOn || firstNext)) answer.next = writeCursor({ since, upto, limit: asked, windows, tables, small, floor, after: goOn ?? { version: since, table: "", id: "" }, figures: after, ...(firstNext ? { first: firstNext } : {}), ...(again.length > 0 ? { again } : {}) }); else if (caller.role === "staff" || caller.role === "owner") answer.people = this.store.peopleSince(since).map(wirePerson); if (caller.who && defs.table(syncStatus.DEVICE_TABLE)) { const write = (fn: (engine: Engine, version: number, outcome: Outcome) => void): void => this.ctx.storage.transactionSync(() => fn(this.engine(defs), this.store.bump(), new Outcome_())); const facts = syncStatus.factsOf(params); const held = syncStatus.ownDevice(this.store, caller.who.deviceId) ?? syncStatus.fileDevice(caller.who.deviceId, facts, now, this.deviceCreate(defs)); // A phone names its running build on every pass: the row is restated // when it says otherwise (a later launch's build), and only then, so a // caught-up pass writes nothing and moves no version. if (held && facts && syncStatus.restates(held, facts)) syncStatus.refreshDevice(held, facts, write); answer.device = held?.id ?? null; if (held) syncStatus.recordPage(held, { rows, version: answer.version, more, figures: after, now }, write); // A device whose own key is wrapped on one row and published again, unwrapped, on another gets that wrap on the // other too, pulled on its next pass (owner at the Mac, 22 Nov 2026). if (defs.table(VAULT_KEY_TABLE) && this.ownKeyRowsToHeal(caller.who.deviceId).length > 0) write((engine, version, outcome) => this.healOwnKeyRows(caller.who!.deviceId, engine, version, outcome)); // Whether this device pulls messages and opens a kept chat picture sealed on a device (GET /v1/media-plain `waiting`). if (facts && caller.role === "owner") { const opens = (params.get("opens") ?? "").split(","); for (const [kind, { table, noted }] of Object.entries(MEDIA_OPENS_KINDS)) { this.noteOpens(noted, caller.who.deviceId, facts.name, !tables || tables.includes(table), opens.includes(kind), now); } } } return json(answer); } /** * `GET /v1/held?tables=
,…[&limit=]`, then `GET /v1/held?cursor=` * (src/protocol.ts `HeldAnswer`): the ids the object holds of `tables`, * live and binned, ids only, so a phone's top-up learns what the object * lacks without pulling every row's data (topup-ids, 11 Nov 2026). The * owner alone asks, as only the owner tops up; the tables are scoped as an * owner's sync with `tables` is (the object's internal tables hold nothing * here). A page is at most `limit` ids (default 20000, at most 50000) in * (table, id) order; the next page reads after the last id, so a row made * meanwhile may or may not be in the answer, and a top-up that sends it * again is answered as held. */ /** * `GET /v1/blind?table=
&tok=,…[&limit=]` (owner's devices * only, sealing plan §4): the ids of a sealed table's live rows holding * every token, newest first by its clear date column. Only a device holds * the key that makes tokens, so this is how a phone searches the object's * whole history beyond its own window; it pulls the rows and opens them * itself. Ids only, never a row's data, unless `rows=1` asks for the hits * as stored: sealed blobs and clear columns, what a sync page carries. */ private blind(caller: Caller, params: URLSearchParams): Response { if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "only the owner's own devices search a sealed table"); this.installed(); const table = params.get("table") ?? refuse(400, "bad_request", "name the table: table=
"); const t = this.definitions().table(table); if (!t || t.raw.internal === true) refuse(404, "no_such_table", `no table ${table}`); if (!t.seal) refuse(400, "not_sealed", `${table} is not a sealed table: search it as any other`); const said = (params.get("tok") ?? "").split(",").filter((x) => x !== ""); if (!said.length) refuse(400, "bad_blind", "name the tokens: tok=,…"); if (said.length > BLIND_PER_QUERY) refuse(400, "bad_blind", `at most ${BLIND_PER_QUERY} tokens a search`); const tokens = [...new Set(said.map((x) => blindToken(x) ?? refuse(400, "bad_blind", `${JSON.stringify(x)} is no token: each is the decimal text of a signed 64-bit number`)))]; const limit = params.has("limit") ? integer(params.get("limit"), "limit", 200) : 200; if (limit < 1 || limit > 1000) refuse(400, "bad_request", "limit is 1 to 1000"); const ids = this.store.blindIds(table, tokens, t.date ?? null, limit); // `rows=1`: the hits as the object stores them, sealed as they are, so a phone pulls rows beyond its own window to open itself. if (params.get("rows") === "1") return json({ table, ids, rows: ids.map((id) => this.store.get(table, id)).filter((r): r is StoredRow => r !== null).map((r) => wire(r, false)) }); return json({ table, ids }); } /** * `GET /v1/older?table=
[&before=[&id=]][&from=][&to=][&eq=:][&limit=]` * (owner's devices only, MAIL.md, 21 Nov 2026): a dated table's live rows older than `before` (exclusive; `id` the * last row a page carried, for rows of one moment), at or after `from` and at or before `to`, newest first by the * table's date column, as the object stores them: sealed blobs and clear columns, what a sync page carries. `eq` * keeps the rows whose clear `column` holds `value` (an email's `thread_id`). At most `limit` (default 50, at most * 1000). A phone that keeps a window of a table (Comms: the newest 90 days of mail) pages what is older from here * as a person scrolls past its window, and opens each row itself; only clear columns are asked about, so the * object learns which page of dates and which conversation, never a word. */ private older(caller: Caller, params: URLSearchParams): Response { if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "only the owner's own devices page a table"); this.installed(); const table = params.get("table") ?? refuse(400, "bad_request", "name the table: table=
"); const t = this.definitions().table(table); if (!t || t.raw.internal === true) refuse(404, "no_such_table", `no table ${table}`); const by = t.date ?? refuse(400, "bad_older", `${table} has no date column to page by`); const clear = (column: string): boolean => !t.seal || !isSealedColumn(t, column); if (!clear(by)) refuse(400, "bad_older", `${table}.${by} is sealed`); const day = (name: string): string | null => { const v = params.get(name); if (v === null) return null; if (v.length === 0 || v.length > 40) refuse(400, "bad_older", `${name} is a date`); return v; }; const before = day("before"); const id = params.get("id") ?? ""; const eqText = params.get("eq"); let eq: { column: string; value: string } | null = null; if (eqText !== null) { const at = eqText.indexOf(":"); const column = at > 0 ? eqText.slice(0, at) : ""; if (!/^[a-z_][a-z0-9_]*$/.test(column) || at === eqText.length - 1) refuse(400, "bad_older", "eq is :"); if (!clear(column)) refuse(400, "bad_older", `${table}.${column} is sealed`); eq = { column, value: eqText.slice(at + 1) }; } const limit = params.has("limit") ? integer(params.get("limit"), "limit", 50) : 50; if (limit < 1 || limit > 1000) refuse(400, "bad_request", "limit is 1 to 1000"); const rows = this.store.olderPage(table, by, { before: before === null ? null : [before, id], from: day("from"), to: day("to"), eq, limit }); return json({ table, by, rows: rows.map((r) => wire(r, false)), more: rows.length === limit }); } /** * Cotton Data's routes, `GET /v1/data/*` (src/data_routes.ts): the owner's own devices only, as `/v1/older` is, and * never the admin. Reads only. */ private dataAnswer(caller: Caller, path: string, params: URLSearchParams): Response { if (caller.role !== "owner" || caller.tokenId || caller.admin) refuse(403, "owner_only", "only the owner's own devices read Cotton Data"); this.installed(); const answer = dataRoute({ store: this.store, defs: this.definitions(), database: { bytes: this.ctx.storage.sql.databaseSize, cap: this.caps.database }, now: new Date() }, path, params); return answer ? json(answer) : refuse(404, "not_found", `no route ${path}`); } /** * `GET /v1/rows?table=
&ids=,…` (owner's devices only, Words' attached files, 22 Nov 2026): the live rows * of one table by their ids, at most 50, as the object stores them: sealed blobs and clear columns, what a sync page * carries. A phone whose kit keeps only some rows of a table (Words pulls web pages of `document`, never every PDF) * fetches the one a note attaches when it is opened, and opens it itself. An id the object does not hold live is * left out; the ids asked are the only thing the object learns. */ private rowsById(caller: Caller, params: URLSearchParams): Response { if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "only the owner's own devices fetch rows by id"); this.installed(); const table = params.get("table") ?? refuse(400, "bad_request", "name the table: table=
"); const t = this.definitions().table(table); if (!t || t.raw.internal === true) refuse(404, "no_such_table", `no table ${table}`); const ids = [...new Set((params.get("ids") ?? "").split(",").filter((id) => id.length > 0))]; if (ids.length === 0) refuse(400, "bad_request", "name the rows: ids=,…"); if (ids.length > 50 || ids.some((id) => id.length > 200)) refuse(400, "bad_request", "at most 50 ids a fetch"); return json({ table: t.id, rows: ids.map((id) => this.store.get(t.id, id)).filter((r): r is StoredRow => r !== null).map((r) => wire(r, false)) }); } /** * `GET /v1/bin?tables=
,…[&after=
:][&limit=]` (owner's devices only, TRIM 3, 21 Nov 2026): the * binned rows of `tables` (a clear `trashed_at` set), as the object stores them, sealed blobs and clear columns, in * (table, id) order, at most `limit` (default 200, at most 1000), `more` when a page follows after the last. A phone * keeps only the last 7 days of its Bin; its Bin lists the rest from here and opens each row itself. Only the clear * bin mark is asked about, never a word. */ /** * `GET /v1/media-plain?kind=messages|people&after=&limit=` (owner's devices only): this database's files of a kind * a device now seals that the bucket still holds plain, a page at a time in key order, `{files: [{key, bytes}], * next}`. The phone's pass (cotton-ffi phone::seal_kept) seals each and puts it back under its own key, which * replaces the plain one (owner's decision, 22 Nov 2026: kept chat pictures never sit unencrypted). Keys and sizes * only: nothing is read. */ private async mediaPlain(caller: Caller, params: URLSearchParams): Promise { if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "only the owner's own devices list plain files"); const kind = params.get("kind") ?? ""; if (!MEDIA_PLAIN_KINDS.includes(kind)) refuse(400, "bad_request", `kind is one of ${MEDIA_PLAIN_KINDS.join(", ")}`); const databaseId = this.store.meta("database_id") ?? refuse(409, "not_ready", "this database has no id yet"); const slug = this.meta().slug; // Not while a device that reads messages cannot open what the reseal leaves: it is named, and nothing listed. const waiting = this.resealWaitsFor(kind, new Date()); if (waiting.length > 0) return json({ files: [], next: null, waiting }); const limit = Math.min(Math.max(Number(params.get("limit") ?? 100) || 100, 1), 1000); const after = params.get("after"); if (after !== null && !after.startsWith(`${databaseId}/${kind}/`)) refuse(400, "bad_request", "after is a key this listing answered"); const prefix = `${slug}/${kind}/`; const files: { key: string; bytes: number }[] = []; let cursor: string | undefined; let startAfter = after === null ? undefined : `${slug}/${after.slice(databaseId.length + 1)}`; let more = true; // A page of R2 may hold sealed files only: read on until the page is full or the folder ends. while (files.length < limit && more) { const page = await this.env.MEDIA.list({ prefix, include: ["httpMetadata"], limit: 1000, ...(cursor ? { cursor } : startAfter ? { startAfter } : {}) }); for (const object of page.objects) { startAfter = object.key; if (isSealedType(object.httpMetadata?.contentType)) continue; files.push({ key: `${databaseId}/${object.key.slice(slug.length + 1)}`, bytes: object.size }); if (files.length >= limit) break; } more = page.truncated && files.length < limit; cursor = page.truncated ? page.cursor : undefined; if (files.length >= limit) more = false; } const last = files.at(-1); return json({ files, next: files.length >= limit && last ? last.key : null }); } /** The owner's devices that pull messages, and whether each said it opens sealed kept pictures; written when that changes, or an hour on. */ private noteOpens(noted: string, deviceId: string, name: string, reads: boolean, opens: boolean, now: Date): void { const sql = this.ctx.storage.sql; sql.exec(mediaOpensSchema(noted)); const held = sql.exec<{ reads: number; opens: number; seen_at: string }>(`SELECT reads, opens, seen_at FROM ${noted} WHERE device_id = ?`, deviceId).toArray()[0]; if (held && Boolean(held.reads) === reads && Boolean(held.opens) === opens && now.getTime() - Date.parse(held.seen_at) < 3_600_000) return; sql.exec( `INSERT INTO ${noted} (device_id, name, reads, opens, seen_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT (device_id) DO UPDATE SET name = excluded.name, reads = excluded.reads, opens = excluded.opens, seen_at = excluded.seen_at`, deviceId, name, reads ? 1 : 0, opens ? 1 : 0, now.toISOString(), ); } /** * The devices a reseal of `kind` waits for: of the owner's devices seen in the last 30 days, each that pulls the * kind's table and has not said it opens that kind sealed on a device (an app from before would read the resealed * file as garbage: a chat picture before 22 Nov 2026, a face before AVATAR SEAL), and each that has synced since * devices began to say it without saying either (it will on its next pass). */ private resealWaitsFor(kind: string, now: Date): string[] { const { noted: table, since: began } = MEDIA_OPENS_KINDS[kind]!; const sql = this.ctx.storage.sql; sql.exec(mediaOpensSchema(table)); const since = now.getTime() - MEDIA_OPENS_RECENT_MS; const noted = new Map(sql.exec<{ device_id: string; name: string; reads: number; opens: number; seen_at: string }>(`SELECT device_id, name, reads, opens, seen_at FROM ${table}`).toArray().map((r) => [r.device_id, r])); const waiting: string[] = []; for (const r of noted.values()) if (r.reads && !r.opens && Date.parse(r.seen_at) >= since) waiting.push(r.name); const defs = this.definitions(); if (defs.table(syncStatus.DEVICE_TABLE)) { for (const d of this.store.select(syncStatus.DEVICE_TABLE, [], "id", 1000).filter((r) => !r.data.revoked_at)) { const id = String(d.data.device_id ?? ""); const at = typeof d.data.synced_at === "string" ? Date.parse(d.data.synced_at) : NaN; if (id && !noted.has(id) && at >= since && Date.parse(began) <= at) waiting.push(String(d.data.name ?? "a device")); } } return waiting.sort(); } private bin(caller: Caller, params: URLSearchParams): Response { if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "only the owner's own devices list the Bin"); this.installed(); const defs = this.definitions(); const tables = (syncTables(params.get("tables")) ?? refuse(400, "bad_request", "name the tables: tables=
,…")).filter((t) => { const def = defs.table(t); return def !== null && def !== undefined && def.raw.internal !== true; }); const afterText = params.get("after"); let after: { table: string; id: string } | null = null; if (afterText !== null) { const at = afterText.indexOf(":"); if (at < 1 || at === afterText.length - 1) refuse(400, "bad_request", "after is
:"); after = { table: afterText.slice(0, at), id: afterText.slice(at + 1) }; } const limit = params.has("limit") ? integer(params.get("limit"), "limit", 200) : 200; if (limit < 1 || limit > 1000) refuse(400, "bad_request", "limit is 1 to 1000"); const { rows, more } = this.store.binnedPage(tables, after, limit); return json({ rows: rows.map((r) => wire(r, false)), more }); } /** * `GET /v1/landed[?after=][&limit=]` (MAIL PREDICATE phase 2, the backfill): each mail's id and when it * landed here (`rows.landed_at`), in id order after `after`, live mail only, never its data. A phone whose copy held * mail before schema 157 fills `cotton_emails.landed_at` from these pages in background slices instead of pulling * gigabytes again. The owner alone asks. A page is at most `limit` (default 5000, at most 20000); `after` in the * answer is the last id when more may follow. * * `GET /v1/landed?id=&id=…` (PHASE 2 PHONE 2, item 5): the same for named mail alone, at most 500 ids, live * mail only: the phone re-asks once a day for the mail its fill found no time for. */ private landed(caller: Caller, params: URLSearchParams): Response { if (caller.role !== "owner") refuse(403, "owner_only", "only the owner asks when its mail landed"); const ids = params.getAll("id"); if (ids.length > 0) { if (ids.length > 500) refuse(400, "bad_request", "at most 500 ids"); return json({ rows: this.store.landedOf(ids) }); } const limit = integer(params.get("limit"), "limit", 5_000); if (limit < 1 || limit > 20_000) refuse(400, "bad_request", "limit is 1 to 20000"); const { rows, more } = this.store.landedPage(params.get("after"), limit); const last = rows[rows.length - 1]; return json({ rows, ...(more && last ? { after: last[0] } : {}) }); } private held(caller: Caller, params: URLSearchParams): Response { if (caller.role !== "owner") refuse(403, "owner_only", "only the owner asks which rows the object holds"); this.installed(); const token = params.get("cursor"); const page = token ? readHeldCursor(token) : null; const asked = page ? page.limit : integer(params.get("limit"), "limit", 20_000); if (asked < 1 || asked > 50_000) refuse(400, "bad_request", "limit is 1 to 50000"); const named = page ? page.tables : syncTables(params.get("tables")); if (!named || named.length === 0) refuse(400, "bad_tables", "name the tables: tables=
,…"); const except = this.definitions().internalTables(); const tables = named.filter((t) => !except.has(t)); const { ids, more } = this.store.heldPage(tables, page?.after ?? null, asked); const held: HeldAnswer["held"] = {}; for (const r of ids) { const of = (held[r.table] ??= { live: [], binned: [] }); (r.deleted ? of.binned : of.live).push(r.id); } const answer: HeldAnswer = { held }; const last = ids[ids.length - 1]; if (more && last) answer.next = writeCursor({ tables: named, limit: asked, after: { table: last.table, id: last.id } }); return json(answer); } /** * The signed-in device's own `device` row, made or adopted from the facts * a call names (`device_name`, `platform`, `app_version` in the query), the * shape a phone's first sync page has: a device that writes but never * syncs (the Mac's importer, which names itself on /v1/me every pass) * is filed as the phone is. On `GET /v1/me` (`refresh`) a held row is * restated from the facts and its `updated_at` moved on. A call naming none * is untouched. */ private fileCaller(caller: Caller, params: URLSearchParams, refresh: boolean): void { const facts = syncStatus.factsOf(params); if (!caller.who || !facts) return; const held = syncStatus.ownDevice(this.store, caller.who.deviceId); if (held && !refresh) return; const defs = this.definitions(); if (!defs.table(syncStatus.DEVICE_TABLE)) return; const write = (fn: (engine: Engine, version: number, outcome: Outcome) => void) => this.ctx.storage.transactionSync(() => fn(this.engine(defs), this.store.bump(), new Outcome_())); if (held) syncStatus.refreshDevice(held, facts, write); else syncStatus.fileDevice(caller.who.deviceId, facts, new Date(), this.deviceCreate(defs)); } /** `message:30,email:90` → each table's date column from the day that many days back, in the business's zone. */ /** * A kit's `only` (`only=
.:|,…`, 21 Nov 2026): of each table named, the live rows whose * clear column holds one of the values. A sealed column is refused: the object cannot read it to choose. */ private onlys(defs: Definitions, text: string | null): SyncWindow[] { if (!text) return []; return text.split(",").map((part) => { const m = /^([a-z][a-z0-9_]*)\.([a-z][a-z0-9_]*):(.+)$/.exec(part.trim()); if (!m) refuse(400, "bad_only", `an only is
.:|, not ${part}`); const t = defs.table(m[1]!); if (!t) refuse(404, "no_such_table", `no table ${m[1]!}`); if (!t.columns.some((c) => c.key === m[2]!)) refuse(400, "bad_only", `${t.id} has no column ${m[2]!}`); if (isSealedColumn(t, m[2]!)) refuse(400, "bad_only", `${t.id}.${m[2]!} is sealed: the object cannot choose rows by it`); const is = m[3]!.split("|").filter((v) => v.length > 0); if (is.length === 0 || is.length > 20) refuse(400, "bad_only", `an only names one to twenty values, not ${part}`); return { table: t.id, column: m[2]!, from: "", is }; }); } private windows(defs: Definitions, text: string | null): SyncWindow[] { if (!text) return []; const today = localDate(new Date(), this.meta().timezone); return text.split(",").map((part) => { const m = /^([a-z][a-z0-9_]*):(\d{1,5})$/.exec(part.trim()); if (!m) refuse(400, "bad_window", `a window is
:, not ${part}`); const t = defs.table(m[1]!); if (!t) refuse(404, "no_such_table", `no table ${m[1]!}`); if (!t.date) refuse(400, "bad_window", `${t.id} has no date column to keep a window by`); return { table: t.id, column: t.date, from: addDays(today, -Number(m[2])) }; }); } // ── Mail on the person's own domain (src/mail) ───────────────────────── /** The Worker's email handler asks whether mail to `to` is this person's, and where its copy goes. */ async mailPlan(to: string): Promise { await this.frozenGate(); if (!this.reachable()) return { accept: false, mailbox: to, forwardTo: null }; return mail.plan(this.mailHost(), to); } /** The Worker's email handler hands over one message: kept sealed at arrival. */ async mailArrive(arrival: mail.Arrival): Promise { await this.frozenGate(); // Its own check (DELETE ACCOUNT 3), not only mailPlan's: an account set to be deleted, or erased, keeps no mail. this.refuseWhileDeleting(); if (!this.personal()) refuse(404, "not_found", "no mail here"); return mail.arrive(this.mailHost(), arrival); } /** Cloudflare's later word on a mail sent from here (src/mail/events.ts). */ async mailDelivered(messageId: string, delivery: "bounced" | "complained" | "failed" | "delivered", words: string | null): Promise { await this.frozenGate(); return mailSend.delivered(this.mailHost(), messageId, delivery, words); } private mailHost(): mail.MailHost { const databaseId = this.databaseId(); return { env: this.env, store: this.store, sql: this.ctx.storage.sql, databaseId, now: () => Date.now(), arrivalPub: () => arrivalPublic((table, id) => this.store.get(table, id)), keepFile: async (key, plain) => { const kept = await asArrived(databaseId, arrivalPublic((table, id) => this.store.get(table, id)), key, plain, "message/rfc822", SEALED_FILE_TYPE); await storeMedia(this.env, bucketKey(key, databaseId, this.slug), kept.bytes, kept.contentType, this.mediaBudget()); }, writeSealed: (fn) => { this.roomToWrite(); return this.writeSealing((engine) => (engine.journal = new Journal(this.store, null, "mail", "act")), fn); }, alert: async () => { const devices = this.ctx.storage.sql.exec<{ device_id: string; platform: "ios" | "android" | null; token: string | null; topic: string | null; sandbox: number }>("SELECT device_id, platform, token, topic, sandbox FROM chat_device").toArray(); await Promise.all( devices.map(async (d) => { if (!d.platform || !d.token) return; const outcome = await mailAlert(this.env, { platform: d.platform, token: d.token, topic: d.topic ?? "", sandbox: d.sandbox === 1 }); if (outcome === "gone") this.ctx.storage.sql.exec("UPDATE chat_device SET token = NULL, platform = NULL, topic = NULL WHERE device_id = ?", d.device_id); }), ); }, }; } /** * The owner's mail routes: * * GET /v1/mail/settings domains (with each proof record), addresses * POST /v1/mail/domains { domain } add one: its proof record * POST /v1/mail/domains/check { domain } read its DNS; proved, its mail comes here * POST /v1/mail/domains/catch-all { domain, on } * DELETE /v1/mail/domains?domain= its mail no longer comes here * POST /v1/mail/addresses { address, forwardTo?, isDefault? } * DELETE /v1/mail/addresses?address= * POST /v1/mail/send { draft, from, to, cc, subject, text, inReplyTo?, references? } * GET /v1/mail/sends?draft=… the ledger's word on each draft named * GET /v1/mail/tally?days=14 each day's arrivals: came, copied, kept * POST /v1/mail/arrived { ids } which of these email ids came by the domain (the Mac's cross-check) * GET /v1/mail/raw messages kept raw only, for the phone to read * POST /v1/mail/raw/read { id, email? } */ /** The sockets Cotton's fetcher holds open, by account (src/mail/fetch.ts): closed when the password is removed. */ private readonly fetchSockets = new Map>(); private fetchHost(): mailFetch.FetchHost { return { sql: this.ctx.storage.sql, env: this.env, databaseId: this.store.meta("database_id") ?? "", now: () => Date.now(), close: (account) => { for (const conn of this.fetchSockets.get(account) ?? []) { try { conn.close(); } catch { // already closed } } this.fetchSockets.delete(account); }, }; } /** Cotton's fetcher on this object (src/mail/fetcher.ts); `dial` is the Worker's TCP socket, a fake server in the tests. */ private fetcherHost(dial: imap.Dial = imap.dial): mailFetcher.FetcherHost { return { ...this.fetchHost(), dial, arrive: (raw, address, received, fetched) => mail.arrive(this.mailHost(), { raw, to: address, forwarded: "none", received, fetched }), hold: (account, conn) => { const held = this.fetchSockets.get(account) ?? new Set(); held.add(conn); this.fetchSockets.set(account, held); }, release: (account, conn) => { const held = this.fetchSockets.get(account); held?.delete(conn); if (held && !held.size) this.fetchSockets.delete(account); }, stopped: () => this.mailJobsOn(), }; } /** Whether this account's mail is fetched by the job beside it (JOBS OUT 1), not by its own alarm. */ private mailJobsOn(): boolean { return this.store.meta(mailJob.SWITCH) === "on"; } /** The message the mailbox's next run is put on the queue with, its credential minted now (the tests run it themselves). */ async mailJobMessage(account: string, delayMs = 0): Promise { await this.frozenGate(); return mailJob.message(this.jobHost(), account, delayMs); } /** What the mail job's door and its scheduling lend from this object (src/mail/fetch_job.ts). */ private jobHost(): mailJob.JobHost { return { ...this.fetcherHost(), slug: this.store.meta("slug") ?? this.slug, on: () => this.mailJobsOn(), arrivalPub: () => arrivalPublic((table, id) => this.store.get(table, id)) }; } /** One pass of Cotton's fetcher over every mailbox due (the alarm's; a test hands its own fake server's `dial`). */ async fetchMailPass(dial?: imap.Dial): Promise<{ next: number | null; results: mailFetcher.PassResult[] }> { await this.frozenGate(); if (!this.personal() || !mailFetch.accounts(this.ctx.storage.sql).length) return { next: null, results: [] }; return mailFetcher.pass(this.fetcherHost(dial)); } /** IDLE held on every live mailbox for one window, new mail read as it is said (src/mail/fetcher.ts `watch`): the alarm's, after its pass. Answers how many came. */ async fetchMailWatch(dial?: imap.Dial, windowMs?: number): Promise { await this.frozenGate(); if (!this.personal()) return 0; const host = this.fetcherHost(dial); const counts = await Promise.all(mailFetch.accounts(this.ctx.storage.sql).map((a) => mailFetcher.watch(host, a.account, windowMs))); return counts.reduce((n, c) => n + c, 0); } /** `POST /v1/mail/send`: one draft through the ledger, by the person's domain or (`route: "smtp"`) a mailbox given to Cotton; a test hands its fake SMTP server. */ async mailSendAsk(body: Record, dial?: imap.Dial): Promise { await this.frozenGate(); const host = this.mailHost(); return mailSend.send(host, mailSend.readAsk(host, body), this.slug, this.fetcherHost(dial)); } /** One act on a mailbox given to Cotton, done there inside the request (src/mail/acts.ts); a test hands its fake server and fake web. */ async fetchMailAct(body: Record, dial?: imap.Dial, post?: typeof globalThis.fetch): Promise { await this.frozenGate(); if (!this.personal()) refuse(404, "not_found", "no mail here"); return mailActs.act(this.fetcherHost(dial), body, post); } private async mailRoute(caller: Caller, request: Request, path: string): Promise { if (caller.role !== "owner") refuse(403, "owner_only", "only the owner's devices reach their mail"); const host = this.mailHost(); const url = new URL(request.url); const m = request.method; if (m === "GET" && path === "/v1/mail/settings") return json({ domains: mail.domains(host), addresses: mail.addresses(host), sending: Boolean(this.env.EMAIL) }); if (m === "POST" && path === "/v1/mail/domains") { const body = await readJson(request); return json(mail.addDomain(host, String(body.domain ?? "").trim().toLowerCase())); } if (m === "POST" && path === "/v1/mail/domains/check") { const body = await readJson(request); const domain = String(body.domain ?? "").trim().toLowerCase(); const held = mail.domains(host).find((d) => d.domain === domain) ?? refuse(404, "unknown_domain", `add ${domain} first`); const code = held.proof.value.slice("cotton-verify=".length); const check = await mailDns.checkDomain(domain, code); if (check.proved) { const taken = await directory(this.env).mailDomainSet(domain, this.slug); if ("refused" in taken) refuse(taken.refused.status, taken.refused.code, taken.refused.message); mail.provedDomain(host, domain); } return json(check); } if (m === "POST" && path === "/v1/mail/domains/catch-all") { const body = await readJson(request); mail.setCatchAll(host, String(body.domain ?? "").toLowerCase(), body.on === true); return json({ domains: mail.domains(host) }); } if (m === "DELETE" && path === "/v1/mail/domains") { const domain = (url.searchParams.get("domain") ?? "").toLowerCase(); await directory(this.env).mailDomainDrop(domain, this.slug); this.ctx.storage.sql.exec("DELETE FROM mail_domain WHERE domain = ?", domain); this.ctx.storage.sql.exec("DELETE FROM mail_address WHERE address LIKE ?", `%@${domain}`); this.ctx.storage.sql.exec("DELETE FROM mail_address_gone WHERE address LIKE ?", `%@${domain}`); return json({ domains: mail.domains(host), addresses: mail.addresses(host) }); } if (m === "POST" && path === "/v1/mail/addresses") return json(mail.setAddress(host, await readJson(request))); // Cotton fetches (src/mail/fetch.ts): a mailbox's password is given from the owner's own signed-in phone alone. if (path === "/v1/mail/fetch" || path.startsWith("/v1/mail/fetch/")) { if (!caller.who?.deviceId || caller.tokenId) refuse(403, "device_only", "a mailbox is given to Cotton from your own signed-in phone"); const fetchHost = this.fetchHost(); if (m === "POST" && path === "/v1/mail/fetch") { const given = await mailFetch.give(fetchHost, await readJson(request)); if (this.mailJobsOn()) { // A new generation: a run for the mailbox as it was given before opens nothing now. mailJob.renew(this.ctx.storage.sql, given.account); await mailJob.schedule(this.jobHost(), given.account, 0); } else await this.ctx.storage.setAlarm(Date.now()); return json(given); } if (m === "DELETE" && path === "/v1/mail/fetch") { const body = request.headers.get("content-type")?.includes("json") ? await readJson(request) : { account: url.searchParams.get("account") }; const removed = mailFetch.remove(fetchHost, body); mailJob.drop(this.ctx.storage.sql, String(body.account)); return json(removed); } if (m === "POST" && path === "/v1/mail/fetch/act") return json(await this.fetchMailAct(await readJson(request))); if (m === "GET" && path === "/v1/mail/fetch/state") { const account = url.searchParams.get("account"); const st = mailFetch.state(this.ctx.storage.sql, account); const job = st.state !== "stopped" && account ? mailJob.stateOf(this.ctx.storage.sql, account) : null; return json(job ? { ...st, ...job } : st); } if (m === "GET" && path === "/v1/mail/fetch/log") return json(mailFetch.readLog(this.ctx.storage.sql, url.searchParams.get("account"), url.searchParams.get("limit") ?? undefined)); } if (m === "DELETE" && path === "/v1/mail/addresses") { // The address in the body (Post CONTRACT) or, as earlier builds send it, in the query. const body = request.headers.get("content-type")?.includes("json") ? await readJson(request) : {}; const asked = typeof body.address === "string" ? body.address : (url.searchParams.get("address") ?? ""); const { removed } = mail.dropAddress(host, asked.toLowerCase()); return json({ removed, addresses: mail.addresses(host) }); } if (m === "POST" && path === "/v1/mail/send") return json(await this.mailSendAsk(await readJson(request))); if (m === "GET" && path === "/v1/mail/sends") return json({ sends: url.searchParams.getAll("draft").map((d) => mailSend.ledger(host, d) ?? { draft: d, state: null }) }); if (m === "GET" && path === "/v1/mail/tally") return json({ days: mail.tallyDays(host, Math.min(90, Math.max(1, Number(url.searchParams.get("days") ?? 14) || 14))) }); // DEV AND TESTS ONLY: the owner hands their own object a raw message as Email Routing would, for the proof at // size on a dev Worker that has no routing (OWN-MAIL.md "What proves each stage"). Refused on any other Worker. // DEV AND TESTS ONLY, beside it: an invented domain held as proved without DNS, never told to the Directory, so // no real mail is ever routed to it. if (m === "POST" && path === "/v1/mail/domains/prove-dev") { if (!devWorker(this.env)) refuse(404, "not_found", "no such route"); const domain = String((await readJson(request)).domain ?? "").trim().toLowerCase(); if (!mail.domains(host).some((d) => d.domain === domain)) refuse(404, "unknown_domain", `add ${domain} first`); mail.provedDomain(host, domain); return json({ domain, proved: true }); } if (m === "POST" && path === "/v1/mail/arrive-raw") { if (!devWorker(this.env)) refuse(404, "not_found", "no such route"); const to = (request.headers.get("x-mail-to") ?? "").trim().toLowerCase(); const plan = mail.plan(host, to); if (!plan.accept) refuse(404, "no_such_mailbox", `${to} is not one of your addresses here`); const raw = new Uint8Array(await request.arrayBuffer()); if (raw.byteLength === 0 || raw.byteLength > mail.MAX_MESSAGE_BYTES) refuse(413, "too_large", "a message is 1 byte to 25 MiB"); const at = Date.now(); const arrived = await mail.arrive(host, { raw, to: plan.mailbox, forwarded: "none", received: at }); return json({ ...arrived, ms: Date.now() - at }); } if (m === "POST" && path === "/v1/mail/arrived") { const body = await readJson(request); const ids = Array.isArray(body.ids) ? body.ids.filter((i): i is string => typeof i === "string").slice(0, 1000) : []; return json({ arrived: mail.arrivedIds(host, ids) }); } if (m === "GET" && path === "/v1/mail/raw") return json({ raw: mail.rawOnly(host) }); if (m === "POST" && path === "/v1/mail/raw/read") { const body = await readJson(request); mail.rawRead(host, String(body.id ?? ""), typeof body.email === "string" ? body.email : null); return json({ ok: true }); } refuse(405, "method_not_allowed", `${m} ${path} is not served`); } // ── Google Calendar ──────────────────────────────────────────────────── /** The owner's Google routes (src/google.ts, src/google_write.ts): connect, status, disconnect, settings, events. */ private async google(caller: Caller, request: Request, path: string): Promise { if (caller.role !== "owner") refuse(403, "owner_only", "only the owner connects Google"); const host = this.googleHost(); if (request.method === "GET" && path === "/v1/google/connect") return json(await google.connect(host)); if (request.method === "GET" && path === "/v1/google/status") return json(google.status(host)); if (request.method === "POST" && path === "/v1/google/disconnect") return json(await google.disconnect(host, request)); if (request.method === "POST" && path === "/v1/google/settings") return json(await google.settings(host, request)); if (request.method === "POST" && path === "/v1/google/events") return googleWrite.events(host, request); if (request.method === "POST" && path === "/v1/google/pull") { // Dev and test only (GCAL READY, 24 Nov 2026): the calendar pull now, not at its next 15 minutes, so a proof // against the fake Google (src/fake_google) sees at once what changed there. The pull itself is the alarm's. if (!devWorker(this.env)) refuse(404, "not_found", "no such route"); await host.wake(); return json({ pulling: true }); } refuse(405, "method_not_allowed", `${request.method} ${path} is not served`); } /** * One write in one transaction whose rows and changes in a sealed table * are sealed at arrival (src/arrival_seam.ts): run once and rolled back when * it made any, sealed, then run again writing them sealed. `fn` must write * the same given the same store: it is called twice, so it keeps what it * changes outside the store to its answer. */ private async writeSealing(setUp: (engine: Engine) => void, fn: (engine: Engine, version: number, outcome: Outcome) => T): Promise { const defs = this.definitions(); const first = this.engine(defs); const clock = first.clock; const capture = new Capture(); const run = (engine: Engine): T => this.ctx.storage.transactionSync(() => { setUp(engine); const answer = fn(engine, this.store.bump(), new Outcome_()); if (engine.arrival === capture && capture.noted.length) throw new RollBack(); if (engine.arrival instanceof Apply) engine.arrival.done(); return answer; }); first.arrival = capture; try { return run(first); } catch (error) { if (!(error instanceof RollBack)) throw error; } const sealed = await sealNoted(this.store, this.databaseId(), defs, capture.noted); const second = this.engine(defs, clock); second.arrival = new Apply(sealed, capture.fresh); return run(second); } private googleHost(): google.GoogleHost { return { env: this.env, store: this.store, sql: this.ctx.storage.sql, databaseId: this.databaseId(), zone: this.meta().timezone, write: (fn) => { this.roomToWrite(); return this.ctx.storage.transactionSync(() => { const engine = this.engine(); engine.journal = new Journal(this.store, null, "google", "act"); return fn(engine, this.store.bump(), new Outcome_()); }); }, writeSealed: (fn) => { this.roomToWrite(); return this.writeSealing((engine) => (engine.journal = new Journal(this.store, null, "google", "act")), fn); }, wake: () => this.ctx.storage.setAlarm(Date.now()), }; } // ── Spotify ────────────────────────────────────────────────────────── /** The owner's Spotify routes (src/spotify.ts): connect, status, disconnect. */ private async spotify(caller: Caller, request: Request, path: string): Promise { if (caller.role !== "owner") refuse(403, "owner_only", "only the owner connects Spotify"); const host = this.spotifyHost(); if (request.method === "GET" && path === "/v1/spotify/connect") return json(await spotify.connect(host)); if (request.method === "GET" && path === "/v1/spotify/status") return json(spotify.status(host)); if (request.method === "POST" && path === "/v1/spotify/disconnect") return json(spotify.disconnect(host)); refuse(405, "method_not_allowed", `${request.method} ${path} is not served`); } private spotifyHost(): spotify.SpotifyHost { return { env: this.env, store: this.store, sql: this.ctx.storage.sql, databaseId: this.databaseId(), write: (fn) => { this.roomToWrite(); return this.ctx.storage.transactionSync(() => { const before = this.store.version(); const version = this.store.bump(); const engine = this.engine(); engine.journal = new Journal(this.store, null, "spotify", "act"); const outcome = new Outcome_(); const answer = fn(engine, version, outcome); // A write that changed nothing moves no version. if (!outcome.changed.length) this.store.setMeta("version", String(before)); return answer; }); }, writeSealed: (fn) => { this.roomToWrite(); return this.writeSealing((engine) => (engine.journal = new Journal(this.store, null, "spotify", "act")), fn); }, wake: () => this.ctx.storage.setAlarm(Date.now()), fetcher: (input, init) => fetch(input, init), }; } private me(caller: Caller): Response { if (!caller.person) refuse(401, "not_signed_in", "sign in first"); return json({ person: wirePerson(caller.person), business: this.meta(), version: this.store.version(), ...this.generationFields() }); } // ── sign-in ──────────────────────────────────────────────────────────── private async code(request: Request): Promise { this.installedOrPending(); const body = await readJson(request); const phone = normalizePhone(text(body.phone, "phone")); if (!phone) refuse(400, "bad_phone", "use an international phone number starting with +"); const deviceId = text(body.device_id, "device_id"); // The personal database admits its owner, and a person the owner put on it, and nobody else: no code is sent. if (!this.admits(phone)) this.refuseAsMissing(); const answer = await issueCode(this.env, this.store, new Date(), phone, deviceId); // The code is never said, fixed or Twilio: the person types the one they know (owner, 25 Oct 2026). // Whether the business already knows this phone: a stranger is asked their name once, with the code. A personal // database never says it (ROUTES-AUDIT 6): there it meant "has signed in to Cotton before", so it answers false // to every number. A phone then offers the name field each time; sign-in keeps a name already given. const known = this.personal() ? false : Boolean(this.store.personByPhone(phone)); return json({ ...answer, known }); } /** * Who may sign in here (ROUTES-AUDIT 1). A business object admits anyone, as a member. A personal database admits * its owner's number and a person the owner put on it (`set_role`, the admin's `/person`), and nobody else. */ private admits(phone: string): boolean { if (!this.personal()) return true; return phone === this.meta().owner_phone || this.store.personByPhone(phone) !== null; } private async signIn(request: Request): Promise { const absent = this.absent(); if (!absent) this.installedOrPending(); const body = await readJson(request); const challenge = text(body.challenge_id, "challenge_id"); const code = text(body.code, "code"); const deviceId = text(body.device_id, "device_id"); // STRANGER BLIND: where no database is, no code was ever sent, so every code is wrong, as a stranger's is. if (absent) this.refuseAsWrongCode(); const name = optionalText(body.name); // THE NAME AFTER THE CODE (NEXT-SIGNIN, owner, 28 Nov 2026): a phone that says `name_after` sends no name with the // code. The code is proved first; a number with no account here is then answered `name_needed` and nothing is made, // and the same device sends the very code it just proved again, now with the name. A number that has an account // goes straight in. Whether a number is here is never said before its code is proved (the code's answer is the same // for every number). A phone from before sends the name with the code, as it always did. const nameAfter = body.name_after === true; const now = new Date(); const again = nameAfter && name ? await provenAlready(this.store, now, challenge, code, deviceId) : null; const phone = again !== null && !this.store.personByPhone(again) ? again : await proveCode(this.env, this.store, now, challenge, code, deviceId); // ROUTES-AUDIT 1 (23 Nov 2026): a code proved elsewhere on this object (the connect page's phone step) never made // a stranger a member of a personal database. Nothing is made, nothing granted. if (!this.admits(phone)) this.refuseAsWrongCode(); if (nameAfter && !name && !this.store.personByPhone(phone)) return json({ name_needed: true }); // AUDIT F: the kit is laid now, for the number's own person, never for a stranger's code. if (this.store.meta(KIT_PENDING)) this.finishKit(); let answer: SignInAnswer | undefined; this.ctx.storage.transactionSync(() => { let person = this.store.personByPhone(phone); const version = this.store.bump(); if (!person) { const role = this.meta().owner_phone === phone ? "owner" : "member"; person = this.store.addPerson(crypto.randomUUID(), phone, name, role, version); } else if (name && !person.name) { person = this.store.setPerson(person.id, { name }, version); } if (person.role === "member") this.ensureOwnCard(person, version, new Outcome_()); answer = { credential: "", person: wirePerson(person), version }; }); // The owner's person is made now, named what this sign-in said (src/owner.ts), never at the code's request before it. await this.keepOwner(); const person = this.store.personByPhone(phone)!; const credential = await grant(this.store, now, person, deviceId); // In its thirty days, the sign-in says so: the phone asks Keep my account or Leave it to be deleted. const setToGo = accountDelete.pending(this.ctx.storage.sql); return json({ ...answer!, credential, expires_in: CREDENTIAL_TTL_SECONDS, ...(setToGo ? { deleting: { erase_at: setToGo.eraseAt } } : {}) } satisfies SignInAnswer & { expires_in: number }); } private signOut(caller: Caller): Response { if (caller.who) this.store.revokeSession(caller.who.tokenHash); // A phone signed out is rung no more. if (caller.who) calling.forgetDevice(this.ctx.storage.sql, caller.who.deviceId); // Nor written to: its chat key, what waits for it and its sockets go. if (caller.who) chat.forgetDevice(this.chatHost(), caller.who.deviceId); return json({ ok: true }); } // ── deleting the account (src/account_delete.ts) ───────────────────── /** A signed-in device of the owner, and nothing else: no token, no admin, no assistant. */ private async deleteAccount(caller: Caller, request: Request, path: string): Promise { if (!accountDelete.switchedOn(this.env)) return accountDelete.notAvailable(path); if (!caller.who || !caller.person || caller.tokenId || caller.admin || caller.person.role !== "owner") refuse(403, "device_only", "only the owner's own signed-in device deletes this account"); const device = `${accountDelete.DEVICE_PREFIX}${caller.who.deviceId}`; const phone = this.meta().owner_phone; if (!phone || caller.person.phone !== phone) refuse(403, "device_only", "only the owner's own signed-in device deletes this account"); if (path === "/v1/account/delete/code") return json(await issueCode(this.env, this.store, new Date(), phone, device)); const body = await readJson(request); if (body.confirm !== accountDelete.CONFIRM) refuse(400, "not_confirmed", 'say confirm: "delete" to delete this account'); await proveCode(this.env, this.store, new Date(), text(body.challenge_id, "challenge_id"), text(body.code, "code"), device); return json(await this.deletionStarted(await accountDelete.start(this.deleteHost(), "app", this.deleteMeta())), 202); } /** * The thirty days (src/account_delete.ts): the owner's number may still ask a code and sign in, and that sign-in * may ask where it stands, keep the account, or leave it to be deleted. Everything else is answered as deleted. */ private async whileDeleting(request: Request, j: accountDelete.Job): Promise { const path = new URL(request.url).pathname; const method = request.method; this.slug = request.headers.get(SLUG_HEADER) ?? this.store.meta("slug") ?? ""; if (method === "POST" && path === "/v1/code") return this.code(request); if (method === "POST" && path === "/v1/sign-in") return this.signIn(request); // The admin's two, in the thirty days too: the hold, and on dev the date brought to now. if (method === "POST" && (path === "/v1/admin/account/hold" || path === "/v1/admin/account/erase-now")) return this.deleteAdmin(request, path); if (!accountDelete.GRACE_PATH.test(path)) return null; const token = bearer(request); const who = token?.startsWith("ctn_") || isAdminToken(this.env, token) ? null : await whoIs(this.store, new Date(), token); if (!who || who.person.role !== "owner" || who.person.phone !== this.meta().owner_phone) refuse(403, "device_only", "only the owner's own sign-in keeps this account"); if (method === "GET" && path === "/v1/account/deleting") return json({ deleting: { erase_at: j.eraseAt, started_at: j.startedAt } }); if (method === "POST" && path === "/v1/account/keep") { return json(await accountDelete.keep(this.deleteHost())); } if (method === "POST" && path === "/v1/account/leave") { this.store.revokeSession(who.tokenHash); return json({ left: true, erase_at: j.eraseAt }); } return null; } /** * The admin's hold on deleting this account (src/account_delete.ts HOLD), and on dev the thirty days ended now * (`erase-now`, refused on live). The admin token only. */ private async deleteAdmin(request: Request, path: string): Promise { if (!isAdminToken(this.env, bearer(request))) refuse(403, "admin_only", "the admin token only"); if (!this.personal()) refuse(404, "not_personal", "only a person's account is deleted"); if (path === "/v1/admin/account/hold") { const { hold } = await readJson(request); if (typeof hold !== "boolean") refuse(400, "bad_request", "hold is true or false"); this.store.setMeta(accountDelete.HOLD, hold ? "on" : null); // A legal hold is logged, set and taken away alike, by the object's name alone (no number, no name). accountDelete.holdLogged(this.ctx.storage.sql, this.store, hold, this.meta().slug); const j = accountDelete.pending(this.ctx.storage.sql); return json({ hold, deleting: j ? { erase_at: j.eraseAt } : null, log: accountDelete.holdLog(this.store) }); } if (!accountDelete.mayEraseNow(this.env)) refuse(404, "not_available", "the erase is brought to now on the dev Worker only"); // Dev only: the object cut off once mid-erase (`kill_after`), as an eviction would, to prove the erase resumes. const body = request.headers.get("content-length") === "0" ? {} : await readJson(request).catch(() => ({}) as Record); this.killAt = accountDelete.KILL_POINTS.find((k) => k === body.kill_after) ?? null; return json(await accountDelete.eraseNow(this.deleteHost())); } /** A Keep cut off before it finished, finished now; while it cannot be, refused in its own words (503 `keeping`). */ private async finishKeepOrSay(): Promise { if (accountDelete.job(this.ctx.storage.sql)?.phase !== "keeping") return; try { await accountDelete.keep(this.deleteHost()); } catch { await accountDelete.ensureAlarm(this.deleteHost()); refuse(503, "keeping", "Your account is being kept; try again in a moment."); } } /** From the web, by RPC from the door (src/open.ts): a code to the owner's number, bound to the browser. Never for anyone else's number. */ async deleteCode(phone: string, browserId: string): Promise<{ challenge_id: string; expires_in: number } | { refused: { status: number; code: string; message: string } }> { await this.frozenGate(); try { if (!accountDelete.switchedOn(this.env)) refuse(404, "not_available", "Deleting an account is not available yet."); // Asked again in the thirty days, a code still goes: the first date stands (`start`). A Keep not yet finished is // finished first (DELETE ACCOUNT 3), or said as being kept, never as deleted. await this.finishKeepOrSay(); if (accountDelete.job(this.ctx.storage.sql) && !accountDelete.pending(this.ctx.storage.sql)) accountDelete.refuseDeleted(); if (!this.personal() || this.meta().owner_phone !== phone) refuse(404, "no_account", "no account to delete"); return await issueCode(this.env, this.store, new Date(), phone, `${accountDelete.WEB_PREFIX}${browserId}`); } catch (error) { if (error instanceof Refused) return { refused: { status: error.status, code: error.code, message: error.message } }; throw error; } } /** From the web: the code proved for the browser that asked, and the deletion begun. */ async deleteConfirm(challengeId: string, code: string, browserId: string): Promise<{ deleting: true; started_at: string; erase_at: string | null } | { refused: { status: number; code: string; message: string } }> { await this.frozenGate(); try { if (!accountDelete.switchedOn(this.env)) refuse(404, "not_available", "Deleting an account is not available yet."); await this.finishKeepOrSay(); if (accountDelete.job(this.ctx.storage.sql) && !accountDelete.pending(this.ctx.storage.sql)) accountDelete.refuseDeleted(); if (!this.personal()) refuse(404, "no_account", "no account to delete"); const phone = await proveCode(this.env, this.store, new Date(), challengeId, code, `${accountDelete.WEB_PREFIX}${browserId}`); if (phone !== this.meta().owner_phone) refuse(401, "invalid_code", "invalid or expired code"); return await this.deletionStarted(await accountDelete.start(this.deleteHost(), "web", this.deleteMeta())); } catch (error) { if (error instanceof Refused) return { refused: { status: error.status, code: error.code, message: error.message } }; throw error; } } /** * The directory's sweep asks after a deletion it holds (src/account_delete.ts `resume`): the alarm made sure of, or * a deletion cut off between its storage going and its closing row written, closed from the directory's receipt. */ async deleteResume(): Promise<{ phase: string; erase_at: string | null }> { await this.frozenGate(); return accountDelete.resume(this.deleteHost()); } /** The admin's read-only check (src/open.ts `/v1/admin/deletions/check`): this object's own deletion phase, or live. */ async deleteStanding(): Promise { await this.frozenGate(); return accountDelete.standing(this.ctx.storage.sql); } /** The admin's read-only founder row check (src/open.ts `/v1/admin/vault-keys/check`, src/vault_key_check.ts): kinds and counts only. */ async vaultKeyStanding(): Promise { await this.frozenGate(); return vaultKeyCheck(this.ctx.storage.sql); } /** Cotton's own database forgets every report a deleted account's number sent, with its picture and log; how many went. */ async feedbackForget(phone: string): Promise { await this.frozenGate(); if (this.store.meta("kind") === "personal" || !this.store.holdsDefinitions("table") || !this.definitions().table(feedback.TABLE)) return 0; const sql = this.ctx.storage.sql; const sent = sql.exec<{ id: string; data: string }>("SELECT id, data FROM rows WHERE table_id = ? AND deleted = 0 AND json_extract(data, '$.sender_number') = ?", feedback.TABLE, phone).toArray(); if (!sent.length) return 0; const files: string[] = []; for (const row of sent) { const data = JSON.parse(row.data) as Record; for (const key of [data.screenshot, data.log]) if (typeof key === "string" && key.startsWith(`${this.meta().slug}/feedback/`)) files.push(key); } // A picture is kept by its hash: one another report still names stays. const kept = new Set( sql.exec<{ k: string | null }>("SELECT json_extract(data, '$.screenshot') AS k FROM rows WHERE table_id = ? AND deleted = 0 AND json_extract(data, '$.sender_number') IS NOT ? UNION SELECT json_extract(data, '$.log') FROM rows WHERE table_id = ? AND deleted = 0 AND json_extract(data, '$.sender_number') IS NOT ?", feedback.TABLE, phone, feedback.TABLE, phone).toArray().map((r) => r.k), ); const drop = [...new Set(files)].filter((k) => !kept.has(k)); if (drop.length) await this.env.PHOTOS.delete(drop); this.ctx.storage.transactionSync(() => { const version = this.store.bump(); for (const row of sent) { const held = this.store.any(feedback.TABLE, row.id); // A tombstone with no data, so a device that holds the report drops it too; the change log and the act log forget it. if (held) this.store.tombstone(held, version); sql.exec("DELETE FROM change WHERE table_id = ? AND record_id = ?", feedback.TABLE, row.id); sql.exec("DELETE FROM acts WHERE args LIKE ?", `%${row.id}%`); } }); console.log(`cottondb: feedback forget: ${sent.length} reports of a deleted account, ${drop.length} files`); return sent.length; } private deleteMeta(): { databaseId: string | null; slug: string; ownerPhone: string | null } { return { databaseId: this.store.meta("database_id"), slug: this.meta().slug, ownerPhone: this.meta().owner_phone ?? null }; } /** Where this object marks, by its own Durable Object id, that it began wiping its storage (src/account_delete.ts `storage`). */ private erasingKey(): string { return `erasing/${this.ctx.id.toString()}`; } private deleteHost(): accountDelete.DeleteHost { return { sql: this.ctx.storage.sql, storage: this.ctx.storage, env: this.env, now: () => new Date(), revokeGoogle: () => google.revokeAll(this.googleHost()), forgetInDirectory: (databaseId, slug) => directory(this.env).forget(databaseId, slug), leaveSpaces: () => this.leaveSpaces(), leaveRecovery: () => this.leaveRecovery(), tellPeople: () => chat.tellGone(this.chatHost()), forgetReports: async (phone) => { const product = this.env.BUSINESS.get(this.env.BUSINESS.idFromName(feedback.FEEDBACK_SLUG), { locationHint: "apac" }) as unknown as { feedbackForget(phone: string): Promise }; return product.feedbackForget(phone); }, closeInDirectory: (databaseId, receipt) => directory(this.env).closed(databaseId, receipt), abortUploads: () => accountDelete.abortOpenUploads(this.ctx.storage.sql, this.env.MEDIA), ledgerQuiet: () => this.ledgerQuiet(), forgetReceipt: (databaseId) => directory(this.env).forgetReceipt(databaseId), erasing: { put: async (mark) => void (await this.env.PHOTOS.put(this.erasingKey(), JSON.stringify(mark))), get: async () => { const held = await this.env.PHOTOS.get(this.erasingKey()); return held ? ((await held.json()) as accountDelete.ErasingMark) : null; }, clear: () => this.env.PHOTOS.delete(this.erasingKey()), }, holdsAccount: () => { // Judged by the account's meta alone (DELETE ACCOUNT 3): the deletion's table being there says nothing. const sql = this.ctx.storage.sql; const hasMeta = sql.exec<{ n: number }>("SELECT count(*) AS n FROM sqlite_master WHERE type = 'table' AND name = 'meta'").one().n > 0; return hasMeta && Boolean(this.store.meta("database_id")); }, killPoint: (at) => { if (this.killAt !== at || !accountDelete.mayEraseNow(this.env)) return; this.killAt = null; console.log(`cottondb: account delete: cut off after ${at}, as asked (dev)`); this.ctx.abort(`account delete: cut off after ${at} (dev)`); }, closeForGrace: async (eraseAt) => { // Every device signed out and every open socket closed: nothing reads or writes this account meanwhile. this.store.revokeAllSessions(); for (const socket of this.ctx.getWebSockets()) { try { socket.close(1000, "account_deleted"); } catch { // already closing } } const meta = this.deleteMeta(); await this.env.PHOTOS.put(accountDelete.marker(meta.slug), ""); if (meta.databaseId) await directory(this.env).deletingSet(meta.databaseId, meta.slug, new Date().toISOString(), eraseAt); }, reopen: async () => { const meta = this.deleteMeta(); await this.env.PHOTOS.delete(accountDelete.marker(meta.slug)); if (meta.databaseId) await directory(this.env).deletingKept(meta.databaseId); // The object's own work (the Google pull, imports, trims) comes back with its alarm. await this.ctx.storage.setAlarm(Date.now()); }, }; } // ── a sign-in approved from another device (src/approval.ts) ───────── private asks(): Asks { return new Asks(this.ctx.storage.sql); } /** The approving side: a device signed in with its own credential, never a token or the admin. */ private async approvals(caller: Caller, request: Request, method: string, path: string): Promise { if (!caller.who || !caller.person) refuse(403, "device_only", "only a signed-in device approves a sign-in"); const now = Math.floor(Date.now() / 1000); const phone = caller.person.phone; // Whether the calling device may let another in: once any device holds the person's key, only one that holds it // itself (GETTING-IN.md: a device that cannot open the data must never seem to let another one in). Before any // device holds it there is nothing to let in to, and an approval only signs the new device in. const holds = (): boolean => { const wrapped = { sql: "json_extract(data, '$.wrapped_vmk') IS NOT NULL", args: [] }; if (this.store.count(VAULT_KEY_TABLE, [wrapped]) === 0) return true; return this.store.count(VAULT_KEY_TABLE, [wrapped, { sql: "json_extract(data, '$.device_id') = ?", args: [caller.who!.deviceId] }]) > 0; }; if (method === "GET" && path === "/v1/approvals") { const asks = this.asks().waiting(phone, caller.who.deviceId, now).map((r) => ({ ask_id: r.id, device_id: r.device_id, device_name: r.device_name, device_kind: r.device_kind, vault_key: r.vault_key, commit: r.commit_hash, nonce_b: r.nonce_b, reveal: r.reveal, asked_at: r.created_at, expires_at: r.expires_at, })); return json({ now, asks, holds: holds() }); } if (method === "POST" && path === "/v1/approvals/nonce") { const body = await readJson(request); const nonce = text(body.nonce, "nonce"); if (!BYTES32.test(nonce)) refuse(400, "bad_nonce", "nonce is 32 bytes of base64url"); const set = this.asks().nonce(text(body.ask_id, "ask_id"), phone, caller.who.deviceId, nonce, now, holds()); if ("status" in set) refuse(set.status, set.code, set.message); return json(set); } if (method === "POST" && path === "/v1/approvals/wrong") { const body = await readJson(request); const counted = this.asks().wrong(text(body.ask_id, "ask_id"), phone, caller.who.deviceId, now); if ("status" in counted) refuse(counted.status, counted.code, counted.message); return json(counted); } if (method === "POST" && (path === "/v1/approvals/approve" || path === "/v1/approvals/refuse")) { const body = await readJson(request); const approve = path.endsWith("/approve"); const scanned = approve && body.scanned !== undefined && body.scanned !== null ? text(body.scanned, "scanned") : null; if (scanned !== null && !BYTES32.test(scanned)) refuse(400, "bad_scan", "scanned is the nonce the new device's code carries, 32 bytes of base64url"); const refused = await this.asks().decide(text(body.ask_id, "ask_id"), phone, caller.who.deviceId, approve ? "approved" : "refused", now, scanned, approve ? holds() : true); if (refused) refuse(refused.status, refused.code, refused.message); return json({ ok: true }); } refuse(405, "method_not_allowed", `${method} ${path} is not served`); } // ── the person's Cotton passkeys (src/passkey.ts) ────────────────────── private passkeyStore(): passkey.Passkeys { return new passkey.Passkeys(this.ctx.storage.sql); } /** Add, list and remove: a device signed in with its own credential, never a token or the admin. */ private async passkeys(caller: Caller, request: Request, method: string, path: string, url: URL): Promise { if (!caller.who || !caller.person) refuse(403, "device_only", "only a signed-in device adds or removes a passkey"); const now = Math.floor(Date.now() / 1000); const store = this.passkeyStore(); const person = caller.person; const rpId = url.hostname; if (method === "GET" && path === "/v1/passkeys") return json({ passkeys: store.list(person.id).map(passkey.wirePasskey) }); if (method === "POST" && path === "/v1/passkeys/options") { const challenge = store.challenge(caller.who.deviceId, now); const existing = store.list(person.id).map((row) => row.credential_id); return json({ request: passkey.creationOptions(challenge, rpId, this.store.meta("database_id") ?? "", person.phone, existing) }); } if (method === "POST" && path === "/v1/passkeys") { const body = await readJson(request); const response = body.response as Record | undefined; if (!response || typeof response !== "object") refuse(400, "bad_request", "response is the platform's answer to the passkey sheet"); const said = clientChallenge(response); if (!said || !store.spend(said, caller.who.deviceId, now)) refuse(passkey.REFUSED.status, passkey.REFUSED.code, passkey.REFUSED.message); let made: passkey.Registered; try { made = await passkey.verifyCreate(response, said, rpId, passkey.origins(rpId, this.env.PASSKEY_ANDROID_ORIGINS)); } catch (error) { console.error("cottondb: a passkey was not added", error instanceof Error ? error.message : "unknown"); refuse(passkey.REFUSED.status, passkey.REFUSED.code, passkey.REFUSED.message); } if (store.has(made.credentialId)) refuse(409, "passkey_known", "That passkey is already on this account."); const name = typeof body.name === "string" ? body.name.replace(/\s+/g, " ").trim().slice(0, 60) || null : null; const row = store.add({ ...made, name, personId: person.id, deviceId: caller.who.deviceId }, now); return json(passkey.wirePasskey(row)); } if (method === "POST" && path === "/v1/passkeys/remove") { const body = await readJson(request); if (!store.remove(text(body.id, "id"), person.id, now)) refuse(404, "no_such_passkey", "That passkey is not on this account."); return json({ ok: true }); } refuse(405, "method_not_allowed", `${method} ${path} is not served`); } /** The open host's passkey sign-in, its challenge already spent by the directory: the signature checked, the device granted. */ async passkeySignIn(input: { challenge: string; response: Record; rpId: string; deviceId: string }): Promise<{ refused: passkey.Refusal } | { ok: Record }> { await this.frozenGate(); if (!this.personal()) return { refused: passkey.REFUSED }; const store = this.passkeyStore(); const credentialId = typeof input.response.id === "string" ? input.response.id : ""; const row = store.byCredential(credentialId); if (!row) return { refused: passkey.REFUSED }; let counted: { signCount: number }; try { counted = await passkey.verifyGet(input.response, input.challenge, input.rpId, passkey.origins(input.rpId, this.env.PASSKEY_ANDROID_ORIGINS), { x: row.x, y: row.y, signCount: row.sign_count }); } catch (error) { console.error("cottondb: a passkey did not sign in", error instanceof Error ? error.message : "unknown"); return { refused: passkey.REFUSED }; } const person = this.store.person(row.person_id); if (!person) return { refused: passkey.REFUSED }; const now = new Date(); store.used(row.id, counted.signCount, Math.floor(now.getTime() / 1000)); const credential = await grant(this.store, now, person, input.deviceId); return { ok: { credential, person: wirePerson(person), version: this.store.version(), expires_in: CREDENTIAL_TTL_SECONDS } }; } /** The directory hands this object an ask for its number (src/directory.ts `ask`). */ async approvalAsk(ask: Ask): Promise { await this.frozenGate(); if (!this.personal() || ask.phone !== this.meta().owner_phone) return; this.asks().add(ask); // The person's other devices are told (GETTING-IN.md), off the ask's own path: its answer waits for nothing. this.ctx.waitUntil(this.alertApprovers(ask).catch(() => undefined)); } /** A push to every device of the person that takes one, but the asking device. */ private async alertApprovers(ask: Ask): Promise { const devices = this.ctx.storage.sql .exec<{ device_id: string; platform: "ios" | "android" | null; token: string | null; topic: string | null; sandbox: number }>("SELECT device_id, platform, token, topic, sandbox FROM chat_device WHERE device_id != ?", ask.deviceId) .toArray(); await Promise.all( devices.map(async (d) => { if (!d.platform || !d.token) return; const outcome = await approvalAlert(this.env, { platform: d.platform, token: d.token, topic: d.topic ?? "", sandbox: d.sandbox === 1 }, ask.deviceKind ?? null, ask.deviceName); if (outcome === "gone") this.ctx.storage.sql.exec("UPDATE chat_device SET token = NULL, platform = NULL, topic = NULL WHERE device_id = ?", d.device_id); }), ); } /** * The directory hands NOBODY (src/approval.ts) an ask for a number on no database: held as any ask is, so its * polls, reveal and claim are answered by the same code as a person's, and it waits and expires like one. Nothing * here serves /v1/approvals (this object is no person's), so nobody ever opens it. */ async approvalHold(ask: Ask): Promise { await this.frozenGate(); if (this.personal()) return; this.asks().add(ask); } /** The asking device's nonce, checked against its commit (src/approval.ts). */ async approvalReveal(askId: string, nonce: string): Promise { await this.frozenGate(); return await this.asks().reveal(askId, nonce, Math.floor(Date.now() / 1000)); } /** What an ask stands at, for the asking device's poll. */ async approvalState(askId: string): Promise<{ state: AskState; nonce_b?: string; challenge?: string; why?: "wrong" }> { await this.frozenGate(); return this.asks().state(askId, Math.floor(Date.now() / 1000)); } /** The asking device claims: its signature checked, the ask used, and its credential granted. */ async approvalClaim(askId: string, sig: string): Promise<{ refused: ApprovalRefusal } | { ok: Record }> { await this.frozenGate(); const now = new Date(); const claimed = await this.asks().claim(askId, sig, Math.floor(now.getTime() / 1000)); if ("refused" in claimed) return claimed; const person = this.store.personByPhone(claimed.phone); if (!person) return { refused: { status: 409, code: "not_approved", message: "That sign-in has not been approved." } }; const credential = await grant(this.store, now, person, claimed.deviceId); return { ok: { credential, person: wirePerson(person), version: this.store.version(), expires_in: CREDENTIAL_TTL_SECONDS } }; } /** A member's own card (the mine(person) table's row for them), made on first sign-in. */ private ensureOwnCard(person: Person, version: number, outcome: Outcome): StoredRow | null { const defs = this.definitions(); const t = defs.personTable(); if (!t) return null; const existing = this.store.owned(t.id, person.id)[0]; if (existing) return existing; const data: Record = { name: person.name ?? person.phone, person: person.id }; if (t.columns.some((c) => c.key === "phone")) data.phone = person.phone; if (t.columns.some((c) => c.key === "currency")) data.currency = this.meta().currency; if (t.date && t.columns.some((c) => c.key === t.date && c.type === "date")) data[t.date] = localDate(new Date(), this.meta().timezone); return this.engine(defs).create(t.id, data, version, outcome); } // ── acts ─────────────────────────────────────────────────────────────── private async act(caller: Caller, body: Record): Promise { try { return json(await this.actAnswer(caller, body)); } catch (error) { // A refused act is said in the log by its name, table and code, never its ids or data, so a phone sending one again // and again shows in a tail (live, 21 Nov 2026: fifty 409s a minute from two phones, and no way to see which act). if (error instanceof Refused && error.status < 500) { const args = body.args !== null && typeof body.args === "object" ? (body.args as Record) : {}; const table = typeof args.table === "string" ? args.table : "-"; console.log(`cottondb: act refused ${this.slug}: ${typeof body.act === "string" ? body.act : "-"} ${table} ${error.status} ${error.code} by ${caller.role}${caller.who ? ` device ${caller.who.deviceId.slice(0, 8)}` : ""}`); } throw error; } } /** One act, dispatched by its name in ACTS (src/acts.ts), in one transaction and one version; a refusal is thrown as it was said. */ private async actAnswer(caller: Caller, body: Record): Promise> { this.installed(); this.roomToWrite(); const act = text(body.act, "act"); const args = body.args === undefined ? {} : object(body.args, "args"); if (caller.tokenId && !caller.admin) this.tokenAct(caller, act, args); // A token's secret is made before the write: hashing is asynchronous, the write is not. const minted = act === "mint_token" && this.personal() ? await mintSecret(this.databaseId()) : null; // find_book asks Open Library first, find_film TMDB, and film_converted finds its stream; a book or a film that cannot be found is refused here, and logged as the act. let found: books.PreparedFind | null; let film: films.PreparedFilm | films.Converted | null; let allow: unlock.PreparedAllow | null = null; let agentAllow: agent.PreparedAgentAllow | null = null; let inherited: { hash: string; memberId: string; blob: string } | null = null; try { // unlock_allow checks the signature and opens the wrap first: both are asynchronous. if (act === "unlock_allow") { this.unlockDevice(caller); allow = await this.unlocks.prepareAllow(this.windowHost(), args, Date.now()); } if (act.startsWith("assistant_") && !this.agentGrantOn()) refuse(404, "agent_grant_off", "Your Claude's standing grant is not on for this Worker yet: assistants ask for windows"); if (act === "assistant_allow") { this.unlockDevice(caller); agentAllow = await this.agents.prepareAllow(this.windowHost(), args, Date.now()); } // A token minted by a token that carries a member carries the same one: a lane is its coordinator's Claude. if (minted && caller.presented && caller.tokenId && this.agentGrantOn()) { await this.agents.ensurePasted(this.windowHost(), caller.presented, caller.tokenId, Date.now()); inherited = await this.agents.inherit(this.windowHost(), caller.presented, minted); } found = await this.bookPrepare(caller, act, args); film = await this.filmPrepare(caller, act, args); } catch (error) { this.store.logAct(crypto.randomUUID(), caller.person?.id ?? null, act, this.loggedArgs(act, args), error instanceof Error ? `refused: ${error.message}` : "refused"); throw error; } const defs = this.definitions(); let engine = this.engine(defs); const clock = engine.clock; // A direct write is said as what it wrote; any other act's writes are the act's. A direct write that says it is an // import (`import: true`: the Mac's mail, WhatsApp and calls readers) is logged only as having happened (src/changes.ts). const direct = act === "create" || act === "update" || act === "delete"; const journalFor = (): Journal => new Journal(this.store, this.actor(caller), act, direct ? (args.import === true ? "import" : null) : "act"); let journal = journalFor(); // A restore brings back rows another database held, as an import does: nothing of it is undone, so nothing is journalled. engine.journal = act === "restore" || act === "import_rows" ? null : journal; let outcome = new Outcome_(); // A row the act makes in a sealed table is sealed at arrival: noted on a first run that is rolled back, then written sealed (src/arrival_seam.ts). const capture = new Capture(); engine.arrival = capture; let version = 0; let logged = "done"; const once = (): void => this.ctx.storage.transactionSync(() => { version = this.store.bump(); const dispatch: Record void> = { definition: () => { if (caller.role !== "owner") refuse(403, "owner_only", "only the owner writes definitions"); try { // The act's `changed` is the records it wrote, which a definition write is none of: // the reply says the definition as held (or the removal, or the conflict), never its own `changed`. // A key's definition write is held to `definable` for every table it names (ADMIN KEYS 4). const keyDefinable = (table: string): string => { if (tokenScopes.PROTECTED.has(table)) throw new ToolFailure(`${table} holds who may do what (keys, credentials, devices, grants): a key never writes it`); if (!keyAllow.mayRead(caller.allow ?? null, table)) throw new ToolFailure(`this key does not read ${table}: the owner opens it for the key from the phone`); return table; }; const reply = definitionAct({ store: this.store, defs: () => this.definitions(), write: (fn) => fn(), byKey: Boolean(caller.tokenId), ...(caller.tokenId ? { definable: keyDefinable } : {}) }, args); delete reply.changed; outcome.reply = reply; } catch (error) { if (error instanceof ToolFailure) refuse(400, "definition_refused", error.message); throw error; } }, book: () => this.book(caller, defs, engine, args, version, outcome), order: () => this.book(caller, defs, engine, args, version, outcome), cancel: () => this.cancelClaim(caller, defs, engine, args, version, outcome), record_act: () => this.recordAct(caller, defs, engine, args, version, outcome), message: () => this.message(caller, engine, args, version, outcome), profile: () => this.profile(caller, defs, engine, args, version, outcome), create: () => this.directWrite(caller, defs, engine, "create", args, version, outcome), update: () => this.directWrite(caller, defs, engine, "update", args, version, outcome), delete: () => this.directWrite(caller, defs, engine, "delete", args, version, outcome), seal: () => this.sealAct(caller, defs, engine, args, version, outcome), seal_many: () => this.sealMany(caller, defs, engine, args, version, outcome), seal_stage: () => this.sealStage(caller, defs, args, outcome), seal_commit: () => this.sealCommit(caller, defs, engine, args, version, outcome), seal_purge: () => this.sealPurge(caller, defs, args, outcome), unlock_allow: () => { if (!allow) refuse(400, "bad_args", "the unlock_allow act was not prepared"); outcome.reply = this.unlocks.applyAllow(this.windowHost(), engine, allow, Date.now(), version, outcome); }, assistant_allow: () => { if (!agentAllow) refuse(400, "bad_args", "the assistant_allow act was not prepared"); outcome.reply = this.agents.applyAllow(this.windowHost(), engine, agentAllow, Date.now(), version, outcome); }, assistant_add: () => { this.unlockDevice(caller); this.agents.add(this.windowHost(), engine, args, Date.now(), version, outcome); }, assistant_scope: () => { this.unlockDevice(caller); outcome.reply = this.agents.scope(this.windowHost(), engine, args, version, outcome); }, assistant_remove: () => { this.unlockDevice(caller); outcome.reply = { ended: this.agents.remove(this.windowHost(), engine, Date.now(), version, outcome) }; this.endConnections(engine, version, outcome); }, unlock_decline: () => { this.unlockDevice(caller); this.unlocks.decline(this.windowHost(), engine, args, version, outcome); }, unlock_end: () => { this.unlockDevice(caller); this.unlocks.endByPhone(this.windowHost(), engine, args, Date.now(), version, outcome); }, restore: () => this.restore(caller, engine, args, version, outcome), import_rows: () => this.importRows(caller, engine, args, version, outcome), set_role: () => this.setRole(caller, args, version), mint_token: () => { this.mintToken(caller, engine, args, minted, version, outcome); if (inherited) this.agents.place(this.windowHost(), [inherited]); }, revoke_token: () => this.revokeToken(caller, engine, args, version, outcome), token_allow: () => this.tokenAllow(caller, engine, args, version, outcome), merge_people: () => this.staffOnly(caller, () => (outcome.reply = personMerge.merge(engine, this.ctx.storage.sql, args, this.now(engine).at, version, outcome))), unmerge_people: () => this.staffOnly(caller, () => (outcome.reply = personMerge.unmerge(engine, this.ctx.storage.sql, args, this.now(engine).at, version, outcome))), make_todo_recurring: () => this.staffOnly(caller, () => recurrence.makeRecurring(engine, args, this.now(engine), version, outcome)), update_todo_recurrence: () => this.staffOnly(caller, () => (outcome.made = recurrence.updateRecurrence(engine, args, this.now(engine), version, outcome))), stop_todo_recurrence: () => this.staffOnly(caller, () => recurrence.stopRecurrence(engine, args, this.now(engine), version, outcome)), read_statement: () => retiredAct("read_statement"), submit_statement_reading: () => retiredAct("submit_statement_reading"), book_statement: () => retiredAct("book_statement"), settle_expected: () => retiredAct("settle_expected"), match_external: () => retiredAct("match_external"), merge_accounts: () => retiredAct("merge_accounts"), subscribe_podcast: () => retiredAct("subscribe_podcast"), refresh_podcast: () => retiredAct("refresh_podcast"), import_opml: () => retiredAct("import_opml"), export_opml: () => retiredAct("export_opml"), fetch_cover: () => retiredAct("fetch_cover"), find_lyrics: () => retiredAct("find_lyrics"), drop_old_music: () => retiredAct("drop_old_music"), start_book: () => this.bookAct(caller, () => (outcome.reply = { book: books.startBook(engine, args, this.today(engine), version, outcome).id })), finish_book: () => this.bookAct(caller, () => (outcome.reply = { book: books.finishBook(engine, args, this.today(engine), version, outcome).id })), find_book: () => this.bookAct(caller, () => { if (!found) refuse(400, "bad_args", "the find_book act was not prepared"); outcome.reply = { ...books.applyFind(engine, found, this.today(engine), version, outcome) }; }), import_goodreads: () => this.bookAct(caller, () => (outcome.reply = { ...books.importGoodreads(engine, args, version, outcome) })), find_film: () => this.filmAct(caller, () => { if (!film || !("columns" in film)) refuse(400, "bad_args", "the find_film act was not prepared"); outcome.reply = { ...films.applyFind(engine, film, this.today(engine), version, outcome) }; }), reshape_films: () => this.filmAct(caller, () => { // The links the held definitions keep, for the relink once the kit's are laid. const links = defs.linkColumns(); const zone = this.meta().timezone; const fresh = (): Engine => { const next = this.engine(); next.journal = journal; return next; }; outcome.reply = { ...films.reshapeFilms(this.store, RULED_PERSONAL, fresh, (at) => localDate(new Date(at), zone), version, outcome) }; this.store.relink(links); }), film_converted: () => this.filmAct(caller, () => { if (!film || !("file" in film)) refuse(400, "bad_args", "the film_converted act was not prepared"); outcome.reply = films.filmConverted(engine, film, version, outcome); }), fetch_add: () => this.fetchAct(caller, () => (outcome.reply = fetches.fetchAdd(engine, args, version, outcome))), fetch_cancel: () => this.fetchAct(caller, () => (outcome.reply = fetches.fetchCancel(engine, args, engine.clock.now, version, outcome))), fetch_retry: () => this.fetchAct(caller, () => (outcome.reply = fetches.fetchRetry(engine, args, version, outcome))), fetch_again: () => this.fetchAct(caller, () => (outcome.reply = fetches.fetchAgain(engine, args, engine.clock.now, version, outcome))), fetch_claim: () => this.fetchAct(caller, () => (outcome.reply = fetches.fetchClaim(engine, args, engine.clock.now, version, outcome))), fetch_progress: () => this.fetchAct(caller, () => (outcome.reply = fetches.fetchProgress(engine, args, this.databaseId(), version, outcome))), fetch_stage: () => this.fetchAct(caller, () => (outcome.reply = fetches.fetchStage(engine, args, engine.clock.now, version, outcome))), fetch_landed: () => this.fetchAct(caller, () => (outcome.reply = fetches.fetchLanded(engine, args, engine.clock.now, version, outcome))), fetch_failed: () => this.fetchAct(caller, () => (outcome.reply = fetches.fetchFailed(engine, args, engine.clock.now, version, outcome))), meeting_claim: () => this.meetingAct(caller, () => (outcome.reply = meetings.meetingClaim(engine, args, version, outcome))), meeting_failed: () => this.meetingAct(caller, () => (outcome.reply = meetings.meetingFailed(engine, args, version, outcome))), }; if (!isAct(act)) refuse(400, "unknown_act", `no act ${act}`); dispatch[act](); // A restored series carries how far it was made: none is made again from it here. if (act !== "restore") recurrence.afterWrites(engine, this.now(engine), version, outcome); if (engine.arrival === capture && capture.noted.length) throw new RollBack(); if (engine.arrival instanceof Apply) engine.arrival.done(); }); try { try { once(); } catch (error) { if (!(error instanceof RollBack)) throw error; const sealed = await sealNoted(this.store, this.databaseId(), defs, capture.noted); engine = this.engine(defs, clock); journal = journalFor(); engine.journal = act === "restore" || act === "import_rows" ? null : journal; engine.arrival = new Apply(sealed, capture.fresh); outcome = new Outcome_(); once(); } } catch (error) { logged = error instanceof Error ? `refused: ${error.message}` : "refused"; this.store.logAct(crypto.randomUUID(), caller.person?.id ?? null, act, this.loggedArgs(act, args), logged); throw error; } this.store.logAct(crypto.randomUUID(), caller.person?.id ?? null, act, this.loggedArgs(act, args), logged); const withOwner = caller.role !== "public"; const answer: ActAnswer = { version, changed: settled(outcome).map((r) => wire(r, withOwner)) }; if (outcome.made) answer.made = { table: outcome.made.table, id: outcome.made.id }; // A write a phone made under an older clear list was taken (src/seal_wide.ts): it asks for the definitions before its next. return { ...answer, notices: outcome.notices, ...(outcome.reply ?? {}), ...(outcome.stale ? { definitions_stale: true } : {}), ...changeIds(journal), ...(minted && outcome.made ? { token: minted.token } : {}) }; } /** An act for staff and the owner: a member never reshapes the database's own records. */ private staffOnly(caller: Caller, fn: () => unknown): void { if (caller.role !== "staff" && caller.role !== "owner") refuse(403, "staff_only", "that is for the owner and staff"); fn(); } /** Who a write is logged as: the token acting, else the signed-in person, else null (the admin). */ private actor(caller: Caller): string | null { return caller.tokenId ?? caller.person?.id ?? null; } /** * An act's args as the act log keeps them (sealing plan §2.2): a write to a * sealed table keeps each sealed column it said in the clear only as a mark * (a device's refused attempt included), and its blind tokens only as a * count; every other act's args as said. */ private loggedArgs(act: string, args: Record): Record { // A grant's wrap carries the table keys: the log keeps that one was said, never the wrap. if (act === "unlock_allow" && "wrapped" in args) return { ...args, wrapped: "‹wrap›" }; if ((act === "assistant_allow" || act === "assistant_add") && ("wrapped" in args || "member_secret" in args)) return { ...args, ...("wrapped" in args ? { wrapped: "‹wrap›" } : {}), ...("member_secret" in args ? { member_secret: "‹secret›" } : {}) }; const defs = this.definitions(); return scrubActArgs(defs, act, args); } /** * `seal { table, id, expect_version, data, blind? }` (sealing plan §7 step * 3): a device seals an open row of a sealed table, or re-seals a sealed * one, only while the row is still at the version it read: an edit landed * since is refused (`version_moved`) and the device reads again. `data` is * the row's clear columns and its seal; the row's open copies of sealed * columns go, from the row and from its logged changes, and nothing of * them is journalled. */ private sealAct(caller: Caller, defs: Definitions, engine: Engine, args: Record, version: number, outcome: Outcome): void { if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "only the owner's own devices seal rows"); const table = text(args.table, "table"); this.refuseMemoryUnhanded(table); const t = defs.table(table); if (!t) refuse(404, "no_such_table", `no table ${table}`); if (!t.seal) refuse(400, "not_sealed", `${table} is not a sealed table`); const id = text(args.id, "id"); const expect = args.expect_version; if (typeof expect !== "number" || !Number.isInteger(expect) || expect < 0) refuse(400, "bad_args", "expect_version is the row's version as the device read it"); const data = this.admitDeviceClear(t, object(args.data, "data"), engine, outcome); if (!checkSealFields(t, data)) refuse(400, "seal_column_missing", `a seal carries sealed_enc, dek_enc and seal_v`); const row = this.store.get(table, id); if (!row) refuse(404, "no_such_record", `no ${table} ${id}`); if (row.version !== expect) refuse(409, "version_moved", `${table} ${id} is at version ${row.version}, not ${expect}: read it again and seal what it holds now`); const tokens = blindArg(args.blind ?? [], table); engine.update(row, data, version, outcome); this.store.setBlind(table, id, tokens); } /** * `seal_many { rows }`: up to SEAL_MANY rows sealed in one act, each as `seal` seals one, each kept or refused on its * own (SYNC STUCK, 25 Nov 2026: a phone's sweep posted one act a row, and his phones could not finish a pass). */ private sealMany(caller: Caller, defs: Definitions, engine: Engine, args: Record, version: number, outcome: Outcome): void { if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "only the owner's own devices seal rows"); const rows = args.rows; if (!Array.isArray(rows) || rows.length === 0 || rows.length > SEAL_MANY) refuse(400, "bad_args", `rows is 1 to ${SEAL_MANY} rows of { table, id, expect_version, data, blind? }`); const results: { table: unknown; id: unknown; ok: boolean; status?: number; code?: string }[] = []; for (const r of rows) { const row = (r && typeof r === "object" && !Array.isArray(r) ? r : {}) as Record; try { this.sealAct(caller, defs, engine, row, version, outcome); results.push({ table: row.table, id: row.id, ok: true }); } catch (error) { // Every refusal of `seal` comes before it writes: the row is left as it was, and the rest still land. if (!(error instanceof Refused)) throw error; results.push({ table: row.table, id: row.id, ok: false, status: error.status, code: error.code }); } } outcome.reply = { results }; } /** The sealed table a migration act names, for the owner's own devices only (sealing plan §7). */ private migrationTable(caller: Caller, defs: Definitions, args: Record): TableDef { if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "only the owner's own devices seal rows"); const table = text(args.table, "table"); this.refuseMemoryUnhanded(table); const t = defs.table(table); if (!t) refuse(404, "no_such_table", `no table ${table}`); if (!t.seal) refuse(400, "not_sealed", `${table} is not a sealed table`); return t; } private migrationHost(): migration.MigrationHost { return { sql: this.ctx.storage.sql, row: (table, id) => this.store.get(table, id), now: () => new Date().toISOString() }; } /** `seal_stage { table, rows }` (src/seal_migration.ts): each row's sealed twin kept beside its clear row, which stays as it is. */ private sealStage(caller: Caller, defs: Definitions, args: Record, outcome: Outcome): void { const t = this.migrationTable(caller, defs, args); const rows = migration.batchOf(args.rows, "rows"); outcome.reply = migration.stage(this.migrationHost(), t, rows, (data) => this.refuseDeviceClear(t, data)); } /** `seal_commit { table, twins }`: each twin the device verified takes its row's place while the row is at the version it read. */ private sealCommit(caller: Caller, defs: Definitions, engine: Engine, args: Record, version: number, outcome: Outcome): void { const t = this.migrationTable(caller, defs, args); const ids = migration.batchOf(args.twins, "twins"); outcome.reply = migration.commit(this.migrationHost(), t, ids, (id, data, blind) => { const row = this.store.get(t.id, id); if (!row) refuse(404, "no_such_record", `no ${t.id} ${id}`); engine.update(row, data, version, outcome); this.store.setBlind(t.id, id, blind); }); } /** `seal_purge { table }`: the act log's earlier args for a sealed table keep none of its sealed columns. */ private sealPurge(caller: Caller, defs: Definitions, args: Record, outcome: Outcome): void { const t = this.migrationTable(caller, defs, args); const scrubbed = migration.purgeActs(this.ctx.storage.sql, t.id, actsWriting(defs, t.id), (act, a) => scrubActArgs(defs, act, a)); // A deleted row is never resealed, so its logged changes still hold what the table now seals (a column a narrowing // moved): they go here too, as a resealed row's go at its commit (LOCK TABLES 2). const gone = this.ctx.storage.sql .exec<{ id: string }>("SELECT DISTINCT c.record_id AS id FROM change c LEFT JOIN rows r ON r.table_id = c.table_id AND r.id = c.record_id WHERE c.table_id = ? AND (r.id IS NULL OR r.deleted = 1)", t.id) .toArray() .map((r) => r.id); for (const id of gone) this.store.scrubChanges(t.id, id, sealedColumns(t)); outcome.reply = { table: t.id, scrubbed, deleted_history: gone.length }; } /** * `GET /v1/secret/rewrap` (the owner's own devices only; OPEN-TABLES.md §3): the passwords still sealed under the * Worker's VAULT_KEY (`k1:`, saved over MCP), opened, at most REWRAP_BATCH at a time, for the device to seal under * the vault key, which the Worker never holds. The Google and Spotify grants are not among them: their tokens are * the object's own (`t1:`), used with no phone present. VAULT_KEY itself never changes (it also makes the * directory's phone-number key); it simply stops sealing passwords. */ private async secretsToRewrap(caller: Caller): Promise<{ rows: ({ id: string; version: number; payload: string } | { id: string; version: number; arrival: string })[]; unopened: number; left: number }> { if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "only the owner's own devices move his passwords under his own key"); // Only once the open tables lock is sealing or sealed (the coordinator's switch): until then nothing moves. const state = this.openTablesState(); if ((state === "off" || state === "handing") && !this.secretLocked()) return { rows: [], unopened: 0, left: 0 }; // And the values sealed to the arrival key (keys DECISIONS.md S3): handed as they are, for the device to open. const held = this.store.select("secret", [], "created_at, id", 100_000).filter((r) => !r.deleted && (vault.isVaultSealed(r.data.sealed) || isArrivalValue(r.data.sealed)) && !SERVICE_TOKEN_SERVICES.includes(String(r.data.service ?? ""))); const rows: ({ id: string; version: number; payload: string } | { id: string; version: number; arrival: string })[] = []; let unopened = 0; for (const row of held) { if (rows.length >= REWRAP_BATCH) break; if (isArrivalValue(row.data.sealed)) { rows.push({ id: row.id, version: row.version, arrival: row.data.sealed as string }); continue; } const payload = await vault.open(this.env, row.id, row.data.sealed as string); if (payload === null) unopened++; else rows.push({ id: row.id, version: row.version, payload }); } return { rows, unopened, left: held.length - rows.length - unopened }; } /** * `POST /v1/secret/rewrap { rows: [{ id, version, value_enc, vmk_version }] }` (the owner's own devices only): each * password the device sealed under the vault key takes its `value_enc` and `vmk_version`, and its `sealed` (and its * hint, four characters of it) goes, in one write. The old value is then taken out of the row's logged changes, so * nothing under VAULT_KEY is left of it anywhere. A row changed since it was read (another version) or no longer * under VAULT_KEY is left as it is, and counted. */ private async secretsRewrapped(caller: Caller, body: unknown): Promise<{ moved: number; skipped: number }> { if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "only the owner's own devices move his passwords under his own key"); const given = (body as { rows?: unknown })?.rows; if (!Array.isArray(given) || given.length > REWRAP_BATCH) refuse(400, "bad_request", `rows is a list of at most ${REWRAP_BATCH} { id, version, value_enc, vmk_version }`); const asked = given.map((r) => { const o = (r ?? {}) as Record; if (typeof o.id !== "string" || typeof o.version !== "number" || typeof o.value_enc !== "string" || !o.value_enc.startsWith("v2:") || typeof o.vmk_version !== "number") { refuse(400, "bad_request", "each row is { id, version, value_enc (v2:, under the vault key), vmk_version }"); } return { id: o.id, version: o.version, value_enc: o.value_enc, vmk_version: o.vmk_version }; }); const sealedTable = Boolean(this.definitions().table("secret")?.seal); const moved: string[] = []; let skipped = 0; // Logged as nothing: a change whose before is the old value would keep it (the log's before and after). await this.writeSealing( (engine) => (engine.journal = null), (engine, version, outcome) => { moved.length = 0; skipped = 0; for (const a of asked) { const row = this.store.get("secret", a.id); if (!row || row.deleted || row.version !== a.version || !(vault.isVaultSealed(row.data.sealed) || isArrivalValue(row.data.sealed))) { skipped++; continue; } // The hint is sealed with the rest once the passwords are sealed; before that it goes with the old value. engine.update(row, { value_enc: a.value_enc, vmk_version: a.vmk_version, sealed: null, ...(sealedTable ? {} : { hint: null }) }, version, outcome); moved.push(a.id); } }, ); for (const id of moved) this.store.scrubChanges("secret", id, ["sealed", "hint"]); return { moved: moved.length, skipped }; } /** `GET /v1/seal/twins?table=
&twins=,…` (owner's devices only): the twins named, as stored, for the device to verify before it commits them. */ private sealTwins(caller: Caller, params: URLSearchParams): Response { const table = params.get("table") ?? refuse(400, "bad_request", "name the table: table=
"); const t = this.migrationTable(caller, this.definitions(), { table }); const ids = (params.get("twins") ?? "").split(",").filter((x) => x !== ""); if (ids.length > migration.SEAL_BATCH) refuse(413, "too_many", `at most ${migration.SEAL_BATCH} twins a read`); return json({ twins: migration.twins(this.ctx.storage.sql, t.id, ids) }); } /** * `POST /v1/admin/service-tokens/rekey` (the admin token, once, right after * SERVICE_TOKEN_KEY is put; sealing plan §7 step 6): each Google and * Spotify grant still sealed under VAULT_KEY (k1) is opened and sealed * again under SERVICE_TOKEN_KEY (t1). Idempotent: a grant already t1 is * counted, never touched. Counts only; a grant that does not open is * counted and left (its account asks to connect again). An account a pass * stopped meanwhile because its k1 grant did not open pulls again. */ private async rekeyServiceTokens(): Promise<{ rekeyed: number; already: number; unopened: number; revived: number }> { this.installed(); let revived = 0; const rows = SERVICE_TOKEN_SERVICES.flatMap((service) => this.store.list("secret", { column: "service", equals: service })); const moved: { row: StoredRow; sealed: string }[] = []; let already = 0; let unopened = 0; for (const row of rows) { const sealed = row.data.sealed; if (!vault.isVaultSealed(sealed)) { if (typeof sealed === "string" && sealed.startsWith("t1:")) already++; continue; } const plain = await vault.open(this.env, row.id, sealed as string); if (plain === null) { unopened++; continue; } moved.push({ row, sealed: await vault.sealServiceToken(this.env, row.id, plain) }); } if (moved.length) { const defs = this.definitions(); this.ctx.storage.transactionSync(() => { const engine = this.engine(defs); const version = this.store.bump(); const outcome = new Outcome_(); for (const m of moved) { const now = this.store.get("secret", m.row.id); // Changed since it was read: the next run moves it. if (now && now.data.sealed === m.row.data.sealed) engine.update(now, { sealed: m.sealed }, version, outcome); } const ids = new Set(moved.map((m) => m.row.id)); revived = google.reviveRekeyed(this.store, ids) + spotify.reviveRekeyed(this.store, ids); }); if (revived) await this.ctx.storage.setAlarm(Date.now()); } return { rekeyed: moved.length, already, unopened, revived }; } /** * No write names a column the table lacks: refused whole, never trimmed. UNKNOWN FIELD (coordinator, 28 Nov 2026): under * its own code, so a phone on a newer kit than this Worker holds the change and sends it again once the definitions * move (cotton-client `transport::object`), instead of taking it as refused for good. */ private refuseStray(t: TableDef, data: Record): void { const stray = Object.keys(data).find((key) => !t.columns.some((c) => c.key === key) && !(t.seal && (SEAL_FIELDS as readonly string[]).includes(key))); if (stray !== undefined) refuse(400, "unknown_field", `${t.id} has no field ${JSON.stringify(stray)}`); } /** * A device's write as the object takes it: never a column the table lacks, and a sealed column in the clear only * when an earlier clear list kept it clear (a phone still holding that list, src/seal_wide.ts): an empty one is * dropped, one with a value is let through to the engine, and the answer tells the phone its definitions are old. * Any other sealed column in the clear is refused. Answers the write to make. */ private admitDeviceClear(t: TableDef, data: Record, engine: Engine, outcome: Outcome): Record { this.refuseStray(t, data); const clear = clearSealed(t, data); if (!clear.length) return data; const taken = sealWide.admit(data, clear, sealWide.wasClear(this.ctx.storage.sql, t.id)); if (taken.refused.length) refuse(400, "sealed_in_clear", `${t.id} keeps ${taken.refused.join(", ")} sealed: a device sends them only inside sealed_enc`); engine.admitWide(t.id, taken.kept); outcome.stale = true; return taken.data; } /** A device never says a sealed column in the clear, nor a column the table lacks (the reseal's twins: src/seal_migration.ts). */ private refuseDeviceClear(t: TableDef, data: Record): void { this.refuseStray(t, data); const clear = clearSealed(t, data); if (clear.length) refuse(400, "sealed_in_clear", `${t.id} keeps ${clear.join(", ")} sealed: a device sends them only inside sealed_enc`); } // ── tokens (the personal object) ───────────────────────────────────── /** `mint_token { name, scopes, expires_in_days? }`: the owner gives an assistant or a script a bearer; the answer carries it once. */ private mintToken(caller: Caller, engine: Engine, args: Record, minted: { token: string; hash: string } | null, version: number, outcome: Outcome): void { if (!minted) refuse(404, "not_personal", "tokens live in the personal database"); if (caller.role !== "owner") refuse(403, "owner_only", "only the owner mints tokens"); const name = text(args.name, "name"); const scopes = checkScopes(args.scopes); if (typeof scopes === "string") refuse(400, "bad_scopes", scopes); const days = args.expires_in_days === undefined ? null : integer(args.expires_in_days, "expires_in_days"); if (days !== null && (days < 1 || days > 366)) refuse(400, "bad_request", "expires_in_days is 1 to 366"); if (scopes.some((s) => s.startsWith("lane:")) && (days === null || days > 7)) refuse(400, "bad_request", "a lane token lives at most 7 days"); const expires = days === null ? null : new Date(Date.now() + days * 86_400_000).toISOString(); // The machine it runs on, when the mint says it: the card then reads "Claude Code on mac-c". const machine = checkMachine(args.machine); if (machine && typeof machine === "object") refuse(400, "bad_request", machine.refused); // A key's mint is a lane token (tokenAct, tokenScopes.laneMintRefusal): it carries the minting key's allow exactly, // never wider, and says which key minted it (`minted_by`, beside the change log's actor). // ADMIN KEYS 4: a machines producer (tokenScopes.producerMintRefusal) carries its own exact list, never wider than // the minting key's, and is named producer of the tables it fills in the same write. const producerOf = Array.isArray(args.producer_of) ? (args.producer_of as unknown[]).map(String) : null; let allow: keyAllow.Allow | null; if (producerOf) { const asked = keyAllow.checkAllow(args.allow); if (typeof asked === "string") refuse(400, "bad_allow", asked); if (caller.tokenId && !keyAllow.within(asked, caller.allow ?? null)) refuse(403, "key_allow", "a key mints only what it may do itself"); // A producer table this database does not hold yet (a Disk tool never added) is named when it is: skipped here. const unwritten = producerOf.find((t) => !keyAllow.mayWrite(asked, t)); if (unwritten) refuse(400, "bad_request", `producer_of names ${unwritten}: a table the new key writes`); allow = asked; } else allow = caller.tokenId ? caller.allow ?? null : this.allowOfMint(caller, args.allow); const by = caller.tokenId ? { minted_by: caller.tokenId } : {}; outcome.made = engine.create(TOKEN_TABLE, { name, scopes, token_hash: minted.hash, expires_at: expires, ...(allow ? { allow: keyAllow.stored(allow) } : {}), ...(machine ? { machine } : {}), ...by }, version, outcome); if (producerOf) { const tokenId = outcome.made.id; const next = this.store.definitions("table").map((d) => (producerOf.includes(String(d.id)) ? { ...d, producer: { token_id: tokenId } } : d)); this.store.replaceDefinitions("table", next); } } /** * ADMIN KEYS 2: what a new key may do. Unnamed, the narrowest useful set (keyAllow.DEFAULT_ALLOW). Named, as asked: * by a narrowed key, never wider than itself; "all" (a key as every key was before allows: its scopes alone, null * here) only from the owner's own device, the admin, or a key that is itself all. */ private allowOfMint(caller: Caller, asked: unknown): keyAllow.Allow | null { // ADMIN KEYS 3: unnamed, a new key is as every key was before allows while the switch says "today" (live, until the // owner flips it); "narrow" gives it the narrowest useful set. if ((asked === undefined || asked === null) && keyDefault(this.env) === "today") return caller.allow ?? null; if (asked === undefined || asked === null) return caller.allow && !keyAllow.within(keyAllow.DEFAULT_ALLOW, caller.allow) ? caller.allow : keyAllow.DEFAULT_ALLOW; if (asked === keyAllow.ALL) { if (caller.allow) refuse(403, "key_allow", "a key mints only what it may do itself"); return null; } const allow = keyAllow.checkAllow(asked); if (typeof allow === "string") refuse(400, "bad_allow", allow); if (caller.tokenId) { if (!keyAllow.within(allow, caller.allow ?? null)) refuse(403, "key_allow", "a key mints only what it may do itself"); if ((allow.read === "*" || allow.write === "*") && caller.allow) refuse(403, "key_allow", "every table is the owner's to give, from the phone"); } return allow; } /** * `token_allow { id, allow }`: the owner's own device (or the admin) sets what a key may do: narrowing a key made before * allows, or widening a new one. Never a token. */ /** * ADMIN KEYS 3, `GET /v1/keys`: the account's live keys for the Assistants screen (the core's `assistant.keys`), newest * first. Token rows never sync to a phone, so the screen asks here. The owner's own device alone, never a key. Never * a hash: id, name, machine, connection, scopes, allow and times. */ private accountKeys(caller: Caller): { keys: Record[] } { if (!this.personal()) refuse(404, "not_personal", "tokens live in the personal database"); if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "the account's keys are listed on the owner's own device"); const at = new Date().toISOString(); const str = (v: unknown) => (typeof v === "string" && v ? v : null); const keys = [...this.store.scan(TOKEN_TABLE)] .filter((r) => !r.data.revoked_at && !(str(r.data.expires_at) && String(r.data.expires_at) <= at)) .sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)) || a.id.localeCompare(b.id)) .map((r) => ({ id: r.id, name: str(r.data.name), machine: str(r.data.machine), connection_id: str(r.data.connection_id), scopes: Array.isArray(r.data.scopes) ? r.data.scopes : [], allow: keyAllow.allowOf(r.data), connector: this.connectorToken(r.id), created_at: r.created_at, last_used_at: str(r.data.last_used_at), expires_at: str(r.data.expires_at), })); return { keys }; } private tokenAllow(caller: Caller, engine: Engine, args: Record, version: number, outcome: Outcome): void { if (!this.personal()) refuse(404, "not_personal", "tokens live in the personal database"); if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "the owner sets what a key may do, from their own device"); const row = this.store.get(TOKEN_TABLE, text(args.id, "id")); if (!row) refuse(404, "no_such_token", "no such token"); const checked = args.allow === keyAllow.ALL ? null : keyAllow.checkAllow(args.allow); if (typeof checked === "string") refuse(400, "bad_allow", checked); const allow = keyAllow.stored(checked); outcome.made = engine.update(row, { allow }, version, outcome); // An OAuth connection's later tokens carry it too: the same allow on every live token of the connection. const connection = row.data.connection_id; if (typeof connection === "string" && connection) { for (const other of this.store.list(TOKEN_TABLE, { column: "connection_id", equals: connection })) { if (other.id !== row.id && !other.data.revoked_at) engine.update(other, { allow }, version, outcome); } } // ADMIN KEYS 4: a key narrowed narrows what it minted. A lane token carries its minter's list exactly, so it takes the // new one; any other minted key (a machines producer) wider than the new list is ended. if (!checked) return; const minters = new Set([row.id, ...(typeof connection === "string" && connection ? this.store.list(TOKEN_TABLE, { column: "connection_id", equals: connection }).map((r) => r.id) : [])]); for (const child of this.store.scan(TOKEN_TABLE)) { if (child.data.revoked_at || typeof child.data.minted_by !== "string" || !minters.has(child.data.minted_by)) continue; if (keyAllow.within(keyAllow.allowOf(child.data) ?? keyAllow.EVERYTHING, checked)) continue; const lane = Array.isArray(child.data.scopes) && (child.data.scopes as unknown[]).some((s) => typeof s === "string" && s.startsWith("lane:")); if (lane) engine.update(child, { allow }, version, outcome); else engine.update(child, { revoked_at: engine.clock.now }, version, outcome); } } /** `revoke_token { id }`: the owner ends a token; the row stays, revoked. */ private revokeToken(caller: Caller, engine: Engine, args: Record, version: number, outcome: Outcome): void { if (!this.personal()) refuse(404, "not_personal", "tokens live in the personal database"); if (caller.role !== "owner") refuse(403, "owner_only", "only the owner revokes tokens"); const row = this.store.get(TOKEN_TABLE, text(args.id, "id")); if (!row) refuse(404, "no_such_token", "no such token"); // ADMIN KEYS 4: a key ends itself, or a key it minted (lane-stop ends the lane token lane-start minted with the same // key); any other key is the owner's own device's to end. if (caller.tokenId && row.id !== caller.tokenId && row.data.minted_by !== caller.tokenId) refuse(403, "access_act", "a key ends only itself or a key it minted: the owner ends any other from their own device"); this.endToken(engine, row, version, outcome); } /** * AUDIT C 1: a token ends whole. Revoked for good (whatever a restore puts back: `Store.update` notes it in the * never-again ledger); an OAuth connection's every token goes with it and every refresh row of theirs is spent, so * nothing mints a successor; each carrier goes (the member stands in its other tokens, if any); and the connection's * windows end, a standing grant too. */ private endToken(engine: Engine, row: StoredRow, version: number, outcome: Outcome): void { const connection = typeof row.data.connection_id === "string" && row.data.connection_id ? row.data.connection_id : null; const rows = connection ? this.store.list(TOKEN_TABLE, { column: "connection_id", equals: connection }) : [row]; const now = engine.clock.now; // AUDIT C 2-1: what an ended key minted (a lane token, a machines producer) ends with it, so a stolen key's own // successors do not outlive it. A minted key mints nothing itself, but the walk follows any depth all the same. for (let i = 0; i < rows.length; i++) { for (const child of this.store.list(TOKEN_TABLE, { column: "minted_by", equals: rows[i]!.id })) { if (!rows.some((r) => r.id === child.id)) rows.push(child); } } for (const token of rows) { if (!token.data.revoked_at) engine.update(token, { revoked_at: now }, version, outcome); if (typeof token.data.token_hash === "string") this.agents.dropCarrier(this.windowHost(), token.data.token_hash); for (const refresh of this.store.list(OAUTH_REFRESH_TABLE, { column: "token", equals: token.id })) { if (!refresh.data.used_at) engine.update(refresh, { used_at: now }, version, outcome); this.agents.dropCarrier(this.windowHost(), refresh.id); } } this.unlocks.endForConnection(this.windowHost(), engine, unlock.connectionOf(this.store, row.id), "token_revoked", Date.now(), version, outcome); } /** AUDIT C 1: Remove ends every assistant connection too: each OAuth connection's tokens and refreshes (hand-minted keys are the owner's to revoke one by one). */ private endConnections(engine: Engine, version: number, outcome: Outcome): void { const seen = new Set(); for (const token of this.store.scan(TOKEN_TABLE)) { const connection = token.data.connection_id; if (typeof connection !== "string" || !connection || seen.has(connection)) continue; seen.add(connection); this.endToken(engine, token, version, outcome); } } private databaseId(): string { return this.store.meta("database_id") ?? refuse(503, "no_database_id", "the personal database has no database_id yet"); } /** Your Claude's standing grant answers here: the Worker's AGENT_GRANT (on for live and dev since 21 Nov 2026), or this object's own `agent_grant` meta "on". A meta "off" keeps this one object on timed windows alone: set only by a test that pins the windows' own rules (no route sets it). */ private agentGrantOn(): boolean { const own = this.store.meta("agent_grant"); return this.personal() && own !== "off" && (this.env.AGENT_GRANT === "on" || own === "on"); } /** * The members something can still read through: a token neither revoked nor expired, or an OAuth refresh token * unspent, unexpired and of a token not revoked (a connector idle past its access token's month still refreshes). */ private readingMembers(now = Date.now()): Set { const at = new Date(now).toISOString(); const out = new Set(); const add = (hash: unknown) => { const member = typeof hash === "string" && hash ? this.memberOfHash(hash) : null; if (member) out.add(member); }; for (const row of this.store.scan(TOKEN_TABLE)) { const d = row.data; if (!d.revoked_at && !(typeof d.expires_at === "string" && d.expires_at && d.expires_at <= at)) add(d.token_hash); } for (const row of this.store.scan(OAUTH_REFRESH_TABLE)) { const d = row.data; if (d.used_at || !(typeof d.expires_at === "string" && d.expires_at > at)) continue; const token = this.store.get(TOKEN_TABLE, String(d.token ?? "")); if (token && !token.data.revoked_at) add(row.id); } return out; } /** * The live grants gate 2 of both locks waits on (HANDING STUCK, coordinator, 25 Nov 2026): only those something * still reads through. A grant whose every token is revoked or expired locks nobody out, so it never holds the lock * in handing; a token it gets later reads gate 1's needs_allow until the phone tops the grant up. */ private gateGrants(): StoredRow[] { const reading = this.readingMembers(); return this.agents.liveGrants(this.store).filter((g) => typeof g.data.member_id === "string" && reading.has(g.data.member_id)); } /** The member a token's carrier names (no key read), or null. */ private memberOfHash(hash: string): string | null { return this.ctx.storage.sql.exec<{ member_id: string }>("SELECT member_id FROM agent_carrier WHERE token_hash = ?", hash).toArray()[0]?.member_id ?? null; } /** The token row a bearer names, read through its hash. */ /** Each key's requests this minute (AUDIT C 5), held in memory: a fresh object starts every key at nought. */ private readonly keyCalls = new Map(); /** * AUDIT C 5: a key makes at most KEY_CALLS_PER_MINUTE requests a minute, at /mcp and at /v1 alike (a batch is one, * and holds at most 20), so a leaked or misled key cannot flood writes, deletes or outward acts. The owner's own * devices are never paced here. */ private keyPace(tokenId: string): void { const minute = Math.floor(Date.now() / 60_000); const held = this.keyCalls.get(tokenId); const now = held && held.minute === minute ? held : { minute, n: 0 }; now.n++; this.keyCalls.set(tokenId, now); if (this.keyCalls.size > 1000) for (const [id, c] of this.keyCalls) if (c.minute !== minute) this.keyCalls.delete(id); const most = Number(this.store.meta("key_calls_per_minute")) || KEY_CALLS_PER_MINUTE; if (now.n > most) refuse(429, "too_many_calls", `a key makes at most ${most} requests a minute; wait for the next minute`); } private async mcpCaller(token: string): Promise { const hash = await sha256Hex(token); const row = this.store.list(TOKEN_TABLE, { column: "token_hash", equals: hash })[0] ?? null; return callerOf(row, new Date().toISOString()); } // ── Cotton MCP (the personal object) ───────────────────────────────── private async mcp(request: Request): Promise { if (!this.absent()) this.installed(); if (request.method !== "POST") return MCP.answer(request, () => refuse(405, "method_not_allowed", "POST")); const token = bearer(request); if (!token) return challenge(unauthorized("a Cotton MCP token is required in the Authorization header"), request, false); if (!token.startsWith(`ctn_${this.store.meta("database_id") ?? ""}_`)) return challenge(unauthorized("unknown token"), request, true); const caller = await this.mcpCaller(token); if (!caller) return challenge(unauthorized("unknown token"), request, true); this.keyPace(caller.tokenId); if (!this.connectorToken(caller.tokenId)) allowlist.guard(this.ctx.storage.sql, request); const presented: agent.Presented = { token, hash: await sha256Hex(token) }; if (this.agentGrantOn() && this.legacyConnection(caller.tokenId, presented.hash)) return this.renewLegacy(caller.tokenId, request); if (this.agentGrantOn()) await this.agents.ensurePasted(this.windowHost(), presented, caller.tokenId, Date.now()); const answer = await MCP.answer(request, () => this.toolContext(caller, this.agentGrantOn() ? presented : null)); this.stampUsed(caller.tokenId); await this.shadowsOwed(); return answer; } /** * An OAuth access token minted before Your Claude's standing grant: it * names a connection and carries no member, so its reads would ask for * timed windows for up to its 30 days. Its member cannot be made here: the * member's private half must ride in the refresh token too, and only a * refresh presents that. Null without WINDOW_KEY (no member is ever made). */ private legacyConnection(tokenId: string, hash: string): boolean { if (!this.windowHost().key) return false; const said = this.store.get(TOKEN_TABLE, tokenId)?.data.connection_id; return typeof said === "string" && !!said && this.memberOfHash(hash) === null; } /** Such a token ends now and the client is told so (401 invalid_token): it refreshes, as at any expiry, and the refresh makes the connection Your Claude, carried in both new tokens. */ private renewLegacy(tokenId: string, request: Request): Response { const row = this.store.get(TOKEN_TABLE, tokenId); // A silent stamp that may only end a token earlier (rowWitness.ONLY_EARLIER): the restore audit explains no later end. if (row) this.ctx.storage.transactionSync(() => this.engine().update(row, { [stampOf("mcp_token", "expires_at")]: new Date().toISOString() }, this.store.bump(), new Outcome_())); return challenge(unauthorized(sayUnlock("assistant.reconnect")), request, true); } /** * A connection just made Your Claude (a code redeemed, or an old * connection's first refresh) files its one card now, while the owner has * the phone in hand, rather than at its first private read. Nothing is * filed for a member that holds a grant (Connect Claude) or when no table * is private; a card the hour's limit refuses is filed at the first read. */ private fileAccountCard(tokenId: string, accessHash: string, clientName: string): void { const memberId = this.memberOfHash(accessHash); if (!memberId) return; const sealed = [...this.definitions().tables.values()].filter((t) => !!t.seal).map((t) => t.id); try { this.agents.request(this.windowHost(), { memberId }, clientName, tokenId, sealed, sealed, Date.now()); } catch (error) { console.warn(`the account card was not filed at connect: ${error instanceof Error ? error.message : String(error)}`); } } /** What src/oauth.ts may touch: the store, a write in one transaction with a fresh version, and the clients: the directory's through the open host's door, its own otherwise. */ private oauthHost(request: Request): OAuthHost { const absent = this.absent(); // Where no database is, the connect runs as it does for a stranger and every write it would make is rolled back: // nothing is kept, so no database comes to be. // Logged (RESTORE AUDIT 2): the tokens a connector's sign-in and refresh make are creates the change log and the // restore audit's witness know, never rows that appear with no change row. const logged = (): Engine => { const engine = this.engine(); engine.journal = new Journal(this.store, null, "oauth", "act"); return engine; }; const write: OAuthHost["write"] = absent ? (fn) => rolledBack(this.ctx.storage, () => fn(logged(), this.store.bump(), new Outcome_())) : (fn) => this.ctx.storage.transactionSync(() => fn(logged(), this.store.bump(), new Outcome_())); const door = throughDoor(request, this.env); // Whether this request's pair made a new member (a redemption, or an old connection's first refresh): only then is the card filed. let fresh = false; return { env: this.env, store: this.store, write, door, // One registry for every database (the directory's), so registering and naming a client says nothing of whether // this one exists. A client registered here before 24 Nov 2026 is still found in its own store. clients: door ? directoryClients(this.env, request.headers.get("cf-connecting-ip") ?? "unknown") : withOldClients(directoryClients(this.env, request.headers.get("cf-connecting-ip") ?? "unknown"), storeClients(this.store, write)), // AUDIT F: a new number whose first sign-in is an assistant's connect page gets its kit as a phone's sign-in does. ownerProved: () => { if (!absent && this.store.meta(KIT_PENDING)) this.finishKit(); }, connectionEnded: (engine, connection, version, outcome) => void this.unlocks.endForConnection(this.windowHost(), engine, connection, "token_revoked", Date.now(), version, outcome), carry: async (pair, clientName, presented, redirect) => { if (!this.agentGrantOn()) return null; const access = { token: pair.access, hash: pair.accessHash }; const refresh = { token: pair.refresh, hash: pair.refreshHash }; fresh = !presented || (await this.agents.opened(this.windowHost(), presented)) === null; return presented ? this.agents.refreshed(this.windowHost(), presented, access, refresh, clientName, Date.now()) : this.agents.redeemed(this.windowHost(), access, refresh, clientName, Date.now(), redirect ?? null); }, connected: (tokenId, accessHash, clientName) => { if (fresh && this.agentGrantOn()) this.fileAccountCard(tokenId, accessHash, clientName); }, }; } /** The write a device row is filed in: logged, so its create is in the change log and keeps a witness (RESTORE AUDIT 2). */ private deviceCreate(defs: Definitions): (fn: (engine: Engine, version: number, outcome: Outcome) => void) => void { return (fn) => this.ctx.storage.transactionSync(() => { const engine = this.engine(defs); engine.journal = new Journal(this.store, null, "device", "act"); fn(engine, this.store.bump(), new Outcome_()); }); } /** A token's last use, kept to the minute so a busy hook does not move the change counter on every call. */ private stampUsed(tokenId: string): void { const row = this.store.get(TOKEN_TABLE, tokenId); if (!row) return; const now = new Date(); const last = typeof row.data.last_used_at === "string" ? Date.parse(row.data.last_used_at) : 0; if (now.getTime() - last < 60_000) return; this.ctx.storage.transactionSync(() => { const version = this.store.bump(); // A silent stamp (no change row): its field is on rowWitness.SILENT_STAMPS, which the restore audit leaves out. this.engine().update(row, { [stampOf("mcp_token", "last_used_at")]: now.toISOString() }, version, new Outcome_()); }); } /** The owner's other databases this endpoint reaches: `siblings` in the meta, set at onboarding. */ private siblings(): Sibling[] { const raw = this.store.meta("siblings"); return raw ? (JSON.parse(raw) as Sibling[]) : []; } /** * A tool call another of the owner's objects forwarded, with the caller its * front door verified. The Worker answers no outside request on /internal/, * so only an object reaches this. */ private async forwarded(request: Request): Promise { this.installed(); const body = await readJson<{ caller: { tokenId: string; name: string; scopes: string[]; lane: string | null }; tool: string; args: Record }>(request); const caller: McpCaller = { tokenId: body.caller.tokenId, name: body.caller.name, scopes: new Set(body.caller.scopes), lane: body.caller.lane }; const answered = await MCP.call(this.toolContext(caller), body.tool, body.args); if (this.store.orderIndexAsked()) await this.carryOn(); return json(answered); } private toolContext(caller: McpCaller, presented: agent.Presented | null = null): ToolContext { const store = this.store; const env = this.env; const meta = this.meta(); const transact = (fn: () => T): T => this.ctx.storage.transactionSync(fn); // An assistant never sees a CLOSED table (agent_statement.ts; Sites' list): every tool reads the object as if it held none. // ADMIN KEYS 2: a key that carries its list (src/key_allow.ts) sees only the tables it may read, as a CLOSED one is // hidden; every row it reads or writes and every file it opens is checked against the list below. const allow = caller.allow ?? null; // LIVE READS (28 Nov 2026): the definitions are read once per question, never once per table; and a key with no list // (allow null) never asks whether a table is sealed at all. const sealedIn = (all: Definitions, id: string): boolean => !!all.table(id)?.seal; const sealedTable = (id: string): boolean => sealedIn(this.definitions(), id); const seenIn = (all: Definitions, id: string): boolean => !agent.closed(id) && (!allow || keyAllow.mayRead(allow, id, sealedIn(all, id))); let shown: { from: Definitions; to: Definitions } | null = null; const defs = (): Definitions => { const all = this.definitions(); if (shown?.from !== all) shown = { from: all, to: [...all.tables.keys()].every((id) => seenIn(all, id)) ? all : new Definitions([...all.tables.values()].filter((t) => seenIn(all, t.id))) }; return shown.to; }; const readable = (table: string): string => { if (allow && !keyAllow.mayReadIn(allow, table, trail.tool, sealedTable(table))) fail(`this key does not read ${table}: the owner opens it for the key from the phone`, { code: "key_allow", table }); return table; }; const writable = (table: string): string => { if (!keyAllow.mayWrite(allow, table)) fail(`this key does not write ${table}: the owner opens it for the key from the phone`, { code: "key_allow", table }); return table; }; const engine = () => this.engine(); const unprotected = (table: string): string => { if (tokenScopes.PROTECTED.has(table)) fail(`${table} holds who may do what (keys, credentials, devices, grants): a key never writes it`, { code: "access_act", table }); return table; }; const trail: ChangeTrail = { tool: null, ids: [] }; const handed: unlock.TableKeys[] = []; // Your Claude's member, opened once for this call from the token it presented, and its opened wraps: dropped with the call. let member: Promise | null = null; const opened = (): Promise => (member ??= presented ? this.agents.opened(this.windowHost(), presented) : Promise.resolve(null)); const bundles = new Map; bk: Uint8Array; files?: Uint8Array }>>(); const sealedTables = (): string[] => [...defs().tables.values()].filter((t) => !!t.seal).map((t) => t.id); // AVATAR SEAL 3 (2): every tool's read of a file goes through here, and a file of a kind a sealed table owns (a // face, a kept chat picture), sealed or plain from before, is read only inside that table's window: with none, the // window is asked for and the read refused, whatever row named the key (a book pointed at a face included). // AVATAR SEAL 4 (1): the same rule as the plain route's tokenFileGate: a kind a device seals is read only when a // sealed table owns it and that table's window is open (asked for here when it is not); any other such kind never. const keyOfAt = (at: string): string => (meta.database_id && at.startsWith(`${meta.slug}/`) ? `${meta.database_id}/${at.slice(meta.slug.length + 1)}` : ""); const sealedKindRead = async (at: string): Promise => { const key = keyOfAt(at); if (allow && !keyAllow.mayReadKind(allow, meta.database_id ? kindOfKey(meta.database_id, key) : null, sealedTable)) fail("this key does not read that kind of file: the owner opens its table for the key from the phone", { code: "key_allow" }); if (!meta.database_id || !isDeviceSealedKind(meta.database_id, key)) return; const owner = tableOfFileKind(kindOfKey(meta.database_id, key) ?? ""); if (!owner || !defs().table(owner)?.seal) fail("That file is one of the person's sealed files: only their own devices read it", { code: "sealed_kind" }); await windowFor(ctx, resolveTable(ctx, owner), "media"); }; // A narrowed key's tools read the store through this: every method that names a table first checks it is readable, // so a tool that reads a fixed table (prompt, session, todo, secret, project, memory) is held to the list as well. const toolStore: Store = allow ? new Proxy(store, { get(target, prop) { const v = Reflect.get(target, prop, target) as unknown; if (typeof v !== "function") return v; const fn = v as (...a: unknown[]) => unknown; if (typeof prop === "string" && keyAllow.STORE_TABLE_FIRST.has(prop)) return (table: string, ...rest: unknown[]) => fn.apply(target, [readable(table), ...rest]); return fn.bind(target); }, }) : store; const ctx: ToolContext = { env, store: toolStore, caller, writable: (table) => writable(unprotected(table)), definable: (table) => readable(unprotected(table)), sealRow: (id) => (id === "arrival" || id.startsWith("v:") ? store.get("seal_key", id) : null), database: { id: meta.database_id ?? "", name: meta.name }, now: new Date().toISOString(), timezone: meta.timezone, defs, scan: (table, where) => store.scan(readable(table), where), where: (table, column, equals) => store.list(readable(table), { column, equals }), get: (table, id) => store.get(readable(table), id), trail, write: (fn: (w: Writer) => T): T => { this.roomToWrite(); const journal = new Journal(store, caller.tokenId, trail.tool ?? "mcp"); const result = transact(() => { const version = store.bump(); const e = engine(); e.journal = journal; const outcome = new Outcome_(); const w: Writer = { version, engine: e, outcome, journal, // ADMIN KEYS 1b: no tool writes a table that holds who may do what (a record tool, undo, a version restored); // ADMIN KEYS 2: and a key writes only the tables its list names. create: (table, data, keep = {}) => e.create(writable(unprotected(table)), data, version, outcome, 0, keep), update: (row, patch, stamps: Stamps = {}) => { writable(unprotected(row.table)); return e.update(row, patch, version, outcome, 0, stamps); }, delete: (row) => { writable(unprotected(row.table)); return e.delete(row, version, outcome); }, now: { at: e.clock.now, zone: meta.timezone }, }; const answer = fn(w); recurrence.afterWrites(e, w.now, version, outcome); return answer; }); trail.ids.push(...journal.ids); return result; }, siblings: this.siblings(), forward: async (sibling, tool, args) => { const stub = env.BUSINESS.get(env.BUSINESS.idFromName(sibling.slug), { locationHint: "apac" }); const res = await stub.fetch("https://object/internal/mcp-call", { method: "POST", headers: { "content-type": "application/json", [SLUG_HEADER]: sibling.slug }, body: JSON.stringify({ caller: { tokenId: caller.tokenId, name: caller.name, scopes: [...caller.scopes], lane: caller.lane }, tool, args }), }); if (!res.ok) return { content: [{ type: "text", text: `${sibling.name} did not answer (${res.status})` }], isError: true }; return res.json(); }, // An MCP token acts as the owner when it holds owner scope, else as staff: a write token runs the packages' acts, never the owner's own (roles, tokens, owner-only tables). act: (act, args) => this.actAnswer({ role: caller.scopes.has("owner") ? "owner" : "staff", person: null, admin: false, who: null, tokenId: caller.tokenId, readBy: caller.name || undefined, connector: this.connectorToken(caller.tokenId), viaMcp: true, allow }, { act, args }), media: { at: (key) => bucketKey(key, meta.database_id ?? "", meta.slug), head: async (at) => (await sealedKindRead(at), env.MEDIA.head(at)), get: async (at) => (await sealedKindRead(at), env.MEDIA.get(at)), draw: async (at, size) => (await sealedKindRead(at), drawMedia(env, at, size)), drawBytes: (bytes, size) => drawBytes(env, bytes, size), // AVATAR SEAL 4 (2): a tool's file of a kind a device seals (story_picture_add's photos/, and people/ too, which // SEALED_KINDS in src/arrival_file.ts holds) is sealed at arrival, never kept plain, never written over a file // already held, and answered the same either way; the one kind the object cannot seal at arrival (messages) is refused. store: async (at, bytes, contentType) => { this.roomToWrite(); const key = keyOfAt(at); if (!meta.database_id || !isDeviceSealedKind(meta.database_id, key)) return storeMedia(env, at, bytes, contentType, this.mediaBudget()); if (!sealsAtArrival(meta.database_id, key)) fail("A person's chat files are written by their own devices, never by an assistant", { code: "sealed_kind" }); if (!(await env.MEDIA.head(at))) { const arrival = arrivalPublic((table, id) => this.store.get(table, id)); if (!arrival) fail("No phone has handed this database its arrival key yet, so the picture cannot be kept: it is never kept in the clear. Open a Cotton app signed in on the phone, then ask again", { code: "arrival_key_missing" }); const kept = await asArrived(meta.database_id, arrival, key, bytes, contentType, SEALED_FILE_TYPE); await storeMedia(env, at, kept.bytes, kept.contentType, this.mediaBudget()); } return { stored: true, bytes: bytes.byteLength }; }, storeStream: (at, length, contentType, fill) => { this.roomToWrite(); if (meta.database_id && isDeviceSealedKind(meta.database_id, keyOfAt(at))) fail("A file of the person's sealed kinds is not written as a stream by a tool", { code: "sealed_kind" }); return storeStream(env, at, length, contentType, this.mediaBudget(), fill); }, }, size: () => ({ database: this.ctx.storage.sql.databaseSize, databaseCap: this.caps.database, media: Number(store.meta(MEDIA_BYTES) ?? "0"), mediaCap: this.spaceMode() === "on" ? this.spaceAllowance() : this.mediaCap(), worker: env.CF_VERSION_METADATA ? { id: env.CF_VERSION_METADATA.id, at: env.CF_VERSION_METADATA.timestamp ?? null } : null }), seal: (rowId, plaintext) => vault.seal(env, rowId, plaintext), open: (rowId, sealed) => vault.open(env, rowId, sealed), memoryRead: () => { if (!caller.tokenId) return; this.ctx.storage.sql.exec("INSERT INTO memory_reader (token_id, last_at) VALUES (?, ?) ON CONFLICT (token_id) DO UPDATE SET last_at = excluded.last_at", caller.tokenId, new Date().toISOString()); }, tablesRead: () => { if (!caller.tokenId) return; this.ctx.storage.sql.exec("INSERT INTO open_reader (token_id, last_at) VALUES (?, ?) ON CONFLICT (token_id) DO UPDATE SET last_at = excluded.last_at", caller.tokenId, new Date().toISOString()); }, agentChat: { host: () => (this.personal() ? this.agentHost() : null), member: async () => { const m = await opened(); return m ? { memberId: m.memberId, secret: m.secret, pub: m.pub } : null; }, }, window: { keys: async (table) => { const m = await opened(); const keys = (m ? await this.agents.keys(this.windowHost(), m, table, bundles) : null) ?? (await this.unlocks.keys(this.windowHost(), caller.tokenId, table, Date.now())); if (keys) handed.push(keys); return keys; }, handed, request: async (tables, reason, minutes) => { const m0 = presented ? await opened() : null; const off = presented ? tables.filter((t) => this.agents.offFor(store, m0?.memberId ?? null, t)) : []; if (off.length) fail(`${off.join(", ")} ${off.length === 1 ? "is" : "are"} off for your Claude: the owner turned ${off.length === 1 ? "it" : "them"} off in Account › Assistants, so nothing is asked.`, { code: "assistant_off", tables: off }); const m = await opened(); if (m) { const card = this.agents.request(this.windowHost(), m, caller.name, caller.tokenId, tables, sealedTables(), Date.now()); if (card) return card; // A granted member reaching a table its phone has not handed yet: the phone adds it on its next pass, unasked. const pending = tables.filter((t) => this.agents.access(store, t) === "on" && !agent.NEVER.includes(t) && this.agents.grantOf(store, m.memberId)); if (pending.length) fail(`${pending.join(", ")} ${pending.length === 1 ? "is" : "are"} in your Claude's grant but the owner's phone has not handed ${pending.length === 1 ? "its" : "their"} keys yet: it does so the next time a Cotton app syncs, with nothing asked. Try again later.`, { code: "grant_catching_up", tables: pending }); } return this.unlocks.request(this.windowHost(), caller, { tables, reason, minutes }, Date.now()); }, end: () => this.windowHost().write((e, version, outcome) => this.unlocks.endForConnection(this.windowHost(), e, unlock.connectionOf(this.store, caller.tokenId), "assistant", Date.now(), version, outcome)), open: () => { const account = presented ? this.memberOfHash(presented.hash) : null; return [...(account ? this.agents.open({ store: this.store }, account) : []), ...this.unlocks.open({ sql: this.ctx.storage.sql, store: this.store }, caller.tokenId, Date.now())]; }, log: (keys, tool, rows, wrote) => this.unlocks.logRead(this.windowHost(), keys, tool, rows, Date.now(), wrote), standing: presented !== null, }, }; return ctx; } /** The caller's own card row (their yoga_member), or the one staff name. */ private memberRowFor(caller: Caller, defs: Definitions, engine: Engine, args: Record, version: number, outcome: Outcome): StoredRow { const t = defs.personTable(); if (!t) refuse(400, "no_member_table", "this business keeps no member cards"); const named = optionalText(args.member); if (caller.role === "staff" || caller.role === "owner") { if (!named) refuse(400, "bad_request", "staff name the member"); const row = this.store.get(t.id, named); if (!row) refuse(404, "no_such_member", "no such member"); return row; } if (!caller.person) refuse(401, "not_signed_in", "sign in to book"); if (named && this.store.get(t.id, named)?.owner !== caller.person.id) refuse(403, "not_yours", "you can only book for yourself"); const own = this.ensureOwnCard(caller.person, version, outcome); if (!own) refuse(400, "no_member_table", "this business keeps no member cards"); void engine; return own; } /** `book { slot, quantity? , member? }`: the slot table's reserve act, with the member and quantity picked. */ private book(caller: Caller, defs: Definitions, engine: Engine, args: Record, version: number, outcome: Outcome): void { const slotId = text(args.slot ?? args.session ?? args.id, "slot"); const member = this.memberRowFor(caller, defs, engine, args, version, outcome); const quantity = integer(args.quantity, "quantity", 1); for (const tool of engine.tools) { const r = tool.reserve; if (!r) continue; const slotDef = defs.table(r.slot_table); const slot = this.store.get(r.slot_table, slotId); if (!slotDef || !slot) continue; if (slotDef.visibility.kind !== "public" && caller.role === "member") refuse(403, "not_visible", "that cannot be booked"); const act = recordActs(slotDef).find((a) => a.verb === "reserve_record"); if (act) { const picks = act.picks ?? (act.pick ? [act.pick] : []); const picked = picks.map((p) => (p.kind === "record" ? member.id : p.kind === "number" ? quantity : "")); engine.runAct(slotDef, slot, act, picked, version, outcome); } else { const data: Record = { member: member.id, quantity }; if (typeof slot.data.name === "string") data.name = slot.data.name; if (slotDef.date && slot.data[slotDef.date] !== undefined) data[slotDef.date] = slot.data[slotDef.date]; engine.reserve(tool, slot.id, data, version, outcome); } return; } refuse(404, "no_such_slot", "nothing to book with that id"); } /** `cancel { id }`: the caller's own claim goes, staff cancel any; a member cannot cancel a past day. */ private cancelClaim(caller: Caller, defs: Definitions, engine: Engine, args: Record, version: number, outcome: Outcome): void { const id = text(args.id ?? args.booking, "id"); for (const tool of engine.tools) { const r = tool.reserve; if (!r) continue; const claim = this.store.get(r.claim_table, id); if (!claim) continue; const staff = caller.role === "staff" || caller.role === "owner"; if (!staff) { if (!caller.person || claim.owner !== caller.person.id) refuse(403, "not_yours", "that booking is not yours"); const slotDef = defs.table(r.slot_table); const slot = this.store.get(r.slot_table, String(claim.data[r.slot_column])); const on = slotDef?.date && slot ? slot.data[slotDef.date] : null; if (typeof on === "string" && on < engine.clock.today) refuse(409, "past", "that session has already happened"); } engine.cancel(claim, version, outcome); return; } refuse(404, "no_such_booking", "no such booking"); } /** `record_act { table, id, act, picked? }`: an act the package defines on a row. */ private recordAct(caller: Caller, defs: Definitions, engine: Engine, args: Record, version: number, outcome: Outcome): void { const table = text(args.table, "table"); const id = text(args.id, "id"); const actId = text(args.act, "act"); const picked = Array.isArray(args.picked) ? (args.picked as unknown[]) : []; const t = defs.table(table); if (!t) refuse(404, "no_such_table", `no table ${table}`); const row = this.store.get(table, id); if (!row) refuse(404, "no_such_record", `no ${table} ${id}`); const act: RecordAct | undefined = recordActs(t).find((a) => a.id === actId); if (!act) refuse(404, "no_such_act", `${table} has no act ${actId}`); const staff = caller.role === "staff" || caller.role === "owner"; if (!staff) { const memberVerb = act.verb === "reserve_record" || act.verb === "cancel_reservation"; const visible = t.visibility.kind === "public" || (caller.person !== null && row.owner === caller.person.id); if (!memberVerb || !visible) refuse(403, "staff_only", `${act.label} is for the studio's staff`); if (act.verb === "reserve_record") { // A member books for themselves: the member pick is their own card. const member = this.memberRowFor(caller, defs, engine, {}, version, outcome); const picks = act.picks ?? (act.pick ? [act.pick] : []); picks.forEach((p, i) => { if (p.kind === "record" && p.table === member.table) picked[i] = member.id; }); } } // ADMIN KEYS 4: a key's record act is held to every table it writes, not only the one it names. if (caller.tokenId) { for (const written of engine.actTables(t, act)) { if (tokenScopes.PROTECTED.has(written)) refuse(403, "access_act", `${written} holds who may do what (keys, credentials, devices, grants): a key never writes it`); if (!keyAllow.mayWrite(caller.allow ?? null, written)) refuse(403, "key_allow", `${act.label} writes ${written}: this key does not`); const away = keyAllow.outwardRefusal(caller.allow ?? null, keyAllow.OUTWARD_TABLES.has(written), act.label); if (away) refuse(403, "key_allow", away); } } engine.runAct(t, row, act, picked, version, outcome); } /** `message { text, about?, person? }`: a member writes to the business, staff write to a person. */ private message(caller: Caller, engine: Engine, args: Record, version: number, outcome: Outcome): void { const body = text(args.text, "text"); const staff = caller.role === "staff" || caller.role === "owner"; let person: string; if (staff) { person = text(args.person, "person"); if (!this.store.person(person)) refuse(404, "no_such_person", "no such person"); } else { if (!caller.person) refuse(401, "not_signed_in", "sign in to send a message"); person = caller.person.id; } const about = optionalText(typeof args.about === "string" ? args.about : args.about ? JSON.stringify(args.about) : null); const made = engine.create( "business_message", { name: body.slice(0, 80), person, from: staff ? "staff" : "member", text: body, about, at: engine.clock.now }, version, outcome, ); outcome.made = made; } /** `profile { name }`: a person names themselves; their card follows. */ private profile(caller: Caller, defs: Definitions, engine: Engine, args: Record, version: number, outcome: Outcome): void { if (!caller.person) refuse(401, "not_signed_in", "sign in first"); const name = text(args.name, "name"); this.store.setPerson(caller.person.id, { name }, version); const t = defs.personTable(); if (t) { const card = this.store.owned(t.id, caller.person.id)[0]; if (card) engine.update(card, { name }, version, outcome); } } /** * `create|update|delete { table, id?, data? }` for staff and the owner; members act, they never write rows. * A create may name its id: the owner's phone mints a row's id where it is written and the object keeps it * (a live row already holding it is a refusal, `duplicate_id`). */ private directWrite(caller: Caller, defs: Definitions, engine: Engine, act: string, args: Record, version: number, outcome: Outcome): void { const table = text(args.table, "table"); const t = defs.table(table); if (!t) refuse(404, "no_such_table", `no table ${table}`); const floor = defs.writeFloor(table); if (!(caller.role === "owner" || (caller.role === "staff" && floor === "staff"))) refuse(403, "staff_only", `writing ${table} is for the studio's staff`); if (table === ownerAsks.ASK_TABLE) refuse(403, "asks_only", `${table} is written by the object as an assistant asks and the owner answers, never directly`); if (unlock.WINDOW_TABLES.has(table)) refuse(403, "unlock_only", `${table} is written by the unlock acts (unlock_allow, unlock_decline, unlock_end), never directly`); // A key the table has no column for is refused, never dropped: a dropped key hid a missing column for a day. let data = act === "delete" ? {} : object(args.data, "data"); if (SEAL_FIELDS.some((k) => k in data)) this.refuseMemoryUnhanded(table); // A token holds no key (a script's, the Mac importers'): its clear words for a sealed table are sealed at arrival by the // engine's seam (src/arrival_seam.ts), as an assistant's create_record is; a device, which holds the key, sends them sealed. if (caller.tokenId && !SEAL_FIELDS.some((k) => k in data)) this.refuseStray(t, data); else data = this.admitDeviceClear(t, data, engine, outcome); // Blind tokens come only beside a write that carries a seal, and replace the row's (sealing plan §4). const sealing = act !== "delete" && SEAL_FIELDS.some((k) => k in data); if (args.blind !== undefined && !sealing) refuse(400, "bad_blind", "blind tokens come only beside a write that carries sealed_enc"); const tokens = sealing ? blindArg(args.blind ?? [], table) : null; // KEPT FOUR 3 A (src/vault_identity.ts): the identity of the key a wrap holds, when the writing device declares it. const vmkCheck = table === VAULT_KEY_TABLE ? vaultIdentity.declared(args) : null; const wrapVersion = (rowId: string | null): number => Number(data.vmk_version ?? (rowId === null ? null : this.store.get(VAULT_KEY_TABLE, rowId)?.data.vmk_version) ?? 0); if (table === VAULT_KEY_TABLE && act !== "delete") { const rowId = args.id === undefined ? null : text(args.id, "id"); this.refuseLaterFounding(caller, act, rowId, data); this.refuseBlindAdmission(caller, act, rowId, data); // A new wrap, or a row moved to another version under the wrap it holds (VAULT GUARD 2 item 4): both name a key. if ((data.wrapped_vmk !== undefined && data.wrapped_vmk !== null) || data.vmk_version !== undefined) { const wrapped = this.ctx.storage.sql .exec<{ id: string; v: number | null }>("SELECT id, json_extract(data, '$.vmk_version') AS v FROM rows WHERE table_id = ? AND deleted = 0 AND json_extract(data, '$.wrapped_vmk') IS NOT NULL", VAULT_KEY_TABLE) .toArray() .map((r) => ({ id: r.id, version: Number(r.v ?? 0) })); // Every live wrap as it stands before this write, the row's own too: a re-wrap of the account's only row at a // new version, or under another key, is a change of the account's key as much as any other row's. vaultIdentity.refuseDifferentKey(this.ctx.storage.sql, wrapped, wrapVersion(rowId), vmkCheck); } } // What the row's identity is once written: kept with a wrap that declares one, forgotten with any other, and // forgotten when only its version moved (the identity names a key at one version). A re-declaration of a row the // device holds unchanged may pin the account's identity (src/vault_identity.ts, VAULT GUARD 2). const before = table === VAULT_KEY_TABLE && act !== "create" && args.id !== undefined ? this.store.get(VAULT_KEY_TABLE, text(args.id, "id")) : null; const declaredKind = table === VAULT_KEY_TABLE && vmkCheck !== null ? vaultIdentity.kindOf(before, data, caller.who?.deviceId) : "new"; const noteIdentity = (rowId: string): void => { if (table !== VAULT_KEY_TABLE) return; const sql = this.ctx.storage.sql; if (act === "delete" || data.wrapped_vmk === null) return vaultIdentity.forget(sql, rowId); const stored = this.store.get(VAULT_KEY_TABLE, rowId); if (data.wrapped_vmk !== undefined) { vaultIdentity.noteWrap(sql, rowId, vmkCheck, wrapVersion(rowId), stored?.data.device_id, declaredKind); const device = caller.who?.deviceId; if (declaredKind === "redeclared" && vmkCheck !== null && device) { const own = this.store.list(VAULT_KEY_TABLE, { column: "device_id", equals: device }).filter((r) => Boolean(r.data.wrapped_vmk)); vaultIdentity.maybePin(sql, { id: rowId, device, check: vmkCheck, version: wrapVersion(rowId) }, own.map((r) => ({ id: r.id, created_at: r.created_at })), Date.now()); } } else if (data.vmk_version !== undefined && Number(data.vmk_version) !== Number(before?.data.vmk_version ?? 0)) vaultIdentity.forget(sql, rowId); }; if (table === SEAL_KEY_TABLE && act !== "delete") this.checkSealKey(caller, defs, act, args.id === undefined ? null : text(args.id, "id"), data); if (table === allowlist.PERSON_KEY_TABLE && this.samePersonKey(caller, act, args.id === undefined ? null : text(args.id, "id"), data, outcome)) return; if (act === "create") { if (RETIRED_TABLES.has(table)) refuse(403, "retired_table", retiredRefusal(table)); const id = args.id === undefined ? undefined : text(args.id, "id"); const made = engine.create(table, data, version, outcome, 0, id ? { id } : {}); outcome.made = made; if (tokens) this.store.setBlind(table, made.id, tokens); noteIdentity(made.id); if (table === VAULT_KEY_TABLE) this.retireOlderKeyRows(caller, made.id, engine, version, outcome); return; } const id = text(args.id, "id"); // An erase of a row the phone's Bin already deleted here ends that tombstone for good: what it kept of its files // goes with it (the phone's emptied Bin; CINEMAS DEV PROOF, 26 Nov 2026: the folder outlived the emptied Bin). const erasing = act === "delete" && args.erase !== undefined; const row = this.store.get(table, id) ?? (erasing ? this.store.any(table, id) : null); if (!row || (row.deleted && (ERASED_KEY in row.data || Object.keys(row.data).length === 0))) refuse(404, "no_such_record", `no ${table} ${id}`); if (act === "update") { // A write made from the version a writer read (STALE, 21 Nov 2026): kept only while the row is still there, else // refused and the writer reads it again and lays its change over what it holds now, as `seal` is. if (args.expect_version !== undefined) { const expect = args.expect_version; if (typeof expect !== "number" || !Number.isInteger(expect) || expect < 0) refuse(400, "bad_args", "expect_version is the row's version as the writer read it"); if (row.version !== expect) refuse(409, "version_moved", `${table} ${id} is at version ${row.version}, not ${expect}: read it again and lay the change over what it holds now`); } engine.update(row, data, version, outcome); if (tokens) this.store.setBlind(table, id, tokens); } else { // A phone's erase (its receipt names why) ends the row for good here too; only the owner's own devices say one. const erase = args.erase === undefined ? null : text(args.erase, "erase"); // EMPTY BIN 1: an owner token is the owner's role but no device of his (with token scopes off it reaches /v1/act). if (erase !== null && (caller.role !== "owner" || caller.tokenId)) refuse(403, "owner_only", "only the owner's own devices erase"); // SERVER 27 H1, M1: a token's delete of a row already in the Bin of a table that bins without the person (chats, // messages, photos) would take it out of the phone's Bin before the owner ever saw it there: refused. if (caller.tokenId && NOT_EMPTIED_BY_AN_ASSISTANT.has(table)) { const binned = ["trashed_at", "deleted_at"].some((k) => typeof row.data[k] === "string" && row.data[k] !== ""); if (binned) refuse(403, "in_the_bin", `${table} ${id} is in the Bin: only the owner's own devices take it out or empty it`); } engine.delete(row, version, outcome, erase); } noteIdentity(id); if (table === VAULT_KEY_TABLE && act === "update") this.retireOlderKeyRows(caller, id, engine, version, outcome); } /** * `import_rows { rows }` (sealing plan L8): the Mac importer runs the * messages, calls and mail engines over its own copy and lands what they * planned here, as apply.ts lands a plan: a row the object lacks (or holds * deleted) is made under its id with its stamps, one it holds takes the * patch, a retract deletes it. One transaction for the whole call, so a * batch lands whole or not at all. A sealed table's row comes sealed with * its blind tokens; the object matches nothing and reads no sealed word. * Only the owner's own devices import, never a token; the key tables are * never imported. */ private importRows(caller: Caller, engine: Engine, args: Record, version: number, outcome: Outcome): void { if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "only the owner's own devices import rows"); const rows = Array.isArray(args.rows) ? (args.rows as unknown[]) : null; if (!rows) refuse(400, "bad_args", "import_rows needs rows"); if (rows.length > IMPORT_ROWS) refuse(413, "too_many", `import at most ${IMPORT_ROWS} rows per call`); blindBudget(rows); const made: Record = {}; const changed: Record = {}; const bump = (m: Record, table: string): void => { m[table] = (m[table] ?? 0) + 1; }; const when = (value: unknown): string | undefined => (typeof value === "string" && !Number.isNaN(Date.parse(value)) ? value : undefined); for (const item of rows) { const row = object(item, "row"); const table = text(row.table, "table"); const id = text(row.id, "id"); const t = engine.defs.table(table); if (!t) refuse(404, "no_such_table", `no table ${table}`); if (table === SEAL_KEY_TABLE || table === allowlist.PERSON_KEY_TABLE || unlock.WINDOW_TABLES.has(table) || table === VAULT_KEY_TABLE) refuse(400, "not_imported", `${table} is never imported`); const held = this.store.any(table, id); if (row.retract === true) { if (row.data !== undefined || row.blind !== undefined) refuse(400, "bad_args", "a retract carries no data"); if (held && !held.deleted) { engine.delete(held, version, outcome); bump(changed, table); } continue; } const data = this.admitDeviceClear(t, object(row.data ?? {}, "data"), engine, outcome); // A sealed row comes with its blind tokens, as a sealed write does (sealing plan §4). const sealing = SEAL_FIELDS.some((k) => k in data); if (row.blind !== undefined && !sealing) refuse(400, "bad_blind", "blind tokens come only beside a row that carries sealed_enc"); const tokens = sealing ? blindArg(row.blind ?? [], table) : null; const stamps: Stamps = {}; const updated = when(row.updated_at); if (updated) stamps.updated_at = updated; if (!held || held.deleted) { const created = when(row.created_at); if (created) stamps.created_at = created; engine.create(table, data, version, outcome, 0, { id, ...stamps }); bump(made, table); } else if (engine.update(held, data, version, outcome, 0, stamps) !== held) bump(changed, table); if (tokens) this.store.setBlind(table, id, tokens); } outcome.reply = { made, changed }; } /** * `restore { rows }` (restore-from-phone, 10 Nov 2026): the owner's phone * brings back the rows its copy of a database that is gone still holds, * each with its own id and times, in the order given (parents before * children: a link to a row the object lacks refuses the call). A row the * object lacks is made; one it holds live takes the phone's version when * the phone's `updated_at` is not older than its own (rows imported from a * backup meanwhile are older, and the phone's newer edit wins), else the * object's stands; one it deleted stays deleted. A held id is answered, * never refused, so a restore stopped part way is sent again whole and * changes nothing twice. Each row is its own write with its own rule * budget, as an import's is. */ private restore(caller: Caller, engine: Engine, args: Record, version: number, outcome: Outcome): void { // RESTORE ACT (coordinator's tenth review, M1): the owner's own PHONE alone, never a token of any scope, on any route. // A token could otherwise lay rows straight into mcp_token, device or a window grant (an owner token minting // itself a lasting token), or write its own data over any row. if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "only the owner's own devices restore rows"); const rows = Array.isArray(args.rows) ? (args.rows as unknown[]) : null; if (!rows) refuse(400, "bad_args", "restore needs rows"); if (rows.length > RESTORE_ROWS) refuse(413, "too_many", `restore at most ${RESTORE_ROWS} rows per call`); blindBudget(rows); const restored: { table: string; id: string; landed: string }[] = []; const when = (value: unknown): string | undefined => (typeof value === "string" && !Number.isNaN(Date.parse(value)) ? value : undefined); for (const item of rows) { const row = object(item, "row"); const table = text(row.table, "table"); const id = text(row.id, "id"); const said = object(row.data ?? {}, "data"); const t = engine.defs.table(table); if (!t) refuse(404, "no_such_table", `no table ${table}`); // Seal keys belong to the database that minted them: a former database's are no row of this one. if (table === SEAL_KEY_TABLE) refuse(400, "not_restored", "seal keys are never restored: this database mints its own data key"); // The person key is published by the phone that holds it, never brought back from another database. if (table === allowlist.PERSON_KEY_TABLE) refuse(400, "not_restored", "a person key is never restored: the phone publishes it itself"); const data = this.admitDeviceClear(t, said, engine, outcome); // A sealed row comes with its blind tokens, as a sealed write does (sealing plan §4). const sealing = SEAL_FIELDS.some((k) => k in data); if (row.blind !== undefined && !sealing) refuse(400, "bad_blind", "blind tokens come only beside a row that carries sealed_enc"); const tokens = sealing ? blindArg(row.blind ?? [], table) : null; const stamps: Stamps = {}; const created = when(row.created_at); const updated = when(row.updated_at); if (created) stamps.created_at = created; if (updated) stamps.updated_at = updated; const each = new Outcome_(); const held = this.store.any(table, id); let landed: string; if (!held) { engine.create(table, data, version, each, 0, { id, ...stamps }); landed = "made"; } else if (held.deleted) { landed = "deleted"; } else if (updated !== undefined && Date.parse(updated) < Date.parse(held.updated_at)) { landed = "standing"; } else { const next = engine.update(held, data, version, each, 0, stamps); landed = next === held ? "unchanged" : "written"; } if (tokens && (landed === "made" || landed === "written" || landed === "unchanged")) this.store.setBlind(table, id, tokens); restored.push({ table, id, landed }); outcome.changed.push(...each.changed); outcome.notices.push(...each.notices); } outcome.reply = { restored }; } /** * `person_key` is published by the owner's own devices alone (never a token, never MCP), once: * its id is the fingerprint, the first 8 characters of `public_key` (a 32-byte Ed25519 public half, * base64url), beside the private half sealed under the vault key (`sealed_private_enc` at * `vmk_version`). A database holds one person key: another is `person_key_held`. The same key * published again (a phone asks at every sign-in) is answered as it stands, so the publish is * idempotent; a row is never changed or deleted (`person_key_fixed`). * Answers whether the write is already done (the same key is held). */ private samePersonKey(caller: Caller, act: string, id: string | null, data: Record, outcome: Outcome): boolean { // Never the admin: a person key the server planted would sign it a window. if (caller.role !== "owner" || caller.tokenId || caller.admin) refuse(403, "owner_only", "only the owner's own devices publish the person key"); if (act !== "create") refuse(409, "person_key_fixed", "a person key is written once, when it is published, and never changed or deleted"); const publicKey = data.public_key; if (typeof publicKey !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(publicKey)) refuse(400, "bad_person_key", "public_key is the person key's 32-byte public half, base64url without padding"); const fingerprint = publicKey.slice(0, 8); if (id !== fingerprint) refuse(400, "bad_person_key", `a person key's id is its fingerprint ${fingerprint}`); if (typeof data.sealed_private_enc !== "string" || !data.sealed_private_enc) refuse(400, "bad_person_key", "sealed_private_enc is the private half sealed under the vault key"); const vmk = data.vmk_version; if (typeof vmk !== "number" || !Number.isInteger(vmk) || vmk < 1) refuse(400, "bad_person_key", "vmk_version is the vault key version the private half is sealed at"); const held = this.store.select(allowlist.PERSON_KEY_TABLE, [], "id", 2); const same = held.find((row) => row.id === fingerprint && row.data.public_key === publicKey); if (same) { outcome.made = same; return true; } if (held.length) refuse(409, "person_key_held", `this database holds person key ${held[0]!.id}: it has one person key`); return false; } /** * `seal_key` is written by the owner's own devices alone, and only as the sealing plan shapes it: * row `dk` holds the data key's wrap (`dk_enc` at `vmk_version`), made once (a second create is * `duplicate_id`, so two first devices racing end with one data key) and re-wrapped only at a * vault key version that does not go back; row `v:
` holds a sealed table's seal version * `v`, which only moves forward (`seal_version_back`), so no two devices seal one version apart. * No seal_key row is deleted (its definition says `delete: false`). */ private checkSealKey(caller: Caller, defs: Definitions, act: string, id: string | null, data: Record): void { if (caller.role !== "owner" || caller.tokenId) refuse(403, "owner_only", "only the owner's own devices write seal keys"); if (id === null) refuse(400, "bad_seal_key", `a seal key names its row: ${SEAL_KEY_DK}, or ${SEAL_KEY_VERSION}
`); const held = act === "create" ? null : this.store.get(SEAL_KEY_TABLE, id); const count = (value: unknown): number | null => (typeof value === "number" && Number.isInteger(value) && value >= 1 ? value : null); if (id === SEAL_KEY_DK) { if ("v" in data) refuse(400, "bad_seal_key", "the data key's row holds no seal version"); const dkEnc = data.dk_enc ?? held?.data.dk_enc; if (typeof dkEnc !== "string" || !dkEnc) refuse(400, "bad_seal_key", "the data key's row holds dk_enc, the data key sealed under the vault key"); const vmk = count(data.vmk_version ?? held?.data.vmk_version); if (vmk === null) refuse(400, "bad_seal_key", "the data key's row names the vault key version it is sealed at (vmk_version)"); const was = count(held?.data.vmk_version); if (was !== null && vmk < was) refuse(409, "seal_version_back", `the data key is sealed at vault key version ${was}; a re-wrap never goes back to ${vmk}`); return; } if (id === ARRIVAL_ROW) { // The arrival key's public half (e2e rulings R2): what the object seals its own writes to. Its private half only devices derive. const extra = Object.keys(data).filter((k) => k !== "pub"); if (extra.length) refuse(400, "bad_seal_key", `the arrival key's row holds pub alone, not ${extra.join(", ")}`); if (!keyFromText(data.pub)) refuse(400, "bad_seal_key", "the arrival key's row holds pub, a 32-byte X25519 public key in base64url"); if (held && held.data.pub !== data.pub) refuse(409, "arrival_key_held", "this database's arrival key is held already: a device derives the same one from the same data key"); return; } if (!id.startsWith(SEAL_KEY_VERSION)) refuse(400, "bad_seal_key", `a seal key's row is ${SEAL_KEY_DK}, ${ARRIVAL_ROW} or ${SEAL_KEY_VERSION}
, not ${JSON.stringify(id)}`); const table = id.slice(SEAL_KEY_VERSION.length); if (!defs.table(table)?.seal) refuse(400, "bad_seal_key", `${JSON.stringify(table)} is no sealed table: only a sealed table has a seal version`); const extra = Object.keys(data).filter((k) => k !== "v"); if (extra.length) refuse(400, "bad_seal_key", `a seal version's row holds v alone, not ${extra.join(", ")}`); const v = count(data.v); if (v === null) refuse(400, "bad_seal_key", "a seal version is a whole number from 1"); const was = count(held?.data.v) ?? 1; if (v <= was) refuse(409, "seal_version_back", `${table} is sealed at version ${was}: the next is ${was + 1}, never ${v}`); } /** * The object is the arbiter of who founds the vault. A device writing the first wrap onto its own * vault_key row (the row's device_id is the device its sign-in named) founds the vault: the first * founding is kept, and a founding while ANOTHER DEVICE'S row already holds a wrap is refused * `vault_founded`, so two first devices racing end with one vault. A device is its vault key's * PUBLIC KEY, not its row id: a wrapped row carrying the caller's own public key under an older id * (a phone that founded before it signed in, its row pushed at adoption) is the caller's own * founding, so this write is a re-wrap or a rename, never a second founding. An approval (a wrap * onto another device's row) and a re-wrap of a row already open (a rotation) pass as before. */ private refuseLaterFounding(caller: Caller, act: string, id: string | null, data: Record): void { if (data.wrapped_vmk === undefined || data.wrapped_vmk === null) return; const device = caller.who?.deviceId; if (!device) return; const held = act === "create" || id === null ? null : this.store.get(VAULT_KEY_TABLE, id); if (held && held.data.wrapped_vmk) return; if ((data.device_id ?? held?.data.device_id) !== device) return; // A device that just opened a way back in (a recovery code, a platform key) puts its own wrap on its own row. if (recovery.granted(this.ctx.storage.sql, device, Date.now())) return; const own = (data.public_key ?? held?.data.public_key ?? null) as string | null; // Its own key already wrapped under another row (another copy on the same phone published a second row, 22 Nov // 2026): a re-wrap onto its own row, never a founding, whatever other devices hold. The older row is retired. if (own && this.store.count(VAULT_KEY_TABLE, [ { sql: "json_extract(data, '$.wrapped_vmk') IS NOT NULL AND id <> ? AND json_extract(data, '$.public_key') = ?", args: [id ?? "", own] }, ]) > 0) return; const others = this.store.count(VAULT_KEY_TABLE, [ { sql: "json_extract(data, '$.wrapped_vmk') IS NOT NULL AND id <> ? AND json_extract(data, '$.public_key') IS NOT ?", args: [id ?? "", own] }, ]); if (others > 0) refuse(409, "vault_founded", "Another device already holds this vault's key, so this one was not kept. This device waits for that one to let it in."); } /** * NO DEVICE INTO THE VAULT ON A TAP (19 Nov 2026). A first wrap written onto ANOTHER device's * vault_key row (an approval: `signin.approve`, `signin.approveSibling`) is kept only when this object holds an * ask that the writing device approved after the two screens' codes were compared, naming that device and that * very key (src/approval.ts `Asks.admitted`). The one-tap Approve of apps from before (`vault.approveDevice`) has * no such ask and is told `update_app`. A device's own row (a founding, a recovery) and a re-wrap of a row already * open (a rotation) are not approvals and pass as before. */ private refuseBlindAdmission(caller: Caller, act: string, id: string | null, data: Record): void { if (data.wrapped_vmk === undefined || data.wrapped_vmk === null) return; const device = caller.who?.deviceId; const held = act === "create" || id === null ? null : this.store.get(VAULT_KEY_TABLE, id); if (held && held.data.wrapped_vmk) return; const target = (data.device_id ?? held?.data.device_id) as string | undefined; if (!target || target === device) return; const key = (data.public_key ?? held?.data.public_key) as string | undefined; if (device && key && this.asks().admitted(target, key, device, Math.floor(Date.now() / 1000))) return; refuse(409, "update_app", "Update Cotton on this phone to let a device in: the new device shows a code, typed here."); } /** * THE SAME KEY'S WRAP ON EVERY ROW OF IT (owner at the Mac, 22 Nov 2026). A phone whose own key is wrapped on one * vault_key row and published again, unwrapped, on a second row under its device id (another copy on the phone) * keeps ONE row per device in its copy; holding the unwrapped one it never opened its vault and so could let no * device in, and its own re-wrap had been refused `vault_founded` and let go, never tried again. The wrap is the * vault key sealed TO that public key, so the object copies it onto the device's other rows carrying the same key: * nothing is opened here, and the holder of the private half opens either. A row under another key is left alone. */ private ownKeyRowsToHeal(deviceId: string): Array<{ row: StoredRow; wrapped: string; version: number; check: string | null }> { const rows = this.store.list(VAULT_KEY_TABLE, { column: "device_id", equals: deviceId }); const heal: Array<{ row: StoredRow; wrapped: string; version: number; check: string | null }> = []; for (const row of rows) { if (row.data.wrapped_vmk || !row.data.public_key) continue; // VAULT GUARD 2 item 1: with no identity pinned in the account, any donor, exactly as before (the 22 Nov fix for // a device stuck waiting for approval); once pinned, only a donor whose identity is the pin. const donor = rows .filter((r) => r.id !== row.id && r.data.wrapped_vmk && r.data.public_key === row.data.public_key && vaultIdentity.healsFrom(this.ctx.storage.sql, r.id, Number(r.data.vmk_version ?? 0))) .sort((a, b) => Number(b.data.vmk_version ?? 0) - Number(a.data.vmk_version ?? 0))[0]; const check = donor ? (vaultIdentity.identityOf(this.ctx.storage.sql, donor.id)?.check ?? null) : null; if (donor) heal.push({ row, wrapped: donor.data.wrapped_vmk as string, version: Number(donor.data.vmk_version ?? 0), check }); } return heal; } private healOwnKeyRows(deviceId: string, engine: Engine, version: number, outcome: Outcome): void { for (const { row, wrapped, version: vmk, check } of this.ownKeyRowsToHeal(deviceId)) { engine.update(row, { wrapped_vmk: wrapped, vmk_version: vmk }, version, outcome); vaultIdentity.noteWrap(this.ctx.storage.sql, row.id, check, vmk, row.data.device_id); } } /** * One row per device key. Once a device's own row (its device_id the one its sign-in named) holds a * wrap, every other row carrying the same public key is that device's under an older id and is * retired: deleted, its tombstone pulled like any other. The phone takes the older row's wrap over its * own (it holds the private half, so it alone knows the key is its own); the object holds both rows, * so it alone can retire the older one. */ private retireOlderKeyRows(caller: Caller, id: string, engine: Engine, version: number, outcome: Outcome): void { const device = caller.who?.deviceId; const kept = this.store.get(VAULT_KEY_TABLE, id); if (!device || !kept || kept.data.device_id !== device || !kept.data.wrapped_vmk || !kept.data.public_key) return; // KEPT FOUR 3 A: only a row of the SAME key identity wrapped to the SAME device, both declared; a row whose identity // is not known (an older build's post) is never retired: both rows stay. for (const older of this.store.list(VAULT_KEY_TABLE, { column: "public_key", equals: kept.data.public_key as string })) { if (older.id === id) continue; if (!vaultIdentity.sameKeySameDevice(this.ctx.storage.sql, { id, device_id: kept.data.device_id, public_key: kept.data.public_key }, { id: older.id, device_id: older.data.device_id, public_key: older.data.public_key })) continue; engine.delete(older, version, outcome); vaultIdentity.forget(this.ctx.storage.sql, older.id); } } /** `set_role { phone, role, name? }`: the owner makes staff (or a member again). */ private setRole(caller: Caller, args: Record, version: number): void { if (caller.role !== "owner") refuse(403, "owner_only", "only the owner changes roles"); const phone = normalizePhone(text(args.phone, "phone")); if (!phone) refuse(400, "bad_phone", "use an international phone number starting with +"); const role = text(args.role, "role"); if (role !== "member" && role !== "staff" && role !== "owner") refuse(400, "bad_role", "role is member, staff or owner"); const name = optionalText(args.name); const existing = this.store.personByPhone(phone); if (existing) { this.store.setPerson(existing.id, { role, ...(name ? { name } : {}) }, version); if (role === "member") this.store.revokePersonSessions(existing.id); } else { this.store.addPerson(crypto.randomUUID(), phone, name, role, version); } } // ── import (the personal object) ───────────────────────────────────── /** The Mac reads sources; the object decides everything (coordinator, 26 Oct 2026). Only the owner imports, into the personal object. */ /** * The three old import routes (messages, message changes, calls) write their rows in the clear: they never seal on * arrival. So they are refused once any table they write is sealed, as the photo route is (ROUTES-AUDIT 11, 23 Nov * 2026). Every live database seals these tables, so the routes answer 410 there. The Mac decides messages and calls * over its own opened copy and lands them through import_rows; no build of it calls these routes. */ private clearImportOpen(): void { const sealed = CLEAR_IMPORT_TABLES.filter((id) => this.definitions().table(id)?.seal); if (sealed.length) refuse(410, "decided_on_the_mac", `messages and calls are decided on the Mac now and land through import_rows (${sealed.join(", ")} sealed here); update the Mac importer`); } private importer(caller: Caller): { databaseId: string; namespace: string } { if (!this.personal()) refuse(404, "not_personal", "imports land in the personal database"); if (caller.role !== "owner") refuse(403, "owner_only", "only the owner imports"); this.installed(); this.roomToWrite(); const databaseId = this.databaseId(); // Derived ids are made under the database's namespace: its own id, unless it was made at the stop under an older file's. return { databaseId, namespace: this.store.meta("namespace") ?? databaseId }; } /** One storage transaction and one version for a whole batch; a batch that changed nothing moves no version. */ private importWrite(fn: (engine: Engine, version: number, outcome: Outcome, applied: Applied) => T): { result: T; version: number; applied: Applied } { let result: T | undefined; let version = 0; const applied = newApplied(); this.ctx.storage.transactionSync(() => { const before = this.store.version(); version = this.store.bump(); const outcome = new Outcome_(); const engine = this.engine(); result = fn(engine, version, outcome, applied); if (!outcome.changed.length) { this.store.setMeta("version", String(before)); version = before; } }); return { result: result as T, version, applied }; } /** * `POST /v1/import/messages`, one `ImportBatch` as serde serialises * crates/cotton-core/src/import/envelope.rs: the messages engine resolves the * thread, its contacts and participants, removes what the object holds, and * links the replies. The same batch twice changes nothing. */ private importMessages(caller: Caller, body: Record): Response { const { databaseId, namespace } = this.importer(caller); this.clearImportOpen(); const issue = batchProblem(body); if (issue) refuse(400, "bad_batch", issue); const batch = body as unknown as ImportBatch; if (batch.workspaceId !== databaseId) refuse(400, "wrong_database", `this batch is for database ${batch.workspaceId}; this is ${databaseId}`); const reader = new Reader(this.store, this.meta().owner_phone ?? null); const { result, version, applied } = this.importWrite((engine, version, outcome, applied) => { let plan; try { plan = planImport(reader, { batch, namespace, now: engine.clock.now, newId: () => crypto.randomUUID() }); } catch (error) { if (error instanceof EngineRefusal && error.code === "IMPORT_SHAPE") refuse(400, "bad_batch", error.message); throw error; } applyChanges(engine, plan.changes, version, outcome, applied); // The reply pass reads the rows that just landed. let unresolved = 0; for (const chat of plan.chats) { const links = planReplyLinks(reader, chat.threadId, batch.channel); unresolved += links.unresolved; applyChanges(engine, links.changes, version, outcome, applied); } return { plan, unresolved }; }); const { plan, unresolved } = result; const made = (table: string): number => applied.made.get(table) ?? 0; return json({ threadId: plan.chats.length === 1 ? plan.chats[0]!.threadId : null, applied: { messages: plan.chats.reduce((n, c) => n + c.inserted, 0), threads: made("thread"), people: made("message_contact"), reactions: made("message_reaction") }, skipped: plan.chats.reduce((n, c) => n + c.skipped, 0), unresolvedReplies: unresolved, chats: plan.chats, version, }); } /** * `POST /v1/import/message_changes { workspaceId, channel, changes }`: edits, * deletes for everyone and reactions on messages the object already holds, * each on the row its message's own id names (crates/cotton-core/src/import/ * message_changes.rs). A change to a message not held is counted, never kept. */ private importMessageChanges(caller: Caller, body: Record): Response { const { databaseId } = this.importer(caller); this.clearImportOpen(); const problem = changesProblem(body); if (problem) refuse(400, "bad_batch", problem); if (body.workspaceId !== databaseId) refuse(400, "wrong_database", `these changes are for database ${String(body.workspaceId)}; this is ${databaseId}`); const channel = body.channel as string; const reader = new Reader(this.store, this.meta().owner_phone ?? null); const { result, version } = this.importWrite((engine, version, outcome, applied) => { const plan = planMessageChanges(reader, databaseId, channel, body.changes as MessageChange[]); applyChanges(engine, plan.changes, version, outcome, applied); return plan.report; }); return json({ applied: result, version }); } /** `POST /v1/import/calls { calls: DeviceCall[] }`: one row per (source, external id), the handle matched to a contact and a person. */ private importCalls(caller: Caller, body: Record): Response { const { namespace } = this.importer(caller); this.clearImportOpen(); const problem = callsProblem(body); if (problem) refuse(400, "bad_batch", problem); const calls = body.calls as DeviceCall[]; const reader = new Reader(this.store, this.meta().owner_phone ?? null); const { result, version, applied } = this.importWrite((engine, version, outcome, applied) => { const changes = callChanges(reader, namespace, calls, engine.clock.now); applyChanges(engine, changes, version, outcome, applied); return changes; }); const written = (applied.made.get("call") ?? 0) + (applied.changed.get("call") ?? 0); return json({ applied: { calls: written, people: result.filter((c) => c.patch?.person_id).length }, unchanged: result.length - written, version }); } /** * `POST /v1/import/photos`, one `PhotoWork` as serde serialises * crates/cotton-client/src/ingest/sources/photos/mod.rs: the photo, video, * sighting and face rows and the people the clusters name, decided by * src/import/photos.ts. The originals were PUT first; whether each is * there, and its size, is a HEAD of its key made before the write. */ private async importPhotos(caller: Caller, body: Record): Promise { const { databaseId } = this.importer(caller); // The Mac decides the library over its own opened copy now and lands it through import_rows (crates/cotton-mac photos.rs): // with People or Photos sealed this route would read and write their words in the clear, so it is refused (e2e rulings R2). if (["photo", "video", "face", "sighting", "person", "person_handle"].some((id) => this.definitions().table(id)?.seal)) refuse(410, "decided_on_the_mac", "the photo library is decided on the Mac now and lands through import_rows; update the Mac importer"); const problem = photosProblem(body); if (problem) refuse(400, "bad_batch", problem); const work = body as unknown as PhotoWork; const slug = this.meta().slug; const keys = [...new Set(work.assets.map((a) => originalKeyOf(databaseId, a)).filter((k): k is string => k !== null))]; const heads = await Promise.all(keys.map((key) => this.env.MEDIA.head(bucketKey(key, databaseId, slug)))); const sizes = new Map(keys.map((key, i) => [key, heads[i]?.size ?? null])); const reader = new PhotoReader(this.store); const { result, version, applied } = this.importWrite((engine, version, outcome, applied) => { const plan = planPhotos(reader, work, { databaseId, sizes, now: engine.clock.now, newPersonId: () => crypto.randomUUID() }); applyChanges(engine, plan.changes, version, outcome, applied); return plan; }); const touched = (table: string): number => (applied.made.get(table) ?? 0) + (applied.changed.get(table) ?? 0); return json({ applied: { photos: result.written.photo, videos: result.written.video, faces: touched("face"), people: applied.made.get("person") ?? 0 }, skipped: result.skipped, notes: result.notes, version, }); } /** * `GET /v1/outbox?status=`: the messages the owner's phone queued for the * Mac to send, oldest first. The phone makes a row and the Mac marks it, both * through the plain `/v1/act`; this read is the Mac's only other door. */ private outbox(caller: Caller, params: URLSearchParams): Response { if (!this.personal()) refuse(404, "not_personal", "the outbox lives in the personal database"); if (caller.role !== "owner") refuse(403, "owner_only", "the outbox is the owner's"); this.installed(); const status = params.get("status") ?? "queued"; if (!["queued", "sending", "sent", "failed"].includes(status)) refuse(400, "bad_status", "status is queued, sending, sent or failed"); return json({ rows: this.store.list("outbox", { column: "status", equals: status }).map((r) => wire(r, true)) }); } // ── photos ───────────────────────────────────────────────────────────── /** * A business's public photo (a menu, a room). Never on a personal database, whose files are its own sealed media: * served to anyone, it would be free hosting for every free account (ROUTES-AUDIT 15). A business's photos are * bounded: PHOTOS_PER_HOUR an hour and PHOTOS_HELD_BYTES in all, and each must be the picture its type says. */ private async putPhoto(caller: Caller, request: Request): Promise { if (this.personal()) refuse(404, "not_personal", "public photos are a business's; a person's files are their media"); if (!(caller.admin || caller.role === "staff" || caller.role === "owner")) refuse(403, "staff_only", "only staff add photos"); const type = request.headers.get("content-type") ?? "application/octet-stream"; const ext = { "image/jpeg": "jpg", "image/png": "png", "image/webp": "webp", "image/heic": "heic", "image/gif": "gif" }[type]; if (!ext) refuse(400, "bad_photo", "send a JPEG, PNG, WebP, HEIC or GIF with its content-type"); const now = Date.now(); const hour = JSON.parse(this.store.meta(PHOTOS_HOUR) ?? "null") as { from: number; n: number } | null; const counted = hour && now - hour.from < 3_600_000 ? hour : { from: now, n: 0 }; if (counted.n >= PHOTOS_PER_HOUR) refuse(429, "too_many_photos", `at most ${PHOTOS_PER_HOUR} photos an hour`); const bytes = await request.arrayBuffer(); if (bytes.byteLength === 0) refuse(400, "bad_photo", "the photo is empty"); if (bytes.byteLength > 25 * 1024 * 1024) refuse(413, "too_big", "a photo is at most 25 MB"); if (!looksLike(new Uint8Array(bytes, 0, Math.min(16, bytes.byteLength)), type)) refuse(400, "bad_photo", `this is not a ${type}`); const held = Number(this.store.meta(PHOTOS_BYTES) ?? "0"); if (held + bytes.byteLength > PHOTOS_HELD_BYTES) refuse(413, "photos_full", "this business holds as many photos as it can"); this.store.setMeta(PHOTOS_HOUR, JSON.stringify({ from: counted.from, n: counted.n + 1 })); const digest = await crypto.subtle.digest("SHA-256", bytes); const sha = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); const key = `${this.meta().slug}/${sha}.${ext}`; if (!(await this.env.PHOTOS.head(key))) { await this.env.PHOTOS.put(key, bytes, { httpMetadata: { contentType: type } }); this.store.setMeta(PHOTOS_BYTES, String(held + bytes.byteLength)); } return json({ key, url: `/v1/photos/${key}`, bytes: bytes.byteLength }, 201); } // ── media (the personal object) ────────────────────────────────────── /** The owner's media in R2 (src/media.ts): put (whole, or in parts), ask which are missing, get at a size. */ private async media(caller: Caller, request: Request, url: URL): Promise { if (!this.personal()) refuse(404, "not_personal", "media live in the personal database"); if (caller.role !== "owner") refuse(403, "owner_only", "the media are the owner's"); const databaseId = this.databaseId(); const slug = this.meta().slug; if (request.method === "POST" && url.pathname === "/v1/media/stream") { const key = text((await readJson(request)).key, "key"); await this.tokenFileGate(caller, key, databaseId, false); const base = `${url.origin}${request.headers.get(PREFIX_HEADER) ?? ""}`; return mintStream(this.env, key, bucketKey(key, databaseId, slug), base, Date.now(), slug); } if (request.method === "POST" && url.pathname === "/v1/media/missing") { const body = await readJson(request); const keys = body.keys; if (!Array.isArray(keys) || !keys.every((k) => typeof k === "string")) refuse(400, "bad_request", "missing needs keys, a list of media keys"); if (keys.length > 500) refuse(413, "too_many", "ask about at most 500 keys at a time"); // AVATAR SEAL 3 (3): a token is never told whether a person's sealed file is held. if (caller.tokenId && (keys as string[]).some((k) => isDeviceSealedKind(databaseId, k))) refuse(403, "sealed_kind", "a token cannot ask after a person's sealed files: only the owner's devices do"); return missingMedia(this.env, (keys as string[]).map((key) => ({ key, at: bucketKey(key, databaseId, slug) })), body.sealed === true); } const key = decodeURIComponent(url.pathname.slice("/v1/media/".length)); // AVATAR SEAL 4 (1, 2): a token's reach into a person's sealed-kind file, decided before anything is looked up, so // the answer is the same whether the file is held or not: never a write or a delete; a read only of a kind a sealed // table owns, inside that table's open window. Device credentials as before. const writes = request.method === "PUT" || request.method === "DELETE" || (request.method === "POST" && (url.searchParams.has("uploads") || url.searchParams.has("upload"))); await this.tokenFileGate(caller, key, databaseId, writes); // AUDIT C 3: a file deleted here is gone for good (no Bin), so an assistant's key never deletes one: an OAuth // connection's, or any key with an allow list. Only the owner's devices, and the owner's own full keys (the film // scripts while token scopes are off), do. if (request.method === "DELETE" && caller.tokenId && (caller.allow || this.store.get(TOKEN_TABLE, caller.tokenId)?.data.connection_id)) { refuse(403, "owner_device_only", "deleting a file erases it for good, so only the owner's own devices do; an assistant's key never does"); } if (request.method === "DELETE" && url.searchParams.get("prefix") === "1") { const gone = await deleteFolder(this.env, bucketFolder(key, databaseId, slug), this.mediaBudget()); if (!gone.deleted) refuse(404, "not_found", "no media under that folder"); return json(gone); } // A kit's tile picture, by its reference: the Worker's static assets, never a key of this database (src/media.ts). const kit = request.method === "GET" || request.method === "HEAD" ? await kitPicture(this.env, key, request.method === "HEAD") : null; if (kit) return kit; const at = bucketKey(key, databaseId, slug); // A file over one request's limit, in parts (src/media.ts). if (request.method === "POST" && url.searchParams.has("uploads")) { const started = await startParts(this.env, at, await readJson(request), this.mediaBudget()); // Its id kept until it is finished, so deleting the account aborts it (src/account_delete.ts UPLOADS). if (started.status === 201) accountDelete.uploadOpened(this.ctx.storage.sql, at, ((await started.clone().json()) as { upload: string }).upload); return started; } const upload = url.searchParams.get("upload"); if (upload !== null && request.method === "PUT") return putPart(this.env, at, upload, url.searchParams.get("part"), request); if (upload !== null && request.method === "POST") { const finished = await finishParts(this.env, at, upload, await readJson(request), this.mediaBudget()); accountDelete.uploadClosed(this.ctx.storage.sql, upload); return finished; } if (request.method === "PUT") return putMedia(this.env, at, request, this.mediaBudget()); if (request.method === "GET" || request.method === "HEAD") return getMedia(this.env, at, url.searchParams, request.method === "HEAD", request.headers.get("range")); if (request.method === "DELETE") return deleteMedia(this.env, at, this.mediaBudget()); refuse(405, "method_not_allowed", "media take GET, HEAD, PUT and DELETE, and POST for a file in parts"); } /** * A Cotton MCP token's reach into one of the person's files on the plain media route (AVATAR SEAL 2, 3, 4; 27 Nov * 2026). A kind a device seals (`DEVICE_SEALED_KINDS`): never written or deleted by a token; read only when the kind * maps to a sealed table (`tableOfFileKind`: messages → message, people → person) and the token holds that table's * window. A kind no table opens (photos, videos, books, music, films, meetings, mail) is refused always. Decided * before any lookup, so a token learns nothing of whether a file is held. No window is asked for here (get_media asks). */ private async tokenFileGate(caller: Caller, key: string, databaseId: string, writes: boolean): Promise { if (!caller.tokenId) return; // The sealed-kind rule answers alike for every key of the kind. if (isDeviceSealedKind(databaseId, key)) { if (writes) refuse(403, "sealed_kind", "a token cannot write or delete a person's sealed files: only the owner's devices do"); const owner = tableOfFileKind(kindOfKey(databaseId, key) ?? ""); if (!owner || !this.definitions().table(owner)?.seal) refuse(403, "sealed_kind", "a person's sealed files are read only on the owner's devices"); const mcp = caller.presented ? await this.mcpCaller(caller.presented.token) : null; const keys = mcp ? await this.toolContext(mcp, this.agentGrantOn() ? caller.presented! : null).window.keys(owner!) : null; if (!keys) refuse(403, "window_needed", `files of ${owner} are read by an assistant only inside a window the owner allows: ask with get_media`); } } /** `GET /v1/stream//`: a film's file, by the stream URL's token alone (src/media.ts). */ private async stream(request: Request): Promise { // A cast receiver (a web page on the TV) reads the stream across origins: the token is the whole grant, so any origin may. if (request.method === "OPTIONS") return streamPreflight(); if (request.method !== "GET" && request.method !== "HEAD") refuse(405, "method_not_allowed", "a stream takes GET and HEAD"); if (!this.personal()) refuse(404, "not_personal", "media live in the personal database"); const [, token, rest] = STREAM_PATH.exec(new URL(request.url).pathname)!; const key = decodeURIComponent(rest!); await admitStream(this.env, token!, key, Date.now(), this.meta().slug); return crossOrigin(await streamMedia(this.env, key, bucketKey(key, this.databaseId(), this.meta().slug), request.method === "HEAD", request.headers.get("range"))); } /** What the object's media may still grow by, and the count every store adds to and every delete takes from (never below none: media put before the count began were never counted). */ /** The media this account may hold: its own limit when it has one, else the default. */ private mediaCap(): number { return Number(this.store.meta(MEDIA_CAP) ?? this.caps.media); } private mediaBudget(): MediaBudget { // Bytes this person added to shared spaces count against the same space, from their own tally (src/space/person.ts). const used = Number(this.store.meta(MEDIA_BYTES) ?? "0") + spacePerson.sharedBytes(this.ctx.storage.sql); const add = (bytes: number): void => this.store.setMeta(MEDIA_BYTES, String(Math.max(0, Number(this.store.meta(MEDIA_BYTES) ?? "0") + bytes))); // The space rules (SPACE.md), once thrown for this account: its allowance, refused as space_full. if (this.spaceMode() === "on") return { left: this.spaceAllowance() - used, add, full: { code: space.SPACE_FULL, words: space.SPACE_FULL_WORDS } }; return { left: this.mediaCap() - used, add }; } // ── space for photos and files (assets/design/shared/SPACE.md) ────────── /** This account's mode: its own when the admin set one, else the Worker's switch. */ private spaceMode(): space.SpaceMode { return space.accountMode(this.store.meta(space.META.mode), this.env.SPACE_RULES); } /** What this account may hold under the rules. The first time it is judged, what it already holds becomes its floor: nobody loses anything. */ private spaceAllowance(): number { let floor = this.store.meta(space.META.floor); if (floor === null) { floor = this.store.meta(MEDIA_BYTES) ?? "0"; this.store.setMeta(space.META.floor, floor); } return space.allowance(Number(this.store.meta(space.META.friends) ?? "0"), this.spaceBought(), Number(floor)); } /** What was bought: the plan's size while it holds (paid for, or in its grace), else what the admin set; the larger. */ private spaceBought(): number { return Math.max(Number(this.store.meta(space.META.bought) ?? "0"), this.spacePlan()?.bytes ?? 0); } /** The space as the owner reads it. */ private spaceAnswer(): space.SpaceAnswer { const mode = this.spaceMode(); const bytes = Number(this.store.meta(MEDIA_BYTES) ?? "0"); const allowance = mode === "on" ? this.spaceAllowance() : this.mediaCap(); return { mode, bytes, allowance, free: Math.max(0, allowance - bytes), friends: Number(this.store.meta(space.META.friends) ?? "0"), counting: { days: Number(this.store.meta(space.META.days) ?? "0"), of: space.DAYS_TO_COUNT }, bought: this.spaceBought(), floor: Number(this.store.meta(space.META.floor) ?? "0"), plan: this.spacePlan(), }; } /** A day this owner used an app (an owner device's sync pass): counted once a UTC day, to 14; at 14 the Directory is told once. */ private spaceDay(now: Date): void { if (this.spaceMode() === "off" || !this.personal()) return; const today = space.dayOf(now); const days = space.dayCounted(this.store.meta(space.META.dayLast), Number(this.store.meta(space.META.days) ?? "0"), today); if (days === null) return; this.store.setMeta(space.META.dayLast, today); this.store.setMeta(space.META.days, String(days)); } /** Once its 14 days are counted, the Directory is told, after the pass that counted them; until it has heard, every pass tells it again. */ private async spaceTell(): Promise { if (!this.personal() || this.store.meta(space.META.told) !== null) return; if (Number(this.store.meta(space.META.days) ?? "0") < space.DAYS_TO_COUNT) return; await directory(this.env).spaceActive(this.meta().slug); this.store.setMeta(space.META.told, new Date().toISOString()); } /** The plan this account holds, as it stands now (SPACE.md "Plans"); null with none. */ private spacePlan(): plans.PlanState | null { return plans.stateOf(plans.parseHeld(this.store.meta(space.META.plan)), Date.now()); } /** * A payment provider's event, made plain (src/plans.ts `applyPlanEvent`): the plan set, renewed or ended, a retry * or an older event changing nothing. Undefined where this is no personal database (no account to hold it). */ async spacePlanEvent(event: plans.PlanEvent): Promise { await this.frozenGate(); if (!this.personal()) return undefined; const held = plans.applied(plans.parseHeld(this.store.meta(space.META.plan)), event); this.store.setMeta(space.META.plan, held ? JSON.stringify(held) : null); return this.spacePlan(); } /** The Directory's count of this account's friends (SPACE.md): what its allowance adds 1 GB for each of. */ async spaceFriends(friends: number): Promise { await this.frozenGate(); if (!Number.isSafeInteger(friends) || friends < 0) return; this.store.setMeta(space.META.friends, String(friends)); } /** * The film folders erased records played from (src/engine.ts * `dropPlayedMedia`) and the single keys a write let go (a converted * film's upload, src/films.ts `filmConverted`), deleted from R2 after the * write: one goes off the list once deleted, so one R2 failed on waits for * the next request or the alarm. */ private async dropMedia(): Promise { // JOBS OUT M1: with its switch on, the folders are the job's to drop, a step at a time; here a run is only asked for. if (this.stepOn("media_drop")) return void (await stepJobs.kick(this.stepHost(), "media_drop")); const toDrop = this.store.mediaToDrop().length; await this.mediaDropStep(Infinity); if (this.store.mediaToDrop().length < toDrop) this.didOnObject("media_drop"); } /** The R2 folders an erase left: at most `most` dropped. Whether one a step can drop now is still left. */ private async mediaDropStep(most: number): Promise { const databaseId = this.store.meta("database_id"); if (!this.personal() || !databaseId) return false; let done = 0; for (const folder of this.store.mediaToDrop()) { // A key an open send names keeps its bytes for the copy: it waits for the send to close (src/send/send.ts). if (send.holds(this.ctx.storage.sql, folder)) continue; if (done >= most) return true; done++; const whole = folder.endsWith("/"); let at: string; try { at = whole ? bucketFolder(folder, databaseId, this.meta().slug) : bucketKey(folder, databaseId, this.meta().slug); } catch { // A key that is not this database's names nothing here to delete. console.error(`media_to_drop: ${folder} is not this database's; left in R2`); this.store.mediaDropped(folder); continue; } try { if (whole) await deleteFolder(this.env, at, this.mediaBudget()); else await dropKey(this.env, at, this.mediaBudget()); this.store.mediaDropped(folder); } catch (error) { console.error(`media_to_drop: ${folder} not deleted yet: ${error instanceof Error ? error.message : String(error)}`); } } return false; } /** JOBS OUT C3: the storage counting's jobs that still had work at their last step, and whose turn is next while in use. */ private storageOwed = new Set(); private storageTurn = 0; /** * JOBS OUT C3: one step of the storage counting (the measure, then the recount), exactly as the alarm's bounded jobs * took them: each its own bounded step (the measure by its work units, the recount by Store.recountChunk rows along * the key), each caught; while the object is in use, one of them in turn. Whether work is left, and whether in use. */ private storageCountStep(): { left: boolean; inUse: boolean } { const now = Date.now(); const inUse = now - this.lastUseAt < BUSY_FOR_MS || now - this.lastPullAt < BUSY_FOR_MS; if (!this.store.holdsDefinitions("table")) return { left: false, inUse }; const wasCounting = this.store.countsPending(); const jobs: Array<[string, () => boolean]> = [ ["measure", () => this.ctx.storage.transactionSync(() => this.store.measureStorage(new Date()))], ["recount", () => this.store.carryCounts(RECOUNT_STEPS, (step) => this.ctx.storage.transactionSync(step))], ]; const one = (name: string, step: () => boolean): boolean => { let left: boolean; try { left = step(); } catch (error) { console.log(`cottondb: alarm job ${name} failed ${this.slug}: ${error instanceof Error ? error.message : String(error)}`); left = true; } if (left) this.storageOwed.add(name); else this.storageOwed.delete(name); return left; }; if (inUse && this.paced()) { for (let k = 0; k < jobs.length; k++) { const i = (this.storageTurn + k) % jobs.length; const [name, step] = jobs[i]!; const had = this.storageOwed.has(name); if (one(name, step) || had) { this.storageTurn = (i + 1) % jobs.length; break; } } } else for (const [name, step] of jobs) one(name, step); const recounting = this.storageOwed.has("recount"); if (wasCounting && !recounting && this.store.countsProgress().ready) console.log(`cottondb: row_counts recount ${this.slug}: done, ${this.store.countsProgress().steps} steps`); if (recounting) { const p = this.store.countsProgress(); console.log(`cottondb: row_counts recount ${this.slug}: ${p.left.length} tables left, ${p.left[0]?.table ?? "-"} at ${p.head_rows} rows, ${p.steps} steps`); } return { left: this.storageOwed.size > 0, inUse }; } /** JOBS OUT C1: a pull under way in this instance (the alarm's, or a step's): the other never runs beside it. */ private calendarPulling = false; /** One pass of the Google Calendar pull over every account (src/google_calendar.ts), and when the next is wanted. */ private async calendarPull(): Promise { this.calendarPulling = true; try { return await calendar.pullAll(this.googleHost()); } finally { this.calendarPulling = false; } } /** * JOBS OUT C1: how long until an account's next pass is due by the pull's own cadence (0: due now), or null with no * account to pull. A pass that stopped at its bound carries on CARRY_ON_MS after it; a synced one PULL_EVERY_MS. One * meta read: never a table. */ private calendarDueIn(now: number): number | null { if (!this.personal()) return null; let soonest: number | null = null; for (const a of google.readAccounts(this.store)) { if (a.phase === "reconnect") continue; const last = a.last_pass_at ? Date.parse(a.last_pass_at) : NaN; const due = Number.isFinite(last) ? last + (a.page_token ? calendar.CARRY_ON_MS : calendar.PULL_EVERY_MS) : now; const wait = Math.max(0, due - now); soonest = soonest === null ? wait : Math.min(soonest, wait); } return soonest; } /** The timed sweeps: repeating todos' next, windows' and asks' end, agents, secrets past their until (indexed: ms). */ private runSweeps(): void { // READ COST 4: a throw in these sweeps is said and skips neither the bounded jobs below nor the re-arm. try { this.ctx.storage.transactionSync(() => { const before = this.store.version(); const version = this.store.bump(); const engine = this.engine(); engine.journal = new Journal(this.store, null, "alarm", "act"); const outcome = new Outcome_(); recurrence.advanceAll(engine, this.now(engine), version, outcome); // Windows past their end end, and requests past their expiry expire. this.unlocks.sweep(this.windowHost(), engine, Date.now(), version, outcome); this.agents.sweep(this.windowHost(), Date.now()); // Asks for the owner's Allow past their time expire, their kept requests with them (src/owner_asks.ts). ownerAsks.sweep(this.ctx.storage.sql, this.store, engine, Date.now(), version, outcome); // A pass that made nothing moves no version. if (!outcome.changed.length) this.store.setMeta("version", String(before)); }); } catch (error) { console.log(`cottondb: alarm sweeps failed ${this.slug}: ${error instanceof Error ? error.message : String(error)}`); } // Secrets past their until: the boxes go, here and on the giver's list (src/send/secrets.ts). secrets.sweep({ sql: this.ctx.storage.sql, now: () => Date.now() }); } /** Whether a step job's switch is on for this account (JOBS OUT M1). */ private stepOn(kind: StepKind): boolean { return this.personal() && this.store.meta(stepJobs.switchKey(kind)) === "on"; } /** What the step jobs' door and scheduling lend from this object (src/step_jobs.ts). */ /** JOBS OUT PROOF: what GET /v1/admin/jobs answers. `left` is what the kind's work has still to do (null: no measure). */ private jobsView(): { kinds: { kind: string; on: boolean; owes: boolean; left: number | boolean | null; state: ReturnType; job_steps: number; object_did: number }[]; alarm_last: unknown; alarm_at_iso?: string } { const host = this.stepHost(); const left = (kind: StepKind): number | boolean | null => { const sql = this.ctx.storage.sql; const count = (q: string, ...a: SqlStorageValue[]) => Number(sql.exec<{ n: number }>(q, ...a).one().n); const window = changeWindow(this.store); const before = new Date(Date.now() - window.days * 86_400_000).toISOString(); switch (kind) { case "media_drop": return this.store.mediaToDrop().length; case "changes": return count("SELECT count(*) AS n FROM change WHERE at < ?", before); case "acts": return count("SELECT count(*) AS n FROM acts WHERE at < ?", before); case "prompts": { const old = this.store.promptsBefore(); return count(`SELECT count(*) AS n FROM ${old.from} WHERE ${old.where}`, new Date(Date.now() - PROMPT_DAYS * 86_400_000).toISOString()); } case "order_shadow": return this.store.shadowsFilling(); case "storage_count": return this.store.countsPending() || this.store.measureOwed(new Date()); default: return host.owes(kind); } }; return { kinds: STEP_KINDS.map((kind) => { let l: number | boolean | null = null; try { l = left(kind); } catch { l = null; } return { kind, on: this.stepOn(kind), owes: host.owes(kind), left: l, state: stepJobs.stateOf(this.ctx.storage.sql, kind), job_steps: this.jobSteps.get(kind) ?? 0, object_did: this.objectDid.get(kind) ?? 0 }; }), alarm_last: this.alarmLast.began ? this.alarmLast : null, }; } /** JOBS OUT PROOF, the dev Worker only: invented work for one kind. Answers whether it could, and why not. */ private async seedJob(kind: StepKind): Promise<{ seeded: boolean; why?: string }> { const sql = this.ctx.storage.sql; const now = new Date().toISOString(); const n = Date.now().toString(36); const insert = (table: string, id: string, data: Record, at = now) => sql.exec("INSERT OR REPLACE INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES (?, ?, ?, NULL, ?, 0, ?, ?)", table, id, JSON.stringify(data), this.store.bump(), at, at); switch (kind) { case "media_drop": { for (let i = 0; i < 25; i++) { await this.env.MEDIA.put(`${this.slug}/films/proof-${n}-${i}/master.m3u8`, "#EXTM3U\n"); this.store.dropMediaLater(`${this.store.meta("database_id")}/films/proof-${n}-${i}/`); } return { seeded: true }; } case "artwork": if (!this.store.definitions("table").some((t) => t.id === "book")) return { seeded: false, why: "the account has no book table" }; for (let i = 0; i < 15; i++) insert("book", `proof-book-${n}-${i}`, { title: `An Invented Proof Book ${n} ${i}`, author: "Nobody Invented" }); return { seeded: true }; case "book_files": if (!this.store.definitions("table").some((t) => t.id === "book")) return { seeded: false, why: "the account has no book table" }; for (let i = 0; i < 12; i++) { const file = `${this.slug}/books/proof-${n}-${i}.epub`; await this.env.MEDIA.put(file, "not a real epub, invented for the proof"); insert("book", `proof-epub-${n}-${i}`, { title: `An Invented File ${i}`, file: `proof-${n}-${i}.epub` }); } return { seeded: true }; case "changes": case "acts": { const days = changeWindow(this.store).days + 30; const old = new Date(Date.now() - days * 86_400_000).toISOString(); for (let i = 0; i < 3_000; i++) { if (kind === "changes") sql.exec("INSERT INTO change (at, actor, via, table_id, record_id, kind, before, after, version) VALUES (?, NULL, 'update', 'note', ?, 'update', '{}', '{}', 1)", old, `proof-${i}`); else sql.exec("INSERT INTO acts (id, at, person_id, act, args, outcome) VALUES (?, ?, NULL, 'proof', '{}', 'ok')", `proof-${n}-${i}`, old); } return { seeded: true }; } case "prompts": { const old = new Date(Date.now() - (PROMPT_DAYS + 10) * 86_400_000).toISOString(); for (let i = 0; i < 1_500; i++) insert("prompt", `proof-prompt-${n}-${i}`, { ts: old, text: "invented" }, old); this.store.setMeta(PROMPTS_KEPT, null); return { seeded: true }; } case "sweeps": // The sweeps read only what is due; an invented account has little due, so the proof asks only that the job runs. return { seeded: true, why: "nothing invented: the job is asked to run and rest" }; case "calendar_sync": return { seeded: false, why: "a calendar pull needs a Google account, which an invented account has not" }; case "storage_count": for (const t of ["note", "prompt", "session"]) if (this.store.definitions("table").some((d) => d.id === t)) this.store.recountTable(t); return { seeded: true }; case "order_shadow": { // The file counts as past the index limit on this dev account (Store.indexTooBig reads the flag), the // account's shadows switched on, 20,000 binned notes, and a lookup asks for their shadow. this.store.setMeta(DEV_INDEX_TOO_BIG, "on"); // Shadows dropped and asked afresh, so each seed leaves a fill to do (the proof seeds once on, once off). this.ctx.storage.transactionSync(() => this.store.setShadows(false)); this.store.setShadows(true); if (!this.store.definitions("table").some((t) => t.id === "note")) return { seeded: false, why: "the account has no note table" }; sql.exec( `WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 20000) INSERT OR IGNORE INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) SELECT 'note', printf('proof-binned-${n}-%05d', x), json_object('title', 'binned ' || x, 'trashed_at', ?), NULL, ?, 0, ?, ? FROM c`, now, this.store.bump(), now, now, ); this.store.binnedLatest("note", "trashed_at", 5); await this.shadowsOwed(); return { seeded: true }; } case "send": { // Send's pass (src/send/send.ts alarmPass) on its own tables only: offers and sends past their two weeks for the // sweep, and two Keeps still copying, 20 small files R2 to R2 inside this account's own folder, more than one // pass's COPY.perPass. The peer is an invented number (555-01xx, kept for fiction) and every offer's `tell` is 0: // the pass tells no other object anything, and Send sends no mail and reaches nothing outside the bucket. const id = (what: string, i: number) => `proof-${what}-${n}-${crypto.randomUUID().slice(0, 8)}-${i}`; const peer = "+15550100199"; const old = Date.now() - send.EXPIRES_MS - 86_400_000; const older = Date.now() - 2 * send.EXPIRES_MS - 86_400_000; this.ctx.storage.transactionSync(() => { for (let i = 0; i < 5; i++) { sql.exec("INSERT INTO send_in (id, peer, peer_slug, payload, title, root_table, bytes, state, at, tell) VALUES (?, ?, 'proof-sender', '{}', '', 'note', 0, 'offered', ?, 0)", id("offer", i), peer, old); sql.exec("INSERT INTO send_in (id, peer, peer_slug, payload, title, root_table, bytes, state, at, tell) VALUES (?, ?, 'proof-sender', '{}', '', 'note', 0, 'kept', ?, 0)", id("kept", i), peer, older); const out = id("out", i); sql.exec("INSERT INTO send_out (id, peer, title, root_table, root_id, bytes, state, at) VALUES (?, ?, '', 'note', ?, 0, 'offered', ?)", out, peer, `proof-note-${i}`, old); sql.exec("INSERT INTO send_hold (send_id, key, folder) VALUES (?, ?, 0)", out, `${this.store.meta("database_id") ?? ""}/files/proof-held-${n}-${i}.bin`); } }); for (let k = 0; k < 2; k++) { const keep = id("keep", k); sql.exec("INSERT INTO send_in (id, peer, peer_slug, payload, title, root_table, bytes, state, at, tell) VALUES (?, ?, 'proof-sender', '{}', '', 'note', 320, 'keeping', ?, 0)", keep, peer, Date.now()); for (let i = 0; i < 10; i++) { const src = `${this.slug}/files/send-proof-src-${keep}/${i}.bin`; await this.env.MEDIA.put(src, "invented bytes for the proof"); sql.exec("INSERT INTO send_copy (send_id, src, dest, bytes) VALUES (?, ?, ?, 28)", keep, src, `${this.slug}/files/send-proof-kept-${keep}/${i}.bin`); } } return { seeded: true }; } } return { seeded: false, why: "no seed for this kind" }; } private stepHost(): stepJobs.StepHost { const stepOf = async (kind: StepKind): Promise => { // JOBS OUT C3: one bounded step of the storage counting, as the alarm's bounded jobs took it; with work left the // next run is asked for at their own pace (GENTLE_WAIT_MS, or BUSY_WAIT_MS while the object is in use). if (kind === "storage_count") { const { left, inUse } = this.storageCountStep(); if (left) await stepJobs.schedule(this.stepHost(), "storage_count", inUse ? BUSY_WAIT_MS : GENTLE_WAIT_MS, true); return false; } // JOBS OUT C1: one pass of the pull (PAGES_PER_PASS pages of Google at most), exactly as the alarm ran it. Its // carry-on keeps the pull's own cadence (CARRY_ON_MS with pages left, PULL_EVERY_MS once synced): the run ends, // and the alarm, woken at that time, has the watchdog ask for the next. if (kind === "calendar_sync") { if (!this.calendarPulling) await this.calendarPull(); return false; } // A step drops at most MEDIA_DROP_STEP folders; one R2 list and delete each. if (kind === "media_drop") return this.mediaDropStep(MEDIA_DROP_STEP); // One artwork pass: at most artwork.PER_PASS rows, each read by its LIMIT. if (kind === "artwork") return !!(await this.artworkPass())?.more; // One book files pass: at most bookFile.PER_PASS books, read by its LIMIT. if (kind === "book_files") return !!(await this.bookFilePass())?.more; // W1: one step of the change log's trim, at most GENTLE_TRIM entries, as the alarm's bounded job takes it. if (kind === "changes") return this.ctx.storage.transactionSync(() => trimChanges(this.store, new Date(), GENTLE_TRIM).more); // W2: one step of the act log's trim, at most GENTLE_ACTS lines. if (kind === "acts") return this.ctx.storage.transactionSync(() => trimActs(this.store, new Date(), GENTLE_ACTS).more); // W3: one step of the prompts' 30 days, at most GENTLE_PROMPTS rows by their index. if (kind === "prompts") return this.ctx.storage.transactionSync(() => keepPrompts(this.store, this.ctx.storage.sql, new Date(), GENTLE_PROMPTS).more); // W4: the timed sweeps, one step (each reads only what is due, by its index). if (kind === "sweeps") { this.runSweeps(); return false; } // JOBS OUT S1: one step of a shadow's fill, GENTLE_SHADOW_ROWS rows of its one table along the key. if (kind === "order_shadow") return this.ctx.storage.transactionSync(() => this.store.shadowStep(GENTLE_SHADOW_ROWS)); // One Send pass: the sweep (its own rows), at most send.COPY.perPass parts of a large Keep's copy, kept sends landing. if (kind === "send") return (await send.alarmPass(this.sendHost())).more; return false; }; return { sql: this.ctx.storage.sql, env: this.env, slug: this.store.meta("slug") ?? this.slug, now: () => Date.now(), on: (kind) => this.stepOn(kind), step: async (kind) => { // JOBS OUT PROOF: the steps each kind's job ran, and its work marked as the job's (not the object's own). this.jobSteps.set(kind, (this.jobSteps.get(kind) ?? 0) + 1); this.inJobStep = true; try { return await stepOf(kind); } finally { this.inJobStep = false; } }, owes: (kind) => { if (kind === "storage_count") return this.store.holdsDefinitions("table") && (this.store.countsPending() || this.store.measureOwed(new Date())); if (kind === "calendar_sync") return this.calendarDueIn(Date.now()) === 0; if (kind === "media_drop") return this.store.mediaToDrop().some((folder) => !send.holds(this.ctx.storage.sql, folder)); if (kind === "artwork") return !!this.artworkFetcher() && !!this.store.meta("database_id") && artwork.pending(this.artworkHost()); if (kind === "book_files") return !!this.store.meta("database_id") && bookFile.pending(this.bookFileHost()); // The sweeps have no cheap "is there work": they owe while their tables are held, and rest once a run finds none. if (kind === "changes" || kind === "acts") return this.store.holdsDefinitions("table"); if (kind === "prompts") return this.store.holdsDefinitions("table") && this.personal(); if (kind === "sweeps") return this.store.holdsDefinitions("table"); if (kind === "order_shadow") return this.store.shadowsFilling(); if (kind === "send") return send.owes(this.ctx.storage.sql); return false; }, restMs: (kind) => (SWEEPS.has(kind) ? ALARM_EVERY_MS : 0), // A window or a pending agent request past its end cannot wait out the sweeps' rest: an assistant would read longer. urgent: (kind) => { if (kind !== "sweeps") return false; const now = Date.now(); const window = this.unlocks.nextDue({ sql: this.ctx.storage.sql, store: this.store }); const pending = this.agents.nextDue({ sql: this.ctx.storage.sql }); return (window !== null && window <= now) || (pending !== null && pending <= now); }, }; } /** The message a step job's next run is put on the queue with, its credential minted now (the tests run it themselves). */ async stepJobMessage(kind: string): Promise { await this.frozenGate(); if (!stepJobs.isKind(kind)) refuse(404, "not_found", "no such job"); return stepJobs.message(this.stepHost(), kind, 0); } // ── admin: onboarding, import, export ────────────────────────────────── private async admin(request: Request, path: string): Promise { const admin = await this.requireAdmin(request, path); // SNAPSHOTS 1 (src/snapshots.ts): the admin token alone. if (path === "/snapshots" || path.startsWith("/snapshots/")) { if (!isAdminToken(this.env, bearer(request))) refuse(403, "admin_only", "snapshots take the admin token"); return await this.snapshotsAdmin(request, path.slice("/snapshots".length)); } allowlist.guard(this.ctx.storage.sql, request); const method = request.method; if (method === "GET" && path === "/feedback/file") { // A report's screenshot or log, for the admin token alone, never cached (ROUTES-AUDIT 15: they are not public). const key = new URL(request.url).searchParams.get("key") ?? ""; if (!admin) refuse(403, "admin_only", "a report's files take the admin token"); if (!key.startsWith(`${this.meta().slug}/feedback/`) || key.includes("..")) refuse(404, "not_found", "no such file"); const file = await this.env.PHOTOS.get(key); if (!file) refuse(404, "not_found", "no such file"); const headers = new Headers(); file.writeHttpMetadata(headers); headers.set("cache-control", "private, no-store"); return new Response(file.body, { headers }); } if (method === "PUT" && path === "/business") { const body = await readJson(request); // What names the database and what it reaches is the coordinator's: an owner of their own database must not point it at another's. const named = ["siblings", "kind", "database_id"].filter((k) => k in body); if (!admin && named.length) refuse(403, "admin_only", `${named.join(", ")} take the admin token`); this.ctx.storage.transactionSync(() => { if ("siblings" in body) { const list = body.siblings; const ok = Array.isArray(list) && list.every((s) => s && typeof s === "object" && ["id", "name", "slug"].every((k) => typeof (s as Record)[k] === "string")); if (!ok) refuse(400, "bad_siblings", "siblings is a list of { id, name, slug }"); this.store.setMeta("siblings", JSON.stringify(list)); } // The blind index's move one way (src/blind.ts): "on" starts it, a step an alarm; null leaves it. if ("blind_oneway" in body) { if (body.blind_oneway !== null && body.blind_oneway !== "on") refuse(400, "bad_request", "blind_oneway is \"on\", or null"); this.store.setMeta("blind_oneway", body.blind_oneway === null ? null : "on"); } // JOBS OUT 1: the account's mail fetched by a job beside the object ("on"), or on its own alarm (null). The coordinator's. if ("mail_jobs" in body) { if (!admin) refuse(403, "admin_only", "mail_jobs takes the admin token"); if (body.mail_jobs !== null && body.mail_jobs !== "on") refuse(400, "bad_request", "mail_jobs is \"on\", or null"); if (body.mail_jobs === "on") { const missing = mailJob.ready(this.env); if (missing) refuse(503, "jobs_unavailable", `mail_jobs cannot be on: ${missing}`); } this.store.setMeta(mailJob.SWITCH, body.mail_jobs === null ? null : "on"); // Either way every credential standing now opens nothing: on, each mailbox gets a new generation below. mailJob.drop(this.ctx.storage.sql, null); if (body.mail_jobs === "on") for (const a of mailFetch.accounts(this.ctx.storage.sql)) mailJob.renew(this.ctx.storage.sql, a.account); } // JOBS OUT M1: a step job per kind run beside the object ("on"), or by the object as before (null). The coordinator's. if ("jobs" in body) { if (!admin) refuse(403, "admin_only", "jobs takes the admin token"); const asked = body.jobs; if (!asked || typeof asked !== "object" || Array.isArray(asked)) refuse(400, "bad_request", "jobs is { : \"on\" | null }"); const kinds = Object.entries(asked as Record); for (const [kind, value] of kinds) { if (!stepJobs.isKind(kind)) refuse(400, "bad_request", `no job ${kind}`); if (value !== null && value !== "on") refuse(400, "bad_request", `jobs.${kind} is "on", or null`); } if (kinds.some(([, value]) => value === "on")) { const missing = stepJobs.ready(this.env); if (missing) refuse(503, "jobs_unavailable", `a job cannot be on: ${missing}`); } for (const [kind, value] of kinds as [StepKind, "on" | null][]) { this.store.setMeta(stepJobs.switchKey(kind), value); // Either way every credential standing now opens nothing: on, a new generation. stepJobs.drop(this.ctx.storage.sql, kind); if (value === "on") stepJobs.renew(this.ctx.storage.sql, kind); } } // The change log's window, per account (src/changes.ts): change_bytes is its size budget, none until set. for (const key of ["change_days", "change_rows", "change_bytes"] as const) { if (!(key in body)) continue; const value = body[key]; if (value !== null && !(typeof value === "number" && Number.isInteger(value) && value > 0)) refuse(400, "bad_request", `${key} is a whole number above 0, or null for the default`); this.store.setMeta(key, value === null ? null : String(value)); } for (const key of ["name", "currency", "timezone", "upi_id", "owner_phone", "kind", "database_id"] as const) { if (key in body) { const value = body[key]; if (key === "kind" && value !== "business" && value !== "personal") refuse(400, "bad_kind", "kind is business or personal"); if (key === "database_id" && (typeof value !== "string" || !/^[0-9a-f-]{36}$/.test(value))) refuse(400, "bad_database_id", "database_id is the database's uuid"); if (key === "owner_phone" && typeof value === "string") { const phone = normalizePhone(value); if (!phone) refuse(400, "bad_phone", "owner_phone must start with +"); this.store.setMeta(key, phone); } else this.store.setMeta(key, value === null ? null : String(value)); } } this.store.setMeta("slug", this.slug); this.store.bump(); }); // The change log's window or budget set here starts now, not at the next hourly pass (the dev proof, 23 Nov 2026: // the switch set at 02:01 on an object whose alarm stood at 02:56 trimmed nothing for 55 minutes). The blind // index's move keeps its own pace from the hourly pass. if (["change_days", "change_rows", "change_bytes"].some((k) => k in body)) await this.ctx.storage.setAlarm(Date.now()); // The mail switch thrown: on, each mailbox's first run goes on the queue now; off, the alarm's fetcher reads at once. if ("mail_jobs" in body) { if (this.mailJobsOn()) { // JOBS OUT 2 (L1): this object's own fetcher lets go first. Its IDLE sockets close now (the watch ends at // once) and a pass under way stops before its next message, so the job never reads beside it. const fetchHost = this.fetchHost(); for (const a of mailFetch.accounts(this.ctx.storage.sql)) fetchHost.close(a.account); for (const a of mailFetch.accounts(this.ctx.storage.sql)) await mailJob.schedule(this.jobHost(), a.account, 0); } else await this.ctx.storage.setAlarm(Date.now()); } return json({ business: this.meta() }); } if (method === "PUT" && path === "/definitions") { const body = await readJson(request); const tools = Array.isArray(body.tools) ? (body.tools as Record[]) : null; const tables = Array.isArray(body.tables) ? (body.tables as Record[]) : null; const flavour = body.flavour !== undefined ? object(body.flavour, "flavour") : null; if (!tools || !tables) refuse(400, "bad_request", "definitions need tools and tables arrays"); for (const t of tables) { const unread = tableProblem(t); if (unread) refuse(400, "bad_definition", unread); } for (const d of [...tools, ...tables]) { const problem = faceProblem(d); if (problem) refuse(400, "bad_definition", problem); } const laid = new Map(tables.map((t) => parseTable(t)).filter((t): t is TableDef => t !== null).map((t) => [t.id, t])); for (const tool of tools) { const problem = toolSealProblem(tool, (id) => laid.get(id)); if (problem) refuse(400, "bad_definition", problem); } this.install(tools, tables, flavour); return json({ ok: true, tools: tools.length, tables: this.store.definitions("table").length, version: this.store.version() }); } if (method === "POST" && path === "/definitions/tables") { // Some tables' definitions, each replacing the one with its id and leaving the rest: an import brings the owner's own made tables this way. const body = await readJson(request); const tables = Array.isArray(body.tables) ? (body.tables as Record[]) : null; if (!tables) refuse(400, "bad_request", "definitions/tables needs a tables array"); for (const t of tables) { const unread = tableProblem(t); if (unread) refuse(400, "bad_definition", unread); } for (const t of tables) { const problem = faceProblem(t); if (problem) refuse(400, "bad_definition", problem); } const sealing = sealedSetProblem(this.store.definitions("table"), tables, this.store.definitions("tool")); if (sealing) refuse(400, "bad_definition", sealing); let changed = 0; this.ctx.storage.transactionSync(() => { const links = this.definitions().linkColumns(); changed = this.store.mergeDefinitions("table", tables); if (!changed) return; this.definitions(); this.store.relink(links); this.store.bump(); }); return json({ ok: true, changed, tables: this.store.definitions("table").length, version: this.store.version() }); } if (method === "POST" && (path === "/definitions/tools" || path === "/definitions/boards" || path === "/definitions/themes")) { // Some tools' (boards', themes') definitions, each replacing the one with its id and leaving the rest — the package's own tool, every table: an import brings the owner's tools, boards and themes this way. const kind = path === "/definitions/tools" ? "tool" : path === "/definitions/boards" ? "board" : "theme"; const body = await readJson(request); const docs = Array.isArray(body[`${kind}s`]) ? (body[`${kind}s`] as Record[]) : null; if (!docs) refuse(400, "bad_request", `definitions/${kind}s needs a ${kind}s array`); const held = this.definitions(); for (const doc of docs) { const problem = definitionProblem(kind, doc) ?? (kind === "tool" ? toolSealProblem(doc, (id) => held.table(id)) : null); if (problem) refuse(400, "bad_definition", problem); } let changed = 0; this.ctx.storage.transactionSync(() => { changed = this.store.mergeDefinitions(kind, docs); if (changed) this.store.bump(); }); return json({ ok: true, changed, [`${kind}s`]: this.store.definitions(kind).length, version: this.store.version() }); } if (method === "POST" && path === "/media/recount") { // The media an object held before the count began (the owner's), summed from the bucket once. if (!this.personal()) refuse(404, "not_personal", "media live in the personal database"); const bytes = await mediaBytes(this.env, `${this.meta().slug}/`); this.store.setMeta(MEDIA_BYTES, String(bytes)); return json({ media_bytes: bytes, cap: this.mediaCap() }); } if (method === "POST" && (path === "/account/hold" || path === "/account/erase-now")) return this.deleteAdmin(request, `/v1/admin${path}`); // ALARM KICK (coordinator, 28 Nov 2026: the owner's alarm stood six hours in the past and nothing fired): the admin // token sets this object's alarm 5 s out, whatever stands, and answers getAlarm() before and after. if (method === "POST" && path === "/alarm/kick") { if (!admin) refuse(403, "admin_only", "this takes the admin token"); const iso = (at: number | null) => (at === null ? null : new Date(at).toISOString()); const before = await this.ctx.storage.getAlarm(); await this.ctx.storage.setAlarm(Date.now() + 5_000); const after = await this.ctx.storage.getAlarm(); console.log(`cottondb: alarm kicked ${this.slug}: was ${iso(before) ?? "none"}, now ${iso(after)}`); return json({ before: iso(before), after: iso(after), now: new Date().toISOString() }); } // ORDER INDEX: the account's switch for order shadows (src/order_shadow.ts), the admin token alone; off drops them. if (path === "/order-shadow") { // The admin token; on the dev and test Workers the account's own owner too, so an invented account's proof // runs without the admin token (ORDER INDEX on dev, 24 Nov 2026). const asking = await this.caller(request); const devOwner = devWorker(this.env) && asking.role === "owner" && !asking.allow; if (!admin && !devOwner) refuse(403, "admin_only", "this takes the admin token"); if (method === "POST") { const { on } = await readJson(request); if (typeof on !== "boolean") refuse(400, "bad_request", "on is true or false"); // One transaction (ORDER GO-LIVE, 25 Nov 2026): off drops tables and triggers, and SQLite refuses a DROP while any // read on the object is open (SQLITE_LOCKED, as Keep met it). Half done, the list would still name a shadow // whose table had gone and a pass would read it; so it is all or nothing, and the same call again finishes it. this.ctx.storage.transactionSync(() => this.store.setShadows(on)); if (on) await this.carryOn(); } // READ COST 3: which object answered, whether its file is past the index limit, and what each lookup last did here // (the instance's memory: empty after a deploy until a lookup runs), so a shadow that is never asked says why. return json({ ...this.store.shadowProgress(), slug: this.store.meta("slug"), database_id: this.store.meta("database_id"), file_bytes: this.ctx.storage.sql.databaseSize, over_index_limit: this.store.indexTooBig(), counts_ready: this.store.liveCount("session") !== null, lookups: [...this.store.lookupsSaid].map(([name, l]) => ({ name, ...l })), // READ COST 4: whether the alarm comes and fills: when it is set for, this instance's last alarm (what it ran, a // throw), an alarm under way or reset (its mark), the object in use, the jobs owed, and the last shadow step. alarm_at: await this.ctx.storage.getAlarm().then((at) => (at === null ? null : new Date(at).toISOString())), alarm_last: this.alarmLast.began ? this.alarmLast : null, alarm_running: this.store.meta(ALARM_RUNNING), in_use: this.inUse(), jobs_owed: this.gentleOwed, shadow_next: this.wants.has("shadow") ? new Date(this.wants.get("shadow")!).toISOString() : null, shadow_last: this.shadowLast, }); } if (method === "POST" && path === "/space/mode") { // The admin token alone (ROUTES-AUDIT 18): an owner token minted on the account itself must not give it its space mode. if (!admin) refuse(403, "admin_only", "this takes the admin token"); // This account's own space mode (SPACE.md), apart from the Worker's switch; null follows the switch again. if (!this.personal()) refuse(404, "not_personal", "space lives in the personal database"); const { mode } = await readJson(request); if (mode !== null && mode !== "off" && mode !== "count" && mode !== "on") refuse(400, "bad_request", "mode is off, count, on, or null for the Worker's switch"); this.store.setMeta(space.META.mode, mode); return json(this.spaceAnswer()); } if (method === "POST" && path === "/space/bought") { // The admin token alone (ROUTES-AUDIT 18): an owner token minted on the account itself must not give it paid space. if (!admin) refuse(403, "admin_only", "this takes the admin token"); // The seam for paid space (SPACE.md): a plan's size in bytes, at most 2 TB; null takes it away. if (!this.personal()) refuse(404, "not_personal", "space lives in the personal database"); const { bytes } = await readJson(request); if (bytes !== null && !(typeof bytes === "number" && Number.isSafeInteger(bytes) && bytes >= 0 && bytes <= space.MOST_BYTES)) refuse(400, "bad_request", `bytes is a whole number from 0 to ${space.MOST_BYTES}, or null`); this.store.setMeta(space.META.bought, bytes === null ? null : String(bytes)); return json(this.spaceAnswer()); } if (method === "POST" && path === "/media/cap") { // The admin token alone (ROUTES-AUDIT 18): an owner token minted on the account itself must not give it its media cap. if (!admin) refuse(403, "admin_only", "this takes the admin token"); // This account's own media limit; null puts it back on the default. if (!this.personal()) refuse(404, "not_personal", "media live in the personal database"); const { bytes } = await readJson(request); if (bytes !== null && !(typeof bytes === "number" && Number.isSafeInteger(bytes) && bytes >= this.caps.media && bytes <= MEDIA_CAP_MOST_BYTES)) { refuse(400, "bad_request", `bytes is a whole number from ${this.caps.media} to ${MEDIA_CAP_MOST_BYTES}, or null for the default`); } this.store.setMeta(MEDIA_CAP, bytes === null ? null : String(bytes)); return json({ media_bytes: Number(this.store.meta(MEDIA_BYTES) ?? "0"), cap: this.mediaCap(), default_cap: this.caps.media }); } if (method === "GET" && path === "/groups/duplicates") { // The same-name tag groups of notes, counted by their blind tokens; the merge is the owner's phone's (notes.merge_tags), which holds the key. if (!this.personal()) refuse(404, "not_personal", "notes live in the personal database"); return json(this.store.duplicateNoteGroups()); } if (method === "POST" && path === "/photos/prune") { // Bins the photos whose original the bucket lacks, one key folder, one bounded page a call (src/photo_prune.ts). if (!this.personal()) refuse(404, "not_personal", "photos live in the personal database"); const defs = this.definitions(); const now = new Date().toISOString(); const answer = await prunePhotos( { store: this.store, bucket: this.env.MEDIA, database: this.databaseId(), slug: this.meta().slug, now, write: (fn) => this.ctx.storage.transactionSync(() => { const outcome = new Outcome_(); fn(this.engine(defs), this.store.bump(), outcome); }), }, await readJson(request), ); if (answer.binned) console.log(`cottondb: photos prune ${this.meta().slug}: binned ${answer.binned} of folder ${answer.folder}, ${answer.kept_in_use} kept in use`); return json(answer); } if (method === "POST" && path === "/erase") { // Rows erased for good, a bounded piece a call (src/erase.ts); without confirm, only what would go. The admin token // alone, token scopes on or off (SERVER 27 H2): an owner token never erases for good, dry run or not. if (!admin) refuse(403, "admin_only", "erasing rows for good takes the admin token"); if (!this.personal()) refuse(404, "not_personal", "erasing rows is for a personal database"); const body = await readJson(request.clone()); if (this.tokenScopesOn() && body.confirm) await this.gateWipe(request, "erase", false); const answer = await runErase(this.eraseHost(), body); console.log(`cottondb: erase ${this.meta().slug} ${answer.set} ${answer.erased ? "confirmed" : "dry"} call ${answer.calls}: ${answer.phase}`); return json(answer); } if (method === "POST" && path === "/retired/erase") { // ERASES, for good, every row, tombstone, change-log entry, link, act line and R2 file of the 68 tables of TABLE // DROP 1 (src/retired.ts TABLE_DROP_1) and nothing else, a bounded piece a call: ask again with the same body while // `more`. Without confirm, a dry run: each table's rows and files. A confirmed run begins only when `export` (the // export's `counts`) agrees with every one of the 68 tables' live rows; phones are told as for any erased table. if (!admin) refuse(403, "admin_only", "erasing rows for good takes the admin token"); if (!this.personal()) refuse(404, "not_personal", "the retired tables live in the personal database"); const body = await readJson(request.clone()); const confirm = body.confirm === "erase"; if (this.tokenScopesOn() && confirm) await this.gateWipe(request, "erase", false); const differs = exportDiffers(this.ctx.storage.sql, body.export); if (confirm && !tableDropUnderWay(this.store)) { if (differs === null) refuse(400, "export_needed", "a confirmed erase takes export: the counts of the export taken before it"); const off = Object.entries(differs); if (off.length) refuse(409, "export_mismatch", `the export does not match ${off.length} table(s): ${off.map(([t, d]) => `${t} exported ${d.exported}, holds ${d.now}`).join("; ")}`); } const answer = await runErase(this.eraseHost(), { set: "table_drop_1", ...(confirm ? { confirm: "erase" } : {}) }); console.log(`cottondb: retired erase ${this.meta().slug} ${answer.erased ? "confirmed" : "dry"} call ${answer.calls}: ${answer.phase}`); return json({ ...answer, export: differs }); } if (method === "POST" && path === "/circle/seal") { // PEOPLE-DESIGN b.4 step C: the Circle's rows written before they were sealed, sealed now to the arrival key, at // most `most` (default 200) a call; with drop, a sealed row also loses its clear number and name. Without confirm // "seal" it only counts. The admin token alone: the coordinator runs it on live, nothing else calls it. if (!admin) refuse(403, "admin_only", "this takes the admin token"); const body = await readJson(request); const most = body.most === undefined ? 200 : Number(body.most); if (!Number.isInteger(most) || most < 1 || most > 2_000) refuse(400, "bad_request", "most is a whole number, 1 to 2000"); chat.ready(this.ctx.storage.sql); return json(await chat.convertCircle(this.chatHost(), { apply: body.confirm === "seal", drop: body.drop === true, most })); } if (method === "POST" && path === "/circle/sealed-only") { // b.4 step B's switch for this account alone (the Worker's is env CIRCLE_SEALED_ONLY): on, a new Circle row keeps no // clear number once sealed. The admin token alone. if (!admin) refuse(403, "admin_only", "this takes the admin token"); const { on } = await readJson(request); if (typeof on !== "boolean") refuse(400, "bad_request", "on: true or false"); this.store.setMeta(chat.CIRCLE_SEALED_ONLY, on ? "on" : "off"); return json({ on }); } if (method === "POST" && path === "/change-log/thin-machine") { // ERASES the bodies of change-log entries machines wrote before they kept only that they happened (src/changes.ts // MACHINE_WRITERS: progress ticks, fetch state, seals, jobs, imports …); the entries stay, and no record is // touched. Without confirm "thin" it only counts, writer by writer; with it, at most `most` (default 2,000) a call. // The admin token alone (NEXT-ADMIN-KEYS part 1): the owner's log is thinned for him by the coordinator; no phone, // Mac or tool calls this, and an assistant's owner token never erased its bodies. const body = await readJson(request); const most = body.most === undefined ? 2_000 : Number(body.most); if (!Number.isInteger(most) || most < 1 || most > 10_000) refuse(400, "bad_request", "most is a whole number, 1 to 10000"); const apply = body.confirm === "thin"; return json(this.ctx.storage.transactionSync(() => this.store.thinMachineChanges(Object.keys(MACHINE_WRITERS), apply, most))); } if (method === "POST" && path === "/import") return this.import(await readJson(request)); if (method === "POST" && path === "/reset") { // The admin token (SERVER 27 H2): on live an owner token never wipes the database. On the dev and test Workers the // account's own owner token too, as order-shadow's, so a builder's dev-seed --reset runs without the admin token. if (!admin && !(resetTakesOwner(this.env) && (await this.caller(request)).role === "owner")) refuse(403, "admin_only", "a reset takes the admin token"); // Token scopes on: never on the live Worker, and only with `confirm` naming this database's id. if (this.tokenScopesOn()) await this.gateWipe(request, "reset", true); let version = 0; this.ctx.storage.transactionSync(() => { this.store.wipeRecords(); version = this.store.bump(); }); return json({ ok: true, version }); } // DEV AND TEST ONLY (the undo-history proof, coordinator for the owner, 23 Nov 2026): plants change-log entries the // way the log held them before 9224954f16, a sealed body before and after, at times spread back over `days`, on // the given records, so the dev Worker can hold an invented account with the owner's undo history (about 82,000 // entries, 2.4 GB) and the per-account trim can be run on it. It adds log entries only: no record is written, and // it erases nothing. Any other Worker answers 404, as if the route were not there. At most 2,000 entries a call. // DEV AND TEST ONLY (ORDER INDEX on dev, coordinator, 24 Nov 2026): plants invented rows of one table, as many as // the owner's object holds, so the dev Worker can hold an account the size of his (3.7 GB) and the order shadows be // filled there by its own alarms. Each row is shaped as a sealed row (its date and group columns clear, a random // sealed block of `bytes`), under its own version, ids `
-`. The row counts are recounted after (by the // alarm, as on any object). Any other Worker answers 404, as if the route were not there. At most 20,000 rows a call. // JOBS OUT PROOF (scripts/jobs-out-proof.ts): each step kind's switch, its run, what is left of its work, the // steps its job ran and what the alarm did of it, since this instance started. The admin token. if (method === "GET" && path === "/jobs") { if (!admin) refuse(403, "admin_only", "this takes the admin token"); return json(this.jobsView()); } // JOBS OUT PROOF, the dev Worker only: an invented personal account made here as a new number's is (provision, the // whole personal kit), under an invented number; one already made is left as it is. if (method === "POST" && path === "/dev/invent-personal") { if (!devWorker(this.env)) refuse(404, "not_found", "no such route"); if (!admin) refuse(403, "admin_only", "this takes the admin token"); if (!this.store.holdsDefinitions("table")) { const phone = `+1555010${String(Math.floor(Math.random() * 10_000)).padStart(4, "0")}`; await this.provision({ databaseId: crypto.randomUUID(), slug: this.slug, phone }); } return json({ slug: this.slug, personal: this.personal(), tables: this.store.definitions("table").length }); } // JOBS OUT PROOF, the dev Worker only: invented work for one step kind, laid where that kind's work reads it. if (method === "POST" && path === "/dev/jobs-seed") { if (!devWorker(this.env)) refuse(404, "not_found", "no such route"); if (!admin) refuse(403, "admin_only", "this takes the admin token"); const { kind } = await readJson(request); if (typeof kind !== "string" || !stepJobs.isKind(kind)) refuse(400, "bad_request", "kind names a step job"); const seeded = await this.seedJob(kind); // Work appeared: with the kind on, a run is asked for (as a request that made such work does); off, the alarm soon. if (this.stepOn(kind)) await stepJobs.kick(this.stepHost(), kind); await this.carryOn(); return json({ kind, ...seeded, ...this.jobsView().kinds.find((k) => k.kind === kind) }); } if (method === "POST" && path === "/dev/plant-rows") { if (!devWorker(this.env)) refuse(404, "not_found", "no such route"); const body = await readJson(request); const table = typeof body.table === "string" && /^[a-z_][a-z0-9_]*$/.test(body.table) ? body.table : ""; const from = Number(body.from ?? 0); const count = Number(body.count); const bytes = Number(body.bytes); const dated = typeof body.dated === "string" && /^[a-z_][a-z0-9_]*$/.test(body.dated) ? body.dated : null; const group = body.group && typeof body.group === "object" ? (body.group as { column?: unknown; prefix?: unknown; of?: unknown }) : null; const groupColumn = group && typeof group.column === "string" && /^[a-z_][a-z0-9_]*$/.test(group.column) ? group.column : null; const groupPrefix = group && typeof group.prefix === "string" && /^[a-z0-9_-]+$/.test(group.prefix) ? group.prefix : null; const groupOf = Number(group?.of ?? 0); if (!table || !this.definitions().table(table)) refuse(400, "bad_request", "table names a table of the account"); if (!Number.isInteger(from) || from < 0 || !Number.isInteger(count) || count < 1 || count > 20_000) refuse(400, "bad_request", "from (0 or more) and count (1 to 20000) are needed"); if (!Number.isInteger(bytes) || bytes < 16 || bytes > 70_000) refuse(400, "bad_request", "bytes (16 to 70000) is needed"); if (group && (!groupColumn || !groupPrefix || !Number.isInteger(groupOf) || groupOf < 1)) refuse(400, "bad_request", "group is { column, prefix, of }"); const sql = this.ctx.storage.sql; const planted = this.ctx.storage.transactionSync(() => { const base = this.store.version(); const pairs = [ ...(dated ? [`'${dated}', strftime('%Y-%m-%dT%H:%M:%SZ', '2007-01-01', '+' || (x * 7) || ' minutes')`] : []), ...(groupColumn ? [`'${groupColumn}', printf('${groupPrefix}%08d', 1 + x % ${groupOf})`] : []), `'sealed_enc', 's1:' || hex(randomblob(${Math.ceil(bytes / 2)}))`, `'dek_enc', 'd1:' || hex(randomblob(30))`, `'seal_v', 1`, ]; sql.exec( `WITH RECURSIVE c(x) AS (SELECT ? UNION ALL SELECT x + 1 FROM c WHERE x < ?) INSERT OR IGNORE INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) SELECT ?, printf('%s-%08d', ?, x), json_object(${pairs.join(", ")}), NULL, ? + x - ?, 0, '2025-01-01T00:00:00Z', '2025-06-01T00:00:00Z' FROM c`, from + 1, from + count, table, table, base + 1, from + 1, ); this.store.setMeta("version", String(base + count)); // That table counted again by the alarm (Store.carryCounts), as when a kit dates a table anew; the rest stand. this.store.recountTable(table); return count; }); await this.carryOn(); return json({ planted, bytes: sql.databaseSize }); } if (method === "POST" && path === "/dev/plant-history") { if (!devWorker(this.env)) refuse(404, "not_found", "no such route"); const body = await readJson(request); const ids = Array.isArray(body.records) ? body.records.filter((x): x is string => typeof x === "string") : []; const table = typeof body.table === "string" ? body.table : ""; const count = Number(body.entries); const chars = Number(body.chars); const days = Number(body.days); const from = Number(body.from ?? 0); const of = Number(body.of ?? count); if (!table || !ids.length || !Number.isInteger(count) || count < 1 || count > 2_000) refuse(400, "bad_request", "table, records and entries (1 to 2000) are needed"); if (!Number.isInteger(chars) || chars < 2 || chars > 40_000 || !(days > 0 && days <= 400)) refuse(400, "bad_request", "chars (2 to 40000) and days (up to 400) are needed"); if (!Number.isInteger(from) || !Number.isInteger(of) || from < 0 || of < from + count) refuse(400, "bad_request", "from and of place this call in the whole run"); const now = Date.now(); this.ctx.storage.transactionSync(() => { for (let i = 0; i < count; i++) { // Spread evenly back over `days`, oldest first across the whole run (from/of), as a long-used account's log. const at = new Date(now - days * 86_400_000 * (1 - (from + i + 1) / of)).toISOString(); const half = Math.floor(chars / 2); this.ctx.storage.sql.exec( `INSERT INTO change (at, actor, via, table_id, record_id, kind, before, after, version) VALUES (?, NULL, 'update', ?, ?, 'update', json_object('_sealed', 'v1.' || substr(hex(randomblob(?)), 1, ?)), json_object('_sealed', 'v1.' || substr(hex(randomblob(?)), 1, ?)), 1)`, at, table, ids[(from + i) % ids.length], Math.ceil(half / 2), half, Math.ceil(half / 2), half, ); } }); return json({ planted: count }); } if (method === "POST" && path === "/service-tokens/rekey") { if (!admin) refuse(403, "admin_only", "the rekey takes the admin token"); return json(await this.rekeyServiceTokens()); } if (method === "GET" && path === "/row-counts") { // How far the row counts' recount stands (src/store.ts): table names and numbers from its plan, never a row. this.definitions(); return json(this.store.countsProgress()); } if (path === "/mail-all") { // MAIL ALL ON PHONE for this account alone (coordinator, 24 Nov 2026; MAIL.md "All mail on the phone"): on, every // sync answer says features ["mail_all"], and a Comms phone keeps all mail from its next launch. The admin token's. if (!admin) refuse(403, "admin_only", "the mail-all switch takes the admin token"); if (method === "GET") return json({ on: this.store.meta(MAIL_ALL_META) !== null }); if (method !== "POST") refuse(405, "method", "GET or POST"); const body = await readJson(request); if (typeof body.on !== "boolean") refuse(400, "bad_request", "mail-all takes { on: true | false }"); this.store.setMeta(MAIL_ALL_META, body.on ? new Date().toISOString() : null); return json({ on: body.on }); } if (path === "/token-scopes") { // The token-scopes switch (src/token_scopes.ts), the admin token's alone, on or off: GET reads the gate, POST throws it. if (!admin) refuse(403, "admin_only", "the token-scopes switch takes the admin token"); if (!this.personal()) refuse(404, "not_personal", "tokens live in the personal database"); const params = new URL(request.url).searchParams; const sinceOf = (v: unknown): string | null => { if (v === undefined || v === null || v === "") return null; if (typeof v !== "string" || Number.isNaN(Date.parse(v))) refuse(400, "bad_request", "since is an ISO time: only the routes seen from then on count"); return new Date(Date.parse(v)).toISOString(); }; if (method === "GET") return json(this.tokenHolders(new Set((params.get("excuse") ?? "").split(",").filter(Boolean)), sinceOf(params.get("since")))); if (method !== "POST") refuse(405, "method", "GET or POST"); const body = await readJson(request); if (typeof body.on !== "boolean") refuse(400, "bad_request", "token-scopes takes { on: true | false, excuse?: [token ids], since?: ISO time }"); if (!body.on) { this.store.setMeta(tokenScopes.META, null); return json({ on: null }); } const excuse = new Set(Array.isArray(body.excuse) ? body.excuse.map(String) : []); const gate = this.tokenHolders(excuse, sinceOf(body.since)); if (!gate.ready) { const lose = gate.holders.filter((h) => h.verdict === "would_lose"); refuse(409, "token_scopes_not_ready", `not switched: ${lose.map((h) => `${h.name || h.token_id} ${h.says}`).join("; ")}. Excuse a token by id once nothing it does needs that route.`); } const on: tokenScopes.Switch = gate.on ?? { on_at: new Date().toISOString(), by: "admin" }; this.store.setMeta(tokenScopes.META, JSON.stringify(on)); return json({ on, holders: gate.holders }); } if (method === "GET" && path === "/memory-lock") { // Gate 1, read only: the tokens in use, whether each can open memory once sealed, and where the lock stands (src/memory_lock.ts). if (!this.personal()) refuse(404, "not_personal", "memory lives in the personal database"); const excuse = new Set((new URL(request.url).searchParams.get("excuse") ?? "").split(",").filter(Boolean)); return json({ lock: memoryLock.readLock(this.store.meta(memoryLock.META)), ...this.memoryReaders(excuse) }); } if (method === "POST" && path === "/memory-lock") { // The switch (src/memory_lock.ts). On: refused unless gate 1 is ready. Off: refused once sealing has begun. if (!this.personal()) refuse(404, "not_personal", "memory lives in the personal database"); if (!this.agentGrantOn()) refuse(409, "agent_grant_off", "Your Claude's standing grant is not on for this database: no assistant could open a sealed memory"); const body = await readJson(request); if (typeof body.on !== "boolean") refuse(400, "bad_request", "memory-lock takes { on: true | false, excuse?: [token ids] }"); const held = memoryLock.readLock(this.store.meta(memoryLock.META)); if (body.on === false) { if (!held) return json({ lock: null, state: "off" }); if (this.memoryLockState() === "sealing" || this.memoryLockState() === "sealed") refuse(409, "memory_lock_sealing", "memory is being sealed or is sealed: no device can open it back to clear yet, so the lock stays on"); this.ctx.storage.transactionSync(() => { this.store.setMeta(memoryLock.META, null); this.store.bump(); }); return json({ lock: null, state: "off" }); } if (held) return json({ lock: held, state: this.memoryLockState() }); const excuse = new Set(Array.isArray(body.excuse) ? body.excuse.filter((x): x is string => typeof x === "string") : []); const gate = this.memoryReaders(excuse); if (!gate.ready) { const left = gate.readers.filter((r) => r.verdict === "needs_allow" || r.verdict === "needs_new_token"); // A member with no grant gets its one card now, so the owner can Allow it on the phone: a hook token never reads a sealed table by itself. const sealed = [...new Set([...this.definitions().tables.values()].filter((t) => !!t.seal).map((t) => t.id).concat(memoryLock.MEMORY))]; let filed = 0; for (const r of left.filter((r) => r.member)) { const hash = this.store.get(TOKEN_TABLE, r.token_id)?.data.token_hash; const memberId = typeof hash === "string" ? this.memberOfHash(hash) : null; if (!memberId || this.agents.grantOf(this.store, memberId)) continue; try { if (this.agents.request(this.windowHost(), { memberId }, r.name, r.token_id, sealed, sealed, Date.now())) filed++; } catch (error) { console.warn(`memory lock: no card filed for ${r.token_id}: ${error instanceof Error ? error.message : String(error)}`); } } const cards = filed ? ` ${filed === 1 ? "Its card is" : `${filed} cards are`} on the owner's phone to Allow (Account › Assistants).` : ""; refuse(409, "memory_lock_not_ready", `${left.length} token${left.length === 1 ? "" : "s"} in use could not open a sealed memory: ${left.map((r) => `${r.name || r.token_id} (${r.says})`).join("; ")}.${cards}`); } const lock: memoryLock.Lock = { on_at: new Date().toISOString(), by: admin ? "admin" : "owner" }; this.ctx.storage.transactionSync(() => { this.store.setMeta(memoryLock.META, JSON.stringify(lock)); // The definitions every device reads change (memory carries its seal block): a new version, so each pulls them. this.store.bump(); }); return json({ lock, state: this.memoryLockState() }); } if (method === "GET" && path === "/open-tables-lock") { // Gate 1, read only: the tokens in use, whether each can open the session tables once sealed (src/open_tables_lock.ts). if (!this.personal()) refuse(404, "not_personal", "the session tables live in the personal database"); const excuse = new Set((new URL(request.url).searchParams.get("excuse") ?? "").split(",").filter(Boolean)); return json({ lock: openTablesLock.readLock(this.store.meta(openTablesLock.META)), ...this.openTablesReaders(excuse) }); } if (method === "POST" && path === "/open-tables-lock") { // The switch (src/open_tables_lock.ts), as memory's. On: refused unless gate 1 is ready. Off: refused once sealing has begun. if (!this.personal()) refuse(404, "not_personal", "the session tables live in the personal database"); if (!this.agentGrantOn()) refuse(409, "agent_grant_off", "Your Claude's standing grant is not on for this database: no assistant could open a sealed session"); const body = await readJson(request); if (typeof body.on !== "boolean") refuse(400, "bad_request", "open-tables-lock takes { on: true | false, excuse?: [token ids] }"); const held = openTablesLock.readLock(this.store.meta(openTablesLock.META)); if (body.on === false) { if (!held) return json({ lock: null, state: "off" }); if (this.openTablesState() === "sealing" || this.openTablesState() === "sealed") refuse(409, "open_tables_lock_sealing", "the session tables are being sealed or are sealed: no device can open them back to clear yet, so the lock stays on"); this.ctx.storage.transactionSync(() => { this.store.setMeta(openTablesLock.META, null); this.store.bump(); }); return json({ lock: null, state: "off" }); } if (held) return json({ lock: held, state: this.openTablesState() }); const excuse = new Set(Array.isArray(body.excuse) ? body.excuse.filter((x): x is string => typeof x === "string") : []); const gate = this.openTablesReaders(excuse); if (!gate.ready) { const left = gate.readers.filter((r) => r.verdict === "needs_allow" || r.verdict === "needs_new_token"); // A member with no grant gets its one card now, naming the locked tables, so the owner's one Allow hands their keys. const sealed = [...new Set([...this.definitions().tables.values()].filter((t) => !!t.seal).map((t) => t.id).concat(openTablesLock.TABLES))]; let filed = 0; for (const r of left.filter((r) => r.member)) { const hash = this.store.get(TOKEN_TABLE, r.token_id)?.data.token_hash; const memberId = typeof hash === "string" ? this.memberOfHash(hash) : null; if (!memberId || this.agents.grantOf(this.store, memberId)) continue; try { if (this.agents.request(this.windowHost(), { memberId }, r.name, r.token_id, sealed, sealed, Date.now())) filed++; } catch (error) { console.warn(`open tables lock: no card filed for ${r.token_id}: ${error instanceof Error ? error.message : String(error)}`); } } const cards = filed ? ` ${filed === 1 ? "Its card is" : `${filed} cards are`} on the owner's phone to Allow (Account › Assistants).` : ""; refuse(409, "open_tables_lock_not_ready", `${left.length} token${left.length === 1 ? "" : "s"} in use could not open a sealed session table: ${left.map((r) => `${r.name || r.token_id} (${r.says})`).join("; ")}.${cards}`); } const lock: openTablesLock.Lock = { on_at: new Date().toISOString(), by: admin ? "admin" : "owner" }; this.ctx.storage.transactionSync(() => { this.store.setMeta(openTablesLock.META, JSON.stringify(lock)); // The definitions every device reads change (each table carries its seal block): a new version, so each pulls them. this.store.bump(); }); return json({ lock, state: this.openTablesState() }); } if (path === "/secret-lock" && (method === "GET" || method === "POST")) { // The passwords' own switch (LOCK TABLES 2): secret sealed alone, no gate (no grant carries its key). Off is // refused once a row is sealed: no device opens a sealed password back to clear. if (!this.personal()) refuse(404, "not_personal", "the passwords live in the personal database"); const counts = () => ({ open_rows: Number(this.ctx.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE table_id = 'secret' AND deleted = 0 AND json_extract(data, '$.sealed_enc') IS NULL").one().n), sealed_rows: Number(this.ctx.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE table_id = 'secret' AND deleted = 0 AND json_extract(data, '$.sealed_enc') IS NOT NULL").one().n), }); const held = openTablesLock.readLock(this.store.meta(openTablesLock.SECRET_META)); const stateOf = (on: boolean) => { const c = counts(); return { state: !on ? "off" : c.open_rows ? "sealing" : "sealed", ...c }; }; if (method === "GET") return json({ lock: held, ...stateOf(held !== null) }); const body = await readJson(request); if (typeof body.on !== "boolean") refuse(400, "bad_request", "secret-lock takes { on: true | false }"); if (body.on === (held !== null)) return json({ lock: held, ...stateOf(held !== null) }); if (!body.on && counts().sealed_rows > 0) refuse(409, "secret_lock_sealing", "passwords are already sealed: no device can open them back to clear, so the lock stays on"); const lock: openTablesLock.Lock | null = body.on ? { on_at: new Date().toISOString(), by: admin ? "admin" : "owner" } : null; this.ctx.storage.transactionSync(() => { this.store.setMeta(openTablesLock.SECRET_META, lock ? JSON.stringify(lock) : null); // The definitions every device reads change: a new version, so each pulls them and its sweep seals the rows. this.store.bump(); }); return json({ lock, ...stateOf(lock !== null) }); } // RESTORE PROOF and RESTORE 2: the restore routes are answered ahead of every door (`restoreDoor`, src/restore.ts). if (method === "GET" && path === "/restore-audit") { // RESTORE AUDIT (coordinator, 27 Nov 2026): read-only, the admin token alone, on any Worker. Did the act `restore` // ever lay rows into mcp_token or device for a caller that was not the owner's own phone (the M1 hole closed in // ca7b919c69)? A restore keeps no change rows (engine.journal = null), so the evidence is the acts log (its window, // 30 days) and any token or device row whose standing state no change row explains. Ids, times and counts only: // never a hash, a name, a scope or any data of a row. if (!admin) refuse(403, "admin_only", "the restore audit takes the admin token"); const watched = [TOKEN_TABLE, syncStatus.DEVICE_TABLE]; const sql = this.ctx.storage.sql; const acts = sql.exec<{ at: string; person_id: string | null; args: string; outcome: string }>("SELECT at, person_id, args, outcome FROM acts WHERE act = 'restore' ORDER BY at").toArray(); const restores = acts.map((a) => { let tables: Record = {}; try { const parsed = JSON.parse(a.args) as { tables?: unknown }; if (parsed.tables && typeof parsed.tables === "object") tables = parsed.tables as Record; } catch { // a cut or odd args text: counted as naming no table } const named = Object.fromEntries(watched.filter((t) => typeof tables[t] === "number").map((t) => [t, tables[t]!])); return { at: a.at, by: a.person_id === null ? "token_or_admin" : "owner_device", done: a.outcome === "done", named }; }); const actsFrom = sql.exec<{ first: string | null }>("SELECT MIN(at) AS first FROM acts").one().first; const logFloor = sql.exec<{ v: number | null }>("SELECT MIN(version) AS v FROM change").one().v; // RESTORE AUDIT 2: each row held to what its last logged write left (src/row_witness.ts), silent stamps aside. const judged = rowWitness.judge(sql); const byToken = restores.filter((r) => r.by === "token_or_admin"); const suspect = byToken.filter((r) => r.done && Object.keys(r.named).length > 0); return json({ acts_from: actsFrom, change_log_from_version: logFloor, restores: { total: restores.length, by_owner_device: restores.length - byToken.length, by_token_or_admin: byToken.length, by_token_or_admin_refused: byToken.filter((r) => !r.done).length }, suspect_restores: suspect, token_and_device_rows: judged.rows, unexplained_rows: judged.unexplained, // Rows adopted as they stood when witnesses began (row_witness_from), untouched by a logged write since. witness_from: this.store.meta(rowWitness.FROM_META), not_judged: judged.notJudged, }); } if (method === "GET" && path === "/vault-key-check") { // FOUNDER ROW CHECK (src/vault_key_check.ts): read only, the admin token alone. Kinds and counts of this object's // vault_key rows against the founding bug; never a key, a wrap, a row or device id, a name or a number. if (!admin) refuse(403, "admin_only", "the vault key check takes the admin token"); return json(vaultKeyCheck(this.ctx.storage.sql)); } if (method === "GET" && path === "/seal-check") { // Counts only, never content (sealing plan §7 step 7): what is left open in each sealed table. const defs = this.definitions(); const sealedTables = [...defs.tables.values()].filter((t) => t.seal); return json({ tables: sealedTables.map((t) => migration.standing(this.ctx.storage.sql, t, actsWriting(defs, t.id), (act, a) => scrubActArgs(defs, act, a))) }); } if (method === "GET" && path === "/export") { // The meta and every definition, the people, and one page of live rows in (table, id) order: ask again with `after` = the answer's `next` until it is null. this.installed(); const url = new URL(request.url); const limit = integer(url.searchParams.get("limit"), "limit", 5000); if (limit < 1 || limit > 10_000) refuse(400, "bad_request", "limit is 1 to 10000"); const after = url.searchParams.get("after"); const from = after === null ? null : { table: after.slice(0, after.indexOf("/")), id: after.slice(after.indexOf("/") + 1) }; if (from && (!from.table || !after!.includes("/"))) refuse(400, "bad_request", "after is
/"); const { rows, more } = this.store.livePage(from, limit); const last = rows[rows.length - 1]; return json({ business: this.meta(), version: this.store.version(), kit_version: this.store.meta(kitKeep.KIT_VERSION), kit_notices: JSON.parse(this.store.meta(kitKeep.KIT_NOTICES) ?? "[]") as string[], tools: this.store.definitions("tool"), tables: this.store.definitions("table"), flavour: this.store.definitions("flavour")[0] ?? null, boards: this.store.definitions("board"), themes: this.store.definitions("theme"), people: this.store.people().map(wirePerson), counts: this.store.counts(), rows: rows.map((r) => wire(r, true)), next: more && last ? `${last.table}/${last.id}` : null, }); } if (method === "POST" && path === "/person") { const body = await readJson(request); const phone = normalizePhone(text(body.phone, "phone")); if (!phone) refuse(400, "bad_phone", "phone must start with +"); const role = text(body.role ?? "member", "role"); if (role !== "member" && role !== "staff" && role !== "owner") refuse(400, "bad_role", "role is member, staff or owner"); let person: Person | undefined; this.ctx.storage.transactionSync(() => { const version = this.store.bump(); const existing = this.store.personByPhone(phone); person = existing ? this.store.setPerson(existing.id, { role, name: optionalText(body.name) ?? existing.name }, version) : this.store.addPerson(crypto.randomUUID(), phone, optionalText(body.name), role, version); if (person.role === "member") this.ensureOwnCard(person, version, new Outcome_()); }); const card = this.definitions().personTable(); return json({ person: wirePerson(person!), card: card ? this.store.owned(card.id, person!.id)[0]?.id ?? null : null }); } refuse(404, "not_found", `nothing answers ${method} /v1/admin${path}`); } /** A package's definitions replace the object's, the built-in message table added. */ private install(tools: Record[], given: Record[], flavour: Record | null): void { const tables = given.some((t) => t.id === "business_message") ? given : [...given, MESSAGE_TABLE]; this.ctx.storage.transactionSync(() => { const links = this.definitions().linkColumns(); this.store.replaceDefinitions("tool", tools); this.store.replaceDefinitions("table", tables); if (flavour) this.store.replaceDefinitions("flavour", [flavour]); this.store.setMeta("slug", this.slug); this.definitions(); this.store.relink(links); this.store.bump(); }); } /** * Bulk rows for onboarding: `{ rows: [{ ref?, table, data, verb?, slot?, act?, picked?, id? }] }`, * in order. A `data` value `"@"` is the id of an earlier row. Verbs: * `create` (default), `reserve` (slot + data → the claim table), `act` * (table + id + act + picked), `find` (table + where → an existing row, * for one a rule wrote), `put` (table + id + data [+ created_at, * updated_at]: a row brought from another database with its own id and * times — made when absent, patched when it differs, untouched when the * same, so a second run changes nothing). Everything lands in one * transaction and one version, with the automations running as they would * for a person; an import that changed nothing moves no version. */ private import(body: Record): Response { this.installed(); this.roomToWrite(); const rows = Array.isArray(body.rows) ? (body.rows as Record[]) : null; if (!rows) refuse(400, "bad_request", "import needs rows"); if (rows.length > 5000) refuse(413, "too_many", "import at most 5000 rows per call"); // k1 sealing is removed (sealing plan §7 step 6): the object seals no plaintext it is handed; a secret's value comes sealed v2 by a vault device. // Token scopes on: an import plants no key, even the admin's (ROUTES-AUDIT finding 10): keys come from the owner's phones. if (this.tokenScopesOn() && rows.some((r) => r && typeof r === "object" && ["person_key", "seal_key", "vault_key"].includes(String((r as Record).table)))) refuse(403, "token_scopes", "an import plants no key: person_key, seal_key and vault_key come from the owner's phones"); if (rows.some((r) => r && typeof r === "object" && "seal" in r)) refuse(400, "no_plaintext_seal", "the object no longer seals a plaintext it is handed: a secret's value comes sealed by a vault device (Cotton Keys)"); const ids: Record = {}; // Each seed row is its own write with its own rule budget; the answer sums them. const whole = new Outcome_(); let outcome = new Outcome_(); let version = 0; const resolve = (value: unknown): unknown => { if (typeof value === "string" && value.startsWith("@")) { const id = ids[value.slice(1)]; if (!id) refuse(400, "bad_ref", `${value} names no earlier row`); return id; } if (value && typeof value === "object" && !Array.isArray(value)) { const out: Record = {}; for (const [k, v] of Object.entries(value as Record)) out[k] = resolve(v); return out; } return value; }; const before = this.store.version(); // What each brought row did, by table: written (made or patched), unchanged, or deleted here since it came. const puts: Record = {}; const tally = (table: string, what: "written" | "unchanged" | "deleted"): void => { (puts[table] ??= { written: 0, unchanged: 0, deleted: 0 })[what] += 1; }; this.ctx.storage.transactionSync(() => { version = this.store.bump(); const defs = this.definitions(); const engine = this.engine(defs); for (const item of rows) { outcome = new Outcome_(); const verb = typeof item.verb === "string" ? item.verb : "create"; const ref = optionalText(item.ref); let made: StoredRow | null = null; if (verb === "create") { const table = text(item.table, "table"); // A seed row may bring its own id: a fixture whose order or paths turn on its ids keeps them. const id = optionalText(item.id); made = engine.create(table, resolve(object(item.data ?? {}, "data")) as Record, version, outcome, 0, id ? { id } : {}); } else if (verb === "reserve") { const slot = text(resolve(item.slot), "slot"); const data = resolve(object(item.data ?? {}, "data")) as Record; let found = false; for (const tool of engine.tools) { if (!tool.reserve) continue; const slotRow = this.store.get(tool.reserve.slot_table, slot); if (!slotRow) continue; const slotDef = defs.table(tool.reserve.slot_table)!; if (typeof slotRow.data.name === "string" && data.name === undefined) data.name = slotRow.data.name; if (slotDef.date && data[slotDef.date] === undefined) data[slotDef.date] = slotRow.data[slotDef.date]; made = engine.reserve(tool, slot, data, version, outcome); found = true; break; } if (!found) refuse(404, "no_such_slot", `no slot ${slot}`); } else if (verb === "act") { const table = text(item.table, "table"); const id = text(resolve(item.id), "id"); const t = defs.table(table); const row = this.store.get(table, id); if (!t || !row) refuse(404, "no_such_record", `no ${table} ${id}`); const act = recordActs(t).find((a) => a.id === item.act); if (!act) refuse(404, "no_such_act", `${table} has no act ${String(item.act)}`); const picked = Array.isArray(item.picked) ? (item.picked as unknown[]).map(resolve) : []; const before = outcome.made; const result = engine.runAct(t, row, act, picked, version, outcome); made = outcome.made !== before ? outcome.made ?? result : result; } else if (verb === "find") { // A row a rule wrote (an order's delivery), found by its columns so later rows can name it. const table = text(item.table, "table"); const where = resolve(object(item.where ?? {}, "where")) as Record; const [first, ...rest] = Object.entries(where); if (!first) refuse(400, "bad_request", "find needs a where"); const found = this.store.list(table, { column: first[0], equals: first[1] }).find((row) => rest.every(([k, v]) => looseSame(row.data[k], v))); if (!found) refuse(404, "no_such_record", `no ${table} where ${JSON.stringify(where)}`); made = found; } else if (verb === "put") { const table = text(item.table, "table"); const id = text(item.id, "id"); // A brought row's data is literal: its values came from another // database, so a text that happens to start with "@" (a vault hint, // a prompt) is that text, not a reference to an earlier seed row. const data = object(item.data ?? {}, "data"); const stamps: Stamps = {}; if (typeof item.created_at === "string") stamps.created_at = item.created_at; if (typeof item.updated_at === "string") stamps.updated_at = item.updated_at; const held = this.store.any(table, id); if (!held) made = engine.create(table, data, version, outcome, 0, { id, ...stamps }); else if (held.deleted) made = held; // deleted here after it came: an import does not bring it back else made = engine.update(held, data, version, outcome, 0, stamps); tally(table, !held || (!held.deleted && made !== held) ? "written" : held.deleted ? "deleted" : "unchanged"); } else refuse(400, "bad_verb", `import knows create, reserve, act, find and put, not ${verb}`); if (ref && made) ids[ref] = made.id; whole.changed.push(...outcome.changed); whole.notices.push(...outcome.notices); } if (!whole.changed.length) { this.store.setMeta("version", String(before)); version = before; } }); return json({ version, ids, changed: settled(whole).length, puts, notices: whole.notices.slice(0, 50) }); } } /** The acts of the apps TABLE DROP 1 retired (27 Nov 2026), each by the app it was: registered so it is refused by name, never unknown. */ const RETIRED_ACTS = { read_statement: "Money", submit_statement_reading: "Money", book_statement: "Money", settle_expected: "Money", match_external: "Money", merge_accounts: "Money", subscribe_podcast: "Podcasts", refresh_podcast: "Podcasts", import_opml: "Podcasts", export_opml: "Podcasts", fetch_cover: "Music", find_lyrics: "Music", drop_old_music: "Music", } as const satisfies Partial>; /** A retired app's act: refused 410 retired, the sentence naming the app. */ function retiredAct(act: keyof typeof RETIRED_ACTS): never { refuse(410, "retired", `${RETIRED_ACTS[act]} is retired: its tables are no longer served`); } /** The services whose refresh tokens the Worker seals under SERVICE_TOKEN_KEY (src/google.ts, src/spotify.ts). */ const SERVICE_TOKEN_SERVICES = ["google", "spotify"]; /** The passwords one `GET /v1/secret/rewrap` answers, and one POST takes back. */ const REWRAP_BATCH = 50; /** * A table whose rows in a pass from nothing number at most this is carried * before the big ones (owner, 2 Nov 2026). On the owner's object it puts * people (1.7k), todos (950), notes (5k), transactions (8.9k), calls (5.6k) * and photos (9.4k) first, the smallest soonest, and leaves messages, email, * its participants and threads, prompts, code credentials and sightings * (10k and up) to after. */ const SMALL_TABLE_ROWS = 10_000; /** How long a first pass's group cuts are kept (`first_cut`): a pass left longer may carry a row twice, never miss one. */ const FIRST_PASS_KEPT_S = 30 * 86_400; /** The rows one `restore` act brings back at most: a call answers in well under the phone's ceiling. */ const RESTORE_ROWS = 500; /** The most rows one `import_rows` lands: one engine batch (MAX_BATCH_MESSAGES) and what it plans beside it fit in a few calls. */ const IMPORT_ROWS = 500; /** The rows a pass's first page carries at most: enough to hold a poll's few changes whole, few enough to answer at once. */ const FIRST_PAGE_ROWS = 200; /** Rows one `seal_many` act seals at most. */ const SEAL_MANY = 200; /** Whether `/v1/admin/reset` takes the account's own owner token besides the admin token: on the dev and test Workers alone. */ export function resetTakesOwner(env: { ENV_LABEL?: string }): boolean { return devWorker(env); } /** The meta key of the mail-all switch (`POST /v1/admin/mail-all`): when it was thrown, or absent. */ const MAIL_ALL_META = "mail_all_on"; interface SyncPage { since: number; upto: number; limit: number; windows: SyncWindow[]; /** The tables the pass keeps to (`tables=`); null is every table the caller reads. */ tables?: string[] | null; /** * The tables the pass carries first, in their order (`Store.changedPage`): * none for a pass in change order; null on a bridged cursor, whose next * page decides them. */ small: string[] | null; /** Where a bridged pass had got to in change order: every row at or before it was carried. */ floor: Cursor | null; /** The last row carried, its table saying which run it is in; null at the start of the runs. */ after: Cursor | null; /** The pass's figures, counted on its first page (src/sync_status.ts). */ figures: syncStatus.PassFigures; /** A later pass's tables carried again whole, first (`again=`); absent, none. */ again?: string[]; /** A pass carrying first rows first (src/first.ts): its plan and where it stands; absent, the runs above. */ first?: { plan: FirstPlan; at: FirstAt | null } | null; } /** A sync cursor: where the last page ended, what the first page asked and what the pass holds, opaque to the phone. */ /** `book,highlight` → the tables a pass keeps to; absent, every table. */ function syncTables(text: string | null): string[] | null { if (text === null) return null; const tables = text.split(",").map((t) => t.trim()); for (const t of tables) if (!/^[a-z][a-z0-9_]*$/.test(t)) refuse(400, "bad_tables", `tables is a list of table ids, not ${text}`); return [...new Set(tables)].sort(); } interface HeldPage { tables: string[]; limit: number; after: { table: string; id: string }; } function readHeldCursor(token: string): HeldPage { try { const page = JSON.parse(atob(token.replace(/-/g, "+").replace(/_/g, "/"))) as HeldPage; if (Array.isArray(page.tables) && typeof page.limit === "number" && typeof page.after?.table === "string" && typeof page.after?.id === "string") return page; } catch { // falls through to the refusal } refuse(400, "bad_cursor", "that cursor is not one this object gave"); } function writeCursor(page: SyncPage | HeldPage): string { return btoa(JSON.stringify(page)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } function readCursor(token: string): SyncPage { let page: SyncPage; try { page = JSON.parse(atob(token.replace(/-/g, "+").replace(/_/g, "/"))) as SyncPage; } catch { refuse(400, "bad_cursor", "that cursor is not one this object gave"); } // The same bridge for a cursor made before a pass counted its tables // (2 Nov 2026): its figures name none, and its pass goes on saying none // rather than starting again. Remove with the one bridge below. const figures = page?.figures as Partial | undefined; if (figures && typeof figures === "object" && figures.tables === undefined) figures.tables = {}; const whole = (n: unknown): boolean => typeof n === "number" && Number.isInteger(n) && n >= 0; const place = (c: unknown): c is Cursor => { const o = c as Cursor | null; return !!o && typeof o === "object" && whole(o.version) && typeof o.table === "string" && typeof o.id === "string"; }; const ok = page && whole(page.since) && whole(page.upto) && whole(page.limit) && page.limit >= 1 && page.limit <= 10_000 && Array.isArray(page.windows) && page.windows.every((w) => w && typeof w.table === "string" && typeof w.column === "string" && typeof w.from === "string" && (w.is === undefined || (Array.isArray(w.is) && w.is.every((v) => typeof v === "string")))) && (page.tables === undefined || page.tables === null || (Array.isArray(page.tables) && page.tables.every((t) => typeof t === "string"))) && place(page.after) && syncStatus.isFigures(page.figures); if (!ok) refuse(400, "bad_cursor", "that cursor is not one this object gave"); // THE ONE BRIDGE (2 Nov 2026): a cursor made before small tables came first // names neither `small` nor `floor`: a pass in change order, `after` where // it got to. It is taken, never refused (a refusal would start the pull // again from nothing), and goes on from there: everything up to `after` is // its floor and, for a pass from nothing, its small tables are decided on // this page, so a copy mid-pull on one gets its people and todos next. // Remove once every device has caught up past such a cursor. const said = page as Partial; if (said.small === undefined && said.floor === undefined) return { ...page, small: null, floor: page.after, after: null }; const named = Array.isArray(page.small) && page.small.every((t) => typeof t === "string") && (page.floor === null || place(page.floor)); if (page.again !== undefined && !(Array.isArray(page.again) && page.again.every((t) => typeof t === "string" && /^[a-z][a-z0-9_]*$/.test(t)))) refuse(400, "bad_cursor", "that cursor is not one this object gave"); if (!named || !(page.first === undefined || page.first === null || isFirst(page.first))) refuse(400, "bad_cursor", "that cursor is not one this object gave"); return page; } /** Whether a cursor's first plan reads: every name a table or column, every count whole (src/first.ts, `Store.firstPage`). */ function isFirst(f: unknown): f is { plan: FirstPlan; at: FirstAt | null } { const o = f as { plan?: FirstPlan; at?: FirstAt | null }; const name = (v: unknown): boolean => typeof v === "string" && /^[a-z_][a-z0-9_]*$/.test(v); const count = (v: unknown): boolean => typeof v === "number" && Number.isInteger(v) && v >= 0; const value = (v: unknown): boolean => v === null || typeof v === "string" || typeof v === "number"; const key = (k: unknown): boolean => k === null || (Array.isArray(k) && k.length === 2 && value(k[0]) && typeof k[1] === "string"); const day = (v: unknown): boolean => typeof v === "string" && /^\d{4}-\d{2}-\d{2}$/.test(v); const spec = (sp: FirstSpec): boolean => !!sp && typeof sp === "object" && name(sp.table) && name(sp.by) && typeof sp.asc === "boolean" && (sp.rows === null || (count(sp.rows) && sp.rows > 0)) && Array.isArray(sp.unless) && sp.unless.every(name) && (sp.around === null || (!!sp.around && day(sp.around.from) && day(sp.around.to))) && typeof sp.soon === "boolean" && (sp.late === undefined || typeof sp.late === "boolean") && (sp.per === null || (!!sp.per && name(sp.per.column) && name(sp.per.of) && name(sp.per.by) && typeof sp.per.asc === "boolean" && (sp.per.groups === null || count(sp.per.groups)) && (sp.per.early === undefined || sp.per.early === null || count(sp.per.early)))); const plan = o?.plan; if (!plan || typeof plan !== "object" || typeof plan.pass !== "string" || !Array.isArray(plan.small) || !plan.small.every((t) => typeof t === "string") || !Array.isArray(plan.specs) || !plan.specs.every(spec) || !Array.isArray(plan.cuts) || plan.cuts.length !== plan.specs.length || !plan.cuts.every(key)) return false; const early = (e: unknown): boolean => e === null || (!!e && typeof e === "object" && key((e as { group: unknown }).group) && (e as { group: unknown }).group !== null && count((e as { groups: unknown }).groups)); if (plan.from !== undefined && !(Array.isArray(plan.from) && plan.from.length === plan.specs.length && plan.from.every(early))) return false; const at = o.at; if (at === null || at === undefined) return at === null; const runs = ["lead", "early", "small", "group", "soon", "soonrest", "change", "tail", "rest"]; const place = (c: unknown): boolean => c === null || (!!c && typeof c === "object" && count((c as Cursor).version) && typeof (c as Cursor).table === "string" && typeof (c as Cursor).id === "string"); return typeof at === "object" && runs.includes(at.run) && count(at.i) && key(at.key) && count(at.n) && key(at.group) && count(at.groups) && place(at.change); } function looseSame(a: unknown, b: unknown): boolean { return JSON.stringify(a ?? null) === JSON.stringify(b ?? null); } class Outcome_ implements Outcome { changed: StoredRow[] = []; made?: StoredRow; notices: string[] = []; reply?: Record; stale?: boolean; } /** * An act's own table rule: the table an act writes without naming it in its * args, and which arg lands in which column (`message` → business_message, * `profile` → the person table's card). Null for an act whose args name their * table (create, update, seal…) or that writes no record's columns. */ function ownTable(defs: Definitions, act: string): { table: string; columns: Record } | null { if (act === "message") return { table: "business_message", columns: { text: "text", about: "about", person: "person" } }; if (act === "profile") { const t = defs.personTable(); return t ? { table: t.id, columns: { name: "name" } } : null; } return null; } /** The acts whose own table rule writes `table` (their args never name it): what `seal_purge` reads beside the acts that name it. */ function actsWriting(defs: Definitions, table: string): string[] { return (Object.keys(ACTS) as ActName[]).filter((act) => ownTable(defs, act)?.table === table); } /** * An act's args as the act log keeps them (sealing plan §2.2): a write to a * sealed table keeps each sealed column it said in the clear only as a mark * (a device's refused attempt included), and its blind tokens only as a * count; every other act's args as said. `seal_purge` runs earlier acts * through the same rule. */ function scrubActArgs(defs: Definitions, act: string, args: Record): Record { const sealedOf = (name: unknown) => (typeof name === "string" ? defs.table(name) : undefined); const own = ownTable(defs, act); if (own) { const t = sealedOf(own.table); if (!t?.seal) return args; // Its args said as the columns they land in, scrubbed as a row's data is. const data: Record = {}; for (const [arg, column] of Object.entries(own.columns)) if (arg in args) data[column] = args[arg]; const scrubbed = scrubData(t, data); const out = { ...args }; for (const [arg, column] of Object.entries(own.columns)) if (arg in args) out[arg] = scrubbed[column]; return out; } const one = (row: Record, table?: unknown): Record => { const t = sealedOf(row.table ?? table); return t?.seal ? migration.scrubRow(t, row) : row; }; const each = (rows: unknown[], table?: unknown) => rows.map((r) => (r && typeof r === "object" && !Array.isArray(r) ? one(r as Record, table) : r)); // A batch of up to 500 rows is kept as its count by table: it keeps no undo // journal, so its rows are no record of what to undo, and whole rows outgrow // the log's 4000 characters, where a cut text no longer reads as JSON and // seal-check could never tell it from one that held a sealed column. if ((act === "restore" || act === "import_rows" || act === "seal_many") && Array.isArray(args.rows)) { const tables: Record = {}; for (const r of args.rows) { const table = r && typeof r === "object" && !Array.isArray(r) && typeof (r as Record).table === "string" ? ((r as Record).table as string) : "?"; tables[table] = (tables[table] ?? 0) + 1; } const { rows: _rows, ...rest } = args; return { ...rest, rows: args.rows.length, tables }; } if (act === "seal_stage" && Array.isArray(args.rows)) return { ...args, rows: each(args.rows, args.table) }; return one(args); } /** The challenge a passkey answer's clientData names, or null. */ function clientChallenge(response: Record): string | null { try { const inner = response.response as Record | undefined; if (!inner || typeof inner.clientDataJSON !== "string") return null; const data = JSON.parse(new TextDecoder().decode(vault.fromBase64Url(inner.clientDataJSON))) as { challenge?: unknown }; return typeof data.challenge === "string" ? data.challenge : null; } catch { return null; } } const ROLLED_BACK = Symbol("rolled back"); /** `fn`'s answer, with everything it wrote undone. */ function rolledBack(storage: DurableObjectStorage, fn: () => T): T { let out: T | undefined; try { storage.transactionSync(() => { out = fn(); throw ROLLED_BACK; }); } catch (error) { if (error !== ROLLED_BACK) throw error; } return out as T; } /** New clients go to `fresh`; one is found there first, then among the `old` (registered before the move). */ function withOldClients(fresh: Clients, old: Clients): Clients { return { get: async (id) => (await fresh.get(id)) ?? (await old.get(id)), add: (client) => fresh.add(client) }; } /** An act's name and its largest list of args, when it holds REQUEST_MARK_ROWS items or more: "import_rows rows=500". */ export function bulkOf(body: unknown): string | null { if (!body || typeof body !== "object") return null; const { act, args } = body as { act?: unknown; args?: unknown }; if (!args || typeof args !== "object") return null; let most: [string, number] | null = null; for (const [k, v] of Object.entries(args as Record)) if (Array.isArray(v) && (!most || v.length > most[1])) most = [k, v.length]; return most && most[1] >= REQUEST_MARK_ROWS ? `${typeof act === "string" ? act.slice(0, 40) : "-"} ${most[0]}=${most[1]}` : null; } /** A silent stamp's field, by name: refused at once if it is not on rowWitness.SILENT_STAMPS (the restore audit's list). */ function stampOf(_table: T, field: (typeof rowWitness.SILENT_STAMPS)[T][number]): string { return field; }