Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
spaces: sealed-body guards, no plaintext left behind, neutral title while sealed (K3) (#790)
nyblnet08b6be988398
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 55638cf7..f901746c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -2875,10 +2875,18 @@ jobs:run: |npm ci --prefix spacesnpm run build:single --prefix spaces+ npm run build:sealtest --prefix spaces- name: Exercise the packaged documents in Chromium# Real UI and serialization, offline; delayed mock writes expose save races.run: |node scripts/test-spaces-save-browser.mjs+ - name: A sealed space writes nothing readable (spaces, Chromium)+ # The build:sealtest shell booted identity-sealed through the shared+ # helper, plus a password space: no recovery snapshot or version in+ # IndexedDB (also across a reload), no preview and no plaintext in the+ # saved file, a neutral tab title, no recovery-off notice. The unsealed+ # control shows each check can see a leak.+ run: node scripts/test-spaces-sealed-browser.mjs- name: One field look in Chromium (spaces)# Port of slides' fields rig: every chrome text field, select and# textarea (inspector incl. "Also known as", dialogs, view popovers,diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 5bdab317..3a907d50 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -11320,6 +11320,38 @@ shell it serves (gate 1, A2).Still for a real phone: TEE and StrongBox residency (the emulator reportssoftware keys), and the API 26–29 consent path, which allows biometrics only.+## 2026-10-18 — bento/spaces: which checks ask isBodySealed, and the tab title while sealed++Every plaintext-to-disk guard in spaces asks `isBodySealed()` (a password OR the+identity seal): the recovery snapshot and throttled version on the autosave+debounce, the version added on save, and the recovery-off notice (main.ts). The+two places that still ask `isEncryptionActive()` are the password UI in+doccmds.ts: the Change/Remove password rows act on a password an+identity-sealed space does not have, and the version-history note names the+password. A new guard on anything written beside the file asks+`isBodySealed()`.++Neutral title while sealed, matching the saved file's title. Every write to+`document.title` goes through `spaces/src/tabtitle.ts` (boot, the password+gate, rename, setting or removing a password).++Guarded by `scripts/test-spaces-sealed-browser.mjs` on the build:sealtest+shell, with an unsealed control. Reverting either main.ts guard, or the title+helper, turns it red.++**Plaintext an unsealed session left behind (security ruling, option a).** A+sealed boot (the seal is in place before boot(), so this is the proven state)+never offers a recovery snapshot for its docId and lists no version history;+it then DELETES that docId's recovery snapshot and versions through the+kernel's `clearRecovery`/`clearVersions`, the calls the password flow already+makes. Only that docId's entries; another document's are untouched; an+unsealed boot deletes nothing. Residual the app cannot scrub: a deleted+IndexedDB record can linger in the browser's on-disk database files until the+browser compacts them.++The recovery-off notice's own seal check is redundant with the autosave guard+(a sealed space never asks for a recovery copy), and is kept on purpose; a+mutation of it alone stays green for that reason.## 2026-10-18 — bento/connect: the plaintext store refuses while sealed (a backstop)Each app guards its own calls to the recovery and version store, about 11diff --git a/scripts/test-spaces-history.ts b/scripts/test-spaces-history.tsindex c066ce68..62bbe764 100644--- a/scripts/test-spaces-history.ts+++ b/scripts/test-spaces-history.ts@@ -417,7 +417,7 @@ console.log('\n10. encrypted spaces: in the envelope, never in IndexedDB (sourceok(!/autosave|indexedDB|putRecovery|addVersion|localStorage/.test(hsrc.replace(/\/\/.*$/gm, '')),'history.ts touches no browser storage — revisions live only in the document')const doSave = main.slice(main.indexOf('async function doSave('), main.indexOf('editor.onUpdateInPlace'))- ok(/recordOnSave\(store\)/.test(doSave) && !/isEncryptionActive\(\)[^\n]*recordOnSave/.test(doSave),+ ok(/recordOnSave\(store\)/.test(doSave) && !/(isEncryptionActive|isBodySealed)\(\)[^\n]*recordOnSave/.test(doSave),'the save records unconditionally — an encrypted space keeps history, inside #bento-doc\'s envelope')}diff --git a/scripts/test-spaces-model.ts b/scripts/test-spaces-model.tsindex cbe92e7d..76ff1eb7 100644--- a/scripts/test-spaces-model.ts+++ b/scripts/test-spaces-model.ts@@ -428,9 +428,10 @@ for (const [label, input, err] of [// as slides keeps them; About no longer holds eitherconst about = fs.readFileSync(new URL('../spaces/src/doccmds.ts', import.meta.url), 'utf8')- // the debounce body must stand down when encryption is on- const guarded = /if \(isEncryptionActive\(\)\) return[\s\S]{0,200}?putRecovery/.test(main)- ok(guarded, 'main.ts skips the recovery snapshot while a space is encrypted')+ // the debounce body must stand down while the body is sealed: a password OR+ // the identity seal (isBodySealed; isEncryptionActive is only the password)+ const guarded = /if \(isBodySealed\(\)\) return[\s\S]{0,200}?putRecovery/.test(main)+ ok(guarded, 'main.ts skips the recovery snapshot while a space is sealed (password or identity seal)')// and turning encryption ON must remove what was written before itok(/clearVersions\(/.test(about) && /clearRecovery\(/.test(about),@@ -445,8 +446,10 @@ for (const [label, input, err] of [ok(/addVersion\(/.test(main), 'main.ts writes a version timeline at all')const throttled = /Date\.now\(\) - lastVersionAt > VERSION_EVERY_MS[\s\S]{0,120}?addVersion/.test(main)ok(throttled, '…on a throttle while editing, so one session cannot spend the cap')- const saveGuarded = /if \(!isEncryptionActive\(\)\) \{ void addVersion/.test(main)- ok(saveGuarded, '…and the SAVE path checks encryption itself, having no early return above it')+ const saveGuarded = /if \(!isBodySealed\(\)\) \{ void addVersion/.test(main)+ ok(saveGuarded, '…and the SAVE path checks the seal itself, having no early return above it')+ ok(!/isEncryptionActive/.test(main.replace(/\/\/.*$/gm, '')),+ 'main.ts asks isBodySealed everywhere: no plaintext-to-disk guard reads the password-only flag')// The restore has to go through replaceDoc: it is the one path that// checkpoints undo first, which is what makes the note "Restoring isdiff --git a/scripts/test-spaces-restore-gate.ts b/scripts/test-spaces-restore-gate.tsindex ee70dbcb..7db53aba 100644--- a/scripts/test-spaces-restore-gate.ts+++ b/scripts/test-spaces-restore-gate.ts@@ -227,7 +227,7 @@ console.log('\nevery restore path uses the gate\n')// since the bar-parity move; About is read too so neither file can regress.const about = readFileSync(join(root, 'spaces/src/about.ts'), 'utf8') +readFileSync(join(root, 'spaces/src/doccmds.ts'), 'utf8')- const offer = main.slice(main.indexOf('async function offerRecovery('), main.indexOf('async function offerRecovery(') + 1400)+ const offer = main.slice(main.indexOf('async function offerRecovery('), main.indexOf('async function offerRecovery(') + 2400)ok(/recoveryOffered\(snap\.json, doc, snap\.at\)/.test(offer), 'the recovery check gates before offering (timed by the snapshot)')ok(/recoverInto\(store, snap\)/.test(offer), 'the banner\'s Restore goes through recoverInto (restoreInto, \'recover\')')ok(/restoreVersion\((h\.)?store, v\.json\)/.test(about), 'History\'s Restore goes through restoreVersion (restoreInto, \'back\')')diff --git a/scripts/test-spaces-restore.ts b/scripts/test-spaces-restore.tsindex cd065d68..3b2856c9 100644--- a/scripts/test-spaces-restore.ts+++ b/scripts/test-spaces-restore.ts@@ -651,8 +651,8 @@ console.log('\n9. the recovery banner\'s words, and the recovery-off notice\n')ok(enc.length === 0, 'an encrypted space: nothing (it was never snapshotted)')const main = readFileSync(join(process.cwd(), 'spaces/src/main.ts'), 'utf8')- ok(/wireRecoveryOff\(\{\s*docId: \(\) => store\.doc\.docId,\s*encrypted: isEncryptionActive,\s*say: \(msg\) => editor\.status\(msg, 8000\),?\s*\}\)/.test(main),- 'main.ts registers the notice for the open space, encryption-aware, in the save status for 8s')+ ok(/wireRecoveryOff\(\{\s*docId: \(\) => store\.doc\.docId,\s*encrypted: isBodySealed,\s*say: \(msg\) => editor\.status\(msg, 8000\),?\s*\}\)/.test(main),+ 'main.ts registers the notice for the open space, seal-aware (isBodySealed), in the save status for 8s')ok(/const spec = recoveryBanner\(snap, store\.doc\)[\s\S]{0,1200}?banner\(spec\.text, spec\.buttons\.map\(\(b\) => \[b\.label, run\[b\.action\], b\.primary, b\.focus\]\)\)/.test(main),'the recovery banner shows what recoveryBanner says, primary and focus and all')ok(/keep: \(\) => \{\}/.test(main), '"Keep the file" deletes nothing')diff --git a/scripts/test-spaces-sealed-browser.mjs b/scripts/test-spaces-sealed-browser.mjsnew file mode 100644index 00000000..11d56ee8--- /dev/null+++ b/scripts/test-spaces-sealed-browser.mjs@@ -0,0 +1,417 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// A SEALED SPACE WRITES NOTHING READABLE, in the built shell (Bento ID, bento/connect: K3).+//+// npm run build:sealtest --prefix spaces && node scripts/test-spaces-sealed-browser.mjs+//+// The shared helper (scripts/lib/sealed-boot.mjs) boots spaces' build:sealtest+// shell with the identity seal set before the app's own boot and proves it took.+// On a space carrying a unique marker in its title and in a page's text:+// 1. after edits, a save and the autosave debounce, NO IndexedDB store holds+// the marker: no recovery snapshot (main.ts autosave guard), no version+// (main.ts save-path guard);+// 2. the saved file (the real ⌘S write) has no first-page preview and the+// marker appears nowhere outside the envelope;+// 3. document.title is neutral (exactly what the saved file's <title> holds)+// at boot, after a rename and after page navigation; and at the password+// gate and after unlock for a password space;+// 4. under a host that refuses recovery copies, no recovery-off notice;+// 5. plaintext an UNSEALED session left for this docId on the same storage is+// never offered to a SEALED boot (no banner, no version history) and is+// deleted, while another document's entries survive.+// CONTROL: the same steps unsealed DO put the marker in the recovery and version+// stores, show the document title in the tab, and show the notice.+//+// Mutations (spaces/src), each red here:+// main.ts autosave guard back to isEncryptionActive → the recovery row+// main.ts save-path guard back to isEncryptionActive → the versions row+// tabtitle.ts tabTitle ignores the seal → the title rows+// main.ts offerRecovery skips the delete → the plaintext-left-behind scan row+// main.ts offerRecovery ignores the seal → the banner row (and the scan row)+// The recovery-off notice's own guard (wireRecoveryOff encrypted:) is covered+// by the autosave guard: a mutation of it alone stays green, by design.+import { writeFileSync, mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { pathToFileURL } from 'node:url'+import { openSealed, savedFile, scanIndexedDB, sealtestShellWith } from './lib/sealed-boot.mjs'++const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')+const MARK = 'ZZSPACESEAL' + Date.now()+const NEUTRAL = 'bento/spaces'+const DB = 'bento-spaces-autosave'+const NOTICE = 'Crash recovery is off for this space'+const PASS = 'correct horse battery staple'+let failures = 0, checks = 0+const ok = (cond, what) => { checks++; if (cond) console.log(' ok ' + what); else { failures++; console.log(' FAIL ' + what) } }++const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })+const dir = mkdtempSync(join(tmpdir(), 'bento-spaces-sealed-'))++/** A save target ⌘S writes to, recording each file written. */+const fsaMock = () => {+ window.__written = []+ const handle = { name: 'sealed.bento.html', async createWritable() {+ return { async write(blob) { window.__written.push(await blob.text()) }, async close() {} }+ } }+ window.showSaveFilePicker = async () => handle+}++/** A host with a per-document store that refuses the recovery copy; counts the+ * recovery copies it was asked for and every save-status sentence shown. */+const refusingHost = () => {+ window.__bentoHost = { ops: ['store'] }+ window.__sets = 0+ window.__notices = []+ const CH = '__bento_tray__'+ window.addEventListener('message', (ev) => {+ const d = ev.data+ if (!d || d[CH] !== true || d.dir !== 'req') return+ let result = { ok: true }+ if (d.op === 'store.set' && d.payload?.name === 'recovery') { window.__sets++; result = { ok: false, reason: 'too-large' } }+ if (d.op === 'store.get') result = { ok: true, bytes: null }+ if (d.op === 'store.list') result = { ok: true, names: [] }+ window.postMessage({ [CH]: true, dir: 'res', id: d.id, result }, '*')+ })+ new MutationObserver((ms) => {+ for (const m of ms) {+ const s = m.target.nodeType === 1 ? m.target.closest?.('.sp-status') : m.target.parentElement?.closest('.sp-status')+ if (s && m.type === 'childList' && s.textContent) window.__notices.push(s.textContent)+ }+ }).observe(document, { subtree: true, childList: true })+}++const sealedNow = (page) => page.evaluate(() => !!globalThis.__bentoTestSealProbe?.sealed())+const booted = (page) => page.waitForFunction(() => window.bento?.doc && document.querySelector('.sp-doctitle'), null, { timeout: 30000 })++/** Rename the space through the title field. */+async function rename(page, value) {+ await page.locator('.sp-doctitle').fill(value)+ await page.locator('.sp-doctitle').press('Tab')+}++/** Open another page from the page list; returns whether the page changed. */+async function navigate(page) {+ const before = await page.evaluate(() => document.querySelector('.sp-treelink.sp-here')?.textContent ?? '')+ await page.locator('.sp-treelink:not(.sp-here)').first().click()+ await page.waitForTimeout(300)+ const after = await page.evaluate(() => document.querySelector('.sp-treelink.sp-here')?.textContent ?? '')+ return after !== before+}++/**+ * End a page openSealed opened. The helper's close() (when this checkout's+ * helper has one) THROWS if the store refused a write on a sealed page: the+ * kernel's backstop must never be what keeps a scan clean, so a refusal is a+ * red row here. Without it, the context is closed as before.+ */+async function finish(o, what) {+ if (typeof o.close === 'function') {+ try { await o.close(); ok(true, `${what}: the store refused nothing`) }+ catch (e) { ok(false, `${what}: ${e.message}`) }+ }+ await o.context.close().catch(() => {})+}++/** IndexedDB stores (db/store) holding the marker. */+const stores = async (page) => scanIndexedDB(page, MARK)++let marked, markedDoc+try {+ // ---- the marked space: a fixed docId, the marker in its title and text ----+ {+ const { page, context } = await openSealed(browser, 'spaces', { sealed: false })+ const doc = await page.evaluate((m) => {+ const d = structuredClone(window.bento.doc)+ d.docId = 'rig-sealed-space'+ d.title = m+ delete d.collab+ const b = d.pages[0].blocks.find((x) => typeof x.html === 'string')+ b.html = `${m} body text`+ return d+ }, MARK)+ ok(doc.pages.length >= 2, `the space has pages to navigate between (${doc.pages.length})`)+ markedDoc = doc+ marked = sealtestShellWith('spaces', doc).href+ await context.close()+ }++ /**+ * The whole walk on the marked space, sealed or not: boot, rename, navigate,+ * edit, ⌘S, wait out the autosave debounce, scan.+ */+ async function walk(sealed) {+ const o = await openSealed(browser, 'spaces', { sealed, doc: markedDoc })+ const { page, context, errors, reload } = o+ await context.addInitScript(fsaMock)+ // reload() installs the key handoff again and re-proves the seal state+ await reload()+ await booted(page)+ const r = { sealedAfterGoto: await sealedNow(page), errors }+ r.titleBoot = await page.title()+ await rename(page, MARK + ' renamed')+ r.titleRename = await page.title()+ r.navigated = await navigate(page)+ r.titleNav = await page.title()+ await page.keyboard.press('ControlOrMeta+s')+ await page.waitForFunction(() => window.__written.length > 0, null, { timeout: 10000 }).catch(() => {})+ // a further edit after the save, then past the 2.5s autosave debounce+ await rename(page, MARK + ' after save')+ await page.waitForTimeout(4000)+ r.titleLater = await page.title()+ r.written = await page.evaluate(() => window.__written.slice(-1)[0] ?? '')+ r.idb = await stores(page)+ r.saved = sealed ? await savedFile(page) : null+ // what a save would write now (the probe sealed; the app's own serializer unsealed)+ r.serialized = sealed ? r.saved.file : await page.evaluate(() => window.bento.serializeAuto())+ // read back across a reload, keyed by docId: a stored snapshot, a banner+ await reload()+ await page.waitForSelector('.sp-banner', { timeout: 5000 }).catch(() => {})+ r.banner = await page.locator('.sp-banner').count()+ r.snapshot = await page.evaluate(([name, id]) => new Promise((res) => {+ const o = indexedDB.open(name)+ o.onsuccess = () => {+ const db = o.result+ if (!db.objectStoreNames.contains('recovery')) { db.close(); res(null); return }+ const g = db.transaction('recovery', 'readonly').objectStore('recovery').get(id)+ g.onsuccess = () => { db.close(); res(g.result ?? null) }+ g.onerror = () => { db.close(); res(null) }+ }+ o.onerror = () => res(null)+ }), [DB, markedDoc.docId])+ await finish(o, sealed ? 'sealed walk' : 'unsealed walk')+ return r+ }++ console.log('\nidentity-sealed space')+ const s = await walk(true)+ ok(s.sealedAfterGoto, 'the marked space booted sealed (the probe says sealed after the navigation)')+ ok(s.idb.length === 0, `NO IndexedDB store holds the marker (${s.idb.join(', ') || 'none'})`)+ ok(!s.idb.includes(`${DB}/recovery`), 'no recovery snapshot (the autosave guard)')+ ok(!s.idb.includes(`${DB}/versions`), 'no version (the save-path and throttled guards)')+ ok(s.written.length > 0, `⌘S wrote the file (${s.written.length} bytes)`)+ ok(/"kdf":"hkdf-kdoc"/.test(s.written), 'the written body is an identity-sealed envelope')+ ok(!s.written.includes('data-bento-preview'), 'the written file carries no first-page preview')+ ok(!s.written.includes(MARK), 'the marker appears nowhere in the written file outside the envelope')+ ok(!s.serialized.includes('data-bento-preview') && !s.serialized.includes(MARK), 'the kernel probe\'s serialized save agrees: no preview, no marker')+ const fileTitle = (s.written.match(/<title>([^<]*)<\/title>/) || [])[1]+ ok(fileTitle === NEUTRAL, `the saved file's <title> is "${NEUTRAL}" (${fileTitle})`)+ ok(s.titleBoot === NEUTRAL, `tab title at boot is neutral (${s.titleBoot})`)+ ok(s.titleRename === NEUTRAL, `tab title after a rename is neutral (${s.titleRename})`)+ ok(s.navigated, 'page navigation happened')+ ok(s.titleNav === NEUTRAL, `tab title after page navigation is neutral (${s.titleNav})`)+ ok(s.titleLater === NEUTRAL, `tab title after the save and later edits is neutral (${s.titleLater})`)+ ok(s.snapshot === null, 'after reload: no recovery snapshot stored for this docId')+ ok(s.banner === 0, 'after reload: no recovery banner')+ ok(s.errors.length === 0, `no page errors${s.errors.length ? ': ' + s.errors[0] : ''}`)++ console.log('\nunsealed control (same shell, same steps, no key handed over)')+ const c = await walk(false)+ ok(!c.sealedAfterGoto, 'not sealed')+ ok(c.idb.includes(`${DB}/recovery`), `control: the recovery store DOES hold the marker (${c.idb.join(', ') || 'none'})`)+ ok(c.idb.includes(`${DB}/versions`), 'control: the versions store DOES hold the marker')+ ok(c.written.includes('data-bento-preview') && c.written.includes(MARK), 'control: the written file DOES carry a preview and the marker')+ ok(c.titleBoot === `${MARK} — ${NEUTRAL}`, `control: tab title at boot shows the document title (${c.titleBoot})`)+ ok(c.titleRename === `${MARK} renamed — ${NEUTRAL}`, `control: tab title after a rename shows it (${c.titleRename})`)+ ok(c.titleNav.startsWith(MARK), `control: and after page navigation (${c.titleNav})`)+ ok(!!c.snapshot && JSON.stringify(c.snapshot).includes(MARK), 'control: after reload, a recovery snapshot IS stored for this docId')+ ok(c.banner > 0, 'control: after reload, the recovery banner IS shown')+ ok(c.serialized.includes('data-bento-preview') && c.serialized.includes(MARK), 'control: a serialized save DOES carry a preview and the marker')+ const cFileTitle = (c.written.match(/<title>([^<]*)<\/title>/) || [])[1] ?? ''+ ok(cFileTitle.includes(MARK), `control: the saved file's <title> DOES carry the document title (${cFileTitle})`)+ ok(c.titleLater.startsWith(MARK), `control: and after the save and later edits (${c.titleLater})`)++ console.log('\nsealed: the identity-sealed file reopened, at its gate')+ {+ const file = join(dir, 'identity-sealed.bento.html')+ writeFileSync(file, s.written)+ const context = await browser.newContext({ viewport: { width: 1280, height: 900 } })+ await context.route(/^https?:/, (route) => route.abort())+ const page = await context.newPage()+ await page.goto(pathToFileURL(file).href)+ await page.waitForSelector('.sp-gate', { timeout: 30000 }).catch(() => {})+ ok(await page.locator('.sp-gate').count() > 0, 'it opens at a gate (this build holds no key for it)')+ const tt = await page.title()+ ok(tt === NEUTRAL, `tab title at the gate is neutral (${tt})`)+ await context.close()+ }+ {+ const file = join(dir, 'unsealed.bento.html')+ writeFileSync(file, c.written)+ const context = await browser.newContext({ viewport: { width: 1280, height: 900 } })+ await context.route(/^https?:/, (route) => route.abort())+ const page = await context.newPage()+ await page.goto(pathToFileURL(file).href)+ await booted(page)+ ok(await page.locator('.sp-gate').count() === 0, 'control: the unsealed file reopened opens with no gate')+ const tt = await page.title()+ ok(tt.startsWith(MARK), `control: and its tab title DOES show the document title (${tt})`)+ await context.close()+ }++ console.log('\npassword space: gate, unlock, rename, navigate')+ {+ // make it through the real UI on the unsealed marked space+ const context = await browser.newContext({ viewport: { width: 1280, height: 900 } })+ await context.route(/^https?:/, (route) => route.abort())+ let page = await context.newPage()+ await page.goto(marked)+ await booted(page)+ const tBefore = await page.title()+ ok(tBefore.startsWith(MARK), `control: before the password is set, the tab title DOES show the document title (${tBefore})`)+ await page.locator('.sp-savemenu').click()+ await page.getByText('Encrypt with password…', { exact: true }).click()+ const pw = page.locator('input[type=password]')+ await pw.nth(0).fill(PASS)+ await pw.nth(1).fill(PASS)+ await pw.nth(1).press('Enter')+ await page.waitForFunction(() => document.querySelectorAll('input[type=password]').length === 0)+ const tSet = await page.title()+ ok(tSet === NEUTRAL, `tab title turns neutral once the password is set (${tSet})`)+ const html = await page.evaluate(() => window.bento.serializeAuto())+ await page.close()+ const file = join(dir, 'password.bento.html')+ writeFileSync(file, html)++ page = await context.newPage()+ const errors = []+ page.on('pageerror', (e) => errors.push(e.message))+ await page.goto(pathToFileURL(file).href)+ await page.waitForSelector('.sp-gate input[type=password]', { timeout: 30000 })+ const tGate = await page.title()+ ok(tGate === NEUTRAL, `tab title at the password gate is neutral (${tGate})`)+ await page.locator('.sp-gate input[type=password]').fill(PASS)+ await page.locator('.sp-gate input[type=password]').press('Enter')+ await booted(page)+ const tUnlock = await page.title()+ ok(tUnlock === NEUTRAL, `tab title after unlock is neutral (${tUnlock})`)+ await rename(page, MARK + ' renamed')+ const tRename = await page.title()+ ok(tRename === NEUTRAL, `tab title after a rename is neutral (${tRename})`)+ ok(await navigate(page), 'page navigation happened')+ const tNav = await page.title()+ ok(tNav === NEUTRAL, `tab title after page navigation is neutral (${tNav})`)+ await page.waitForTimeout(4000)+ const idb = await stores(page)+ ok(idb.length === 0, `NO IndexedDB store holds the marker (${idb.join(', ') || 'none'})`)+ ok(errors.length === 0, `no page errors${errors.length ? ': ' + errors[0] : ''}`)+ await context.close()+ }+ {+ // the control for every password row: the same space with no password+ const context = await browser.newContext({ viewport: { width: 1280, height: 900 } })+ await context.route(/^https?:/, (route) => route.abort())+ const page = await context.newPage()+ await page.goto(marked)+ await booted(page)+ ok(await page.locator('.sp-gate').count() === 0, 'control: with no password there is no gate')+ const tOpen = await page.title()+ ok(tOpen.startsWith(MARK), `control: the tab title on open DOES show the document title (${tOpen})`)+ await rename(page, MARK + ' renamed')+ const tRename = await page.title()+ ok(tRename.startsWith(MARK), `control: after a rename it DOES (${tRename})`)+ await navigate(page)+ const tNav = await page.title()+ ok(tNav.startsWith(MARK), `control: after page navigation it DOES (${tNav})`)+ await page.waitForTimeout(4000)+ const idb = await stores(page)+ ok(idb.length > 0, `control: IndexedDB DOES hold the marker (${idb.join(', ')})`)+ await context.close()+ }++ /** The marked space under a host that refuses the recovery copy. */+ async function hosted(sealed) {+ const o = await openSealed(browser, 'spaces', { sealed, doc: markedDoc })+ const { page, context, reload } = o+ await context.addInitScript(refusingHost)+ await reload()+ await booted(page)+ const sealedAfter = await sealedNow(page)+ await rename(page, MARK + ' hosted')+ await page.waitForTimeout(3500)+ await rename(page, MARK + ' hosted again')+ await page.waitForTimeout(3500)+ const r = await page.evaluate((n) => ({ sets: window.__sets, notices: window.__notices.filter((x) => x.startsWith(n)).length }), NOTICE)+ await finish(o, sealed ? 'sealed, hosted' : 'unsealed, hosted')+ return { sealedAfter, ...r }+ }++ console.log('\nrecovery-off notice under a refusing host')+ {+ const h = await hosted(true)+ ok(h.sealedAfter, 'sealed')+ ok(h.sets === 0, `sealed: the host was never asked for a recovery copy (${h.sets})`)+ ok(h.notices === 0, `sealed: no recovery-off notice (${h.notices})`)+ const hc = await hosted(false)+ ok(hc.sets >= 1 && hc.notices === 1, `control: unsealed, the host refused a copy and the notice showed once (${hc.sets} asked, ${hc.notices} shown)`)+ }++ console.log('\nplaintext an unsealed session left behind, then a sealed boot on the same storage')+ {+ const MX = MARK + 'X', MY = MARK + 'Y'+ const docOf = (id, title) => ({ ...structuredClone(markedDoc), docId: id, title })+ /** an unsealed session on `context` that edits, so a snapshot and a version land */+ async function leave(context, doc, edit) {+ const o = await openSealed(browser, 'spaces', { sealed: false, doc, context })+ await booted(o.page)+ await rename(o.page, edit)+ await o.page.waitForTimeout(4000)+ await o.page.close()+ return o+ }+ async function bannerAndHistory(page) {+ await page.waitForSelector('.sp-banner', { timeout: 4000 }).catch(() => {})+ const banner = await page.locator('.sp-banner').count()+ await page.locator('.sp-savemenu').click()+ await page.getByText('Version history…', { exact: true }).click()+ await page.waitForTimeout(800)+ const versions = await page.locator('.sp-ab-version').count()+ return { banner, versions }+ }++ // control: an unsealed reboot of X on the same storage IS offered the copy+ {+ const context = await browser.newContext({ viewport: { width: 1280, height: 900 } })+ await context.route(/^https?:/, (route) => route.abort())+ const x = await leave(context, docOf('rig-left-x', MX), MX + ' edited')+ const again = await openSealed(browser, 'spaces', { sealed: false, context, url: x.url })+ await booted(again.page)+ const r = await bannerAndHistory(again.page)+ ok(r.banner > 0, `control: an UNSEALED reboot of X on the same storage IS offered the banner (${r.banner})`)+ ok(r.versions > 0, `control: and its version history DOES list X's versions (${r.versions})`)+ await finish(again, 'unsealed reboot of X')+ }++ const context = await browser.newContext({ viewport: { width: 1280, height: 900 } })+ await context.route(/^https?:/, (route) => route.abort())+ const x = await leave(context, docOf('rig-left-x', MX), MX + ' edited')+ await leave(context, docOf('rig-left-y', MY), MY + ' edited')+ {+ const probe = await context.newPage()+ await probe.goto(x.url)+ await booted(probe)+ const before = await scanIndexedDB(probe, MX)+ ok(before.includes(`${DB}/recovery`) && before.includes(`${DB}/versions`),+ `precondition: the unsealed session left X's snapshot and a version (${before.join(', ')})`)+ await probe.close()+ }+ const sealedX = await openSealed(browser, 'spaces', { context, url: x.url })+ await booted(sealedX.page)+ const r = await bannerAndHistory(sealedX.page)+ ok(r.banner === 0, `a SEALED boot of X on the same storage offers NO banner (${r.banner})`)+ ok(r.versions === 0, `and its version history shows NOTHING (${r.versions})`)+ await sealedX.page.waitForTimeout(500)+ const leftX = await scanIndexedDB(sealedX.page, MX)+ ok(leftX.length === 0, `afterwards NO IndexedDB store holds X's plaintext (${leftX.join(', ') || 'none'})`)+ const leftY = await scanIndexedDB(sealedX.page, MY)+ ok(leftY.includes(`${DB}/recovery`) && leftY.includes(`${DB}/versions`),+ `a SECOND document's (Y) snapshot and version survive the sealed boot of X (${leftY.join(', ') || 'none'})`)+ await finish(sealedX, 'sealed boot of X')+ }+} finally {+ await browser.close()+}++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 3993b4d5..c8770e57 100755--- a/scripts/test-spaces.mjs+++ b/scripts/test-spaces.mjs@@ -87,6 +87,9 @@ const RIGS = [{ name: 'encrypted-browser', file: 'scripts/test-spaces-encrypted-browser.mjs' },// the older-copy warning and the recovery-off notice, in the built shell{ name: 'recovery-browser', file: 'scripts/test-spaces-recovery-browser.mjs' },+ // a sealed space (identity seal or password) on the build:sealtest shell:+ // nothing readable in IndexedDB, no preview, neutral tab title, no notice+ { name: 'sealed-browser', file: 'scripts/test-spaces-sealed-browser.mjs' },// drives the BUILT shell in Chrome; self-skips outside CI without one{ name: 'chrome', file: 'scripts/test-spaces-chrome.ts' },]diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.mdindex ece3f10d..faa547e4 100644--- a/spaces/CHANGELOG.md+++ b/spaces/CHANGELOG.md@@ -1375,6 +1375,13 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.recovery is off for this space — it’s too large to keep a backup copy. Saveoften." It says so once per space, and never for an encrypted space, whichnever keeps a recovery copy.+- **A sealed space keeps no readable copy in this browser.** A space sealed+ by a password or by the identity seal writes no crash-recovery copy and no+ version, and shows no recovery-off notice. Opening a sealed space never+ offers a readable copy an earlier unsealed session left in this browser, and+ deletes that space's copies. Neutral title while sealed,+ matching the saved file's title: the tab reads "bento/spaces", from the+ password prompt on.## [0.1.0] — 2026-08-03diff --git a/spaces/src/doccmds.ts b/spaces/src/doccmds.tsindex 1799f997..e5d4c8bc 100644--- a/spaces/src/doccmds.ts+++ b/spaces/src/doccmds.ts@@ -20,7 +20,8 @@// out, a page as its own space) sits in the slot of its KIND — exports with// the export, Import beside Replace from JSON, the two ways a document arrives.-import { setEncryptionPassword, isEncryptionActive } from '../../kernel/src/save.ts'+import { setEncryptionPassword, isEncryptionActive, isBodySealed } from '../../kernel/src/save.ts'+import { setTabTitle } from './tabtitle.ts'import { clearVersions, clearRecovery, listVersions, type Snapshot } from '../../kernel/src/autosave.ts'import type { Dialog } from '../../kernel/src/ui/dialog.ts'import { t } from './i18n'@@ -65,6 +66,8 @@ export function saveRows(m: Menu, h: DocHost): void {row(m, { icon: ICONS.markdown, label: t('Export as Markdown…'), desc: t('Every page, as one .md file'), run: () => h.exportMarkdown() })row(m, { icon: ICONS.page, label: t('Export page as a space…'), desc: t('One page and what is under it, as its own file'), run: () => h.exportSpace() })h.moreExports?.(m)+ // isEncryptionActive, not isBodySealed: this is the PASSWORD UI. Change and+ // remove act on a password, and an identity-sealed space has none.if (isEncryptionActive()) {row(m, { icon: ICONS.lock, label: t('Change password…'), desc: t('Takes effect on the next save'), off: ro, run: () => openPassword(h) })row(m, { icon: ICONS.lock, label: t('Remove password…'),@@ -164,6 +167,7 @@ function openPassword(h: DocHost): void {if (!a.value) { err.textContent = t('Password'); a.focus(); return }if (a.value !== b.value) { err.textContent = t('Passwords do not match'); b.focus(); return }setEncryptionPassword(a.value)+ setTabTitle(h.store.doc.title)await clearVersions(h.store.doc.docId)await clearRecovery(h.store.doc.docId)close()@@ -180,6 +184,7 @@ function openRemovePassword(h: DocHost): void {body.append(el('p', 'sp-note', t('The next save writes this space as plain, readable JSON — anybody who opens the file can read every page.')))body.append(actions(button(t('Cancel'), close), button(t('Remove the password'), () => {setEncryptionPassword(null)+ setTabTitle(h.store.doc.title)close()h.notice(t('Password removed. Save to write the space unencrypted.'))}, true)))@@ -198,6 +203,7 @@ function openHistory(h: DocHost): void {const render = (versions: Snapshot[]): void => {list.textContent = ''if (!versions.length) {+ // isEncryptionActive, not isBodySealed: this note names the password.list.append(el('p', 'sp-note', isEncryptionActive()? t('This space is encrypted, so no versions are kept.'): t('No versions yet — they build up as you write and save.')))@@ -225,7 +231,9 @@ function openHistory(h: DocHost): void {}}render([])- void listVersions(h.store.doc.docId).then(render).catch(() => { /* no store, no history */ })+ // a sealed space lists nothing: any entry for it is a plaintext copy an+ // unsealed session left, which boot deletes (main.ts offerRecovery)+ if (!isBodySealed()) void listVersions(h.store.doc.docId).then(render).catch(() => { /* no store, no history */ })}))}diff --git a/spaces/src/editor.ts b/spaces/src/editor.tsindex 867bdcd9..4a294674 100644--- a/spaces/src/editor.ts+++ b/spaces/src/editor.ts@@ -89,6 +89,7 @@ import {import {internAsset, prepareImage, humanBytes, IMAGE_EMBED_BUDGET, MEDIA_EMBED_BUDGET, blobToDataUri,} from './assets'+import { setTabTitle } from './tabtitle.ts'const CTRL = navigator.platform.toLowerCase().includes('mac') ? 'metaKey' : 'ctrlKey'@@ -380,7 +381,7 @@ export class Editor {title.setAttribute('aria-label', t('Space name'))title.addEventListener('input', () => {this.store.runEdit('__title', () => { this.store.doc.title = title.value })- document.title = `${title.value} — bento/spaces`+ setTabTitle(title.value)})this.statusEl = el('span', 'sp-status')diff --git a/spaces/src/main.ts b/spaces/src/main.tsindex a7cea7f7..8d2d8a2c 100644--- a/spaces/src/main.ts+++ b/spaces/src/main.ts@@ -10,15 +10,16 @@ import './styles.css'// AFTER styles.css: a design rule and the base rule it restyles often tie on// specificity, and the tie goes to the later sheet.import './designs.css'-import { configureApp, appConfig } from '../../kernel/src/app.ts'+import { configureApp } from '../../kernel/src/app.ts'import { startTheme } from '../../kernel/src/theme.ts'import {capturePristine, readEmbeddedDoc, serializeFile, serializeAuto, registerPreview,saveFile, parseEnvelope, canWriteInPlace, decryptEnvelope, setEncryptionPassword,writeUpdatedFileAs, suggestedFileName,- isEncryptionActive,+ isBodySealed,} from '../../kernel/src/save.ts'-import { putRecovery, getRecovery, clearRecovery, pruneOld, addVersion } from '../../kernel/src/autosave.ts'+import { setTabTitle, setNeutralTabTitle } from './tabtitle.ts'+import { putRecovery, getRecovery, clearRecovery, clearVersions, pruneOld, addVersion } from '../../kernel/src/autosave.ts'import { APP_VERSION, applyUpdateInPlace } from '../../kernel/src/update.ts'import { t, locale, applyDirection } from './i18n'import { i18nApi } from '../../kernel/src/i18n.ts'@@ -123,6 +124,8 @@ if (envelope) {* every later save stays encrypted.*/async function passwordGate(): Promise<void> {+ // neutral title while sealed, matching the saved file's title+ setNeutralTabTitle()document.getElementById('bento-splash')?.remove()const wrap = document.createElement('div')wrap.className = 'sp-gate'@@ -220,7 +223,7 @@ function gate(title: string, body: string, actions: Array<[string, () => void]>)}function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version'): void {- document.title = `${doc.title} — ${appConfig().appName}`+ setTabTitle(doc.title)document.getElementById('bento-splash')?.remove()const store = new Store(doc)@@ -383,8 +386,9 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')// editing runs, but the point somebody chose to write the file is the// point they would most want back, so it is never throttled away. The// version is the snapshot that was WRITTEN, not whatever is on screen now.- // Encrypted spaces keep nothing here, for the reason putRecovery does not.- if (!isEncryptionActive()) { void addVersion(out.doc); lastVersionAt = Date.now() }+ // Sealed spaces (a password or the identity seal) keep nothing here, for the+ // reason putRecovery does not.+ if (!isBodySealed()) { void addVersion(out.doc); lastVersionAt = Date.now() }if (out.result === 'saved' && out.current) {// Only when the disk holds what is on screen: after a stale write the// recovery snapshot is the one copy of the newer edit.@@ -447,8 +451,8 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')// any means the app offered.//// So a version is added on a throttle while editing, and unthrottled on save.- // The kernel caps and prunes the timeline; both stores stay empty while a- // password is set.+ // The kernel caps and prunes the timeline; both stores stay empty while the+ // body is sealed (a password or the identity seal).let timer: ReturnType<typeof setTimeout> | undefinedstore.on('doc', () => {clearTimeout(timer)@@ -469,7 +473,9 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')// Written DURING editing, not at save — so, unlike `revisions`, it counts// toward the recovery key (docclass.ts SPACES_NOT_EDIT does not list it).recordToday()- if (isEncryptionActive()) return+ // isBodySealed, not isEncryptionActive: an identity-sealed space has no+ // password, and its snapshot would be the same plaintext on disk.+ if (isBodySealed()) returntimer = setTimeout(() => {void putRecovery(store.doc)if (Date.now() - lastVersionAt > VERSION_EVERY_MS) {@@ -482,10 +488,16 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')void offerRecovery(doc, store, editor)// A host that refuses the recovery copy (too large) turns crash recovery off// for this space; say so once, where the save status shows, held long enough- // to read (slides holds it 8s). Never for an encrypted space.+ // to read (slides holds it 8s). Never for a sealed space.+ //+ // `encrypted: isBodySealed` is redundant today: the autosave guard above+ // (`if (isBodySealed()) return`) means a sealed space never asks for a+ // recovery copy, so the kernel never fires for it. Kept on purpose; a+ // mutation of this line alone stays green because that guard covers it,+ // which is not a gap.wireRecoveryOff({docId: () => store.doc.docId,- encrypted: isEncryptionActive,+ encrypted: isBodySealed,say: (msg) => editor.status(msg, 8000),})@@ -748,6 +760,16 @@ function banner(text: string, actions: Array<[string, () => void, boolean?, bool*/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 rewritten+ // A SEALED SPACE IS NEVER OFFERED A PLAINTEXT COPY, and the ones an unsealed+ // session left for this docId are deleted: the recovery snapshot and every+ // version. boot() runs after the seal is in place (the identity seal is set+ // in capturePristine, the password before boot), so isBodySealed() here is+ // the proven state. Only this docId's entries; never another document's.+ if (isBodySealed()) {+ await clearRecovery(doc.docId)+ await clearVersions(doc.docId)+ return+ }const snap = await getRecovery(doc.docId)if (!snap || !recoveryOffered(snap.json, doc, snap.at)) return// What the banner SAYS is recoverynotice.ts: when the snapshot looks olderdiff --git a/spaces/src/tabtitle.ts b/spaces/src/tabtitle.tsnew file mode 100644index 00000000..9ec9b652--- /dev/null+++ b/spaces/src/tabtitle.ts@@ -0,0 +1,27 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// The browser tab's title. Every write to document.title goes through here.+//+// Neutral title while sealed, matching the saved file's title: while the body+// is sealed (a password or the identity seal, kernel isBodySealed()), the tab+// reads the app's name, exactly what the kernel writes into the saved file's+// <title>, and never the space's or a page's title.++import { appConfig } from '../../kernel/src/app.ts'+import { isBodySealed } from '../../kernel/src/save.ts'++/** What the tab should read for a space titled `docTitle`. */+export function tabTitle(docTitle: string): string {+ const app = appConfig().appName+ return isBodySealed() ? app : `${docTitle} — ${app}`+}++/** Set the tab's title for a space titled `docTitle`. */+export function setTabTitle(docTitle: string): void {+ document.title = tabTitle(docTitle)+}++/** The neutral title, before the body is open (the password gate). */+export function setNeutralTabTitle(): void {+ document.title = appConfig().appName+}