Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

webext: stateless writes, sender-derived paths, and a rig for the half that writes (#218)

nyblnet55bded9f239f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3bbb52a5..d5fa870c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -122,6 +122,14 @@ jobs:
# file carrying a script tag.
run: node scripts/test-preview.ts
+ - name: WebExtension background rig
+ # The half that WRITES, and previously the untested half. Two properties
+ # it must hold: the target file comes from sender.url (browser-stamped)
+ # and never from the page, and nothing is carried between messages,
+ # because an MV3 service worker is evicted mid-save and state across that
+ # gap fails intermittently on nobody's machine but the user's.
+ run: node scripts/test-webext-background.ts
+
- name: WebExtension bridge rig
# tray/webext decides, per save, whether to write in place or hand back
# to the browser's own picker. Wrong in the permissive direction it
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index d7de8997..a56f7d79 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -1258,3 +1258,37 @@ The library tier — many spaces, searched together — attaches at a named seam
and is `bento/vault`'s job, which is optional by its own invariants 2 and 3.
One space needs nothing installed, ever; a library is software you run, on a
laptop or a 24/7 box or a cluster, the same artifact either way.
+
+## 2026-08-03 — tray/webext ships through the stores; unpacked stays available
+
+Settled with the maintainer. The **app stores are the main distribution
+channel** for `tray/webext` — Chrome Web Store, Edge Add-ons, and the others as
+they come — with the unpacked folder in this repo remaining a supported option
+for people who want it.
+
+Two corrections to earlier reasoning in this thread, both of which had made the
+extension look less viable than it is:
+
+**Developer mode is not required.** It is needed only for "Load unpacked". A
+store-installed extension needs no Developer mode, no unpacked folder and no
+warning banner. An earlier note in this session treated that as an inherent
+cost of the whole approach; it is a cost of one distribution method.
+
+**Store distribution does not conflict with the signed-release model.**
+`docs/RELEASING.md`'s "signed locally, the signed bytes are the served bytes"
+governs the DOCUMENT SHELL and its self-update channel. The extension is not a
+document, carries none, and never touches that path, so a store-distributed
+extension and a locally-signed shell coexist. What a store actually costs is
+review latency and a second release cadence — ordinary, not philosophical.
+
+**What does survive a store listing** is `Allow access to file URLs`: a
+per-extension user toggle, off by default, required for content scripts on
+`file://`. No manifest permission grants it. It is, however, DETECTABLE via
+`chrome.extension.isAllowedFileSchemeAccess()`, so the extension can turn silent
+failure into a guided one-time setup step rather than a mystery. That API's MV3
+behaviour is unverified — measure before building on it.
+
+Consequences already implemented: `permissions` trimmed to `storage` (an unused
+`offscreen` would draw review questions it cannot answer), and content scripts
+narrowed from every `file:///*.html` to `file:///*.bento.html`, which is both
+correct and far easier to justify to a reviewer.
diff --git a/scripts/test-webext-background.ts b/scripts/test-webext-background.ts
new file mode 100644
index 00000000..61df42c0
--- /dev/null
+++ b/scripts/test-webext-background.ts
@@ -0,0 +1,147 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// tray/webext background rig.
+//
+// node scripts/test-webext-background.ts
+//
+// WHAT THIS PROVES. This is the half that WRITES, and it was the untested half:
+// the bridge had 15 checks while the code putting bytes on disk had none. Two
+// properties matter more than the rest, and neither is visible by reading a
+// successful save.
+//
+// 1. THE PAGE DOES NOT CHOOSE THE FILE. The path comes from `sender.url`,
+// which the browser stamps, never from the message payload, which a local
+// HTML file controls. A document that could name its own target could name
+// the deck next to it in the granted folder and overwrite that instead.
+//
+// 2. NOTHING IS HELD BETWEEN MESSAGES. An MV3 service worker is evicted
+// whenever the browser likes, and a save serialises ~900KB first, so an
+// eviction between "which file?" and "write it" is ordinary. State carried
+// across that gap fails a save intermittently and reproduces on nobody's
+// machine. Every message re-resolves.
+//
+// Both are checked by construction here: a write is issued with no preceding
+// claim at all, which is exactly what a service worker restart looks like.
+
+import { pathFromSender, findByName, claim, write, resolve } from '../tray/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}`)
+}
+
+// ---- a fake granted folder --------------------------------------------------
+const written = new Map<string, string>()
+
+function fileHandle(name: string) {
+ return {
+ kind: 'file' as const,
+ name,
+ async createWritable() {
+ let buf = ''
+ return {
+ async write(t: string) { buf += t },
+ async close() { written.set(name, buf) },
+ }
+ },
+ }
+}
+
+function dirHandle(tree: Record<string, any>, perm = 'granted') {
+ return {
+ kind: 'directory' as const,
+ name: 'Decks',
+ async queryPermission() { return perm },
+ async *entries() {
+ for (const [k, v] of Object.entries(tree)) {
+ yield [k, typeof v === 'object' && !v.kind ? dirHandle(v, perm) : v] as const
+ }
+ },
+ }
+}
+
+const senderFor = (path: string) => ({ url: 'file://' + path })
+
+// ---- 1. the path comes from the browser, not the page -----------------------
+ok(pathFromSender({ url: 'file:///Users/x/Decks/Q3.bento.html' }) === '/Users/x/Decks/Q3.bento.html',
+ 'a file:// sender yields its path')
+ok(pathFromSender({ url: 'https://evil.example/x.bento.html' }) === null,
+ 'an http sender is refused — the bridge is for local documents')
+ok(pathFromSender({}) === null, 'a sender with no url is refused')
+ok(pathFromSender({ url: 'file:///Users/x/My%20Decks/Q3.bento.html' }) === '/Users/x/My Decks/Q3.bento.html',
+ 'a percent-encoded path is decoded')
+
+// ---- 2. resolution inside the grant ----------------------------------------
+const deps = (tree: Record<string, any>, perm = 'granted') => ({
+ readGrant: async () => dirHandle(tree, perm),
+ findByName,
+})
+
+{
+ const tree = { 'Q3.bento.html': fileHandle('Q3.bento.html'), 'notes.txt': fileHandle('notes.txt') }
+ const r = await resolve(senderFor('/Users/x/Decks/Q3.bento.html'), deps(tree))
+ ok(r.ok === true && r.name === 'Q3.bento.html', 'a unique file in the granted folder resolves')
+}
+{
+ const tree = { 'Q3.bento.html': fileHandle('Q3.bento.html') }
+ const r = await resolve(senderFor('/Users/x/Decks/Other.bento.html'), deps(tree))
+ ok(r.ok === false && /not in the granted folder/.test(r.reason!),
+ 'a file outside the grant is declined, not guessed at')
+}
+{
+ // the same name in two subfolders — the case a real Decks folder hits
+ const tree = {
+ ClientA: { 'Q3.bento.html': fileHandle('a/Q3.bento.html') },
+ ClientB: { 'Q3.bento.html': fileHandle('b/Q3.bento.html') },
+ }
+ const r = await resolve(senderFor('/Users/x/Decks/ClientA/Q3.bento.html'), deps(tree))
+ ok(r.ok === false && /ambiguous/.test(r.reason!),
+ 'a duplicate file name is declined rather than written to the wrong one')
+}
+{
+ const tree = { 'Q3.bento.html': fileHandle('Q3.bento.html') }
+ const r = await resolve(senderFor('/Users/x/Decks/Q3.bento.html'), deps(tree, 'prompt'))
+ ok(r.ok === false && /renewing/.test(r.reason!),
+ 'a lapsed folder grant is reported, never silently prompted for')
+}
+{
+ const r = await resolve({ url: 'https://evil.example/Q3.bento.html' },
+ deps({ 'Q3.bento.html': fileHandle('Q3.bento.html') }))
+ ok(r.ok === false && /not a local file/.test(r.reason!),
+ 'an http page cannot resolve a file in the granted folder')
+}
+
+// ---- 3. a write needs no prior claim (service-worker eviction) --------------
+{
+ written.clear()
+ const tree = { 'Q3.bento.html': fileHandle('Q3.bento.html') }
+ // NO claim() first — this is precisely what a restarted service worker sees.
+ const r = await write(senderFor('/Users/x/Decks/Q3.bento.html'), '<html>deck</html>', deps(tree))
+ ok(r.ok === true && r.bytes === 17, 'a write with no preceding claim succeeds — no state is carried')
+ ok(written.get('Q3.bento.html') === '<html>deck</html>', 'and the bytes land in the right file')
+}
+
+// ---- 4. claim reports without writing --------------------------------------
+{
+ written.clear()
+ const tree = { 'Q3.bento.html': fileHandle('Q3.bento.html') }
+ const r = await claim(senderFor('/Users/x/Decks/Q3.bento.html'), deps(tree))
+ ok(r.ok === true && r.name === 'Q3.bento.html', 'claim reports the file it would write')
+ ok(written.size === 0, 'and writes nothing while doing so')
+}
+
+// ---- 5. the depth limit ----------------------------------------------------
+{
+ // 6 levels deep — past the limit, so it must NOT be found rather than hang
+ let deep: any = { 'Q3.bento.html': fileHandle('deep/Q3.bento.html') }
+ for (let i = 0; i < 6; i++) deep = { sub: deep }
+ const r = await resolve(senderFor('/Users/x/Decks/Q3.bento.html'), deps(deep))
+ ok(r.ok === false, 'a file buried past the depth limit is declined, not searched forever')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/tray/webext/README.md b/tray/webext/README.md
index 37e8ff32..c2b1d470 100644
--- a/tray/webext/README.md
+++ b/tray/webext/README.md
@@ -18,6 +18,19 @@ The last row is the one that matters: the copy and the export went elsewhere
rather than overwriting the document being edited. An earlier build got that
wrong and silently destroyed it.
+## Distribution
+
+**The app stores are the main channel** — Chrome Web Store, Edge Add-ons, and
+the others as they come. The unpacked folder here stays supported for anyone who
+prefers it.
+
+A store install needs **no Developer mode** and no unpacked folder. What it
+still needs is **Allow access to file URLs**: a per-extension user toggle, off by
+default, required for content scripts on `file://`, and grantable by no manifest
+permission. It is detectable (`chrome.extension.isAllowedFileSchemeAccess()`),
+so it should become a guided one-time setup step rather than a silent failure —
+not yet built, and that API's MV3 behaviour is unverified.
+
## Operating it
**The folder grant lapses when the extension reloads.** A reload resets the
@@ -127,7 +140,10 @@ file.
## Trying it
-1. `chrome://extensions` → Developer mode → **Load unpacked** → `tray/webext/`
+1. **From a store:** install, then enable **Allow access to file URLs** on its
+ card in `chrome://extensions`.
+ **Unpacked:** `chrome://extensions` → Developer mode → **Load unpacked** →
+ `tray/webext/`, then the same file-URL toggle.
2. Open its **options** and grant the folder your decks live in
3. Double-click a `.bento.html` in that folder, edit something, press ⌘S
diff --git a/tray/webext/manifest.json b/tray/webext/manifest.json
index 8ed96ba0..6c830a1d 100644
--- a/tray/webext/manifest.json
+++ b/tray/webext/manifest.json
@@ -4,7 +4,9 @@
"version": "0.0.1",
"description": "Save a Bento document back to the file you opened, without a destination prompt.",
"minimum_chrome_version": "116",
- "permissions": ["storage", "offscreen"],
+ "permissions": [
+ "storage"
+ ],
"options_page": "src/options.html",
"background": {
"service_worker": "src/background.js",
@@ -12,14 +14,22 @@
},
"content_scripts": [
{
- "matches": ["file:///*.html"],
- "js": ["src/page-bridge.js"],
+ "matches": [
+ "file:///*.bento.html"
+ ],
+ "js": [
+ "src/page-bridge.js"
+ ],
"world": "MAIN",
"run_at": "document_start"
},
{
- "matches": ["file:///*.html"],
- "js": ["src/relay.js"],
+ "matches": [
+ "file:///*.bento.html"
+ ],
+ "js": [
+ "src/relay.js"
+ ],
"world": "ISOLATED",
"run_at": "document_start"
}
diff --git a/tray/webext/src/background.js b/tray/webext/src/background.js
index 044a911a..7fb827b8 100644
--- a/tray/webext/src/background.js
+++ b/tray/webext/src/background.js
@@ -11,13 +11,21 @@
// double-clicking be written without a destination prompt, which no web page
// can do for itself.
//
-// THE MATCHING PROBLEM, and why it is not solved perfectly. A page gives us
-// `/Users/…/Decks/Q3.bento.html`; a `FileSystemDirectoryHandle` knows its own
-// NAME but not its path, and there is no API to ask. So the two cannot be
-// compared directly. This resolves it by searching the granted tree for a file
-// of that name and requiring EXACTLY ONE match: unambiguous in the ordinary
-// case, and when it is ambiguous the answer is to decline and let the native
-// picker handle it. Declining costs a prompt; guessing costs somebody's file.
+// TWO RULES SHAPE THIS FILE.
+//
+// 1. NO STATE BETWEEN MESSAGES. An MV3 service worker is evicted whenever the
+// browser feels like it, and a save serialises the whole deck first —
+// encryption, preview, ~900KB — so an eviction can easily land between
+// "which file is this?" and "write it". Anything held in memory across that
+// gap produces a failed save that looks random and reproduces on nobody's
+// machine. So every message re-resolves from the grant; nothing is cached.
+//
+// 2. THE PAGE DOES NOT GET TO SAY WHICH FILE IT IS. `sender.url` is set by the
+// browser, not by the content script, so it cannot be forged by the document
+// — whereas anything in the message payload can. A local HTML file is
+// untrusted content; if it could name its own target it could name somebody
+// else's deck in the granted folder and overwrite it. The path comes from
+// the sender, and a payload path is ignored even if present.
const DB = 'bento-tray'
const STORE = 'grant'
@@ -39,10 +47,27 @@ async function readGrant() {
})
}
+/**
+ * The file this message is about, according to the BROWSER.
+ *
+ * Not according to the page: a content script's `sender.url` is stamped by
+ * Chrome. Only `file:` is accepted — the bridge exists for local documents, and
+ * an http page has no business claiming one.
+ */
+export function pathFromSender(sender) {
+ try {
+ const u = new URL(sender?.url ?? '')
+ if (u.protocol !== 'file:') return null
+ return decodeURIComponent(u.pathname)
+ } catch {
+ return null
+ }
+}
+
/** Every file of this name in the granted tree. Depth-limited: a Decks folder
* is not a filesystem, and an unbounded walk on a mistakenly-granted home
* directory would hang the save the user is waiting on. */
-async function findByName(dir, name, depth = 0, found = []) {
+export async function findByName(dir, name, depth = 0, found = []) {
if (depth > 4 || found.length > 1) return found
for await (const [entryName, handle] of dir.entries()) {
if (handle.kind === 'file' && entryName === name) found.push(handle)
@@ -54,38 +79,56 @@ async function findByName(dir, name, depth = 0, found = []) {
return found
}
-/** token → file handle, for the life of this service-worker instance. */
-const claims = new Map()
+/**
+ * Resolve the writable handle for a sender's own file, or say why not.
+ *
+ * THE MATCHING PROBLEM. A page is at `/Users/…/Decks/Q3.bento.html`; a
+ * `FileSystemDirectoryHandle` knows its own NAME but not its path, and no API
+ * exposes one, so the two cannot be compared directly. This searches the
+ * granted tree for that file name and requires EXACTLY ONE match — unambiguous
+ * in the ordinary case, and when it is ambiguous the answer is to decline and
+ * let the browser's own picker handle it. Declining costs a prompt; guessing
+ * costs somebody's file.
+ */
+export async function resolve(sender, deps = {}) {
+ const grant = deps.readGrant ?? readGrant
+ const search = deps.findByName ?? findByName
+
+ const path = pathFromSender(sender)
+ if (!path) return { ok: false, reason: 'not a local file' }
-async function claim(path) {
- const dir = await readGrant()
+ const dir = await grant()
if (!dir) return { ok: false, reason: 'no folder granted' }
- // queryPermission only — never prompt from here. A service worker has no
- // user gesture, so a request would be refused, and a save is the wrong
- // moment to discover that. The options page is where granting happens.
+ // queryPermission only — never prompt from here. A service worker has no user
+ // gesture, so a request would be refused, and a save is the wrong moment to
+ // discover that. The options page is where granting happens.
const perm = await dir.queryPermission({ mode: 'readwrite' })
if (perm !== 'granted') return { ok: false, reason: 'folder grant needs renewing' }
- const name = decodeURIComponent(path.split('/').pop() || '')
+ const name = path.split('/').pop() || ''
if (!name) return { ok: false, reason: 'no file name' }
- const hits = await findByName(dir, name)
+ const hits = await search(dir, name)
if (hits.length !== 1) {
- return { ok: false, reason: hits.length ? `${name} is ambiguous in the granted folder` : 'not in the granted folder' }
+ return {
+ ok: false,
+ reason: hits.length ? `${name} is ambiguous in the granted folder` : 'not in the granted folder',
+ }
}
- const token = crypto.randomUUID()
- claims.set(token, hits[0])
- return { ok: true, token, name }
+ return { ok: true, name, handle: hits[0] }
+}
+
+/** Can this sender's file be written in place? Resolves; writes nothing. */
+export async function claim(sender, deps) {
+ const r = await resolve(sender, deps)
+ return r.ok ? { ok: true, name: r.name } : { ok: false, reason: r.reason }
}
-async function write({ token, text }) {
- const handle = claims.get(token)
- if (!handle) return { ok: false, reason: 'stale claim' }
+/** Write the sender's own file. Re-resolves, so no state is carried. */
+export async function write(sender, text, deps) {
+ const r = await resolve(sender, deps)
+ if (!r.ok) return { ok: false, reason: r.reason }
try {
- // The open question this scaffold cannot settle without being loaded:
- // whether an MV3 service worker may createWritable() on a stored handle,
- // or whether the write must move to an offscreen document. Kept as ONE
- // call so that answer changes this function and nothing else.
- const w = await handle.createWritable()
+ const w = await r.handle.createWritable()
await w.write(text)
await w.close()
return { ok: true, bytes: text.length }
@@ -94,10 +137,14 @@ async function write({ token, text }) {
}
}
-chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
- const run = msg?.op === 'claim' ? claim(msg.payload?.path)
- : msg?.op === 'write' ? write(msg.payload ?? {})
- : Promise.resolve({ ok: false, reason: 'unknown op' })
- run.then(sendResponse, (e) => sendResponse({ ok: false, reason: String(e?.message || e) }))
- return true // async response
-})
+// `chrome` is absent when this module is loaded by the test rig, which imports
+// the logic above and never needs the listener.
+if (typeof chrome !== 'undefined' && chrome.runtime?.onMessage) {
+ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
+ const run = msg?.op === 'claim' ? claim(sender)
+ : msg?.op === 'write' ? write(sender, msg.payload?.text ?? '')
+ : Promise.resolve({ ok: false, reason: 'unknown op' })
+ run.then(sendResponse, (e) => sendResponse({ ok: false, reason: String(e?.message || e) }))
+ return true // async response
+ })
+}
diff --git a/tray/webext/src/page-bridge.js b/tray/webext/src/page-bridge.js
index 92f97808..2ccd81e5 100644
--- a/tray/webext/src/page-bridge.js
+++ b/tray/webext/src/page-bridge.js
@@ -129,7 +129,11 @@
if (native) return native(forNative(opts))
throw new DOMException('No file picker available', 'AbortError')
}
- const claim = await ask('claim', { path: decodeURIComponent(window.location.pathname) })
+ // No path is sent: the extension takes it from `sender.url`, which the
+ // browser stamps and this page cannot forge. A local HTML file is untrusted
+ // content, and one that could name its own target could name someone else's
+ // deck in the granted folder.
+ const claim = await ask('claim')
if (!claim?.ok) {
// Say WHY. Falling through to the native picker is the safe outcome, but
// an unexplained dialog is indistinguishable from the extension not being
@@ -156,7 +160,7 @@
? chunks[0]
: new Blob(chunks)
const text = await blob.text()
- const res = await ask('write', { token: claim.token, text })
+ const res = await ask('write', { text })
if (!res?.ok) throw new DOMException(res?.reason || 'write failed', 'NotAllowedError')
console.info('[bento-tray] wrote', claim.name, `(${res.bytes} bytes) in place`)
},