Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

save: key a remembered file handle by docId + file name (#556) (#696)

nyblneta617a17c98a7
diff --git a/kernel/src/save.ts b/kernel/src/save.ts
index a9bab2c9..0d608329 100644
--- a/kernel/src/save.ts
+++ b/kernel/src/save.ts
@@ -697,19 +697,28 @@ function handleDb(): Promise<IDBDatabase> {
req.onerror = () => reject(req.error)
})
}
-async function idbHandle(op: 'get' | 'put' | 'delete', docId: string, val?: unknown): Promise<unknown> {
+async function idbHandle(op: 'get' | 'put' | 'delete', key: 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)
+ const r = op === 'get' ? store.get(key) : op === 'put' ? store.put(val, key) : store.delete(key)
r.onsuccess = () => resolve(op === 'get' ? r.result : undefined)
r.onerror = () => reject(r.error)
})
} finally { db.close() }
}
+/** The store key for one FILE's handle. A copy shares its origin's docId
+ * ("Save a copy…" is the same deck, same live session), so keying by docId
+ * ALONE let the last-saved file evict the other's handle: saving a copy
+ * overwrote the original's entry, and reopening the original then fell back to
+ * the picker (#556). Keying by docId AND file name gives each file its own
+ * entry — correct whichever deck "Save a copy…" leaves open, because it keys
+ * by the file that was actually written. U+001F can't occur in a file name. */
+const handleKey = (docId: string, name: string) => `${docId}\u001f${name}`
+
/** A FileSystemFileHandle with the permission methods (not in every lib.dom). */
type PermHandle = FsFileHandle & {
queryPermission(d: { mode: 'readwrite' }): Promise<PermissionState>
@@ -728,9 +737,10 @@ const isRealHandle = (h: unknown): h is PermHandle =>
* 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> {
+export 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 */ }
+ // Per FILE (docId + name), not per docId — see handleKey (#556).
+ try { await idbHandle('put', handleKey(doc.docId, handle.name), handle) } catch { /* best effort — a lost handle just means tomorrow's picker */ }
}
/**
@@ -753,22 +763,33 @@ export async function reconnectHandle(doc: KernelDoc): Promise<FsFileHandle | nu
// the planted-entry path. Real, isolated origins reconnect as normal.
if (sharedStorageOrigin()) return null
if (!doc.docId) return null
+ // The remembered handle must be the file ON SCREEN, and the only check we have
+ // on a bare reopen is its NAME (isSameEntry needs a second handle we do not
+ // have). With no name on screen — the hosted app, nothing open — there is
+ // nothing to verify against, so we do NOT reconnect: reading a docId-only entry
+ // unchecked could re-permission a handle to a different file. A real reopen
+ // always has a name.
+ const onScreen = openedFileName()
+ if (!onScreen) return null
+ // Primary key is per FILE (docId + name). Fall back to the legacy docId-only
+ // key for entries written before #556 — the name guard below validates it too,
+ // so the fallback is no weaker than the primary.
+ let key = handleKey(doc.docId, onScreen)
let stored: unknown
- try { stored = await idbHandle('get', doc.docId) } catch { return null }
+ try {
+ stored = await idbHandle('get', key)
+ if (!isRealHandle(stored)) { key = doc.docId; stored = await idbHandle('get', key) }
+ } 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
+ if (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
+ void idbHandle('delete', key) // denied → forget it, use the picker
return null
} catch { // NotFoundError (file moved/deleted) or any handle failure
- void idbHandle('delete', doc.docId)
+ void idbHandle('delete', key)
return null
}
}
diff --git a/scripts/test-file-handle.ts b/scripts/test-file-handle.ts
index 72a7dfea..2cf863f6 100644
--- a/scripts/test-file-handle.ts
+++ b/scripts/test-file-handle.ts
@@ -77,7 +77,7 @@ class FakeFSHandle {
;(globalThis as Record<string, unknown>).self = { origin: 'https://bento.page' }
const ON_SCREEN = 'Q3-board.bento.html'
-const { reconnectHandle, consumeLaunchQueue, hasFileHandle, currentFileName, writeUpdatedFile, encodeDocBody, setEncryptionPassword, parseEnvelope, decryptEnvelope, adoptFileHandle, embeddedDocBlock } = await import('../kernel/src/save.ts')
+const { reconnectHandle, persistHandle, consumeLaunchQueue, hasFileHandle, currentFileName, writeUpdatedFile, encodeDocBody, setEncryptionPassword, parseEnvelope, decryptEnvelope, adoptFileHandle, embeddedDocBlock } = await import('../kernel/src/save.ts')
const DOC = { docId: 'd1', title: 'Q3' }
const reset = () => store.clear()
const has = () => store.has('d1')
@@ -139,6 +139,62 @@ const settle = () => new Promise((r) => setTimeout(r, 10))
ok((await reconnectHandle(DOC as never)) === null, 'no stored handle → null (first-ever save picks)')
}
+// 7b. #556 — "Save a copy…" must not evict the original's remembered handle.
+// A copy shares the original's docId, so a docId-only key let the copy's save
+// overwrite the original's entry; reopening the original then fell to the picker.
+// Drive the REAL persist→reconnect cycle (per-file keying), both reopen orders.
+// At an original web origin, each file lives at its own URL, so openedFileName()
+// (location basename here) is how "which file is on screen" is set.
+{
+ const atFile = (name: string) => {
+ ;(globalThis as Record<string, unknown>).location = { href: `https://bento.page/${name}`, protocol: 'https:', origin: 'https://bento.page' }
+ }
+ reset()
+ const original = new FakeFSHandle('Q3-board.bento.html', { q: 'granted' })
+ const copy = new FakeFSHandle('Q3-copy.bento.html', { q: 'granted' })
+ // save the original, then Save a copy… (same docId d1, different file)
+ atFile('Q3-board.bento.html'); await persistHandle(DOC as never, original as never)
+ atFile('Q3-copy.bento.html'); await persistHandle(DOC as never, copy as never)
+ ok(store.size === 2, 'the copy gets its OWN entry — it does not evict the original (two files, two handles)')
+ // reopen the ORIGINAL
+ atFile('Q3-board.bento.html')
+ ok((await reconnectHandle(DOC as never)) === (original as never),
+ 'reopening the original reconnects the original\'s handle (no picker) — the #556 fix')
+ // reopen the COPY
+ atFile('Q3-copy.bento.html')
+ ok((await reconnectHandle(DOC as never)) === (copy as never),
+ 'reopening the copy reconnects the copy\'s handle')
+ ;(globalThis as Record<string, unknown>).location = { href: 'https://bento.page/Q3-board.bento.html', protocol: 'https:', origin: 'https://bento.page' }
+}
+// 7c. a legacy docId-only entry (written before #556) still reconnects, via the
+// fallback, and is still name-checked.
+{
+ reset()
+ const legacy = new FakeFSHandle(ON_SCREEN, { q: 'granted' })
+ store.set('d1', legacy) // the pre-#556 key: docId alone
+ ok((await reconnectHandle(DOC as never)) === (legacy as never),
+ 'a legacy docId-only entry reconnects through the fallback')
+ reset()
+ const legacyWrong = new FakeFSHandle('Other.bento.html', { q: 'granted' })
+ store.set('d1', legacyWrong)
+ ok((await reconnectHandle(DOC as never)) === null,
+ 'and a legacy entry whose name is not the file on screen is still rejected (name guard holds on the fallback)')
+}
+
+// 7d. #556 edge (security): with NO file name on screen (the hosted app, nothing
+// open — openedFileName() is null), a docId-only entry must NOT reconnect: there
+// is no name to verify it against, and a real reopen always has one.
+{
+ reset()
+ ;(globalThis as Record<string, unknown>).location = { href: 'https://bento.page/', protocol: 'https:', origin: 'https://bento.page' } // no .bento.html basename → openedFileName() === null
+ const h = new FakeFSHandle('anything.bento.html', { q: 'granted' })
+ store.set('d1', h) // a legacy docId-only entry
+ ok((await reconnectHandle(DOC as never)) === null, 'with no file name on screen, a docId-only entry is not reconnected (no name to check → picker)')
+ ok(h.queryCalls === 0 && h.requestCalls === 0, 'and its permission is never touched')
+ ok(store.has('d1'), 'the entry is kept (not proven stale)')
+ ;(globalThis as Record<string, unknown>).location = { href: 'https://bento.page/Q3-board.bento.html', protocol: 'https:', origin: 'https://bento.page' }
+}
+
// 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 —