Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

home/webext: DocStore extension backend — sidecar data in the extension's origin, partitioned by path (#587)

nyblnet12f4428b45b8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index cdb9cf45..2e8d83e4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -763,6 +763,15 @@ jobs:
# document that asked; a beside-name is never a path or the original.
run: node scripts/test-webext-saveas.ts
+ - name: WebExtension DocStore rig
+ # A document's crash recovery and member key live in the extension's
+ # origin, partitioned by the file path the browser reports. One document
+ # must never reach another's entries, a payload must never name a
+ # partition, and a moved file's recovery follows it only when the old
+ # path is gone (seen through a grant) and the content hash matches; the
+ # member key never follows.
+ run: node scripts/test-webext-store.ts
+
- name: WebExtension localisation rig
# Every failure mode of a message catalogue is silent: a key the code
# uses but English lacks renders as the key name, a locale missing a key
diff --git a/home/webext/src/background.js b/home/webext/src/background.js
index 164f225c..0d6ff097 100644
--- a/home/webext/src/background.js
+++ b/home/webext/src/background.js
@@ -39,7 +39,8 @@ import {
modelsKey, builtinContext, models as listRoutes, select as selectRoute, runTurn,
describe as describeAssistant, check as checkAssistant, run as runAssistant,
} from './assistant.js'
-import { learnPrefix, noteOpened } from './db.js'
+import { learnPrefix, noteOpened, prefixes as knownPrefixes } from './db.js'
+import * as docstore from './store.js'
import { resolveFileGrant, dropFileGrant, declined, downloadsDir, downloadsRelative, writeViaDownloads, downloadsUnusable, setDownloadsUnusable, defaultDeps as defaultFileGrantDeps } from './filegrant.js'
import { recentOpened } from './db.js'
import * as saveas from './saveas.js'
@@ -326,6 +327,77 @@ export async function write(sender, text, deps = {}) {
}
}
+// ---------------------------------------------------------------- DocStore
+//
+// The document's sidecar data, in this origin (store.js). The PATH is the
+// sender's, derived here; nothing in the payload can name another one.
+
+const STORE_OPS = {
+ 'store.get': docstore.get, 'store.chunk': docstore.chunk, 'store.put': docstore.put,
+ 'store.commit': docstore.commit, 'store.set': docstore.set, 'store.list': docstore.list,
+ 'store.delete': docstore.remove,
+}
+let storeDeps = null
+const hex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('')
+export function docstoreDeps() {
+ if (!storeDeps) {
+ storeDeps = {
+ db: docstore.idbAdapter(),
+ now: () => Date.now(),
+ txid: () => crypto.randomUUID(),
+ sha256: async (bytes) => hex(await crypto.subtle.digest('SHA-256', bytes)),
+ // the extension reads the file ITSELF (it has file access): the page's
+ // account of its own content is never what a carry is decided on
+ fileBlockHash: async (path) => {
+ const r = await fetch(`file://${path.split('/').map(encodeURIComponent).join('/')}`)
+ return r.ok ? docstore.blockHash(await r.text(), storeDeps) : null
+ },
+ // "gone" only as a grant whose location is proven sees it
+ gone: async (path) => {
+ const at = await knownPrefixes()
+ const grants = (await getGrants()).map((dir) => ({ dir, prefix: at[dir.name] })).filter((g) => g.prefix)
+ return docstore.goneVia(path, grants)
+ },
+ }
+ }
+ return storeDeps
+}
+
+/**
+ * A moved document's recovery may follow it (store.js `carry`). Decided once
+ * per path per worker lifetime, and BEFORE the page's first store op is
+ * answered, so the page never reads an empty partition that is about to fill.
+ */
+const carriedBy = new WeakMap() // deps → Map(path → Promise): one store, one decision per path
+export function ensureCarried(path, deps = docstoreDeps()) {
+ if (!path) return Promise.resolve(null)
+ if (!carriedBy.has(deps)) carriedBy.set(deps, new Map())
+ const carried = carriedBy.get(deps)
+ if (!carried.has(path)) {
+ carried.set(path, docstore.carry(path, deps).then((r) => {
+ if (r?.carried) console.info('[bento/home] recovery followed a moved document from', r.carried, 'to', path)
+ return r
+ }, () => null))
+ }
+ return carried.get(path)
+}
+
+export async function storeOp(op, sender, payload, deps = docstoreDeps()) {
+ const fn = STORE_OPS[op]
+ if (!fn) return { ok: false, reason: 'unknown op' }
+ // Top frame only, here too: the content scripts never run in a sub-frame,
+ // but a partition is too valuable to rest on that alone.
+ const path = sender?.frameId === 0 ? pathFromSender(sender) : null
+ if (path) await ensureCarried(path, deps)
+ return fn(path, payload ?? {}, deps)
+}
+
+/** After the extension wrote the sender's file: which document it now holds (store.js recordSaved). */
+function noteSaved(sender, text) {
+ const path = sender?.frameId === 0 ? pathFromSender(sender) : null
+ if (path) void docstore.recordSaved(path, text, docstoreDeps()).catch(() => {})
+}
+
// ---------------------------------------------------------------- assistant
//
// The chat's extension half. Rules and rationale in assistant.js; this is the
@@ -744,7 +816,7 @@ if (typeof chrome !== 'undefined' && chrome.runtime?.onMessage) {
: msg?.op === 'filegrant.answered' ? Promise.resolve(offerAnswered(sender, msg))
: msg?.op === 'save.status' ? saveStatus(sender, msg.url)
: msg?.op === 'save.rebadge' ? (async () => { const tabs = await chrome.tabs.query({ url: 'file:///*.bento.html' }).catch(() => []); for (const tb of tabs) await badgeTab(tb.id, { url: tb.url, frameId: 0, tab: tb }); return { ok: true } })()
- : msg?.op === 'write' ? write(sender, msg.payload?.text ?? '')
+ : msg?.op === 'write' ? write(sender, msg.payload?.text ?? '').then((r) => { if (r?.ok) noteSaved(sender, msg.payload?.text ?? ''); return r })
: msg?.op === 'backup' ? backup(sender, msg.payload?.text ?? '', msg.payload?.name)
: msg?.op === 'assistant.consent' ? recordConsent(sender, msg)
: typeof msg?.op === 'string' && msg.op.startsWith('assistant.') ? assistantOp(msg.op, sender, msg.payload)
@@ -752,6 +824,7 @@ if (typeof chrome !== 'undefined' && chrome.runtime?.onMessage) {
: msg?.op === 'saveas.write' ? saveas.write(topPath(sender), msg.payload, saveasDeps(sender))
: msg?.op === 'saveas.answered' ? Promise.resolve(saveasAnswered(sender, msg))
: msg?.op === 'saveas.drop' ? saveas.drop(topPath(sender), msg.payload, saveasDeps(sender))
+ : typeof msg?.op === 'string' && msg.op.startsWith('store.') ? storeOp(msg.op, sender, msg.payload)
: Promise.resolve({ ok: false, reason: 'unknown op' })
run.then((r) => {
sendResponse(r)
@@ -784,6 +857,9 @@ if (typeof chrome !== 'undefined' && chrome.runtime?.onMessage) {
// asked — `checkForUpdate` returns immediately for them.
chrome.runtime.onStartup?.addListener(() => void checkForUpdate())
chrome.runtime.onStartup?.addListener(() => { void saveas.gc(saveasDeps(null)).catch(() => {}) })
+ // DocStore's sweep: partitions of files that are gone or untouched for a
+ // month, and transfers that never committed. Once per browser session.
+ chrome.runtime.onStartup?.addListener(() => { void docstore.gc(docstoreDeps()).catch(() => {}) })
chrome.runtime.onInstalled?.addListener(() => void checkForUpdate())
void reportLapsed()
diff --git a/home/webext/src/home.js b/home/webext/src/home.js
index c7347b0b..6b85586f 100644
--- a/home/webext/src/home.js
+++ b/home/webext/src/home.js
@@ -1796,6 +1796,10 @@ document.addEventListener('visibilitychange', () => {
// Before ANY painting: a saved language choice has to be in hand, or the page
// renders in the browser's language and visibly re-renders a moment later.
await initI18n()
+// The extension's storage holds documents' crash recovery (store.js): ask
+// the browser not to evict it under disk pressure. Best effort — the answer
+// is the browser's, and nothing depends on it.
+try { void navigator.storage?.persist?.() } catch { /* not offered */ }
localize()
// Read BEFORE the first grid render, so someone who chose list mode never
diff --git a/home/webext/src/page-bridge.js b/home/webext/src/page-bridge.js
index 08181cbc..915c57e7 100644
--- a/home/webext/src/page-bridge.js
+++ b/home/webext/src/page-bridge.js
@@ -146,7 +146,7 @@
* directions where "are you at least version N" does not.
*/
Object.defineProperty(window, '__bentoHost', {
- value: Object.freeze({ name: 'home/webext', ops: Object.freeze(['claim', 'write', 'backup', 'assistant', 'saveas']) }),
+ value: Object.freeze({ name: 'home/webext', ops: Object.freeze(['claim', 'write', 'backup', 'assistant', 'saveas', 'store']) }),
writable: false, configurable: false, enumerable: false,
})
diff --git a/home/webext/src/relay.js b/home/webext/src/relay.js
index b24cdfd0..ed1ba5a0 100644
--- a/home/webext/src/relay.js
+++ b/home/webext/src/relay.js
@@ -95,6 +95,68 @@ chrome.runtime.sendMessage({ op: 'hello' }).catch(() => {
/* worker asleep, extension reloading, page outside every grant — all fine */
})
+// ---------------------------------------------------------------- DocStore
+//
+// The page speaks BYTES (store.get/set/list/delete — the kernel's DocStore
+// interface); runtime messaging speaks JSON. So this is the one place bytes
+// become base64 and back, and a large value is cut into chunks under one
+// transaction id and committed in one step (store.js). Encoding, not logic:
+// every decision — which partition, what is allowed — is the worker's.
+const STORE_CHUNK = 3 * 1024 * 1024
+const STORE_MAX = 64 * 1024 * 1024
+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 s = atob(b64)
+ const u8 = new Uint8Array(s.length)
+ for (let i = 0; i < s.length; i++) u8[i] = s.charCodeAt(i)
+ return u8
+}
+const ask = (op, payload) => chrome.runtime.sendMessage({ op, payload })
+
+async function storeRequest(op, payload) {
+ if (op === 'store.set') {
+ const bytes = payload?.bytes
+ if (!(bytes instanceof Uint8Array)) return { ok: false, reason: 'bytes must be a Uint8Array' }
+ if (bytes.length > STORE_MAX) return { ok: false, reason: 'too large' }
+ if (bytes.length <= STORE_CHUNK) return ask('store.set', { name: payload.name, data: toB64(bytes) })
+ const tx = crypto.randomUUID()
+ let n = 0
+ for (let i = 0; i < bytes.length; i += STORE_CHUNK, n++) {
+ const r = await ask('store.put', { name: payload.name, tx, i: n, data: toB64(bytes.subarray(i, i + STORE_CHUNK)) })
+ if (!r?.ok) return r
+ }
+ return ask('store.commit', { name: payload.name, tx, n })
+ }
+ if (op === 'store.get') {
+ // a value replaced mid-read is read again from the top, once
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const m = await ask('store.get', { name: payload?.name })
+ if (!m?.ok) return m
+ if (!m.found) return { ok: true, bytes: null }
+ if (typeof m.inline === 'string') return { ok: true, bytes: fromB64(m.inline) }
+ const out = new Uint8Array(m.size)
+ let at = 0
+ let gone = false
+ for (let i = 0; i < m.n; i++) {
+ const c = await ask('store.chunk', { name: payload.name, tx: m.tx, i })
+ if (!c?.ok) { if (c?.reason === 'gone') { gone = true; break } return c }
+ const part = fromB64(c.data)
+ out.set(part, at)
+ at += part.length
+ }
+ if (!gone) return { ok: true, bytes: out }
+ }
+ return { ok: false, reason: 'changed while reading' }
+ }
+ if (op === 'store.list') return ask('store.list', { prefix: payload?.prefix ?? '' })
+ if (op === 'store.delete') return ask('store.delete', { name: payload?.name })
+ return { ok: false, reason: 'unknown op' }
+}
+
window.addEventListener('message', async (ev) => {
const d = ev.data
// Same-window only: `ev.source !== window` rejects anything posted in from a
@@ -102,6 +164,13 @@ window.addEventListener('message', async (ev) => {
// another document.
if (ev.source !== window || !d || d[CH] !== true || d.dir !== 'req') return
+ if (typeof d.op === 'string' && d.op.startsWith('store.')) {
+ let result
+ try { result = await storeRequest(d.op, d.payload) } catch (e) { result = { ok: false, reason: String(e?.message || e) } }
+ window.postMessage({ [CH]: true, dir: 'res', id: d.id, result }, '*')
+ return
+ }
+
if (typeof d.op === 'string' && d.op.startsWith('assistant.')) {
// The page mints these ids with a prefix of its own; anything else is not
// the page's assistant client and gets nothing.
diff --git a/home/webext/src/store.js b/home/webext/src/store.js
new file mode 100644
index 00000000..fac8f12a
--- /dev/null
+++ b/home/webext/src/store.js
@@ -0,0 +1,376 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// DocStore, the extension backend: what a document keeps beside itself —
+// its CRASH RECOVERY and its collab MEMBER KEY, nothing else — stored in THIS
+// extension's origin rather than the page's. (Version history lives in the
+// file itself: maintainer ruling, 2026-10-10.)
+//
+// WHY HERE. Every document opened from disk shares one storage origin
+// (docs/DECISIONS.md, 2026-10-04), so a page-side store is a store every
+// local HTML file can read. The extension has an origin of its own, and the
+// browser tells it which file is asking (`sender.url`, stamped, not
+// forgeable by the page). So each document gets a PARTITION keyed by its
+// absolute path, derived here from the sender and never from the payload,
+// and the page can only ever reach its own. A document id the page supplies
+// is never a key: it is page data, and a hostile local file could claim
+// another deck's.
+//
+// The kernel's DocStore interface (agreed 2026-09-26) is four operations,
+// bytes both ways: get(name) → bytes|null, set(name, bytes), list(prefix) →
+// names, delete(name). The names are exactly NAMES; values are opaque —
+// stored blindly, never parsed. No encryption on this path: the partition is
+// the isolation.
+//
+// TRANSPORT. Runtime messaging is JSON, so bytes cross the relay↔worker hop
+// as base64, and a value over CHUNK bytes travels as numbered chunks under a
+// transaction id, committed in one step: a reader sees the old value or the
+// new one, never half. Every message re-derives the partition and holds no
+// state between messages (the worker is evicted at will); chunks of a
+// transfer that never committed are swept by `gc`.
+//
+// A MOVED FILE (security ruling 2026-10-10, handoffs/…docstore-carryover).
+// The partition is the path, so a moved or renamed document opens with an
+// empty one. Its recovery may FOLLOW it — once — and only when all of this
+// holds, every part checked by the extension, none taken from the page:
+// · the new file's #bento-doc block hashes to the hash recorded when the
+// extension last WROTE the old file (`recordSaved`, at every save it
+// performs) — the same saved document, moved; a different file, or one
+// edited elsewhere since, does not match and nothing carries;
+// · the old path is GONE, as seen through the extension's own folder grant
+// (`deps.gone`): where the old folder is not granted, or the answer is
+// anything but a definite not-found, nothing carries;
+// · the recovery was written in the last CARRY_DAYS;
+// · exactly one old partition qualifies.
+// It MOVES (re-keyed, the old entry deleted), so two files can never both
+// claim it. The MEMBER KEY NEVER CARRIES: a moved honest file re-enrols
+// through its own invite chain, and nothing here can tell a genuine file from
+// one that copied its docId. Whatever carries reaches the page through the
+// kernel's restore gate like any other recovery.
+//
+// RETENTION. `recovery` and `memberkey` are single entries by construction.
+// A partition untouched for MAX_AGE_DAYS is dropped. One whose file is gone is
+// kept only while it could still carry (recovery younger than CARRY_DAYS),
+// then dropped; "gone" is the grant's answer, never a guess.
+//
+// Pure: the IndexedDB adapter, the hash, the file reader and the grant walk
+// come in as `deps`, so scripts/test-webext-store.ts drives the real code.
+
+/** Bytes per chunk on the relay↔worker hop (before base64). */
+export const CHUNK = 3 * 1024 * 1024
+/** Largest value one name may hold. */
+export const MAX_VALUE = 64 * 1024 * 1024
+/** The only names a document may keep here. */
+export const NAMES = Object.freeze(['recovery', 'memberkey'])
+/** A partition untouched this long is dropped. */
+export const MAX_AGE_DAYS = 30
+/** A recovery older than this never follows a moved file. */
+export const CARRY_DAYS = 7
+const DAY = 24 * 3600 * 1000
+/** A transfer that never committed is swept after this long. */
+const STALE_TX_MS = 3600 * 1000
+
+/** Names: exactly NAMES. Prefixes for list: any string, matched against NAMES. */
+export const validName = (n) => typeof n === 'string' && NAMES.includes(n)
+export const validPrefix = (p) => typeof p === 'string' && p.length <= 200 && !p.includes('\u0000')
+export const validTx = (t) => typeof t === 'string' && /^[A-Za-z0-9-]{8,64}$/.test(t)
+
+const S = '\u0000'
+const mKey = (path, name) => `m${S}${path}${S}${name}`
+const cKey = (path, name, tx, i) => `c${S}${path}${S}${name}${S}${tx}${S}${String(i).padStart(6, '0')}`
+const cPrefix = (path, name, tx) => `c${S}${path}${S}${name}${S}${tx ?? ''}`
+const END = '￿'
+
+export 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)
+}
+export const fromB64 = (b64) => {
+ const s = atob(b64)
+ const u8 = new Uint8Array(s.length)
+ for (let i = 0; i < s.length; i++) u8[i] = s.charCodeAt(i)
+ return u8
+}
+const b64Len = (b64) => Math.floor((b64.length * 3) / 4) - (b64.endsWith('==') ? 2 : b64.endsWith('=') ? 1 : 0)
+
+// ---------------------------------------------------------------- the ops
+// Each takes the PATH the worker derived from the sender, never one from
+// the page. A null path is not a document: every op refuses it.
+
+export async function get(path, p, deps) {
+ if (!path) return { ok: false, reason: 'not a document' }
+ if (!validName(p?.name)) return { ok: false, reason: 'bad name' }
+ const m = await deps.db.get(mKey(path, p.name))
+ if (!m) return { ok: true, found: false }
+ if (m.n === 1) {
+ const c = await deps.db.get(cKey(path, p.name, m.tx, 0))
+ if (c == null) return { ok: false, reason: 'missing chunk' }
+ return { ok: true, found: true, size: m.size, inline: c }
+ }
+ return { ok: true, found: true, size: m.size, tx: m.tx, n: m.n }
+}
+
+export async function chunk(path, p, deps) {
+ if (!path) return { ok: false, reason: 'not a document' }
+ if (!validName(p?.name) || !validTx(p?.tx) || !Number.isInteger(p?.i) || p.i < 0) return { ok: false, reason: 'bad request' }
+ const m = await deps.db.get(mKey(path, p.name))
+ if (!m || m.tx !== p.tx || p.i >= m.n) return { ok: false, reason: 'gone' } // replaced mid-read: the caller starts over
+ const c = await deps.db.get(cKey(path, p.name, p.tx, p.i))
+ return c == null ? { ok: false, reason: 'missing chunk' } : { ok: true, data: c }
+}
+
+/** One chunk of a transfer. Nothing is visible until `commit`. */
+export async function put(path, p, deps) {
+ if (!path) return { ok: false, reason: 'not a document' }
+ if (!validName(p?.name) || !validTx(p?.tx) || !Number.isInteger(p?.i) || p.i < 0 || typeof p?.data !== 'string') return { ok: false, reason: 'bad request' }
+ if (b64Len(p.data) > CHUNK) return { ok: false, reason: 'chunk too large' }
+ if (p.i * CHUNK >= MAX_VALUE) return { ok: false, reason: 'too large' }
+ await deps.db.put(cKey(path, p.name, p.tx, p.i), p.data)
+ await deps.db.put(`t${S}${path}${S}${p.name}${S}${p.tx}`, { at: deps.now() }) // for the stale sweep
+ return { ok: true }
+}
+
+/** Make a transfer the value of `name`: every chunk present, then one manifest write. */
+export async function commit(path, p, deps) {
+ if (!path) return { ok: false, reason: 'not a document' }
+ if (!validName(p?.name) || !validTx(p?.tx) || !Number.isInteger(p?.n) || p.n < 1) return { ok: false, reason: 'bad request' }
+ let size = 0
+ for (let i = 0; i < p.n; i++) {
+ const c = await deps.db.get(cKey(path, p.name, p.tx, i))
+ if (c == null) return { ok: false, reason: 'incomplete' }
+ size += b64Len(c)
+ }
+ if (size > MAX_VALUE) { await dropTx(path, p.name, p.tx, deps); return { ok: false, reason: 'too large' } }
+ const old = await deps.db.get(mKey(path, p.name))
+ await deps.db.put(mKey(path, p.name), { tx: p.tx, n: p.n, size, at: deps.now() })
+ await deps.db.del(`t${S}${path}${S}${p.name}${S}${p.tx}`)
+ if (old && old.tx !== p.tx) await dropTx(path, p.name, old.tx, deps)
+ return { ok: true }
+}
+
+/** The small case in one message: a single chunk, committed. */
+export async function set(path, p, deps) {
+ if (!path) return { ok: false, reason: 'not a document' }
+ if (!validName(p?.name) || typeof p?.data !== 'string') return { ok: false, reason: 'bad request' }
+ if (b64Len(p.data) > CHUNK) return { ok: false, reason: 'chunk too large' }
+ const tx = deps.txid()
+ const r = await put(path, { name: p.name, tx, i: 0, data: p.data }, deps)
+ return r.ok ? commit(path, { name: p.name, tx, n: 1 }, deps) : r
+}
+
+export async function list(path, p, deps) {
+ if (!path) return { ok: false, reason: 'not a document' }
+ const prefix = p?.prefix ?? ''
+ if (!validPrefix(prefix)) return { ok: false, reason: 'bad prefix' }
+ const lo = mKey(path, prefix)
+ const names = (await deps.db.range(lo, `${lo}${END}`)).map(([k]) => k.slice(mKey(path, '').length))
+ return { ok: true, names: names.sort() }
+}
+
+export async function remove(path, p, deps) {
+ if (!path) return { ok: false, reason: 'not a document' }
+ if (!validName(p?.name)) return { ok: false, reason: 'bad name' }
+ const m = await deps.db.get(mKey(path, p.name))
+ await deps.db.del(mKey(path, p.name))
+ if (m) await dropTx(path, p.name, m.tx, deps)
+ return { ok: true }
+}
+
+async function dropTx(path, name, tx, deps) {
+ const lo = cPrefix(path, name, tx)
+ for (const [k] of await deps.db.range(`${lo}${S}`, `${lo}${S}${END}`)) await deps.db.del(k)
+ await deps.db.del(`t${S}${path}${S}${name}${S}${tx}`)
+}
+
+// ---------------------------------------------------------------- moved files
+
+const SCRIPT_CLOSE = '</' + 'script>'
+const DOC_ATTR = ' id="bento-doc"'
+/**
+ * The #bento-doc body of an HTML file, exactly as kernel/src/save.ts
+ * `embeddedDocBlock` reads it (anchored on the id attribute, CRLF normalised,
+ * trimmed), so the hash here and the kernel's notion of "same document" agree.
+ */
+export function docBlock(html) {
+ const at = html.indexOf(DOC_ATTR)
+ if (at < 0) return null
+ const start = html.indexOf('>', at + DOC_ATTR.length)
+ if (start < 0) return null
+ const end = html.indexOf(SCRIPT_CLOSE, start + 1)
+ if (end < 0) return null
+ return html.slice(start + 1, end).replace(/\r\n/g, '\n').trim() || null
+}
+
+/** sha-256 (hex) of the block's UTF-8 bytes, or null when there is no block. */
+export async function blockHash(html, deps) {
+ const block = docBlock(String(html ?? ''))
+ return block == null ? null : deps.sha256(new TextEncoder().encode(block))
+}
+
+const hKey = (path) => `h${S}${path}`
+
+/**
+ * The extension just WROTE this file: remember which document it now holds.
+ * Called from the worker's own save path with the bytes it wrote — never with
+ * anything the page says about itself.
+ */
+export async function recordSaved(path, html, deps) {
+ if (!path) return
+ const hash = await blockHash(html, deps)
+ if (hash) await deps.db.put(hKey(path), { hash, at: deps.now() })
+ else await deps.db.del(hKey(path))
+}
+
+/** Move one entry (manifest + chunks) from one partition to another; the old one is deleted. */
+async function moveEntry(from, to, name, deps) {
+ const m = await deps.db.get(mKey(from, name))
+ if (!m) return false
+ for (let i = 0; i < m.n; i++) {
+ const c = await deps.db.get(cKey(from, name, m.tx, i))
+ if (c == null) return false
+ }
+ for (let i = 0; i < m.n; i++) await deps.db.put(cKey(to, name, m.tx, i), await deps.db.get(cKey(from, name, m.tx, i)))
+ await deps.db.put(mKey(to, name), { ...m, at: deps.now() })
+ await deps.db.del(mKey(from, name))
+ await dropTx(from, name, m.tx, deps)
+ return true
+}
+
+/**
+ * A document opened at `path`: if its partition is empty, may a moved
+ * document's recovery follow it? Returns what happened, for the log and the
+ * rig: { carried: oldPath } or { carried: null, why }.
+ */
+export async function carry(path, deps) {
+ if (!path) return { carried: null, why: 'not a document' }
+ const own = await deps.db.range(`m${S}${path}${S}`, `m${S}${path}${S}${END}`)
+ if (own.length) return { carried: null, why: 'has its own' }
+ let hash = null
+ try { hash = await deps.fileBlockHash(path) } catch { hash = null }
+ if (!hash) return { carried: null, why: 'no block' }
+ const cutoff = deps.now() - CARRY_DAYS * DAY
+ const eligible = []
+ for (const [k, v] of await deps.db.range(`h${S}`, `h${S}${END}`)) {
+ const old = k.slice(2)
+ if (old === path || v?.hash !== hash) continue
+ const rec = await deps.db.get(mKey(old, 'recovery'))
+ if (!rec || !(rec.at >= cutoff)) continue
+ let state = 'unknown'
+ try { state = await deps.gone(old) } catch { state = 'unknown' }
+ if (state !== 'gone') continue
+ eligible.push(old)
+ }
+ if (!eligible.length) return { carried: null, why: 'nothing matches' }
+ if (eligible.length > 1) return { carried: null, why: 'ambiguous' }
+ const [old] = eligible
+ // recovery ONLY. The member key stays behind with the old partition and is swept.
+ if (!(await moveEntry(old, path, 'recovery', deps))) return { carried: null, why: 'incomplete' }
+ await deps.db.put(hKey(path), { ...(await deps.db.get(hKey(old))), at: deps.now() })
+ await deps.db.del(hKey(old))
+ await deps.db.put(`x${S}${path}`, { from: old, at: deps.now() })
+ return { carried: old }
+}
+
+/**
+ * Is `path` definitely gone? Asked through a folder grant whose location the
+ * extension has PROVEN (db prefixes): walk from it; a NotFoundError on the way
+ * is 'gone', reaching the file is 'present', anything else — no grant covers
+ * it, permission lapsed, an unexpected error — is 'unknown'. Never a file://
+ * probe: a folder the browser may not read (macOS privacy, say) looks exactly
+ * like a missing one.
+ */
+export async function goneVia(path, grants) {
+ for (const { dir, prefix } of grants) {
+ if (!prefix || !path.startsWith(prefix.endsWith('/') ? prefix : `${prefix}/`)) continue
+ const rel = path.slice(prefix.length).split('/').filter(Boolean)
+ if (!rel.length) continue
+ try {
+ if (await dir.queryPermission({ mode: 'read' }) !== 'granted') continue
+ let cur = dir
+ for (const seg of rel.slice(0, -1)) cur = await cur.getDirectoryHandle(seg)
+ await cur.getFileHandle(rel[rel.length - 1])
+ return 'present'
+ } catch (e) {
+ if (e?.name === 'NotFoundError') return 'gone'
+ }
+ }
+ return 'unknown'
+}
+
+/**
+ * The sweep: partitions untouched for MAX_AGE_DAYS; partitions whose file is
+ * gone and whose recovery is too old to carry; and chunks of transfers that
+ * never committed. Returns what it dropped, for the log and the rig.
+ */
+export async function gc(deps) {
+ const now = deps.now()
+ const parts = new Map() // path → newest at
+ for (const [k, v] of await deps.db.range(`m${S}`, `m${S}${END}`)) {
+ const path = k.split(S)[1]
+ parts.set(path, Math.max(parts.get(path) ?? 0, v?.at ?? 0))
+ }
+ const dropped = []
+ for (const [path, newest] of parts) {
+ let why = newest < now - MAX_AGE_DAYS * DAY ? 'age' : null
+ if (!why) {
+ let state = 'unknown'
+ try { state = await deps.gone(path) } catch { state = 'unknown' }
+ if (state === 'gone') {
+ const rec = await deps.db.get(mKey(path, 'recovery'))
+ // still a carry candidate: keep it until it is too old to follow
+ if (!(rec && rec.at >= now - CARRY_DAYS * DAY)) why = 'gone'
+ }
+ }
+ if (!why) continue
+ for (const [k] of await deps.db.range(`m${S}${path}${S}`, `m${S}${path}${S}${END}`)) {
+ await remove(path, { name: k.slice(mKey(path, '').length) }, deps)
+ }
+ await deps.db.del(hKey(path))
+ await deps.db.del(`x${S}${path}`)
+ dropped.push({ path, why })
+ }
+ for (const [k, v] of await deps.db.range(`t${S}`, `t${S}${END}`)) {
+ if ((v?.at ?? 0) < now - STALE_TX_MS) {
+ const [, path, name, tx] = k.split(S)
+ const m = await deps.db.get(mKey(path, name))
+ if (!m || m.tx !== tx) await dropTx(path, name, tx, deps)
+ }
+ }
+ return dropped
+}
+
+// ---------------------------------------------------------------- IndexedDB
+
+/** The real adapter: its own database, so large values never share a version with the grant store. */
+export function idbAdapter(dbName = 'bento-docstore') {
+ const open = () => new Promise((res, rej) => {
+ const r = indexedDB.open(dbName, 1)
+ r.onupgradeneeded = () => { if (!r.result.objectStoreNames.contains('kv')) r.result.createObjectStore('kv') }
+ r.onsuccess = () => res(r.result)
+ r.onerror = () => rej(r.error)
+ })
+ const tx = async (mode, fn) => {
+ const d = await open()
+ return new Promise((res, rej) => {
+ const t = d.transaction('kv', mode)
+ const out = fn(t.objectStore('kv'))
+ t.oncomplete = () => res(out?.result ?? out?.value)
+ t.onerror = () => rej(t.error)
+ })
+ }
+ return {
+ get: (k) => tx('readonly', (s) => s.get(k)).then((v) => v ?? null),
+ put: (k, v) => tx('readwrite', (s) => { s.put(v, k) }),
+ del: (k) => tx('readwrite', (s) => { s.delete(k) }),
+ range: async (lo, hi) => {
+ const d = await open()
+ return new Promise((res, rej) => {
+ const out = []
+ const req = d.transaction('kv', 'readonly').objectStore('kv').openCursor(IDBKeyRange.bound(lo, hi))
+ req.onsuccess = () => { const c = req.result; if (c) { out.push([c.key, c.value]); c.continue() } else res(out) }
+ req.onerror = () => rej(req.error)
+ })
+ },
+ }
+}
diff --git a/scripts/pack-webext.mjs b/scripts/pack-webext.mjs
index 9dcad0f2..184ccb3c 100644
--- a/scripts/pack-webext.mjs
+++ b/scripts/pack-webext.mjs
@@ -261,8 +261,9 @@ if (manifest) {
// A dotted permission names a capability inside an API, not a namespace:
// `downloads.ui` is used as `chrome.downloads.setUiOptions`.
const usedAs = { 'downloads.ui': 'chrome\\.downloads\\.setUiOptions' }
+ const usedWithoutApi = { storage: true }
for (const perm of manifest.permissions ?? []) {
- if (!new RegExp(usedAs[perm] ?? `chrome\\.${perm}\\b`).test(srcText) && perm !== 'storage') {
+ if (!new RegExp(usedAs[perm] ?? `chrome\\.${perm}\\b`).test(srcText) && !usedWithoutApi[perm]) {
fail(`permission "${perm}" is declared but never used in the shipped code`)
}
}
diff --git a/scripts/test-webext-store.ts b/scripts/test-webext-store.ts
new file mode 100644
index 00000000..3aab540c
--- /dev/null
+++ b/scripts/test-webext-store.ts
@@ -0,0 +1,271 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// home/webext DocStore rig.
+//
+// node scripts/test-webext-store.ts
+//
+// WHAT THIS PROVES. A document's sidecar data (crash recovery and the collab
+// member key — nothing else; version history lives in the file) is kept in the
+// extension's origin, partitioned by the file path the BROWSER reports for the
+// sender. One document can never read, list, overwrite or delete another's
+// entries; nothing in the payload can name a different partition; bytes
+// survive the base64 hop and the chunked path intact; a half-sent value is
+// never visible. And for a MOVED file (security ruling 2026-10-10): its
+// recovery follows only when the old path is gone as a grant sees it, the new
+// file's #bento-doc hashes to what the extension last wrote, and the recovery
+// is under a week old; it moves once; the member key never follows. Includes
+// the ruling's two required mutations (drop the hash check; carry the member
+// key), both red.
+// The real store.js, background.js and relay.js run here.
+
+import { readFileSync } from 'node:fs'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { createContext, runInContext } from 'node:vm'
+import { createHash } from 'node:crypto'
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+const SRC = join(root, 'home/webext')
+const st = await import('../home/webext/src/store.js')
+const bg = await import('../home/webext/src/background.js')
+
+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}`)
+}
+
+/** An ordered in-memory key/value store with the adapter's shape. */
+function memory() {
+ const m = new Map<string, any>()
+ return {
+ m,
+ get: async (k: string) => (m.has(k) ? m.get(k) : null),
+ put: async (k: string, v: any) => { m.set(k, v) },
+ del: async (k: string) => { m.delete(k) },
+ range: async (lo: string, hi: string) => [...m.entries()].filter(([k]) => k >= lo && k <= hi).sort(([a], [b]) => (a < b ? -1 : 1)),
+ }
+}
+let clock = Date.UTC(2026, 9, 4)
+let txn = 0
+const sha256 = async (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex')
+/** A store with no grants (nothing is ever "gone") and no readable files, unless a test says otherwise. */
+const deps = (db = memory(), over: any = {}) => ({ db, now: () => clock, txid: () => `tx-${String(++txn).padStart(8, '0')}`, sha256, gone: async (_p: string) => 'unknown', fileBlockHash: async (_p: string) => null, ...over })
+
+const A = { url: 'file:///Users/you/Decks/Q3.bento.html', frameId: 0 }
+const B = { url: 'file:///Users/you/Decks/Other.bento.html', frameId: 0 }
+const enc = (s: string) => st.toB64(new TextEncoder().encode(s))
+const dec = (b: string) => new TextDecoder().decode(st.fromB64(b))
+
+console.log('\n— partitions: the sender\'s path, never the payload\'s')
+{
+ const d = deps()
+ ok((await bg.storeOp('store.set', A, { name: 'recovery', data: enc('A-recovery') }, d)).ok, 'set from A')
+ ok((await bg.storeOp('store.set', B, { name: 'recovery', data: enc('B-recovery') }, d)).ok, 'set from B, same name')
+ const ga = await bg.storeOp('store.get', A, { name: 'recovery' }, d)
+ const gb = await bg.storeOp('store.get', B, { name: 'recovery' }, d)
+ ok(dec(ga.inline) === 'A-recovery' && dec(gb.inline) === 'B-recovery', 'each document reads only its own value under the same name')
+ ok((await bg.storeOp('store.list', A, { prefix: '' }, d)).names.join() === 'recovery', 'list sees only the sender\'s partition')
+ // the payload cannot redirect: extra fields naming a path are ignored
+ await bg.storeOp('store.set', A, { name: 'recovery', data: enc('evil'), path: '/Users/you/Decks/Other.bento.html', url: B.url }, d)
+ ok(dec((await bg.storeOp('store.get', B, { name: 'recovery' }, d)).inline) === 'B-recovery', 'a payload naming another path changes nothing there')
+ await bg.storeOp('store.delete', A, { name: 'recovery' }, d)
+ ok((await bg.storeOp('store.get', B, { name: 'recovery' }, d)).found === true, 'A deleting its entry leaves B\'s')
+ for (const [label, s] of [['a sub-frame', { ...A, frameId: 2 }], ['an https page', { url: 'https://bento.page/slides/', frameId: 0 }], ['no sender', undefined]] as const) {
+ const r = await bg.storeOp('store.get', s, { name: 'recovery' }, d)
+ ok(!r.ok && r.reason === 'not a document', `${label} has no partition`)
+ }
+ for (const n of ['../x', 'a\u0000b', 'ver/0001', 'recovery/x', 'Recovery', 'other'])
+ ok((await bg.storeOp('store.set', A, { name: n, data: enc('x') }, d)).reason === 'bad request' && (await bg.storeOp('store.get', A, { name: n }, d)).reason === 'bad name', `name ${JSON.stringify(n)} refused — only ${st.NAMES.join(' and ')} (version history lives in the file)`)
+ ok((await bg.storeOp('store.list', A, { prefix: 'x\u0000' }, d)).reason === 'bad prefix', 'a list prefix cannot carry the key separator')
+ ok((await bg.storeOp('store.nope', A, {}, d)).ok === false, 'an unknown store op is refused')
+}
+
+console.log('\n— chunked values: committed whole or not at all')
+{
+ const d = deps()
+ const tx = 'tx-chunked-1'
+ await bg.storeOp('store.put', A, { name: 'recovery', tx, i: 0, data: enc('part0-') }, d)
+ ok((await bg.storeOp('store.get', A, { name: 'recovery' }, d)).found === false, 'before commit, nothing is visible')
+ ok((await bg.storeOp('store.commit', A, { name: 'recovery', tx, n: 2 }, d)).reason === 'incomplete', 'a commit with a chunk missing is refused')
+ await bg.storeOp('store.put', A, { name: 'recovery', tx, i: 1, data: enc('part1') }, d)
+ ok((await bg.storeOp('store.commit', A, { name: 'recovery', tx, n: 2 }, d)).ok, 'all chunks present → committed')
+ const m = await bg.storeOp('store.get', A, { name: 'recovery' }, d)
+ const parts = [await bg.storeOp('store.chunk', A, { name: 'recovery', tx: m.tx, i: 0 }, d), await bg.storeOp('store.chunk', A, { name: 'recovery', tx: m.tx, i: 1 }, d)]
+ ok(m.n === 2 && m.size === 11 && parts.map((p: any) => dec(p.data)).join('') === 'part0-part1', 'read back chunk by chunk, size exact')
+ ok((await bg.storeOp('store.chunk', B, { name: 'recovery', tx: m.tx, i: 0 }, d)).reason === 'gone', 'another document cannot read A\'s chunks even with the tx id')
+ // replacing the value retires the old chunks
+ await bg.storeOp('store.set', A, { name: 'recovery', data: enc('new') }, d)
+ ok(![...d.db.m.keys()].some((k) => k.includes(m.tx)), 'a replaced value leaves no chunks behind')
+ ok((await bg.storeOp('store.put', A, { name: 'memberkey', tx, i: 0, data: st.toB64(new Uint8Array(st.CHUNK + 1)) }, d)).reason === 'chunk too large', 'a chunk over CHUNK is refused')
+}
+
+console.log('\n— the sweep')
+{
+ const DAY = 24 * 3600 * 1000
+ const d = deps(memory(), { gone: async (p: string) => (p.endsWith('Other.bento.html') || p.endsWith('Recent.bento.html') ? 'gone' : 'unknown') })
+ await bg.storeOp('store.set', A, { name: 'recovery', data: enc('r') }, d)
+ clock -= 10 * DAY
+ await bg.storeOp('store.set', B, { name: 'recovery', data: enc('b') }, d) // gone, recovery 10 days old
+ clock += 8 * DAY
+ const R = { url: 'file:///Users/you/Decks/Recent.bento.html', frameId: 0 }
+ await bg.storeOp('store.set', R, { name: 'recovery', data: enc('r2') }, d) // gone, recovery 2 days old
+ const C = { url: 'file:///Users/you/Old/C.bento.html', frameId: 0 }
+ clock -= 40 * DAY
+ await bg.storeOp('store.set', C, { name: 'recovery', data: enc('c') }, d) // untouched 40 days
+ await bg.storeOp('store.put', A, { name: 'recovery', tx: 'tx-abandoned', i: 0, data: enc('half') }, d)
+ clock += 42 * DAY
+ const dropped = await st.gc(d)
+ ok(dropped.some((x: any) => x.path.endsWith('Other.bento.html') && x.why === 'gone'), 'a gone file whose recovery is too old to carry is dropped')
+ ok(!dropped.some((x: any) => x.path.endsWith('Recent.bento.html')), `a gone file whose recovery could still carry (< ${st.CARRY_DAYS} days) is kept`)
+ ok(dropped.some((x: any) => x.path.endsWith('C.bento.html') && x.why === 'age'), `a partition untouched for ${st.MAX_AGE_DAYS} days is dropped`)
+ ok(!dropped.some((x: any) => x.path.endsWith('Q3.bento.html')), '"unknown" (no grant covers it) is never treated as gone')
+ ok(![...d.db.m.keys()].some((k) => k.includes('tx-abandoned')), 'a transfer that never committed is swept')
+}
+
+console.log('\n— a moved file: what follows it, and what never does (security ruling 2026-10-10)')
+{
+ const DAY = 24 * 3600 * 1000
+ const OLD = '/Users/you/Decks/Q3.bento.html'
+ const NEW = '/Users/you/Archive/Q3 final.bento.html'
+ const NEWs = { url: 'file:///Users/you/Archive/Q3%20final.bento.html', frameId: 0 }
+ const saved = '<!doctype html><script type="application/json" id="bento-doc">{"docId":"V",\n"title":"Q3"}</' + 'script><p>shell</p>'
+ // the same document with CRLF line endings INSIDE the block (where trim cannot hide them)
+ const savedCRLF = saved.replace(',\n"title"', ',\r\n"title"')
+ /** V: saved once by the extension, then edited (recovery), with a member key; a world where OLD is `oldState`. */
+ const world = async (opts: { oldState?: string; newFile?: string; recoveryAge?: number } = {}) => {
+ const files: Record<string, string> = { [NEW]: opts.newFile ?? saved }
+ const d = deps(memory(), {
+ gone: async (p: string) => (p === OLD ? (opts.oldState ?? 'gone') : 'unknown'),
+ fileBlockHash: async (p: string) => (files[p] ? st.blockHash(files[p], { sha256 }) : null),
+ })
+ clock -= (opts.recoveryAge ?? 1) * DAY
+ await st.recordSaved(OLD, saved, d)
+ await bg.storeOp('store.set', A, { name: 'recovery', data: enc('UNSAVED DELTA') }, d)
+ await bg.storeOp('store.set', A, { name: 'memberkey', data: enc('V-MEMBER-KEY') }, d)
+ clock += (opts.recoveryAge ?? 1) * DAY
+ return d
+ }
+ const at = async (d: any, s: any, name: string) => { const r = await bg.storeOp('store.get', s, { name }, d); return r.found ? dec(r.inline) : null }
+
+ {
+ const d = await world()
+ ok(await at(d, NEWs, 'recovery') === 'UNSAVED DELTA', 'the same saved file, moved (old path gone, block hash equal): its recovery follows')
+ ok(await at(d, NEWs, 'memberkey') === null, 'the member key does NOT follow — the moved file re-enrols through its own invite chain')
+ ok(!(await d.db.get(`m\u0000${OLD}\u0000recovery`)) && !(await d.db.get(`h\u0000${OLD}`)), 'carried once: the old record itself is gone (moved, not copied), so two files can never both claim it')
+ ok((await d.db.get(`x\u0000${NEW}`))?.from === OLD, 'the carry is noted against the new path (for the restore prompt)')
+ }
+ {
+ const d = await world({ newFile: saved.replace('"title":"Q3"', '"title":"Q3, edited elsewhere"') })
+ ok(await at(d, NEWs, 'recovery') === null && await at(d, A, 'recovery') === 'UNSAVED DELTA', 'a hostile or edited file with the same docId, old path gone, different content: nothing carries')
+ ok(await at(d, NEWs, 'memberkey') === null, 'and the member key never moves')
+ }
+ {
+ const d = await world({ oldState: 'present' })
+ ok(await at(d, NEWs, 'recovery') === null, 'old path still present (a copy, not a move): nothing carries')
+ }
+ {
+ const d = await world({ oldState: 'unknown' })
+ ok(await at(d, NEWs, 'recovery') === null, 'old path not checkable through a grant: nothing carries')
+ }
+ {
+ const d = await world({ recoveryAge: st.CARRY_DAYS + 1 })
+ ok(await at(d, NEWs, 'recovery') === null, `a recovery older than ${st.CARRY_DAYS} days never carries`)
+ }
+ {
+ const d = await world({ newFile: savedCRLF })
+ ok(await at(d, NEWs, 'recovery') === 'UNSAVED DELTA', 'CRLF line endings do not make it a different document (kernel embeddedDocBlock rule)')
+ }
+ {
+ // two gone partitions both match: ambiguous, so neither carries
+ const d = await world()
+ const OLD2 = '/Users/you/Decks/Q3 copy.bento.html'
+ await st.recordSaved(OLD2, saved, d)
+ await bg.storeOp('store.set', { url: 'file:///Users/you/Decks/Q3%20copy.bento.html', frameId: 0 }, { name: 'recovery', data: enc('OTHER') }, d)
+ d.gone = async (p: string) => (p === OLD || p === OLD2 ? 'gone' : 'unknown')
+ ok(await at(d, NEWs, 'recovery') === null, 'two moved copies both match: neither carries')
+ }
+ {
+ // the page cannot vouch for its own content: only the extension's read of the file counts
+ // everything else would carry; the new path already has an entry of its own
+ const d = await world()
+ await st.set(NEW, { name: 'memberkey', data: enc('NEW-OWN') }, d)
+ ok(await at(d, NEWs, 'recovery') === null && await at(d, NEWs, 'memberkey') === 'NEW-OWN', 'a partition that already has entries never receives a carry')
+ }
+ {
+ // the hash recorded is the bytes the extension WROTE
+ const d = deps()
+ await st.recordSaved(OLD, saved, d)
+ ok((await d.db.get(`h\u0000${OLD}`))?.hash === createHash('sha256').update(st.docBlock(saved)!).digest('hex'), 'recordSaved stores sha-256 of the #bento-doc block of the bytes written')
+ await st.recordSaved(OLD, '<p>no block</p>', d)
+ ok(!(await d.db.get(`h\u0000${OLD}`)), 'a write with no block clears the record')
+ }
+ {
+ // gone, as only a grant can see it
+ const dir = (tree: any): any => ({ name: 'Decks', queryPermission: async () => 'granted',
+ getDirectoryHandle: async (n: string) => { if (!tree[n] || typeof tree[n] !== 'object') { const e: any = new Error(); e.name = 'NotFoundError'; throw e } return dir(tree[n]) },
+ getFileHandle: async (n: string) => { if (tree[n] !== 1) { const e: any = new Error(); e.name = 'NotFoundError'; throw e } return {} } })
+ const g = [{ dir: dir({ 'Q3.bento.html': 1, Sub: {} }), prefix: '/Users/you/Decks' }]
+ ok(await st.goneVia('/Users/you/Decks/Q3.bento.html', g) === 'present', 'goneVia: a file the grant reaches is present')
+ ok(await st.goneVia('/Users/you/Decks/Old.bento.html', g) === 'gone' && await st.goneVia('/Users/you/Decks/Nope/x.bento.html', g) === 'gone', 'goneVia: a definite NotFound is gone')
+ ok(await st.goneVia('/Users/you/Elsewhere/Q3.bento.html', g) === 'unknown', 'goneVia: outside every grant is unknown')
+ const lapsed = [{ dir: { ...g[0].dir, queryPermission: async () => 'prompt' }, prefix: '/Users/you/Decks' }]
+ ok(await st.goneVia('/Users/you/Decks/Old.bento.html', lapsed) === 'unknown', 'goneVia: a lapsed grant is unknown, not gone')
+ const denied = [{ dir: { ...g[0].dir, getFileHandle: async () => { const e: any = new Error(); e.name = 'NotAllowedError'; throw e } }, prefix: '/Users/you/Decks' }]
+ ok(await st.goneVia('/Users/you/Decks/Old.bento.html', denied) === 'unknown', 'goneVia: any error but NotFound is unknown')
+ }
+}
+
+console.log('\n— the relay: bytes in, bytes out, chunked above CHUNK')
+{
+ const d = deps()
+ const posted: any[] = []
+ const listeners: any[] = []
+ const win: any = { addEventListener: (_: string, f: any) => listeners.push(f), postMessage: (m: any) => posted.push(m) }
+ let sent = 0
+ const chrome = { runtime: { sendMessage: async (m: any) => { if (m.op === 'hello') return {}; sent++; return bg.storeOp(m.op, A, m.payload, d) } } }
+ const ctx: any = createContext({ window: win, chrome, btoa, atob, crypto: { randomUUID: () => 'relay-tx-0001' }, Uint8Array, String, console })
+ runInContext(readFileSync(join(SRC, 'src/relay.js'), 'utf8'), ctx)
+ const CH = '__bento_tray__'
+ const call = async (op: string, payload: any) => {
+ const id = `s-${posted.length}-${Math.random()}`
+ for (const f of listeners) f({ data: { [CH]: true, dir: 'req', id, op, payload }, source: win })
+ for (let i = 0; i < 500 && !posted.some((p) => p.id === id); i++) await new Promise((r) => setTimeout(r, 0))
+ return posted.find((p) => p.id === id).result
+ }
+ const small = new Uint8Array([0, 1, 2, 250, 255])
+ ok((await call('store.set', { name: 'memberkey', bytes: new ctx.Uint8Array(small) })).ok, 'set small bytes through the relay')
+ const back = await call('store.get', { name: 'memberkey' })
+ ok(back.ok && back.bytes.length === 5 && [...back.bytes].join() === '0,1,2,250,255', 'get returns the exact bytes (binary-safe base64 hop)')
+ const big = new ctx.Uint8Array(7 * 1024 * 1024 + 123)
+ for (let i = 0; i < big.length; i++) big[i] = (i * 31) & 255
+ sent = 0
+ ok((await call('store.set', { name: 'recovery', bytes: big })).ok && sent === 4, `a 7 MB value travels as 3 chunks + a commit (${sent} messages)`)
+ const bigBack = await call('store.get', { name: 'recovery' })
+ let same = bigBack.ok && bigBack.bytes.length === big.length
+ for (let i = 0; same && i < big.length; i += 4099) same = bigBack.bytes[i] === big[i]
+ ok(same, 'and comes back whole, byte for byte')
+ ok((await call('store.get', { name: 'nothing' })).reason === 'bad name', 'a name outside NAMES is refused through the relay too')
+ ok((await call('store.set', { name: 'recovery', bytes: 'not bytes' })).reason === 'bytes must be a Uint8Array', 'non-bytes refused at the relay')
+ ok((await call('store.list', { prefix: 'rec' })).names.join() === 'recovery', 'list through the relay')
+ ok((await call('store.delete', { name: 'memberkey' })).ok && (await call('store.get', { name: 'memberkey' })).bytes === null, 'delete through the relay')
+ for (const f of listeners) f({ data: { [CH]: true, dir: 'req', id: 'frame', op: 'store.get', payload: { name: 'recovery' } }, source: { other: true } })
+ await new Promise((r) => setTimeout(r, 5))
+ ok(!posted.some((p) => p.id === 'frame'), 'a request posted from another window (an iframe) is dropped')
+}
+{
+ const bgSrc = readFileSync(join(SRC, 'src/background.js'), 'utf8')
+ ok(/op === 'write' \? write\(sender, msg\.payload\?\.text \?\? ''\)\.then\(\(r\) => \{ if \(r\?\.ok\) noteSaved\(sender/.test(bgSrc), 'the saved hash is recorded after a SUCCESSFUL extension write, from the bytes written')
+ ok((bgSrc.match(/recordSaved\(/g) ?? []).length === 1 && !/'store\.[a-z]+': docstore\.recordSaved/.test(bgSrc), 'and from nowhere else: no store op lets a page set it')
+ ok(/if \(path\) await ensureCarried\(path, deps\)\s*\n\s*return fn\(path/.test(bgSrc), 'the carry is decided before the page\'s first store op is answered')
+ ok(/fileBlockHash: async \(path\) => \{\s*\n\s*const r = await fetch\(`file:\/\//.test(bgSrc), 'the new file\'s hash is read by the extension from disk, not reported by the page')
+ ok(/'store'/.test(readFileSync(join(SRC, 'src/page-bridge.js'), 'utf8')), 'page-bridge.js announces the store capability')
+ const manifest = JSON.parse(readFileSync(join(SRC, 'manifest.json'), 'utf8'))
+ ok(manifest.content_scripts.every((cs: any) => cs.all_frames === false || cs.all_frames === undefined), 'content scripts stay top-frame only')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)