/** * SNAPSHOTS 1 (coordinator for the owner, 27 Nov 2026; assets/design/shared/RESTORE.md, Part 2). A copy of an account's * rows AS STORED (a sealed row stays sealed), outside the object, in R2, so it survives the loss of the object or its * class, which point-in-time recovery does not: * * weekly full every live row, each with its blind tokens _snapshots/weekly/<slug>/<stamp>/ * daily changes every row (tombstones too) above the last copy's version _snapshots/daily/<slug>/<stamp>/ * * Each part is newline-delimited JSON, gzipped, then sealed with AES-256-GCM under the account's own snapshot key * (12-byte IV first), its additional data naming the account, the kind, the stamp and the part's number, so a part * moved to another account, copy or place does not open (RESTORE 2 SERVER 2, L1). The manifest carries an HMAC-SHA-256 * under a key derived from the same key (HKDF), and every part's SHA-256 is checked against it before a restore. The key is kept in the directory, never in the object and never beside the copy, so an R2 leak * alone reads nothing, and deleting the key (the account delete) leaves anything that lingers unreadable. The manifest, * written last, is counts and hashes only; a copy without its manifest is not a copy, and is never counted as one. * * A FULL COPY ALONE IS A MIX OF MOMENTS (L2): it is read a few parts an alarm pass while the account goes on changing, * so a row read early is as it was then and one read late as it is later. Only a full AND the daily after it (which * holds every row written from the version the full began at, tombstones included) make one consistent state, at the * daily's version. So a daily is due as soon as a full is done, and a restore refuses a full with no daily after it. * (One consistent read of a whole account is not possible: a 4 GB account does not fit one invocation, and the object's * reads are consistent only between awaits.) * * Kept: the 4 newest weeklies and the 7 newest dailies (and no daily older than the oldest weekly kept), pruned by the * job; R2 lifecycle rules on the two prefixes are the backstop (8 and 29 days). * * OFF by default, per account (`POST /v1/admin/snapshots {on}`), or for every account at once with the Worker's * `SNAPSHOTS_ALL` set to "on" (publishing checklist, 28 Nov 2026): then an account takes copies unless the admin * switched it off for that account by name ("off"). Unset, the default on dev and live, nothing changes. Written by the object's alarm a few parts a pass, its * place kept in meta, so a 4 GB account never needs one long invocation. *//** The account's switch (meta), "on" or absent. */exportconst SWITCH = "snapshots";/** Whether an account takes copies: its own switch ("on" or "off"), else the Worker's `SNAPSHOTS_ALL`. */exportfunction snapshotsOn(own: string | null | undefined, env: { SNAPSHOTS_ALL?: string }): boolean {if (own === "on") returntrue;if (own === "off") returnfalse;return env.SNAPSHOTS_ALL === "on";}/** The job under way (meta, JSON). */exportconst JOB = "snapshot_job";/** The last copies finished (meta, JSON). */exportconst LAST = "snapshot_last";/** A restore from snapshots under way (meta, JSON). */exportconst RESTORING = "snapshot_restore";exportconst KEEP_WEEKLY = 4;exportconst KEEP_DAILY = 7;exportconst ROWS_PER_PART = 5_000;/** A part's lines stop short of this many bytes (before gzip), whatever the row count (L5). */exportconst PART_BYTES = 8 * 1_048_576;exportconst WEEK_MS = 7 * 24 * 3_600_000;exportconst DAY_MS = 24 * 3_600_000;exporttypeKind = "full" | "daily";exporttypeJob = { kind: Kind; stamp: string; base: number; upto: number; cursor: string | null; part: number; rows: number; bytes: number; started_at: string };exporttypeLast = { full?: { stamp: string; upto: number; at: string }; daily?: { stamp: string; upto: number; at: string } };exporttypePartInfo = { key: string; rows: number; bytes: number; sha256: string };exporttypeManifest = { kind: Kind; stamp: string; slug: string; base: number; upto: number; rows: number; bytes: number; parts: PartInfo[]; started_at: string; written_at: string; format: "ndjson.gz.aes256gcm+aad"; mac?: string };exportconst prefixOf = (kind: Kind, slug: string): string => `_snapshots/${kind === "full" ? "weekly" : "daily"}/${slug}/`;exportconst snapshotPrefix = (kind: Kind, slug: string, stamp: string): string => `${prefixOf(kind, slug)}${stamp}/`;exportconst stampOf = (at: Date): string => at.toISOString().replace(/[:.]/g, "-");/** * What is due now: a full when none is kept or the last is a week old; changes at once after a full (a full alone is * no consistent state, L2), else when the last copy is a day old. */exportfunction due(last: Last, now: number): Kind | null {if (!last.full || now - Date.parse(last.full.at) >= WEEK_MS) return"full";if (!last.daily || Date.parse(last.daily.at) <= Date.parse(last.full.at)) return"daily";const latest = last.daily && Date.parse(last.daily.at) > Date.parse(last.full.at) ? last.daily : last.full;return now - Date.parse(latest.at) >= DAY_MS ? "daily" : null;}/** The version a daily copy starts above: the newest copy's. */exportfunction baseOf(last: Last): number {returnMath.max(last.full?.upto ?? 0, last.daily?.upto ?? 0);}// ── the key ──────────────────────────────────────────────────────────────/** The account's snapshot key, as the two keys it is used as: AES-GCM for the parts, HMAC for the manifests. */exporttypeKeys = { aes: CryptoKey; mac: CryptoKey };exportasyncfunction importKey(raw: string): Promise<Keys> {const bytes = Uint8Array.from(atob(raw), (c) => c.charCodeAt(0));const aes = await crypto.subtle.importKey("raw", bytes, "AES-GCM", false, ["encrypt", "decrypt"]);const base = await crypto.subtle.importKey("raw", bytes, "HKDF", false, ["deriveKey"]);const mac = await crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: newUint8Array(0), info: newTextEncoder().encode("cotton snapshot manifest v1") }, base, { name: "HMAC", hash: "SHA-256", length: 256 }, false, ["sign", "verify"]);return { aes, mac };}/** What a part's seal is bound to: the account, the kind ("full", "daily", "export"), the copy's stamp and the part's number. */exportconst aadOf = (slug: string, kind: Kind | "export", stamp: string, part: number): Uint8Array => newTextEncoder().encode(`cotton-snapshot-part|${slug}|${kind}|${stamp}|${part}`);const manifestBytes = (m: Manifest): Uint8Array => {const { mac: _mac, ...rest } = m;returnnewTextEncoder().encode(JSON.stringify(rest));};const b64 = (b: ArrayBuffer): string => btoa(String.fromCharCode(...newUint8Array(b)));/** The manifest with its HMAC. */exportasyncfunction signManifest(keys: Keys, m: Manifest): Promise<Manifest> {return { ...m, mac: b64(await crypto.subtle.sign("HMAC", keys.mac, manifestBytes(m))) };}/** Whether a manifest is this account's, as written: its HMAC holds, and it names the account, kind and stamp asked. */exportasyncfunction manifestHolds(keys: Keys, m: Manifest, slug: string, kind: Kind, stamp: string): Promise<boolean> {if (!m || typeof m.mac !== "string" || m.slug !== slug || m.kind !== kind || m.stamp !== stamp) returnfalse;try {returnawait crypto.subtle.verify("HMAC", keys.mac, Uint8Array.from(atob(m.mac), (c) => c.charCodeAt(0)), manifestBytes(m)); } catch {returnfalse; }}exportfunction freshKey(): string {const bytes = crypto.getRandomValues(newUint8Array(32));let s = "";for (const b of bytes) s += String.fromCharCode(b);return btoa(s);}// ── a part ───────────────────────────────────────────────────────────────asyncfunction through(bytes: Uint8Array, stream: CompressionStream | DecompressionStream): Promise<Uint8Array> {const out = newResponse(newBlob([bytes]).stream().pipeThrough(stream));returnnewUint8Array(await out.arrayBuffer());}exportasyncfunction sealPart(keys: Keys, aad: Uint8Array, lines: string[]): Promise<Uint8Array> {const gz = await through(newTextEncoder().encode(lines.join("\n")), newCompressionStream("gzip"));const iv = crypto.getRandomValues(newUint8Array(12));const sealed = newUint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: aad }, keys.aes, gz));const out = newUint8Array(12 + sealed.length); out.set(iv, 0); out.set(sealed, 12);return out;}/** A part opened: throws when its tag does not hold (a changed byte, another key, or another place than `aad` names). */exportasyncfunction openPart(keys: Keys, aad: Uint8Array, bytes: Uint8Array): Promise<string[]> {const gz = newUint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12), additionalData: aad }, keys.aes, bytes.slice(12)));const text = newTextDecoder().decode(await through(gz, newDecompressionStream("gzip")));return text ? text.split("\n") : [];}exportasyncfunction sha256(bytes: Uint8Array): Promise<string> {return [...newUint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((b) => b.toString(16).padStart(2, "0")).join("");}// ── the rows ─────────────────────────────────────────────────────────────/** A stored row as a snapshot line: every column of `rows` as SQLite holds it, and its blind tokens (hex) if any. */exporttypeLine = Record<string, unknown> & { table_id: string; id: string; version: number; deleted: number; toks?: string | null };const hex = (b: ArrayBuffer | null): string | null => (b ? [...newUint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("") : null);exportconst unhex = (s: string): Uint8Array => Uint8Array.from(s.match(/../g) ?? [], (h) => parseInt(h, 16));/** One page of the copy: a full by (table, id) over live rows, changes by version over every row. */exportfunction page(sql: SqlStorage, job: Job, limit: number): { lines: Line[]; cursor: string | null } {typeRaw = Record<string, SqlStorageValue> & { table_id: string; id: string; version: number; deleted: number; toks: ArrayBuffer | null };let raws: Raw[];if (job.kind === "full") {const [t, i] = job.cursor ? [job.cursor.slice(0, job.cursor.indexOf("/")), job.cursor.slice(job.cursor.indexOf("/") + 1)] : ["", ""]; raws = sql .exec<Raw>("SELECT r.*, b.toks AS toks FROM rows r LEFT JOIN blind_row b ON b.table_id = r.table_id AND b.id = r.id WHERE r.deleted = 0 AND (r.table_id, r.id) > (?, ?) ORDER BY r.table_id, r.id LIMIT ?", t, i, limit) .toArray(); } else {const [v, t, i] = job.cursor ? (JSON.parse(job.cursor) as [number, string, string]) : [job.base, "", ""]; raws = sql .exec<Raw>("SELECT r.*, b.toks AS toks FROM rows r LEFT JOIN blind_row b ON b.table_id = r.table_id AND b.id = r.id WHERE r.version <= ? AND (r.version, r.table_id, r.id) > (?, ?, ?) ORDER BY r.version, r.table_id, r.id LIMIT ?", job.upto, v, t, i, limit, ) .toArray(); }// A part stops short of PART_BYTES (L5): the rest of the page comes in the next part.const lines: Line[] = [];let size = 0;for (const r of raws) {const line = { ...r, toks: hex(r.toks) } asLine;const length = JSON.stringify(line).length + 1;if (lines.length > 0 && size + length > PART_BYTES) break; lines.push(line); size += length; }const cut = lines.length < raws.length;const last = lines[lines.length - 1];const cursor = (!cut && raws.length < limit) || !last ? null : job.kind === "full" ? `${last.table_id}/${last.id}` : JSON.stringify([last.version, last.table_id, last.id]);return { lines, cursor };}