Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
Offline mode reaches the network from exactly one place (#305)
nyblnet759fb9368eb3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 14a4b6cf..86088598 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -202,6 +202,20 @@ jobs:# file carrying a script tag.run: node scripts/test-preview.ts+ - name: Offline-mode rig+ # Offline mode promises "nothing leaves this computer" and was broken+ # five ways at once (GHSA-5c3x-xqp6-g94r): a manual update check, a+ # language-pack download, a deck's remote <video>, in-flight requests+ # that kept running, and a second tab's socket that kept syncing.+ #+ # It stayed hidden because it reads as correct: an agent asked to audit+ # it said "secure" from the docs AND from the code. So the rig does not+ # check the call sites — it enforces the POLICY that no file outside+ # kernel/src/net.ts may touch a network primitive at all, which is what+ # stops the NEXT call site being wrong, plus the chokepoint's own+ # behaviour (refusal, aborting what is already in flight, cross-tab).+ run: node scripts/test-offline.ts+- name: Untrusted-markup sanitizer rig# Every deck is untrusted input somebody may open, paste or receive over# collab, and script in that page owns the collab keys, the plaintextdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2d1bcf17..c0a1f197 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,32 @@ pre-1.0.## [Unreleased]+- **Security: offline mode did not block everything it promised.** The switch+ says "nothing leaves this computer", and five things still went out with it+ on: a manual *Check for updates* called the release server, *Manage+ languages…* downloaded the pack index and any pack you added, a deck's video+ or image pointing at a web address still loaded from it, requests already+ running were left to finish, and a second tab that was already in a live+ session kept syncing edits.++ The last two matter most. A remote image or video in a document is the+ cheapest tracking beacon there is — it tells whoever hosts it that you opened+ the file, and when — and offline mode is exactly what you would turn on+ before opening a deck you did not write. The second tab was worse: real+ document content kept moving.++ Separately, where a browser blocks site data — a private window, or a+ locked-down setup — the checkbox showed the switch on while nothing had been+ stored, so it did nothing at all. It now holds for the session regardless and+ says plainly that it will not survive a reload.++ Offline mode now covers all of it: the network is reachable from exactly one+ place in the code, flipping the switch cuts requests and connections that are+ already open rather than only the next one, and a deck's remote images and+ video are left unloaded. Reported privately, with a reproduction — and found+ by watching real traffic after reading the code twice suggested there was+ nothing wrong.+- **Updating a file no longer interrupts you.** With Bento Tray installed and afolder granted, "Update this file" now finishes without a single dialog. Thebackup it leaves behind is saved **beside your document** instead of beingdiff --git a/dash/src/sync/online.ts b/dash/src/sync/online.tsindex 485d8e7b..919251ce 100644--- a/dash/src/sync/online.ts+++ b/dash/src/sync/online.ts@@ -28,6 +28,7 @@ import type { DashDoc } from '../model.ts'import type { Op, SyncStateJSON } from './crdt.ts'import type { Frame, RefusalCode, SyncSession, Transport } from './session.ts'import { offlineEnabled } from '../../../kernel/src/update.ts'+import { netWebSocket } from '../../../kernel/src/net.ts'import { lsGet, lsSet } from '../../../kernel/src/storage.ts'export const DEFAULT_SYNC_HOST = 'wss://sync.bento.page'@@ -328,9 +329,11 @@ export class OnlineTransport implements Transport {this.setStatus('connecting')let ws: WebSockettry {- ws = new WebSocket(`${this.url}&since=${this.seq}`)+ ws = netWebSocket(`${this.url}&since=${this.seq}`)} catch {- this.retry()+ // Offline is a decision, not an outage: retrying would spin until the+ // switch flips, and net.ts has closed anything already open anyway.+ if (!offlineEnabled()) this.retry()return}this.ws = wsdiff --git a/kernel/src/net.ts b/kernel/src/net.tsnew file mode 100644index 00000000..c510febe--- /dev/null+++ b/kernel/src/net.ts@@ -0,0 +1,181 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// The ONE place this app touches the network.+//+// WHY THIS EXISTS. Offline mode used to be a boolean that five call sites+// remembered to consult, and the ones that forgot were invisible from the+// inside: the switch looked sound in the docs AND in the code — an agent+// asked to audit it reported "secure" twice — and only watching real traffic+// showed otherwise. Reported 2026-08-09 (GHSA-5c3x-xqp6-g94r), reproduced on+// 802804b. With the switch ON:+//+// - a manual "Check for updates" still called home (the gate sat on the+// AUTO-check call site; checkForUpdates() itself fetched unconditionally)+// - "Manage languages…" still downloaded packs.json and a 73KB pack+// - a deck's remote <video src> still loaded — 4 requests, and NOT a fetch+// at all, so no fetch-shaped gate could ever have caught it+// - in-flight requests kept running (nothing in the codebase could abort:+// there was no AbortController anywhere)+// - a second tab's open socket kept carrying edits, because the toggle+// disconnected only its own tab's session and nothing watched `storage`+// - and with site data blocked, the checkbox showed ENABLED while the+// preference never persisted, so the switch silently did nothing+//+// So the switch stops being a thing to remember. Every request goes through+// netFetch/netWebSocket, and `scripts/test-offline.ts` FAILS THE BUILD if any+// file outside this one calls `fetch(` or `new WebSocket` directly. That is+// the property worth having: not "the call sites are right today" but "a new+// call site cannot be wrong". Suggested by the reporter, and it is the right+// shape — an agent, or a person, can check a rule like that mechanically.+//+// What offline does NOT block, deliberately: BroadcastChannel. Same-machine+// tab sync is not networking, and nothing leaves the computer.++import { lsGet, lsSet } from './storage.ts'++/** Thrown by netFetch/netWebSocket when the offline switch is on. */+export class OfflineError extends Error {+ constructor(what = 'the network') {+ super(`Offline mode is on — refusing to reach ${what}.`)+ this.name = 'OfflineError'+ }+}++/**+ * Set for THIS session once anyone flips the switch, so the guarantee holds+ * even where the preference cannot be stored. Storage-blocked contexts are+ * not an edge case here — they are private windows and locked-down browsers,+ * i.e. exactly the people most likely to want this switch on.+ */+let sessionOffline: boolean | null = null++/**+ * Offline mode: a hard, viewer-side switch that blocks EVERY network touch —+ * update checks, language packs, collaboration and remote media alike. The+ * guarantee it buys: with the switch on, nothing about you or a document ever+ * leaves this computer.+ */+export const offlineEnabled = (): boolean =>+ sessionOffline ?? lsGet('bento-offline') === 'on'++/**+ * Set the switch. Returns whether it actually PERSISTED — false where site+ * data is blocked or storage is full.+ *+ * The caller must not ignore this. It used to swallow the failure, so with+ * storage unavailable the checkbox showed "on" over a switch that was off:+ * measured — checkbox enabled, preference `off`, request went out anyway.+ * A privacy switch that lies is worse than one that is missing, because the+ * whole reason to touch it is to stop doing something.+ */+export const setOffline = (on: boolean): boolean => {+ sessionOffline = on+ const stuck = lsSet('bento-offline', on ? 'on' : 'off')+ if (on) enforceOffline()+ return stuck+}++// ——— live connections, so "go offline" can mean NOW rather than "next time"++const inFlight = new Set<AbortController>()+const sockets = new Set<WebSocket>()++/**+ * Cut everything already running. Called when the switch goes on — in THIS+ * tab by setOffline, and in every OTHER tab by the `storage` listener below,+ * which is the half that was missing: `bento-offline` is shared across tabs,+ * so a second tab already believed it was offline while its socket kept+ * carrying edits both ways.+ */+export function enforceOffline(): void {+ for (const ac of [...inFlight]) {+ try { ac.abort(new OfflineError()) } catch { /* already settled */ }+ }+ inFlight.clear()+ for (const ws of [...sockets]) {+ try { ws.close(1000, 'offline mode') } catch { /* already closing */ }+ }+ sockets.clear()+}++let guarding = false+/**+ * Watch the switch in other tabs. `storage` fires only in the tabs that did+ * NOT make the change, which is exactly the set that needs telling.+ */+export function startNetGuard(): void {+ if (guarding || typeof addEventListener !== 'function') return+ guarding = true+ addEventListener('storage', (e) => {+ if (e.key !== 'bento-offline') return+ // Mirror the other tab's decision into this one, or a session flag set+ // here would outrank it and keep letting requests out.+ sessionOffline = e.newValue === 'on'+ if (sessionOffline) enforceOffline()+ })+}++// ——— the primitives++/** fetch(), refused when offline and abortable the moment the switch flips. */+export async function netFetch(input: string | URL, init: RequestInit = {}): Promise<Response> {+ if (offlineEnabled()) throw new OfflineError(String(input))+ const ac = new AbortController()+ inFlight.add(ac)+ // Honour a caller's own signal as well as ours.+ if (init.signal) {+ if (init.signal.aborted) ac.abort(init.signal.reason)+ else init.signal.addEventListener('abort', () => ac.abort(init.signal!.reason), { once: true })+ }+ try {+ return await fetch(input, { ...init, signal: ac.signal })+ } finally {+ inFlight.delete(ac)+ }+}++/** new WebSocket(), refused when offline and closed the moment the switch flips. */+export function netWebSocket(url: string): WebSocket {+ if (offlineEnabled()) throw new OfflineError(url)+ const ws = new WebSocket(url)+ sockets.add(ws)+ ws.addEventListener('close', () => sockets.delete(ws), { once: true })+ return ws+}++// ——— the part no fetch wrapper can see++/**+ * Does this `src` reach the network when a browser loads it?+ *+ * Media and images are loaded by the BROWSER from a `src` attribute, not by+ * us from a fetch — which is why a remote <video> sailed through a switch+ * that gated every fetch in the app. The renderer asks this before it emits+ * one.+ *+ * `data:`, `blob:` and `asset:` are carried inside the file. Anything that+ * resolves to http(s) is a request leaving the machine — including a+ * same-origin relative path, because a deck opened from a web server still+ * reaches that server for it, and "nothing leaves this computer" has to mean+ * what it says.+ */+export function isRemoteUrl(src: string): boolean {+ const s = (src ?? '').trim()+ if (!s) return false+ if (/^(data|blob|asset|file):/i.test(s)) return false+ // Protocol-relative names a HOST whatever the page's scheme is. Judged+ // before resolution, so the answer does not depend on whether the deck was+ // opened from a web server or from a file:// path — a privacy switch that+ // changes its mind based on that is not one you can reason about.+ if (s.startsWith('//')) return true+ try {+ const base = typeof document !== 'undefined' ? document.baseURI : undefined+ return /^https?:$/i.test(new URL(s, base).protocol)+ } catch {+ return false // unparseable is not a URL a browser will reach either+ }+}++/** A `src` the renderer must not emit right now. */+export const remoteSrcBlocked = (src: string): boolean => offlineEnabled() && isRemoteUrl(src)diff --git a/kernel/src/update.ts b/kernel/src/update.tsindex 9d449cd8..940f06e0 100644--- a/kernel/src/update.ts+++ b/kernel/src/update.ts@@ -26,34 +26,22 @@ import {hasFileHandle, writeUpdatedFile, writeUpdatedFileAs, writeBackupBeside, hostCan,} from './save.ts'import { lsDel, lsGet, lsSet } from './storage.ts'+import { netFetch } from './net.ts'declare const __APP_VERSION__: string/** Version of the running app shell (baked in at build from package.json). */export const APP_VERSION: string = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '0.0.0'-/** Per-browser preference: check for updates automatically at launch. *//**- * Offline mode: a hard, viewer-side switch that blocks EVERY network touch —- * update checks and online collaboration alike. Same-machine tab sync- * (BroadcastChannel) is not networking and stays on. The guarantee this- * buys: with the switch on, nothing about you or a document ever leaves- * this computer.+ * The offline switch and every network primitive now live in net.ts — one+ * chokepoint, so a call site cannot forget to consult the switch (that is+ * exactly how GHSA-5c3x-xqp6-g94r happened: the gate below used to sit on the+ * auto-check CALL SITE while checkForUpdates() fetched unconditionally).+ * Re-exported here because this has been update.ts's public surface since+ * 0.9.x and shipped code imports it from here.*/-export const offlineEnabled = (): boolean => {- try {- return lsGet('bento-offline') === 'on'- } catch {- return false- }-}-export const setOffline = (on: boolean): void => {- try {- lsSet('bento-offline', on ? 'on' : 'off')- } catch {- /* storage unavailable */- }-}+export { offlineEnabled, setOffline, OfflineError, startNetGuard } from './net.ts'export const autoCheckEnabled = (): boolean => lsGet('bento-auto-check') !== 'off'export const setAutoCheck = (on: boolean): void => {@@ -188,7 +176,7 @@ export async function fetchPinned(url: string, sha256: string): Promise<ArrayBufif (!/^[0-9a-f]{64}$/i.test(sha256 ?? '')) return nulllet bytes: ArrayBuffertry {- const res = await fetch(url, { cache: 'no-store' })+ const res = await netFetch(url, { cache: 'no-store' })if (!res.ok) return nullbytes = await res.arrayBuffer()} catch {@@ -217,7 +205,7 @@ async function verifyManifest(raw: string): Promise<ReleaseInfo> {export async function checkForUpdates(manifestUrl?: string): Promise<UpdateCheck> {const url = manifestUrl ?? lsGet('bento-update-url') ?? updateManifestUrl()try {- const res = await fetch(url, { cache: 'no-store' })+ const res = await netFetch(url, { cache: 'no-store' })if (!res.ok) throw new Error(`release server answered ${res.status}`)const release = await verifyManifest(await res.text())if (compareVersions(release.version, APP_VERSION) <= 0)@@ -248,7 +236,7 @@ export function registerUpdatePrepare(fn: (version: string) => Promise<void>): v}export async function buildUpdatedFile(release: ReleaseInfo, doc: KernelDoc): Promise<string> {- const res = await fetch(release.url, { cache: 'no-store' })+ const res = await netFetch(release.url, { cache: 'no-store' })if (!res.ok) throw new Error(`downloading the update failed (${res.status})`)const bytes = await res.arrayBuffer()// Same pin as fetchPinned, spelled out here because THIS path distinguishesdiff --git a/scripts/test-offline.ts b/scripts/test-offline.tsnew file mode 100644index 00000000..92beec30--- /dev/null+++ b/scripts/test-offline.ts@@ -0,0 +1,236 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Offline-mode rig.+//+// node scripts/test-offline.ts+//+// WHAT THIS PROVES. Offline mode is a promise made in the product's own+// words — "nothing leaves this computer" — and it was broken in five separate+// ways at once (GHSA-5c3x-xqp6-g94r, reported 2026-08-09). What makes that+// worth a permanent rig is HOW it stayed hidden: the reporter asked an agent+// to audit the feature, and the agent read the docs and said secure, then read+// the CODE and still said secure. It only came out when something watched real+// traffic. Reading a call site cannot tell you about the call site nobody+// wrote yet.+//+// So this rig does not check that the current call sites are correct. It+// checks the two things that survive the next contributor:+//+// 1. THE POLICY. No file outside kernel/src/net.ts may touch a network+// primitive. A new feature cannot forget the switch, because the only+// way to reach the network is through something that already consults+// it. This is the reporter's own suggestion, and it is the right shape:+// mechanically checkable, by a person or an agent, in one grep.+// 2. THE CHOKEPOINT'S BEHAVIOUR. That netFetch/netWebSocket actually+// refuse; that flipping the switch cuts what is ALREADY running rather+// than only what starts next; that another tab's flip is honoured; that+// a src a browser would load is classified as network even though no+// fetch is involved; and that a switch which cannot be persisted still+// holds for the session instead of quietly doing nothing.++import { readdirSync, readFileSync, statSync } from 'node:fs'+import { join, dirname, relative } from 'node:path'+import { fileURLToPath } from 'node:url'++const root = join(dirname(fileURLToPath(import.meta.url)), '..')++let failures = 0+let checks = 0+const ok = (cond: boolean, msg: string) => {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) } else console.log(` ok ${msg}`)+}++// ---------------------------------------------------------------- 1. policy+// The primitives that reach the network. Anything here, outside net.ts, is a+// path that can ignore the switch.+const PRIMITIVES: Array<[RegExp, string]> = [+ [/(?<![.\w])fetch\s*\(/, 'fetch('],+ [/\.fetch\s*\(/, '.fetch('],+ [/new\s+WebSocket\s*\(/, 'new WebSocket('],+ [/new\s+XMLHttpRequest\s*\(/, 'new XMLHttpRequest('],+ [/sendBeacon\s*\(/, 'sendBeacon('],+ [/new\s+EventSource\s*\(/, 'new EventSource('],+]++/** The one file allowed to touch them, and the test files that stub them. */+const CHOKEPOINT = 'kernel/src/net.ts'++/** Strip comments and string literals — a primitive NAMED in prose is fine. */+function code(src: string): string {+ let out = ''+ let i = 0+ let state: 'code' | 'line' | 'block' | 's' | 'd' | 't' = 'code'+ while (i < src.length) {+ const c = src[i], n = src[i + 1]+ if (state === 'code') {+ if (c === '/' && n === '/') { state = 'line'; i += 2; continue }+ if (c === '/' && n === '*') { state = 'block'; i += 2; continue }+ if (c === "'") { state = 's'; i++; continue }+ if (c === '"') { state = 'd'; i++; continue }+ if (c === '`') { state = 't'; i++; continue }+ out += c; i++; continue+ }+ if (state === 'line') { if (c === '\n') { state = 'code'; out += '\n' } ; i++; continue }+ if (state === 'block') { if (c === '*' && n === '/') { state = 'code'; i += 2 } else i++; continue }+ if (c === '\\') { i += 2; continue }+ if ((state === 's' && c === "'") || (state === 'd' && c === '"') || (state === 't' && c === '`')) state = 'code'+ i+++ }+ return out+}++function walk(dir: string, out: string[] = []): string[] {+ let entries: string[]+ try { entries = readdirSync(dir) } catch { return out }+ for (const e of entries) {+ if (e === 'node_modules' || e === 'dist' || e === 'dist-single' || e.startsWith('.')) continue+ const p = join(dir, e)+ if (statSync(p).isDirectory()) walk(p, out)+ else if (/\.ts$/.test(e) && !/\.d\.ts$/.test(e)) out.push(p)+ }+ return out+}++const sources = ['kernel/src', 'slides/src', 'dash/src', 'spaces/src']+ .flatMap((d) => walk(join(root, d)))+ .map((p) => relative(root, p))+ .filter((p) => p !== CHOKEPOINT)++ok(sources.length > 50, `the policy scan actually found sources to scan (${sources.length} files)`)++const offenders: string[] = []+for (const rel of sources) {+ const body = code(readFileSync(join(root, rel), 'utf8'))+ for (const [re, name] of PRIMITIVES) {+ if (re.test(body)) offenders.push(`${rel} uses ${name}`)+ }+}+ok(offenders.length === 0,+ `no file outside ${CHOKEPOINT} touches a network primitive${offenders.length ? `\n ${offenders.join('\n ')}` : ''}`)++// A gate nobody has seen fail is not a gate: prove the scanner can see one.+{+ const planted = code(`const r = await fetch('https://example.com')`)+ ok(PRIMITIVES.some(([re]) => re.test(planted)), 'the scanner detects a planted fetch( — it can fail')+ const prose = code(`// we used to call fetch( here\nconst x = 1`)+ ok(!PRIMITIVES.some(([re]) => re.test(prose)), 'a primitive named in a COMMENT is not an offence')+ const str = code(`const msg = 'call fetch( to reach it'`)+ ok(!PRIMITIVES.some(([re]) => re.test(str)), 'a primitive named in a STRING is not an offence')+ ok(!PRIMITIVES.some(([re]) => re.test(code('await netFetch(url)'))), 'netFetch( is not mistaken for fetch(')+}++// ------------------------------------------------------- 2. the chokepoint+// Stub the platform BEFORE importing, since net.ts reads these globals.+const store = new Map<string, string>()+let storageWorks = true+;(globalThis as any).localStorage = {+ getItem: (k: string) => (storageWorks ? store.get(k) ?? null : (() => { throw new Error('blocked') })()),+ setItem: (k: string, v: string) => { if (!storageWorks) throw new Error('blocked'); store.set(k, v) },+ removeItem: (k: string) => { store.delete(k) },+}++let fetchCalls: string[] = []+let lastSignal: AbortSignal | null = null+;(globalThis as any).fetch = (url: any, init: any = {}) => {+ fetchCalls.push(String(url))+ lastSignal = init.signal ?? null+ // '/slow' hangs until aborted, so the in-flight abort path can be observed;+ // everything else answers at once, like a reachable server.+ if (!String(url).includes('/slow')) return Promise.resolve({ ok: true, status: 200 })+ return new Promise((_resolve, reject) => {+ init.signal?.addEventListener('abort', () => reject(init.signal.reason))+ })+}++let socketsOpened: string[] = []+const closed: string[] = []+class FakeWS {+ url: string+ listeners: Record<string, Array<() => void>> = {}+ constructor(url: string) { this.url = url; socketsOpened.push(url) }+ addEventListener(t: string, fn: () => void) { (this.listeners[t] ??= []).push(fn) }+ close() { closed.push(this.url); for (const fn of this.listeners.close ?? []) fn() }+}+;(globalThis as any).WebSocket = FakeWS++const storageHandlers: Array<(e: any) => void> = []+;(globalThis as any).document = { baseURI: 'https://deck.example/talk.bento.html' }+;(globalThis as any).addEventListener = (t: string, fn: (e: any) => void) => {+ if (t === 'storage') storageHandlers.push(fn)+}++const net = await import('../kernel/src/net.ts')++// --- refusal+net.setOffline(false)+fetchCalls = []+await net.netFetch('https://example.com/a').catch(() => {})+ok(fetchCalls.length === 1, 'with the switch OFF, netFetch reaches the network')++net.setOffline(true)+fetchCalls = []+let threw: unknown = null+await net.netFetch('https://example.com/b').catch((e) => { threw = e })+ok(fetchCalls.length === 0, 'with the switch ON, netFetch makes NO request')+ok((threw as any)?.name === 'OfflineError', 'and it rejects with OfflineError rather than failing silently')++socketsOpened = []+let wsThrew: unknown = null+try { net.netWebSocket('wss://relay.example/room') } catch (e) { wsThrew = e }+ok(socketsOpened.length === 0, 'with the switch ON, netWebSocket opens NO socket')+ok((wsThrew as any)?.name === 'OfflineError', 'and it throws OfflineError')++// --- cutting what is ALREADY running (claims 4 and 5)+net.setOffline(false)+fetchCalls = []+const pending = net.netFetch('https://example.com/slow').catch((e) => e)+const live = net.netWebSocket('wss://relay.example/live')+ok(fetchCalls.length === 1 && socketsOpened.includes('wss://relay.example/live'),+ 'a request and a socket are running before the switch flips')+net.setOffline(true)+const aborted = await pending+ok(lastSignal?.aborted === true, 'flipping the switch ABORTS the request already in flight')+ok((aborted as any)?.name === 'OfflineError', 'the in-flight request rejects with OfflineError')+ok(closed.includes('wss://relay.example/live'), 'flipping the switch CLOSES the socket already open')++// --- another tab flipping it (claim 5's missing half)+net.setOffline(false)+net.startNetGuard()+ok(storageHandlers.length === 1, 'startNetGuard subscribes to storage events')+const other = net.netWebSocket('wss://relay.example/othertab')+store.set('bento-offline', 'on')+for (const fn of storageHandlers) fn({ key: 'bento-offline', newValue: 'on' })+ok(closed.includes('wss://relay.example/othertab'),+ "a DIFFERENT tab turning the switch on closes this tab's open socket")+ok(net.offlineEnabled() === true, "and this tab now agrees it is offline, so new requests are refused too")+void other++// --- a src the browser loads (claim 3) — no fetch involved+ok(net.isRemoteUrl('https://cdn.example/clip.mp4'), 'an https src counts as reaching the network')+ok(net.isRemoteUrl('//cdn.example/clip.mp4'), 'a protocol-relative src counts too')+ok(!net.isRemoteUrl('data:video/mp4;base64,AAAA'), 'a data: URI does not')+ok(!net.isRemoteUrl('asset:clip'), 'an asset: reference does not')+ok(!net.isRemoteUrl(''), 'an empty src does not')+ok(net.isRemoteUrl('clip.mp4'),+ 'a RELATIVE src on a web-served deck counts — it still reaches that server')+net.setOffline(true)+ok(net.remoteSrcBlocked('https://cdn.example/clip.mp4'), 'offline blocks a remote src')+ok(!net.remoteSrcBlocked('data:video/mp4;base64,AAAA'), 'offline does not block an embedded one')+net.setOffline(false)+ok(!net.remoteSrcBlocked('https://cdn.example/clip.mp4'), 'online allows a remote src')++// --- a switch that cannot be stored (claim 6)+storageWorks = false+const stuck = net.setOffline(true)+ok(stuck === false, 'setOffline REPORTS that it could not persist, instead of swallowing it')+ok(net.offlineEnabled() === true,+ 'and the switch still holds for this session — it does not silently do nothing')+fetchCalls = []+await net.netFetch('https://example.com/c').catch(() => {})+ok(fetchCalls.length === 0, 'so no request goes out even though the preference was never saved')+storageWorks = true++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.tsindex e4d3e84f..54943100 100644--- a/slides/src/editor/editor.ts+++ b/slides/src/editor/editor.ts@@ -2967,7 +2967,11 @@ export class Editor {offCb.type = 'checkbox'offCb.checked = offlineEnabled()offCb.addEventListener('change', () => {- setOffline(offCb.checked)+ // setOffline reports whether the preference PERSISTED. It holds for this+ // session either way (net.ts keeps it in memory), but a switch that+ // silently forgets itself on reload has to say so — it used to show+ // "on" over a setting that had never been stored.+ const stuck = setOffline(offCb.checked)if (offCb.checked) {if (this.session) disconnectOnline(this.session)} else {@@ -2975,9 +2979,11 @@ export class Editor {}this.wireOnlineStatus()this.toast(- offCb.checked- ? t('Offline mode on — nothing leaves this computer')- : t('Offline mode off — online features re-enabled'),+ !stuck+ ? t('Offline mode is on for this tab, but could not be saved — this browser is blocking site data, so it will not survive a reload')+ : offCb.checked+ ? t('Offline mode on — nothing leaves this computer')+ : t('Offline mode off — online features re-enabled'),)})offRow.append(offCb, document.createTextNode(' ' + t('Offline mode — block all network features (updates, online collaboration)')))diff --git a/slides/src/main.ts b/slides/src/main.tsindex ea5ba272..d8c0113c 100644--- a/slides/src/main.ts+++ b/slides/src/main.ts@@ -7,6 +7,7 @@ import './styles.css'import { anim } from './anim'import { configureApp, appConfig } from '../../kernel/src/app.ts'import { startTheme } from '../../kernel/src/theme.ts'+import { startNetGuard } from '../../kernel/src/net.ts'import {capturePristine, readEmbeddedDoc, serializeFile, serializeAuto, downloadFile,suggestedFileName, parseEnvelope, decryptEnvelope, setEncryptionPassword,@@ -54,6 +55,11 @@ capturePristine()// lays anything out — it sets two attributes on the root element.startTheme()+// Watch the offline switch in OTHER tabs. `storage` fires only in the tabs+// that did not make the change — which is precisely the set that has an open+// socket it does not yet know to close (GHSA-5c3x-xqp6-g94r).+startNetGuard()+// Chrome direction follows the VIEWER's language (Arabic/Hebrew/… get an RTL// interface). Deliberately AFTER capturePristine: saves re-serialize the// pristine clone, so the dir/lang attributes never reach a saved file — thediff --git a/slides/src/packs.ts b/slides/src/packs.tsindex 4b7c496a..88c94d66 100644--- a/slides/src/packs.ts+++ b/slides/src/packs.ts@@ -22,6 +22,7 @@ import { appConfig } from '../../kernel/src/app.ts'import { addPack, removePack, type LanguagePack } from '../../kernel/src/i18n.ts'import { readShellBlocks, type ShellBlock } from '../../kernel/src/save.ts'import { fetchPinned, verifySigned } from '../../kernel/src/update.ts'+import { netFetch } from '../../kernel/src/net.ts'// Extension-explicit like the kernel imports above, so this module also loads// under plain node — scripts/test-packs.ts exercises the real thing.import { PACKED } from './i18n/packed.ts'@@ -138,7 +139,7 @@ export async function fetchPack(listing: PackListing): Promise<LanguagePack | Pa// offline / it isn't published" from "those bytes are not the pack we// were promised". Either way nothing unverified is returned.try {- return (await fetch(url, { cache: 'no-store', method: 'HEAD' })).ok ? 'unverified' : 'offline'+ return (await netFetch(url, { cache: 'no-store', method: 'HEAD' })).ok ? 'unverified' : 'offline'} catch {return 'offline'}@@ -227,7 +228,7 @@ export function shellBlocksForPacks(): ShellBlock[] {*/async function fetchIndex(): Promise<PackListing[]> {try {- const res = await fetch(`${channel()}/packs.json`, { cache: 'no-store' })+ const res = await netFetch(`${channel()}/packs.json`, { cache: 'no-store' })if (!res.ok) return []const payload = (await verifySigned(await res.text(), 'language pack index')) as {app?: unknowndiff --git a/slides/src/render.ts b/slides/src/render.tsindex 86cd4c78..4f881728 100644--- a/slides/src/render.ts+++ b/slides/src/render.ts@@ -3,6 +3,7 @@// Shared model → DOM renderer. One code path draws slides everywhere:// editor canvas, sidebar thumbnails, and Reveal.js sections.+import { offlineEnabled, isRemoteUrl, remoteSrcBlocked } from '../../kernel/src/net.ts'import type { BentoDoc, ShapeElement, Slide, SlideElement, SvgElement, TableElement } from './model'import { morphKey, paginates } from './model'import { chartSnapshotSvg } from './charts'@@ -79,6 +80,58 @@ export function resolveAsset(doc: BentoDoc, ref: string): string {return ref.startsWith('asset:') ? (doc.assets?.[ref.slice(6)] ?? '') : ref}+/**+ * The src to actually put on an element, or '' when offline mode must not let+ * it out. Media and images are loaded by the BROWSER from a src attribute,+ * not by us from a fetch — so no wrapper around fetch() can see them, and a+ * deck's remote <video> sailed straight through the offline switch+ * (GHSA-5c3x-xqp6-g94r: measured, 4 requests). A remote src in a document is+ * also a tracking beacon, and offline mode is exactly what a careful reader+ * turns on before opening a deck they do not trust.+ *+ * Callers must OMIT the attribute rather than set it to '', because+ * `video.src = ''` resolves against the page and makes browsers request the+ * document's own URL — a blank src is a request, not the absence of one.+ */+export function assetSrc(doc: BentoDoc, ref: string): string {+ const url = resolveAsset(doc, ref)+ return remoteSrcBlocked(url) ? '' : url+}++/** Attributes a browser will go to the network for, all element types. */+const URL_ATTRS = ['src', 'href', 'xlink:href', 'poster', 'srcset', 'data'] as const++/**+ * Last line of defence for offline mode: strip every remote reference from a+ * rendered subtree.+ *+ * assetSrc covers the srcs the RENDERER emits, but author content is markup —+ * an svg's `<image href="https://…">` (which the sanitizer allows on purpose,+ * because it is a legitimate picture), an `<img>` inside a text box or a table+ * cell — and that markup is injected as HTML without passing through any of+ * our src helpers. A browser fetches those the moment they are in the+ * document. No wrapper around fetch() can see it and no allowlist can, since+ * the markup is perfectly legitimate; the only question offline mode asks is+ * where it POINTS.+ *+ * A remote reference in a document you were sent is also the cheapest tracking+ * beacon there is, and offline mode is precisely what a careful reader turns+ * on before opening one.+ */+export function stripRemoteRefs(node: HTMLElement): void {+ if (!offlineEnabled()) return+ const all = [node, ...node.querySelectorAll<HTMLElement>('*')]+ for (const e of all) {+ for (const a of URL_ATTRS) {+ const v = e.getAttribute?.(a)+ if (v && isRemoteUrl(v)) {+ e.removeAttribute(a)+ e.dataset.bentoOffline = '1'+ }+ }+ }+}+function svgMarkup(el: SvgElement, doc: BentoDoc): string {return (el.asset ? doc.assets?.[el.asset] : el.markup) ?? ''}@@ -975,7 +1028,9 @@ export function renderElement(el: SlideElement, doc: BentoDoc, opts: RenderOptsbreakcase 'image': {const img = document.createElement('img')- img.src = resolveAsset(doc, el.src)+ const imgSrc = assetSrc(doc, el.src)+ if (imgSrc) img.src = imgSrc+ else img.dataset.bentoOffline = '1'img.draggable = falseimg.style.cssText = `width:100%;height:100%;object-fit:${el.fit};border-radius:${el.radius}px;display:block`node.appendChild(img)@@ -990,7 +1045,8 @@ export function renderElement(el: SlideElement, doc: BentoDoc, opts: RenderOptsstill.style.cssText = `width:100%;height:100%;border-radius:${radius}px;display:flex;align-items:center;justify-content:center;overflow:hidden;background:${el.kind === 'video' ? '#0b0f14' : '#e7edf4'}`if (el.kind === 'video' && el.poster) {const img = document.createElement('img')- img.src = resolveAsset(doc, el.poster)+ const posterSrc = assetSrc(doc, el.poster)+ if (posterSrc) img.src = posterSrcimg.style.cssText = `width:100%;height:100%;object-fit:${el.fit ?? 'contain'};display:block`still.appendChild(img)} else {@@ -1009,7 +1065,8 @@ export function renderElement(el: SlideElement, doc: BentoDoc, opts: RenderOpts// and looked odd) — only centre it in the element box. Size the box to// the control's ~54px intrinsic height (defaultMedia audio uses 56).const audio = document.createElement('audio')- if (el.src) audio.src = resolveAsset(doc, el.src)+ const audioSrc = assetSrc(doc, el.src)+ if (audioSrc) audio.src = audioSrcaudio.controls = el.controls !== falseaudio.loop = !!el.loopaudio.preload = 'metadata'@@ -1025,8 +1082,11 @@ export function renderElement(el: SlideElement, doc: BentoDoc, opts: RenderOptsbreak}const video = document.createElement('video')- if (el.src) video.src = resolveAsset(doc, el.src)- if (el.poster) video.poster = resolveAsset(doc, el.poster)+ const videoSrc = assetSrc(doc, el.src)+ if (videoSrc) video.src = videoSrc+ else if (el.src) video.dataset.bentoOffline = '1'+ const posterUrl = assetSrc(doc, el.poster ?? '')+ if (posterUrl) video.poster = posterUrlvideo.controls = el.controls !== falsevideo.loop = !!el.loopvideo.muted = el.muted !== false@@ -1090,6 +1150,9 @@ export function renderElement(el: SlideElement, doc: BentoDoc, opts: RenderOptsbreak}}+ // Every element type funnels through here, so this is the one place that+ // sees author markup after it has been built into DOM.+ stripRemoteRefs(node)return node}diff --git a/slides/src/sync/blobs.ts b/slides/src/sync/blobs.tsindex 65a6e17d..41c64ce0 100644--- a/slides/src/sync/blobs.ts+++ b/slides/src/sync/blobs.ts@@ -26,6 +26,10 @@const CHUNK = 4 * 1024 * 1024/** Must match the relay's MAX_BLOB. NOTE this bounds the ENCODED blob, not the* plaintext — the relay measures what it receives. */+// 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 { netFetch } from '../../../kernel/src/net.ts'+export const MAX_BLOB = 8 * 1024 * 1024const MAGIC = 0x4242 // 'BB'const HEADER = 16@@ -238,7 +242,7 @@ export async function putBlob(e: BlobEndpoint, rawRoomKey: Uint8Array, bytes: Uiif (encodedSize(bytes.length) > MAX_BLOB) return { ok: false, reason: 'too-large' }const key = await blobKey(rawRoomKey, bytes)try {- const head = await fetch(url(e, key), { method: 'HEAD' })+ const head = await netFetch(url(e, key), { method: 'HEAD' })if (head.status === 200) {void cachePut(key, bytes)return { ok: true, key, deduped: true }@@ -246,7 +250,7 @@ export async function putBlob(e: BlobEndpoint, rawRoomKey: Uint8Array, bytes: Uiif (head.status === 501) return { ok: false, reason: 'unsupported' }if (head.status === 403) return { ok: false, reason: 'forbidden' }const body = await encodeBlob(rawRoomKey, bytes)- const res = await fetch(url(e, key), {+ const res = await netFetch(url(e, key), {method: 'PUT', body: body as BodyInit,headers: { 'content-type': 'application/octet-stream' },})@@ -288,7 +292,7 @@ export async function getBlob(e: BlobEndpoint, rawRoomKey: Uint8Array, key: stri// not a rejection. session.resolveBlobs has try/finally and no catch, so a// throw here escapes as an unhandled rejection.if (hit && await addressMatches(rawRoomKey, key, hit)) return hit- const res = await fetch(url(e, key))+ const res = await netFetch(url(e, key))if (!res.ok) return nullconst enc = new Uint8Array(await res.arrayBuffer())const plain = await decodeBlob(rawRoomKey, enc)diff --git a/slides/src/sync/online.ts b/slides/src/sync/online.tsindex ab7585fa..c0be426f 100644--- a/slides/src/sync/online.ts+++ b/slides/src/sync/online.ts@@ -15,6 +15,7 @@ import type { BentoDoc } from '../model'import type { Op, SyncStateJSON } from './crdt'import type { Frame, RefusalCode, SyncSession, Transport } from './session'import { offlineEnabled } from '../update'+import { netWebSocket } from '../../../kernel/src/net.ts'import { lsGet, lsSet } from '../../../kernel/src/storage.ts'export const DEFAULT_SYNC_HOST = 'wss://sync.bento.page'@@ -315,9 +316,11 @@ export class OnlineTransport implements Transport {this.setStatus('connecting')let ws: WebSockettry {- ws = new WebSocket(`${this.url}&since=${this.lastSeq()}`)+ ws = netWebSocket(`${this.url}&since=${this.lastSeq()}`)} catch {- this.retry()+ // Offline is a decision, not an outage: retrying would spin until the+ // switch flips, and net.ts has closed anything already open anyway.+ if (!offlineEnabled()) this.retry()return}this.ws = ws