Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

autosave: the plaintext store refuses while sealed; the page tells its host when it's sealed (#796)

nyblnetfafde7973f28
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d346e4ba..aede2813 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1090,6 +1090,19 @@ jobs:
BENTO_TEST_APP=bento-slides node "$RUNNER_TEMP/test-autosave.mjs"
BENTO_TEST_APP=bento-spaces node "$RUNNER_TEMP/test-autosave.mjs"
+
+ - name: The plaintext store refuses while sealed (bento/connect backstop)
+ # kernel/src/autosave.ts: while the body is sealed (password or identity
+ # seal), putRecovery/addVersion refuse and getRecovery/listVersions offer
+ # nothing, so an app missing one of its own guards still can't write or
+ # offer plaintext. The purge (clearRecovery/clearVersions) still works
+ # while sealed, for that document only.
+ run: |
+ slides/node_modules/.bin/esbuild scripts/test-store-backstop.ts --bundle --platform=node --format=esm \
+ --alias:fake-indexeddb/auto=./slides/node_modules/fake-indexeddb/auto/index.js \
+ --outfile="$RUNNER_TEMP/test-store-backstop.mjs"
+ node "$RUNNER_TEMP/test-store-backstop.mjs"
+
- name: Publish deletion-gate rig
# A publish assembles site/ for ONE app and mirrors it authoritatively.
# Measured: a spaces-shaped site/ deleted 47 live files — the signed
diff --git a/dash/package.json b/dash/package.json
index c098f270..b797e402 100644
--- a/dash/package.json
+++ b/dash/package.json
@@ -8,7 +8,7 @@
"dev": "vite",
"build": "tsc -b && vite build",
"build:single": "tsc -b && SINGLEFILE=1 vite build --outDir dist-single && mv dist-single/index.html dist-single/Bento_Dash.bento.html && node ../scripts/postbuild-compress.mjs dist-single/Bento_Dash.bento.html --generator bento-dash --title \"bento/dash\"",
- "build:sealtest": "rm -rf dist-sealtest && tsc -b && SINGLEFILE=1 BENTO_TEST_SEAL=1 vite build --outDir dist-sealtest && mv dist-sealtest/index.html dist-sealtest/Bento_Dash.bento.html && node ../scripts/postbuild-compress.mjs dist-sealtest/Bento_Dash.bento.html --generator bento-dash --title \"bento/dash\"",
+ "build:sealtest": "rm -rf dist-sealtest && tsc -b && SINGLEFILE=1 BENTO_TEST_SEAL=1 vite build --outDir dist-sealtest && mv dist-sealtest/index.html dist-sealtest/Bento_Dash.bento.html && node ../scripts/postbuild-compress.mjs dist-sealtest/Bento_Dash.bento.html --generator bento-dash --title \"bento/dash\" && touch dist-sealtest/.complete",
"preview": "vite preview"
},
"devDependencies": {
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 21504a30..6fbd5d3e 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -11292,3 +11292,32 @@ shell it serves (gate 1, A2).
Still for a real phone: TEE and StrongBox residency (the emulator reports
software keys), and the API 26–29 consent path, which allows biometrics only.
+
+## 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 11
+sites across four apps. kernel/src/autosave.ts is the one place they all go
+through, so it now fails closed (security): while `isBodySealed()`,
+`putRecovery` and `addVersion` refuse, and `getRecovery` and `listVersions`
+offer nothing. Deleting still works (`clearRecovery`, `clearVersions`): a sealed
+boot purges plaintext copies left from an earlier unsealed session, for that
+document only, and depends on it. The apps KEEP their guards and their purge
+calls. So the backstop can't mask a missing guard, each refusal is counted, and
+the count is readable only through the test-build probe. The sealed-test helper
+fails any sealed page whose rig leaned on it (`close()`/`reload()` throw), so an
+app's guard mutants stay red with no local kernel mutant. `build:sealtest` also
+writes `dist-sealtest/.complete` as its last step, and the helper refuses a shell
+without it: a build that fails after vite wrote the shell can no longer be scored.
+
+## 2026-10-18 — bento/connect: the page tells its host whether it is sealed
+
+A host that declares `'seal'` in `__bentoHost.ops` (Android, through
+home/bridge.js) blanks its app-switcher snapshot while a sealed document is open
+(security §30.6). kernel/src/save.ts posts `{__bento_tray__, dir:'req',
+op:'seal.state', payload:{sealed: isBodySealed()}}` at boot (capturePristine)
+and on every change: a password set or removed, the identity seal on or off. It
+posts the moment the change happens, before any save, because a password set but
+not yet saved is already a secret. The payload is a bare boolean, fire-and-forget,
+and not deduplicated: the host can only ADD blanking, so a missed `true` is the
+only failure and a redundant post costs nothing. Hosts that don't declare
+`'seal'` are sent nothing.
diff --git a/kernel/fixtures/README.md b/kernel/fixtures/README.md
index 6b116a2e..ee25b3ec 100644
--- a/kernel/fixtures/README.md
+++ b/kernel/fixtures/README.md
@@ -23,6 +23,13 @@ bytes end to end. Reference: `kernel/src/recovery.ts`. Rig:
- **Argon2id first.** Check your Argon2id against the `rfc9106` row (RFC 9106
§5.3, with its own parameters) before trusting it. Then use OUR parameters:
version 0x13, p = 1, m = 64 MiB, t = 3, a 32-byte tag, 16-byte salts.
+- **Check the memory BEFORE allocating; don't count on catching the failure.**
+ On Android, catching `OutOfMemoryError` around Argon2id does NOT fail closed.
+ On a 48 MiB heap, the runtime's own threads hit the OOM and the process
+ died. Measure the remaining heap first and refuse unless it covers the
+ 65,536 blocks plus headroom (each 1 KiB block costs 1,040 bytes on ART).
+ iOS and desktop have their own memory behaviour, but the rule is the same:
+ decide first, then allocate. (home-android, measured)
- **The code is 17 symbols: 16 data symbols and a check symbol**, printed
`XXXX-XXXX-XXXX-XXXX-C`. Data symbols are Crockford base32 (no I, L, O, U).
The check is the 80-bit value mod 37, with `* ~ $ = U` for 32 to 36. Every one
diff --git a/kernel/src/autosave.ts b/kernel/src/autosave.ts
index 5ee83da6..3b9e9edc 100644
--- a/kernel/src/autosave.ts
+++ b/kernel/src/autosave.ts
@@ -18,6 +18,23 @@
import type { KernelDoc } from './doc.ts'
import { appConfig } from './app.ts'
import { docStore, getJSON, setJSON } from './docstore.ts'
+import { isBodySealed, noteStoreRefusal } from './save.ts'
+
+/**
+ * The BACKSTOP (security): while the body is sealed, by a password or the
+ * identity seal, this store neither keeps nor offers a plaintext copy. Every app
+ * already guards its own calls; this is the one place they all go through, so an
+ * app that misses one of its sites still cannot write or offer plaintext.
+ * Deleting stays allowed (clearRecovery, clearVersions): the purge of copies left
+ * from an earlier unsealed session depends on it. Each refusal is counted
+ * (save.ts noteStoreRefusal), and the sealed-test rigs fail on any, so an app
+ * that relies on this instead of its own guard still fails its own rig.
+ */
+function sealedRefusal(): boolean {
+ if (!isBodySealed()) return false
+ noteStoreRefusal()
+ return true
+}
/**
* One database PER APP.
@@ -211,6 +228,7 @@ export function onRecoveryOff(fn: (docId: string, reason: string) => void): () =
}
export async function putRecovery(doc: KernelDoc): Promise<boolean> {
+ if (sealedRefusal()) return false
const snap: Snapshot = { docId: doc.docId, at: Date.now(), title: doc.title, json: contentOnly(doc) }
// Under a host with a per-document store (docstore.ts), the recovery copy
// lives THERE — out of the storage origin every local file shares — and any
@@ -239,6 +257,7 @@ export async function putRecovery(doc: KernelDoc): Promise<boolean> {
}
export async function getRecovery(docId: string): Promise<Snapshot | null> {
+ if (sealedRefusal()) return null
const ds = docStore()
if (ds) {
try {
@@ -284,15 +303,16 @@ export async function clearRecovery(docId: string): Promise<void> {
* encrypted: the plaintext snapshots written before encryption was enabled must
* not linger in IndexedDB (they'd defeat the encryption the user just turned on). */
export async function clearVersions(docId: string): Promise<void> {
- const all = await listVersions(docId)
+ const all = await versionsOf(docId) // NOT listVersions: it reads nothing while sealed, and this must still delete
await Promise.all(all.map((v) => tx(VERSIONS, 'readwrite', (s) => s.delete(v.id!))))
}
export async function addVersion(doc: KernelDoc): Promise<void> {
+ if (sealedRefusal()) return
await tx(VERSIONS, 'readwrite', (s) =>
s.add({ docId: doc.docId, at: Date.now(), title: doc.title, json: contentOnly(doc) } as Snapshot))
// prune to the newest MAX_VERSIONS for this doc
- const all = await listVersions(doc.docId)
+ const all = await versionsOf(doc.docId)
if (all.length > MAX_VERSIONS) {
const doomed = all.slice(MAX_VERSIONS)
await Promise.all(doomed.map((v) => tx(VERSIONS, 'readwrite', (s) => s.delete(v.id!))))
@@ -300,6 +320,13 @@ export async function addVersion(doc: KernelDoc): Promise<void> {
}
export async function listVersions(docId: string): Promise<Snapshot[]> {
+ if (sealedRefusal()) return []
+ return versionsOf(docId)
+}
+
+/** Every version snapshot for a docId, newest first, whatever the seal: for
+ * this module's own pruning and purging, never handed to an app. */
+async function versionsOf(docId: string): Promise<Snapshot[]> {
const db = await openDb()
if (!db) return []
return new Promise((resolve) => {
diff --git a/kernel/src/save.ts b/kernel/src/save.ts
index 13fbbeb3..a14044ea 100644
--- a/kernel/src/save.ts
+++ b/kernel/src/save.ts
@@ -39,6 +39,7 @@ let pristine: Document | null = null
export function capturePristine() {
pristine = document.cloneNode(true) as Document
if (typeof __BENTO_TEST_SEAL__ !== 'undefined' && __BENTO_TEST_SEAL__) consumeTestSeal()
+ announceSeal() // boot: the host learns the starting state before anything else happens
}
/**
@@ -72,6 +73,7 @@ function consumeTestSeal() {
body: (doc: KernelDoc) => encodeDocBody(doc),
file: (doc: KernelDoc) => serializeAuto(doc),
fileName: (doc: KernelDoc) => suggestedFileName(doc),
+ storeRefusals: () => storeRefusalCount(),
})
}
@@ -496,6 +498,7 @@ let encPassword: string | null = null
/** Set (or clear with null) the password used for every subsequent save. */
export function setEncryptionPassword(p: string | null) {
encPassword = p
+ announceSeal()
}
export const isEncryptionActive = () => encPassword !== null
@@ -515,9 +518,10 @@ let sealBodyKey: Promise<CryptoKey> | null = null
* every later save closed rather than letting it write plaintext.
*/
export function setIdentitySeal(kdoc: Uint8Array | null): void {
- if (kdoc === null) { sealBodyKey = null; return }
+ if (kdoc === null) { sealBodyKey = null; announceSeal(); return }
if (!(kdoc instanceof Uint8Array) || kdoc.length !== 32) throw new Error('the document key is 32 bytes')
sealBodyKey = crypto.subtle.importKey('raw', kdoc.slice() as BufferSource, 'HKDF', false, ['deriveKey'])
+ announceSeal()
}
/**
@@ -530,6 +534,36 @@ export function setIdentitySeal(kdoc: Uint8Array | null): void {
*/
export const isBodySealed = () => encPassword !== null || sealBodyKey !== null
+/**
+ * How many times the plaintext store (autosave.ts) refused a write or a read
+ * because the body is sealed. The store's refusal is a BACKSTOP under each app's
+ * own guards: an app that leans on it has a missing guard. Readable only through
+ * the test probe, so the sealed-test rigs can fail on any refusal (security).
+ */
+/**
+ * Tell the HOST whether this document is sealed (security §30.6): a host that
+ * declares 'seal' (home/bridge.js, Android today) blanks its app-switcher
+ * snapshot while it is. Sent at boot and on EVERY change (password set or
+ * removed, identity seal on or off), the moment it happens and before any save,
+ * because a password set but not yet saved is already a secret. A bare boolean,
+ * fire-and-forget: the host never replies, and it can only ADD blanking, so a
+ * missed `true` is the only failure and a redundant post is free. Not
+ * deduplicated, for that reason.
+ */
+let sealPostId = 0
+function announceSeal(): void {
+ const host = (globalThis as { __bentoHost?: { ops?: readonly string[] } }).__bentoHost
+ if (typeof window === 'undefined' || typeof window.postMessage !== 'function') return
+ if (!Array.isArray(host?.ops) || !host.ops.includes('seal')) return
+ window.postMessage({ __bento_tray__: true, dir: 'req', id: `seal-${++sealPostId}`, op: 'seal.state', payload: { sealed: isBodySealed() } }, '*')
+}
+
+let storeRefusals = 0
+export function noteStoreRefusal(): void { storeRefusals++ }
+/** For rigs only (node, or a page through the test probe). Unreachable from page
+ * script in a release: a module export inside the bundle, and unused there. */
+export function storeRefusalCount(): number { return storeRefusals }
+
/** Parse a data-block body as an encryption envelope; null if it is not one. */
export function parseEnvelope(text: string): EncEnvelope | null {
try {
diff --git a/scripts/lib/sealed-boot.mjs b/scripts/lib/sealed-boot.mjs
index 0f61f89c..a88363a6 100644
--- a/scripts/lib/sealed-boot.mjs
+++ b/scripts/lib/sealed-boot.mjs
@@ -12,9 +12,11 @@
// guard check against a document that was never sealed passes vacuously.
//
// import { openSealed, scanIndexedDB } from './lib/sealed-boot.mjs'
-// const { page, reload } = await openSealed(browser, 'slides', { doc }) // doc optional
+// const { page, reload, close } = await openSealed(browser, 'slides', { doc }) // doc optional
// ...edit the document, wait out the autosave debounce...
// assert.deepEqual(await scanIndexedDB(page, MARKER), [])
+// await close() // THROWS if the kernel store had to refuse a plaintext write:
+// // the app's own guard is missing (use close(), not context.close())
//
// Every rig that uses it should also run its edit on an UNSEALED page
// (openSealed(browser, app, { sealed: false })) and see the marker land in
@@ -37,15 +39,20 @@ export const TEST_KDOC = Array.from({ length: 32 }, (_, i) => (i * 7 + 3) & 0xff
/**
* The test shell for an app, by explicit path. Never a release (dist-single)
- * shell. build:sealtest deletes dist-sealtest/ before it compiles, so a build
- * that fails leaves NO shell rather than the previous one: a mutation that does
- * not compile can't be scored against stale code (type and dash both hit this).
+ * shell. build:sealtest deletes dist-sealtest/ before it compiles and writes
+ * dist-sealtest/.complete only after its last step, so a build that fails at ANY
+ * step leaves nothing this accepts: a mutation that does not build can't be
+ * scored against stale or half-built code (type, dash and security all hit this).
*/
export function sealtestShell(app) {
const rel = SHELLS[app]
if (!rel) throw new Error(`sealed-boot: no such app ${app}`)
const url = new URL(`../../${rel}`, import.meta.url)
if (!existsSync(url)) throw new Error(`sealed-boot: no ${rel}. Run npm run build:sealtest --prefix ${app}, and check its exit code: a failed build leaves no shell`)
+ // build:sealtest touches .complete as its LAST step, after postbuild-compress:
+ // a build that failed after vite wrote the shell leaves a shell but no marker
+ // (security measured one: an uncompressed shell that failed a row spuriously)
+ if (!existsSync(new URL('.complete', url))) throw new Error(`sealed-boot: ${rel} is from a build:sealtest that did not finish (no .complete marker). Rebuild, and check its exit code`)
return url
}
@@ -82,7 +89,8 @@ export function sealtestShellWith(app, doc) {
* openSealed(browser, app, { context: first.context, url: first.url })
* boots the SAME document SEALED on the same storage, which must refuse it.
*/
-export async function openSealed(browser, app, { sealed = true, kdoc = TEST_KDOC, doc, url, context, viewport = { width: 1280, height: 900 } } = {}) {
+export async function openSealed(browser, app, { sealed = true, kdoc = TEST_KDOC, doc, url, context, allowStoreRefusals = false, viewport = { width: 1280, height: 900 } } = {}) {
+ const ownContext = !context
if (!context) {
context = await browser.newContext({ viewport })
await context.route(/^https?:/, (route) => route.abort())
@@ -96,8 +104,23 @@ export async function openSealed(browser, app, { sealed = true, kdoc = TEST_KDOC
url ??= (doc === undefined ? sealtestShell(app) : sealtestShellWith(app, doc)).href
await page.goto(url)
await provenState(page, app, sealed)
- const reload = async () => { await page.reload(); await provenState(page, app, sealed) }
- return { context, page, errors, url, reload }
+ // The kernel store refuses plaintext while sealed, as a BACKSTOP. An app's
+ // own guard must stop the call first, so any refusal is a missing guard: a
+ // sealed page fails here before it reloads or closes, unless the rig opts out
+ // with { allowStoreRefusals: true } for a row that tests the backstop itself.
+ const settle = async () => {
+ if (!sealed || allowStoreRefusals) return
+ const n = await storeRefusals(page)
+ if (n !== 0) throw new Error(`sealed-boot: ${app} leaned on the kernel store's backstop ${n} time(s): one of its own plaintext guards is missing`)
+ }
+ const reload = async () => { await settle(); await page.reload(); await provenState(page, app, sealed) }
+ const close = async () => { try { await settle() } finally { if (ownContext) await context.close(); else await page.close() } }
+ return { context, page, errors, url, reload, close, settle }
+}
+
+/** How many plaintext reads or writes the kernel store has refused on this (sealed) page. */
+export async function storeRefusals(page) {
+ return page.evaluate(() => globalThis.__bentoTestSealProbe?.storeRefusals?.() ?? 0)
}
/** Wait for boot, then prove the seal state matches `sealed`; throw otherwise. */
diff --git a/scripts/test-body-seal.ts b/scripts/test-body-seal.ts
index efd6c98e..ce298a3b 100644
--- a/scripts/test-body-seal.ts
+++ b/scripts/test-body-seal.ts
@@ -20,7 +20,7 @@
import { configureApp } from '../kernel/src/app.ts'
import {
setIdentitySeal, isBodySealed, isEncryptionActive, setEncryptionPassword, encodeDocBody,
- parseEnvelope, previewAllowed, openIdentitySealed, decryptEnvelope, suggestedFileName,
+ parseEnvelope, previewAllowed, openIdentitySealed, decryptEnvelope, suggestedFileName, capturePristine,
} from '../kernel/src/save.ts'
let failures = 0
@@ -110,5 +110,36 @@ let threw = false
try { setIdentitySeal(new Uint8Array(16)) } catch { threw = true }
ok(threw && !isBodySealed(), 'a document key that is not 32 bytes is refused, and seals nothing')
+console.log('\nthe host is told the seal state (security §30.6), on every change, before any save')
+{
+ const posts: unknown[] = []
+ const g = globalThis as Record<string, unknown>
+ g.window = { postMessage: (m: unknown) => posts.push(m) }
+ g.document = { cloneNode: () => ({}) }
+ const last = () => (posts.at(-1) as { payload?: { sealed?: unknown } } | undefined)?.payload?.sealed
+ // a host that does NOT declare 'seal' hears nothing
+ g.__bentoHost = { ops: ['store'] }
+ setEncryptionPassword('x'); setEncryptionPassword(null)
+ ok(posts.length === 0, "a host without 'seal' is sent nothing")
+ g.__bentoHost = { ops: ['store', 'seal'] }
+ capturePristine()
+ ok(posts.length === 1 && last() === false, 'boot: sealed=false for a plain document')
+ setEncryptionPassword('correct horse')
+ ok(last() === true, 'a password SET (not yet saved): sealed=true, at once')
+ setEncryptionPassword(null)
+ ok(last() === false, 'the password removed: sealed=false')
+ setIdentitySeal(kdoc)
+ ok(last() === true, 'the identity seal on: sealed=true')
+ setIdentitySeal(null)
+ ok(last() === false, 'the identity seal off: sealed=false')
+ const m = posts[1] as Record<string, unknown> & { payload: Record<string, unknown> }
+ ok(m.__bento_tray__ === true && m.dir === 'req' && m.op === 'seal.state' && typeof m.payload.sealed === 'boolean' && Object.keys(m.payload).length === 1,
+ "the message is the relay's shape, and the payload a bare boolean")
+ setEncryptionPassword('a'); setEncryptionPassword('b')
+ ok(posts.length === 7, 'not deduplicated: an unchanged state is posted again (a missed true is the only failure)')
+ setEncryptionPassword(null)
+ delete g.window; delete g.document; delete g.__bentoHost
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`)
process.exit(failures ? 1 : 0)
diff --git a/scripts/test-sealed-boot.mjs b/scripts/test-sealed-boot.mjs
index 54ae0055..e3b1fac6 100644
--- a/scripts/test-sealed-boot.mjs
+++ b/scripts/test-sealed-boot.mjs
@@ -14,7 +14,7 @@
//
// npm run build:sealtest --prefix slides && node scripts/test-sealed-boot.mjs
-import { openSealed, savedFile, scanIndexedDB } from './lib/sealed-boot.mjs'
+import { openSealed, savedFile, scanIndexedDB, storeRefusals } from './lib/sealed-boot.mjs'
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')
const MARK = 'ZZSEALEDMARK' + Date.now()
@@ -49,17 +49,37 @@ try {
ok(!file.includes('data-bento-preview'), 'no first-page preview')
ok(!fileName.includes(MARK), `the filename is neutral, not the title (${fileName})`)
const idb = await scanIndexedDB(page, MARK)
- console.log(` info IndexedDB records carrying the content after an edit, sealed: ${idb.length ? idb.join(', ') : 'none'}`)
+ ok(idb.length === 0, `no plaintext in IndexedDB after a sealed edit (${idb.join(', ') || 'none'}): the app's guard, or the kernel store's backstop`)
ok(errors.length === 0, `no page errors${errors.length ? ': ' + errors[0] : ''}`)
await context.close()
}
+ console.log('\nthe backstop is visible to the rigs: an app leaning on it fails close()')
+ {
+ // Which branch runs depends on the app's guards: today slides' are not yet
+ // switched, so its sealed edit reaches the store and is REFUSED there. Once
+ // its guards switch, nothing reaches the store. Either way close() must agree
+ // with the counter: that is what keeps each app's guard mutants red.
+ const s = await openSealed(browser, 'slides')
+ await markDocument(s.page)
+ const n = await storeRefusals(s.page)
+ const threw = await s.close().then(() => null, (e) => e.message)
+ console.log(` info the kernel store refused ${n} plaintext call(s) on a sealed slides edit`)
+ ok(n > 0 ? /leaned on the kernel store's backstop/.test(threw ?? '') : threw === null,
+ n > 0 ? 'refusals > 0, so close() throws: the missing guard fails the rig' : 'no refusals, so close() passes')
+ const t = await openSealed(browser, 'slides', { allowStoreRefusals: true })
+ await markDocument(t.page)
+ ok(await t.close().then(() => true, () => false), 'with { allowStoreRefusals: true }, close() does not throw')
+ }
+
console.log('\na fixed document, across a reload (for recovery rows keyed by docId)')
{
const base = await openSealed(browser, 'slides', { sealed: false })
const doc = await base.page.evaluate((m) => ({ ...structuredClone(window.bento.doc), title: m }), MARK)
await base.context.close()
- const { page, context, reload } = await openSealed(browser, 'slides', { doc })
+ // allowStoreRefusals: this row tests the helper's fixed-document mechanics,
+ // not slides' guards (its own rig asserts those)
+ const { page, context, reload } = await openSealed(browser, 'slides', { doc, allowStoreRefusals: true })
const first = await page.evaluate(() => ({ id: window.bento.doc.docId, title: window.bento.doc.title }))
ok(first.id === doc.docId && first.title === MARK, 'the fixed document booted, sealed, with its own docId')
await reload() // re-installs the handoff and re-proves the seal, or throws
@@ -74,7 +94,7 @@ try {
await markDocument(plain.page)
ok((await scanIndexedDB(plain.page, MARK)).length > 0, 'the unsealed session leaves the marker in IndexedDB')
const docId = await plain.page.evaluate(() => window.bento.doc.docId)
- const sealedPage = await openSealed(browser, 'slides', { context: plain.context, url: plain.url })
+ const sealedPage = await openSealed(browser, 'slides', { context: plain.context, url: plain.url, allowStoreRefusals: true })
ok((await scanIndexedDB(sealedPage.page, MARK)).length > 0, 'a sealed page on the same context sees the same storage')
ok(await sealedPage.page.evaluate(() => !!globalThis.__bentoTestSealProbe), 'and it is sealed (the handoff is per page)')
await plain.reload()
diff --git a/scripts/test-store-backstop.ts b/scripts/test-store-backstop.ts
new file mode 100644
index 00000000..66e16767
--- /dev/null
+++ b/scripts/test-store-backstop.ts
@@ -0,0 +1,85 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The plaintext store's BACKSTOP (security, after K3): while the body is sealed,
+// kernel/src/autosave.ts neither keeps nor offers a plaintext copy, and still
+// DELETES, because the purge of copies left from an earlier unsealed session
+// depends on it.
+//
+// Each app guards its own calls to the store. This is the one place they all go
+// through, so an app that misses one of its ~11 sites still can't write or offer
+// plaintext for a sealed document. (The sealed-test helper fails any app that
+// leans on it, through a refusal counter only the test probe can read.)
+//
+// esbuild-bundled like test-autosave.ts (fake-indexeddb); see the CI step.
+
+import 'fake-indexeddb/auto'
+import { configureApp } from '../kernel/src/app.ts'
+import { putRecovery, getRecovery, addVersion, listVersions, clearRecovery, clearVersions } from '../kernel/src/autosave.ts'
+import { setIdentitySeal, setEncryptionPassword, isBodySealed, storeRefusalCount } from '../kernel/src/save.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+configureApp({ appId: 'bento-slides', appName: 'Bento Slides', manifestUrl: 'https://invalid.example/m.json' })
+const kdoc = Uint8Array.from({ length: 32 }, (_, i) => i + 9)
+const docOf = (docId: string, title: string) => ({ format: 'bento/slides', docId, title, slides: [] }) as never
+const A = docOf('doc-a', 'ZZ A ZZ'), B = docOf('doc-b', 'ZZ B ZZ')
+
+console.log('\nunsealed: the store keeps and offers, as today')
+ok(!isBodySealed(), 'nothing is sealed')
+ok(await putRecovery(A), 'putRecovery stores')
+ok((await getRecovery('doc-a'))?.title === 'ZZ A ZZ', 'getRecovery offers it')
+await addVersion(A)
+ok((await listVersions('doc-a')).length === 1, 'addVersion keeps a version, and listVersions offers it')
+await putRecovery(B); await addVersion(B)
+
+for (const [label, seal, unseal] of [
+ ['the identity seal', () => setIdentitySeal(kdoc), () => setIdentitySeal(null)],
+ ['a password', () => setEncryptionPassword('correct horse'), () => setEncryptionPassword(null)],
+] as const) {
+ console.log(`\nsealed by ${label}: nothing kept, nothing offered`)
+ seal()
+ ok(isBodySealed(), 'sealed')
+ ok((await putRecovery(docOf('doc-a', 'ZZ NEW ZZ'))) === false, 'putRecovery refuses')
+ ok((await getRecovery('doc-a')) === null, 'getRecovery offers nothing (the earlier plaintext copy is not shown)')
+ await addVersion(docOf('doc-a', 'ZZ NEW ZZ'))
+ ok((await listVersions('doc-a')).length === 0, 'listVersions offers nothing')
+ unseal()
+ ok((await getRecovery('doc-a'))?.title === 'ZZ A ZZ', 'unsealed again: the refused write never landed (the old copy is untouched)')
+ ok((await listVersions('doc-a')).length === 1, 'and no version was added while sealed')
+}
+
+console.log('\nthe refusal counter, directly: each refused call counts once, nothing else counts')
+{
+ const n0 = storeRefusalCount()
+ await putRecovery(docOf('doc-c', 'c')); await addVersion(docOf('doc-c', 'c'))
+ await getRecovery('doc-c'); await listVersions('doc-c')
+ ok(storeRefusalCount() === n0, 'unsealed: four store calls, the counter unchanged')
+ setIdentitySeal(kdoc)
+ await putRecovery(docOf('doc-c', 'c')); await addVersion(docOf('doc-c', 'c'))
+ ok(storeRefusalCount() === n0 + 2, 'sealed: putRecovery + addVersion raise it by exactly 2')
+ await getRecovery('doc-c'); await listVersions('doc-c')
+ ok(storeRefusalCount() === n0 + 4, 'sealed: READS count too: getRecovery + listVersions raise it by 2 more')
+ await clearRecovery('doc-c'); await clearVersions('doc-c')
+ ok(storeRefusalCount() === n0 + 4, 'sealed: the purge is not a refusal (unchanged)')
+ setIdentitySeal(null)
+}
+
+console.log('\nthe purge still works while sealed, for that document only')
+setIdentitySeal(kdoc)
+await clearRecovery('doc-a')
+await clearVersions('doc-a')
+setIdentitySeal(null)
+ok((await getRecovery('doc-a')) === null, 'clearRecovery deleted the plaintext recovery copy while sealed')
+ok((await listVersions('doc-a')).length === 0, 'clearVersions deleted the plaintext versions while sealed')
+ok((await getRecovery('doc-b'))?.title === 'ZZ B ZZ', "another document's recovery copy survives")
+ok((await listVersions('doc-b')).length === 1, "another document's versions survive")
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)
diff --git a/slides/package.json b/slides/package.json
index 6251e42e..e51c5d70 100644
--- a/slides/package.json
+++ b/slides/package.json
@@ -8,7 +8,7 @@
"dev": "vite",
"build": "tsc -b && vite build",
"build:single": "tsc -b && SINGLEFILE=1 vite build --outDir dist-single && mv dist-single/index.html dist-single/Bento_Slides.bento.html && node ../scripts/postbuild-compress.mjs dist-single/Bento_Slides.bento.html",
- "build:sealtest": "rm -rf dist-sealtest && tsc -b && SINGLEFILE=1 BENTO_TEST_SEAL=1 vite build --outDir dist-sealtest && mv dist-sealtest/index.html dist-sealtest/Bento_Slides.bento.html && node ../scripts/postbuild-compress.mjs dist-sealtest/Bento_Slides.bento.html",
+ "build:sealtest": "rm -rf dist-sealtest && tsc -b && SINGLEFILE=1 BENTO_TEST_SEAL=1 vite build --outDir dist-sealtest && mv dist-sealtest/index.html dist-sealtest/Bento_Slides.bento.html && node ../scripts/postbuild-compress.mjs dist-sealtest/Bento_Slides.bento.html && touch dist-sealtest/.complete",
"preview": "vite preview"
},
"dependencies": {
diff --git a/spaces/package.json b/spaces/package.json
index fc1cd178..481e9ae6 100644
--- a/spaces/package.json
+++ b/spaces/package.json
@@ -8,7 +8,7 @@
"dev": "vite",
"build": "tsc -b && vite build",
"build:single": "tsc -b && SINGLEFILE=1 vite build --outDir dist-single && mv dist-single/index.html dist-single/Bento_Spaces.bento.html && node ../scripts/postbuild-compress.mjs dist-single/Bento_Spaces.bento.html --generator bento-spaces --title \"bento/spaces\"",
- "build:sealtest": "rm -rf dist-sealtest && tsc -b && SINGLEFILE=1 BENTO_TEST_SEAL=1 vite build --outDir dist-sealtest && mv dist-sealtest/index.html dist-sealtest/Bento_Spaces.bento.html && node ../scripts/postbuild-compress.mjs dist-sealtest/Bento_Spaces.bento.html --generator bento-spaces --title \"bento/spaces\"",
+ "build:sealtest": "rm -rf dist-sealtest && tsc -b && SINGLEFILE=1 BENTO_TEST_SEAL=1 vite build --outDir dist-sealtest && mv dist-sealtest/index.html dist-sealtest/Bento_Spaces.bento.html && node ../scripts/postbuild-compress.mjs dist-sealtest/Bento_Spaces.bento.html --generator bento-spaces --title \"bento/spaces\" && touch dist-sealtest/.complete",
"preview": "vite preview"
},
"devDependencies": {
diff --git a/type/package.json b/type/package.json
index b874a518..9d1d0120 100644
--- a/type/package.json
+++ b/type/package.json
@@ -8,7 +8,7 @@
"dev": "vite",
"build": "tsc -b && vite build",
"build:single": "tsc -b && SINGLEFILE=1 vite build --outDir dist-single && mv dist-single/index.html dist-single/Bento_Type.bento.html && node ../scripts/postbuild-compress.mjs dist-single/Bento_Type.bento.html --generator bento-type --title \"bento/type\"",
- "build:sealtest": "rm -rf dist-sealtest && tsc -b && SINGLEFILE=1 BENTO_TEST_SEAL=1 vite build --outDir dist-sealtest && mv dist-sealtest/index.html dist-sealtest/Bento_Type.bento.html && node ../scripts/postbuild-compress.mjs dist-sealtest/Bento_Type.bento.html --generator bento-type --title \"bento/type\"",
+ "build:sealtest": "rm -rf dist-sealtest && tsc -b && SINGLEFILE=1 BENTO_TEST_SEAL=1 vite build --outDir dist-sealtest && mv dist-sealtest/index.html dist-sealtest/Bento_Type.bento.html && node ../scripts/postbuild-compress.mjs dist-sealtest/Bento_Type.bento.html --generator bento-type --title \"bento/type\" && touch dist-sealtest/.complete",
"preview": "vite preview"
},
"devDependencies": {