Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

kernel: a launched handle is adopted only if its file is still this document (replaces #652) (#654)

nyblnet1f231605f04e
diff --git a/kernel/src/save.ts b/kernel/src/save.ts
index 6c0a8ee9..a9bab2c9 100644
--- a/kernel/src/save.ts
+++ b/kernel/src/save.ts
@@ -46,6 +46,29 @@ export function readEmbeddedDoc(): string | null {
return text || null
}
+/**
+ * The `#bento-doc` body from an HTML string — the file as bytes, not the live
+ * DOM — so a handle's current file can be checked against the open document
+ * without a parser (it runs in the launch consumer AND in a node rig). This proves
+ * SAME DOCUMENT (an identical #bento-doc body), NOT same file: a copy re-saved with
+ * a different surrounding shell still matches, which is exactly what the launch
+ * check wants. Anchored by indexOf on the exact id attribute — double-quoted as the
+ * DOM serializes it, with a LEADING SPACE so it can never match a `data-id`
+ * lookalike — which is linear, where a regex over an unterminated `<script` is
+ * quadratic. CRLF is normalised so a file saved with CRLF line endings still
+ * compares equal. The body is <-escaped at write time so it can never itself
+ * contain the close tag. null if there is no block. */
+const DOC_BLOCK_ID_ATTR = ` id="${DATA_BLOCK_ID}"`
+export function embeddedDocBlock(html: string): string | null {
+ const at = html.indexOf(DOC_BLOCK_ID_ATTR)
+ if (at < 0) return null
+ const start = html.indexOf('>', at + DOC_BLOCK_ID_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
+}
+
/**
* Extra plaintext blocks the app wants written into every saved shell —
* language packs today (docs/i18n-packs.md), whatever else later. The kernel
@@ -506,6 +529,7 @@ type SaveResult = 'saved' | 'saved-as' | 'downloaded' | 'cancelled'
interface FsFileHandle {
createWritable(): Promise<{ write(data: Blob): Promise<void>; close(): Promise<void> }>
+ getFile?(): Promise<{ text(): Promise<string> }>
name: string
}
@@ -828,10 +852,25 @@ export function consumeLaunchQueue(): void {
}
const lq = w.launchQueue
if (!lq || typeof lq.setConsumer !== 'function') return
+ // The open document's #bento-doc, captured now (boot, before any edit), CRLF
+ // normalised to match embeddedDocBlock. The handle we adopt must still hold THIS
+ // document: a host bug that vends the wrong file would otherwise have the first
+ // autosave silently overwrite it.
+ const booted = readEmbeddedDoc()?.replace(/\r\n/g, '\n') ?? null
try {
- lq.setConsumer((params) => {
+ lq.setConsumer(async (params) => {
const handle = params?.files?.[0]
- if (handle) adoptFileHandle(handle) // only when the host actually vended one
+ if (!handle || !booted || typeof handle.getFile !== 'function') return
+ try {
+ const text = await (await handle.getFile()).text()
+ // Adopt only if the file is still this document AND nothing claimed a handle
+ // while we awaited getFile: a Save As / "Duplicate as new deck" during that
+ // await sets its own handle, and snapping back to the launched file here
+ // would have autosave overwrite the file the user just moved to.
+ if (!hasFileHandle() && embeddedDocBlock(text) === booted) adoptFileHandle(handle)
+ // else: a different/unverifiable file, or a handle already held — leave it;
+ // ⌘S falls back to the picker.
+ } catch { /* unreadable handle → do not adopt */ }
})
} catch { /* setConsumer rejects a second registration — the first already won */ }
}
diff --git a/scripts/test-file-handle.ts b/scripts/test-file-handle.ts
index 7713e7c3..72a7dfea 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 } = await import('../kernel/src/save.ts')
+const { reconnectHandle, 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')
@@ -183,6 +183,27 @@ const settle = () => new Promise((r) => setTimeout(r, 10))
ok(/instanceof FileSystemFileHandle/.test(src), 'only a real FileSystemFileHandle is stored (host polyfill skipped)')
}
+// --- embeddedDocBlock: the string-level #bento-doc extractor ------------------
+// It reads the block from file BYTES (so the launch check runs with no parser),
+// anchored by indexOf on the exact ` id="bento-doc"` attribute.
+console.log('\nembeddedDocBlock reads the #bento-doc body from file bytes')
+{
+ // the block body is opaque to the extractor (it is whatever bytes sit there), so
+ // an interior newline is possible; the boot DOM holds it as LF (HTML parsing
+ // normalises), a file on disk may hold it as CRLF. A multi-line body proves the
+ // normalise does real work — with single-line JSON, trim alone would hide it.
+ const body = '{"docId":"x",\n"title":"T"}'
+ const close = '</scr' + 'ipt>'
+ const file = (b: string) => `<!doctype html><head><script type="application/json" id="bento-doc">\n${b}\n${close}</head>`
+ ok(embeddedDocBlock(file(body)) === body, 'extracts the #bento-doc body')
+ ok(embeddedDocBlock(file(body.replace(/\n/g, '\r\n'))) === body,
+ 'CRLF line endings (surrounding AND interior) normalise to the LF body — a CRLF file still compares equal')
+ // a data-id lookalike must NOT be mistaken for the real block (the old \bid regex did)
+ const lookalike = `<script data-id="bento-doc">\nDECOY\n${close}` + file(body)
+ ok(embeddedDocBlock(lookalike) === body, 'a data-id="bento-doc" lookalike is skipped; the real id block is read')
+ ok(embeddedDocBlock('<html>no block here</html>') === null, 'no block → null')
+}
+
// --- launchQueue: a launched document holds a writable handle at boot ---------
// A page opened in a native host or an installed PWA held NO handle until its
// first Cmd-S, so autosave only snapshotted to IndexedDB and the file on disk
@@ -190,84 +211,116 @@ const settle = () => new Promise((r) => setTimeout(r, 10))
// delivers, so autosave's `if (hasFileHandle())` path (editor.ts) writes the FILE
// from the first edit. These drive the consumer against a fake launchQueue; the
// module import itself is a no-op here (node has no window).
-console.log('\nlaunchQueue: a launched document is writable from the first edit')
+console.log('\nlaunchQueue adopts the open document — and only it')
{
- // a writable handle like the one home/bridge.js vends (makeHandle): name, kind,
- // createWritable — records whether bytes reached it.
- const written: string[] = []
- const launched = {
- kind: 'file', name: ON_SCREEN,
- async createWritable() { return { async write(s: string) { written.push(s) }, async close() {} } },
+ const DOC = { docId: 'launch-doc', title: 'Secret Q3 numbers', format: 'bento/slides', slides: [] }
+ const MARKER = 'Secret Q3 numbers' // content that must never appear in an encrypted file
+ const BOOT = JSON.stringify(DOC) // the open document's #bento-doc body
+ const esc = (s: string) => s.replace(/</g, '\\u003c')
+ // the live page holds the open doc's #bento-doc (escaped, as a file does)
+ ;(globalThis as Record<string, unknown>).document = {
+ getElementById: (id: string) => (id === 'bento-doc' ? { textContent: '\n' + esc(BOOT) + '\n' } : null),
}
- // a queue the rig controls: setConsumer hands the consumer one params object
- const setQueue = (params: { files?: unknown[] } | null) => {
- ;(globalThis as Record<string, unknown>).launchQueue = params === null ? undefined
- : { setConsumer(fn: (p: unknown) => void) { fn(params) } }
+ const fileWith = (body: string) =>
+ `<!doctype html><html><head><script type="application/json" id="bento-doc">\n${esc(body)}\n` +
+ `</scr` + `ipt></head><body></body></html>`
+ // a handle: getFile() yields its CURRENT file; createWritable() captures writes.
+ // fileBody null = unreadable (getFile throws); omit getFile = cannot be verified.
+ const handle = (fileBody: string | null, opts: { noGetFile?: boolean } = {}) => {
+ let got: Blob | null = null
+ const h: Record<string, unknown> = {
+ kind: 'file', name: ON_SCREEN, wrote: async () => (got ? await got.text() : ''),
+ async createWritable() { return { async write(b: Blob) { got = b }, async close() {} } },
+ }
+ if (!opts.noGetFile) h.getFile = async () => {
+ if (fileBody === null) throw new Error('unreadable')
+ return { text: async () => fileWith(fileBody) }
+ }
+ return h
+ }
+ let pending: unknown
+ const vend = async (files: unknown[] | null) => {
+ ;(globalThis as Record<string, unknown>).launchQueue = files === null ? undefined
+ : { setConsumer(fn: (p: unknown) => void) { pending = fn({ files }) } }
+ pending = undefined
+ consumeLaunchQueue()
+ await pending // the consumer reads the file and verifies BEFORE it adopts
}
- ok(!hasFileHandle(), 'no handle before a launch (so autosave would only snapshot — the bug)')
-
- setQueue(null)
- consumeLaunchQueue()
- ok(!hasFileHandle(), 'no launchQueue (plain tab / node) → nothing adopted, no throw')
-
- setQueue({ files: [] }) // a host that refused the launch (e.g. a read-only doc) vends nothing
- consumeLaunchQueue()
- ok(!hasFileHandle(), 'a refused launch (empty files) adopts nothing')
+ ok(!hasFileHandle(), 'no handle before a launch (autosave would only snapshot — the bug)')
+ await vend(null); ok(!hasFileHandle(), 'no launchQueue (plain tab / node) → nothing adopted, no throw')
+ await vend([]); ok(!hasFileHandle(), 'a refused launch (empty files) adopts nothing')
- // (c) with no vended handle, the write path writes NOTHING — it throws rather
- // than touch a file it was never given. (fileHandle is still null here.)
+ // (c) with no handle, the write path writes NOTHING — it throws, touches no file
let threw = false
try { await writeUpdatedFile('<html>x') } catch { threw = true }
- ok(threw && !hasFileHandle(), 'with no handle, writeUpdatedFile writes nothing (throws, no file touched)')
-
- setQueue({ files: [launched] }) // the host handed over the open document
- consumeLaunchQueue()
- ok(hasFileHandle(), 'the launched file handle is adopted — hasFileHandle() is now true, so autosave writes the FILE')
- ok(currentFileName() === ON_SCREEN, `and it is the open document (${currentFileName()})`)
-
- // a second consume (the module init already ran one in a browser) must not throw
- setQueue({ files: [launched] })
- consumeLaunchQueue()
- ok(hasFileHandle(), 'a second consume is harmless (setConsumer re-registration is caught)')
+ ok(threw && !hasFileHandle(), 'with no handle, writeUpdatedFile writes nothing (throws)')
-}
+ // the WRONG-FILE guard: a host that vends a handle to a DIFFERENT document, or an
+ // unreadable one, or one that cannot be checked, must NOT be adopted — otherwise
+ // the first autosave would silently overwrite a file that is not this document.
+ await vend([handle('{"docId":"someone-elses","title":"Not yours"}')])
+ ok(!hasFileHandle(), 'a handle whose file is a DIFFERENT document is NOT adopted')
+ await vend([handle(null)])
+ ok(!hasFileHandle(), 'an unreadable handle is NOT adopted')
+ await vend([handle(BOOT, { noGetFile: true })])
+ ok(!hasFileHandle(), 'a handle that cannot be verified (no getFile) is NOT adopted')
-// The whole B6 claim, proven by RUNNING the REAL write path: boot with a vended
-// handle, then writeUpdatedFile → the handle's createWritable().write (what the
-// editor autosave invokes under hasFileHandle()) must put the real document bytes
-// on THAT handle. We drive it with encodeDocBody — the exact bytes a save puts in
-// #bento-doc; the HTML shell around them is DOM-only furniture (serializeBody),
-// proven by the splice/preview rigs, and carries the body verbatim.
-console.log('\nthe first write after a launch carries the real document')
-{
- const DOC = { docId: 'launch-doc', title: 'Secret Q3 numbers', format: 'bento/slides', slides: [] }
- const MARKER = 'Secret Q3 numbers' // document content that must never appear in an encrypted file
- const capture = () => {
- let got: Blob | null = null
- return { kind: 'file', name: ON_SCREEN, text: async () => (got ? await got.text() : ''),
- async createWritable() { return { async write(b: Blob) { got = b }, async close() {} } } }
- }
- const vend = (h: unknown) => { (globalThis as Record<string, unknown>).launchQueue = { setConsumer(fn: (p: unknown) => void) { fn({ files: [h] }) } }; consumeLaunchQueue() }
+ // the open document: its file's #bento-doc equals the boot block → adopted
+ const open = handle(BOOT)
+ await vend([open])
+ ok(hasFileHandle(), 'the handle whose file IS this document is adopted')
+ ok(currentFileName() === ON_SCREEN, `and it is the open document (${currentFileName()})`)
- // (a) plaintext: the bytes written parse back to the edited document
+ // Then the REAL write path (what autosave invokes under hasFileHandle()) puts the
+ // document bytes on it — driven with encodeDocBody (the exact #bento-doc bytes;
+ // the HTML shell is DOM-only furniture, proven by the splice/preview rigs).
+ // (a) plaintext parses back to the edited document
setEncryptionPassword(null)
- const plain = capture(); vend(plain)
- await writeUpdatedFile(await encodeDocBody(DOC))
- const back = JSON.parse(await plain.text())
- ok(back.docId === DOC.docId && back.title === DOC.title, 'the written bytes parse back to the edited document')
-
- // (b) with a password active: a bento/enc envelope, no plaintext, decrypts back
+ await writeUpdatedFile(await encodeDocBody(DOC as never))
+ ok(JSON.parse(await (open.wrote as () => Promise<string>)()).docId === DOC.docId,
+ 'the first write parses back to the edited document')
+ // (b) with a password: a bento/enc envelope, no plaintext, decrypts back
setEncryptionPassword('hunter2')
- const sealed = capture(); vend(sealed)
- await writeUpdatedFile(await encodeDocBody(DOC))
- const bytes = await sealed.text()
+ await writeUpdatedFile(await encodeDocBody(DOC as never))
+ const bytes = await (open.wrote as () => Promise<string>)()
const env = parseEnvelope(bytes)
ok(!!env, 'with a password active the written bytes are a bento/enc envelope')
- ok(!bytes.includes(MARKER), 'and carry NO plaintext — the document title appears nowhere in the file')
+ ok(!bytes.includes(MARKER), 'and carry NO plaintext — the title appears nowhere in the file')
const dec = env ? await decryptEnvelope(env, 'hunter2') : null
ok(!!dec && JSON.parse(dec).docId === DOC.docId, 'and decrypt back to the edited document with the password')
- setEncryptionPassword(null) // reset module state for anything after
+ setEncryptionPassword(null)
+
+ // a second consume is harmless (setConsumer re-registration is caught)
+ await vend([open])
+ ok(hasFileHandle(), 'a second consume is harmless')
+
+ // THE RACE (security's condition): the consumer awaits getFile. If a Save As /
+ // "Duplicate as new deck" sets its own handle WHILE the check is pending, the
+ // launch must NOT snap the handle back to the launched file and overwrite it.
+ // A deferred getFile holds the check open across the adopt.
+ {
+ let release!: (v: { text: () => Promise<string> }) => void
+ const slow = {
+ kind: 'file', name: ON_SCREEN, // its file WOULD match — only the race must stop it
+ getFile: () => new Promise<{ text: () => Promise<string> }>((res) => { release = res }),
+ async createWritable() { return { async write() {}, async close() {} } },
+ }
+ let pending: unknown
+ ;(globalThis as Record<string, unknown>).launchQueue = { setConsumer(fn: (p: unknown) => void) { pending = fn({ files: [slow] }) } }
+ consumeLaunchQueue() // the consumer starts and awaits slow.getFile() — still pending
+ const saveAs = {
+ kind: 'file', name: 'Saved-As-elsewhere.bento.html',
+ async createWritable() { return { async write() {}, async close() {} } },
+ }
+ adoptFileHandle(saveAs as never) // the user does Save As during the await
+ release({ text: async () => fileWith(BOOT) }) // now getFile resolves and the file DOES match
+ await pending
+ ok(hasFileHandle() && currentFileName() === 'Saved-As-elsewhere.bento.html',
+ 'a Save As during the pending check wins — the launch does not snap back and overwrite it')
+ }
+
+ delete (globalThis as Record<string, unknown>).document
}
// Source pin for the trigger the behavioural row stands in for: the editor