Cotton code
198 lines · 11.8 KB · TypeScriptRaw
/** * 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. */export const SWITCH = "snapshots";/** Whether an account takes copies: its own switch ("on" or "off"), else the Worker's `SNAPSHOTS_ALL`. */export function snapshotsOn(own: string | null | undefined, env: { SNAPSHOTS_ALL?: string }): boolean {  if (own === "on") return true;  if (own === "off") return false;  return env.SNAPSHOTS_ALL === "on";}/** The job under way (meta, JSON). */export const JOB = "snapshot_job";/** The last copies finished (meta, JSON). */export const LAST = "snapshot_last";/** A restore from snapshots under way (meta, JSON). */export const RESTORING = "snapshot_restore";export const KEEP_WEEKLY = 4;export const KEEP_DAILY = 7;export const ROWS_PER_PART = 5_000;/** A part's lines stop short of this many bytes (before gzip), whatever the row count (L5). */export const PART_BYTES = 8 * 1_048_576;export const WEEK_MS = 7 * 24 * 3_600_000;export const DAY_MS = 24 * 3_600_000;export type Kind = "full" | "daily";export type Job = { kind: Kind; stamp: string; base: number; upto: number; cursor: string | null; part: number; rows: number; bytes: number; started_at: string };export type Last = { full?: { stamp: string; upto: number; at: string }; daily?: { stamp: string; upto: number; at: string } };export type PartInfo = { key: string; rows: number; bytes: number; sha256: string };export type Manifest = { 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 };export const prefixOf = (kind: Kind, slug: string): string => `_snapshots/${kind === "full" ? "weekly" : "daily"}/${slug}/`;export const snapshotPrefix = (kind: Kind, slug: string, stamp: string): string => `${prefixOf(kind, slug)}${stamp}/`;export const 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. */export function 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. */export function baseOf(last: Last): number {  return Math.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. */export type Keys = { aes: CryptoKey; mac: CryptoKey };export async function 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: new Uint8Array(0), info: new TextEncoder().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. */export const aadOf = (slug: string, kind: Kind | "export", stamp: string, part: number): Uint8Array => new TextEncoder().encode(`cotton-snapshot-part|${slug}|${kind}|${stamp}|${part}`);const manifestBytes = (m: Manifest): Uint8Array => {  const { mac: _mac, ...rest } = m;  return new TextEncoder().encode(JSON.stringify(rest));};const b64 = (b: ArrayBuffer): string => btoa(String.fromCharCode(...new Uint8Array(b)));/** The manifest with its HMAC. */export async function 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. */export async function 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) return false;  try {    return await crypto.subtle.verify("HMAC", keys.mac, Uint8Array.from(atob(m.mac), (c) => c.charCodeAt(0)), manifestBytes(m));  } catch {    return false;  }}export function freshKey(): string {  const bytes = crypto.getRandomValues(new Uint8Array(32));  let s = "";  for (const b of bytes) s += String.fromCharCode(b);  return btoa(s);}// ── a part ───────────────────────────────────────────────────────────────async function through(bytes: Uint8Array, stream: CompressionStream | DecompressionStream): Promise<Uint8Array> {  const out = new Response(new Blob([bytes]).stream().pipeThrough(stream));  return new Uint8Array(await out.arrayBuffer());}export async function sealPart(keys: Keys, aad: Uint8Array, lines: string[]): Promise<Uint8Array> {  const gz = await through(new TextEncoder().encode(lines.join("\n")), new CompressionStream("gzip"));  const iv = crypto.getRandomValues(new Uint8Array(12));  const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: aad }, keys.aes, gz));  const out = new Uint8Array(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). */export async function openPart(keys: Keys, aad: Uint8Array, bytes: Uint8Array): Promise<string[]> {  const gz = new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12), additionalData: aad }, keys.aes, bytes.slice(12)));  const text = new TextDecoder().decode(await through(gz, new DecompressionStream("gzip")));  return text ? text.split("\n") : [];}export async function sha256(bytes: Uint8Array): Promise<string> {  return [...new Uint8Array(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. */export type Line = Record<string, unknown> & { table_id: string; id: string; version: number; deleted: number; toks?: string | null };const hex = (b: ArrayBuffer | null): string | null => (b ? [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("") : null);export const 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. */export function page(sql: SqlStorage, job: Job, limit: number): { lines: Line[]; cursor: string | null } {  type Raw = 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) } as Line;    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 };}