Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
spaces: gate recovery and version restore, like slides' restoregate (#620)
nyblnet532d9916c9cd
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 4727924c..1ab074c4 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -172,6 +172,18 @@ jobs:--outfile="$RUNNER_TEMP/test-spaces-undo.mjs"node "$RUNNER_TEMP/test-spaces-undo.mjs"+ - name: Spaces restore-gate rig+ # The recovery snapshot and every History entry live in IndexedDB, which+ # every file:// document shares, so restore is foreign input. Like+ # slides' restore gate: an entry naming another space is refused, it+ # never brings collab/readonly/template, block html is sanitized, and+ # junk, frozen, __proto__ and oversized entries apply nothing.+ # (Bundled: store.ts imports './model' extensionless.)+ run: |+ slides/node_modules/.bin/esbuild scripts/test-spaces-restore-gate.ts --bundle --platform=node --format=esm \+ --outfile="$RUNNER_TEMP/test-spaces-restore-gate.mjs"+ node "$RUNNER_TEMP/test-spaces-restore-gate.mjs"+- name: Spaces agent-surface rig# agent.ts is ~900 lines and shipped with no coverage at all: two of the# five defects an adversarial review found in round 2 lived here,diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 20e1768f..c41861ac 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -7790,6 +7790,35 @@ needs those more than anyone. Remote edits arrive through `touch()`, not`commit`, so a locked copy still follows the room. `copyIsReceiveOnly` is thelock's question (a document with no `collab` is local and editable — unlike`copyCanWrite`, which says no only because there is no room to write to).++## 2026-10-04 — Spaces: a restore from this browser passes a gate, like slides' restoregate++`spaces/src/restoregate.ts` is the spaces counterpart of slides'+`slides/src/restoregate.ts` (`gateRestored`, rig+`scripts/test-slides-restore-gate.ts`). The recovery snapshot and every+History entry live in IndexedDB, and every `file://` document shares that+origin, so a stored entry is foreign input. The recovery check+(`recoveryOffered`), the banner's Restore and History's Restore all go+through it (`restoreInto`); none of them parses a stored entry straight into+`replaceDoc` any more.++The gate refuses, applying nothing and deleting nothing, an entry that is over+`MAX_RESTORE_CHARS` (128 MiB), is not JSON, has a `__proto__` key anywhere,+names a docId other than the open space's (checked on the raw value, before+`parseDoc` could mint one), fails `parseDoc`, or would open frozen (newer+version or unknown policy): a restore cannot open read-only, so it must not+happen. What passes has every block's `html` run through `sanitizeInline`,+the gate importSpace puts on arriving blocks, and takes identity from the+live space via `FROM_LIVE`. A read-only store is never restored into, and the+banner is shown only for an entry that passes and differs from the open space+as it would be restored, so a bad entry cannot raise one.++Two deliberate differences from slides. Spaces REFUSES a foreign docId where+slides overwrites it with the live one: a space's content is its pages, and+another space's pages under this one's identity is exactly the forgery. And+spaces does NOT drop unknown keys: the format is additive, a file open keeps+every field it does not understand, and the restore path must not be the one+that loses them.## 2026-09-28 — Spaces: the unsaved dot answers for one revision, and every write of the open file queuesSpaces adopts the kernel's `SaveQueue` (kernel/src/savequeue.ts). The race itdiff --git a/scripts/test-spaces-model.ts b/scripts/test-spaces-model.tsindex a61883d3..2ce5a087 100644--- a/scripts/test-spaces-model.ts+++ b/scripts/test-spaces-model.ts@@ -418,7 +418,11 @@ for (const [label, input, err] of [// checkpoints undo first, which is what makes the note "Restoring is// undoable" true rather than reassuring.ok(/listVersions\(/.test(about), 'About reads the timeline')- ok(/store\.replaceDoc\(restored\)/.test(about), '…and restores through replaceDoc, so ⌘Z walks it back')+ // (through restoreInto since the restore gate: the stored entry is foreign+ // input, gated first — restoregate.ts — and then handed to replaceDoc)+ const gate = fs.readFileSync(new URL('../spaces/src/restoregate.ts', import.meta.url), 'utf8')+ ok(/restoreInto\(store, v\.json\)/.test(about) && /store\.replaceDoc\(g\.doc\)/.test(gate),+ '…and restores through replaceDoc, so ⌘Z walks it back')}// ---- a popover is as tall as the room it has ------------------------------diff --git a/scripts/test-spaces-restore-gate.ts b/scripts/test-spaces-restore-gate.tsnew file mode 100644index 00000000..d0f63ddf--- /dev/null+++ b/scripts/test-spaces-restore-gate.ts@@ -0,0 +1,232 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// A space kept in this browser is gated before it replaces the open one.+//+// node scripts/test-spaces.mjs restore-gate+//+// (Bundled: store.ts imports './model' extensionless — the runner does what CI+// does. Run from the repo root; the last section reads main.ts and about.ts.)+//+// WHAT THIS PROVES. The recovery banner's snapshot and every History entry+// live in IndexedDB under the space's docId — and on file:// that store is+// shared by every local document. Restore used to JSON.parse the stored text+// straight into store.replaceDoc. Now (spaces/src/restoregate.ts, like slides'+// restoregate.ts):+// 1. an entry that names another space is refused, whatever key it sits under;+// 2. an entry never brings identity or capability (collab, readonly,+// template, docId) — the open space's survive;+// 3. hostile html in blocks comes out through sanitizeInline, the gate an+// arriving file's blocks pass on import;+// 4. non-JSON, another format, a frozen (newer) document, a `__proto__` key+// and an oversized entry are refused, and nothing is applied;+// 5. a refused entry never raises the recovery banner;+// 6. an honest recovery and an honest version restore still work, unknown+// fields included (the spaces format is additive);+// 7. both restore paths in the app go through the gate.+//+// Rows 1–5 drive a real Store through restoreInto, so bypassing the gate+// (raw JSON → replaceDoc) turns them red.++import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { Store } from '../spaces/src/store.ts'+import { parseDoc, docContentKey, FORMAT, type SpacesDoc } from '../spaces/src/model.ts'+import { gateRestored, recoveryOffered, restoreInto, MAX_RESTORE_CHARS } from '../spaces/src/restoregate.ts'+import { sanitizeInline } from '../spaces/src/sanitize.ts'++let checks = 0+let failures = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}+const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v)) as T++const LIVE_COLLAB = { v: 2, room: 'wLIVEROOM', key: 'live-key', on: true }++/** Space A, as it is open — with a live session. */+function liveA(): SpacesDoc {+ const r = parseDoc(JSON.stringify({+ format: FORMAT, version: 1, docId: 'space-A', title: 'A', home: 'pa',+ theme: { background: '#fff', color: '#1E2A3A', accent: '#F7A600', measure: 720 },+ pages: [+ { id: 'pa', title: 'Home', blocks: [{ id: 'b1', type: 'p', html: 'written in A' }] },+ { id: 'pb', title: 'Notes', parent: 'pa', blocks: [+ { id: 'b2', type: 'h2', html: 'Heading' },+ { id: 'b3', type: 'code', html: 'if (a < b) return', lang: 'js' },+ ] },+ ],+ collab: LIVE_COLLAB,+ }))+ if (!r.ok) throw new Error('fixture did not parse')+ return r.doc+}+/** What autosave writes: the document minus collab (kernel contentOnly). */+const snapshotOf = (doc: SpacesDoc): Record<string, any> => {+ const { collab: _c, ...rest } = clone(doc) as SpacesDoc & { collab?: unknown }+ void _c+ return rest+}+/** A snapshot of A with its first block rewritten — an edit after the save. */+const editedA = (text = 'edited after the save'): Record<string, any> => {+ const s = snapshotOf(liveA())+ s.pages[0].blocks[0].html = text+ return s+}+const first = (s: Store) => String((s.doc.pages as SpacesDoc['pages'] | undefined)?.[0]?.blocks?.[0]?.html ?? '')+/** A restore that THROWS was not refused cleanly — the app would have applied+ * whatever it got to before the throw — so it counts as "went through". */+const restore = (s: Store, json: unknown): boolean => { try { return restoreInto(s, json) } catch { return true } }+const offered = (json: unknown, live: SpacesDoc): boolean => { try { return recoveryOffered(json, live) } catch { return true } }++console.log('bento/spaces restore gate\n')++console.log('cross-docId forgery\n')+{+ // space B's content, filed under A's key (getRecovery/listVersions only look+ // at the KEY), still naming B+ const b = editedA('B wrote this'); b.docId = 'space-B'+ const s = new Store(liveA())+ ok(!restore(s, JSON.stringify(b)), 'an entry naming another space is refused')+ ok(first(s) === 'written in A' && s.doc.docId === 'space-A', 'and none of its content is applied')+ ok(!s.canUndo, 'nothing was applied, so there is nothing to undo')+ ok(!offered(JSON.stringify(b), liveA()), 'it never raises the recovery banner')+}+{+ const b = editedA('no id at all'); delete b.docId+ const s = new Store(liveA())+ ok(!restore(s, JSON.stringify(b)), 'an entry with no docId is refused (parseDoc would mint one)')+ ok(first(s) === 'written in A', 'and its content is not applied')+}+{+ // the check runs against the space as it is NOW: duplicated under a new+ // docId since the entry was listed, the entry is somebody else's+ const s = new Store(liveA())+ s.doc.docId = 'space-A-copy'+ ok(!restore(s, JSON.stringify(editedA())), 'an entry from before "Duplicate as a new space" is refused in the copy')+}++console.log('\nidentity and capability stay the open space\'s\n')+{+ const snap = editedA()+ snap.collab = { v: 2, room: 'wATTACKER', key: 'attacker-key', on: true }+ snap.readonly = true+ snap.template = true+ const s = new Store(liveA())+ ok(restore(s, JSON.stringify(snap)), 'an entry carrying collab/readonly/template still restores its content')+ ok(first(s) === 'edited after the save', 'the content is the entry\'s')+ ok(JSON.stringify(s.doc.collab) === JSON.stringify(LIVE_COLLAB), 'collab is the open space\'s room and key')+ ok(s.doc.readonly === undefined, 'a forged readonly does not survive')+ ok(s.doc.template === undefined, 'a forged template does not survive (it would re-mint docId on every open)')+ ok(s.doc.docId === 'space-A', 'docId is the open space\'s')+}+{+ const noCollab = liveA(); delete noCollab.collab+ const snap = editedA(); snap.collab = { v: 2, room: 'wATTACKER', key: 'k', on: true }+ const g = gateRestored(JSON.stringify(snap), noCollab)+ ok(g.ok && g.doc.collab === undefined, 'a space with no live session does not gain one from an entry')+}++console.log('\nhostile html is sanitized, as an arriving file\'s blocks are\n')+{+ const hostile = '<img src=x onerror="alert(1)">hi<script>alert(2)</script><a href="javascript:alert(3)">x</a>'+ const snap = editedA(hostile)+ const s = new Store(liveA())+ ok(restore(s, JSON.stringify(snap)), 'an entry with hostile html restores')+ const html = first(s)+ ok(html === sanitizeInline(hostile), 'its block html is exactly what sanitizeInline makes of it')+ ok(!/onerror|<script|<img|javascript:/i.test(html), `no handler, script, image or javascript: url survives (${JSON.stringify(html)})`)+}++console.log('\nnot a restorable document → refused, nothing applied\n')+{+ const cases: Array<[string, string]> = [+ ['unparseable text', 'not json {'],+ ['a JSON array', '[]'],+ ['another format', JSON.stringify({ ...editedA(), format: 'bento/slides' })],+ ['no pages array', JSON.stringify({ ...editedA(), pages: 'x' })],+ ['a newer version this build would open frozen', JSON.stringify({ ...editedA(), version: 999 })],+ ['an unknown policy this build would open frozen', JSON.stringify({ ...editedA(), policy: 'bento-spaces-9' })],+ ]+ for (const [what, json] of cases) {+ const s = new Store(liveA())+ ok(!restore(s, json) && first(s) === 'written in A', what)+ }+ {+ // a __proto__ key, top level and nested: JSON.parse makes it an own+ // property, and the next merge that treats it as the setter pollutes+ const top = JSON.stringify(editedA()).replace(/^\{/, '{"__proto__":{"polluted":true},')+ const nested = JSON.stringify(editedA()).replace('"blocks":[{', '"blocks":[{"__proto__":{"polluted":true},')+ for (const [what, json] of [['a top-level __proto__ key', top], ['a nested __proto__ key', nested]] as const) {+ const s = new Store(liveA())+ ok(!restore(s, json) && first(s) === 'written in A', what)+ }+ ok(({} as Record<string, unknown>).polluted === undefined, 'Object.prototype is untouched')+ }+ {+ const big = editedA('x'.repeat(MAX_RESTORE_CHARS))+ const s = new Store(liveA())+ ok(!restore(s, JSON.stringify(big)) && first(s) === 'written in A', `an entry over ${MAX_RESTORE_CHARS / 1024 / 1024} MiB`)+ }+ {+ const s = new Store(liveA())+ ok(!restore(s, 42 as unknown as string), 'a non-string entry')+ }+ {+ const s = new Store(liveA()); s.readOnly = true+ ok(!restore(s, JSON.stringify(editedA())) && first(s) === 'written in A', 'a read-only store is never rewritten')+ }+}++console.log('\nthe recovery banner\n')+ok(offered(JSON.stringify(editedA()), liveA()), 'an honest snapshot with lost edits raises it')+ok(!offered(JSON.stringify(snapshotOf(liveA())), liveA()), 'a snapshot identical to the file does not')+ok(!offered('garbage', liveA()), 'junk does not')+ok(!offered(JSON.stringify({ ...snapshotOf(liveA()), collab: { room: 'wX' }, readonly: true }), liveA()),+ 'an entry that differs only in identity it cannot bring does not')++console.log('\nthe controls: honest restores still work\n')+{+ // recovery: an edit lost in a crash, plus a field this build does not know+ const snap = editedA(); snap.futureField = { kept: true }; snap.pages[1].futurePageField = 7+ const s = new Store(liveA())+ ok(restore(s, JSON.stringify(snap)), 'an honest recovery snapshot restores')+ ok(first(s) === 'edited after the save', 'with its edit')+ ok((s.doc as Record<string, any>).futureField?.kept === true && (s.doc.pages[1] as Record<string, any>).futurePageField === 7,+ 'and unknown fields survive, as a file open keeps them')+ ok(s.doc.pages[1].blocks[1].html === 'if (a < b) return', 'a code block\'s escaped text is untouched')+ s.undo()+ ok(first(s) === 'written in A', 'and ⌘Z walks it back')+}+{+ // version restore: an older version of the same space+ const live = liveA()+ const older = snapshotOf(live); older.title = 'A, an hour ago'; older.pages.pop()+ const s = new Store(live)+ ok(restore(s, JSON.stringify(older)), 'an honest version restores')+ ok(s.doc.title === 'A, an hour ago' && s.doc.pages.length === 1, 'with its content')+ ok(JSON.stringify(s.doc.collab) === JSON.stringify(LIVE_COLLAB), 'and the live session it is restored into')+}+{+ const live = liveA()+ const g = gateRestored(JSON.stringify(snapshotOf(live)), live)+ ok(g.ok && docContentKey(g.doc) === docContentKey(live) && JSON.stringify(g.doc) === JSON.stringify(live),+ 'an honest snapshot of the open space comes back byte-identical')+}++console.log('\nevery restore path uses the gate\n')+{+ const root = process.cwd()+ const main = readFileSync(join(root, 'spaces/src/main.ts'), 'utf8')+ const about = readFileSync(join(root, 'spaces/src/about.ts'), 'utf8')+ const offer = main.slice(main.indexOf('async function offerRecovery('), main.indexOf('async function offerRecovery(') + 1400)+ ok(/recoveryOffered\(snap\.json, doc\)/.test(offer), 'the recovery check gates before offering')+ ok(/restoreInto\(store, snap\.json\)/.test(offer), 'the banner\'s Restore goes through restoreInto')+ ok(/restoreInto\(store, v\.json\)/.test(about), 'History\'s Restore goes through restoreInto')+ ok(!/JSON\.parse\((snap|v)\.json\)/.test(main + about), 'no raw JSON.parse of a stored entry remains')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)diff --git a/scripts/test-spaces.mjs b/scripts/test-spaces.mjsindex 1f24b4bf..efbe7993 100755--- a/scripts/test-spaces.mjs+++ b/scripts/test-spaces.mjs@@ -50,6 +50,7 @@ const RIGS = [{ name: 'undo', file: 'scripts/test-spaces-undo.ts', bundle: true },{ name: 'invite', file: 'scripts/test-spaces-invite.ts', bundle: true },{ name: 'roundtrip', file: 'scripts/test-spaces-roundtrip.ts', bundle: true },+ { name: 'restore-gate', file: 'scripts/test-spaces-restore-gate.ts', bundle: true },{ name: 'size', file: 'scripts/test-spaces-size.mjs' },// Revision tracking has no timezone dependency; the browser rig needs the// built spaces shell and Playwright/Chrome (the CI browser job provides both).diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.mdindex ee61842b..7e69880e 100644--- a/spaces/CHANGELOG.md+++ b/spaces/CHANGELOG.md@@ -521,6 +521,17 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.About. A save that fails now says so ("Save failed — see console") instead ofleaving "Saving…" on screen, and the space stays unsaved.+- **Restoring from this browser checks what it restores.** The recovery+ banner's snapshot and every History entry are kept in the browser's storage,+ which every local Bento file shares, so they are now treated like a file+ that arrived from somewhere else, as Bento Slides already treats them. An+ entry that names a different space, is not a bento/spaces document, was+ written by a newer version, or is oversized is not restored: nothing+ changes, and the entry is left where it is. Text in a restored entry is+ cleaned the way an imported space's is. A bad entry never raises the+ recovery banner in the first place. Reading copies and view-only copies+ don't offer to restore at all.+## [0.1.0] — 2026-08-03First release.diff --git a/spaces/src/about.ts b/spaces/src/about.tsindex c91c1501..8749727d 100644--- a/spaces/src/about.ts+++ b/spaces/src/about.ts@@ -45,6 +45,7 @@ import { htmlToMd } from './marks.ts'import { humanBytes } from './assets'import { SPEC, mdLayout, type MdCtx } from './blocks'import { parseDoc, uid } from './model'+import { restoreInto } from './restoregate'import {issuesOf, passesFilter, sortRows, fieldByKey, optionOf, fieldsOf,} from './fields'@@ -584,13 +585,13 @@ export function openAbout(hooks: AboutHooks): void {doIt.textContent = t('Restore')b.append(left, tag, doIt)b.addEventListener('click', () => {- let restored: SpacesDoc- try { restored = JSON.parse(v.json) as SpacesDoc } catch {- say(t('That version could not be read')); return- }- // replaceDoc checkpoints undo first, so ⌘Z walks this back — the same- // contract the recovery banner's Restore already honours.- store.replaceDoc(restored)+ // FOREIGN INPUT, gated as the recovery banner gates it (restoregate.ts):+ // every file:// document shares this IndexedDB. A refusal applies+ // nothing and leaves the entry where it is.+ if (store.readOnly) { say(t('This file is open read-only')); return }+ // replaceDoc (inside restoreInto) checkpoints undo first, so ⌘Z walks+ // this back — the same contract the recovery banner's Restore honours.+ if (!restoreInto(store, v.json)) { say(t('That version could not be read')); return }onRepaint()close()say(t('Restored the version from {when} — ⌘Z undoes it', { when }))diff --git a/spaces/src/main.ts b/spaces/src/main.tsindex 4b3650b0..efcb99ec 100644--- a/spaces/src/main.ts+++ b/spaces/src/main.ts@@ -19,7 +19,8 @@ import { putRecovery, getRecovery, clearRecovery, pruneOld, addVersion } from '.import { APP_VERSION, applyUpdateInPlace } from '../../kernel/src/update.ts'import { t, locale, applyDirection } from './i18n'import { i18nApi } from '../../kernel/src/i18n.ts'-import { parseDoc, docContentKey, uid, newPage, type SpacesDoc, type ParseResult } from './model'+import { parseDoc, uid, newPage, type SpacesDoc, type ParseResult } from './model'+import { recoveryOffered, restoreInto } from './restoregate'import {validateDoc, outlineDoc, statsDoc,planInsertBlocks, planUpdateBlock, planRemoveBlocks, planMoveBlock, planUpdatePage, planRemovePage,@@ -632,15 +633,26 @@ function banner(text: string, actions: Array<[string, () => void]> = []): void {document.body.prepend(bar)}-/** A snapshot that differs from the file we loaded means a crash lost work. */+/**+ * A snapshot that differs from the file we loaded means a crash lost work.+ *+ * The snapshot is FOREIGN INPUT (restoregate.ts): every file:// document shares+ * this IndexedDB, so it is offered only when it passes the gate, and compared as+ * it WOULD be restored. An entry that is not this space, not a document, or+ * that gates down to what is already open never shows a banner at all — like+ * slides' checkRecovery.+ */async function offerRecovery(doc: SpacesDoc, store: Store, editor: Editor): Promise<void> {+ if (store.readOnly) return // a reading copy, a view-only follower or a frozen file is never rewrittenconst snap = await getRecovery(doc.docId)- if (!snap) return- let saved: SpacesDoc- try { saved = JSON.parse(snap.json) as SpacesDoc } catch { return }- if (docContentKey(saved) === docContentKey(doc)) return+ if (!snap || !recoveryOffered(snap.json, doc)) returnbanner(t('Unsaved changes from a previous session were found.'), [- [t('Restore'), () => { store.replaceDoc(saved); editor.repaint() }],+ [t('Restore'), () => {+ // re-gated against the space as it is NOW (restoreInto). A refusal+ // applies nothing and keeps the entry; only Discard deletes it.+ if (!restoreInto(store, snap.json)) { editor.status(t('That version could not be read')); return }+ editor.repaint()+ }],[t('Discard'), () => { void clearRecovery(doc.docId) }],])}diff --git a/spaces/src/restoregate.ts b/spaces/src/restoregate.tsnew file mode 100644index 00000000..fc99d908--- /dev/null+++ b/spaces/src/restoregate.ts@@ -0,0 +1,119 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// The gate a document kept in THIS BROWSER passes before it replaces the space+// that is open: the "Unsaved changes from a previous session" snapshot and+// every entry in History. Like slides' restoregate.ts, for the same reason.+//+// WHY IT IS A GATE AT ALL. Those snapshots are not the file. They live in+// IndexedDB under the space's docId, and on file:// every local .bento.html+// shares one origin — so the store is shared too, readable and writable by any+// other local document. A snapshot is therefore foreign input that arrives+// behind the most trusting prompt in the app ("restore YOUR changes"), and it+// used to go straight from JSON.parse into store.replaceDoc.+//+// So it is held to what an arriving file is held to, and to a little more:+// · bounded and prototype-safe before it is parsed at all;+// · it must name THIS space — a snapshot whose docId is not the open+// space's is refused, whatever key it was filed under;+// · `parseDoc` is the format, version and shape check a file open runs, and+// a snapshot this build would open frozen (newer version, unknown policy)+// is refused: a restore cannot open read-only, so it must not happen;+// · every block's html goes through `sanitizeInline`, the gate importSpace+// and the Markdown import put on arriving blocks — render sanitizes the+// same html again, so what a reader SEES is what a file open shows;+// · identity and capability (store.ts FROM_LIVE: docId, collab, readonly,+// template) are the OPEN space's, never the snapshot's. replaceDoc applies+// that too; it is applied here as well so the gate's output is already the+// document that will be installed, and the recovery check compares that.+//+// What it deliberately does NOT do that slides' gate does: drop unknown keys.+// The spaces format is additive — a file open keeps every field it does not+// understand and writes it back untouched — and a restore that silently lost+// them would be the one path that broke that promise.+//+// Deliberately free of the editor, so the rig runs it in node.++import { parseDoc, docContentKey, type SpacesDoc } from './model.ts'+import { sanitizeInline } from './sanitize.ts'+import { FROM_LIVE, type Store } from './store.ts'++/**+ * The largest snapshot the gate will parse, in UTF-16 code units of JSON.+ * Far above any space a person writes (a 200-page handbook is ~2.5 MB) and+ * above a space carrying a dozen embedded clips, but bounded: a foreign entry+ * must not be able to make opening a space parse a gigabyte.+ */+export const MAX_RESTORE_CHARS = 128 * 1024 * 1024++export type GateRefusal = 'size' | 'json' | 'proto' | 'format' | 'frozen' | 'docId'++/**+ * Gate a snapshot's JSON against the open space. Returns the document to+ * install — content from the snapshot, identity from `live` — or why it was+ * refused. A refusal is never applied and never deletes the entry.+ */+export function gateRestored(json: unknown, live: SpacesDoc):+ { ok: true; doc: SpacesDoc } | { ok: false; why: GateRefusal } {+ if (typeof json !== 'string' || json.length > MAX_RESTORE_CHARS) return { ok: false, why: 'size' }++ // PROTOTYPE-SAFE: a `__proto__` key anywhere refuses the whole entry. No+ // legitimate snapshot has one (every key is a format field or a minted id),+ // and refusing beats having to prove that no later spread, assign or merge+ // of this object ever treats it as the setter.+ let raw: unknown+ let proto = false+ try {+ raw = JSON.parse(json, function (k, v) { if (k === '__proto__') proto = true; return v })+ } catch { return { ok: false, why: 'json' } }+ if (proto) return { ok: false, why: 'proto' }+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { ok: false, why: 'json' }++ // THIS space's snapshot, or nothing. Checked on the RAW docId: parseDoc+ // mints one when it is missing, and a minted id is not this space either.+ if ((raw as { docId?: unknown }).docId !== live.docId) return { ok: false, why: 'docId' }++ const res = parseDoc(json)+ if (!res.ok) return { ok: false, why: 'format' }+ if (res.frozen) return { ok: false, why: 'frozen' }++ const doc = res.doc+ for (const page of doc.pages) {+ for (const b of page.blocks) if (typeof b.html === 'string' && b.html) b.html = sanitizeInline(b.html)+ }++ const from = live as Record<string, unknown>+ const to = doc as Record<string, unknown>+ for (const k of FROM_LIVE) {+ if (from[k] !== undefined) to[k] = from[k]+ else delete to[k]+ }+ return { ok: true, doc }+}++/**+ * Should the recovery banner be shown at all? Only for a snapshot that passes+ * the gate AND, compared as it would be restored, differs from what is open.+ * A forged or junk entry therefore never raises a banner — it cannot be used+ * to keep one on screen, any more than to restore through it.+ */+export function recoveryOffered(json: unknown, live: SpacesDoc): boolean {+ const g = gateRestored(json, live)+ return g.ok && docContentKey(g.doc) !== docContentKey(live)+}++/**+ * THE restore: the recovery banner's Restore and every History entry come+ * through here. Gated against the space as it is NOW — a live session may have+ * been joined, or the space duplicated under a new docId, since the entry was+ * listed — and a refusal applies nothing and deletes nothing. A read-only+ * store (a reading copy, a view-only follower, a frozen file) is never+ * rewritten from this browser's storage.+ */+export function restoreInto(store: Store, json: unknown): boolean {+ if (store.readOnly) return false+ const g = gateRestored(json, store.doc)+ if (!g.ok) return false+ store.replaceDoc(g.doc)+ return true+}