/** * SHARED SPACE (coordinator, 26 Nov 2026; assets/design/albums/SHARED-SPACE.md, DECISIONS.md "Shared albums"): a * place several people share, its own Durable Object and its own R2 prefix (`spaces/<id>/`), on nobody's own object, * so it neither dies with one member's account nor loads into anyone's. Cotton Albums is its first tenant; records * are kinds (`album`, `item`) so Comms groups or Secrets could later live in a space without changing the gate. * * WHAT IT HOLDS is only what the phones and the members' own objects give it: members (bound for ever to their * DATABASE id; the number, sharing and signing keys and name their OWN object gave), each epoch's `w1:` wraps, records * (a per-record key wrapped at an epoch, `g1:`, a body sealed under that key, `r1:`, and the adder's signature, * `s1:`), file rows, links, and bytes per adder. It never holds a key that opens a record or a file. * * ONE GATE. Every route (src/space/routes.ts `ROUTES`) passes `gate` before its handler runs, and a handler is handed * only the gate's answer. Anyone not let in is told the space is not there, whether or not it is. * * OWNERSHIP (DECISIONS.md "Ownership, and what survives"). The founder is the owner: the owner adds and removes * members, moves the epoch, removes anyone's records, makes and stops links, and deletes the space. When the owner * leaves or their account is erased, ownership passes to the member who has been in longest. A member who leaves (or * is removed, or whose account is erased) is out at once, and every link they made stops; the records they added stay * for the others for thirty days and any member may Keep them; what nobody keeps then goes, refunded to who added it. * When the last member leaves, or the owner deletes the space, links stop, and thirty days later the alarm erases it * (a deleted space's members still read and save meanwhile). * * NOTHING SWALLOWED (review, 27 Nov): telling a member's object they are out, and every refund, go through an outbox * the alarm retries until the object takes it. */import { DurableObject } from"cloudflare:workers";import { directory } from"../directory.ts";importtype { Env } from"../env.ts";import { Refused, refuse, sha256Hex } from"../http.ts";import { MEDIA_MAX_BYTES } from"../media.ts";import { SPACE_FULL, SPACE_FULL_WORDS } from"../space.ts";importtype { JoinAnswer } from"./person.ts";import { ROUTES, typeRoute, typeRouteName } from"./routes.ts";import { b64url, fileAt, mediaPath, mint, READ_LIFE_MS, WRITE_LIFE_MS } from"./signed.ts";import { spacesOn } from"./switch.ts";exportconst LIMITS = { members: 64,/** Spaces one person founds, and is in (held by their own object, src/space/person.ts `join`). */ founded: 200, joined: 500, records: 100_000, recordBytes: 65_536, perCall: 200, filesPerRecord: 6, fileBytes: MEDIA_MAX_BYTES, uploadsPerHour: 2000, links: 20, linkDays: 30, linkReadsPerMinute: 600, listPage: 500,} asconst;/** How long a departed member's records stay, and how long an ending or deleted space waits before it is erased. */exportconst LEAVE_MS = 30 * 24 * 3_600_000;/** What a record's wrapped key is counted as, whatever its length: a re-wrap never changes what the adder is charged. */const KEY_ALLOWANCE = 400;/** How often the alarm looks for bytes under the prefix with no file row. */const ORPHAN_SWEEP_MS = 24 * 3_600_000;/** * SPACES 1 (coordinator, 28 Nov 2026): a space names the app it belongs to, fixed at founding, and each app its record * kinds. Albums keeps `album` (its own container) and `item`; every other app shares one plain pair, `thing` (a note, * a site, an event, a list: its own container, as an album is) and `part` (a page, an entry, a list's item, inside one). * A space made before SPACES 1 says no app and is an Albums space. */exportconst APPS: Readonly<Record<string, { kinds: ReadonlySet<string>; container: string }>> = { albums: { kinds: newSet(["album", "item"]), container: "album" }, words: { kinds: newSet(["thing", "part"]), container: "thing" }, sites: { kinds: newSet(["thing", "part"]), container: "thing" }, days: { kinds: newSet(["thing", "part"]), container: "thing" }, cinemas: { kinds: newSet(["thing", "part"]), container: "thing" },};exporttypeApp = keyoftypeof APPS;const SPACE_ID = /^[A-Za-z0-9_-]{22}$/;const FILE_ID = /^[A-Za-z0-9_-]{22}$/;const MEMBER_ID = /^m[A-Za-z0-9_-]{16}$/;const RECORD_ID = /^[A-Za-z0-9_-]{1,64}$/;const LINK_ID = /^[A-Za-z0-9_-]{8,64}$/;const KEY = /^[A-Za-z0-9_-]{43}$/;const WRAP = /^w1:[A-Za-z0-9_-]{20,600}$/;const RECORD_KEY = /^g1:(\d{1,9}):[A-Za-z0-9_-]{20,400}$/;const BODY = /^r1:[A-Za-z0-9_-]+$/;const SIG = /^s1:[A-Za-z0-9_-]{40,200}$/;const HASH = /^[0-9a-f]{64}$/;const NUMBER = /^\+[1-9]\d{6,14}$/;/** Who is asking, as the door settled it: a person (vouched by their own object), a link holder, or nobody. */exporttypeCaller = { kind: "person"; number: string; slug: string; database: string } | { kind: "link"; link: string; auth: string } | { kind: "none" };exportinterfaceAsk { route: RouteName; space: string; link?: string | null; query?: Record<string, string>; body?: Record<string, unknown>;/** The origin URLs are minted against. */ base: string;}exportinterfaceAnswer { status: number; body: unknown;}/** What a person's object answers a space (src/business.ts). */exportinterfacePersonObject { spacePeers(numbers: string[]): Promise<string[]>; spaceJoin(space: string, from: string, founding: boolean, serial: number, app?: string): Promise<JoinAnswer>; spaceLeft(space: string, serial: number): Promise<boolean>; spaceCharge(space: string, delta: number): Promise<boolean>;}/** The one refusal anyone not let in gets: it never says whether the space, the link or the member exists. */exportconst NOT_THERE = { status: 404, code: "no_space", message: "That is not there." } asconst;typeMember = { id: string; database: string; number: string; slug: string; key: string; sign: string | null; name: string | null;/** owner; member (can add, said "add" to phones); see (SPACES 1: reads, adds nothing). */ role: "owner" | "member" | "see"; joined_at: number; left_at: number | null; cursor: number;/** This membership's serial in the space: a later telling for an earlier membership never undoes a re-add. */ serial: number;};typeLinkRow = { id: string; album: string; public_key: string; auth_hash: string; expires: number; stopped: number; made_by: string; window: number; reads: number;};typeRecordRow = { id: string; kind: string; album: string; adder: string; epoch: number; key: string | null; body: string | null; sig: string | null;/** Who signed the body, and the signing key they had then: kept when Keep moves the record to another adder. */ signer: string | null; signer_key: string | null; files: string; bytes: number; seq: number; deleted: number;/** The adder's version of the record (1, 2, …): the phone refuses one lower than it saw. */ version: number;/** A deletion's signature (cotton-core `seal::shared_album::tomb_message`) and who signed it. */ tomb: string | null; tomb_by: string | null;};typeFileRow = { id: string; adder: string; size: number;/** reserved (granted) → claimed (the door took the one PUT) → uploaded (the bytes landed whole) → stored (a record names it). */ state: "reserved" | "claimed" | "uploaded" | "stored"; record: string | null; at: number;};/** `delta`: the bytes a refund gives back (negative), or the membership serial a telling-out is for. */typeOutbox = { id: number; kind: "left" | "refund"; slug: string; delta: number; tries: number; next_at: number };typeGated = { kind: "member"; member: Member } | { kind: "link"; link: LinkRow } | { kind: "founder" };typeTaken = { slug: string; identity: { database: string; key: string; sign: string | null; name: string | null }; number: string; serial: number };const SCHEMA = `CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT NOT NULL);CREATE TABLE IF NOT EXISTS member (id TEXT PRIMARY KEY, database TEXT NOT NULL UNIQUE, number TEXT NOT NULL, slug TEXT NOT NULL, key TEXT NOT NULL, sign TEXT, name TEXT, role TEXT NOT NULL, joined_at INTEGER NOT NULL, left_at INTEGER, cursor INTEGER NOT NULL DEFAULT 0, serial INTEGER NOT NULL DEFAULT 0);CREATE TABLE IF NOT EXISTS wrap (epoch INTEGER NOT NULL, holder TEXT NOT NULL, wrap TEXT NOT NULL, PRIMARY KEY (epoch, holder));CREATE TABLE IF NOT EXISTS record (id TEXT PRIMARY KEY, kind TEXT NOT NULL, album TEXT NOT NULL, adder TEXT NOT NULL, epoch INTEGER NOT NULL, key TEXT, body TEXT, sig TEXT, signer TEXT, signer_key TEXT, files TEXT NOT NULL, bytes INTEGER NOT NULL DEFAULT 0, seq INTEGER NOT NULL, at INTEGER NOT NULL, deleted INTEGER NOT NULL DEFAULT 0, version INTEGER NOT NULL DEFAULT 1, tomb TEXT, tomb_by TEXT);CREATE INDEX IF NOT EXISTS record_seq ON record (seq);CREATE INDEX IF NOT EXISTS record_album ON record (album, seq);CREATE TABLE IF NOT EXISTS file (id TEXT PRIMARY KEY, adder TEXT NOT NULL, size INTEGER NOT NULL, state TEXT NOT NULL, record TEXT, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS link (id TEXT PRIMARY KEY, album TEXT NOT NULL, public_key TEXT NOT NULL, auth_hash TEXT NOT NULL, expires INTEGER NOT NULL, stopped INTEGER NOT NULL DEFAULT 0, made_by TEXT NOT NULL, window INTEGER NOT NULL DEFAULT 0, reads INTEGER NOT NULL DEFAULT 0);CREATE TABLE IF NOT EXISTS roster (seq INTEGER PRIMARY KEY, text TEXT NOT NULL, hash TEXT NOT NULL, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS outbox (id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, slug TEXT NOT NULL, delta INTEGER NOT NULL DEFAULT 0, tries INTEGER NOT NULL DEFAULT 0, next_at INTEGER NOT NULL);`;/** * SPACES 1 rule 2: no route reads a whole table. What a route used to sum or count over every record and file is kept * as it changes: `tally` is each adder's bytes (every file, and every live record's sealed text), `epoch_live` the live * records keyed at each epoch. Partial indexes answer the stale list, the tombstone prune, an adder's own rows and the * reserved files without a scan. A space made before SPACES 1 is filled once (meta `tally_v`). */const TALLIES = `CREATE TABLE IF NOT EXISTS tally (adder TEXT PRIMARY KEY, n INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS epoch_live (epoch INTEGER PRIMARY KEY, n INTEGER NOT NULL);CREATE TRIGGER IF NOT EXISTS record_tally_in AFTER INSERT ON record WHEN NEW.deleted = 0 BEGIN INSERT INTO tally (adder, n) VALUES (NEW.adder, NEW.bytes) ON CONFLICT (adder) DO UPDATE SET n = n + excluded.n; INSERT INTO epoch_live (epoch, n) VALUES (NEW.epoch, 1) ON CONFLICT (epoch) DO UPDATE SET n = n + 1;END;CREATE TRIGGER IF NOT EXISTS record_tally_out AFTER DELETE ON record WHEN OLD.deleted = 0 BEGIN UPDATE tally SET n = n - OLD.bytes WHERE adder = OLD.adder; UPDATE epoch_live SET n = n - 1 WHERE epoch = OLD.epoch;END;CREATE TRIGGER IF NOT EXISTS record_tally_was AFTER UPDATE OF adder, bytes, epoch, deleted ON record WHEN OLD.deleted = 0 BEGIN UPDATE tally SET n = n - OLD.bytes WHERE adder = OLD.adder; UPDATE epoch_live SET n = n - 1 WHERE epoch = OLD.epoch;END;CREATE TRIGGER IF NOT EXISTS record_tally_now AFTER UPDATE OF adder, bytes, epoch, deleted ON record WHEN NEW.deleted = 0 BEGIN INSERT INTO tally (adder, n) VALUES (NEW.adder, NEW.bytes) ON CONFLICT (adder) DO UPDATE SET n = n + excluded.n; INSERT INTO epoch_live (epoch, n) VALUES (NEW.epoch, 1) ON CONFLICT (epoch) DO UPDATE SET n = n + 1;END;CREATE TRIGGER IF NOT EXISTS file_tally_in AFTER INSERT ON file BEGIN INSERT INTO tally (adder, n) VALUES (NEW.adder, NEW.size) ON CONFLICT (adder) DO UPDATE SET n = n + excluded.n;END;CREATE TRIGGER IF NOT EXISTS file_tally_out AFTER DELETE ON file BEGIN UPDATE tally SET n = n - OLD.size WHERE adder = OLD.adder;END;CREATE TRIGGER IF NOT EXISTS file_tally_moved AFTER UPDATE OF adder, size ON file BEGIN UPDATE tally SET n = n - OLD.size WHERE adder = OLD.adder; INSERT INTO tally (adder, n) VALUES (NEW.adder, NEW.size) ON CONFLICT (adder) DO UPDATE SET n = n + excluded.n;END;CREATE INDEX IF NOT EXISTS record_stale ON record (epoch, seq) WHERE deleted = 0;CREATE INDEX IF NOT EXISTS record_tombs ON record (seq) WHERE deleted = 1;CREATE INDEX IF NOT EXISTS record_adder ON record (adder) WHERE deleted = 0;CREATE INDEX IF NOT EXISTS file_adder ON file (adder, at);CREATE INDEX IF NOT EXISTS file_reserved ON file (at) WHERE state <> 'stored';`;/** Columns a space made before SHARED SPACE 3 gains (a table only gains columns). */const COLUMNS: [table: string, column: string, type: string][] = [ ["member", "serial", "INTEGER NOT NULL DEFAULT 0"], ["record", "signer", "TEXT"], ["record", "signer_key", "TEXT"], ["record", "version", "INTEGER NOT NULL DEFAULT 1"], ["record", "tomb", "TEXT"], ["record", "tomb_by", "TEXT"],];/** Tables a space made before SHARED 4 gains. */const TABLES = ["CREATE TABLE IF NOT EXISTS roster (seq INTEGER PRIMARY KEY, text TEXT NOT NULL, hash TEXT NOT NULL, at INTEGER NOT NULL)"];/** The routes each kind of roster statement is recorded with (the phones', cotton-ffi albums_shared). */const STATEMENT_ROUTES: Readonly<Record<string, readonly string[]>> = { found: ["epoch"], epoch: ["epoch"], add: ["wraps.add"], leave: ["leave"], link: ["links.make"], claim: ["roster.add"],void: ["roster.add"], handover: ["roster.add"],};/** The kinds only the space's owner signs. */const OWNER_KINDS = newSet(["found", "epoch", "add", "link", "void", "handover"]);/** Does `sig` (base64url) verify as `signKey`'s (Ed25519, base64url) over the roster's signed text for `json`? */asyncfunction verifiesRoster(signKey: string, json: string, sig: string): Promise<boolean> {try {const key = await crypto.subtle.importKey("raw", b64urlDecode(signKey), { name: "Ed25519" }, false, ["verify"]);returnawait crypto.subtle.verify({ name: "Ed25519" }, key, b64urlDecode(sig), newTextEncoder().encode(`cotton-space-roster-v1\n${json}`)); } catch {returnfalse; }}/** A roster statement as a phone posts it: `t1:` b64url(body JSON) `.` b64url(signature). */const STATEMENT = /^t1:([A-Za-z0-9_-]{20,90000})\.([A-Za-z0-9_-]{40,200})$/;const ROUTE_BY_NAME = newMap<string, Route>(ROUTES.map((r) => [r.name, r asRoute]));/** A fresh id the Worker mints: 16 random bytes, base64url (22 characters). */exportfunction freshId(): string {return b64url(crypto.getRandomValues(newUint8Array(16)));}function freshMemberId(): string {return`m${b64url(crypto.getRandomValues(new Uint8Array(12)))}`;}exportclassSpaceextendsDurableObject<Env> {privateget sql(): SqlStorage {returnthis.ctx.storage.sql; }/** Whether this object holds a space: a read of an id nobody founded writes nothing. */private exists(): boolean {if (!this.sql.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'meta'").toArray().length || this.meta("id") === null) returnfalse;if (!this.upgraded) {for (const create of TABLES) this.sql.exec(create);for (const [table, column, type] of COLUMNS) {if (!this.sql.exec<{ name: string }>(`PRAGMA table_info(${table})`).toArray().some((c) => c.name === column)) this.sql.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`); }if (this.meta("tally_v") === null) this.fillTallies();this.upgraded = true; }returntrue; }private upgraded = false;/** Once, for a space made before SPACES 1: its tallies from what it holds (the only whole-table read, and only once). */private fillTallies(): void {this.ctx.storage.transactionSync(() => {this.sql.exec(TALLIES);this.sql.exec("DELETE FROM tally");this.sql.exec("DELETE FROM epoch_live");this.sql.exec("INSERT INTO tally (adder, n) SELECT adder, SUM(size) FROM file GROUP BY adder");this.sql.exec("INSERT INTO tally (adder, n) SELECT adder, SUM(bytes) FROM record WHERE deleted = 0 GROUP BY adder ON CONFLICT (adder) DO UPDATE SET n = n + excluded.n", );this.sql.exec("INSERT INTO epoch_live (epoch, n) SELECT epoch, COUNT(*) FROM record WHERE deleted = 0 GROUP BY epoch");this.setMeta("tally_v", 1); }); }/** Live records keyed before `epoch` (all of them when it is past the newest). */private liveBefore(epoch: number): number {returnthis.sql.exec<{ n: number | null }>("SELECT SUM(n) AS n FROM epoch_live WHERE epoch < ?", epoch).one().n ?? 0; }/** Each adder's bytes in this space. */private tallies(): { adder: string; n: number }[] {returnthis.sql.exec<{ adder: string; n: number }>("SELECT adder, n FROM tally WHERE n <> 0").toArray(); }/** A statement is being recorded with its act: a second waits (the chain is one line). */private statementBusy = false;/** * A roster statement kept in the chain: it must name the hash of the last one (none for the first) and the next * seq, and (AUDIT FIX B1, B-1 and B-10) be the calling member's own: `by` is their member id and the signature * verifies under their signing key, over the exact text the phones verify (cotton-core `seal::shared_roster`: * "cotton-space-roster-v1\n" + body JSON). Each kind rides only on the route that records it; an owner's kind comes * only from the owner the space holds; a `claim` only from a member the space already made owner (the old one gone). * The phones still verify every statement against the chain. Answers its seq, or null for none. */privateasync takeStatement(raw: unknown, me: Member, route: string): Promise<number | null> {if (raw === undefined || raw === null) returnnull;const m = typeof raw === "string" ? STATEMENT.exec(raw) : null;if (!m) refuse(400, "bad_statement", "statement: t1: body . signature");let body: { space?: unknown; seq?: unknown; prev?: unknown; kind?: unknown; by?: unknown };let json: string;try { json = newTextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(b64urlDecode(m[1]!)); body = JSON.parse(json) astypeof body; } catch { refuse(400, "bad_statement", "statement: its body is JSON"); }const kind = typeof body.kind === "string" ? body.kind : "";const rides = STATEMENT_ROUTES[kind];if (!rides || !rides.includes(route)) refuse(400, "bad_statement", `a ${kind || "statement"} is not recorded with this act`);if (body.by !== me.id) refuse(403, "not_yours", "A statement is signed by the member who sends it.");if ((OWNER_KINDS.has(kind) || kind === "claim") && me.role !== "owner") refuse(403, "owner_only", "Only the owner of this space says that.");if (!me.sign || !(await verifiesRoster(me.sign, json, m[2]!))) refuse(403, "bad_signature", "This statement is not signed by the member who sends it.");const hash = await sha256Hex(raw as string);if (this.statementBusy) refuse(409, "roster_busy", "Another change to the members is being recorded; try again.");const head = this.sql.exec<{ seq: number; hash: string }>("SELECT seq, hash FROM roster ORDER BY seq DESC LIMIT 1").toArray()[0];const seq = head ? head.seq + 1 : 0;if (body.space !== this.space() || body.seq !== seq || body.prev !== (head?.hash ?? "")) refuse(409, "roster_moved", "The members changed meanwhile; read the space again and retry.");this.statementBusy = true;this.sql.exec("INSERT INTO roster (seq, text, hash, at) VALUES (?, ?, ?, ?)", seq, raw, hash, Date.now());return seq; }/** * The owner takes the newest statement off the chain (AUDIT FIX B1, B-1): one their phone found does not apply (a * member's signed statement the chain refuses), so no member can leave a roster stuck for good. Only the head, never * the founding one, and only the one named by its hash. */private dropStatement(body: Record<string, unknown>): { ok: true; head: { seq: number; hash: string } | null } {const head = this.rosterHead();if (!head || head.seq === 0 || body.seq !== head.seq || body.hash !== head.hash) refuse(409, "roster_moved", "Only the newest statement is taken off, named by its seq and hash; read the space again.");this.sql.exec("DELETE FROM roster WHERE seq = ?", head.seq);return { ok: true, head: this.rosterHead() }; }private rosterHead(): { seq: number; hash: string } | null {returnthis.sql.exec<{ seq: number; hash: string }>("SELECT seq, hash FROM roster ORDER BY seq DESC LIMIT 1").toArray()[0] ?? null; }private rosterList(query: Record<string, string>): unknown {const after = Number(query.after ?? "-1");const rows = this.sql.exec<{ seq: number; text: string }>("SELECT seq, text FROM roster WHERE seq > ? ORDER BY seq LIMIT ?", Number.isFinite(after) ? after : -1, LIMITS.listPage).toArray();return { statements: rows, head: this.rosterHead() }; }/** The `rekey_due` mark set, and counted, so a move begun before it does not clear it (SHARED 4). */private markDue(): void {this.setMeta("rekey_due", "1");this.setMeta("due_count", Number(this.meta("due_count") ?? "0") + 1); }private meta(k: string): string | null {returnthis.sql.exec<{ v: string }>("SELECT v FROM meta WHERE k = ?", k).toArray()[0]?.v ?? null; }private setMeta(k: string, v: string | number | null): void {if (v === null) this.sql.exec("DELETE FROM meta WHERE k = ?", k);elsethis.sql.exec("INSERT INTO meta (k, v) VALUES (?, ?) ON CONFLICT (k) DO UPDATE SET v = excluded.v", k, String(v)); }private space(): string {returnthis.meta("id")!; }/** The app this space belongs to; a space made before SPACES 1 is Albums'. */private app(): string {returnthis.meta("app") ?? "albums"; }private epoch(): number {returnNumber(this.meta("epoch") ?? "0"); }private nextSeq(): number {const seq = Number(this.meta("seq") ?? "0") + 1;this.setMeta("seq", seq);return seq; }/** The last member left: nobody reads it, and it is erased thirty days on. */private ending(): boolean {returnthis.meta("state") === "ending"; }/** The owner deleted it: its members read and save for thirty days, nothing changes, then it is erased. */private deleted(): boolean {returnthis.meta("state") === "deleted"; }private active(): Member[] {returnthis.sql.exec<Member>("SELECT * FROM member WHERE left_at IS NULL ORDER BY serial, joined_at, id").toArray(); }private memberById(id: string): Member | null {returnthis.sql.exec<Member>("SELECT * FROM member WHERE id = ?", id).toArray()[0] ?? null; }private liveLinks(now: number): LinkRow[] {returnthis.sql.exec<LinkRow>("SELECT * FROM link WHERE stopped = 0 AND expires > ?", now).toArray(); }/** The one entry the door calls: the gate, then the route's handler. Refusals come back as answers. */async handle(caller: Caller, ask: Ask): Promise<Answer> {try {if (!spacesOn()) refuse(404, "not_found", "no such route");const route = ROUTE_BY_NAME.get(ask.route);if (!route || !SPACE_ID.test(ask.space)) refuse(NOT_THERE.status, NOT_THERE.code, NOT_THERE.message);const gated = awaitthis.gate(route, caller, ask);// A roster statement rides on the act it records: kept in the chain before the act runs, let go if it fails.const statement = gated.kind === "member" ? awaitthis.takeStatement(ask.body?.statement, gated.member, route.name) : null;try {return { status: 200, body: awaitthis.run(route, gated, caller, ask) }; } catch (error) {if (statement !== null) this.sql.exec("DELETE FROM roster WHERE seq = ?", statement);throw error; } finally {if (statement !== null) this.statementBusy = false; } } catch (error) {if (error instanceofRefused) return { status: error.status, body: { code: error.code, message: error.message } };throw error; } }/** * THE GATE. Nothing below it reads membership, links or the epoch on its own account. A member is found by the * DATABASE the door read from the credential, never by the number: a number someone else holds later opens nothing. */privateasync gate(route: Route, caller: Caller, ask: Ask): Promise<Gated> {const notThere: () => never = () => refuse(NOT_THERE.status, NOT_THERE.code, NOT_THERE.message);const now = Date.now();if (route.name === "spaces.found") {if (caller.kind !== "person" || this.exists()) notThere();return { kind: "founder" }; }if (!this.exists() || this.ending()) notThere();if (route.need === "link") {if (caller.kind !== "link" || !ask.link || caller.link !== ask.link || !LINK_ID.test(ask.link) || this.deleted()) notThere();const link = this.sql.exec<LinkRow>("SELECT * FROM link WHERE id = ?", ask.link).toArray()[0];if (!link || link.stopped || link.expires <= now) notThere();if (!timingSafeEqual(await sha256Hex(caller.auth), link.auth_hash)) notThere();const window = Math.floor(now / 60_000);const reads = link.window === window ? link.reads + 1 : 1;this.sql.exec("UPDATE link SET window = ?, reads = ? WHERE id = ?", window, reads, link.id);if (reads > LIMITS.linkReadsPerMinute) refuse(429, "slow_down", "This link is being read too often; try again in a minute.");return { kind: "link", link }; }if (caller.kind !== "person") notThere();const member = this.sql.exec<Member>("SELECT * FROM member WHERE database = ? AND left_at IS NULL", caller.database).toArray()[0];if (!member || member.slug !== caller.slug) notThere();if (route.need === "owner" && member.role !== "owner") refuse(403, "owner_only", "Only the owner of this space does that.");if (route.adds && member.role === "see") refuse(403, "see_only", "You can see this space but not add to it. Ask its owner.");if (this.deleted() && !route.whileDeleted) refuse(409, "space_deleted", "This space was deleted; its photos can still be saved until it goes.");if (route.epoch) {const want = route.epoch === "next" ? this.epoch() + 1 : this.epoch();if (ask.body?.epoch !== want) refuse(409, "stale_epoch", `This space is at epoch ${this.epoch()}; open it again and retry.`);if (route.epoch === "current" && !route.duringRekey && this.meta("rekey_due") === "1") refuse(409, "rekey_due", "Someone left: the owner's phone moves the space's key on before anything is added.");if (route.epoch === "current" && this.epoch() < 1) refuse(409, "no_epoch", "The owner's phone has not handed out the space's first key yet."); }return { kind: "member", member }; }privateasync run(route: Route, gated: Gated, caller: Caller, ask: Ask): Promise<unknown> {const body = ask.body ?? {};const query = ask.query ?? {};if (gated.kind === "founder") returnthis.found(caller asExtract<Caller, { kind: "person" }>, ask.space, body);if (gated.kind === "link") {if (route.name === "link.read") returnthis.linkRead(gated.link, body);if (route.name === "link.media") returnthis.media(body, ask.base, gated.link.album); refuse(NOT_THERE.status, NOT_THERE.code, NOT_THERE.message); }const me = gated.member;switch (route.name asRouteName) {case"space.read":returnthis.read(me);case"roster.list":returnthis.rosterList(query);case"roster.drop":returnthis.dropStatement(body);case"roster.add":// The statement itself was the act (an owner's claim after an erase, say); it is in the chain already.if (body.statement === undefined) refuse(400, "bad_statement", "statement: the one to record");return { ok: true, head: this.rosterHead() };case"records.list":returnthis.list(query, me, null);case"records.put":returnthis.put(me, body);case"records.rewrap":returnthis.rewrap(me, body);case"records.delete":returnthis.remove(me, body);case"records.stale":returnthis.stale(query);case"upload":returnthis.upload(me, body, ask.base);case"media":returnthis.media(body, ask.base, null);case"members.add":returnthis.addMembers(me, body);case"roles.set":returnthis.setRole(me, body);case"wraps.add":returnthis.addWraps(body);case"epoch":returnthis.moveEpoch(me, body);case"keep":returnthis.keep(me, body);case"leave":awaitthis.leave(me, true);return { ok: true };case"space.delete":returnthis.deleteSpace(me);case"links.make":returnthis.makeLink(me, body);case"links.stop":returnthis.stopLink(body);default: refuse(NOT_THERE.status, NOT_THERE.code, NOT_THERE.message); } }// ── founding and members ──────────────────────────────────────────────/** Each newcomer's own object takes them in and says who they are; any refusal undoes the ones taken in this call. */privateasync takeIn(space: string, from: string, numbers: string[], founder: { slug: string; database: string } | null, app: string): Promise<Taken[]> {const taken: Taken[] = [];const serial = (): number => {const next = Number(this.meta("serial") ?? "0") + 1;this.setMeta("serial", next);return next; };try {if (founder) {const s = serial();const answer = await personObject(this.env, founder.slug).spaceJoin(space, from, true, s, app);if ("refused"in answer) refuseJoin(answer.refused, true); taken.push({ slug: founder.slug, identity: answer.ok, number: from, serial: s });if (answer.ok.database !== founder.database) refuse(403, "not_your_person", "That sign-in is not this number's database."); }for (const number of numbers) {const slug = await directory(this.env).lookup(number);if (!slug) refuse(403, "not_your_person", "A space is shared only with your people: someone you both accepted on Cotton.");const s = serial();const answer = await personObject(this.env, slug).spaceJoin(space, from, false, s, app);if ("refused"in answer) refuseJoin(answer.refused, false); taken.push({ slug, identity: answer.ok, number, serial: s }); }return taken; } catch (error) {for (const t of taken) awaitthis.tellOut(t.slug, space, t.serial);throw error; } }privateasync found(caller: Extract<Caller, { kind: "person" }>, space: string, body: Record<string, unknown>): Promise<unknown> {const numbers = numbersOf(body.members, caller.number);const app = body.app ?? "albums";if (typeof app !== "string" || !Object.hasOwn(APPS, app)) refuse(400, "bad_app", `app: one of ${Object.keys(APPS).join(", ")}`);if (numbers.length + 1 > LIMITS.members) refuse(400, "too_many_members", `a space holds at most ${LIMITS.members} members`);const peers = numbers.length ? await personObject(this.env, caller.slug).spacePeers(numbers) : [];if (numbers.some((n) => !peers.includes(n))) refuse(403, "not_your_person", "A space is shared only with your people: someone you both accepted on Cotton.");this.sql.exec(SCHEMA);this.sql.exec(TALLIES);this.setMeta("tally_v", 1);const taken = awaitthis.takeIn(space, caller.number, numbers, { slug: caller.slug, database: caller.database }, app);const now = Date.now();this.setMeta("app", app);this.setMeta("epoch", 0);this.setMeta("state", "live");this.setMeta("founded_at", now);this.setMeta("seq", 0);const see = seeOf(body.see, numbers); taken.forEach((t, i) => this.insertMember(t, i === 0 ? "owner" : see.has(t.number) ? "see" : "member", now + i));this.setMeta("id", space);const founder = this.sql.exec<Member>("SELECT * FROM member WHERE database = ?", caller.database).one();return { ok: true, ...(awaitthis.read(founder)) }; }private insertMember(t: Taken, role: Member["role"], at: number): void {this.sql.exec(`INSERT INTO member (id, database, number, slug, key, sign, name, role, joined_at, left_at, cursor, serial) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, 0, ?) ON CONFLICT (database) DO UPDATE SET number = excluded.number, slug = excluded.slug, key = excluded.key, sign = excluded.sign, name = excluded.name, role = excluded.role, joined_at = excluded.joined_at, left_at = NULL, cursor = 0, serial = excluded.serial`, freshMemberId(), t.identity.database, t.number, t.slug, t.identity.key, t.identity.sign, t.identity.name, role, at, t.serial, ); }/** The owner adds their own people; each newcomer's own object must take them in (and gives their keys). */privateasync addMembers(me: Member, body: Record<string, unknown>): Promise<unknown> {const numbers = numbersOf(body.numbers, me.number);if (!numbers.length) refuse(400, "bad_members", "numbers: at least one");const activeNumbers = newSet(this.active().map((m) => m.number));if (numbers.some((n) => activeNumbers.has(n))) refuse(409, "already_member", "already a member");if (this.active().length + numbers.length > LIMITS.members) refuse(400, "too_many_members", `a space holds at most ${LIMITS.members} members`);const peers = await personObject(this.env, me.slug).spacePeers(numbers);if (numbers.some((n) => !peers.includes(n))) refuse(403, "not_your_person", "A space is shared only with your people: someone you both accepted on Cotton.");const taken = awaitthis.takeIn(this.space(), me.number, numbers, null, this.app());// Checked again after the awaits: two calls at once must not pass the cap, or add one person twice.const nowActive = this.active();if (nowActive.length + taken.length > LIMITS.members || taken.some((t) => nowActive.some((m) => m.number === t.number))) {for (const t of taken) awaitthis.tellOut(t.slug, this.space(), t.serial); refuse(409, "changed_meanwhile", "The members changed meanwhile; read the space again and retry."); }const now = Date.now();const role = roleOf(body.role ?? "add"); taken.forEach((t, i) => this.insertMember(t, role, now + i));// Who still needs a wrap of the current key (`unwrapped`): the owner's phone hands them out next (POST wraps).return { ok: true, ...(awaitthis.read(me)) }; }/** The owner says what a member may do: add, or only see. The owner's own role moves only by a handover. */privateasync setRole(me: Member, body: Record<string, unknown>): Promise<unknown> {const member = typeof body.member === "string" ? this.memberById(body.member) : null;if (!member || member.left_at !== null) refuse(404, "no_member", "No such member.");if (member.role === "owner") refuse(409, "owner_role", "The owner's role changes only when ownership is handed over.");this.sql.exec("UPDATE member SET role = ? WHERE id = ?", roleOf(body.role), member.id);return { ok: true, ...(awaitthis.read(me)) }; }/** The owner's phone hands the current key to members who have none yet. */private addWraps(body: Record<string, unknown>): unknown {const wraps = wrapsOf(body.wraps, "wraps");const epoch = this.epoch();for (const holder ofObject.keys(wraps)) {const m = this.memberById(holder);if (!m || m.left_at !== null) refuse(400, "bad_wraps", "a wrap for someone not a member");if (this.sql.exec("SELECT 1 FROM wrap WHERE epoch = ? AND holder = ?", epoch, holder).toArray().length) refuse(409, "bad_wraps", "that member holds the current key already"); }for (const [holder, wrap] ofObject.entries(wraps)) this.sql.exec("INSERT INTO wrap (epoch, holder, wrap) VALUES (?, ?, ?)", epoch, holder, wrap);return { ok: true, epoch }; }// ── reading ───────────────────────────────────────────────────────────privateasync read(me: Member): Promise<Record<string, unknown>> {const now = Date.now();const active = this.active();// A member sees another's number only when that person is already theirs; names otherwise.const others = active.filter((m) => m.id !== me.id).map((m) => m.number);const known = newSet(others.length ? await personObject(this.env, me.slug).spacePeers(others) : []);const epoch = this.epoch();const wrapped = newSet(this.sql.exec<{ holder: string }>("SELECT holder FROM wrap WHERE epoch = ?", epoch).toArray().map((w) => w.holder));const members = active.map((m) => ({ member: m.id, name: m.name, key: m.key, sign: m.sign, role: m.role === "member" ? "add" : m.role, serial: m.serial, joined_at: m.joined_at, you: m.id === me.id, ...(m.id === me.id || known.has(m.number) ? { number: m.number } : {}), }));const left = this.sql .exec<{ id: string; name: string | null; sign: string | null; left_at: number }>("SELECT id, name, sign, left_at FROM member WHERE left_at IS NOT NULL ORDER BY left_at") .toArray() .map((m) => ({ member: m.id, name: m.name, sign: m.sign, left_at: m.left_at, leaves_at: m.left_at + LEAVE_MS }));const wraps: Record<string, Record<string, string>> = {};for (const w ofthis.sql.exec<{ epoch: number; holder: string; wrap: string }>("SELECT epoch, holder, wrap FROM wrap ORDER BY epoch").toArray()) { (wraps[String(w.epoch)] ??= {})[w.holder] = w.wrap; }const links = this.liveLinks(now).map((l) => ({ link: l.id, album: l.album, public: l.public_key, expires_at: l.expires, made_by: l.made_by }));const bytes: Record<string, number> = {};for (const b ofthis.tallies()) bytes[b.adder] = b.n;const deleted = this.deleted() ? { by: this.meta("deleted_by"), at: Number(this.meta("deleted_at")), erase_at: Number(this.meta("deleted_at")) + LEAVE_MS } : null;return { space: this.space(), app: this.app(), me: me.id, epoch, rekey_due: this.meta("rekey_due") === "1", roster: this.rosterHead(), unwrapped: active.filter((m) => !wrapped.has(m.id)).map((m) => m.id), deleted, members, left, wraps, links, bytes, }; }/** Records since a cursor: a member's view (with the adder and signature), or a link's (no member at all). */private list(query: Record<string, string>, me: Member | null, album: string | null): Record<string, unknown> {const after = Math.max(0, Number(query.after ?? "0") || 0);const limit = Math.min(LIMITS.listPage, Math.max(1, Number(query.limit ?? LIMITS.listPage) || LIMITS.listPage));if (me && after > me.cursor) {this.sql.exec("UPDATE member SET cursor = ? WHERE id = ?", after, me.id);// A deletion every member has read past is told to nobody again.this.sql.exec("DELETE FROM record WHERE deleted = 1 AND seq <= (SELECT MIN(cursor) FROM member WHERE left_at IS NULL)"); }const rows = album ? this.sql.exec<RecordRow>("SELECT * FROM record WHERE seq > ? AND (album = ? OR (kind = 'album' AND id = ?)) ORDER BY seq LIMIT ?", after, album, album, limit + 1).toArray() : this.sql.exec<RecordRow>("SELECT * FROM record WHERE seq > ? ORDER BY seq LIMIT ?", after, limit + 1).toArray();const more = rows.length > limit;const page = rows.slice(0, limit);const records = page.filter((r) => !r.deleted).map((r) => (me ? shown(r) : seenByLink(r)));const gone = page.filter((r) => r.deleted);const deleted = gone.map((r) => r.id);// Each deletion's signature, for the phones to check (none for what the thirty-day sweep took).const tombs = me ? Object.fromEntries(gone.filter((r) => r.tomb).map((r) => [r.id, { version: r.version, sig: r.tomb, by: r.tomb_by }])) : undefined;return { records, deleted, ...(tombs ? { tombs } : {}), next: page.length ? page[page.length - 1]!.seq : after, more }; }private stale(query: Record<string, string>): unknown {const limit = Math.min(LIMITS.listPage, Math.max(1, Number(query.limit ?? LIMITS.listPage) || LIMITS.listPage));const rows = this.sql.exec<RecordRow>("SELECT * FROM record WHERE deleted = 0 AND epoch < ? ORDER BY epoch, seq LIMIT ?", this.epoch(), limit).toArray();const left = this.liveBefore(this.epoch());return { epoch: this.epoch(), records: rows.map(shown), left }; }// ── writing records ───────────────────────────────────────────────────/** A member writes their OWN records: a new one, or a new body for one they added. Nobody rewrites another's. */privateasync put(me: Member, body: Record<string, unknown>): Promise<unknown> {const items = Array.isArray(body.records) ? body.records : refuse(400, "bad_records", "records: a list");if (items.length > LIMITS.perCall) refuse(400, "too_many", `at most ${LIMITS.perCall} records a call`);const epoch = this.epoch();const now = Date.now();const checked = items.map((raw) => recordOf(raw, epoch, this.app()));const ids = newSet<string>();for (const r of checked) {if (ids.has(r.id)) refuse(400, "bad_records", "a record twice in one call"); ids.add(r.id); }// Every check before any write: a call lands whole or not at all.const plans: { r: ReturnType<typeof recordOf>; was: RecordRow | null; added: string[]; dropped: string[]; bytes: number }[] = [];let fresh = 0;let delta = 0;for (const r of checked) {const was = this.sql.exec<RecordRow>("SELECT * FROM record WHERE id = ?", r.id).toArray()[0] ?? null;if (was?.deleted) refuse(409, "record_gone", "a deleted record's id is not used again");if (was && was.adder !== me.id) refuse(403, "not_yours", "Only who added a record changes it.");if (was && was.kind !== r.kind) refuse(409, "bad_records", "a record keeps its kind");if (r.version !== (was ? was.version + 1 : 1)) refuse(409, "bad_version", `a record's next version is ${was ? was.version + 1 : 1}`);if (!was) fresh += 1;const before = was ? (JSON.parse(was.files) as string[]) : [];const added = r.files.filter((f) => !before.includes(f));const dropped = before.filter((f) => !r.files.includes(f));for (const f of added) {const file = this.sql.exec<FileRow>("SELECT * FROM file WHERE id = ?", f).toArray()[0];if (!file || file.adder !== me.id || file.record !== null || file.state !== "uploaded") refuse(409, "bad_file", "a record names only files its writer uploaded whole to this space and no other record names");const held = awaitthis.env.MEDIA.head(fileAt(this.space(), f));if (!held || held.size !== file.size) refuse(409, "file_missing", "a file the record names has not been uploaded whole"); }const bytes = r.body.length + r.sig.length + KEY_ALLOWANCE; delta += bytes - (was?.bytes ?? 0); plans.push({ r, was, added, dropped, bytes }); }const count = this.liveBefore(Number.MAX_SAFE_INTEGER);if (count + fresh > LIMITS.records) refuse(413, "space_records_full", `a space holds at most ${LIMITS.records} records`);// The sealed text counts to its adder as the photos do.if (delta > 0 && !(awaitthis.charge(me, delta))) refuse(413, SPACE_FULL, SPACE_FULL_WORDS);// The awaits above let another call in: everything checked is checked again before a write, and the writes below// run with no await between them (SHARED SPACE 3: two members putting one new id both passed the first check).// The key may have moved while this call waited: what it sealed is under the old key, so it seals again.if (this.epoch() !== epoch) {if (delta > 0) awaitthis.refund(me.slug, delta); refuse(409, "key_moved", "The space's key moved on while this was sent; seal it again."); }const moved = plans.some(({ r, was, added }) => {const now = this.sql.exec<RecordRow>("SELECT * FROM record WHERE id = ?", r.id).toArray()[0] ?? null;const recordMoved = was ? !now || now.deleted === 1 || now.adder !== me.id || now.seq !== was.seq : now !== null;const fileMoved = added.some((f) => {const file = this.sql.exec<FileRow>("SELECT * FROM file WHERE id = ?", f).toArray()[0];return !file || file.adder !== me.id || file.record !== null || file.state !== "uploaded"; });return recordMoved || fileMoved; });if (moved) {if (delta > 0) awaitthis.refund(me.slug, delta); refuse(409, "changed_meanwhile", "Something in this call changed while it was checked; read the space again and retry."); }for (const { r, added, bytes } of plans) {this.sql.exec(`INSERT INTO record (id, kind, album, adder, epoch, key, body, sig, signer, signer_key, files, bytes, seq, at, deleted, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?) ON CONFLICT (id) DO UPDATE SET album = excluded.album, epoch = excluded.epoch, key = excluded.key, body = excluded.body, sig = excluded.sig, signer = excluded.signer, signer_key = excluded.signer_key, files = excluded.files, bytes = excluded.bytes, seq = excluded.seq, at = excluded.at, version = excluded.version WHERE record.adder = excluded.adder AND record.deleted = 0`, r.id, r.kind, r.album, me.id, epoch, r.key, r.body, r.sig, me.id, me.sign, JSON.stringify(r.files), bytes,this.nextSeq(), now, r.version, );for (const f of added) this.sql.exec("UPDATE file SET state = 'stored', record = ? WHERE id = ?", r.id, f); }for (const { dropped } of plans) for (const f of dropped) awaitthis.dropFile(f);if (delta < 0) awaitthis.refund(me.slug, -delta);this.dropOldWraps();return { ok: true, epoch, seq: Number(this.meta("seq")) }; }/** * On an epoch move a record's KEY is wrapped again at the new epoch; its body, signature, files and album never * change here (re-wrapped, never re-contented). By its adder, or by the owner for anyone's. */private rewrap(me: Member, body: Record<string, unknown>): unknown {const items = Array.isArray(body.records) ? body.records : refuse(400, "bad_records", "records: a list of { id, key }");if (items.length > LIMITS.perCall) refuse(400, "too_many", `at most ${LIMITS.perCall} records a call`);const epoch = this.epoch();const plans: { id: string; key: string }[] = [];for (const raw of items) {const item = raw asRecord<string, unknown>;const id = typeof item?.id === "string" && RECORD_ID.test(item.id) ? item.id : refuse(400, "bad_records", "a record's id");const key = typeof item.key === "string" ? item.key : refuse(400, "bad_records", "a record's key");const m = RECORD_KEY.exec(key);if (!m) refuse(400, "bad_records", "a record's key, wrapped in the space (g1:)");if (Number(m[1]) !== epoch) refuse(409, "stale_epoch", `a key is wrapped at the current epoch (${epoch})`);const was = this.sql.exec<RecordRow>("SELECT * FROM record WHERE id = ? AND deleted = 0", id).toArray()[0];if (!was) refuse(404, "no_record", "no such record");if (was.adder !== me.id && me.role !== "owner") refuse(403, "not_yours", "A record is wrapped again by its adder or the owner.");if (was.epoch >= epoch) refuse(409, "not_stale", "that record is at the current epoch already"); plans.push({ id, key }); }for (const p of plans) this.sql.exec("UPDATE record SET key = ?, epoch = ?, seq = ?, at = ? WHERE id = ?", p.key, epoch, this.nextSeq(), Date.now(), p.id);this.dropOldWraps();return { ok: true, epoch, left: this.liveBefore(epoch) }; }/** * Records go: by their adder or the owner, each with the phone's signed deletion (`tombs`: id → {version, sig}), * which the space keeps for the other phones to check. Every row is marked gone before any wait, so two deletions * at once refund once. */privateasync remove(me: Member, body: Record<string, unknown>): Promise<unknown> {const ids = Array.isArray(body.ids) ? body.ids : refuse(400, "bad_records", "ids: a list");if (ids.length > LIMITS.perCall) refuse(400, "too_many", `at most ${LIMITS.perCall} records a call`);const tombs = body.tombs && typeof body.tombs === "object" ? (body.tombs asRecord<string, { version?: unknown; sig?: unknown }>) : {};const rows: RecordRow[] = [];for (const id of ids) {if (typeof id !== "string" || !RECORD_ID.test(id)) refuse(400, "bad_records", "an id");const row = this.sql.exec<RecordRow>("SELECT * FROM record WHERE id = ? AND deleted = 0", id).toArray()[0];if (!row) continue;if (row.adder !== me.id && me.role !== "owner") refuse(403, "not_yours", "Only who added a record, or the owner, deletes it.");const tomb = tombs[id];if (tomb !== undefined && (tomb.version !== row.version + 1 || typeof tomb.sig !== "string" || !SIG.test(tomb.sig))) refuse(400, "bad_tomb", `a deletion names the record's next version (${row.version + 1}) and is signed (s1:)`); rows.push(row); }let done = 0;for (const row of rows) {const tomb = tombs[row.id];if (awaitthis.tombstone(row.id, null, tomb ? { sig: tomb.sig as string, by: me.id } : null)) done += 1; }return { ok: true, deleted: done }; }/** * One record marked gone, read again and changed with no wait between (only if it is still there and, when `adder` * is named, still theirs), then its files dropped and its bytes refunded to whoever holds it NOW. False when it was * gone already (another call took it). */privateasync tombstone(id: string, adder: string | null, tomb: { sig: string; by: string } | null): Promise<boolean> {const row = this.sql.exec<RecordRow>("SELECT * FROM record WHERE id = ? AND deleted = 0", id).toArray()[0];if (!row || (adder !== null && row.adder !== adder)) returnfalse;this.sql.exec("UPDATE record SET deleted = 1, key = NULL, body = NULL, sig = NULL, signer = NULL, signer_key = NULL, files = '[]', bytes = 0, seq = ?, at = ?, version = version + ?, tomb = ?, tomb_by = ? WHERE id = ?",this.nextSeq(),Date.now(), tomb ? 1 : 0, tomb?.sig ?? null, tomb?.by ?? null, id, );// Who is refunded is read now, before any wait: the sweep may delete their member row meanwhile.const slug = this.memberById(row.adder)?.slug ?? null;const files = (JSON.parse(row.files) as string[]).map((f) => this.takeFileRow(f)).filter((f): f is FileRow & { slug: string | null } => f !== null);for (const f of files) awaitthis.dropTaken(f);if (row.bytes > 0 && slug) awaitthis.refund(slug, row.bytes);returntrue; }/** A file's row taken out with no wait (so a second caller finds nothing to refund); null when it was gone. */private takeFileRow(id: string): (FileRow & { slug: string | null }) | null {const file = this.sql.exec<FileRow>("SELECT * FROM file WHERE id = ?", id).toArray()[0];if (!file) returnnull;this.sql.exec("DELETE FROM file WHERE id = ?", id);return { ...file, slug: this.memberById(file.adder)?.slug ?? null }; }/** A taken file's bytes go from R2 and its adder (read when it was taken) is refunded. */privateasync dropTaken(file: FileRow & { slug: string | null }): Promise<void> {awaitthis.env.MEDIA.delete(fileAt(this.space(), file.id));if (file.slug) awaitthis.refund(file.slug, file.size); }/** A file goes from R2 and its adder is refunded, once. */privateasync dropFile(id: string): Promise<void> {const file = this.takeFileRow(id);if (file) awaitthis.dropTaken(file); }/** An epoch's wraps go once no record is keyed at it (the current epoch's always stay). */private dropOldWraps(): void {this.sql.exec("DELETE FROM wrap WHERE epoch < ? AND epoch NOT IN (SELECT epoch FROM epoch_live WHERE n > 0)", this.epoch()); }// ── bytes ─────────────────────────────────────────────────────────────privateasync upload(me: Member, body: Record<string, unknown>, base: string): Promise<unknown> {const size = body.size;if (typeof size !== "number" || !Number.isInteger(size) || size <= 0) refuse(400, "bad_size", "size: the sealed file's length in bytes");if (size > LIMITS.fileBytes) refuse(413, "too_big", `a file is at most ${LIMITS.fileBytes / 1024 / 1024} MB`);const now = Date.now();const hour = this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM file WHERE adder = ? AND at > ?", me.id, now - 3_600_000).one().n;if (hour >= LIMITS.uploadsPerHour) refuse(429, "slow_down", "Too many uploads to this space in an hour; carry on later.");if (!(awaitthis.charge(me, size))) refuse(413, SPACE_FULL, SPACE_FULL_WORDS);const file = freshId();this.sql.exec("INSERT INTO file (id, adder, size, state, record, at) VALUES (?, ?, ?, 'reserved', NULL, ?)", file, me.id, size, now);const expires = Math.floor((now + WRITE_LIFE_MS) / 1000);awaitthis.wake(now + WRITE_LIFE_MS + 60_000);return { file, url: `${base}${mediaPath(await mint(this.env, "w", this.space(), file, size, expires), this.space(), file)}`, expires_at: expires * 1000 }; }/** * The door asks before it writes a PUT: true once, for a file granted and not yet uploaded, of this length. A write * URL is single-use: a second PUT, or a PUT for a file whose row has gone, is refused before a byte is written. */async claim(file: string, size: number): Promise<boolean> {if (!spacesOn() || !this.exists() || this.ending() || this.deleted() || !FILE_ID.test(file)) returnfalse;const row = this.sql.exec<FileRow>("SELECT * FROM file WHERE id = ?", file).toArray()[0];if (!row || row.state !== "reserved" || row.size !== size) returnfalse;this.sql.exec("UPDATE file SET state = 'claimed' WHERE id = ?", file);returntrue; }/** The door says a claimed PUT landed whole: the file may now be named by a record. */async landed(file: string, size: number): Promise<boolean> {if (!this.exists()) returnfalse;const row = this.sql.exec<FileRow>("SELECT * FROM file WHERE id = ?", file).toArray()[0];if (!row || row.state !== "claimed" || row.size !== size) returnfalse;this.sql.exec("UPDATE file SET state = 'uploaded' WHERE id = ?", file);returntrue; }privateasync media(body: Record<string, unknown>, base: string, album: string | null): Promise<unknown> {const files = Array.isArray(body.files) ? body.files : refuse(400, "bad_files", "files: a list of file ids");if (files.length > LIMITS.listPage) refuse(400, "too_many", `at most ${LIMITS.listPage} files a call`);const expires = Math.floor((Date.now() + READ_LIFE_MS) / 1000);const space = this.space();const urls: Record<string, string> = {};for (const f of files) {if (typeof f !== "string" || !FILE_ID.test(f)) continue;const row = album ? this.sql.exec("SELECT 1 FROM file JOIN record ON record.id = file.record WHERE file.id = ? AND file.state = 'stored' AND record.deleted = 0 AND (record.album = ? OR (record.kind = 'album' AND record.id = ?))", f, album, album).toArray()[0] : this.sql.exec("SELECT 1 FROM file WHERE id = ? AND state = 'stored'", f).toArray()[0];if (!row) continue; urls[f] = `${base}${mediaPath(await mint(this.env, "r", space, f, null, expires), space, f)}`; }return { urls, expires_at: expires * 1000 }; }/** The member's own object counts the bytes against their space; false when they would not fit. */privateasync charge(member: Member, delta: number): Promise<boolean> {return personObject(this.env, member.slug).spaceCharge(this.space(), delta); }/** A refund, tried now and kept in the outbox until the object takes it. */privateasync refund(slug: string, bytes: number): Promise<void> {if (bytes <= 0) return;try {if (await personObject(this.env, slug).spaceCharge(this.space(), -bytes)) return; } catch {// Kept below and tried again. }awaitthis.queue("refund", slug, -bytes); }/** A member's object told they are out of the membership `serial` names, now or by the outbox. */privateasync tellOut(slug: string, space: string, serial: number): Promise<void> {try {if (await personObject(this.env, slug).spaceLeft(space, serial)) return; } catch {// Kept below and tried again. }awaitthis.queue("left", slug, serial); }privateasync queue(kind: Outbox["kind"], slug: string, delta: number): Promise<void> {const now = Date.now();this.sql.exec("INSERT INTO outbox (kind, slug, delta, tries, next_at) VALUES (?, ?, ?, 0, ?)", kind, slug, delta, now + 60_000);awaitthis.wake(now + 60_000); }// ── epochs, leaving, keeping ──────────────────────────────────────────/** * The owner moves the epoch: the new key wrapped to every member who stays. Members named in `remove` are out; every * link they made stops; any other live link is kept only when `link_wraps` wraps it again, and stops otherwise. */privateasync moveEpoch(me: Member, body: Record<string, unknown>): Promise<unknown> {const remove = Array.isArray(body.remove) ? (body.remove as unknown[]) : [];const wraps = wrapsOf(body.wraps, "wraps");const linkWraps = wrapsOf(body.link_wraps ?? {}, "link_wraps");const now = Date.now();// What was due when this move began: a leave or a stopped link during it keeps the epoch due (SHARED 4).const dueAtStart = this.meta("due_count") ?? "0";const out = newSet<string>();for (const id of remove) {const m = typeof id === "string" ? this.memberById(id) : null;if (!m || m.left_at !== null) refuse(400, "bad_members", "remove: members of this space");if (m.id === me.id) refuse(400, "bad_members", "the owner leaves by leaving"); out.add(m.id); }const staying = this.active().filter((m) => !out.has(m.id));const holders = newSet(Object.keys(wraps));if (holders.size !== staying.length || staying.some((m) => !holders.has(m.id))) refuse(400, "bad_wraps", "a wrap of the new key for every member who stays, and no one else");const live = this.liveLinks(now).filter((l) => !out.has(l.made_by));for (const id ofObject.keys(linkWraps)) if (!live.some((l) => l.id === id)) refuse(400, "bad_wraps", "a link wrap for a link that is not live, or whose maker is removed");const epoch = this.epoch() + 1;this.setMeta("epoch", epoch);for (const [holder, wrap] ofObject.entries(wraps)) this.sql.exec("INSERT INTO wrap (epoch, holder, wrap) VALUES (?, ?, ?)", epoch, holder, wrap);for (const l ofthis.liveLinks(now)) {const wrap = linkWraps[l.id];if (wrap) this.sql.exec("INSERT INTO wrap (epoch, holder, wrap) VALUES (?, ?, ?)", epoch, `link:${l.id}`, wrap);elsethis.stop(l.id, false); }for (const id of out) awaitthis.depart(this.memberById(id)!, true);// Everything this move stopped is keyed anew by it; anything that fell due while it ran is not.if ((this.meta("due_count") ?? "0") === dueAtStart) this.setMeta("rekey_due", null);this.dropOldWraps();return { ok: true, epoch, stale: this.liveBefore(epoch) }; }/** Out at once: their links stop, their object is told (unless it is the one erasing), the thirty days start. */privateasync depart(m: Member, tellThem: boolean): Promise<void> {const now = Date.now();this.sql.exec("UPDATE member SET left_at = ?, role = 'member' WHERE id = ? AND left_at IS NULL", now, m.id);for (const l ofthis.sql.exec<{ id: string }>("SELECT id FROM link WHERE made_by = ? AND stopped = 0", m.id).toArray()) this.stop(l.id);if (tellThem) awaitthis.tellOut(m.slug, this.space(), m.serial);awaitthis.wake(now + LEAVE_MS); }/** A member leaves (or their account is erased): out at once, the epoch due to move; the last one out ends the space. */privateasync leave(m: Member, tellThem: boolean): Promise<void> {const now = Date.now();awaitthis.depart(m, tellThem);if (!this.active().length) {// A deleted space keeps its own date; any other is ending from now.if (!this.deleted()) this.setMeta("state", "ending");this.setMeta("ending_at", now);this.sql.exec("UPDATE link SET stopped = 1");this.sql.exec("DELETE FROM wrap WHERE holder LIKE 'link:%'"); } else {this.markDue();this.succeed(); } }/** When no owner is left, the member who has been in longest becomes it. */private succeed(): void {const active = this.active();if (active.length && !active.some((m) => m.role === "owner")) this.sql.exec("UPDATE member SET role = 'owner' WHERE id = ?", active[0]!.id); }/** * Keep them: the records a departed member added move to the member who taps it. The bytes stay where they are and * count to that member from now on (refused `space_full` when they do not fit), and the departed member is refunded. */privateasync keep(me: Member, body: Record<string, unknown>): Promise<unknown> {const id = typeof body.member === "string" && MEMBER_ID.test(body.member) ? body.member : refuse(400, "bad_members", "member: whose photos to keep");const gone = this.sql.exec<Member>("SELECT * FROM member WHERE id = ? AND left_at IS NOT NULL", id).toArray()[0];if (!gone) refuse(404, "nothing_to_keep", "Nothing of theirs is leaving this space.");// Moved to the keeper before any wait (SHARED 4): a second Keep, or the sweep, finds nothing of theirs left; the// bytes are counted from what actually moved.const files = this.sql.exec<{ id: string; size: number }>("SELECT id, size FROM file WHERE adder = ? AND state = 'stored'", id).toArray();const records = this.sql.exec<{ id: string; bytes: number; seq: number }>("SELECT id, bytes, seq FROM record WHERE adder = ? AND deleted = 0", id).toArray();if (!files.length && !records.length) return { ok: true, records: 0, bytes: 0 };const bytes = files.reduce((n, f) => n + f.size, 0) + records.reduce((n, r) => n + r.bytes, 0);for (const f of files) this.sql.exec("UPDATE file SET adder = ? WHERE id = ?", me.id, f.id);const seqs = newMap<string, number>();for (const r of records) {const seq = this.nextSeq(); seqs.set(r.id, seq);this.sql.exec("UPDATE record SET adder = ?, seq = ?, at = ? WHERE id = ?", me.id, seq, Date.now(), r.id); }if (bytes > 0 && !(awaitthis.charge(me, bytes))) {// Not taken: what is still as this Keep left it goes back to them.for (const f of files) this.sql.exec("UPDATE file SET adder = ? WHERE id = ? AND adder = ?", id, f.id, me.id);for (const r of records) this.sql.exec("UPDATE record SET adder = ? WHERE id = ? AND adder = ? AND seq = ?", id, r.id, me.id, seqs.get(r.id)!); refuse(413, SPACE_FULL, SPACE_FULL_WORDS); }awaitthis.refund(gone.slug, bytes);return { ok: true, records: records.length, bytes }; }/** The owner deletes the space: links stop, members still read and save for thirty days, then the alarm erases it. */privateasync deleteSpace(me: Member): Promise<unknown> {const now = Date.now();this.setMeta("state", "deleted");this.setMeta("deleted_at", now);this.setMeta("deleted_by", me.id);this.sql.exec("UPDATE link SET stopped = 1");this.sql.exec("DELETE FROM wrap WHERE holder LIKE 'link:%'");awaitthis.wake(now + LEAVE_MS);return { ok: true, erase_at: now + LEAVE_MS }; }// ── links ─────────────────────────────────────────────────────────────privateasync makeLink(me: Member, body: Record<string, unknown>): Promise<unknown> {const now = Date.now();const id = typeof body.link === "string" && LINK_ID.test(body.link) ? body.link : refuse(400, "bad_link", "link: its id");const album = typeof body.album === "string" && RECORD_ID.test(body.album) ? body.album : refuse(400, "bad_link", "album: the album it opens");const pub = typeof body.public === "string" && KEY.test(body.public) ? body.public : refuse(400, "bad_link", "public: the link's public key");const hash = typeof body.auth_hash === "string" && HASH.test(body.auth_hash) ? body.auth_hash : refuse(400, "bad_link", "auth_hash: sha256 of its auth token, hex");const wrap = typeof body.wrap === "string" && WRAP.test(body.wrap) ? body.wrap : refuse(400, "bad_link", "wrap: the epoch key wrapped to the link");const days = body.days ?? LIMITS.linkDays;if (typeof days !== "number" || !Number.isInteger(days) || days < 1 || days > LIMITS.linkDays) refuse(400, "bad_link", `days: 1 to ${LIMITS.linkDays}`);if (this.sql.exec("SELECT 1 FROM link WHERE id = ?", id).toArray().length) refuse(409, "link_exists", "a link with this id is here already");if (this.liveLinks(now).length >= LIMITS.links) refuse(429, "too_many_links", `a space has at most ${LIMITS.links} live links`);const expires = now + days * 24 * 3_600_000;this.sql.exec("INSERT INTO link (id, album, public_key, auth_hash, expires, stopped, made_by) VALUES (?, ?, ?, ?, ?, 0, ?)", id, album, pub, hash, expires, me.id);this.sql.exec("INSERT INTO wrap (epoch, holder, wrap) VALUES (?, ?, ?)", this.epoch(), `link:${id}`, wrap);awaitthis.wake(expires + 1000);return { ok: true, link: id, expires_at: expires }; }/** A link stops at once; the epoch is then due, so what it could open is keyed anew. */private stop(id: string, due = true): void {this.sql.exec("UPDATE link SET stopped = 1 WHERE id = ?", id);this.sql.exec("DELETE FROM wrap WHERE holder = ?", `link:${id}`);if (due) this.markDue(); }private stopLink(body: Record<string, unknown>): unknown {const id = typeof body.link === "string" && LINK_ID.test(body.link) ? body.link : refuse(400, "bad_link", "link: its id");this.stop(id);return { ok: true }; }/** A link's view: its own wraps and its album's records, with no member, number, name or signature in it. */private linkRead(link: LinkRow, body: Record<string, unknown>): unknown {const wraps: Record<string, string> = {};for (const w ofthis.sql.exec<{ epoch: number; wrap: string }>("SELECT epoch, wrap FROM wrap WHERE holder = ?", `link:${link.id}`).toArray()) wraps[String(w.epoch)] = w.wrap;const page = this.list({ after: String(body.after ?? "0"), limit: String(body.limit ?? LIMITS.listPage) }, null, link.album);return { space: this.space(), link: link.id, album: link.album, epoch: this.epoch(), expires_at: link.expires, wraps, ...page }; }// ── a member's account erased (src/business.ts, before the directory lets the number go) ──/** The erasing person's object says their database is gone: as leaving. Throws only when the space could not record it. */async gone(database: string): Promise<void> {if (!this.exists()) return;const m = this.sql.exec<Member>("SELECT * FROM member WHERE database = ? AND left_at IS NULL", database).toArray()[0];if (m) awaitthis.leave(m, false); }// ── the sweep ─────────────────────────────────────────────────────────privateasync wake(at: number): Promise<void> {const held = awaitthis.ctx.storage.getAlarm();if (held === null || held > at) awaitthis.ctx.storage.setAlarm(at); } override async alarm(): Promise<void> {if (!this.exists()) return;const now = Date.now();awaitthis.drainOutbox(now);const endsAt = this.endsAt();if (endsAt !== null && endsAt <= now && (awaitthis.erase())) return;// Uploads never named by a record within the hour: gone, refunded.for (const f ofthis.sql.exec<FileRow>("SELECT * FROM file WHERE state <> 'stored' AND at <= ?", now - WRITE_LIFE_MS).toArray()) awaitthis.dropFile(f.id);// Members out for thirty days: what nobody kept goes, refunded to them.for (const m ofthis.sql.exec<Member>("SELECT * FROM member WHERE left_at IS NOT NULL AND left_at <= ?", now - LEAVE_MS).toArray()) {// Each record only if still theirs when its turn comes: a Keep meanwhile takes it out of the sweep.for (const r ofthis.sql.exec<{ id: string }>("SELECT id FROM record WHERE adder = ? AND deleted = 0", m.id).toArray()) awaitthis.tombstone(r.id, m.id, null);for (const f ofthis.sql.exec<{ id: string }>("SELECT id FROM file WHERE adder = ?", m.id).toArray()) {const taken = this.sql.exec<FileRow>("SELECT * FROM file WHERE id = ? AND adder = ?", f.id, m.id).toArray()[0];if (taken) awaitthis.dropFile(taken.id); }this.sql.exec("DELETE FROM member WHERE id = ?", m.id); }// Links past their day.for (const l ofthis.sql.exec<LinkRow>("SELECT * FROM link WHERE expires <= ? OR stopped = 1", now).toArray()) {this.sql.exec("DELETE FROM wrap WHERE holder = ?", `link:${l.id}`);this.sql.exec("DELETE FROM link WHERE id = ?", l.id); }// Bytes under the prefix that no file row names (a PUT that lost its row): gone, once a day.if (Number(this.meta("orphans_at") ?? "0") + ORPHAN_SWEEP_MS <= now) {awaitthis.sweepOrphans();this.setMeta("orphans_at", now); }awaitthis.planAlarm(now); }private endsAt(): number | null {if (this.ending()) returnNumber(this.meta("ending_at")) + LEAVE_MS;if (this.deleted()) returnNumber(this.meta("deleted_at")) + LEAVE_MS;returnnull; }privateasync planAlarm(now: number): Promise<void> {const one = (q: string): number | null => this.sql.exec<{ at: number | null }>(q).one().at;const reserved = one("SELECT MIN(at) AS at FROM file WHERE state <> 'stored'");const departed = one("SELECT MIN(left_at) AS at FROM member WHERE left_at IS NOT NULL");const times = [ reserved === null ? null : reserved + WRITE_LIFE_MS, departed === null ? null : departed + LEAVE_MS, one("SELECT MIN(expires) AS at FROM link"), one("SELECT MIN(next_at) AS at FROM outbox"),this.endsAt(),Number(this.meta("orphans_at") ?? "0") + ORPHAN_SWEEP_MS, ].filter((t): t is number => t !== null);awaitthis.ctx.storage.setAlarm(Math.max(now + 1000, Math.min(...times))); }/** Every told-out and refund the objects did not take yet, tried again; kept, with a longer wait, until taken. */privateasync drainOutbox(now: number): Promise<void> {const space = this.space();for (const o ofthis.sql.exec<Outbox>("SELECT * FROM outbox WHERE next_at <= ? ORDER BY id LIMIT 100", now).toArray()) {let done = false;try {const object = personObject(this.env, o.slug); done = o.kind === "left" ? await object.spaceLeft(space, o.delta) : await object.spaceCharge(space, o.delta); } catch { done = false; }if (done) this.sql.exec("DELETE FROM outbox WHERE id = ?", o.id);elsethis.sql.exec("UPDATE outbox SET tries = tries + 1, next_at = ? WHERE id = ?", Date.now() + Math.min(3_600_000, 60_000 * 2 ** Math.min(o.tries + 1, 10)), o.id); } }privateasync sweepOrphans(): Promise<void> {const space = this.space();const prefix = `spaces/${space}/`;let cursor: string | undefined;do {const page = awaitthis.env.MEDIA.list({ prefix, cursor });const orphans = page.objects.map((o) => o.key).filter((key) => !this.sql.exec("SELECT 1 FROM file WHERE id = ?", key.slice(prefix.length)).toArray().length);if (orphans.length) awaitthis.env.MEDIA.delete(orphans); cursor = page.truncated ? page.cursor : undefined; } while (cursor); }/** Test seam: the orphan sweep now. */async sweepOrphansNow(): Promise<void> {if (this.exists()) awaitthis.sweepOrphans(); }/** * An ended space: each adder refunded what they still had in it and each member's object told it is out (every one * taken, or the erase waits for the outbox and tries again), every byte under its prefix, then its storage. */privateasync erase(): Promise<boolean> {const space = this.space();if (this.meta("erasing") === null) {const owed = newMap<string, number>();for (const r ofthis.tallies()) owed.set(r.adder, r.n);for (const [adder, n] of owed) {const slug = this.memberById(adder)?.slug;if (slug && n > 0) this.sql.exec("INSERT INTO outbox (kind, slug, delta, tries, next_at) VALUES ('refund', ?, ?, 0, 0)", slug, -n); }for (const m ofthis.active()) this.sql.exec("INSERT INTO outbox (kind, slug, delta, tries, next_at) VALUES ('left', ?, ?, 0, 0)", m.slug, m.serial);this.sql.exec("DELETE FROM file");this.sql.exec("UPDATE record SET bytes = 0");this.setMeta("erasing", Date.now());awaitthis.drainOutbox(Date.now()); }if (this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM outbox").one().n > 0) returnfalse;let cursor: string | undefined;do {const page = awaitthis.env.MEDIA.list({ prefix: `spaces/${space}/`, cursor });if (page.objects.length) awaitthis.env.MEDIA.delete(page.objects.map((o) => o.key)); cursor = page.truncated ? page.cursor : undefined; } while (cursor);awaitthis.ctx.storage.deleteAlarm();awaitthis.ctx.storage.deleteAll();returntrue; }}/** A record as a member reads it. */function shown(r: RecordRow): Record<string, unknown> {return { id: r.id, kind: r.kind, album: r.album, adder: r.adder, signer: r.signer, signer_key: r.signer_key, epoch: r.epoch, files: JSON.parse(r.files) as string[], key: r.key, body: r.body, sig: r.sig, seq: r.seq };}/** A record as a link holder reads it: nothing that names who added it. */function seenByLink(r: RecordRow): Record<string, unknown> {return { id: r.id, kind: r.kind, album: r.album, epoch: r.epoch, files: JSON.parse(r.files) as string[], key: r.key, body: r.body, seq: r.seq };}function refuseJoin(why: "not_your_person" | "too_many_spaces" | "no_key", founding: boolean): never {if (why === "too_many_spaces") refuse(429, "too_many_spaces", founding ? `One person founds at most ${LIMITS.founded} spaces.` : "They are in as many spaces as one person may be.");if (why === "no_key") refuse(409, "share_key_not_yet", founding ? "Open Cotton on your phone once more, then share." : "Their phone has not opened Cotton since you connected. Try again once they have."); refuse(403, "not_your_person", "A space is shared only with your people: someone you both accepted on Cotton.");}function recordOf(raw: unknown, epoch: number, app: string): { id: string; kind: string; album: string; files: string[]; key: string; body: string; sig: string; version: number } {const r = raw asRecord<string, unknown>;const bad = (why: string): never => refuse(400, "bad_records", `a record: ${why}`);if (!r || typeof r !== "object") bad("an object");if (typeof r.id !== "string" || !RECORD_ID.test(r.id)) bad("its id");const { kinds, container } = APPS[app] ?? APPS.albums!;if (typeof r.kind !== "string" || !kinds.has(r.kind)) bad(`its kind (${[...kinds].join(", ")})`);if (typeof r.album !== "string" || !RECORD_ID.test(r.album)) bad("its album (the container it is in)");if (r.kind === container && r.album !== r.id) bad(`a ${container} record is its own container`);const files = r.files ?? [];if (!Array.isArray(files) || files.length > LIMITS.filesPerRecord || files.some((f) => typeof f !== "string" || !FILE_ID.test(f)) || newSet(files).size !== files.length) bad(`its files (at most ${LIMITS.filesPerRecord} ids)`);if (typeof r.body !== "string" || r.body.length > LIMITS.recordBytes || !BODY.test(r.body)) bad(`its body, sealed (r1:), at most ${LIMITS.recordBytes} bytes`);if (typeof r.sig !== "string" || !SIG.test(r.sig)) bad("its adder's signature (s1:)");const m = typeof r.key === "string" ? RECORD_KEY.exec(r.key) : null;if (!m) bad("its key, wrapped in the space (g1:)");if (Number(m![1]) !== epoch) refuse(409, "stale_epoch", `a record's key is wrapped at the current epoch (${epoch})`);const version = r.version ?? 1;if (typeof version !== "number" || !Number.isInteger(version) || version < 1 || version > 1_000_000_000) bad("its version (1, 2, …)");return { id: r.id as string, kind: r.kind as string, album: r.album as string, files: files as string[], key: r.key as string, body: r.body as string, sig: r.sig as string, version: version as number };}/** A role a phone names, as the space keeps it: add (kept as member, as every member before SPACES 1) or see. */function roleOf(raw: unknown): "member" | "see" {if (raw === "add") return"member";if (raw === "see") return"see"; refuse(400, "bad_role", "role: add or see");}/** The founding members who only see (`see`: numbers among `members`). */function seeOf(raw: unknown, members: string[]): Set<string> {if (raw === undefined) returnnewSet();if (!Array.isArray(raw) || raw.some((n) => typeof n !== "string" || !members.includes(n))) refuse(400, "bad_members", "see: numbers among members");returnnewSet(raw as string[]);}function numbersOf(raw: unknown, me: string): string[] {const list = raw ?? [];if (!Array.isArray(list)) refuse(400, "bad_members", "a list of numbers");const out: string[] = [];for (const n of list) {if (typeof n !== "string" || !NUMBER.test(n)) refuse(400, "bad_members", "a member is named by their number");if (n !== me && !out.includes(n)) out.push(n); }return out;}function wrapsOf(raw: unknown, what: string): Record<string, string> {if (!raw || typeof raw !== "object" || Array.isArray(raw)) refuse(400, "bad_wraps", `${what}: holder → w1: wrap`);const out: Record<string, string> = {};for (const [holder, wrap] ofObject.entries(raw asRecord<string, unknown>)) {if (typeof wrap !== "string" || !WRAP.test(wrap)) refuse(400, "bad_wraps", `${what}: a w1: wrap`); out[holder] = wrap; }return out;}function b64urlDecode(text: string): Uint8Array {const b64 = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);returnUint8Array.from(atob(b64), (c) => c.charCodeAt(0));}function timingSafeEqual(a: string, b: string): boolean {if (a.length !== b.length) returnfalse;let diff = 0;for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);return diff === 0;}exportfunction personObject(env: Env, slug: string): PersonObject {return env.BUSINESS.get(env.BUSINESS.idFromName(slug), { locationHint: "apac" }) as unknown asPersonObject;}exportfunction spaceObject(env: Env, space: string): DurableObjectStub<Space> {return env.SPACES.get(env.SPACES.idFromName(space), { locationHint: "apac" });}