Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
kernel: autosave keeps content only; boot URL overrides trust real origins (#520)
nyblnet72093ab40c6f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex eacdef5c..ee04bc29 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -414,6 +414,12 @@ jobs:# behaviour (refusal, aborting what is already in flight, cross-tab).run: node scripts/test-offline.ts+ - name: Origin-trust rig+ # The release-manifest / sync / pack URL dev overrides live in+ # localStorage, which is shared across all file:// documents — so they+ # are honoured only from a real, isolated origin (sharedStorageOrigin).+ run: node scripts/test-origin-overrides.ts+- name: Embed element rig# The `embed` element (docs/DECISIONS.md 2026-08-19 shape): the static# view always paints through the svg sanitiser; a live sandboxed framediff --git a/kernel/src/autosave.ts b/kernel/src/autosave.tsindex ed9b188f..a06fede2 100644--- a/kernel/src/autosave.ts+++ b/kernel/src/autosave.ts@@ -162,6 +162,24 @@ function tx<T>(store: string, mode: IDBTransactionMode, fn: (s: IDBObjectStore)})}+/**+ * A recovery/version snapshot is CONTENT ONLY — `doc.collab` is dropped.+ *+ * Every autosave writes to IndexedDB, and Chrome gives every `file://` document+ * ONE shared origin, so an IndexedDB record is readable by any other local+ * document. `doc.collab` carries the live-room secrets — the read key, the owner+ * and writer private keys, the invite, the audience key — and content recovery+ * has no use for them: restore takes `collab` from the file that is actually+ * open, never from the snapshot (see the editor's restore path), so a snapshot+ * that keeps collab would only be a place for those secrets to leak. A deck that+ * was never saved has no file to re-read and re-mints its collab, as it does+ * today. `collab` is a top-level field, so omitting it here removes it whole.+ */+function contentOnly(doc: KernelDoc): string {+ const { collab: _collab, ...rest } = doc as KernelDoc & { collab?: unknown }+ return JSON.stringify(rest)+}+/*** Write the single latest recovery snapshot for this doc.*@@ -176,7 +194,7 @@ function tx<T>(store: string, mode: IDBTransactionMode, fn: (s: IDBObjectStore)*/export async function putRecovery(doc: KernelDoc): Promise<boolean> {const key = await tx(RECOVERY, 'readwrite', (s) =>- s.put({ docId: doc.docId, at: Date.now(), title: doc.title, json: JSON.stringify(doc) } as Snapshot))+ s.put({ docId: doc.docId, at: Date.now(), title: doc.title, json: contentOnly(doc) } as Snapshot))return key != null}@@ -198,7 +216,7 @@ export async function clearVersions(docId: string): Promise<void> {export async function addVersion(doc: KernelDoc): Promise<void> {await tx(VERSIONS, 'readwrite', (s) =>- s.add({ docId: doc.docId, at: Date.now(), title: doc.title, json: JSON.stringify(doc) } as Snapshot))+ s.add({ docId: doc.docId, at: Date.now(), title: doc.title, json: contentOnly(doc) } as Snapshot))// prune to the newest MAX_VERSIONS for this docconst all = await listVersions(doc.docId)if (all.length > MAX_VERSIONS) {diff --git a/kernel/src/net.ts b/kernel/src/net.tsindex 5bf4563d..d2684be5 100644--- a/kernel/src/net.ts+++ b/kernel/src/net.ts@@ -97,6 +97,34 @@ export const sandboxed = (): boolean => {return sandboxFlag}+/**+ * Is this document's localStorage / IndexedDB SHARED with other local documents?+ *+ * Chrome gives every `file://` page ONE origin, so one deck's localStorage and+ * IndexedDB are readable and writable by any other local `.bento.html` the user+ * opens. An opaque origin (`self.origin === 'null'`) is untrusted the same way.+ * A real web origin (https, or http on localhost) has isolated per-origin+ * storage and is trusted.+ *+ * Boot-read DEV OVERRIDES (the release-manifest URL, the sync host, the pack+ * host) must NOT be honoured from shared storage: a malicious local deck could+ * plant one and steer the next deck the user opens to a hostile server. Read+ * them only when this returns false. Distinct from `sandboxed()` — a plain+ * file:// deck is not sandboxed (not framed) but its storage IS shared.+ * Fail safe: if the origin cannot be determined, treat storage as shared.+ */+export const sharedStorageOrigin = (): boolean => {+ try {+ if (typeof location !== 'undefined' && location.protocol === 'file:') return true+ const o = typeof self !== 'undefined' && typeof (self as { origin?: unknown }).origin === 'string'+ ? (self as { origin: string }).origin+ : (typeof location !== 'undefined' ? location.origin : 'null')+ return o === 'null'+ } catch {+ return true+ }+}+/*** Set for THIS session once anyone flips the switch, so the guarantee holds* even where the preference cannot be stored. Storage-blocked contexts arediff --git a/kernel/src/sync/online.ts b/kernel/src/sync/online.tsindex 3bcc7188..656b6262 100644--- a/kernel/src/sync/online.ts+++ b/kernel/src/sync/online.ts@@ -16,7 +16,7 @@ import { lsGet, lsSet } from '../storage.ts'import { offlineEnabled } from '../update.ts'// Every request in the app goes through the one chokepoint (kernel/src/net.ts)// so the offline switch cannot be forgotten — see GHSA-5c3x-xqp6-g94r.-import { netWebSocket, SandboxedError } from '../net.ts'+import { netWebSocket, SandboxedError, sharedStorageOrigin } from '../net.ts'import { appConfig } from '../app.ts'/** the app's store, structurally — see session.ts HostStore */@@ -168,7 +168,11 @@ export function syncHost(): string {let configured: string | undefinedtry { configured = appConfig().syncHost } catch { /* not configured: platform default */ }try {- return lsGet('bento-sync-url') || configured || DEFAULT_SYNC_HOST+ // The localStorage dev override is honoured only from a real, isolated+ // origin: on file:// (shared storage) a malicious local deck could plant it+ // and steer this deck's collab at a hostile relay.+ const devOverride = sharedStorageOrigin() ? '' : lsGet('bento-sync-url')+ return devOverride || configured || DEFAULT_SYNC_HOST} catch {return configured || DEFAULT_SYNC_HOST}diff --git a/kernel/src/update.ts b/kernel/src/update.tsindex be44c4ba..ee44dcdf 100644--- a/kernel/src/update.ts+++ b/kernel/src/update.ts@@ -26,7 +26,7 @@ import {hasFileHandle, writeUpdatedFile, writeUpdatedFileAs, writeBackupBeside, hostCan,} from './save.ts'import { lsDel, lsGet, lsSet } from './storage.ts'-import { netFetch } from './net.ts'+import { netFetch, sharedStorageOrigin } from './net.ts'declare const __APP_VERSION__: string@@ -205,7 +205,13 @@ async function verifyManifest(raw: string): Promise<ReleaseInfo> {/** Ask the release origin for the latest version. */export async function checkForUpdates(manifestUrl?: string): Promise<UpdateCheck> {- const url = manifestUrl ?? lsGet('bento-update-url') ?? updateManifestUrl()+ // The localStorage dev override is honoured only from a real, isolated origin.+ // On file:// (and opaque origins) storage is shared with every other local+ // document, so a malicious deck could plant an override that steers this deck's+ // update check at a hostile server (signatures still block RCE; this stops the+ // downgrade/DoS/steer). Dev works from localhost or a real origin.+ const devOverride = sharedStorageOrigin() ? null : lsGet('bento-update-url')+ const url = manifestUrl ?? devOverride ?? updateManifestUrl()try {const res = await netFetch(url, { cache: 'no-store' })if (!res.ok) throw new Error(`release server answered ${res.status}`)diff --git a/scripts/test-autosave.ts b/scripts/test-autosave.tsindex 66f67e12..107e538f 100644--- a/scripts/test-autosave.ts+++ b/scripts/test-autosave.ts@@ -124,5 +124,35 @@ await addVersion({ docId: 'deck-uuid-1', title: 'v3', json: '{}' } as any)const after = await listVersions('deck-uuid-1')ok(after.length === 4, `adding one version gives 4, not 7 — the legacy rows were not copied twice (got ${after.length})`)+// ---- a snapshot is CONTENT ONLY — it never carries doc.collab --------------+// Every autosave writes to IndexedDB, whose origin is shared across all local+// documents, so a snapshot must not carry the live-room secrets in doc.collab.+// Restore takes collab from the file that is open, not the snapshot, so content+// recovery is unaffected.+{+ const secretDoc = {+ docId: 'deck-collab', title: 'Shared deck',+ slides: [{ id: 's1', elements: [{ id: 'e1', html: 'CONTENT-STAYS' }] }],+ collab: {+ room: 'wROOMROOMROOM', key: 'READCAP-b64', on: true, v: 2, owner: 'OWNERPUB', role: 'writer',+ ownerPriv: 'OWNERPRIV-pkcs8', writerPriv: 'WRITERPRIV-pkcs8',+ invite: { pub: 'IPUB', priv: 'INVITEPRIV-pkcs8', role: 'writer', sig: 's', key: 'SHOWKEY-b64' },+ audience: 'AUDTICKET',+ },+ } as any+ await putRecovery(secretDoc)+ const snap = (await getRecovery('deck-collab'))!+ const parsed = JSON.parse(snap.json)+ ok(!('collab' in parsed), 'a recovery snapshot drops doc.collab entirely')+ for (const s of ['READCAP', 'OWNERPRIV', 'WRITERPRIV', 'INVITEPRIV', 'SHOWKEY', 'AUDTICKET', 'wROOMROOMROOM'])+ ok(!snap.json.includes(s), `no ${s} (key/priv/invite/room) in the recovery snapshot`)+ ok(snap.json.includes('CONTENT-STAYS'), 'but the document content is kept — recovery still restores it')++ await addVersion(secretDoc)+ const v = (await listVersions('deck-collab'))[0]+ ok(!('collab' in JSON.parse(v.json)), 'a version snapshot drops collab too')+ ok(!v.json.includes('OWNERPRIV') && v.json.includes('CONTENT-STAYS'), 'version keeps content, not secrets')+}+console.log(`\n[${APP}] ${checks - failures}/${checks} checks passed`)if (failures) process.exit(1)diff --git a/scripts/test-origin-overrides.ts b/scripts/test-origin-overrides.tsnew file mode 100644index 00000000..e8d867ca--- /dev/null+++ b/scripts/test-origin-overrides.ts@@ -0,0 +1,60 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Origin-trust rig for boot-read dev overrides.+//+// node scripts/test-origin-overrides.ts+//+// The release-manifest URL, the sync host and the pack host each have a+// localStorage dev override. Chrome gives every file:// document one shared+// origin, so localStorage there is not this document's alone — an override must+// be honoured only from a real, isolated origin. sharedStorageOrigin() is that+// gate. The read sites are asserted at source (they need a DOM/network to run).++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}`) }++const g = globalThis as Record<string, unknown>+const setOrigin = (protocol: string, origin: string | undefined) => {+ g.location = { protocol, origin }+ g.self = origin === undefined ? undefined : { origin }+}+const { sharedStorageOrigin } = await import('../kernel/src/net.ts')++// file:// — every local document shares this origin's storage+setOrigin('file:', 'null')+ok(sharedStorageOrigin() === true, 'file:// is shared storage (overrides ignored)')+// file:// where the origin string serialises non-null (some engines): the+// protocol check, not the opaque check, is what catches it+setOrigin('file:', 'file://')+ok(sharedStorageOrigin() === true, 'file:// is shared even when its origin is not the string "null"')+// a real isolated web origin+setOrigin('https:', 'https://bento.page')+ok(sharedStorageOrigin() === false, 'a real https origin is trusted (overrides honoured)')+// localhost dev over http — a real origin, isolated+setOrigin('http:', 'http://localhost:5199')+ok(sharedStorageOrigin() === false, 'localhost dev is trusted')+// opaque origin (self.origin === 'null') even on a non-file protocol+setOrigin('https:', 'null')+ok(sharedStorageOrigin() === true, 'an opaque origin is shared storage')+// cannot determine → fail safe (treat as shared)+g.location = undefined; g.self = undefined+ok(sharedStorageOrigin() === true, 'origin undeterminable → treated as shared (fail safe)')++// --- the kernel read sites gate the override on it --------------------------+{+ const upd = readFileSync(join(root, 'kernel/src/update.ts'), 'utf8')+ ok(/sharedStorageOrigin\(\)\s*\?\s*null\s*:\s*lsGet\('bento-update-url'\)/.test(upd),+ 'update.ts honours bento-update-url only from a non-shared origin')+ const onl = readFileSync(join(root, 'kernel/src/sync/online.ts'), 'utf8')+ ok(/sharedStorageOrigin\(\)\s*\?\s*''\s*:\s*lsGet\('bento-sync-url'\)/.test(onl),+ 'online.ts honours bento-sync-url only from a non-shared origin')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)