Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
type: a snapshot kept in this browser is gated before it is restored (#621)
nyblnetbadfe05c2cec
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 1ab074c4..22a86537 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1856,6 +1856,14 @@ jobs:# a null lookup there has silently broken the boot twice.run: node scripts/test-type-chrome.ts+ - name: Type restore-gate rig+ # A snapshot kept in the browser (Unsaved changes banner, Version+ # history) is foreign input: on file:// any local page can write it.+ # Restoring one never brings its own docId, room/keys or mode, and an+ # honest one keeps the open file's sharing. Replace from JSON — a+ # document the person chose — is NOT gated. Counterpart of slides'.+ run: node scripts/test-type-restore-gate.ts+- name: Clipboard embedded-font rigrun: |slides/node_modules/.bin/esbuild scripts/test-clipboard.ts --bundle --platform=node --format=esm --outfile="$RUNNER_TEMP/test-clipboard.mjs"diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex c41861ac..159b3b9f 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -7889,3 +7889,30 @@ is not undoable whichever action changed it. slides behaves the same.adapter, undoes all the way back checking at every step, and covers each fieldincluding one that is absent in the live document. Reverting to the full swapreddens every identity row and the undo-must-not-unlock pair.++## 2026-10-04 — A browser-kept snapshot is gated before it is restored (type)++**Restoring something this browser kept — the "Unsaved changes … were found"+banner, or a Version history entry — passes `gateRestored`+(type/src/restoregate.ts), the counterpart of slides' restoregate.ts.** The+snapshot goes through `parseDoc` (recovery used to `JSON.parse` it with no+format check at all), and its `docId`, `collab` and `readonly` are always the+OPEN file's — the same `FROM_LIVE` list undo uses. Those snapshots live in+IndexedDB, which on file:// every local document shares (see 2026-09-19), so+they are foreign input arriving behind the app's most trusting prompt.++**It also fixes a bug that needed no forger.** The kernel writes snapshots+without `collab` (autosave.ts `contentOnly`), so restoring your OWN unsaved+changes replaced the document with one that had no room credentials at all —+measured: on a view-only copy that dropped `collab` and, through the+read-only lock, made the copy editable. With the gate, the open file's sharing+survives every restore.++**Restore is not open.** Opening a file and "Replace from JSON…" are documents+the person chose, and keep their own identity; only a browser-kept snapshot is+gated. Version history therefore has its own hook (`onRestoreDoc`) rather than+reusing Replace from JSON's, which is how it had come to carry the snapshot's+identity in. slides' gate additionally rebuilds content key by key; type has+no such layer, and its renderer already treats any opened file's content as+untrusted — the risk specific to a snapshot is the identity and capability,+which is what this closes. `test-type-restore-gate.ts` pins it.diff --git a/scripts/test-type-restore-gate.ts b/scripts/test-type-restore-gate.tsnew file mode 100644index 00000000..c6eacda8--- /dev/null+++ b/scripts/test-type-restore-gate.ts@@ -0,0 +1,143 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// A document kept in this browser is gated before it replaces the open one —+// the bento/type counterpart of test-slides-restore-gate.ts.+//+// node scripts/test-type-restore-gate.ts+//+// WHAT THIS PROVES. The "Unsaved changes … were found — Restore" snapshot and+// every Version history entry live in IndexedDB under the document's docId,+// and on file:// that store is shared by every local document. Restore used to+// hand the stored JSON straight to store.replace: recovery via a bare+// JSON.parse (no format check at all), version history via the SAME handler as+// "Replace from JSON…". Now (type/src/restoregate.ts):+// 1. a snapshot never brings identity or capability: docId, collab and+// readonly are the OPEN FILE's, present or absent, whatever it carries —+// including a forged docId and a forged room/key;+// 2. an HONEST snapshot keeps the document's sharing: kernel writes+// snapshots WITHOUT collab (autosave.ts contentOnly), so the old path+// silently dropped the room credentials on every restore, and turned a+// view-only copy into an editable local one;+// 3. an honest snapshot's content comes back as it went in;+// 4. something that is not a bento/type document is never offered;+// 5. every restore path goes through the gate — and "Replace from JSON…",+// which is a document the person chose, does NOT: it keeps its own+// identity.+// Not proven here, deliberately: slides' gate also rebuilds content key by key+// (untrusted.ts). bento/type has no such layer — see restoregate.ts.++import { register } from 'node:module'+import { readFileSync } from 'node:fs'+register('./lib/ts-resolve-hooks.mjs', import.meta.url)+const { gateRestored } = await import('../type/src/restoregate.ts')+const { Store } = await import('../type/src/store.ts')+const { emptyDoc, parseDoc } = await import('../type/src/model.ts')+import type { TypeDoc } from '../type/src/model.ts'++let checks = 0, failures = 0+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`) } else console.log(` ok ${m}`) }+const read = (p: string) => readFileSync(new URL('../' + p, import.meta.url), 'utf8')++// A real document, through parseDoc the way a file reaches the editor.+const docOf = (over: object = {}): TypeDoc => {+ const r = parseDoc(JSON.stringify({ ...emptyDoc(), body: [{ id: 'p1', kind: 'para', text: 'agreed terms' }], ...over }))+ if (!r.ok) throw new Error('fixture did not parse')+ return r.doc+}+// What kernel/src/autosave.ts contentOnly() writes into a snapshot: the+// document WITHOUT collab. Pinned against the kernel source below, so this+// fixture cannot quietly drift from what the browser really stores.+const snapshotOf = (d: TypeDoc): string => { const { collab: _c, ...rest } = d as TypeDoc & { collab?: unknown }; return JSON.stringify(rest) }+const ROOM = { v: 2, on: true, room: 'w-mine', key: 'MY-KEY', owner: 'OP', ownerPriv: 'OK' }++console.log('\na snapshot never brings identity or capability\n')+{+ const live = docOf({ collab: ROOM })+ // FORGED: a snapshot planted under this docId by another local page,+ // claiming to be a different document, in a different room, read-only.+ const forged = JSON.stringify({ ...docOf(), docId: 'doc-ATTACKER', readonly: true,+ body: [{ id: 'p1', kind: 'para', text: 'planted text' }],+ collab: { v: 2, on: true, room: 'w-EVIL', key: 'EVIL-KEY', owner: 'EVIL-PUB', ownerPriv: 'EVIL-PRIV' } })+ const g = gateRestored(forged, live)!+ ok(g.docId === live.docId, 'cross-docId forgery: the restored document keeps the OPEN file\'s docId')+ ok(g.collab?.room === 'w-mine' && g.collab?.key === 'MY-KEY',+ 'forged collab: the room and key are the open file\'s, never the snapshot\'s')+ ok(!JSON.stringify(g).includes('EVIL'), 'and nothing of the forged credentials survives anywhere in the result')+ ok(!('readonly' in g), 'a forged readonly is dropped — the open file has no mode set, so neither does the result')+ ok(g.body[0].text === 'planted text', 'its CONTENT is what is restored (that is the feature)')++ // the other direction: the open file IS read-only / view-only+ const viewOnly = docOf({ readonly: true, collab: { ...ROOM, ownerPriv: undefined, role: 'reader' } })+ const unlockAttempt = JSON.stringify({ ...docOf(), readonly: false, collab: { ...ROOM } })+ const st = new Store(viewOnly)+ st.replace(gateRestored(unlockAttempt, st.doc)!)+ ok(st.locked && st.doc.collab?.role === 'reader',+ 'a snapshot forging WRITER credentials onto a view-only copy cannot unlock it (#588\'s lock reads collab)')+ ok((st.doc as { readonly?: boolean }).readonly === true, 'nor clear its read-only mode')+}++console.log('\nan honest snapshot keeps the document\'s sharing\n')+{+ // The bug that needs no forger: kernel writes snapshots WITHOUT collab.+ const writer = docOf({ collab: ROOM })+ const snap = snapshotOf({ ...writer, body: [{ id: 'p1', kind: 'para', text: 'my unsaved words' }] } as TypeDoc)+ ok(!JSON.parse(snap).collab, 'a real snapshot carries no collab (kernel contentOnly)')+ const g = gateRestored(snap, writer)!+ ok(g.collab?.room === 'w-mine' && g.collab?.key === 'MY-KEY',+ 'restoring it KEEPS the room credentials — the old path dropped them on every restore')+ const reader = docOf({ collab: { ...ROOM, ownerPriv: undefined, role: 'reader' } })+ const st = new Store(reader)+ st.replace(gateRestored(snapshotOf(reader), st.doc)!)+ ok(st.locked, 'and a view-only copy stays view-only — the old path turned it into an editable local document')+}++console.log('\nan honest snapshot round-trips\n')+{+ const live = docOf({ title: 'Lease', collab: ROOM,+ body: [{ id: 'h', kind: 'h1', text: 'Lease' }, { id: 'p', kind: 'para', text: 'Rent is due monthly.' }] })+ const g = gateRestored(snapshotOf(live), live)!+ const strip = (d: TypeDoc) => { const { modified: _m, ...r } = d as TypeDoc & { modified?: unknown }; return JSON.stringify(r) }+ ok(strip(g) === strip(live), 'content, title and identity come back as they went in, key for key')+}++console.log('\nnot a document → never offered\n')+{+ const live = docOf({ collab: ROOM })+ ok(gateRestored('{not json', live) === null, 'malformed JSON is not offered')+ ok(gateRestored('', live) === null, 'an empty snapshot is not offered')+ ok(gateRestored(JSON.stringify({ format: 'bento/slides', slides: [] }), live) === null,+ 'another app\'s document is not offered as a bento/type restore')+}++console.log('\nrestore is gated; opening a document is not\n')+{+ // Replace from JSON / opening a file: a document the person CHOSE — it keeps+ // its own identity. parseDoc + store.replace, exactly as main.ts does.+ const chosen = docOf({ docId: 'doc-CHOSEN', collab: { ...ROOM, room: 'w-theirs', key: 'THEIR-KEY' } })+ const st = new Store(docOf({ collab: ROOM }))+ const r = parseDoc(JSON.stringify(chosen)); st.replace(r.ok ? r.doc : st.doc)+ ok(st.doc.docId === 'doc-CHOSEN' && st.doc.collab?.room === 'w-theirs',+ 'Replace from JSON keeps the CHOSEN document\'s own identity — that is not a restore')+}++console.log('\nevery restore path uses the gate\n')+{+ const autosave = read('type/src/autosave.ts')+ ok(!/JSON\.parse\(\s*snap\.json/.test(autosave), 'type/src/autosave.ts: no raw JSON.parse of a stored snapshot remains')+ ok((autosave.match(/gateRestored\(snap\.json/g) ?? []).length >= 2,+ 'type/src/autosave.ts: recovery gates when the banner appears AND again at the click')+ const about = read('type/src/about.ts')+ const history = about.slice(about.indexOf('function openVersionHistory'))+ ok(/onRestoreDoc\(v\.json\)/.test(history) && !/onReplaceDoc\(v\.json\)/.test(history),+ 'type/src/about.ts: Version history restores through onRestoreDoc, not Replace from JSON\'s hook')+ const main = read('type/src/main.ts')+ const hook = main.slice(main.indexOf('onRestoreDoc:'), main.indexOf('onRestoreDoc:') + 400)+ ok(/gateRestored\(json, store\.doc\)/.test(hook), 'type/src/main.ts: onRestoreDoc goes through gateRestored')+ const kernel = read('kernel/src/autosave.ts')+ ok(/function contentOnly[\s\S]{0,120}collab/.test(kernel),+ 'kernel/src/autosave.ts: snapshots are still written without collab — the fixture above matches the real thing')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/type/src/about.ts b/type/src/about.tsindex 67fe243a..a450fcf8 100644--- a/type/src/about.ts+++ b/type/src/about.ts@@ -31,12 +31,18 @@ export interface AboutHooks {/** pages, from the last pagination pass — the dialog does not re-measure */pages: number;onReplaceDoc(json: string): void;+ /**+ * Restore a version THIS BROWSER kept. Not onReplaceDoc: a pasted document+ * keeps its own identity, a browser-kept snapshot never does — it is gated+ * (restoregate.ts) and takes docId, collab and readonly from the open file.+ */+ onRestoreDoc(json: string): void;}const esc = (s: string) => s.replace(/[&<>"]/g, c =>({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]!));-export function openAbout({ store, pages, onReplaceDoc }: AboutHooks): void {+export function openAbout({ store, pages, onReplaceDoc, onRestoreDoc }: AboutHooks): void {const back = document.createElement('div');back.className = 't-overlay';const card = document.createElement('div');@@ -209,13 +215,15 @@ export function openAbout({ store, pages, onReplaceDoc }: AboutHooks): void {// ---- version history -----------------------------------------------------//// Browses the auto-save timeline autosave.ts keeps in IndexedDB (never in- // the file, never online). Restoring reuses `onReplaceDoc` exactly as- // "Replace from JSON…" does above — `Snapshot.json` already IS a bento/type- // document JSON string — so this needed no new hook into main.ts: parseDoc- // validates it, store.replace makes it undoable, editor.render() repaints.+ // the file, never online). Restoring does NOT reuse `onReplaceDoc`, though it+ // once did — `Snapshot.json` already is a bento/type document, so it looked+ // like the same act. It is not: Replace from JSON is a document the person+ // chose, and keeps its own identity; a snapshot is foreign input from a store+ // any local page can write, and must not bring its own docId, room or mode.+ // So it has its own hook, which goes through restoregate.ts.const historyRow = document.createElement('div');historyRow.className = 't-row';- historyRow.append(button(t('Version history…'), () => openVersionHistory({ store, onReplaceDoc, close })));+ historyRow.append(button(t('Version history…'), () => openVersionHistory({ store, onRestoreDoc, close })));card.append(historyRow);card.append(p(t('Versions are saved automatically as you edit, kept only in this browser, ' +@@ -248,7 +256,7 @@ export function openAbout({ store, pages, onReplaceDoc }: AboutHooks): void {* render synchronously the moment the wordmark is clicked.*/async function openVersionHistory(- { store, onReplaceDoc, close: closeAbout }: { store: Store; onReplaceDoc(json: string): void; close(): void },+ { store, onRestoreDoc, close: closeAbout }: { store: Store; onRestoreDoc(json: string): void; close(): void },): Promise<void> {const versions = await listVersions(store.doc.docId);@@ -285,7 +293,7 @@ async function openVersionHistory(doIt.textContent = t('Restore');rowEl.append(label, doIt);rowEl.addEventListener('click', () => {- onReplaceDoc(v.json);+ onRestoreDoc(v.json);close();closeAbout();});diff --git a/type/src/autosave.ts b/type/src/autosave.tsindex 9cb2756e..9f707779 100644--- a/type/src/autosave.ts+++ b/type/src/autosave.ts@@ -36,6 +36,7 @@ import {import { canonicalize } from './canon.ts';import { registerReady, type FeatureContext } from './features.ts';import type { TypeDoc } from './model.ts';+import { gateRestored } from './restoregate.ts';import { t } from './i18n.ts';export { putRecovery, getRecovery, clearRecovery, addVersion, listVersions, pruneOld, clearVersions };@@ -101,14 +102,17 @@ async function checkRecovery(ctx: FeatureContext): Promise<void> {const doc = ctx.store.doc;const snap = await getRecovery(doc.docId);if (!snap) return;- let recovered: TypeDoc;- try { recovered = JSON.parse(snap.json) as TypeDoc; } catch { return; }+ // A snapshot is foreign input (restoregate.ts): format-checked, and never+ // allowed to bring its own identity. Anything parseDoc refuses is simply+ // not offered — the file on disk is still the file.+ const recovered = gateRestored(snap.json, doc);+ if (!recovered) return;// The file on disk already has these edits (this save cycle wrote both) —// nothing to offer back. Compared with the shared content key, not a// byte comparison, so volatile churn (modified timestamps, sync state)// never trips a false banner.if (docContentKey(recovered) === docContentKey(doc)) return;- showRecoveryBanner(ctx, snap, recovered);+ showRecoveryBanner(ctx, snap);}let styleInjected = false;@@ -131,7 +135,7 @@ function ensureStyle(): void {document.head.appendChild(style);}-function showRecoveryBanner(ctx: FeatureContext, snap: Snapshot, recovered: TypeDoc): void {+function showRecoveryBanner(ctx: FeatureContext, snap: Snapshot): void {ensureStyle();document.querySelector('.t-recover')?.remove();const bar = document.createElement('div');@@ -145,9 +149,15 @@ function showRecoveryBanner(ctx: FeatureContext, snap: Snapshot, recovered: Typerestore.type = 'button';restore.textContent = t('Restore');restore.addEventListener('click', () => {- // Through the store, so this is one ⌘Z away from undone — never a- // silent, un-undoable swap of the document under the author.- ctx.store.replace(recovered);+ // Gated AGAIN, against the document open at the click: identity comes from+ // the live document, and that can change while this banner is up (Stop+ // sharing, Reset access). Through the store, so this is one ⌘Z away from+ // undone — never a silent, un-undoable swap of the document under the author.+ const gated = gateRestored(snap.json, ctx.store.doc);+ // Never fall back to the copy gated when the banner appeared: its identity+ // was the document's THEN, which is the staleness this re-gate exists for.+ if (!gated) { bar.remove(); return; }+ ctx.store.replace(gated);ctx.refresh();bar.remove();ctx.toast(t('Restored your unsaved changes'));diff --git a/type/src/i18n/de.ts b/type/src/i18n/de.tsindex fe305132..d32901b4 100644--- a/type/src/i18n/de.ts+++ b/type/src/i18n/de.ts@@ -273,6 +273,7 @@ export const de: Catalog = {"That is already a caption": "Das ist bereits eine Beschriftung","That is not a bento/type document: {detail}": "Dies ist kein bento/type-Dokument: {detail}","That is not an address this document can link to": "Dies ist keine Adresse, zu der dieses Dokument verlinken kann",+ "That saved version could not be restored.": "Diese gespeicherte Version konnte nicht wiederhergestellt werden.","That sheet is larger than any printer takes.": "Dieses Blatt ist größer, als jeder Drucker verarbeiten kann.","That sheet is smaller than 2 inches — pick a bigger page.": "Dieses Blatt ist kleiner als 2 Zoll – wählen Sie eine größere Seite.","The document is the interchange unit: hand this JSON to an AI, get one back, and paste it in. `window.bento` exposes the same thing to scripts.": "Das Dokument ist die Austauscheinheit: Geben Sie dieses JSON an eine KI weiter, holen Sie eines zurück und fügen Sie es ein. `window.bento` stellt Skripten dasselbe bereit.",diff --git a/type/src/i18n/es.ts b/type/src/i18n/es.tsindex 78b059af..ce709014 100644--- a/type/src/i18n/es.ts+++ b/type/src/i18n/es.ts@@ -273,6 +273,7 @@ export const es: Catalog = {"That is already a caption": "Eso ya es un título","That is not a bento/type document: {detail}": "No es un documento de bento/type: {detail}","That is not an address this document can link to": "Esa no es una dirección a la que este documento pueda enlazar",+ "That saved version could not be restored.": "No se pudo restaurar esa versión guardada.","That sheet is larger than any printer takes.": "Esa hoja es más grande de lo que admite cualquier impresora.","That sheet is smaller than 2 inches — pick a bigger page.": "Esa hoja mide menos de 2 pulgadas: elige una página más grande.","The document is the interchange unit: hand this JSON to an AI, get one back, and paste it in. `window.bento` exposes the same thing to scripts.": "El documento es la unidad de intercambio: entrega este JSON a una IA, recibe otro y pégalo aquí. `window.bento` expone lo mismo a los scripts.",diff --git a/type/src/i18n/fr.ts b/type/src/i18n/fr.tsindex 9557de9a..b0eca3f2 100644--- a/type/src/i18n/fr.ts+++ b/type/src/i18n/fr.ts@@ -273,6 +273,7 @@ export const fr: Catalog = {"That is already a caption": "C'est déjà une légende","That is not a bento/type document: {detail}": "Ce n'est pas un document bento/type : {detail}","That is not an address this document can link to": "Ce n'est pas une adresse vers laquelle ce document peut créer un lien",+ "That saved version could not be restored.": "Impossible de restaurer cette version enregistrée.","That sheet is larger than any printer takes.": "Cette feuille est plus grande que ce qu'accepte n'importe quelle imprimante.","That sheet is smaller than 2 inches — pick a bigger page.": "Cette feuille fait moins de 2 pouces — choisissez une page plus grande.","The document is the interchange unit: hand this JSON to an AI, get one back, and paste it in. `window.bento` exposes the same thing to scripts.": "Le document est l'unité d'échange : donnez ce JSON à une IA, récupérez-en un et collez-le ici. `window.bento` expose la même chose aux scripts.",diff --git a/type/src/i18n/it.ts b/type/src/i18n/it.tsindex ba809d60..e1aac3ad 100644--- a/type/src/i18n/it.ts+++ b/type/src/i18n/it.ts@@ -273,6 +273,7 @@ export const it: Catalog = {"That is already a caption": "Questa è già una didascalia","That is not a bento/type document: {detail}": "Non è un documento bento/type: {detail}","That is not an address this document can link to": "Non è un indirizzo a cui questo documento può collegarsi",+ "That saved version could not be restored.": "Impossibile ripristinare quella versione salvata.","That sheet is larger than any printer takes.": "Quel foglio è più grande di quanto qualsiasi stampante possa gestire.","That sheet is smaller than 2 inches — pick a bigger page.": "Quel foglio è più piccolo di 2 pollici: scegli una pagina più grande.","The document is the interchange unit: hand this JSON to an AI, get one back, and paste it in. `window.bento` exposes the same thing to scripts.": "Il documento è l'unità di interscambio: consegna questo JSON a un'IA, riceverne uno e incollalo qui. `window.bento` espone la stessa cosa agli script.",diff --git a/type/src/i18n/ja.ts b/type/src/i18n/ja.tsindex 8af62082..cea614dc 100644--- a/type/src/i18n/ja.ts+++ b/type/src/i18n/ja.ts@@ -273,6 +273,7 @@ export const ja: Catalog = {"That is already a caption": "それはすでにキャプションです","That is not a bento/type document: {detail}": "bento/type の文書ではありません:{detail}","That is not an address this document can link to": "この文書からリンクできるアドレスではありません",+ "That saved version could not be restored.": "保存されたバージョンを復元できませんでした。","That sheet is larger than any printer takes.": "その用紙サイズはどのプリンターにも対応していません。","That sheet is smaller than 2 inches — pick a bigger page.": "その用紙サイズは 2 インチ未満です — もっと大きいページを選んでください。","The document is the interchange unit: hand this JSON to an AI, get one back, and paste it in. `window.bento` exposes the same thing to scripts.": "文書そのものが交換単位です — この JSON を AI に渡して受け取った JSON を貼り付けてください。スクリプトからは `window.bento` で同じものを利用できます。",diff --git a/type/src/i18n/packed.ts b/type/src/i18n/packed.tsindex 2317b404..0b966335 100644--- a/type/src/i18n/packed.ts+++ b/type/src/i18n/packed.ts@@ -314,6 +314,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"That is already a caption": ["それはすでにキャプションです","这已经是题注","這已經是題注","Eso ya es un título","C'est déjà une légende","Das ist bereits eine Beschriftung","Questa è già una didascalia","Isso já é uma legenda"],"That is not a bento/type document: {detail}": ["bento/type の文書ではありません:{detail}","这不是 bento/type 文档:{detail}","這不是 bento/type 文件:{detail}","No es un documento de bento/type: {detail}","Ce n'est pas un document bento/type : {detail}","Dies ist kein bento/type-Dokument: {detail}","Non è un documento bento/type: {detail}","Isso não é um documento bento/type: {detail}"],"That is not an address this document can link to": ["この文書からリンクできるアドレスではありません","这不是本文档可以链接到的地址","這不是本文件可以連結到的位址","Esa no es una dirección a la que este documento pueda enlazar","Ce n'est pas une adresse vers laquelle ce document peut créer un lien","Dies ist keine Adresse, zu der dieses Dokument verlinken kann","Non è un indirizzo a cui questo documento può collegarsi","Esse não é um endereço ao qual este documento pode vincular"],+ "That saved version could not be restored.": ["保存されたバージョンを復元できませんでした。","无法恢复该已保存的版本。","無法還原該已儲存的版本。","No se pudo restaurar esa versión guardada.","Impossible de restaurer cette version enregistrée.","Diese gespeicherte Version konnte nicht wiederhergestellt werden.","Impossibile ripristinare quella versione salvata.","Não foi possível restaurar essa versão salva."],"That sheet is larger than any printer takes.": ["その用紙サイズはどのプリンターにも対応していません。","该纸张尺寸超出了任何打印机的支持范围。","該紙張尺寸超出任何印表機的支援範圍。","Esa hoja es más grande de lo que admite cualquier impresora.","Cette feuille est plus grande que ce qu'accepte n'importe quelle imprimante.","Dieses Blatt ist größer, als jeder Drucker verarbeiten kann.","Quel foglio è più grande di quanto qualsiasi stampante possa gestire.","Essa folha é maior do que qualquer impressora aceita."],"That sheet is smaller than 2 inches — pick a bigger page.": ["その用紙サイズは 2 インチ未満です — もっと大きいページを選んでください。","该纸张尺寸小于 2 英寸——请选择更大的页面。","該紙張尺寸小於 2 英吋 — 請選擇更大的頁面。","Esa hoja mide menos de 2 pulgadas: elige una página más grande.","Cette feuille fait moins de 2 pouces — choisissez une page plus grande.","Dieses Blatt ist kleiner als 2 Zoll – wählen Sie eine größere Seite.","Quel foglio è più piccolo di 2 pollici: scegli una pagina più grande.","Essa folha é menor que 2 polegadas — escolha uma página maior."],"The document is the interchange unit: hand this JSON to an AI, get one back, and paste it in. `window.bento` exposes the same thing to scripts.": ["文書そのものが交換単位です — この JSON を AI に渡して受け取った JSON を貼り付けてください。スクリプトからは `window.bento` で同じものを利用できます。","文档本身就是交换单元:把这段 JSON 交给 AI,拿到返回结果后粘贴回来即可。脚本可通过 `window.bento` 使用同样的接口。","文件本身就是交換單元:把這段 JSON 交給 AI,拿到回傳結果後貼回來即可。指令碼可透過 `window.bento` 使用相同的介面。","El documento es la unidad de intercambio: entrega este JSON a una IA, recibe otro y pégalo aquí. `window.bento` expone lo mismo a los scripts.","Le document est l'unité d'échange : donnez ce JSON à une IA, récupérez-en un et collez-le ici. `window.bento` expose la même chose aux scripts.","Das Dokument ist die Austauscheinheit: Geben Sie dieses JSON an eine KI weiter, holen Sie eines zurück und fügen Sie es ein. `window.bento` stellt Skripten dasselbe bereit.","Il documento è l'unità di interscambio: consegna questo JSON a un'IA, riceverne uno e incollalo qui. `window.bento` espone la stessa cosa agli script.","O documento é a unidade de intercâmbio: entregue este JSON a uma IA, receba outro de volta e cole-o aqui. `window.bento` expõe a mesma coisa para scripts."],diff --git a/type/src/i18n/pt.ts b/type/src/i18n/pt.tsindex f85ce8eb..a47dbac1 100644--- a/type/src/i18n/pt.ts+++ b/type/src/i18n/pt.ts@@ -317,6 +317,7 @@ export const pt: Catalog = {"That is already a caption": "Isso já é uma legenda","That is not a bento/type document: {detail}": "Isso não é um documento bento/type: {detail}","That is not an address this document can link to": "Esse não é um endereço ao qual este documento pode vincular",+ "That saved version could not be restored.": "Não foi possível restaurar essa versão salva.","That sheet is larger than any printer takes.": "Essa folha é maior do que qualquer impressora aceita.","That sheet is smaller than 2 inches — pick a bigger page.": "Essa folha é menor que 2 polegadas — escolha uma página maior.","The document is the interchange unit: hand this JSON to an AI, get one back, and paste it in. `window.bento` exposes the same thing to scripts.": "O documento é a unidade de intercâmbio: entregue este JSON a uma IA, receba outro de volta e cole-o aqui. `window.bento` expõe a mesma coisa para scripts.",diff --git a/type/src/i18n/zh-Hans.ts b/type/src/i18n/zh-Hans.tsindex f69dd281..1cede893 100644--- a/type/src/i18n/zh-Hans.ts+++ b/type/src/i18n/zh-Hans.ts@@ -273,6 +273,7 @@ export const zhHans: Catalog = {"That is already a caption": "这已经是题注","That is not a bento/type document: {detail}": "这不是 bento/type 文档:{detail}","That is not an address this document can link to": "这不是本文档可以链接到的地址",+ "That saved version could not be restored.": "无法恢复该已保存的版本。","That sheet is larger than any printer takes.": "该纸张尺寸超出了任何打印机的支持范围。","That sheet is smaller than 2 inches — pick a bigger page.": "该纸张尺寸小于 2 英寸——请选择更大的页面。","The document is the interchange unit: hand this JSON to an AI, get one back, and paste it in. `window.bento` exposes the same thing to scripts.": "文档本身就是交换单元:把这段 JSON 交给 AI,拿到返回结果后粘贴回来即可。脚本可通过 `window.bento` 使用同样的接口。",diff --git a/type/src/i18n/zh-Hant.ts b/type/src/i18n/zh-Hant.tsindex 4ac0f3bc..c6c214ad 100644--- a/type/src/i18n/zh-Hant.ts+++ b/type/src/i18n/zh-Hant.ts@@ -273,6 +273,7 @@ export const zhHant: Catalog = {"That is already a caption": "這已經是題注","That is not a bento/type document: {detail}": "這不是 bento/type 文件:{detail}","That is not an address this document can link to": "這不是本文件可以連結到的位址",+ "That saved version could not be restored.": "無法還原該已儲存的版本。","That sheet is larger than any printer takes.": "該紙張尺寸超出任何印表機的支援範圍。","That sheet is smaller than 2 inches — pick a bigger page.": "該紙張尺寸小於 2 英吋 — 請選擇更大的頁面。","The document is the interchange unit: hand this JSON to an AI, get one back, and paste it in. `window.bento` exposes the same thing to scripts.": "文件本身就是交換單元:把這段 JSON 交給 AI,拿到回傳結果後貼回來即可。指令碼可透過 `window.bento` 使用相同的介面。",diff --git a/type/src/main.ts b/type/src/main.tsindex 4a7f8513..7a8f2d4b 100644--- a/type/src/main.ts+++ b/type/src/main.ts@@ -18,6 +18,7 @@ import { i18nApi } from '../../kernel/src/i18n.ts';import { openAbout } from './about.ts';import { startTheme, setTheme, themeChoice, type ThemeChoice } from '../../kernel/src/theme.ts';import { parseDoc, emptyDoc, uid, wordCount, type TypeDoc } from './model.ts';+import { gateRestored } from './restoregate.ts';import { Store } from './store.ts';import { Editor } from './editor.ts';import { paginate, drawPages, type Metrics } from './paginate.ts';@@ -239,6 +240,15 @@ const showAbout = () => openAbout({schedule();} catch { alert(t('That JSON could not be read.')); }},+ // A version THIS BROWSER kept — gated, never trusted for identity. See+ // restoregate.ts for why this is not onReplaceDoc.+ onRestoreDoc: json => {+ const doc = gateRestored(json, store.doc);+ if (!doc) { alert(t('That saved version could not be restored.')); return; }+ store.replace(doc);+ editor.render();+ schedule();+ },});byId('mark').addEventListener('click', showAbout);byId('about').addEventListener('click', showAbout);diff --git a/type/src/restoregate.ts b/type/src/restoregate.tsnew file mode 100644index 00000000..fa4c4e93--- /dev/null+++ b/type/src/restoregate.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// The gate a document kept in THIS BROWSER passes before it replaces the one+// that is open: the "Unsaved changes … were found — Restore" snapshot, and+// every entry in Version history. The type counterpart of bento/slides'+// restoregate.ts.+//+// WHY IT IS A GATE AT ALL. Those snapshots are not the file. They live in+// IndexedDB under the document's docId, and on file:// every local+// .bento.html shares one origin (docs/DECISIONS.md, 2026-09-19) — so the+// store is shared too, readable and writable by any other local page. A+// snapshot is therefore FOREIGN INPUT, arriving behind the most trusting+// prompt in the app ("restore YOUR unsaved changes"). It used to reach+// store.replace as raw JSON.parse output, with no format check at all, and+// carrying its own identity: a planted snapshot could swap in a different+// docId, a different room and keys (`collab`), or drop the file's mode.+//+// So a snapshot is (1) put through parseDoc, the same format check a file+// gets, and anything parseDoc refuses is not offered; and (2) never allowed+// to bring its own IDENTITY or CAPABILITY. docId, collab and readonly are the+// OPEN FILE's, whatever the snapshot says — the same list undo uses+// (store.ts FROM_LIVE), and the same as slides'. Content is restored; who+// the document is, which room it syncs with and whether it can be edited are+// not.+//+// RESTORE IS NOT OPEN. Opening a file and "Replace from JSON…" keep the+// incoming document's own identity — the person chose that document, and it+// is the thing they want to be holding. Only a restore of something this+// browser kept is gated. That is why version history has its own hook+// (about.ts onRestoreDoc) instead of reusing Replace from JSON's.+//+// What this does NOT do, deliberately and stated: slides' gate also rebuilds+// content key by key through its untrusted.ts. bento/type has no such layer;+// its renderer already has to treat any opened file's content as untrusted,+// so the risk SPECIFIC to a browser-held snapshot is the identity and+// capability it could smuggle under that prompt, which is what this closes.+//+// DOM-free, so scripts/test-type-restore-gate.ts runs it in node.++import { parseDoc, type TypeDoc } from './model.ts';+import { keepLiveIdentity } from './store.ts';++/**+ * A browser-kept snapshot, made safe to restore over `live` — or null when it+ * is not a bento/type document at all, in which case nothing is offered.+ *+ * Call it at the moment of restoring, with the document that is open THEN:+ * identity is taken from the live document, and the live document can change+ * between showing a prompt and the click that accepts it.+ */+export function gateRestored(json: string, live: TypeDoc): TypeDoc | null {+ const parsed = parseDoc(json);+ if (!parsed.ok) return null;+ const doc = parsed.doc;+ keepLiveIdentity(doc, live);+ return doc;+}diff --git a/type/src/store.ts b/type/src/store.tsindex 4d9264fb..9c4e40ee 100644--- a/type/src/store.ts+++ b/type/src/store.ts@@ -58,7 +58,7 @@ const LIMIT = 200;*/export const FROM_LIVE = ['docId', 'collab', 'readonly'] as const;-function keepLiveIdentity(doc: TypeDoc, live: TypeDoc): void {+export function keepLiveIdentity(doc: TypeDoc, live: TypeDoc): void {const d = doc as unknown as Record<string, unknown>;const l = live as unknown as Record<string, unknown>;for (const k of FROM_LIVE) {