Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

home: native hosts keep a document's recovery copy and member key outside the page (#756)

nyblnetad220e7f0d2c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 15a77242..9035bb7c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -730,6 +730,25 @@ jobs:
# silent save — and a launch request the host cannot meet is refused,
# never turned into an export. Runs the real bridge against a fake host.
run: node scripts/test-home-launch.mjs
+ - name: home per-document store rig
+ # The shared bridge relays the kernel's per-document store
+ # (kernel/src/docstore.ts) to a native host, which keeps the recovery
+ # copy and the member key out of the page's own web storage. Driven end
+ # to end here: the real bridge, the real kernel client, a fake host. It
+ # proves the store appears ONLY when the native side declares it — a
+ # store advertised and then refused would lose the member key on every
+ # reload — and that bytes round-trip as a Uint8Array the kernel accepts.
+ run: node scripts/test-home-docstore.mjs
+ - name: home legacy-origin inspector rig
+ # Before an Android document adopts the storage it used under the old
+ # per-path origins, an inspector page reports which documents own data
+ # there. This runs that script as it ships (extracted from
+ # DocumentOrigin.kt) against kernel-shaped storage: every app's autosave
+ # attributed, bento-handles by key, and anything it cannot tie to a
+ # document — including bento-blobcache, which holds plaintext media —
+ # refusing adoption. The JVM tests cover the decision; only this covers
+ # the script.
+ run: node scripts/test-home-inspector.mjs
- name: tray mark is one source
# tray-icon.svg is the only drawing of the mark. Everything else is
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 4a1deb75..dbc5b74f 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -14,6 +14,69 @@ Decision. Why. Pointers.
---
+## 2026-10-18 — Native hosts keep a document's recovery copy and member key outside the page
+
+**Decision.** The native hosts provide the per-document store that
+`kernel/src/docstore.ts` already speaks, so the kernel stops keeping two
+things in the page's own web storage: the crash-recovery copy (`recovery`) and
+this device's member key for the document (`memberkey`, whose private half is
+what lets this device act in the document's live room). Until now only the
+browser extension provided one, and on Android and iOS the whole member key,
+private half included, sat in the document origin's localStorage.
+
+**The shared half, `home/bridge.js`:**
+
+- **The host declares; the bridge obeys.** Each host prepends
+ `window.__bentoHostCaps = ['store']` to the injected bridge. Only then does
+ the bridge define `window.__bentoHost = {ops:['store']}` (non-writable) and
+ relay. A host that advertised a store it could not serve would lose the
+ member key on every reload: the kernel, finding a store present but refusing,
+ keeps the key for that page only and deliberately never falls back to
+ localStorage.
+- **Top frame only, page window only.** No store in a subframe, and a request
+ whose source is not the page's own window is ignored.
+- **The native contract**, written at the relay and enforced by
+ `scripts/test-home-docstore.mjs`. Requests are `{op, name, b64}`. Replies are
+ `(ok, value)`: `get` gives base64 or null; `set` and `delete` give null;
+ `list` gives a JSON array; any failure gives `'refused'` (a name other than
+ recovery/memberkey), `'too-large'` or `'unavailable'`. Bytes are rebuilt as a
+ `Uint8Array` in the page's own realm, because the kernel checks
+ `instanceof`.
+
+**Android, `DocStore.kt`:** partitioned by the document's claim (the identity
+that chooses its origin, 2026-10-18), never a path, URI or anything the page
+names. Encrypted with AES-GCM under a Keystore key. Kept in no-backup app
+storage. Written beside the entry, then renamed, so a crash leaves the old
+entry, not a truncated one. Capped at 64 MB. Runs on the same ordered thread
+as file writes.
+
+Each entry is authenticated with its claim and name (AES-GCM additional data):
+an entry file copied into another document's directory, or renamed from
+`recovery` to `memberkey`, fails authentication instead of decrypting as that
+document's (measured: a renamed genuine entry is refused, and the real one still
+reads). Such an entry reads as ABSENT, not as unavailable. The kernel refuses to
+mint a member key while the store "cannot answer", so treating it as unavailable
+would wedge that document's member identity for good. Absent lets it mint a
+fresh one; the next write replaces the bad entry.
+
+**Verified.** The rig drives the real bridge with the kernel's real client: no
+capability means no store at all; with the capability, 1 MiB round-trips and
+refusals pass through. The kernel's real `deviceIdentity` runs through it too:
+an existing member key in localStorage is adopted unchanged, with its private
+half moved into the store and only `{pub}` left behind; a new key is minted
+straight into the store; without the capability, nothing moves (the control). Removing the capability gate fails the three no-store
+checks. On the emulator the kernel's own autosave moved its recovery copy into
+the native store, and IndexedDB recovery came back empty.
+
+**With it:** the legacy-origin inspector now reads keys only (key cursors),
+attributes `bento-handles` by key, and refuses any other database that holds
+records. That includes `bento-blobcache`, which caches live-session media in
+plaintext. `scripts/test-home-inspector.mjs` runs the script as it ships; it
+also matched real Chromium IndexedDB case for case.
+
+**iOS** implements the same native contract in its own change, keeping the
+member key in the Keychain (this device only).
+
## 2026-10-18 — Android: every docId form the apps mint counts as a docId
**Supersedes "a strict UUID"** in the entry below. Spaces always mints
diff --git a/home/README.md b/home/README.md
index 175e1e2c..037d691d 100644
--- a/home/README.md
+++ b/home/README.md
@@ -462,6 +462,12 @@ be — but the question it asked was the right one, and it was asked first.
### Parity with the iOS host
+**Encrypting a document changes which storage it gets on Android.** An
+encrypted document carries no readable docId, so its storage is tied to its
+exact bytes instead — and the first save after adding a password writes
+different bytes. The document keeps working; its previous recovery copy and
+member key stay in the storage it had, which it no longer opens.
+
The two hosts are meant to behave identically from inside the document. Where
they cannot, it is because the platform forces it — and that is written down
here rather than discovered later.
@@ -469,8 +475,10 @@ here rather than discovered later.
| behaviour | `home/ios` | `home/android` | |
|---|---|---|---|
| FSA polyfill | `home/bridge.js` | `home/bridge.js` | **one shared file** |
-| per-document origin | `bento-tray://<host>`: follows the FILE (its document identifier), not the path — `OriginIdentity` | `https://<sha24>.bento-tray.invalid`, intercepted — from the URI | **differs** (Android fixing) |
-| a document is served only under its own host | ✓ | — | — |
+| per-document origin | `bento-tray://<host>`: follows the FILE (its document identifier), not the path — `OriginIdentity` | `https://<claim>.bento-tray.invalid`: a claim bound to the document's docId in a device-local index, not the URI — `DocumentOrigin` | same |
+| a document is served only under its own host | ✓ | ✓ (by code: the interceptor answers only the document's own host) | same |
+| a moved document keeps its storage | ✓ (the document identifier follows the file) | ✗ by design: a move outside the app gets a fresh claim; the old storage is left, never cleared — SAF has no device-local anchor | **differs** |
+| per-document store for the recovery copy and member key (`__bentoHost`) | — | ✓ Keystore-encrypted, no-backup app storage, partitioned by the claim — `DocStore` | **differs** (iOS in progress) |
| document served from memory, never parsed | ✓ | ✓ | same |
| bridge injected at document start | `WKUserScript(.atDocumentStart)` | `addDocumentStartJavaScript` | same |
| bridge reachable only from the document | every message checked: main frame + own origin (`BridgeSender`) | `allowedOriginRules` + `isMainFrame` | same |
diff --git a/home/android/app/src/main/java/page/bento/home/DocStore.kt b/home/android/app/src/main/java/page/bento/home/DocStore.kt
new file mode 100644
index 00000000..66f752c7
--- /dev/null
+++ b/home/android/app/src/main/java/page/bento/home/DocStore.kt
@@ -0,0 +1,133 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+package page.bento.home
+
+import android.content.Context
+import android.security.keystore.KeyGenParameterSpec
+import android.security.keystore.KeyProperties
+import java.io.File
+import java.security.KeyStore
+import javax.crypto.Cipher
+import javax.crypto.KeyGenerator
+import javax.crypto.SecretKey
+import javax.crypto.spec.GCMParameterSpec
+
+/**
+ * The host's per-document store for `kernel/src/docstore.ts`: a document's
+ * crash-recovery copy ('recovery') and this device's member key for it
+ * ('memberkey').
+ *
+ * Without it, the kernel keeps both in the page's own web storage, so the
+ * member PRIVATE key sits wherever that origin's data does. Here it leaves the
+ * web layer altogether:
+ *
+ * - **Partitioned by the document's claim** ([DocumentOrigin]), the same
+ * identity that chooses its origin — never by a path, a URI or anything the
+ * page names. A different file at a reused path gets a different claim and
+ * so an empty store.
+ * - **Encrypted at rest** with AES-GCM under a key that never leaves the
+ * Android Keystore, in no-backup app storage: not readable by other apps,
+ * not in a backup, not usable on another device.
+ * - **Two names only.** Anything else is refused, so the store can never become
+ * a general key-value channel a page could fill.
+ * - **Bounded.** A recovery copy is the whole document; one over [MAX_BYTES]
+ * is refused rather than held in memory twice over in base64.
+ *
+ * Calls run on the caller's ordered executor, so a write followed by a read
+ * always sees the write.
+ */
+class DocStore(context: Context, private val claim: String) {
+ companion object {
+ val NAMES = setOf("recovery", "memberkey")
+ const val MAX_BYTES = 64 * 1024 * 1024
+ private const val KEY_ALIAS = "bento-docstore"
+ private const val IV_BYTES = 12
+ private const val TAG_BYTES = 16
+ private val CLAIM = Regex("^[0-9a-f]{24}$")
+ }
+
+ private val dir: File = File(context.noBackupFilesDir, "docstore/$claim")
+
+ init {
+ // The claim names a directory, so it must be exactly what DocumentOrigin
+ // mints and nothing a crafted value could turn into a path.
+ require(CLAIM.matches(claim)) { "not a document claim" }
+ }
+
+ class Refused(reason: String) : Exception(reason)
+
+ private fun file(name: String): File {
+ if (name !in NAMES) throw Refused("refused")
+ return File(dir, "$name.bin")
+ }
+
+ fun get(name: String): ByteArray? {
+ val f = file(name)
+ if (!f.exists()) return null
+ val blob = f.readBytes()
+ // Shorter than an IV plus a GCM tag cannot be an entry we wrote — the
+ // atomic rename rules out a torn write, so this is corruption. Absent,
+ // for the same reason a failed tag is: anything else would read as
+ // "unavailable" and wedge the member identity. (A Keystore or I/O fault
+ // still propagates as unavailable, so a transient one never overwrites a
+ // good key.)
+ if (blob.size < IV_BYTES + TAG_BYTES) return null
+ val c = Cipher.getInstance("AES/GCM/NoPadding")
+ c.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(TAG_BYTES * 8, blob, 0, IV_BYTES))
+ c.updateAAD(boundTo(name))
+ return try {
+ c.doFinal(blob, IV_BYTES, blob.size - IV_BYTES)
+ } catch (e: javax.crypto.AEADBadTagException) {
+ // An entry that fails authentication holds nothing usable, so it
+ // reads as ABSENT, not as an unanswered request. The kernel treats a
+ // store that cannot answer as blind and refuses to mint a member key
+ // while blind — so "unavailable" here would wedge this document's
+ // member identity for good. Left on disk; the next write replaces it.
+ android.util.Log.w("BentoTray", "store entry $name failed authentication; reading as absent")
+ null
+ }
+ }
+
+ fun set(name: String, bytes: ByteArray) {
+ val f = file(name)
+ if (bytes.size > MAX_BYTES) throw Refused("too-large")
+ val c = Cipher.getInstance("AES/GCM/NoPadding")
+ c.init(Cipher.ENCRYPT_MODE, key())
+ c.updateAAD(boundTo(name))
+ dir.mkdirs()
+ // Written beside, then renamed over: a crash mid-write leaves the old
+ // entry, never a truncated one that would fail to decrypt.
+ val tmp = File(dir, "$name.tmp")
+ tmp.writeBytes(c.iv + c.doFinal(bytes))
+ if (!tmp.renameTo(f)) { tmp.delete(); throw Refused("unavailable") }
+ }
+
+ fun list(): List<String> = NAMES.filter { File(dir, "$it.bin").exists() }.sorted()
+
+ fun delete(name: String): Boolean {
+ val f = file(name)
+ return !f.exists() || f.delete()
+ }
+
+ /**
+ * Authenticated with each entry: which document it belongs to and which
+ * entry it is. An entry file copied into another document's directory, or
+ * renamed from recovery to memberkey, then fails authentication instead of
+ * decrypting as that document's — the directory layout is not trusted to
+ * say whose a ciphertext is.
+ */
+ private fun boundTo(name: String) = "bento-docstore\u001f$claim\u001f$name".toByteArray()
+
+ private fun key(): SecretKey {
+ val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+ (ks.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
+ return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
+ init(KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .setKeySize(256)
+ .build())
+ }.generateKey()
+ }
+}
diff --git a/home/android/app/src/main/java/page/bento/home/DocumentOrigin.kt b/home/android/app/src/main/java/page/bento/home/DocumentOrigin.kt
index 3a5a72c7..5275f5ba 100644
--- a/home/android/app/src/main/java/page/bento/home/DocumentOrigin.kt
+++ b/home/android/app/src/main/java/page/bento/home/DocumentOrigin.kt
@@ -185,11 +185,25 @@ object DocumentOrigin {
const val INSPECTOR_PATH = "/.bento-host-inspect"
val INSPECTOR_HTML = """<!doctype html><meta charset="utf-8"><script>
(async () => {
+ // docIds that own data here, and whether anything could not be attributed.
+ // Reads KEYS only (key cursors), never record bodies.
const ids = new Set(); let unattributed = false
+ const req = (r) => new Promise((res, rej) => { r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error) })
+ // every key a cursor yields, as a docId; a non-string key is unattributable
+ const keysOf = (source, primary) => new Promise((res, rej) => {
+ const r = source.openKeyCursor()
+ r.onerror = () => rej(r.error)
+ r.onsuccess = () => {
+ const c = r.result
+ if (!c) return res()
+ const k = primary ? c.primaryKey : c.key
+ if (typeof k === 'string') ids.add(k); else unattributed = true
+ c.continue()
+ }
+ })
try {
for (let i = 0; i < localStorage.length; i++) {
- const k = localStorage.key(i)
- const m = /^bento-member-(.+)$/.exec(k)
+ const m = /^bento-member-(.+)${'$'}/.exec(localStorage.key(i))
if (m) ids.add(m[1])
}
} catch (e) { unattributed = true }
@@ -198,14 +212,20 @@ object DocumentOrigin {
// unattributable, never "empty". Only names that already exist are
// opened, at their own version, so looking never creates a database.
if (!indexedDB.databases) throw new Error('cannot list databases')
- const dbs = await indexedDB.databases()
- for (const { name } of dbs) {
- if (!name || !/autosave$/.test(name)) { if (name) unattributed = true; continue }
- const db = await new Promise((res, rej) => { const r = indexedDB.open(name); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error) })
- for (const st of db.objectStoreNames) {
- const all = await new Promise(res => { const r = db.transaction(st).objectStore(st).getAll(); r.onsuccess = () => res(r.result || []); r.onerror = () => res(null) })
- if (!all) { unattributed = true; continue }
- for (const rec of all) { if (rec && typeof rec.docId === 'string') ids.add(rec.docId); else unattributed = true }
+ for (const { name } of await indexedDB.databases()) {
+ if (!name) continue
+ const db = await req(indexedDB.open(name))
+ for (const st of Array.from(db.objectStoreNames)) {
+ const store = db.transaction(st).objectStore(st)
+ if (/-autosave${'$'}/.test(name) && st === 'recovery') await keysOf(store, true) // keyPath docId
+ else if (/-autosave${'$'}/.test(name) && st === 'versions' && store.indexNames.contains('docId'))
+ await keysOf(store.index('docId'), false) // the docId index
+ else if (name === 'bento-handles') await keysOf(store, true) // keyed by docId
+ // Anything else that holds records cannot be tied to a document —
+ // including bento-blobcache, which caches live-session media in
+ // PLAINTEXT (sync/blobs.ts), so adopting it would hand a successor the
+ // previous document's images. An empty store is harmless.
+ else if (await req(store.count()) > 0) unattributed = true
}
db.close()
}
diff --git a/home/android/app/src/main/java/page/bento/home/EditorActivity.kt b/home/android/app/src/main/java/page/bento/home/EditorActivity.kt
index f6969603..9cf433d4 100644
--- a/home/android/app/src/main/java/page/bento/home/EditorActivity.kt
+++ b/home/android/app/src/main/java/page/bento/home/EditorActivity.kt
@@ -463,7 +463,11 @@ class EditorActivity : Activity() {
message.data?.let { onBridgeMessage(it) }
}
- val src = assets.open("bridge.js").use { it.readBytes().toString(Charsets.UTF_8) }
+ // Capabilities first, then the shared bridge, in one injected script:
+ // bridge.js advertises the per-document store to the page ONLY when
+ // the host declares it here, so a host without one never offers it.
+ val src = "window.__bentoHostCaps = ['store'];\n" +
+ assets.open("bridge.js").use { it.readBytes().toString(Charsets.UTF_8) }
WebViewCompat.addDocumentStartJavaScript(web, src, rules)
}
@@ -687,6 +691,8 @@ class EditorActivity : Activity() {
}
}
+ "store.get", "store.set", "store.list", "store.delete" -> onStore(id, m)
+
else -> reply(id, false, "unknown op")
}
}
@@ -764,6 +770,35 @@ class EditorActivity : Activity() {
Log.w(TAG, "write failed", e); e.message ?: "write failed"
}
+ /** The document's store, partitioned by the claim its origin was chosen by. */
+ private val docStore: DocStore by lazy { DocStore(this, originHost.substringBefore('.')) }
+
+ /**
+ * The per-document store (see [DocStore]). On the ordered [io] thread, like
+ * the file writes: a set followed by a get must see the set, and the
+ * Keystore and disk work stay off the main thread.
+ */
+ private fun onStore(id: Int, m: JSONObject) {
+ val op = m.optString("op")
+ val name = m.optString("name")
+ val b64 = if (op == "store.set") m.optString("b64") else null
+ io.execute {
+ val (ok, value) = try {
+ when (op) {
+ "store.get" -> true to docStore.get(name)?.let { android.util.Base64.encodeToString(it, android.util.Base64.NO_WRAP) }
+ "store.set" -> { docStore.set(name, android.util.Base64.decode(b64 ?: "", android.util.Base64.DEFAULT)); true to null }
+ "store.list" -> true to org.json.JSONArray(docStore.list()).toString()
+ else -> { docStore.delete(name); true to null }
+ }
+ } catch (e: DocStore.Refused) {
+ false to (e.message ?: "refused")
+ } catch (e: Exception) {
+ Log.w(TAG, "store $op failed", e); false to "unavailable"
+ }
+ runOnUiThread { reply(id, ok, value) }
+ }
+ }
+
private fun beginExport(id: Int, name: String, text: String) {
val safe = safeFileName(name) ?: return reply(id, false, "unsafe name")
val open = pendingExport
diff --git a/home/bridge.js b/home/bridge.js
index d38bdc6d..04c48ed2 100644
--- a/home/bridge.js
+++ b/home/bridge.js
@@ -210,4 +210,86 @@
},
}
}
+ // ------------------------------------------------- the per-document store
+ //
+ // kernel/src/docstore.ts keeps two things out of the page's own web storage
+ // when a host offers a store: the crash-recovery copy ('recovery') and this
+ // device's member key for the document ('memberkey'). It finds the store by
+ // `window.__bentoHost.ops` including 'store' at boot, then speaks a
+ // request/response protocol over postMessage on its own window. This relays
+ // that protocol to the native host, which keeps each document's entries in
+ // storage partitioned by the document's own identity — never by anything the
+ // page names.
+ //
+ // ONLY when the native side says it implements the store. This file is
+ // shared, and a host that advertised a store it could not serve would cost
+ // the user their member identity on every reload: the kernel, seeing a store
+ // present but refusing, keeps the key for that page only and deliberately
+ // never falls back to localStorage. So each host declares its capabilities
+ // ahead of this file (`window.__bentoHostCaps`), and without that nothing
+ // here runs.
+ //
+ // Top frame only. Android injects this script into same-origin subframes as
+ // well; a store reachable from a frame the document created is not one the
+ // document controls.
+ ;(() => {
+ const caps = Array.isArray(window.__bentoHostCaps) ? window.__bentoHostCaps.slice() : []
+ try { delete window.__bentoHostCaps } catch (_) {}
+ if (window !== window.top || caps.indexOf('store') < 0) return
+
+ const prev = window.__bentoHost && Array.isArray(window.__bentoHost.ops) ? window.__bentoHost.ops : []
+ const ops = Object.freeze(Array.from(new Set(prev.concat(['store']))))
+ Object.defineProperty(window, '__bentoHost', {
+ value: Object.freeze({ ops }), writable: false, enumerable: true, configurable: false,
+ })
+
+ // THE NATIVE CONTRACT, identical on every host. Requests arrive through the
+ // ordinary call() channel as {id, op, name} (plus b64 for store.set). The
+ // native side answers through the ordinary reply, (id, ok, value), with
+ // value a string or null:
+ // store.get ok, value = base64 of the bytes | null when absent
+ // store.set ok, value = null
+ // store.list ok, value = JSON array of names, e.g. '["memberkey","recovery"]'
+ // store.delete ok, value = null (also when it was already absent)
+ // any failure !ok, value = 'refused' (a name other than recovery/memberkey)
+ // | 'too-large' (over the host's cap)
+ // | 'unavailable' (the host could not do it)
+ // The partition is the document's identity as the HOST derived it; nothing
+ // in a request names it. scripts/test-home-docstore.mjs holds a host to this.
+ const CH = '__bento_tray__'
+ const KNOWN = { 'store.get': 1, 'store.set': 1, 'store.list': 1, 'store.delete': 1 }
+ // Both transports carry strings, so bytes travel as base64 — and are turned
+ // back into a Uint8Array HERE, in the page's own realm, because the kernel
+ // checks `instanceof Uint8Array` and a typed array built elsewhere fails it.
+ const toB64 = (u8) => {
+ let s = ''
+ for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000))
+ return btoa(s)
+ }
+ const fromB64 = (b64) => {
+ const bin = atob(b64)
+ const out = new Uint8Array(bin.length)
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
+ return out
+ }
+
+ window.addEventListener('message', (ev) => {
+ const d = ev.data
+ if (ev.source !== window || !d || d[CH] !== true || d.dir !== 'req' ||
+ typeof d.op !== 'string' || d.op.indexOf('store.') !== 0) return
+ const respond = (result) => window.postMessage({ [CH]: true, dir: 'res', id: d.id, result }, '*')
+ if (!KNOWN[d.op]) { respond({ ok: false, reason: 'unknown op' }); return }
+ const p = d.payload || {}
+ const params = { name: p.name }
+ if (d.op === 'store.set') {
+ if (!(p.bytes instanceof Uint8Array)) { respond({ ok: false, reason: 'bytes must be a Uint8Array' }); return }
+ params.b64 = toB64(p.bytes)
+ }
+ call(d.op, params).then((value) => {
+ if (d.op === 'store.get') respond({ ok: true, bytes: value == null ? null : fromB64(String(value)) })
+ else if (d.op === 'store.list') respond({ ok: true, names: JSON.parse(String(value || '[]')) })
+ else respond({ ok: true })
+ }, (e) => respond({ ok: false, reason: String((e && e.message) || e) }))
+ })
+ })()
})();
diff --git a/scripts/test-home-docstore.mjs b/scripts/test-home-docstore.mjs
new file mode 100644
index 00000000..ffff8497
--- /dev/null
+++ b/scripts/test-home-docstore.mjs
@@ -0,0 +1,198 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The per-document store relay in home/bridge.js, driven end to end: the REAL
+// bridge, the REAL kernel client (kernel/src/docstore.ts ExtensionBackend), and
+// a fake native host that answers the way both native hosts must.
+//
+// node scripts/test-home-docstore.mjs
+//
+// What it guards:
+// - NO capability, NO store. A host that has not declared 'store' must not get
+// `window.__bentoHost` — the kernel would then use a store that refuses, and
+// deliberately never fall back, losing the member key on every reload.
+// - With the capability: get/set/list/delete round trips, bytes intact, and a
+// reply's bytes are a Uint8Array the kernel accepts.
+// - The relay answers only the page's own window, refuses unknown ops, passes a
+// native refusal through, and does nothing in a subframe.
+//
+// Each scenario runs in its own process: both the bridge and the kernel decide
+// once per page and cache it on the global.
+
+import { spawnSync } from 'node:child_process'
+import { readFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import vm from 'node:vm'
+
+const here = dirname(fileURLToPath(import.meta.url))
+const root = join(here, '..')
+const BRIDGE = readFileSync(join(root, 'home/bridge.js'), 'utf8')
+
+// ------------------------------------------------------------ one scenario
+
+async function scenario(name) {
+ // A page: a window with postMessage → 'message' events whose source is the
+ // window itself, and a top. Node has btoa/atob and Uint8Array already.
+ const listeners = new Set()
+ const win = globalThis
+ win.window = win
+ win.top = name === 'subframe' ? {} : win
+ win.addEventListener = (t, fn) => { if (t === 'message') listeners.add(fn) }
+ win.removeEventListener = (t, fn) => { if (t === 'message') listeners.delete(fn) }
+ const dispatch = (data, source) => setTimeout(() => { for (const fn of [...listeners]) fn({ data, source }) }, 0)
+ win.postMessage = (data) => dispatch(data, win)
+
+ // The fake native host: Android's transport (JSON strings both ways), and
+ // the native contract — names allow-listed, bytes as base64, refusals as
+ // ok:false.
+ const kept = new Map()
+ const native = {
+ onmessage: null,
+ postMessage(json) {
+ const m = JSON.parse(json)
+ const reply = (ok, value) => setTimeout(() => native.onmessage({ data: JSON.stringify({ id: m.id, ok, value }) }), 0)
+ if (!String(m.op).startsWith('store.')) return reply(false, 'not this rig')
+ if (m.op !== 'store.list' && m.name !== 'recovery' && m.name !== 'memberkey') return reply(false, 'refused')
+ if (m.op === 'store.set' && m.b64.length > 4 * 1024 * 1024) return reply(false, 'too-large')
+ if (m.op === 'store.get') return reply(true, kept.has(m.name) ? kept.get(m.name) : null)
+ if (m.op === 'store.set') { kept.set(m.name, m.b64); return reply(true, null) }
+ if (m.op === 'store.list') return reply(true, JSON.stringify([...kept.keys()]))
+ if (m.op === 'store.delete') { kept.delete(m.name); return reply(true, null) }
+ return reply(false, 'unknown op')
+ },
+ }
+ win.__bentoTrayNative = native
+ if (name !== 'no-caps' && name !== 'identity-control') win.__bentoHostCaps = ['store']
+
+ vm.runInThisContext(BRIDGE, { filename: 'home/bridge.js' })
+
+ if (name.startsWith('identity-')) return identity(name, win, kept)
+
+ const { docStore } = await import(pathToFileURL(join(root, 'kernel/src/docstore.ts')).href)
+ // `wait` is how long silence must last to count as "no answer". Requests that
+ // expect one get a long wait, so a slow machine is never read as a refusal;
+ // only the cases that must get NO answer use the short one.
+ const ask = (data, source = win, wait = 300) => new Promise((res) => {
+ const fn = (ev) => { if (ev.data && ev.data.dir === 'res' && ev.data.id === data.id) { listeners.delete(fn); res(ev.data.result) } }
+ listeners.add(fn); dispatch(data, source)
+ setTimeout(() => { listeners.delete(fn); res('NO ANSWER') }, wait)
+ })
+ const out = { capsLeft: 'caps' in win && win.__bentoHostCaps !== undefined, host: win.__bentoHost ?? null }
+
+ if (name === 'no-caps' || name === 'subframe') {
+ out.store = docStore() === null ? 'none' : 'PRESENT'
+ out.raw = await ask({ __bento_tray__: true, dir: 'req', id: 'x1', op: 'store.list', payload: {} })
+ return out
+ }
+
+ const s = docStore()
+ out.store = s ? 'present' : 'none'
+ const big = new Uint8Array(1 << 20); for (let i = 0; i < big.length; i++) big[i] = (i * 31 + 7) & 0xff
+ out.set = await s.set('recovery', big)
+ const got = await s.get('recovery')
+ out.getIsU8 = got instanceof Uint8Array
+ out.getEqual = got && got.length === big.length && got.every((v, i) => v === big[i])
+ out.setKey = await s.set('memberkey', new TextEncoder().encode('{"docId":"d","pub":"P","priv":"K"}'))
+ out.list = (await s.list()).sort()
+ out.del = await s.delete('recovery')
+ out.afterDelete = await s.get('recovery')
+ out.unknownOp = await ask({ __bento_tray__: true, dir: 'req', id: 'x2', op: 'store.wipe', payload: {} }, win, 5000)
+ out.foreignName = await ask({ __bento_tray__: true, dir: 'req', id: 'x3', op: 'store.get', payload: { name: 'evil' } }, win, 5000)
+ out.otherSource = await ask({ __bento_tray__: true, dir: 'req', id: 'x4', op: 'store.list', payload: {} }, {})
+ out.tooLarge = await s.set('recovery', new Uint8Array(4 * 1024 * 1024))
+ out.tooLargeRaw = await ask({ __bento_tray__: true, dir: 'req', id: 'x5', op: 'store.set', payload: { name: 'recovery', bytes: new Uint8Array(4 * 1024 * 1024) } }, win, 15000)
+ out.hostWritable = (() => { try { win.__bentoHost = { ops: [] }; return win.__bentoHost.ops.length === 0 } catch (_) { return false } })()
+ return out
+}
+
+// The kernel's REAL member-key path (kernel/src/sync/online.ts deviceIdentity)
+// through the real bridge. This is the step that takes every existing Android
+// member key out of web storage: an identity already in localStorage is ADOPTED
+// (same keys) with its private half moved into the host store, and a new one is
+// minted straight into the store. Without the capability, nothing moves — the
+// control that shows the probe can tell the difference.
+async function identity(name, win, kept) {
+ const ls = new Map()
+ win.localStorage = { getItem: (k) => ls.get(k) ?? null, setItem: (k, v) => ls.set(k, String(v)), removeItem: (k) => ls.delete(k),
+ key: (i) => [...ls.keys()][i] ?? null, get length() { return ls.size } }
+ win.location = new URL('https://0123456789abcdef01234567.bento-tray.invalid/index.html')
+ // Enough document for the kernel modules this import chain loads. save.ts runs
+ // its launchQueue consumer at import (the real bridge defines launchQueue here),
+ // and with no #bento-doc block it reads nothing and adopts nothing.
+ win.document = { visibilityState: 'visible', addEventListener() {}, removeEventListener() {},
+ getElementById: () => null, querySelector: () => null, querySelectorAll: () => [] }
+ const { register } = await import('node:module')
+ register(pathToFileURL(join(root, 'scripts/lib/ts-resolve-hooks.mjs')).href, import.meta.url)
+ const { configureApp } = await import(pathToFileURL(join(root, 'kernel/src/app.ts')).href)
+ configureApp({ appId: 'bento-rig', appName: 'Rig', manifestUrl: 'https://example.invalid/m.json' })
+ const { deviceIdentity } = await import(pathToFileURL(join(root, 'kernel/src/sync/online.ts')).href)
+
+ const docId = 'doc-k3x9q2ab'
+ const existing = { pub: 'EXISTING-PUB', priv: 'EXISTING-PRIV' }
+ if (name !== 'identity-mint') ls.set(`bento-member-${docId}`, JSON.stringify(existing))
+ const id = await deviceIdentity(docId)
+ const held = kept.has('memberkey') ? JSON.parse(Buffer.from(kept.get('memberkey'), 'base64').toString()) : null
+ return { id, local: JSON.parse(ls.get(`bento-member-${docId}`) ?? 'null'), held, host: win.__bentoHost ?? null }
+}
+
+// ------------------------------------------------------------ the checks
+
+if (process.argv[2] === '--scenario') {
+ scenario(process.argv[3]).then((r) => { process.stdout.write(JSON.stringify(r)); process.exit(0) },
+ (e) => { process.stdout.write(JSON.stringify({ error: String(e && e.stack || e) })); process.exit(0) })
+} else {
+ let pass = 0, fail = 0
+ const ok = (c, m) => { console.log(` ${c ? 'ok ' : 'FAIL'} ${m}`); c ? pass++ : fail++ }
+ const run = (n) => {
+ const r = spawnSync(process.execPath, ['--no-warnings', fileURLToPath(import.meta.url), '--scenario', n], { encoding: 'utf8' })
+ try { return JSON.parse(r.stdout) } catch (_) { return { error: r.stdout + r.stderr } }
+ }
+
+ const none = run('no-caps')
+ if (none.error) console.log(none.error)
+ ok(none.host === null, 'no declared capability: no window.__bentoHost')
+ ok(none.store === 'none', 'no declared capability: the kernel finds no store and keeps its own storage')
+ ok(none.raw === 'NO ANSWER', 'no declared capability: a store request gets no relay at all')
+
+ const sub = run('subframe')
+ ok(sub.host === null && sub.store === 'none', 'in a subframe: no store, even with the capability declared')
+ ok(sub.raw === 'NO ANSWER', 'in a subframe: a store request gets no relay')
+
+ const r = run('caps')
+ if (r.error) console.log(r.error)
+ ok(r.capsLeft === false, 'the capability declaration is consumed, not left on the page')
+ ok(Array.isArray(r.host?.ops) && r.host.ops.includes('store'), 'declared capability: __bentoHost.ops includes store')
+ ok(r.hostWritable === false, '__bentoHost cannot be replaced by the page')
+ ok(r.store === 'present', 'declared capability: the kernel uses the host store')
+ ok(r.set === 'stored', 'a 1 MiB recovery copy is stored')
+ ok(r.getIsU8 === true, 'a read returns a Uint8Array the kernel accepts (built in the page realm)')
+ ok(r.getEqual === true, 'the bytes come back identical')
+ ok(r.setKey === 'stored', 'the member key is stored')
+ ok(JSON.stringify(r.list) === JSON.stringify(['memberkey', 'recovery']), 'list names both entries')
+ ok(r.del === true && r.afterDelete === null, 'delete removes an entry; a later read finds nothing')
+ ok(r.unknownOp?.ok === false && /unknown op/.test(r.unknownOp.reason), 'an unknown store op is refused by the relay')
+ ok(r.foreignName?.ok === false && r.foreignName.reason === 'refused', "a name outside recovery/memberkey is refused, reason 'refused'")
+ ok(r.tooLarge === 'refused', 'a host over-cap refusal reaches the kernel as a refused write, not a hang')
+ ok(r.tooLargeRaw?.ok === false && r.tooLargeRaw.reason === 'too-large', "the host's 'too-large' reason passes through the relay unchanged")
+ ok(r.otherSource === 'NO ANSWER', 'a request whose source is not the page window is ignored')
+
+ const adopt = run('identity-adopt')
+ if (adopt.error) console.log(adopt.error)
+ ok(adopt.id?.pub === 'EXISTING-PUB' && adopt.id?.priv === 'EXISTING-PRIV', 'deviceIdentity ADOPTS an existing member key unchanged (no re-join, same identity)')
+ ok(adopt.held?.priv === 'EXISTING-PRIV' && adopt.held?.docId === 'doc-k3x9q2ab', "the adopted key's private half moves into the host store, under this document")
+ ok(adopt.local && adopt.local.pub === 'EXISTING-PUB' && !('priv' in adopt.local), 'localStorage keeps only the public key after adoption')
+
+ const mint = run('identity-mint')
+ if (mint.error) console.log(mint.error)
+ ok(typeof mint.held?.priv === 'string' && mint.held.priv.length > 20 && mint.held.pub === mint.id?.pub, 'a freshly minted member key goes into the host store')
+ ok(mint.local && mint.local.pub === mint.id?.pub && !('priv' in mint.local), 'a fresh mint never writes the private half to localStorage')
+
+ const ctl = run('identity-control')
+ if (ctl.error) console.log(ctl.error)
+ ok(ctl.host === null && ctl.held === null && ctl.local?.priv === 'EXISTING-PRIV', 'control, no capability: the private key stays in localStorage (so the cases above discriminate)')
+
+ console.log(`\n${pass}/${pass + fail} checks passed`)
+ process.exit(fail ? 1 : 0)
+}
diff --git a/scripts/test-home-inspector.mjs b/scripts/test-home-inspector.mjs
new file mode 100644
index 00000000..68c9848b
--- /dev/null
+++ b/scripts/test-home-inspector.mjs
@@ -0,0 +1,138 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The Android host's legacy-origin inspector, run as it ships: the script is
+// extracted from DocumentOrigin.kt (INSPECTOR_HTML) and executed against
+// kernel-shaped storage.
+//
+// node scripts/test-home-inspector.mjs
+//
+// Why it matters: before adopting an old per-path origin, the host asks this
+// script which documents own data there. A docId it misses lets a different
+// document inherit the old one's recovery copy and member key; data it cannot
+// attribute must REFUSE adoption. The JVM rig covers the decision; only this
+// covers the script.
+//
+// IndexedDB is a small in-memory fake implementing exactly what the script
+// uses (databases, open, objectStoreNames, transaction/objectStore,
+// openKeyCursor on stores and indexes, count, indexNames). The same script was
+// also run once against real Chromium storage when this rig was written.
+
+import { readFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+const kt = readFileSync(join(root, 'home/android/app/src/main/java/page/bento/home/DocumentOrigin.kt'), 'utf8')
+const html = kt.slice(kt.indexOf('val INSPECTOR_HTML = """') + 'val INSPECTOR_HTML = """'.length)
+const script = html.slice(html.indexOf('<script>') + 8, html.indexOf('</script>')).replaceAll("${'$'}", '$')
+
+// ------------------------------------------------------------ a fake origin
+
+function origin({ dbs = {}, local = {}, noList = false } = {}) {
+ // dbs: { name: { store: { records: [[key, value]], indexes: { idx: field } } } }
+ const opened = []
+ const later = (fn) => setTimeout(fn, 0)
+ const request = (result) => { const r = {}; later(() => { r.result = typeof result === 'function' ? result() : result; r.onsuccess && r.onsuccess() }); return r }
+ const cursorOver = (keys) => {
+ const r = {}; let i = 0
+ const step = () => later(() => {
+ r.result = i < keys.length ? { primaryKey: keys[i][0], key: keys[i][1], continue: () => { i++; step() } } : null
+ r.onsuccess && r.onsuccess()
+ })
+ step(); return r
+ }
+ const indexedDB = {
+ open(name) {
+ opened.push(name)
+ if (!dbs[name]) throw new Error(`opened a database that was not listed: ${name}`)
+ const stores = dbs[name]
+ return request({
+ objectStoreNames: Object.keys(stores),
+ transaction: (st) => ({ objectStore: () => {
+ const s = stores[st]; const recs = s.records || []
+ return {
+ indexNames: { contains: (n) => !!(s.indexes || {})[n] },
+ openKeyCursor: () => cursorOver(recs.map(([k]) => [k, k])),
+ count: () => request(recs.length),
+ index: (n) => ({ openKeyCursor: () => cursorOver(recs.map(([k, v]) => [k, v[s.indexes[n]]]).sort((a, b) => String(a[1]).localeCompare(String(b[1])))) }),
+ }
+ } }),
+ close() {},
+ })
+ },
+ }
+ if (!noList) indexedDB.databases = async () => Object.keys(dbs).map((name) => ({ name, version: 1 }))
+ const keys = Object.keys(local)
+ const localStorage = { get length() { return keys.length }, key: (i) => keys[i] }
+ return { indexedDB, localStorage, opened }
+}
+
+async function inspect(env) {
+ let report = null
+ const __bentoInspect = { postMessage: (s) => { report = JSON.parse(s) } }
+ const run = new Function('indexedDB', 'localStorage', '__bentoInspect', script)
+ run(env.indexedDB, env.localStorage, __bentoInspect)
+ for (let i = 0; i < 200 && !report; i++) await new Promise((r) => setTimeout(r, 1))
+ return { ...report, docIds: (report?.docIds || []).sort(), opened: env.opened }
+}
+
+// ------------------------------------------------------------ the checks
+
+let pass = 0, fail = 0
+const ok = (c, m) => { console.log(` ${c ? 'ok ' : 'FAIL'} ${m}`); c ? pass++ : fail++ }
+const A = '0176ab3a-fd86-4cd6-9d1a-5339e0a3bab4', S = 'doc-k3x9q2ab', D = 'd-4fz8w1qplmz9k2', B = 'doc-zzzzzzzz'
+const autosave = (...owners) => ({
+ recovery: { records: owners.map((o) => [o, { docId: o }]) },
+ versions: { records: owners.map((o, i) => [i + 1, { docId: o }]), indexes: { docId: 'docId' } },
+})
+
+ok(script.includes('openKeyCursor') && !script.includes('getAll'), 'the shipped script reads keys with cursors, never record bodies')
+
+let r = await inspect(origin())
+ok(r.docIds.length === 0 && r.unattributed === false, 'an empty origin: nothing owned, nothing unattributable (adoptable)')
+
+for (const [app, id] of [['slides', A], ['spaces', S], ['dash', D], ['type', A]]) {
+ r = await inspect(origin({ dbs: { [`bento-${app}-autosave`]: autosave(id) } }))
+ ok(JSON.stringify(r.docIds) === JSON.stringify([id]) && r.unattributed === false, `bento-${app}-autosave: its records are attributed to ${id.slice(0, 12)}`)
+}
+
+r = await inspect(origin({ dbs: { 'bento-autosave': autosave(A) } }))
+ok(JSON.stringify(r.docIds) === JSON.stringify([A]), 'the legacy shared bento-autosave is attributed too')
+
+r = await inspect(origin({ dbs: { 'bento-slides-autosave': { recovery: { records: [] }, versions: { records: [[1, { docId: B }]], indexes: { docId: 'docId' } } } } }))
+ok(r.docIds.includes(B), 'a version record alone (no recovery copy) still names its owner, through the docId index')
+
+r = await inspect(origin({ dbs: { 'bento-handles': { handles: { records: [[A, {}]] } } } }))
+ok(JSON.stringify(r.docIds) === JSON.stringify([A]) && r.unattributed === false, 'bento-handles is attributed by its docId keys')
+
+r = await inspect(origin({ local: { [`bento-member-${S}`]: '{}', 'bento-lang': 'en' } }))
+ok(JSON.stringify(r.docIds) === JSON.stringify([S]), 'a member key names its document; a viewer preference is not data')
+
+r = await inspect(origin({ dbs: { 'bento-blobcache': { blobs: { records: [['h1', new Uint8Array(1)]] } } } }))
+ok(r.unattributed === true, 'bento-blobcache with records refuses (it caches live-session media in plaintext)')
+
+r = await inspect(origin({ dbs: { 'bento-blobcache': { blobs: { records: [] } } } }))
+ok(r.unattributed === false, 'an EMPTY bento-blobcache does not refuse')
+
+r = await inspect(origin({ dbs: { 'someone-else': { kv: { records: [['k', 1]] } } } }))
+ok(r.unattributed === true, 'an unknown database with records refuses')
+
+r = await inspect(origin({ dbs: { 'bento-slides-autosave': { extra: { records: [['x', 1]] }, ...autosave(A) } } }))
+ok(r.unattributed === true, 'an unexpected store with records inside an autosave database refuses')
+
+r = await inspect(origin({ dbs: { 'bento-handles': { handles: { records: [[42, {}]] } } } }))
+ok(r.unattributed === true, 'a non-string key cannot be attributed, so it refuses')
+
+r = await inspect(origin({ noList: true, dbs: { 'bento-slides-autosave': autosave(A) } }))
+ok(r.unattributed === true && r.opened.length === 0, 'no indexedDB.databases(): unattributable, and nothing is opened')
+
+r = await inspect(origin({ dbs: { 'bento-slides-autosave': autosave(A, B) } }))
+ok(r.docIds.includes(A) && r.docIds.includes(B), 'two documents in one origin are both reported (the host then refuses adoption)')
+
+r = await inspect(origin({ dbs: { 'bento-slides-autosave': autosave(A) } }))
+ok(JSON.stringify(r.opened) === JSON.stringify(['bento-slides-autosave']), 'only listed databases are opened, so looking creates none')
+
+console.log(`\n${pass}/${pass + fail} checks passed`)
+process.exit(fail ? 1 : 0)