Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
tray/webext: a new document is verified before it is written (#318)
nyblnet7b227ba89767
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c25894a7..06b511f0 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -334,6 +334,20 @@ jobs:# document carrying an image.run: node scripts/test-webext-library.ts+ - name: WebExtension release-trust rig+ # Creating a document downloads an app shell and writes it to the user's+ # disk, where they later double-click it — executable HTML they go on to+ # trust. So the manifest's signature is checked against the key compiled+ # into the extension, and the download against the digest that signature+ # covers. Signature over the pin, pin over the bytes.+ #+ # It also reads a REAL manifest captured from the release origin, which+ # is the check that could not be faked into passing: the shipped code+ # read `url` off the top level of a SIGNED ENVELOPE that has no top-level+ # url, so the + button had never worked in any version — and the rig+ # agreed, because its fixture was written to the shape the code wanted.+ run: node scripts/test-webext-release.ts+- name: WebExtension update-notice rig# Store installs update themselves; one loaded unpacked never will, and# Chrome ignores update_url for a development install. So the GitHubdiff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 2b5ca227..51be409e 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -287,6 +287,104 @@ a notes app may never blur — while a page changes only when somebodynavigates, which is the rate presence is worth.---+## 2026-08-16 — Creating a document: every host VERIFIES the release it downloads++**Decision.** Starter shells are bundled in no host (settled separately the same+day: they change too often, and there are three apps with more coming), so+fetch-from-the-release-channel is the ONLY way any tray host creates a document.+That path must therefore verify, in this order, in every host:++1. fetch the manifest **as text** — it is a signed envelope, `{payload, sig}`,+ and the fields (`app`, `version`, `sha256`, `url`) are inside the payload+ STRING; there is nothing useful at the top level;+2. verify the ECDSA P-256 / SHA-256 signature over the payload's **exact UTF-8+ bytes** (no canonicalisation) against the release public key;+3. check the payload's `app` matches the channel being read — the channels are+ sibling paths on one origin, so a genuine manifest from the wrong path hands+ somebody a different application;+4. download the shell and check its sha256 against the payload's pin;+5. only then touch a file handle. A refusal writes **nothing**.++**Why.** The shell is executable HTML written to the user's own disk, which they+subsequently double-click and trust. Without the chain, whoever can answer for+the release origin — compromised host, bad CDN edge, hostile-network proxy —+chooses what code the user creates. Signature over the pin, pin over the bytes;+neither half is worth anything alone.++Step 3 is the one that is invisible to the other two, so it is the one that gets+skipped: a `bento-slides` manifest and a `bento-dash` manifest are both+genuinely signed by the same key, and the shell each points at really does hash+to what its payload pins. Serving one on the other's channel passes the+signature AND the digest — every byte authentic, just not what was asked for.+Only identity catches a swap between two REAL releases, which is exactly what+survives an origin or CDN compromise where the attacker cannot forge but can+re-serve. The check must be made against the app that was **requested**, not+against the payload's own claim about itself, and an ABSENT `app` must not read+as a match. (`tray/ios` found both native hosts missing this while reviewing+webext's rig — PR #315, PR #318.)++**Ask for BYTES: send `Accept: */*` explicitly on every release fetch.**+Measured against the live shell URL on 2026-08-17, independently by tray/ios and+tray/webext: the wildcard returns 689,316 bytes and matches the signed pin; a+browser's own `Accept: text/html,…` returns 689,675 and does not. The extra 359+bytes are a Cloudflare Web Analytics beacon the edge injects before `</body>`+into anything it reads as a page being browsed. Same URL, same `.bento.html`+extension both times, so the trigger is the header — fortunate, because a+path-keyed injection could not be avoided by any host. Most platforms already+default to the wildcard; set it anyway, because the default is the platform's+and not ours. (An earlier note that this was "fixed at the origin" was wrong and+is retracted — it is live as of this entry.)++**NO DOWNGRADES: every host keeps a per-app version floor.** Decided by Andy on+2026-08-17, after `tray/ios` implemented one and `tray/webext` held pending the+call — it is a policy trade, not a pure security win, and three hosts+half-adopting it would be worse than one landing late. A replayed OLD release+passes signature, app identity AND digest: it is genuinely signed and its shell+really does hash to its pin. Only memory catches it, because a document being+created carries no version to be monotonic against (unlike the shell's own+update, which measures from its running build). Two details that bite:++- **Raise the floor only AFTER the downloaded bytes pass their hash.** Raising+ it on a merely-verified manifest lets one forged-but-unfetchable release lock+ the host out of every real release below it — a failed attack made permanent.+- **An EQUAL version must be accepted.** Re-fetching the version already held is+ the normal case (the second document somebody creates), and refusing it breaks+ creation on its second use rather than at some exotic edge.++An unreadable store reads as NO floor: availability over protection in a case+that is not an attack. An unparsable version component sorts as 0 rather than+throwing — verified identical in `kernel/src/update.ts`, `tray/webext`'s+`compareVersions` and `Releases.swift`, since `Number('x')` is NaN and+`NaN || 0` is 0. **The accepted cost:** a deliberate maintainer rollback is+refused until the version moves past the floor. That is the same trade+`kernel/src/update.ts` already makes, so the whole system is at least+consistent.++**A 404 on a channel is an ANSWER, not a fault.** Only Slides is published+today; the app list is aspirational on every host. All three say+"<App> has not been released yet" rather than surfacing an HTTP status.++**Status.** `tray/webext` done (`src/release.js`, used by `library.js+newDocument`); `tray/ios` done (`Releases.swift`, PR #315); `tray/android` in+progress.++**Pointers.** `kernel/src/update.ts` is the reference implementation+(`verifySigned` / `fetchPinned` / `verifyManifest`) and hosts should reuse it+where they can import it. The extension **cannot** — it ships as unbundled ES+modules Chrome loads from disk, and adding a bundler would mean the shipped+package is no longer the reviewed source — so `tray/webext/src/release.js` is a+deliberate line-by-line mirror, with the resulting obligation stated in the+file: *if the key or the envelope format moves in the kernel, it moves here+too.* `scripts/test-webext-release.ts` pins both ends against a REAL captured+manifest (`scripts/fixtures/release-manifest-slides.json`).++**The failure this came out of, because it generalises.** `newDocument` read+`manifest.url` off the envelope's top level, where there is no `url`, and so+threw on every invocation: the `+` button had never worked in any version. Its+rig passed, because the fixture was written to the shape the CODE expected+rather than the shape the SERVER sends. A fixture that is not the real shape+proves only that the code agrees with itself — hence the captured manifest, and+hence the same warning for android and ios.## 2026-08-16 — Document search: the list stays native, the indexer is shared by FIXTUREdiff --git a/scripts/fixtures/release-manifest-slides.json b/scripts/fixtures/release-manifest-slides.jsonnew file mode 100644index 00000000..d8343bfe--- /dev/null+++ b/scripts/fixtures/release-manifest-slides.json@@ -0,0 +1,4 @@+{+ "payload": "{\"app\":\"bento-slides\",\"version\":\"1.0.18\",\"sha256\":\"9fef088beb763e86a7c13b6b5e2226816a9e8e1c61331f0c5270fdd5cf538424\",\"url\":\"https://bento.page/releases/slides/Bento_Slides.bento.html\",\"notes\":\"• Security: offline mode did not block everything it promised.\\n• Updating a file no longer interrupts you.\\n• Fix: Share opened cut in half on a narrow window.\\n• The update card drops its peach stripe.\\n• Security: update this file. A deck could run code hidden in its own content. (1.0.17)\\n• A dark interface, if you want one. (1.0.17)\\n…and 8 more\",\"notesFrom\":{\"1.0.18\":[\"Security: offline mode did not block everything it promised.\",\"Updating a file no longer interrupts you.\",\"Fix: Share opened cut in half on a narrow window.\",\"The update card drops its peach stripe.\"],\"1.0.17\":[\"Security: update this file. A deck could run code hidden in its own content.\",\"A dark interface, if you want one.\",\"Hide a slide from the show.\",\"A deck that is being shared now says so before an agent reads it.\",\"Fix: a live session could crash when two people created the same element at the same moment.\",\"Fix: the end of the toolbar could be cut off the right edge.\",\"Fix: on a narrow window, the ⋯ menu could not be clicked.\",\"Fix: choosing a custom slide size now reveals its width and height.\"],\"1.0.16\":[\"Fix: the slide could open off-centre, pushed to one side and clipped.\"],\"1.0.15\":[\"Fix: removing a formatting option no longer disconnects the people you are working with.\",\"\\\"Save a copy…\\\" and share exports remember their own folder.\",\"Fix: the topbar came back in the wrong order after the window narrowed and widened again.\",\"Fix: a deck opens where the browser refuses it storage.\"],\"1.0.14\":[\"Pan the canvas by dragging, and past the slide's edges.\",\"Fit a text box to its text, in one click.\",\"Entrances and count-ups now run on morph slides.\",\"Fix: the built-in layouts fit the slide.\",\"Check a deck for what the runtime silently swallows.\",\"Fix: two gallery templates asked for a typeface they did not carry.\",\"The agent authoring guide describes what the runtime actually does.\"],\"1.0.13\":[\"Fix: fade, slide and zoom transitions animate again.\",\"Copy and paste keeps embedded typefaces intact.\",\"Update notes now cover every version you skipped.\"]},\"at\":\"2026-08-15T19:48:04.509Z\"}",+ "sig": "iqII5phREEUo9st7o3HkNoQifZobKbAY/h9Oeq6ibXjGOJf+uaWjIV7PMtCGW75CT4Wek1rJ6iPFF7OGvjtYIg=="+}diff --git a/scripts/lib/release-sign.ts b/scripts/lib/release-sign.tsnew file mode 100644index 00000000..57f36406--- /dev/null+++ b/scripts/lib/release-sign.ts@@ -0,0 +1,56 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// A throwaway release channel, for rigs that have to exercise verification.+//+// The real signing key is offline by design (docs/RELEASING.md) and never+// reaches CI, so a rig cannot produce a manifest the shipped public key will+// accept. It can produce a whole channel of its own instead: generate a+// keypair, sign payloads with the private half, and hand the public half to the+// verifier through the same test seam that already substitutes `fetch`.+//+// That covers everything EXCEPT "is the embedded key the real one, and is the+// envelope still shaped the way the server shapes it" — which is precisely the+// half a self-consistent fixture cannot prove, and precisely the half that was+// wrong. `scripts/fixtures/release-manifest-slides.json` is a real manifest+// captured from https://bento.page/releases/slides/manifest.json for that, and+// it verifies against the SHIPPED key with no seam involved.++import { readFileSync } from 'node:fs'++export type Signer = {+ /** Public half, in the JWK shape the verifiers embed. */+ jwk: { kty: string; crv: string; x: string; y: string }+ /** Sign a payload object → the `{payload, sig}` envelope, as served text. */+ envelope(payload: unknown): Promise<string>+}++export async function releaseSigner(): Promise<Signer> {+ const kp = await crypto.subtle.generateKey(+ { name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify'],+ ) as CryptoKeyPair+ const pub = await crypto.subtle.exportKey('jwk', kp.publicKey)+ return {+ jwk: { kty: pub.kty!, crv: pub.crv!, x: pub.x!, y: pub.y! },+ async envelope(payload: unknown) {+ // Signed over the payload's exact bytes AS A STRING — the same reason the+ // envelope carries a string rather than an object. A rig that re-encoded+ // here would pass while the real thing failed.+ const text = JSON.stringify(payload)+ const sig = await crypto.subtle.sign(+ { name: 'ECDSA', hash: 'SHA-256' }, kp.privateKey,+ new TextEncoder().encode(text),+ )+ return JSON.stringify({ payload: text, sig: Buffer.from(sig).toString('base64') })+ },+ }+}++/** Lowercase hex sha256 — what every pin in this project is written as. */+export const sha256Hex = async (bytes: BufferSource): Promise<string> =>+ [...new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))]+ .map((b) => b.toString(16).padStart(2, '0')).join('')++/** A real manifest, as the release origin actually served it. */+export const realManifest = (): string =>+ readFileSync(new URL('../fixtures/release-manifest-slides.json', import.meta.url), 'utf8')diff --git a/scripts/test-webext-library.ts b/scripts/test-webext-library.tsindex 4fca0972..fba10176 100644--- a/scripts/test-webext-library.ts+++ b/scripts/test-webext-library.ts@@ -22,6 +22,7 @@import { existsSync, readFileSync } from 'node:fs'import { listDocuments, describe, newDocument, duplicate, rename, APPS } from '../tray/webext/src/library.js'+import { releaseSigner, sha256Hex } from './lib/release-sign.ts'let failures = 0let checks = 0@@ -323,26 +324,52 @@ if (existsSync(REAL)) {}// ---- 4. new document ---------------------------------------------------------const fakeNet = (version = '1.0.17', html = '<html>shell</html>') => async (url: string) => ({- ok: true,- async json() { return { version, url: 'https://bento.page/releases/slides/Bento_Slides.bento.html' } },- async text() { return html },- url,-})+// The release channel is SIGNED, and these fixtures are signed too — with a+// throwaway key, handed to `newDocument` through the same seam that substitutes+// `fetch`. What this section tests is naming and dispatch; the trust chain+// itself, and the real captured manifest that pins its format, live in+// `scripts/test-webext-release.ts`.+//+// They are signed here rather than faked because the fixture in this slot used+// to be `{version, url}` flat — the shape the CODE wanted, not the shape the+// SERVER sends — and it passed, cheerfully, for a `newDocument` that threw on+// every real invocation. A fixture that is not the real shape tests nothing.+const SHELL = '<html>shell</html>'+const signer = await releaseSigner()+const RELEASE_URL = 'https://bento.page/releases/slides/Bento_Slides.bento.html'++const fakeNet = (version = '1.0.17', html = SHELL, app = 'bento-slides') => {+ // The manifest pins the shell it is serving. Computed from the bytes this+ // fixture will actually hand back, so the fixture cannot drift out of its own+ // pin — and so a test that wants a MISMATCH has to arrange one deliberately.+ const envelope = sha256Hex(new TextEncoder().encode(html))+ .then((sha256) => signer.envelope({ app, version, url: RELEASE_URL, sha256 }))+ return async (url: string) => url.endsWith('manifest.json')+ ? { ok: true, status: 200, async text() { return await envelope }, url }+ : {+ ok: true,+ status: 200,+ async arrayBuffer() { return new TextEncoder().encode(html).buffer },+ url,+ }+}+const signedDeps = (net: any, extra: Record<string, unknown> = {}) =>+ ({ fetch: net, jwk: signer.jwk, ...extra })+{written.clear()const tree: Record<string, any> = {}const dir = dirHandle('Decks', tree)- const made = await newDocument(dir as any, 'Untitled', { fetch: fakeNet() })+ const made = await newDocument(dir as any, 'Untitled', signedDeps(fakeNet()))ok(made.name === 'Untitled.bento.html', 'the first new document is Untitled.bento.html')- ok(written.get('Untitled.bento.html') === '<html>shell</html>',+ ok(written.get('Untitled.bento.html') === SHELL,'and carries the downloaded release, so it is the same version everyone else has')}{written.clear()const tree: Record<string, any> = { 'Untitled.bento.html': fileHandle('Untitled.bento.html') }const dir = dirHandle('Decks', tree)- const made = await newDocument(dir as any, 'Untitled', { fetch: fakeNet() })+ const made = await newDocument(dir as any, 'Untitled', signedDeps(fakeNet()))// UIKit's own de-duplicator produces "Untitled.bento 2.html" here, because it// reads `.bento.html` as the name "Untitled.bento" plus extension "html" and// counts before the LAST extension only. tray/ios had to write its own for@@ -354,17 +381,18 @@ const fakeNet = (version = '1.0.17', html = '<html>shell</html>') => async (url:{const dir = dirHandle('Decks', {})let threw = ''- await newDocument(dir as any, 'X', { fetch: async () => ({ ok: false, status: 503 }) })+ await newDocument(dir as any, 'X', signedDeps(async () => ({ ok: false, status: 503 }))).catch((e: any) => { threw = e.message })ok(/release server/.test(threw), `an unreachable release server is reported, not silent (${threw})`)}{const dir = dirHandle('Decks', {})let threw = ''- await newDocument(dir as any, 'X', {- fetch: async () => ({ ok: true, async json() { return {} } }),- }).catch((e: any) => { threw = e.message })- ok(/did not offer a build/.test(threw), 'a manifest with no build is reported rather than written as empty')+ await newDocument(dir as any, 'X', signedDeps(+ async () => ({ ok: true, status: 200, async text() { return '{}' } })))+ .catch((e: any) => { threw = e.message })+ ok(/not signed/.test(threw),+ `a manifest that offers no signed build is reported rather than written as empty (${threw})`)}// ---- 5. duplicate and rename ------------------------------------------------@@ -470,27 +498,21 @@ const fakeNet = (version = '1.0.17', html = '<html>shell</html>') => async (url:{written.clear()const asked: string[] = []- const net = async (url: string) => {- asked.push(url)- return {- ok: true,- async json() { return { version: '1.0.0', url: 'https://bento.page/x.bento.html' } },- async text() { return '<html>spaces</html>' },- }- }+ const inner = fakeNet('1.0.0', '<html>spaces</html>', 'bento-spaces')+ const net = async (url: string) => { asked.push(url); return inner(url) }const dir = dirHandle('Decks', {})- const made = await newDocument(dir as any, 'Untitled', { fetch: net, app: 'spaces' })+ const made = await newDocument(dir as any, 'Untitled', signedDeps(net, { app: 'spaces' }))ok(asked[0].includes('/spaces/'), `the chosen app's channel is used (${asked[0]})`)ok(made.app === 'Spaces', `and the result says what was made (${made.app})`)+ ok(written.get('Untitled.bento.html') === '<html>spaces</html>',+ 'and it is the Spaces build that lands, not whatever the first channel serves')}{// An unknown app must not silently fetch nothing, nor pick at random.const asked: string[] = []- const net = async (url: string) => {- asked.push(url)- return { ok: true, async json() { return { version: '1', url: 'https://x/y' } }, async text() { return 'x' } }- }- await newDocument(dirHandle('Decks', {}) as any, 'Untitled', { fetch: net, app: 'nonsense' })+ const inner = fakeNet()+ const net = async (url: string) => { asked.push(url); return inner(url) }+ await newDocument(dirHandle('Decks', {}) as any, 'Untitled', signedDeps(net, { app: 'nonsense' }))ok(asked[0] === APPS[0].manifest,'an unknown app falls back to the first, rather than requesting an invented URL')}diff --git a/scripts/test-webext-release.ts b/scripts/test-webext-release.tsnew file mode 100644index 00000000..7863ebbc--- /dev/null+++ b/scripts/test-webext-release.ts@@ -0,0 +1,414 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// tray/webext release-trust rig.+//+// node scripts/test-webext-release.ts+//+// WHAT THIS PROVES. Creating a document downloads an app shell and writes it to+// the user's disk, where they will later double-click it. That is executable+// HTML, so the download has to be earned: the manifest's signature against the+// key compiled into the extension, then the shell's sha256 against the digest+// that signature covers. Signature over the pin, pin over the bytes. Neither+// half alone is worth anything — a signature with no pin verifies a description+// of a build, and a pin with no signature is a digest chosen by whoever served+// the bytes.+//+// WHY IT EXISTS AT ALL. `newDocument` read `manifest.url` off the top level of+// the envelope, where there is no `url`. It threw "the release server did not+// offer a build" every single time: the `+` button had never worked, in any+// version, and nothing said so. The rig agreed with the bug, because its+// fixture was written to the shape the CODE expected — `{version, url}` flat —+// rather than the shape the SERVER sends. A self-consistent fixture proves the+// code agrees with itself.+//+// So the load-bearing check here is not a hand-written envelope: it is+// `scripts/fixtures/release-manifest-slides.json`, captured verbatim from+// https://bento.page/releases/slides/manifest.json, verified against the+// SHIPPED public key with no test seam in the path. If the envelope format+// moves, or the embedded key drifts from the kernel's, that fixture stops+// verifying here instead of the `+` button stopping working out there.+//+// This matters more than it did. Starter shells are bundled in NO host as of+// 2026-08-16 (they change too often, and there are three apps with more+// coming), so fetch-and-verify is the ONLY way a new document gets created —+// here, in tray/android, and in tray/ios.++import { readFileSync } from 'node:fs'+import {+ RELEASE_KEY, verifySigned, verifyManifest, fetchPinned,+} from '../tray/webext/src/release.js'+import { newDocument, APPS } from '../tray/webext/src/library.js'+import { releaseSigner, sha256Hex, realManifest } from './lib/release-sign.ts'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}+const threw = async (fn: () => Promise<unknown>): Promise<string> => {+ try { await fn(); return '' } catch (e: any) { return e?.message ?? 'threw' }+}++// ---- 1. the envelope, as the server actually sends it -----------------------+// THE REGRESSION. Every assertion in this block would have failed the code that+// shipped, and none of them needs a key or a network.+{+ const raw = realManifest()+ const envelope = JSON.parse(raw)+ ok(Object.keys(envelope).sort().join(',') === 'payload,sig',+ `a manifest is exactly {payload, sig} (${Object.keys(envelope).join(', ')})`)+ ok(typeof envelope.payload === 'string',+ 'and the payload is a STRING — the signature covers its exact bytes, so it '+ + 'cannot travel as an object without making the check depend on key order')+ ok(envelope.url === undefined && envelope.version === undefined && envelope.sha256 === undefined,+ 'there is NO url, version or sha256 at the top level — reading one is the bug this rig exists for')++ const info = JSON.parse(envelope.payload)+ ok(info.app === 'bento-slides' && typeof info.version === 'string',+ `the fields live inside the payload (${info.app} ${info.version})`)+ ok(/^[0-9a-f]{64}$/.test(info.sha256), 'and the payload pins the shell it describes')+}+{+ // No seam: the captured manifest against the compiled-in key.+ const info = await verifySigned(realManifest(), 'release manifest') as any+ ok(info.app === 'bento-slides',+ 'a REAL manifest verifies against the shipped public key — which proves the '+ + 'key is right and the envelope format has not moved')+}+{+ // A valid signature under a key we do not trust — and NO test seam: the REAL+ // payload, re-signed with a throwaway key, handed to the shipped verifier+ // using the SHIPPED key. It must refuse.+ //+ // Distinct from bending a signature, which any bug-free crypto call rejects.+ // This one validates perfectly; it is simply not ours. It is what catches a+ // verifier that imported the wrong key, or one that would trust a key+ // travelling in the envelope alongside the signature — a verifier like that+ // passes every tampering test ever written. (tray/ios's construction, from+ // PR #315; it is better than the seam-based version I had.)+ const real = JSON.parse(realManifest())+ const impostor = await releaseSigner()+ const forged = JSON.parse(await impostor.envelope(JSON.parse(real.payload)))+ ok(forged.payload === real.payload, 'the impostor signs the genuine payload, byte for byte')+ const msg = await threw(() => verifySigned(JSON.stringify(forged), 'release manifest'))+ ok(/INVALID/.test(msg),+ `a real payload re-signed by another key is refused against the shipped key (${msg})`)+}+{+ // Mirrored code has one failure mode: drift. Pin both ends.+ const kernel = readFileSync(new URL('../kernel/src/update.ts', import.meta.url), 'utf8')+ // From the declaration onward, and `\b` on the coordinate names — `kty: 'EC'`+ // ends in `y:` and matches a lazy pattern, which reads as a key mismatch.+ const block = kernel.slice(kernel.indexOf('PUBLIC_KEY_JWK'))+ const x = block.match(/\bx:\s*'([A-Za-z0-9_-]+)'/)?.[1]+ const y = block.match(/\by:\s*'([A-Za-z0-9_-]+)'/)?.[1]+ ok(!!x && x === RELEASE_KEY.x && y === RELEASE_KEY.y,+ "the extension's key is byte-identical to the kernel's — the extension mirrors "+ + 'kernel/src/update.ts because it cannot import it, and a mirror drifts silently')+}++// ---- 2. what verification refuses -------------------------------------------+const signer = await releaseSigner()+const SHELL = '<html><!-- a real app shell would be 560KB --></html>'+const shellBytes = new TextEncoder().encode(SHELL)+const shellHash = await sha256Hex(shellBytes)+const payloadFor = (over: Record<string, unknown> = {}) => ({+ app: 'bento-slides',+ version: '1.0.18',+ sha256: shellHash,+ url: 'https://bento.page/releases/slides/Bento_Slides.bento.html',+ ...over,+})++{+ const raw = await signer.envelope(payloadFor())+ const info = await verifyManifest(raw, 'bento-slides', signer.jwk) as any+ ok(info.version === '1.0.18', 'a well-signed manifest verifies and yields its payload')+}+{+ const raw = await signer.envelope(payloadFor())+ const e = JSON.parse(raw)+ // One character, in the URL — the whole point of signing.+ e.payload = e.payload.replace('bento.page', 'bento.pagd')+ const msg = await threw(() => verifyManifest(JSON.stringify(e), 'bento-slides', signer.jwk))+ ok(/INVALID/.test(msg), `an edited payload is refused (${msg})`)+}+{+ const raw = await signer.envelope(payloadFor())+ const other = await releaseSigner()+ const msg = await threw(() => verifyManifest(raw, 'bento-slides', other.jwk))+ ok(/INVALID/.test(msg),+ `a manifest signed by somebody else is refused — a signature only means something against OUR key (${msg})`)+}+{+ // The shape the broken code believed in. It must not merely fail to find a+ // url: it must be refused for being unsigned.+ const msg = await threw(() => verifyManifest(+ JSON.stringify({ version: '9.9.9', url: 'https://evil.example/x.html', sha256: shellHash }),+ 'bento-slides', signer.jwk))+ ok(/not signed/.test(msg), `an unsigned flat manifest is refused outright (${msg})`)+}+{+ // A 404 page, a captive portal, a proxy's error — HTML where JSON was asked for.+ const msg = await threw(() => verifyManifest('<!DOCTYPE html><title>404</title>', 'bento-slides', signer.jwk))+ ok(/not valid JSON/.test(msg), `a page of HTML is reported, not parsed hopefully (${msg})`)+}+{+ // The channels are sibling paths on ONE origin, so a genuine manifest served+ // from the wrong one would hand somebody a different application.+ const raw = await signer.envelope(payloadFor())+ const msg = await threw(() => verifyManifest(raw, 'bento-spaces', signer.jwk))+ ok(/malformed/.test(msg),+ `a correctly signed manifest for ANOTHER app is refused on the wrong channel (${msg})`)+}+{+ // An ABSENT app must not read as a match. `undefined !== 'bento-slides'` gets+ // this right, but only by construction — a later refactor to something like+ // `info.app && info.app !== appId` would turn a missing field into a pass,+ // and no other check would notice: signature and digest are both happy.+ // (tray/ios raised this on PR #315; the same case, from the other direction.)+ const raw = await signer.envelope({+ version: '1.0.18', sha256: shellHash, url: 'https://bento.page/x.bento.html',+ })+ const msg = await threw(() => verifyManifest(raw, 'bento-slides', signer.jwk))+ ok(/malformed/.test(msg), `a payload naming no app at all is refused (${msg})`)+}+{+ const raw = await signer.envelope(payloadFor({ sha256: 'not-a-digest' }))+ const msg = await threw(() => verifyManifest(raw, 'bento-slides', signer.jwk))+ ok(/malformed/.test(msg), `a payload that pins nothing is refused (${msg})`)+}++// ---- 3. the pin, over the bytes ---------------------------------------------+const netFor = (body: string, status = 200) => async () => ({+ ok: status >= 200 && status < 300,+ status,+ async arrayBuffer() { return new TextEncoder().encode(body).buffer },+ async text() { return body },+})+{+ const bytes = await fetchPinned(netFor(SHELL), 'https://x/shell.html', shellHash)+ ok(new TextDecoder().decode(bytes) === SHELL, 'bytes matching the signed digest come back')+}+{+ const msg = await threw(() => fetchPinned(netFor(SHELL + '<script>evil()</script>'), 'https://x/s.html', shellHash))+ ok(/does not match the signed release/.test(msg),+ `bytes that do not hash to the pin are refused — this is the half that catches a swapped download (${msg})`)+}+{+ const msg = await threw(() => fetchPinned(netFor('', 404), 'https://x/s.html', shellHash))+ ok(/could not download/.test(msg), `a missing shell is reported (${msg})`)+}+{+ const msg = await threw(() => fetchPinned(netFor(SHELL), 'https://x/s.html', ''))+ ok(/not pinned/.test(msg), 'an unpinned release is refused rather than fetched and hoped over')+}+{+ // The header is load-bearing, and its absence is silent. Measured 2026-08-17:+ // the live release URL serves 689,675 bytes to a browser-shaped Accept and+ // 689,316 — the signed ones — to the wildcard, the difference being an+ // analytics beacon the edge injects into anything it reads as a page. Asking+ // for a page here would mean the digest check refuses every real download.+ const seen: any[] = []+ const net = async (_u: string, init: any) => {+ seen.push(init)+ return { ok: true, status: 200, async arrayBuffer() { return new TextEncoder().encode(SHELL).buffer } }+ }+ await fetchPinned(net, 'https://x/s.html', shellHash)+ ok(seen[0]?.headers?.Accept === '*/*',+ `the shell is fetched asking for BYTES, not for a page (${JSON.stringify(seen[0]?.headers)})`)+ ok(seen[0]?.cache === 'no-store', 'and uncached — a stale shell is a stale document')+}+{+ // Hex case is a presentation choice, not a difference.+ const bytes = await fetchPinned(netFor(SHELL), 'https://x/s.html', shellHash.toUpperCase())+ ok(bytes.byteLength > 0, 'a digest written in upper case still matches')+}++// ---- 4. end to end, through newDocument -------------------------------------+// A fake directory that records what was actually written, because the only+// failure that matters is unverified bytes reaching a file handle.+const written = new Map<string, string>()+const dirHandle = () => {+ const tree = new Set<string>()+ return {+ kind: 'directory' as const,+ name: 'Decks',+ written,+ async getFileHandle(n: string, opts?: { create?: boolean }) {+ if (!tree.has(n) && !opts?.create) throw Object.assign(new Error(n), { name: 'NotFoundError' })+ tree.add(n)+ return {+ kind: 'file' as const,+ name: n,+ async createWritable() {+ return {+ async write(chunk: any) {+ written.set(n, typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk))+ },+ async close() {},+ }+ },+ }+ },+ }+}++/** A release channel that answers both requests: manifest, then shell. */+const channel = (manifestRaw: string, shell = SHELL, shellStatus = 200) => async (url: string) =>+ url.endsWith('manifest.json')+ ? { ok: true, status: 200, async text() { return manifestRaw } }+ : {+ ok: shellStatus >= 200 && shellStatus < 300,+ status: shellStatus,+ async arrayBuffer() { return new TextEncoder().encode(shell).buffer },+ }++{+ written.clear()+ const good = channel(await signer.envelope(payloadFor()))+ const made = await newDocument(dirHandle() as any, 'Untitled', { fetch: good, jwk: signer.jwk })+ ok(made.name === 'Untitled.bento.html' && made.version === '1.0.18',+ `a verified release is written, and reports the version it wrote (${made.version})`)+ ok(written.get('Untitled.bento.html') === SHELL,+ 'and the file holds the downloaded shell — the whole feature, which had never once run')+}+{+ // The bug, exactly: the envelope, read by code that wants a flat manifest.+ // Kept as a standing check that nobody "simplifies" the parse back.+ written.clear()+ const flat = JSON.stringify({ version: '1.0.18', url: 'https://bento.page/x.html', sha256: shellHash })+ const msg = await threw(() => newDocument(dirHandle() as any, 'Untitled', {+ fetch: channel(flat), jwk: signer.jwk,+ }))+ ok(/not signed/.test(msg), `an unsigned manifest stops the whole thing (${msg})`)+ ok(written.size === 0, 'and NOTHING is written — a half-created document is a document the user will open')+}+{+ written.clear()+ const swapped = channel(await signer.envelope(payloadFor()), '<html>swapped payload</html>')+ const msg = await threw(() => newDocument(dirHandle() as any, 'Untitled', {+ fetch: swapped, jwk: signer.jwk,+ }))+ ok(/does not match the signed release/.test(msg),+ `a shell that is not the signed one is refused (${msg})`)+ ok(written.size === 0,+ 'and nothing lands on disk — the file would be executable HTML the user goes on to trust')+}+{+ written.clear()+ const other = await releaseSigner()+ const forged = channel(await other.envelope(payloadFor()))+ const msg = await threw(() => newDocument(dirHandle() as any, 'Untitled', {+ fetch: forged, jwk: signer.jwk,+ }))+ ok(/INVALID/.test(msg) && written.size === 0,+ 'a manifest from the wrong key writes nothing — a network attacker cannot choose what the user creates')+}+{+ // Spaces and Dash have no published release yet: the channel 404s. The user+ // asked for a document and must be told why they have not got one.+ written.clear()+ const msg = await threw(() => newDocument(dirHandle() as any, 'Untitled', {+ app: 'spaces', jwk: signer.jwk,+ fetch: async () => ({ ok: false, status: 404, async text() { return '<html>404</html>' } }),+ }))+ ok(/Spaces has not been released yet/.test(msg),+ `an unpublished channel says so, rather than reporting a parse failure (${msg})`)+}+// ---- 5. no downgrades -------------------------------------------------------+// A replayed OLD release passes every other check in this file: genuinely+// signed, right app, and its shell really does hash to its pin. Every byte+// authentic, just last month's — which is exactly what survives an origin or+// CDN compromise where the attacker can re-serve but cannot forge. A document+// carries no version to be monotonic against, unlike the shell's own update, so+// the host has to remember. Semantics mirrored from tray/ios (PR #315).+const floorStore = (initial: string | null = null) => {+ const box = { value: initial, writes: 0 }+ return {+ box,+ getFloor: async () => box.value,+ putFloor: async (v: string) => { box.value = v; box.writes++ },+ }+}+{+ written.clear()+ const store = floorStore('1.0.18')+ const chan = channel(await signer.envelope(payloadFor({ version: '1.0.9' })))+ const msg = await threw(() => newDocument(dirHandle() as any, 'Untitled',+ { fetch: chan, jwk: signer.jwk, ...store }))+ ok(/older than the 1\.0\.18/.test(msg), `a signed but OLDER release is refused (${msg})`)+ ok(written.size === 0, 'and nothing is written — the replay does not become a document')+}+{+ written.clear()+ const store = floorStore('1.0.18')+ const chan = channel(await signer.envelope(payloadFor({ version: '1.0.18' })))+ const made = await newDocument(dirHandle() as any, 'Untitled',+ { fetch: chan, jwk: signer.jwk, ...store })+ ok(made.version === '1.0.18' && written.size === 1,+ 'the SAME version is accepted — re-fetching what you already have is the normal '+ + 'case, and refusing it would break the + button on its second use')+ ok(store.box.writes === 0, 'and the floor is not rewritten when it has not moved')+}+{+ written.clear()+ const store = floorStore('1.0.9')+ const chan = channel(await signer.envelope(payloadFor({ version: '1.0.18' })))+ await newDocument(dirHandle() as any, 'Untitled', { fetch: chan, jwk: signer.jwk, ...store })+ ok(store.box.value === '1.0.18', `a newer release raises the floor (${store.box.value})`)+}+{+ // THE DENIAL-OF-SERVICE CASE. A manifest that verifies but whose shell fails+ // its digest must NOT raise the floor: otherwise one forged-but-unfetchable+ // release locks this browser out of every real release below it, and a failed+ // attack becomes a permanent one.+ written.clear()+ const store = floorStore('1.0.9')+ const chan = channel(await signer.envelope(payloadFor({ version: '9.9.9' })), '<html>not the signed bytes</html>')+ const msg = await threw(() => newDocument(dirHandle() as any, 'Untitled',+ { fetch: chan, jwk: signer.jwk, ...store }))+ ok(/does not match the signed release/.test(msg), `the swapped shell is refused (${msg})`)+ ok(store.box.value === '1.0.9',+ `and the floor stays at ${store.box.value} — a failed attack must not become a lasting one`)+}+{+ // An unreadable store reads as NO floor. Availability over protection, in a+ // case that is not an attack: private mode, quota, a migration mid-flight.+ written.clear()+ const chan = channel(await signer.envelope(payloadFor()))+ const made = await newDocument(dirHandle() as any, 'Untitled', {+ fetch: chan, jwk: signer.jwk,+ getFloor: async () => { throw new Error('private mode') },+ putFloor: async () => { throw new Error('private mode') },+ })+ ok(made.version === '1.0.18' && written.size === 1,+ 'a store that cannot be read or written still creates the document')+}+{+ // A strange version string must be able to fail to RAISE the floor, never to+ // block a release. `Number('x')` is NaN and `NaN || 0` is 0, so it sorts as+ // zero rather than throwing — the same behaviour as kernel/src/update.ts and+ // tray/ios, verified rather than assumed.+ written.clear()+ const store = floorStore('1.0.x')+ const chan = channel(await signer.envelope(payloadFor({ version: '1.0.18' })))+ const made = await newDocument(dirHandle() as any, 'Untitled',+ { fetch: chan, jwk: signer.jwk, ...store })+ ok(made.version === '1.0.18', 'an unparsable stored floor does not block a real release')+}++// ---- 6. the app family ------------------------------------------------------+{+ // Every app must name itself, or its channel silently skips the app check.+ ok(APPS.every((a: any) => /^bento-[a-z]+$/.test(a.appId)),+ `every app declares the appId its manifest is signed for (${APPS.map((a: any) => a.appId).join(', ')})`)+ ok(APPS.every((a: any) => a.manifest.includes(`/${a.id}/`)),+ 'and each points at its own release channel')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/tray/webext/README.md b/tray/webext/README.mdindex 765830a0..4e5e7bd8 100644--- a/tray/webext/README.md+++ b/tray/webext/README.md@@ -107,6 +107,50 @@ that was reviewed.Bump `manifest.json`'s `version` before packing; the store rejects a re-upload ofan existing version, and unpacked users compare against exactly that number.+## Creating a document, and why it is verified++The `+` button downloads the current release of the chosen app and writes it+into a granted folder. Nothing is bundled — a shell inside the extension would+drift from the real release and be re-reviewed on every update — and as of+2026-08-16 no tray host bundles one, so this is the only way a new document+comes into existence anywhere.++That makes it a path worth being careful on: the thing being written is+executable HTML, landing on the user's own disk, which they will then+double-click and trust. So `src/release.js` earns it rather than assuming it.++1. The manifest is fetched **as text**. It is a signed envelope —+ `{"payload": "<json string>", "sig": "<base64>"}` — and the fields live+ inside the payload string. There is no top-level `url`.+2. The ECDSA P-256 / SHA-256 signature is verified over the payload's exact+ bytes, against the release public key compiled into the extension.+3. The payload's `app` must match the channel it came from. The channels are+ sibling paths on one origin, so a genuine manifest served from the wrong one+ would otherwise hand somebody a different application.+4. The downloaded shell must hash to the `sha256` that signature covers.+5. Only then is a file handle opened. Any refusal writes **nothing** — a+ half-created document is a document somebody opens.++Signature over the pin, pin over the bytes. A signature with no pin verifies a+description of a build; a pin with no signature is a digest chosen by whoever+served the bytes.++`release.js` is a deliberate **mirror** of `kernel/src/update.ts`, not an+import: the kernel is TypeScript that Vite compiles into an app shell, and this+extension ships as unbundled ES modules Chrome loads from disk. Adding a bundler+to share forty lines would cost more trust than it buys, because the uploaded+package would stop being the reviewed source. The price is a maintenance rule —+**if the release key or the envelope format changes in the kernel, change it+here too** — and `scripts/test-webext-release.ts` enforces it: it asserts the+two keys are byte-identical and verifies a real manifest captured from+`bento.page`, with no test seam in the path.++That captured fixture is the point. The first version of this feature read+`manifest.url` off the envelope's top level and threw `the release server did+not offer a build` on every single invocation — the `+` button had never once+worked — and the rig passed throughout, because its fixture was written to the+shape the code expected instead of the shape the server sends.+## Two surfaces- **Toolbar click → the library** (`src/home.html`): browsing and managing.diff --git a/tray/webext/src/library.js b/tray/webext/src/library.jsindex 6ab1a51c..d10c3221 100644--- a/tray/webext/src/library.js+++ b/tray/webext/src/library.js@@ -16,8 +16,14 @@// the popup opens, is bounded, and its results are cached. Different job,// different rules.-import { CACHE, get, put, prefixes } from './db.js'+import { CACHE, GRANT, get, put, prefixes } from './db.js'import { getGrants } from './status.js'+import { verifyManifest, fetchPinned, ACCEPT_BYTES } from './release.js'+// Not a third implementation: `update.js` already has the dotted-numeric+// compare, and it behaves the same as the kernel's — an unparsable component+// coerces to 0 rather than throwing, because `NaN || 0` is 0. A strange version+// string should be able to fail to RAISE the floor, never to block a release.+import { compareVersions } from './update.js'/** How deep to look, and how many documents to show. A folder of documents is* not a filesystem; someone who granted a home directory should get a useful@@ -272,6 +278,11 @@ function extractText(html) {* instead means a document created here is the same version everyone else has,* the same day.*+ * Bundling is settled policy across all three hosts now (2026-08-16), which+ * makes this the ONLY way any of them creates a document — so the download is+ * verified, not trusted: signature, then digest, then the file handle. See+ * `release.js` for the chain and why it is mirrored from the kernel.+ ** Create-only, and the name is derived here rather than taken from anywhere —* the same rule as `backup`. Nothing existing is ever replaced.*/@@ -287,12 +298,18 @@ function extractText(html) {* Adding an app here is the whole integration; nothing else in the extension* asks which app it is looking at.*/+// `appId` is the name the app calls ITSELF inside its signed manifest+// (scripts/apps.mjs, and the shell's own `configureApp({appId})`), and it is+// checked against the payload — the channels are sibling paths on one origin,+// so without that check a genuine manifest served from the wrong path hands+// somebody the wrong application. It is spelled out rather than derived from+// `id` so that adding an app cannot silently opt out of the check.export const APPS = [- { id: 'slides', name: 'Slides', blurb: 'Presentations',+ { id: 'slides', name: 'Slides', blurb: 'Presentations', appId: 'bento-slides',manifest: 'https://bento.page/releases/slides/manifest.json' },- { id: 'spaces', name: 'Spaces', blurb: 'Notes and pages',+ { id: 'spaces', name: 'Spaces', blurb: 'Notes and pages', appId: 'bento-spaces',manifest: 'https://bento.page/releases/spaces/manifest.json' },- { id: 'dash', name: 'Dash', blurb: 'Data and sheets',+ { id: 'dash', name: 'Dash', blurb: 'Data and sheets', appId: 'bento-dash',manifest: 'https://bento.page/releases/dash/manifest.json' },]@@ -368,23 +385,92 @@ export async function rename(doc, wantedBase) {return { name, base }}+/**+ * The highest release version of an app this browser has ever accepted.+ *+ * Per app, in the extension's own store — a document carries no version of its+ * own to compare against, so unlike the shell's self-update (which has its+ * running build to measure from) creating a document has nothing to be+ * monotonic ABOUT unless the host remembers.+ *+ * An unreadable store reads as NO floor rather than as a refusal: private mode,+ * quota, a migration mid-flight. That is a deliberate choice of availability+ * over protection in a case that is not an attack — being unable to remember+ * must not mean being unable to create a document.+ */+const floorKey = (app) => `release-floor:${app.id}`++async function readFloor(app, deps) {+ const read = deps.getFloor ?? (() => get(GRANT, floorKey(app)))+ try { return (await read()) || null } catch { return null }+}++async function raiseFloor(app, version, floor, deps) {+ // EQUAL is not a downgrade. Re-fetching the version already seen is the+ // normal case — the second document somebody creates — and treating it as a+ // rollback would break the `+` button on its second use rather than at some+ // exotic edge.+ if (floor && compareVersions(version, floor) <= 0) return+ const write = deps.putFloor ?? ((v) => put(GRANT, floorKey(app), v))+ // Best effort: a floor that cannot be written costs protection next time, not+ // this document.+ try { await write(version) } catch { /* quota, private mode */ }+}+export async function newDocument(dir, wantedBase = 'Untitled', deps = {}) {const net = deps.fetch ?? fetchconst app = APPS.find((a) => a.id === deps.app) ?? APPS[0]- const res = await net(app.manifest, { cache: 'no-store' })++ // The manifest is a SIGNED ENVELOPE — `{payload, sig}`, the fields inside the+ // payload STRING — and it is read as text for that reason: the bytes the+ // signature covers are the bytes that arrived, so anything that parses and+ // re-serialises on the way past has verified something else.+ //+ // This was the bug, and it is worth naming because it was invisible. The code+ // here read `manifest.url` off the ENVELOPE, where there is no `url`, so every+ // attempt threw "the release server did not offer a build" — the `+` button+ // had never once worked. The rig agreed with it, because the fixture was+ // hand-written to the shape the code expected rather than to the shape the+ // server sends. It is checked against a real captured manifest now+ // (scripts/test-webext-release.ts).+ // ACCEPT_BYTES on the manifest too. The edge injection measured on the shell+ // targets things it reads as pages, so a JSON manifest is not today's victim+ // — but "ask for bytes on the one request we remembered" is a rule that only+ // holds until somebody adds a third fetch.+ const res = await net(app.manifest, { cache: 'no-store', headers: ACCEPT_BYTES })+ // Only Slides has a published channel today, so a 404 here is an EXPECTED+ // answer rather than a fault, and an HTTP status is the wrong way to say it.+ // The wording matches tray/ios (and tray/android is following): the app list+ // is aspirational on all three hosts, so all three phrase this identically.+ if (res.status === 404) throw new Error(`${app.name} has not been released yet`)if (!res.ok) throw new Error(`could not reach the ${app.name} release server (${res.status})`)- const manifest = await res.json()- const url = manifest?.url- if (!url) throw new Error('the release server did not offer a build')+ const release = await verifyManifest(await res.text(), app.appId, deps.jwk)- const shell = await net(url, { cache: 'no-store' })- if (!shell.ok) throw new Error(`could not download the app (${shell.status})`)- const html = await shell.text()+ // NO DOWNGRADES. Everything above passes for a replayed OLD release: it is+ // genuinely signed, it names the right app, and its shell really does hash to+ // its pin. Every byte is authentic — it is just last month's. That is what+ // survives an origin or CDN compromise where the attacker can re-serve but+ // cannot forge, so the only thing that catches it is remembering.+ const floor = await readFloor(app, deps)+ if (floor && compareVersions(release.version, floor) < 0)+ throw new Error(+ `the ${app.name} channel offered ${release.version}, older than the ${floor} `+ + 'already seen — refusing it')++ // Signature over the pin, pin over the bytes. Both, or the shell being written+ // to somebody's disk is whatever the network felt like returning.+ const bytes = await fetchPinned(net, release.url, release.sha256)++ // Raised only NOW, after the bytes passed their digest. Raising it on a+ // merely-verified manifest would let one forged-but-unfetchable release lock+ // this browser out of every real release below it — turning a failed attack+ // into a permanent one. (tray/ios hit this reasoning first, on PR #315.)+ await raiseFloor(app, release.version, floor, deps)const { name, base } = await freeName(dir, wantedBase)const handle = await dir.getFileHandle(name, { create: true })const w = await handle.createWritable()- await w.write(html)+ await w.write(bytes)await w.close()- return { name, base, version: manifest.version, app: app.name }+ return { name, base, version: release.version, app: app.name }}diff --git a/tray/webext/src/release.js b/tray/webext/src/release.jsnew file mode 100644index 00000000..54cc4175--- /dev/null+++ b/tray/webext/src/release.js@@ -0,0 +1,166 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Release-channel trust: is this really a Bento build?+//+// WHY THIS EXISTS. Creating a new document means downloading an app shell and+// writing it to the user's own disk, where they will subsequently double-click+// it. That file is executable HTML with a runtime inside it. A plain https GET+// of a URL a JSON file told us about is NOT enough to earn that: whoever can+// answer for the release origin — a compromised host, a bad CDN edge, a proxy+// on a hostile network — chooses what code the user creates and then trusts.+//+// The release channel was built for exactly this and we were ignoring it. The+// manifest is a SIGNED ENVELOPE, `{payload: "<json string>", sig: "<base64>"}`,+// signed offline (scripts/sign-release.mjs) with a key that lives on the+// maintainer's machine and never enters CI. The payload pins the shell's+// sha256. So there is a chain — signature over the pin, pin over the bytes —+// and it terminates in a public key compiled into this file. Neither half is+// optional: a signature with no pin verifies a description of a build rather+// than a build, and a pin with no signature is a digest chosen by the same+// party that serves the bytes.+//+// MIRRORED, NOT IMPORTED. `kernel/src/update.ts` is the reference implementation+// (`verifySigned`, `fetchPinned`, `verifyManifest`) and this is a deliberate+// line-by-line mirror of it: same envelope, same key, same ECDSA P-256 /+// SHA-256 over the payload's exact UTF-8 bytes with NO canonicalisation, same+// hex-digest comparison. It is copied because it cannot be imported — the+// kernel is TypeScript compiled by Vite into an app shell, and this extension+// ships as plain unbundled ES modules that Chrome loads from disk with no build+// step. Adding a bundler to the extension to share ~40 lines would cost more+// trust than it buys (the shipped package would stop being the reviewed source).+//+// The consequence of mirroring is a maintenance obligation, so state it plainly:+// **if the release key or the envelope format changes in kernel/src/update.ts,+// it must change here too.** `scripts/test-webext-release.ts` pins both ends —+// it asserts this key is byte-identical to the kernel's, and verifies a REAL+// captured manifest, so a format drift fails a test rather than a user.++/**+ * Release signing PUBLIC key — the same one embedded in every shipped shell+ * (kernel/src/update.ts PUBLIC_KEY_JWK). The private half is offline+ * (`scripts/keygen.mjs` → `~/.bento/release-key.json`). Rotating it orphans+ * every already-shipped file, so the key is guarded rather than rotated.+ */+export const RELEASE_KEY = {+ kty: 'EC',+ crv: 'P-256',+ x: 'GMHSKwWcAoJVq-Dz1ZxWZM6TXATWIKbaQBpjoTystH8',+ y: 'flFNzbdXCmJN8RQYCeG71rBZnnbN-MCEnp1EbCLFrj0',+}++// Ask for BYTES, not for a page — explicitly, rather than inheriting whatever+// the platform's default happens to be.+//+// Not hypothetical. Measured against the live release URL on 2026-08-17: the+// SAME url answers differently depending on this one header. Asking with the+// wildcard returns 689,316 bytes, which match the signed pin. Asking with a+// browser's own header (text/html, application/xhtml+xml, …) returns 689,675,+// which do not.+//+// The 359-byte difference is a Cloudflare Web Analytics beacon the edge injects+// before the closing body tag, for anything it reads as a page being browsed.+// The URL and its `.bento.html` extension are identical either way, so the+// trigger is the header — the good outcome, since a path-keyed injection could+// not be avoided by any host.+//+// An extension's `fetch` already defaults to the wildcard, so this changes+// nothing today. Set anyway: the default belongs to the browser, not to this+// code, and if it ever moves the symptom is a `+` button that refuses every+// download. The digest check catching that IS the system working, but it is+// better not to depend on the catch.+//+// Found by tray/android, measured by tray/ios, reproduced here.+export const ACCEPT_BYTES = { Accept: '*/*' }++const b64ToBytes = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0))+const hex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('')++/** Lowercase hex sha256 of some bytes — the digest form every pin uses. */+const sha256Hex = async (bytes) => hex(await crypto.subtle.digest('SHA-256', bytes))++/**+ * Verify a SIGNED ENVELOPE and return its parsed payload.+ *+ * The signature covers the payload's exact UTF-8 bytes, which is why the+ * payload travels as a STRING rather than as an object: re-serialising an+ * object to check a signature makes the check depend on key order and spacing,+ * and a signature check that is subtly wrong looks exactly like one that is+ * right.+ *+ * Throws on anything short of a good signature — never returns a "probably+ * fine". `what` only names the thing in those messages.+ *+ * `jwk` is a TEST SEAM and nothing else: no caller in the extension passes it,+ * and passing one is exactly as much of a trust decision as passing the `fetch`+ * these functions take. Production reads the key above.+ */+export async function verifySigned(raw, what = 'signed file', jwk = RELEASE_KEY) {+ let payload, sig+ try {+ ;({ payload, sig } = JSON.parse(raw))+ } catch {+ throw new Error(`the ${what} is not valid JSON`)+ }+ if (typeof payload !== 'string' || typeof sig !== 'string')+ throw new Error(`the ${what} is not signed — refusing it`)++ const key = await crypto.subtle.importKey(+ 'jwk', jwk, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify'],+ )+ const ok = await crypto.subtle.verify(+ { name: 'ECDSA', hash: 'SHA-256' }, key,+ b64ToBytes(sig), new TextEncoder().encode(payload),+ )+ if (!ok) throw new Error(`the ${what} signature is INVALID — refusing it`)++ try {+ return JSON.parse(payload)+ } catch {+ throw new Error(`the ${what} payload is not valid JSON`)+ }+}++/**+ * The signature check, plus the shape checks that make a payload a release.+ *+ * `appId` is checked because the channels are siblings on one origin and a+ * signed manifest is a valid signed manifest wherever it is served from:+ * without this, anyone who can move bytes around that origin could answer the+ * Spaces channel with the (genuine, correctly signed) Slides manifest and hand+ * somebody the wrong application. The shipped shells make the same check for+ * the same reason (`kernel/src/update.ts verifyManifest`).+ */+export async function verifyManifest(raw, appId, jwk) {+ const info = await verifySigned(raw, 'release manifest', jwk)+ if (+ info?.app !== appId ||+ typeof info.version !== 'string' ||+ !/^[0-9a-f]{64}$/i.test(info.sha256 ?? '') ||+ typeof info.url !== 'string'+ )+ throw new Error('the release manifest payload is malformed')+ return info+}++/**+ * Fetch an artifact and hand back its BYTES only if they hash to `sha256`.+ *+ * Fails CLOSED, and throws rather than returning null (the kernel's variant+ * returns null because its callers have a "keep what we have" option; there is+ * no previous document to keep here, and the one thing that must not happen is+ * unverified bytes reaching a file handle).+ *+ * Bytes, deliberately — not text. The digest is over the bytes that were+ * served, so decoding to a string first and hashing that would be verifying+ * something adjacent to what we are about to write.+ */+export async function fetchPinned(net, url, sha256) {+ if (!/^[0-9a-f]{64}$/i.test(sha256 ?? '')) throw new Error('the release is not pinned to a digest')+ const res = await net(url, { cache: 'no-store', headers: ACCEPT_BYTES })+ if (!res.ok) throw new Error(`could not download the app (${res.status})`)+ const bytes = await res.arrayBuffer()+ if ((await sha256Hex(bytes)) !== sha256.toLowerCase())+ throw new Error('the downloaded app does not match the signed release — refusing it')+ return bytes+}