Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

kernel: remember the file handle across reopens — gated to real origins (#533)

nyblnet299e4e039b7c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3c08850b..d88e5476 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -627,6 +627,15 @@ jobs:
# every host silently loses the distinction.
run: node scripts/test-savepurpose.ts
+ - name: Remember-the-file-handle rig
+ # A deck in ~/Documents or ~/Downloads can never be covered by a
+ # directory grant (Chrome's blocklist), so it re-ran the save picker on
+ # every reopen. The FILE handle is remembered (IndexedDB by docId) and
+ # reconnected with a permission prompt inside the save gesture. Guards:
+ # name-match, denied/NotFound -> picker + drop, only a real handle (never
+ # a host polyfill), reconnect BEFORE serialize so activation stays fresh.
+ run: node scripts/test-file-handle.ts
+
- name: Guarded storage rig
# localStorage's absence is hostile: reading the PROPERTY throws, so
# `if (localStorage)` is itself the crash and one bare read at module
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6e0c8abb..5d4dba16 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,15 @@ pre-1.0.
## [Unreleased]
+- **A document in Downloads or Documents remembers where it lives.** Chrome
+ will not let any app hold a standing grant to those folders, so a deck kept
+ there used to show the full save dialog on every reopen. Bento now remembers
+ the file itself: the first ⌘S after you reopen asks once — Chrome offers
+ "Allow on every visit" — and after that it saves silently in place, like a
+ deck that never left. Move or delete the file and it simply asks again. This
+ is for a deck opened from a real web address or through the iOS, Android or
+ browser-extension apps; a deck opened straight from disk keeps asking each
+ time, by the same rule that isolates local files from each other.
- **Collaborators stop flickering in and out.** A person whose tab was in the
background appeared to leave and rejoin about once a minute: a browser slows a
hidden tab's timers to roughly one tick a minute, so their "still here" beat
diff --git a/kernel/src/save.ts b/kernel/src/save.ts
index d8ae7038..380bf0b3 100644
--- a/kernel/src/save.ts
+++ b/kernel/src/save.ts
@@ -9,6 +9,7 @@
import type { KernelDoc } from './doc.ts'
import { appConfig } from './app.ts'
+import { sharedStorageOrigin } from './net.ts'
const DATA_BLOCK_ID = 'bento-doc'
// Split so the literal never appears in the bundle (it would terminate the
@@ -641,11 +642,119 @@ export function downloadFile(html: string, name: string) {
setTimeout(() => URL.revokeObjectURL(url), 5000)
}
+// --- remembering the file handle across reopens -----------------------------
+//
+// Chrome's File System Access blocklist refuses ~/Documents, ~/Downloads, the
+// Desktop and the home folder as DIRECTORY grants, so a deck sitting directly in
+// one of them can never be covered by a bento/home folder grant and re-ran the
+// full save picker on every reopen. FILE handles are not blocked and are
+// structured-cloneable, so we remember the one a save produced (IndexedDB, keyed
+// by docId) and, on the first ⌘S after a reopen, re-request readwrite permission
+// INSIDE the save gesture — Chrome 122+ shows a small "Allow on every visit"
+// prompt instead of a picker. Only a real FileSystemFileHandle is stored: a host
+// polyfill (home/ios, home/webext) hands back its own handle, which is not one
+// and stays on the bridge path untouched.
+
+const HANDLE_DB = 'bento-handles'
+const HANDLE_STORE = 'handles'
+
+function handleDb(): Promise<IDBDatabase> {
+ return new Promise((resolve, reject) => {
+ const req = indexedDB.open(HANDLE_DB, 1)
+ req.onupgradeneeded = () => { req.result.createObjectStore(HANDLE_STORE) }
+ req.onsuccess = () => resolve(req.result)
+ req.onerror = () => reject(req.error)
+ })
+}
+async function idbHandle(op: 'get' | 'put' | 'delete', docId: string, val?: unknown): Promise<unknown> {
+ const db = await handleDb()
+ try {
+ return await new Promise((resolve, reject) => {
+ const tx = db.transaction(HANDLE_STORE, op === 'get' ? 'readonly' : 'readwrite')
+ const store = tx.objectStore(HANDLE_STORE)
+ const r = op === 'get' ? store.get(docId) : op === 'put' ? store.put(val, docId) : store.delete(docId)
+ r.onsuccess = () => resolve(op === 'get' ? r.result : undefined)
+ r.onerror = () => reject(r.error)
+ })
+ } finally { db.close() }
+}
+
+/** A FileSystemFileHandle with the permission methods (not in every lib.dom). */
+type PermHandle = FsFileHandle & {
+ queryPermission(d: { mode: 'readwrite' }): Promise<PermissionState>
+ requestPermission(d: { mode: 'readwrite' }): Promise<PermissionState>
+}
+const isRealHandle = (h: unknown): h is PermHandle =>
+ typeof FileSystemFileHandle !== 'undefined' && h instanceof FileSystemFileHandle
+
+/** Remember the handle a save produced so the next reopen can reconnect it.
+ * Only ever reached from saveFile — a readonly player never saves, so its
+ * handle is never stored — and only a real handle, never a host polyfill.
+ *
+ * NOT on a shared-storage origin. Chrome gives every file:// document one
+ * IndexedDB, so a stored handle is a live write capability any other local
+ * deck could read and re-permission (docs/DECISIONS.md, security-review-pr519).
+ * There a persistent grant has no identity to bind to, so it is not offered;
+ * the per-session handle still works. Real web origins and real-origin host
+ * apps (isolated storage) persist as normal. */
+async function persistHandle(doc: KernelDoc, handle: FsFileHandle): Promise<void> {
+ if (sharedStorageOrigin() || !doc.docId || !isRealHandle(handle)) return
+ try { await idbHandle('put', doc.docId, handle) } catch { /* best effort — a lost handle just means tomorrow's picker */ }
+}
+
+/**
+ * First ⌘S after a reopen: if we remember a handle for this docId, re-acquire
+ * permission inside the save gesture instead of showing the picker. Returns the
+ * handle when permission is granted, else null (the caller falls back to the
+ * picker). Exported for the rig.
+ *
+ * MUST run before the expensive serializeAuto so the user activation the save
+ * gesture carries is still fresh when requestPermission() prompts (Chrome keeps
+ * transient activation ~5 s across awaits; a ~1 s serialize would risk it).
+ */
+export async function reconnectHandle(doc: KernelDoc): Promise<FsFileHandle | null> {
+ // Never reconnect from shared storage. On a file:// origin the store is shared
+ // with every local deck, so an entry found here could have been planted by a
+ // malicious file — keyed to this docId and named to match the file on screen,
+ // which would make the name check below pass and re-permission a handle to a
+ // DIFFERENT file on the user's own ⌘S (security-review-pr519, finding 1). We
+ // also never write there (persistHandle), but refusing to READ is what closes
+ // the planted-entry path. Real, isolated origins reconnect as normal.
+ if (sharedStorageOrigin()) return null
+ if (!doc.docId) return null
+ let stored: unknown
+ try { stored = await idbHandle('get', doc.docId) } catch { return null }
+ if (!isRealHandle(stored)) return null // absent, or a host polyfill handle
+ // the remembered handle must be the file on screen: docId + name. isSameEntry
+ // needs a second handle we do not have on a bare file:// reopen, so the name
+ // check is the guard.
+ const onScreen = openedFileName()
+ if (onScreen && stored.name !== onScreen) return null // mismatch → picker, entry kept
+ try {
+ let perm = await stored.queryPermission({ mode: 'readwrite' })
+ if (perm !== 'granted') perm = await stored.requestPermission({ mode: 'readwrite' })
+ if (perm === 'granted') return stored
+ void idbHandle('delete', doc.docId) // denied → forget it, use the picker
+ return null
+ } catch { // NotFoundError (file moved/deleted) or any handle failure
+ void idbHandle('delete', doc.docId)
+ return null
+ }
+}
+
/**
* Save the document. Chrome/Edge: File System Access API (picker on first
- * save, silent rewrite after). Firefox/Safari: download a copy.
+ * save, silent rewrite after — and, since a remembered handle can reconnect,
+ * one permission prompt rather than a picker on the first save after a reopen).
+ * Firefox/Safari: download a copy.
*/
export async function saveFile(doc: KernelDoc, forcePicker = false): Promise<SaveResult> {
+ // Reconnect a remembered handle BEFORE serializing: requestPermission() has to
+ // fire inside the fresh save gesture, and serializeAuto can take ~a second.
+ if (hasFsAccess() && !forcePicker && !fileHandle) {
+ const re = await reconnectHandle(doc)
+ if (re) fileHandle = re
+ }
const html = await serializeAuto(doc)
if (hasFsAccess()) {
if (forcePicker || !fileHandle) {
@@ -655,9 +764,13 @@ export async function saveFile(doc: KernelDoc, forcePicker = false): Promise<Sav
if (!handle) return 'cancelled'
fileHandle = handle
await writeHandle(handle, html)
+ void persistHandle(doc, handle)
return 'saved-as'
}
await writeHandle(fileHandle, html)
+ // idempotent, and the one place the ADOPTED-handle path (a dropped file) is
+ // remembered too — it only matters once you have actually saved to it.
+ void persistHandle(doc, fileHandle)
return 'saved'
}
downloadFile(html, suggestedFileName(doc))
diff --git a/scripts/test-file-handle.ts b/scripts/test-file-handle.ts
new file mode 100644
index 00000000..a926a393
--- /dev/null
+++ b/scripts/test-file-handle.ts
@@ -0,0 +1,187 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Remember-the-file-handle rig (kernel/src/save.ts reconnectHandle).
+//
+// node scripts/test-file-handle.ts
+//
+// WHAT THIS PROVES. Chrome's File System Access blocklist refuses ~/Documents
+// and ~/Downloads as directory grants, so a deck there re-ran the full save
+// picker on every reopen. We now remember the FILE handle (IndexedDB, by docId)
+// and re-request permission inside the save gesture. The behaviour that matters
+// is all in reconnectHandle — serializeAuto/writeHandle need a real DOM and a
+// picker, so saveFile itself is asserted at source (that it reconnects BEFORE
+// serialize, to keep the user activation fresh). The reconnect paths are driven
+// here against a fake IndexedDB and a fake FileSystemFileHandle.
+
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { dirname, join } from 'node:path'
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+
+let failures = 0, checks = 0
+function ok(cond: boolean, msg: string) { checks++; if (!cond) { failures++; console.log(` FAIL ${msg}`) } else console.log(` ok ${msg}`) }
+
+// --- the world save.ts's handle code expects --------------------------------
+// A minimal IndexedDB backed by one Map (the 'handles' store), so the rig can
+// seed a stored handle and inspect what reconnect left behind.
+const store = new Map<string, unknown>()
+;(globalThis as Record<string, unknown>).indexedDB = {
+ open() {
+ const req: Record<string, unknown> = {}
+ Promise.resolve().then(() => {
+ const request = (fn: () => unknown) => {
+ const r: Record<string, unknown> = {}
+ Promise.resolve().then(() => { try { r.result = fn(); (r.onsuccess as (() => void))?.() } catch (e) { r.error = e; (r.onerror as (() => void))?.() } })
+ return r
+ }
+ req.result = {
+ createObjectStore() {},
+ transaction() {
+ return { objectStore() {
+ return {
+ get: (k: string) => request(() => store.get(k)),
+ put: (v: unknown, k: string) => request(() => { store.set(k, v); return undefined }),
+ delete: (k: string) => request(() => { store.delete(k); return undefined }),
+ }
+ } }
+ },
+ close() {},
+ }
+ ;(req.onupgradeneeded as (() => void))?.()
+ ;(req.onsuccess as (() => void))?.()
+ })
+ return req
+ },
+}
+
+// A fake FileSystemFileHandle: instanceof is the real guard, so this IS the
+// global. Options steer the permission answers and a thrown error.
+class FakeFSHandle {
+ name: string
+ queryCalls = 0
+ requestCalls = 0
+ private q: string
+ private r: string
+ private throwName?: string
+ constructor(name: string, opts: { q?: string; r?: string; throwName?: string } = {}) {
+ this.name = name; this.q = opts.q ?? 'granted'; this.r = opts.r ?? 'granted'; this.throwName = opts.throwName
+ }
+ async queryPermission() { this.queryCalls++; if (this.throwName) { const e = new Error('x') as Error & { name: string }; e.name = this.throwName; throw e } return this.q }
+ async requestPermission() { this.requestCalls++; return this.r }
+}
+;(globalThis as Record<string, unknown>).FileSystemFileHandle = FakeFSHandle
+// A real, isolated web origin — persistence and reconnect are ON here. (The
+// file:// shared-origin gate is exercised in its own block near the end.)
+;(globalThis as Record<string, unknown>).location = { href: 'https://bento.page/Q3-board.bento.html', protocol: 'https:', origin: 'https://bento.page' }
+;(globalThis as Record<string, unknown>).self = { origin: 'https://bento.page' }
+const ON_SCREEN = 'Q3-board.bento.html'
+
+const { reconnectHandle } = await import('../kernel/src/save.ts')
+const DOC = { docId: 'd1', title: 'Q3' }
+const reset = () => store.clear()
+const has = () => store.has('d1')
+// the drop on denied/NotFound is fire-and-forget (void) so the save is not held
+// on it — in production the picker interaction gives it ample time; here, let the
+// microtasks flush before asserting the entry is gone.
+const settle = () => new Promise((r) => setTimeout(r, 10))
+
+// 1. remembered + already granted → reconnect, no prompt, entry kept
+{
+ reset(); const h = new FakeFSHandle(ON_SCREEN, { q: 'granted' }); store.set('d1', h)
+ const got = await reconnectHandle(DOC as never)
+ ok(got === (h as never), 'a granted handle reconnects (no picker)')
+ ok(h.requestCalls === 0, 'and does not prompt when permission is already granted')
+ ok(has(), 'the entry is kept')
+}
+// 2. remembered, permission prompt → granted → reconnect (the "one prompt then silent" case)
+{
+ reset(); const h = new FakeFSHandle(ON_SCREEN, { q: 'prompt', r: 'granted' }); store.set('d1', h)
+ const got = await reconnectHandle(DOC as never)
+ ok(got === (h as never) && h.requestCalls === 1, 'a prompt that the user grants reconnects the handle')
+ ok(has(), 'the entry is kept after a granted prompt')
+}
+// 3. denied → null (picker) AND the entry is dropped
+{
+ reset(); const h = new FakeFSHandle(ON_SCREEN, { q: 'prompt', r: 'denied' }); store.set('d1', h)
+ const got = await reconnectHandle(DOC as never)
+ ok(got === null, 'a denied prompt falls back to the picker')
+ await settle()
+ ok(!has(), 'and the stored entry is dropped')
+}
+// 4. NotFoundError (file moved/deleted) → null (picker) AND the entry is dropped
+{
+ reset(); const h = new FakeFSHandle(ON_SCREEN, { throwName: 'NotFoundError' }); store.set('d1', h)
+ const got = await reconnectHandle(DOC as never)
+ ok(got === null, 'a moved/deleted file (NotFoundError) falls back to the picker')
+ await settle()
+ ok(!has(), 'and the stored entry is dropped')
+}
+// 5. name mismatch → null (picker), no prompt, entry KEPT (it is not proven stale)
+{
+ reset(); const h = new FakeFSHandle('Other.bento.html', { q: 'granted' }); store.set('d1', h)
+ const got = await reconnectHandle(DOC as never)
+ ok(got === null, 'a handle whose name is not the file on screen is not used')
+ ok(h.queryCalls === 0 && h.requestCalls === 0, 'and it is rejected before touching permissions')
+ ok(has(), 'the entry is kept on a mere name mismatch')
+}
+// 6. a host polyfill handle (not a FileSystemFileHandle) → skipped, entry kept
+{
+ reset(); const poly = { name: ON_SCREEN, async queryPermission() { return 'granted' }, async requestPermission() { return 'granted' } }
+ store.set('d1', poly)
+ const got = await reconnectHandle(DOC as never)
+ ok(got === null, 'a host polyfill handle is never reconnected (the bridge path owns it)')
+ ok(has(), 'and it is left in place, harmless')
+}
+// 7. nothing remembered → null
+{
+ reset()
+ ok((await reconnectHandle(DOC as never)) === null, 'no stored handle → null (first-ever save picks)')
+}
+
+// 8. SHARED file:// ORIGIN: persistence off, and a planted entry is never used.
+// Chrome gives every file:// deck one IndexedDB, so a malicious local file can
+// plant a handle keyed to this docId and NAMED to match the file on screen —
+// the name check alone would pass. The shared-origin gate must refuse to read
+// it at all, so the victim's handle is never re-permissioned on the user's ⌘S.
+{
+ ;(globalThis as Record<string, unknown>).location = { href: 'file:///Users/x/Downloads/Q3-board.bento.html', protocol: 'file:', origin: 'null' }
+ ;(globalThis as Record<string, unknown>).self = { origin: 'null' }
+ reset()
+ const planted = new FakeFSHandle(ON_SCREEN, { q: 'granted' }) // forged: matches the file on screen
+ store.set('d1', planted)
+ const got = await reconnectHandle(DOC as never)
+ ok(got === null, 'on a shared file:// origin a planted, name-matching entry is NEVER reconnected')
+ ok(planted.queryCalls === 0 && planted.requestCalls === 0, 'and permission is never requested on it (the forgery is blocked before any prompt)')
+ ok(store.has('d1'), 'the shared store is not touched — we neither read into nor delete from it')
+ // restore a real origin for the source block below (origin-independent, but tidy)
+ ;(globalThis as Record<string, unknown>).location = { href: 'https://bento.page/Q3-board.bento.html', protocol: 'https:', origin: 'https://bento.page' }
+ ;(globalThis as Record<string, unknown>).self = { origin: 'https://bento.page' }
+}
+
+// --- the shared-origin gate is on both the read and the write path ----------
+{
+ const src = readFileSync(join(root, 'kernel/src/save.ts'), 'utf8')
+ const persist = src.slice(src.indexOf('async function persistHandle'), src.indexOf('async function persistHandle') + 400)
+ const reconnect = src.slice(src.indexOf('export async function reconnectHandle'), src.indexOf('export async function reconnectHandle') + 700)
+ ok(/sharedStorageOrigin\(\)/.test(persist), 'persistHandle does not store on a shared-storage origin')
+ ok(/if \(sharedStorageOrigin\(\)\) return null/.test(reconnect), 'reconnectHandle refuses to read on a shared-storage origin')
+}
+
+// --- saveFile must reconnect BEFORE it serializes ---------------------------
+// requestPermission() has to fire inside the fresh save gesture; serializeAuto
+// can take ~a second and would age out the transient activation. Asserted at
+// source because the write path needs a DOM.
+{
+ const src = readFileSync(join(root, 'kernel/src/save.ts'), 'utf8')
+ const body = src.slice(src.indexOf('export async function saveFile'))
+ const reAt = body.indexOf('reconnectHandle(doc)')
+ const serAt = body.indexOf('serializeAuto(doc)')
+ ok(reAt > 0 && serAt > 0 && reAt < serAt, 'saveFile calls reconnectHandle BEFORE serializeAuto (activation stays fresh)')
+ ok(/void persistHandle\(doc, handle\)/.test(body) && /void persistHandle\(doc, fileHandle\)/.test(body),
+ 'saveFile persists the handle on both the picked and the reconnected/adopted save')
+ ok(/instanceof FileSystemFileHandle/.test(src), 'only a real FileSystemFileHandle is stored (host polyfill skipped)')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)