/** * RESTORE 2 (coordinator for the owner, 27 Nov 2026; assets/design/shared/RESTORE-2.md, the wire contract in * RESTORE-2-CONTRACT.md). A point-in-time restore of an account's object that reaches the phones: * * freeze every request but the admin token's answered 503 `account_frozen`; the alarm held; sockets closed * export today's live rows, as stored (sealed rows stay sealed), to R2 under the account's prefix, page by page * restore Durable Object point-in-time recovery to a bookmark, the version held now and a fresh generation * written down OUTSIDE the object first (the restore rolls the object back) * finish on the restarted object: the version raised past anything a phone could hold, the new generation and * `restored_to` written, the object's rows counted * unfreeze the freeze lifted; each phone sees the new generation and makes its copy again * * What must outlive the restore (the freeze, the version before, the generation to come) is kept in one small R2 * marker beside the account-delete marker (`<slug>/.restore` in PHOTOS), read once per object instance. A freeze kept * in the object would be undone by the very restore it guards. * * The routes are the admin token's alone, and answer on the dev and test Workers only (404 elsewhere) until a * reviewed runbook says otherwise. They are answered ahead of the account-delete door, so an erased account can be * restored on dev (RESTORE-2.md, "Restoring an erased account"); on live, delete means delete. */import { json, refuse } from"./http.ts";/** The account's generation (RESTORE-2-CONTRACT.md 1): made once, replaced only by a restore. */exportconst GENERATION = "generation";/** The moment a restore put the account back to (ISO), set by `finish`. */exportconst RESTORED_TO = "restored_to";/** The request header a phone's write carries (RESTORE-2-CONTRACT.md 2). */exportconst GENERATION_HEADER = "x-cotton-generation";/** How long a frozen account asks to be left (RESTORE-2-CONTRACT.md 5). */exportconst FROZEN_RETRY_S = 30;/** What `finish` lifts the version by, over the highest the object held before the restore. */exportconst VERSION_MARGIN = 1_000;/** What outlives a restore, kept outside the object. */exporttypeMarker = { frozen: boolean; frozen_at: string | null; reason: string | null;/** A restore asked and not yet finished: the version held before it, the generation to write, and its moment. */ pending: { version_before: number; generation: string; restored_to: string; bookmark_hash: string; erased_before: boolean; asked_at: string; sentinel: string } | null;/** The owner began this restore from their own phone (src/restore_owner.ts): the server finishes and unfreezes it by itself. */ owner?: { device: string; point: string; to: string; started_at: string } | null;};/** * WHERE RESTORE KEEPS ITS OWN THINGS (RESTORE 2 SERVER 3, M1): never under `<slug>/`, which the front Worker serves * publicly from PHOTOS (src/index.ts `photo`). Every prefix begins with `_`, which no slug can (`SLUG` in index.ts: * a letter first), and no route maps a key from a caller's path into one: a serving bug cannot expose them. * * PHOTOS _restore/<slug>/marker.json the freeze and a restore asked (this file) * PHOTOS _restore/<slug>/never-again/… the never-again ledger (src/never_again.ts) * MEDIA _snapshots/weekly/<slug>/…, _snapshots/daily/<slug>/… sealed snapshots (src/snapshots.ts) * MEDIA _restore-exports/<slug>/… a restore's sealed export of the rows it replaced * * The account delete erases all four (src/account_delete.ts, `hiddenPrefixes`). */exportconst HIDDEN_PHOTOS = (slug: string): string => `_restore/${slug}/`;/** Where a restore's export of the rows it replaces is kept, sealed, in MEDIA; a lifecycle rule ends it (SNAPSHOTS.md). */exportconst EXPORTS = "_restore-exports/";exportconst markerKey = (slug: string): string => `${HIDDEN_PHOTOS(slug)}marker.json`;/** Every prefix restore and snapshots keep for an account, by bucket: what the account delete erases. */exportfunction hiddenPrefixes(slug: string): { photos: string[]; media: string[] } {return { photos: [HIDDEN_PHOTOS(slug)], media: [`_snapshots/weekly/${slug}/`, `_snapshots/daily/${slug}/`, `${EXPORTS}${slug}/`] };}exportasyncfunction readMarker(bucket: R2Bucket, slug: string): Promise<Marker | null> {const got = await bucket.get(markerKey(slug));if (!got) returnnull;// A marker that does not read throws, like a failed R2 call: never kept, never taken as frozen or as not frozen;// the request is answered 503 retryable and the next one reads it again (RESTORE 2 SERVER 2, H1).const parsed = JSON.parse(await got.text()) asMarker;if (typeof parsed !== "object" || parsed === null || typeof parsed.frozen !== "boolean") thrownewError("the restore marker did not read");return parsed;}/** * THE SENTINEL (RESTORE 2 SERVER 2, M2): a row written just before a point-in-time restore is asked, after any * moment a bookmark can name. A restore that lands takes it away; finish refuses while it is still there. */exportconst SENTINEL_SQL = "CREATE TABLE IF NOT EXISTS restore_sentinel (id INTEGER PRIMARY KEY CHECK (id = 1), token TEXT NOT NULL)";exportfunction sentinelHeld(sql: SqlStorage, token: string): boolean {try {return sql.exec<{ token: string }>("SELECT token FROM restore_sentinel WHERE id = 1").toArray()[0]?.token === token; } catch {returnfalse; }}/** What a call from another object, a socket or a pass is told while frozen: "not delivered, try again" (M1). */exportconst FROZEN_CALL = "account_frozen";/** The answer when the marker could not be read: retryable, nothing kept (H1). */exportfunction unreadAnswer(): Response {return json({ code: "try_again", message: "This account could not be reached for a moment. Try again shortly.", retry_after_s: 5 }, 503, { "retry-after": "5" });}exportasyncfunction writeMarker(bucket: R2Bucket, slug: string, marker: Marker | null): Promise<void> {if (!marker || (!marker.frozen && !marker.pending)) await bucket.delete(markerKey(slug));elseawait bucket.put(markerKey(slug), JSON.stringify(marker), { httpMetadata: { contentType: "application/json" } });}/** A fresh generation: 16 random bytes, base64url (22 characters). */exportfunction freshGeneration(): string {const bytes = crypto.getRandomValues(newUint8Array(16));let s = "";for (const b of bytes) s += String.fromCharCode(b);return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}/** The answer every request but the admin's gets while the account is frozen. */exportfunction frozenAnswer(): Response {return json({ code: "account_frozen", message: "This account is being looked after for a moment. Try again shortly.", retry_after_s: FROZEN_RETRY_S }, 503, { "retry-after": String(FROZEN_RETRY_S) });}/** A write from a copy of another generation: refused before anything lands (RESTORE-2-CONTRACT.md 3). */exportfunction generationMoved(generation: string, restoredTo: string | null): Response {return json({ code: "generation_moved", message: "This account was put back to an earlier moment: this copy is made again before it writes.", generation, restored_to: restoredTo }, 409);}/** Only the dev and test Workers answer the restore routes. */exportfunction restoreRoutesOn(env: { ENV_LABEL?: string }): boolean {return env.ENV_LABEL === "dev" || env.ENV_LABEL === "test";}/** A short, one-way name for a bookmark, for logs and answers: the bookmark itself is never echoed. */exportasyncfunction bookmarkHash(bookmark: string): Promise<string> {const digest = await crypto.subtle.digest("SHA-256", newTextEncoder().encode(bookmark));return [...newUint8Array(digest).slice(0, 8)].map((b) => b.toString(16).padStart(2, "0")).join("");}/** Refuses with the route's own words when the account is not frozen. */exportfunction mustBeFrozen(marker: Marker | null): Marker {if (!marker?.frozen) refuse(409, "not_frozen", "freeze the account first (POST /v1/admin/restore/freeze)");return marker;}// ── which devices send the generation (coordinator, 27 Nov 2026: the phone review's contract gap) ──────────────//// An older build sends no `x-cotton-generation`, so after a restore it re-sends its queued damage as if nothing// happened. Each device signed in is kept here: when it was last seen, whether it has ever sent the header on a write,// and the last value it sent. A restore is refused while any device active in the last 30 days has never sent it// (or a live sign-in has never been seen at all), unless the admin says `override_devices: true`.exportconst DEVICES_SQL = "CREATE TABLE IF NOT EXISTS device_generation (device_id TEXT PRIMARY KEY, first_seen INTEGER NOT NULL, last_seen INTEGER NOT NULL, sent_at INTEGER, last_generation TEXT)";exportconst ACTIVE_MS = 30 * 24 * 3_600_000;/** A device's last-seen is written at most this often (a write per phone request would cost every request). */exportconst SEEN_EVERY_MS = 3_600_000;exporttypeDeviceSeen = { device: string; first_seen: string; last_seen: string; sent_header: boolean; sent_at: string | null; last_generation: string | null };/** A request from `device` seen at `now`: `said` is the header it carried on a write, if any. */exportfunction noteDevice(sql: SqlStorage, device: string, now: number, said: string | null): void { sql.exec(DEVICES_SQL);if (said !== null) { sql.exec("INSERT INTO device_generation (device_id, first_seen, last_seen, sent_at, last_generation) VALUES (?, ?, ?, ?, ?) ON CONFLICT (device_id) DO UPDATE SET last_seen = excluded.last_seen, sent_at = excluded.sent_at, last_generation = excluded.last_generation", device, now, now, now, said, ); } else { sql.exec("INSERT INTO device_generation (device_id, first_seen, last_seen) VALUES (?, ?, ?) ON CONFLICT (device_id) DO UPDATE SET last_seen = excluded.last_seen", device, now, now); }}/** Every device seen or signed in: those kept here, and live sign-ins never seen (as not having sent the header). */exportfunction devicesSeen(sql: SqlStorage, now: number): { devices: DeviceSeen[]; unready: DeviceSeen[] } { sql.exec(DEVICES_SQL);const iso = (ms: number | null) => (ms === null ? null : newDate(ms).toISOString());const kept = sql.exec<{ device_id: string; first_seen: number; last_seen: number; sent_at: number | null; last_generation: string | null }>("SELECT device_id, first_seen, last_seen, sent_at, last_generation FROM device_generation ORDER BY last_seen DESC").toArray();const devices: DeviceSeen[] = kept.map((d) => ({ device: d.device_id, first_seen: iso(d.first_seen)!, last_seen: iso(d.last_seen)!, sent_header: d.sent_at !== null, sent_at: iso(d.sent_at), last_generation: d.last_generation }));const known = newSet(kept.map((d) => d.device_id));// A sign-in still good whose device was never seen since this record began: not known to send it.let unseen: { device_id: string; issued_at: number }[] = [];try { unseen = sql.exec<{ device_id: string; issued_at: number }>("SELECT device_id, max(issued_at) AS issued_at FROM sessions WHERE revoked = 0 AND expires_at > ? GROUP BY device_id", Math.floor(now / 1000)).toArray().filter((s) => !known.has(s.device_id)); } catch {// an erased object keeps no sessions }for (const s of unseen) devices.push({ device: s.device_id, first_seen: iso(s.issued_at * 1000)!, last_seen: iso(s.issued_at * 1000)!, sent_header: false, sent_at: null, last_generation: null });const unready = devices.filter((d) => !d.sent_header && (now - Date.parse(d.last_seen) < ACTIVE_MS || !known.has(d.device)));return { devices, unready };}