/** * THE "NEVER AGAIN" LEDGER (RESTORE 2 SERVER 2, coordinator's decision M5, 27 Nov 2026). Some things that happened to * an account must stay true whatever a restore puts back: a table or rows erased for good, a token or a device's * sign-in revoked, a table turned sealed, the account set to be deleted (or kept). A restore (point-in-time or from * snapshots) brings back the state of an earlier moment, and with it those rows, tokens and sessions. So every restore * replays this ledger before the account is unfrozen. * * Where it lives: OUTSIDE what is restored, in R2 beside the restore marker, as numbered chunks * (`_restore//never-again/-.jsonl` in PHOTOS: outside `/`, which is served publicly), never rewritten. Each event is first written in the object's own * outbox table (`never_again_outbox`) in the same transaction as the write it records, then copied out after the * request or on the alarm (`flush`), so nothing is lost to a failed R2 call. A restore copies the outbox out first. * The account delete erases `_restore//` (src/restore.ts `hiddenPrefixes`). * * Every entry replays idempotently, in order, and the newest account-deletion entry wins. */ export type Entry = | { kind: "erase_table"; table: string; version: number; at: string } | { kind: "erase_row"; table: string; id: string; version: number; at: string } | { kind: "row_revoked"; table: string; id: string; at: string } | { kind: "sessions_all_revoked"; at: string } | { kind: "row_expires"; table: string; id: string; expires_at: string; at: string } | { kind: "row_deleted"; table: string; id: string; at: string } | { kind: "row_revived"; table: string; id: string; at: string } | { kind: "session_revoked"; token_hash: string; at: string } | { kind: "meta"; key: string; value: string | null; at: string } | { kind: "account_delete"; started_at: string; erase_at: string | null; by: string; at: string } | { kind: "account_keep"; at: string }; /** * Every entry as kept (RESTORE 2 SERVER 5): `server_at` is the server's own clock when the entry was written, in * milliseconds. `at` is data (a phone may have set it: a device's `revoked_at`, a sync's `updated_at`) and is never * trusted; the fold's age is judged by `server_at` alone, and an entry without a readable one is kept. */ export type Stamped = Entry & { server_at?: number }; const OUTBOX = `CREATE TABLE IF NOT EXISTS never_again_outbox (seq INTEGER PRIMARY KEY AUTOINCREMENT, entry TEXT NOT NULL)`; /** Meta keys whose every value is a ledger entry: the sealing locks (src/memory_lock.ts, src/open_tables_lock.ts). */ export const LEDGER_META = new Set(["memory_lock", "open_tables_lock"]); /** Tables whose rows are revoked by `revoked_at`: a token (an assistant's, OAuth's) and a device. */ export const REVOCABLE = new Set(["mcp_token", "device"]); export const prefixOf = (slug: string): string => `_restore/${slug}/never-again/`; /** An event, written in the object's outbox in the caller's transaction. */ export function note(sql: SqlStorage, entry: Entry): void { sql.exec(OUTBOX); sql.exec("INSERT INTO never_again_outbox (entry) VALUES (?)", JSON.stringify({ ...entry, server_at: Date.now() })); } /** Whether the outbox holds anything (cheap; no table, nothing held). */ export function waiting(sql: SqlStorage): boolean { try { return sql.exec("SELECT 1 FROM never_again_outbox LIMIT 1").toArray().length > 0; } catch { return false; } } /** The outbox copied to R2, a chunk at a time; each chunk deleted from the outbox once it is in R2. Answers the chunks written. */ export async function flush(bucket: R2Bucket, slug: string, sql: SqlStorage, may: () => boolean = () => true): Promise { if (!slug || !waiting(sql)) return 0; let chunks = 0; for (let chunk = 0; chunk < 20; chunk++) { // Asked again just before every put (RESTORE 2 SERVER 5): an erase that began since writes nothing more here. if (!may()) break; const rows = sql.exec<{ seq: number; entry: string }>("SELECT seq, entry FROM never_again_outbox ORDER BY seq LIMIT 500").toArray(); if (!rows.length) break; const first = rows[0]!.seq; const last = rows[rows.length - 1]!.seq; // Named by the moment and the outbox's place: unique across restores, which can bring an outbox's numbers back. const key = `${prefixOf(slug)}${Date.now().toString().padStart(15, "0")}-${String(first).padStart(10, "0")}.jsonl`; await bucket.put(key, rows.map((r) => r.entry).join("\n"), { httpMetadata: { contentType: "application/x-ndjson" } }); sql.exec("DELETE FROM never_again_outbox WHERE seq <= ?", last); chunks += 1; } return chunks; } /** When the ledger was last folded (meta), and how often. */ export const COMPACTED = "never_again_compacted"; /** Chunks copied out since the last fold (meta). */ export const CHUNKS = "never_again_chunks"; export const COMPACT_EVERY_MS = 7 * 24 * 3_600_000; /** * THE BOUND (RESTORE 2 SERVER 4, L3): a fold keeps only the entries of the last 40 days, by the server's stamp * (`server_at`, SERVER 5), never by a time a phone set; an entry without a readable stamp is kept. Safe for restore because no * restore reaches further back: point-in-time recovery keeps 30 days, the weekly snapshots are kept 4 weeks (the * lifecycle rule ends them at 29 days), and both restores refuse a moment older than this (`restorable`). An entry older * than the oldest moment a restore can bring back is already true in that moment, so laying it again changes nothing. */ export const KEEP_MS = 40 * 24 * 3_600_000; /** Whether a moment is recent enough for the ledger to cover a restore to it. */ export function restorable(at: string | number, now = Date.now()): boolean { const ms = typeof at === "number" ? at : Date.parse(at); return Number.isFinite(ms) && now - ms < KEEP_MS; } /** * The ledger's chunks folded into one, in order, named so it sorts where the last folded chunk did (later chunks sort * after it); written before any is deleted, so a cut between leaves entries twice, which replays the same. Answers how * many chunks were folded. */ export async function compact(bucket: R2Bucket, slug: string, now = Date.now()): Promise { const keys = await listKeys(bucket, slug); if (keys.length < 2) return keys.length; // No spread (a spread of a huge file is a RangeError, after which nothing would fold again): line by line, and only // the entries a restore can still need (KEEP_MS). const lines: string[] = []; for (const key of keys) { const got = await bucket.get(key); if (!got) continue; for (const line of (await got.text()).split("\n")) { if (!line) continue; if (!kept(line, now)) continue; lines.push(line); } } const last = keys[keys.length - 1]!; const folded = last.replace(/(-c)?\.jsonl$/, "-c.jsonl"); await bucket.put(folded, lines.join("\n"), { httpMetadata: { contentType: "application/x-ndjson" } }); const gone = keys.filter((k) => k !== folded); for (let i = 0; i < gone.length; i += 1000) await bucket.delete(gone.slice(i, i + 1000)); return keys.length; } /** * Whether a fold keeps this line: dropped only when its server stamp is readable and older than KEEP_MS. A missing or * unreadable stamp, or a line that is not JSON, is kept (RESTORE 2 SERVER 5): losing an entry is the one thing a fold * must never do; keeping one too many only lays again what is already true. */ export function kept(line: string, now = Date.now()): boolean { let stamp: unknown; try { stamp = (JSON.parse(line) as { server_at?: unknown }).server_at; } catch { return true; } return !(typeof stamp === "number" && Number.isFinite(stamp) && stamp > 0 && now - stamp >= KEEP_MS); } async function listKeys(bucket: R2Bucket, slug: string): Promise { const keys: string[] = []; let cursor: string | undefined; do { const listed = await bucket.list({ prefix: prefixOf(slug), ...(cursor ? { cursor } : {}) }); keys.push(...listed.objects.map((o) => o.key)); cursor = listed.truncated ? listed.cursor : undefined; } while (cursor); return keys.sort(); } /** * Every entry of the ledger, in the server's own order: chunks by their names (the server's clock at the copy, then * the outbox's place), entries within a chunk by the outbox's place. No time a phone set orders anything. A line that * is not an entry is skipped (and said), never fatal to a restore. */ export async function read(bucket: R2Bucket, slug: string): Promise { const out: Stamped[] = []; for (const key of await listKeys(bucket, slug)) { const got = await bucket.get(key); if (!got) continue; for (const line of (await got.text()).split("\n")) { if (!line) continue; try { out.push(JSON.parse(line) as Stamped); } catch { console.error(`cottondb: never-again ${slug}: a line in ${key} is not an entry; skipped`); } } } return out; } /** What a replay did, counted. */ export type Replayed = { rows_erased: number; tokens_revoked: number; sessions_revoked: number; meta: number; tables: string[]; deletion: "set" | "kept" | "as_restored" }; /** What the newest deletion entry asks of the restored account (the caller does it: a Keep is async). */ export type DeletionWanted = { kind: "set"; entry: Extract } | { kind: "keep" } | null; /** * The ledger laid over a restored object, before it is unfrozen. Rows erased stay erased (any copy at or below the * version the erase saw), tokens and sessions revoked stay revoked, the sealing locks stand as last set, and the * newest deletion entry decides whether a deletion is pending. `deletion` sets or clears it. */ export function replay(sql: SqlStorage, entries: Stamped[], setMeta: (key: string, value: string | null) => void): { done: Replayed; wanted: DeletionWanted } { const done: Replayed = { rows_erased: 0, tokens_revoked: 0, sessions_revoked: 0, meta: 0, tables: [], deletion: "as_restored" }; const tables = new Set(); const blindGone = (where: string, ...args: SqlStorageValue[]): void => { for (const { rid } of sql.exec<{ rid: number }>(`SELECT b.rid FROM blind_row b JOIN rows r ON r.table_id = b.table_id AND r.id = b.id WHERE ${where}`, ...args).toArray()) { sql.exec("DELETE FROM blind WHERE rid = ?", rid); sql.exec("DELETE FROM blind_row WHERE rid = ?", rid); } }; let lastDeletion: Entry | null = null; // A token's or device's deletion and revival: the last of them for each row decides (laid after the loop). const ended = new Map(); for (const e of entries) { switch (e.kind) { case "erase_table": { tables.add(e.table); blindGone("r.table_id = ? AND r.version <= ?", e.table, e.version); sql.exec("DELETE FROM links WHERE (table_id, id) IN (SELECT table_id, id FROM rows WHERE table_id = ? AND version <= ?)", e.table, e.version); done.rows_erased += sql.exec("DELETE FROM rows WHERE table_id = ? AND version <= ?", e.table, e.version).rowsWritten; break; } case "erase_row": { tables.add(e.table); blindGone("r.table_id = ? AND r.id = ? AND r.version <= ?", e.table, e.id, e.version); sql.exec("DELETE FROM links WHERE table_id = ? AND id = ? AND EXISTS (SELECT 1 FROM rows WHERE table_id = ? AND id = ? AND version <= ?)", e.table, e.id, e.table, e.id, e.version); done.rows_erased += sql.exec("DELETE FROM rows WHERE table_id = ? AND id = ? AND version <= ?", e.table, e.id, e.version).rowsWritten; break; } case "row_revoked": done.tokens_revoked += sql.exec("UPDATE rows SET data = json_set(data, '$.revoked_at', ?) WHERE table_id = ? AND id = ? AND json_extract(data, '$.revoked_at') IS NULL", e.at, e.table, e.id).rowsWritten; break; case "row_expires": done.tokens_revoked += sql.exec("UPDATE rows SET data = json_set(data, '$.expires_at', ?) WHERE table_id = ? AND id = ? AND (json_extract(data, '$.expires_at') IS NULL OR json_extract(data, '$.expires_at') = '' OR json_extract(data, '$.expires_at') > ?)", e.expires_at, e.table, e.id, e.expires_at).rowsWritten; break; case "row_deleted": case "row_revived": ended.set(`${e.table}/${e.id}`, { table: e.table, id: e.id, deleted: e.kind === "row_deleted" }); break; case "sessions_all_revoked": // Every sign-in made before it (one made after, by a Keep's new sign-in, stands). done.sessions_revoked += sql.exec("UPDATE sessions SET revoked = 1 WHERE revoked = 0 AND issued_at <= ?", Math.floor((typeof e.server_at === "number" ? e.server_at : Date.parse(e.at)) / 1000)).rowsWritten; break; case "session_revoked": done.sessions_revoked += sql.exec("UPDATE sessions SET revoked = 1 WHERE token_hash = ? AND revoked = 0", e.token_hash).rowsWritten; break; case "meta": setMeta(e.key, e.value); done.meta += 1; break; case "account_delete": case "account_keep": lastDeletion = e; break; } } for (const r of ended.values()) { if (!r.deleted) continue; const gone = sql.exec("UPDATE rows SET deleted = 1 WHERE table_id = ? AND id = ? AND deleted = 0", r.table, r.id).rowsWritten; if (gone) tables.add(r.table); done.tokens_revoked += gone; } done.tables = [...tables]; const last = lastDeletion as Entry | null; const wanted: DeletionWanted = last?.kind === "account_delete" ? { kind: "set", entry: last } : last?.kind === "account_keep" ? { kind: "keep" } : null; return { done, wanted }; }