Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

type: keep a sealed document's plaintext out of local copies; neutral title while sealed (#782)

nyblnet80de674ae1fa
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 53bf1686..d630bbfe 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2917,3 +2917,24 @@ jobs:
run: |
sudo apt-get install -y -qq gnome-keyring dbus >/dev/null
./keyring-rig.sh
+
+ type-sealed-browser:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ - name: Install browser test runtime
+ # Pinned outside app packages: browser automation is not shipped in documents.
+ run: |
+ npm install --prefix "$RUNNER_TEMP/bento-browser" --no-package-lock --ignore-scripts [email protected]
+ "$RUNNER_TEMP/bento-browser/node_modules/.bin/playwright" install --with-deps chromium
+ echo "PLAYWRIGHT_MODULE=$RUNNER_TEMP/bento-browser/node_modules/playwright/index.mjs" >> "$GITHUB_ENV"
+ - name: Build the sealed TEST shell
+ run: |
+ npm ci --prefix type
+ npm run build:sealtest --prefix type
+ - name: A sealed document leaves no plaintext and shows a neutral title
+ run: node scripts/test-type-sealed-browser.mjs
diff --git a/scripts/test-type-autosave.ts b/scripts/test-type-autosave.ts
index 7c0502f9..f7c0d77f 100644
--- a/scripts/test-type-autosave.ts
+++ b/scripts/test-type-autosave.ts
@@ -26,7 +26,7 @@
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { configureApp } from '../kernel/src/app.ts'
-import { setEncryptionPassword } from '../kernel/src/save.ts'
+import { setEncryptionPassword, setIdentitySeal, isBodySealed } from '../kernel/src/save.ts'
import { docContentKey, canSnapshot, recoveryBanner } from '../type/src/autosave.ts'
import { sign, newKey, verifyChain, newHistorySalt } from '../type/src/canon.ts'
import { RESTORE_RULES } from '../type/src/restorerules.ts'
@@ -90,6 +90,10 @@ H('canSnapshot refuses while encryption is active')
ok(!canSnapshot(), 'encryption active — canSnapshot refuses, so runAutosave never reaches putRecovery')
setEncryptionPassword(null)
ok(canSnapshot(), 'clearing the password restores snapshotting')
+ setIdentitySeal(new Uint8Array(32).fill(7))
+ ok(isBodySealed() && !canSnapshot(), 'an identity-sealed body (no password) — canSnapshot refuses too')
+ setIdentitySeal(null)
+ ok(canSnapshot(), 'clearing the seal restores snapshotting')
}
H('restoring a recovered snapshot round-trips the document exactly')
diff --git a/scripts/test-type-preview.ts b/scripts/test-type-preview.ts
index 85e9fb25..cc534bc4 100644
--- a/scripts/test-type-preview.ts
+++ b/scripts/test-type-preview.ts
@@ -44,7 +44,7 @@
import { register } from 'node:module';
register('./lib/ts-resolve-hooks.mjs', import.meta.url);
-import { isEncryptionActive, setEncryptionPassword } from '../kernel/src/save.ts';
+import { isEncryptionActive, setEncryptionPassword, setIdentitySeal, isBodySealed } from '../kernel/src/save.ts';
import { emptyDoc, type TypeDoc, type Block } from '../type/src/model.ts';
let checks = 0, bad = 0;
@@ -73,6 +73,17 @@ console.log('\n— the encryption veto, which buildTypePreview checks itself —
ok(buildTypePreview(withBody) === null, 'an encrypted document gets NO preview, even with real content');
setEncryptionPassword(null);
ok(!isEncryptionActive(), 'cleared for the rest of this file');
+ // The IDENTITY seal has no password: a document sealed to people. Its body is
+ // just as sealed, so it gets no preview either.
+ setIdentitySeal(new Uint8Array(32).fill(7));
+ ok(isBodySealed() && !isEncryptionActive(), 'an identity-sealed body is sealed, with no password set');
+ // a guard that let it through would go on to BUILD a preview (here, in node,
+ // that throws for want of a DOM), so a throw counts as "a preview was made"
+ let sealedPreview: unknown = 'built';
+ try { sealedPreview = buildTypePreview(withBody); } catch { /* it tried to build one */ }
+ ok(sealedPreview === null, 'an identity-sealed document gets NO preview either');
+ setIdentitySeal(null);
+ ok(!isBodySealed(), 'the seal is cleared for the rest of this file');
}
console.log('\n— an empty document gets no preview either —');
diff --git a/scripts/test-type-sealed-browser.mjs b/scripts/test-type-sealed-browser.mjs
new file mode 100644
index 00000000..da612683
--- /dev/null
+++ b/scripts/test-type-sealed-browser.mjs
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// A SEALED bento/type document leaves no plaintext behind it, and shows a
+// neutral title.
+//
+// npm run build:sealtest --prefix type && node scripts/test-type-sealed-browser.mjs
+//
+// Uses the shared sealed TEST document (scripts/lib/sealed-boot.mjs): type's
+// test shell, booted with the identity seal set before the app runs, and
+// PROVEN sealed before any row checks a guard. Every sealed row has an
+// UNSEALED control on the same edit, so a row that never fires cannot pass.
+//
+// WHAT THIS PROVES, sealed (identity seal, no password) vs unsealed:
+// 1. after an edit and the autosave debounce, no IndexedDB record holds the
+// edit's text: no recovery snapshot and no version (control: unsealed,
+// the text IS found, so the scan can see a leak);
+// 2. the tab title is "bento/type", neutral while sealed, matching the saved
+// file's title (control: unsealed shows the document's own title);
+// 3. what a save would write carries no first-page preview and no plaintext;
+// 4. a file type will not open lands on its refusal with the title
+// "bento/type", whatever the file's own <title> says, and offers no
+// recovery banner;
+// 5. plaintext copies an EARLIER UNSEALED session left for a document are
+// never offered when that document boots sealed (no restore banner) and
+// are deleted, for that docId only: on the same storage, an unsealed
+// reboot still offers the banner (control), the sealed boot shows none
+// and leaves none of that document's text, and another document's copy
+// survives.
+// The preview guard itself (type/src/preview.ts) is also pinned in
+// scripts/test-type-preview.ts, where the kernel's own preview veto does not
+// mask it.
+//
+// Mutations (run, judged by exit code): canSnapshot back on the
+// password-only check → 1 red; paintTitle without the sealed branch → 2 red;
+// the refusal path without its title → 4 red; the sealed purge skipping the
+// delete → 5 red; the sealed purge removed (the banner offered) → 5 red.
+import { readFileSync, writeFileSync, mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { openSealed, savedFile, scanIndexedDB, sealtestShell } from './lib/sealed-boot.mjs'
+const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')
+
+let checks = 0, failures = 0
+const ok = (c, m) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`) } else console.log(` ok ${m}`) }
+
+const MARKER = 'zq-sealed-marker-7731'
+const edit = async (page, text = MARKER) => {
+ const bb = await page.locator('#paper p[data-kind=para]').first().boundingBox()
+ await page.mouse.click(bb.x + 4, bb.y + bb.height / 2)
+ await page.keyboard.press('End')
+ await page.keyboard.type(' ' + text)
+ await page.waitForTimeout(4500) // past the 2.5s autosave debounce, and its write
+}
+
+// an envelope type does not open, in a shell whose own <title> names the document
+const refusalUrl = () => {
+ const shell = readFileSync(sealtestShell('type'), 'utf8')
+ const env = JSON.stringify({ format: 'bento/enc', v: 1, it: 300000, salt: 'AAAA', iv: 'AAAA', data: 'AAAA' })
+ const html = shell.replace(/<title>[^<]*<\/title>/, '<title>Secret memo — bento/type</title>')
+ .replace(/(<script[^>]*id="bento-doc"[^>]*>)[\s\S]*?(<\/script>)/, (_m, a, b) => a + '\n' + env + '\n' + b)
+ if (!html.includes('<title>Secret memo') || !html.includes('bento/enc')) throw new Error('could not build the refusal fixture')
+ const f = join(mkdtempSync(join(tmpdir(), 'bento-type-sealed-')), 'refused.html'); writeFileSync(f, html)
+ return 'file://' + f
+}
+
+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })
+try {
+ for (const sealed of [false, true]) {
+ const label = sealed ? 'sealed' : 'UNSEALED control'
+ console.log(`\n${label}\n`)
+ const { context, page, errors } = await openSealed(browser, 'type', { sealed })
+ const docTitle = await page.evaluate(() => window.bento.doc.title)
+ await edit(page)
+ const inDoc = await page.evaluate((m) => JSON.stringify(window.bento.doc).includes(m), MARKER)
+ ok(inDoc, `${label}: the edit is in the document`)
+ const hits = await scanIndexedDB(page, MARKER)
+ if (sealed) ok(hits.length === 0, `${label}: no IndexedDB record holds the edit (no recovery, no version)${hits.length ? ' — found in ' + hits.join(', ') : ''}`)
+ else ok(hits.length > 0, `${label}: the edit IS in IndexedDB (${hits.join(', ')}), so the scan can see a leak`)
+ const title = await page.title()
+ if (sealed) ok(title === 'bento/type', `${label}: the tab title is the neutral "bento/type" (${JSON.stringify(title)})`)
+ else ok(!!docTitle && title.includes(docTitle), `${label}: the tab title shows the document's own title (${JSON.stringify(title)})`)
+ if (sealed) {
+ const s = await savedFile(page)
+ ok(!s.file.includes('data-bento-preview') && !s.file.includes(MARKER) && !s.file.includes(docTitle),
+ `${label}: a save would write no preview and no plaintext (preview ${s.file.includes('data-bento-preview')}, marker ${s.file.includes(MARKER)})`)
+ }
+ ok(errors.length === 0, `${label}: no page error (${JSON.stringify(errors)})`)
+ await context.close()
+ }
+
+ // 5. copies left by an earlier UNSEALED session, on the same storage
+ console.log('\nleft over from an unsealed session\n')
+ {
+ const A_MARK = 'zq-alpha-left-over-4417', B_MARK = 'zq-bravo-other-doc-5521'
+ const fixed = (docId, title) => ({ format: 'bento/type', docId, title, body: [{ id: 'p1', kind: 'para', text: `${title} opening paragraph.` }] })
+ const banner = (page) => page.evaluate(() => !!document.querySelector('.t-recover'))
+ // unsealed sessions on document A and on document B leave plaintext copies
+ const a = await openSealed(browser, 'type', { sealed: false, doc: fixed('doc-alpha', 'Alpha') })
+ await edit(a.page, A_MARK)
+ const b = await openSealed(browser, 'type', { sealed: false, doc: fixed('doc-bravo', 'Bravo'), context: a.context })
+ await edit(b.page, B_MARK)
+ await b.page.close()
+ ok((await scanIndexedDB(a.page, A_MARK)).length > 0 && (await scanIndexedDB(a.page, B_MARK)).length > 0,
+ 'both unsealed sessions left plaintext copies on this storage (the fixture is real)')
+ await a.page.close()
+ // control: A reopened UNSEALED still offers its recovery banner
+ const ctl = await openSealed(browser, 'type', { sealed: false, context: a.context, url: a.url })
+ await ctl.page.waitForTimeout(1500)
+ ok(await banner(ctl.page), 'control: an unsealed reboot of the same document still offers the recovery banner')
+ await ctl.page.close()
+ // A booted SEALED on the same storage
+ const sealedA = await openSealed(browser, 'type', { context: a.context, url: a.url })
+ await sealedA.page.waitForTimeout(1500)
+ ok(!(await banner(sealedA.page)), 'sealed: the left-over plaintext is NOT offered (no recovery banner)')
+ const aHits = await scanIndexedDB(sealedA.page, A_MARK)
+ ok(aHits.length === 0, `sealed: none of that document's left-over text remains (no recovery, no version)${aHits.length ? ' — found in ' + aHits.join(', ') : ''}`)
+ ok((await scanIndexedDB(sealedA.page, B_MARK)).length > 0, "another document's copy survives: the purge is for this docId only")
+ // a refused file, on storage that holds a snapshot, offers no banner
+ const rp = await a.context.newPage()
+ await rp.goto(refusalUrl())
+ await rp.waitForTimeout(1500)
+ ok(!(await banner(rp)), 'a refused file offers no recovery banner')
+ await rp.close()
+ await a.context.close()
+ }
+
+ // 4. the refusal: an envelope type does not open, in a shell whose own
+ // <title> names the document
+ console.log('\nrefusal\n')
+ const p = await browser.newPage(); await p.route(/^https?:/, (r) => r.abort())
+ await p.goto(refusalUrl())
+ await p.waitForFunction(() => document.body.textContent.includes('This file could not be opened'), null, { timeout: 15000 }).catch(() => {})
+ const r = await p.evaluate(() => ({ title: document.title, refused: window.bento?.refused === true }))
+ ok(r.refused && r.title === 'bento/type', `a file type refuses shows the title "bento/type", not its own <title> (${JSON.stringify(r.title)}, refused ${r.refused})`)
+ await p.close()
+} finally {
+ await browser.close()
+}
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/type/src/about.ts b/type/src/about.ts
index a450fcf8..eaf82741 100644
--- a/type/src/about.ts
+++ b/type/src/about.ts
@@ -17,7 +17,7 @@
// product.
import { checkForUpdates, applyUpdate, APP_VERSION, type ReleaseInfo } from '../../kernel/src/update.ts';
-import { canWriteInPlace, openedFileName } from '../../kernel/src/save.ts';
+import { canWriteInPlace, openedFileName, isBodySealed } from '../../kernel/src/save.ts';
import { setTheme, themeChoice, type ThemeChoice } from '../../kernel/src/theme.ts';
import type { Store } from './store.ts';
import { wordCount, docForExport } from './model.ts';
@@ -258,7 +258,9 @@ export function openAbout({ store, pages, onReplaceDoc, onRestoreDoc }: AboutHoo
async function openVersionHistory(
{ store, onRestoreDoc, close: closeAbout }: { store: Store; onRestoreDoc(json: string): void; close(): void },
): Promise<void> {
- const versions = await listVersions(store.doc.docId);
+ // nothing while the body is sealed: its plaintext versions are not offered
+ // (autosave.ts checkRecovery deletes them; this covers the moment before)
+ const versions = isBodySealed() ? [] : await listVersions(store.doc.docId);
const back = document.createElement('div');
back.className = 't-overlay';
diff --git a/type/src/autosave.ts b/type/src/autosave.ts
index 66628ad5..3ace3055 100644
--- a/type/src/autosave.ts
+++ b/type/src/autosave.ts
@@ -33,7 +33,7 @@
//
// Registered once, at import time, mirroring every other feature module.
-import { isEncryptionActive } from '../../kernel/src/save.ts';
+import { isBodySealed } from '../../kernel/src/save.ts';
import {
putRecovery, getRecovery, clearRecovery, addVersion, listVersions, pruneOld,
clearVersions, recoveryLooksOlder, onRecoveryOff, type Snapshot,
@@ -77,16 +77,16 @@ export function docContentKey(doc: TypeDoc): string {
/**
* May the CURRENT document's plaintext touch IndexedDB right now?
*
- * bento/type has no encryption feature yet — `isEncryptionActive()` can
- * never return true today — but the guard costs nothing and is the one line
- * that must already be correct the day encryption ships, exactly as it is in
- * slides/src/autosave.ts. Never remove this without confirming that day has
- * not arrived. Exported (rather than kept as a private `if`) so the rig can
+ * Not while the body is SEALED — by a password or by the identity seal
+ * (`isBodySealed()`, kernel save.ts): a sealed document's plaintext must
+ * never reach a recovery snapshot or version history. bento/type has no
+ * password feature of its own, but a document sealed to people opens here,
+ * so this is live, not hypothetical. Exported (rather than kept as a private `if`) so the rig can
* assert the guard directly against the kernel's real encryption state,
* instead of trusting that the call site was written correctly.
*/
export function canSnapshot(): boolean {
- return !isEncryptionActive();
+ return !isBodySealed();
}
const AUTOSAVE_DEBOUNCE_MS = 2500;
@@ -121,6 +121,15 @@ async function runAutosave(ctx: FeatureContext): Promise<void> {
async function checkRecovery(ctx: FeatureContext): Promise<void> {
const doc = ctx.store.doc;
+ // A SEALED body: plaintext copies this browser kept for this document in an
+ // earlier, unsealed session are never offered (no banner, nothing in
+ // version history) and are deleted — for THIS docId only; every other
+ // document's copies are untouched. Guarded by
+ // scripts/test-type-sealed-browser.mjs.
+ if (isBodySealed()) {
+ await Promise.all([clearRecovery(doc.docId), clearVersions(doc.docId)]);
+ return;
+ }
const snap = await getRecovery(doc.docId);
if (!snap) return;
// A snapshot is foreign input (restoregate.ts): format-checked, and never
diff --git a/type/src/main.ts b/type/src/main.ts
index 996289f6..a271d719 100644
--- a/type/src/main.ts
+++ b/type/src/main.ts
@@ -8,7 +8,7 @@
import './styles.css';
import { configureApp } from '../../kernel/src/app.ts';
import {
- capturePristine, readEmbeddedDoc, saveFile, currentFileName, canWriteInPlace,
+ capturePristine, readEmbeddedDoc, saveFile, currentFileName, canWriteInPlace, isBodySealed,
} from '../../kernel/src/save.ts';
import { ICONS } from './icons.ts';
import { t } from './i18n.ts';
@@ -102,6 +102,10 @@ if (parsed.ok) {
line('p', parsed.detail);
line('p', 'Nothing has been changed. Close this tab rather than saving over it.', 'color:#8d95a3');
document.body.replaceChildren(card);
+ // Neutral title while sealed, matching the saved file's title. A file this
+ // refuses may be sealed (bento/type opens no envelope itself), so the title
+ // is the app's name, whatever the shell's <title> says.
+ document.title = 'bento/type';
// Tell the shell loader this was a deliberate refusal, not a failed start
// (its contract: { doc } running, { locked } at a password gate, { refused }
// painted its own refusal). Without it the loader counts the throw below as
@@ -982,7 +986,8 @@ const markDirty = () => { dirty = true; paintTitle(); };
function paintTitle() {
const name = currentFileName();
const docTitle = store.doc.title || t('Untitled');
- document.title = `${dirty ? '• ' : ''}${docTitle} — bento/type`;
+ // Neutral title while sealed, matching the saved file's title.
+ document.title = isBodySealed() ? 'bento/type' : `${dirty ? '• ' : ''}${docTitle} — bento/type`;
const btn = document.getElementById('save')!;
// Update the LABEL only. Setting textContent here wiped the icon that
// label() had just installed, so the button silently lost its glyph the
diff --git a/type/src/preview.ts b/type/src/preview.ts
index 0e8b73fc..6ef4b98d 100644
--- a/type/src/preview.ts
+++ b/type/src/preview.ts
@@ -44,7 +44,7 @@
// and a remote URL here would be a preview that phones home from a context
// where nobody could consent.
-import { registerPreview, isEncryptionActive } from '../../kernel/src/save.ts';
+import { registerPreview, isBodySealed } from '../../kernel/src/save.ts';
import type { Block, TypeDoc } from './model.ts';
import { registerReady } from './features.ts';
import { groupBlocks, blockHtml, renderBody, TAG } from './render.ts';
@@ -319,7 +319,7 @@ function titleCard(doc: TypeDoc): HTMLElement {
* plaintext beside the ciphertext that exists to hide them.
*/
export function buildTypePreview(doc: TypeDoc): HTMLElement | null {
- if (isEncryptionActive()) return null;
+ if (isBodySealed()) return null;
if (!doc?.body?.length) return null;
const pageOne = firstPageBlocks(doc);