Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
release: script and block pins, a signed release history, and a signing gate (K4) (#824)
nyblnet72070e01c241
diff --git a/.github/actions/validate-kernel/action.yml b/.github/actions/validate-kernel/action.ymlindex 4f9906f1..222487bf 100644--- a/.github/actions/validate-kernel/action.yml+++ b/.github/actions/validate-kernel/action.yml@@ -89,6 +89,14 @@ runs:shell: bento-step {0}run: node scripts/test-body-seal.ts+ - name: release history — append-only, anti-rollback, every block or unknown+ # bento/connect K4 (security §36): the signed release history only grows;+ # a host refuses a history that lacks an entry it holds or rolls its+ # newest version back; a file matches a release only if ONE entry matches+ # EVERY block. sign-history.mjs end to end with a throwaway test key.+ shell: bento-step {0}+ run: node scripts/test-release-history.ts+- name: Language pack verification rig# Packs come off the network, so the signature + hash-pin chain is the# only thing between a hostile channel and the strings in the UI.diff --git a/.github/workflows/ci-dash.yml b/.github/workflows/ci-dash.ymlindex dbf0e60a..2013609d 100644--- a/.github/workflows/ci-dash.yml+++ b/.github/workflows/ci-dash.yml@@ -89,6 +89,12 @@ jobs:# dates, 3/4/2026 stays text, the formula bar shows 100% not 1, and# =A11+ is refused in the cell and the bar with the reason shown.run: node scripts/test-dash-entryparse-browser.mjs+ - name: Release pins in Chromium+ # bento/connect K4 (security §18/§36): this build's pins come from its+ # own bytes, a real file its ⌘S saved, and it boots under them while its+ # UI is driven, with only the loader's two designed refusals. What+ # release.mjs requires before it signs, checked on every PR.+ run: node scripts/derive-pins.mjs dash/dist-single/Bento_Dash.bento.htmldash-gate-browser:runs-on: ubuntu-latestdiff --git a/.github/workflows/ci-slides.yml b/.github/workflows/ci-slides.ymlindex c99e0950..70cf0fd1 100644--- a/.github/workflows/ci-slides.yml+++ b/.github/workflows/ci-slides.yml@@ -54,6 +54,18 @@ jobs:# neutral <title> and filename, no preview, and no plaintext; the# unsealed control shows the same checks can see a leak.run: node scripts/test-sealed-boot.mjs+ - name: Release pins in Chromium+ # bento/connect K4 (security §18/§36): this build's pins come from its+ # own bytes, a real file its ⌘S saved, and it boots under them while its+ # UI is driven, with only the loader's two designed refusals. What+ # release.mjs requires before it signs, checked on every PR.+ run: node scripts/derive-pins.mjs slides/dist-single/Bento_Slides.bento.html+ - name: The pinned-CSP boot check refuses doctored copies in Chromium+ # K4: the boot check excuses only the loader's two fallbacks, from a+ # line AND column inside its own text. An injected <script> in <head>+ # or on the loader's own lines is reported, and the rig checks WHICH+ # refusal was excused, not just how many. A wrong loader pin never boots.+ run: node scripts/test-csp-boot-browser.mjs- name: A sealed slides deck keeps its content out of IndexedDB in Chromium# The autosave and ⌘S checkpoints write no recovery copy or version for# a deck sealed by identity; the password menu stays keyed to thediff --git a/.github/workflows/ci-spaces.yml b/.github/workflows/ci-spaces.ymlindex 4b0015bc..7fed0666 100644--- a/.github/workflows/ci-spaces.yml+++ b/.github/workflows/ci-spaces.yml@@ -88,3 +88,9 @@ jobs:# given, refuses a malformed value, and never emits a placeholder: the# platforms cache these files, so a wrong one is worse than none.run: node scripts/test-well-known.ts+ - name: Release pins in Chromium+ # bento/connect K4 (security §18/§36): this build's pins come from its+ # own bytes, a real file its ⌘S saved, and it boots under them while its+ # UI is driven, with only the loader's two designed refusals. What+ # release.mjs requires before it signs, checked on every PR.+ run: node scripts/derive-pins.mjs spaces/dist-single/Bento_Spaces.bento.htmldiff --git a/.github/workflows/ci-type.yml b/.github/workflows/ci-type.ymlindex f1eb6bf5..a43745a7 100644--- a/.github/workflows/ci-type.yml+++ b/.github/workflows/ci-type.yml@@ -48,6 +48,12 @@ jobs:npm run build:single --prefix type- name: Type boots on the loader's inline path; fields wiring still worksrun: node scripts/test-type-boot-browser.mjs+ - name: Release pins in Chromium+ # bento/connect K4 (security §18/§36): this build's pins come from its+ # own bytes, a real file its ⌘S saved, and it boots under them while its+ # UI is driven, with only the loader's two designed refusals. What+ # release.mjs requires before it signs, checked on every PR.+ run: node scripts/derive-pins.mjs type/dist-single/Bento_Type.bento.htmltype-find-browser:runs-on: ubuntu-latestdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 58e8beca..f20a805b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -37,7 +37,10 @@ concurrency:jobs:validate:runs-on: ubuntu-latest- timeout-minutes: 15+ # 20, not 15: the dash slice's release rehearsal now boots the release in+ # Chromium to check its pins (K4), about two minutes on top of a 9–11+ # minute job.+ timeout-minutes: 20steps:- uses: actions/checkout@v4@@ -64,6 +67,16 @@ jobs:# the repo root. Until this step existed they skipped in every run.run: npm install --prefix "$GITHUB_WORKSPACE" --no-save --no-package-lock --no-audit --no-fund [email protected]+ - name: Install browser test runtime (the release rehearsal checks pins)+ # release.mjs refuses to sign without checking the release's pins in a+ # real browser (scripts/derive-pins.mjs, K4), and the dash slice runs+ # that real pipeline as its release rehearsal. Pinned outside the app+ # packages, as in the ci-<zone>.yml browser jobs.+ run: |+ npm install --prefix "$RUNNER_TEMP/bento-browser" --no-package-lock --ignore-scripts [email protected]+ "$RUNNER_TEMP/bento-browser/node_modules/.bin/playwright" install --with-deps chromium+ echo "PLAYWRIGHT_MODULE=$RUNNER_TEMP/bento-browser/node_modules/playwright/index.mjs" >> "$GITHUB_ENV"+- name: Rig steps fail on a skip# Puts scripts/ci on PATH, so every slice step below can declare# `shell: bento-step {0}`: a rig that reports a skip CI does not allowdiff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 008b69a4..b55cdc5b 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -11687,6 +11687,77 @@ Also settled the same day: a stored `bento-lang` is validated before `Intl`sees it (dash/src/i18n.ts `intlLocale`), because the key is shared across everyfile on the origin and a bad value used to stop boot.+## 2026-10-21 — bento/connect K4: release pins and the signed release history++A host that SERVES a document (iOS, Android, desktop, the hosted runtime)+decides "genuine runtime" by hashing the file's code blocks and serving it under+a hash-pinned script CSP (security §18). K4 publishes what that needs, per+release, signed with the release key:+- **Pins, in the manifest (additively: shipped shells read only+ app/version/sha256/url):** `pins = { v: 1, blocks: { bento-rt, bento-rt-css,+ loader, remover }, scriptSrc: [loader, remover] }`. Blocks are sha256 hex of+ each code block's text; `scriptSrc` is the CSP form. They're derived from the+ release's OWN bytes: the built shell, and a file it saved through its real ⌘S+ fallback (`scripts/derive-pins.mjs`). The remover exists only in saved files,+ and one app's scripting API returns JSON, not a file.+- **A signed, cumulative history:** `releases/<app>/history.json`, the release+ envelope over `{ app, v: 1, releases: [{ version, sha256, at, pins }] }`,+ newest first. It's append-only: a release must be newer than everything held,+ and a held entry never changes. The first history is backfilled from every+ earlier release with a signed manifest, each shell checked against its own+ manifest's sha256 first. For slides that's 66 versions, 0.7.0 to 1.2.9.+ Earlier shells have no compressed runtime blocks, so they're unknown to hosts.+- **The host rules (scripts/lib/release-history.mjs, security §36):**+ - a file matches a release only if ONE entry matches EVERY block, with+ exactly one block per id. A partial or ambiguous match is UNKNOWN:+ restricted mode or an update offer, never a borrowed pinned CSP.+ - a host keeps the newest history it has verified and refuses one that lacks+ a held entry or rolls its newest version back. (With a well-formed history+ the second check is implied by the first, and is kept as defence in depth.)+- **The signing gate:** `release.mjs` refuses to sign on any pins mismatch, on+ any executable inline script in a saved file other than the pinned loader and+ remover, and on any CSP refusal while the release is driven under its pins,+ except the loader's two designed fallbacks (an inline script, then `new+ Function`). Those are matched on directive AND on a line inside the pinned+ loader's span: matching on the source file alone excused an injected script.+ There's no unchecked path. CI runs the same check on every PR's build of all+ four apps, and the required `validate` job's release rehearsal runs the whole+ pipeline.+- **Refusal COLUMNS aren't reliable across Chrome versions.** Chrome Headless+ Shell 149, Playwright's bundled browser and the one CI runs, reports a script+ injected right after the loader's `</script>` at column 0, a position INSIDE+ the loader's span. Chrome 155 reports its real column. So on CI's browser the+ line-and-column rule alone would excuse that script, and the ONCE-EACH CAP+ (at most one inline and one eval refusal excused) is what catches it. The cap+ is the real guard and the column a refinement (security, measured). Rigs+ identify an injected refusal by its line, with its column matching or 0, and+ run under the bundled browser as well as system Chrome.+- **The verdict is a GRAMMAR, not a list of cases (security, 2026-10-21).** A+ `<script>` is inert only if its type is exactly one of the data types Bento+ writes (`application/bento+json`, `application/bento+lang`,+ `bento/deflate-b64`, `bento/deflate-b86`). Everything else is executable,+ including no type, any JavaScript type, `module`, an unknown type, a+ differently cased data type, and any `src=`. An executable script must then+ be exactly the pinned loader or remover by hash. A file carrying `<iframe>`,+ `<object>`, `<embed>`, `<base>`, a `<meta>` refresh or CSP, an `on*=`+ attribute, a comment or `<style>` holding a `<script>`, or a data block+ containing `<` is UNKNOWN. Bento's data blocks never contain `<`: the JSON is+ escaped and the b64/b86 alphabets exclude it. Every genuine build of the four+ apps, a real deck with a live embed and an svg diagram, and all 66 backfilled+ slides releases pass it unchanged. Agreement between the hosts' scanners+ (Rust, Swift, Kotlin, JS) is K5's shared corpus.+- **No style pins in phase 1 (security §36a).** The policy is+ `script-src <pins> blob:; style-src 'unsafe-inline'`. A document's own svg+ `<style>` (an svg element's `css`, sanitized and scoped) can't be pinned per+ release: measured, the pinned style policy refused it, which breaks every+ user diagram with hover or animation. Style injection gives no route to+ Bento's secrets: keys and the document JSON live in script text, which CSS+ selectors can't read, and document CSS is sanitized and scoped. So pinning+ would only remove what the svg element provides on purpose. The style control+ is the SANITIZER, whose rig covers the obfuscated url() forms with a browser+ fetch check. The route to style pins later is moving svg CSS into constructed+ stylesheets (a slides change); collecting the hashes from the browser's own+ CSP engine under a report-only policy was measured to work.## 2026-10-20 — calendar span renamed Agenda (gantt keeps Timeline); calendars prefer Due — maintainer, 2026-10-20Two rulings on the bento/spaces calendar layout, made by the maintainer.diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 8d5c6732..b8b6c854 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -48,11 +48,23 @@ matters. Neither needs the signing key.The `CNAME` file in the site sets the custom domain; after the certificateis issued, tick *Enforce HTTPS* (mandatory for `.page` anyway).-3. **DNS at the registrar** for the apex `bento.page`:+3. **A browser for the pins gate.** `release.mjs` won't sign until it has+ checked the release's pins in a real browser (below), so the release machine+ needs Playwright and Chromium, pinned outside the app packages as CI does:++ ```sh+ npm install --prefix ~/.bento/browser --no-package-lock [email protected]+ ~/.bento/browser/node_modules/.bin/playwright install chromium+ export PLAYWRIGHT_MODULE=~/.bento/browser/node_modules/playwright/index.mjs+ ```++ Or point `CHROME_PATH` at an installed Chrome. Without either, the release+ stops before anything is signed. There's no unchecked path.+4. **DNS at the registrar** for the apex `bento.page`:- `A` records → `185.199.108.153`, `185.199.109.153`, `185.199.110.153`, `185.199.111.153`- `AAAA` records → `2606:50c0:8000::153`, `2606:50c0:8001::153`, `2606:50c0:8002::153`, `2606:50c0:8003::153`- Optional `www` `CNAME` → `<user>.github.io`-4. **Verify the domain on GitHub** (Settings → Pages → Verified domains: add+5. **Verify the domain on GitHub** (Settings → Pages → Verified domains: addthe `_github-pages-challenge-<user>` TXT record it gives you). Thisprevents Pages domain takeover if the site is ever unconfigured.@@ -143,6 +155,25 @@ matters. Neither needs the signing key.`slides`. It finishes by printing the exact tag-push and publish commandsfor the app it just built.+ Before it signs, it derives the release's **pins** from the release's own+ bytes (`scripts/derive-pins.mjs`): the hashes of its code blocks, its loader+ and its preview remover, taken from a file the release itself saved through+ ⌘S. It then boots the release under the CSP a host will serve it with, while+ driving its UI. Any mismatch, or any script refusal beyond the loader's two+ designed fallbacks, stops the release. The pins go into the manifest+ (additively: shipped shells ignore them) and into the app's signed+ **release history**, `releases/<app>/history.json`. That cumulative list+ lets a host verify a file saved by ANY genuine release, not only the newest.+ The history only grows: `sign-history.mjs` verifies the published one, adds+ this release, and refuses an older version or a changed entry.++ The FIRST history is backfilled from every earlier signed release, found in+ the history of the `../bento-site` clone (`scripts/backfill-history.mjs`).+ Each shell is checked against its own signed manifest before it's pinned.+ That needs the clone's FULL history, so don't use a shallow clone. Releases+ from before the runtime shipped compressed (slides < 0.7.0) can't be pinned,+ and stay unknown to hosts.+It also stamps `site/.bento-release.json` with the app and version itstaged. `publish-site.mjs` reads that to name the tag, the release title andthe shell it attaches — all per app, and all silently wrong if it guesses.@@ -280,7 +311,10 @@ throwaway half. It asserts the positives (gate passes, manifest shape, the pinis the sha256 of the staged bytes, a correctly signed manifest is offered) and,more importantly, the refusals: a tampered payload, a manifest validly signedfor a **different app**, a downgrade replay, a shell with one bit flipped, and-a shell whose doc block closes its own script. CI runs it for dash on every PR.+a shell whose doc block closes its own script. It also checks that the+manifest carries the pins and that the signed history holds this release with+the same pins. CI runs it for dash on every PR, in the required `validate`+job, which installs Chromium for it.This is as close to a release as anything can get without the key. What itcannot cover is the live channel — step 7 above is still the last word.diff --git a/scripts/backfill-history.mjs b/scripts/backfill-history.mjsnew file mode 100644index 00000000..a378dedd--- /dev/null+++ b/scripts/backfill-history.mjs@@ -0,0 +1,82 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// BACKFILL the release history (K4, security §36c) from every release already+// published: each version with a SIGNED manifest, its shell checked against+// that manifest's own sha256 first.+//+// node scripts/backfill-history.mjs --site ../bento-site --dir slides --app bento-slides --out entries.json+//+// Walks the site repository's git history of releases/<dir>/manifest.json. For+// each publication it verifies the manifest's signature against the release+// public key, checks the app id, reads the shell from the SAME commit and+// checks its sha256 against the manifest, and only then derives the pins, by+// booting that shell and saving through its own ⌘S fallback. Nothing historic+// is trusted on its own say-so.+//+// Not every verified release can be pinned. A shell from before the runtime+// shipped compressed has no bento-rt block (slides < 0.7.0), and those stay+// UNKNOWN to hosts, as security ruled. They are listed, never signed. A version+// published more than once (a re-signed manifest) has one shell (measured);+// the first publication's date is kept.+//+// Writes UNSIGNED entries: sign-history.mjs --seed turns them into the first+// signed history, on the maintainer's machine, on an explicit release go.++import { execFileSync } from 'node:child_process'+import { createHash } from 'node:crypto'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { releasePublicKey, verifyEnvelope } from './sign-payload.mjs'+import { derivePins, checkAgainstPins, scanBlocks, executableScripts } from './lib/release-pins.mjs'+import { savedBy } from './lib/saved-by.mjs'++const args = process.argv.slice(2)+const opt = (n) => { const i = args.indexOf(`--${n}`); return i >= 0 ? args[i + 1] : undefined }+const site = opt('site'), dir = opt('dir'), app = opt('app'), out = opt('out')+if (!site || !dir || !app || !out) { console.error('usage: backfill-history.mjs --site <bento-site> --dir <slides> --app <bento-slides> --out entries.json'); process.exit(2) }++const git = (...a) => execFileSync('git', ['-C', site, ...a], { maxBuffer: 1 << 28 })+const pub = releasePublicKey()+const commits = git('log', '--reverse', '--format=%H', '--', `releases/${dir}/manifest.json`).toString().trim().split('\n').filter(Boolean)++const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })+const work = mkdtempSync(join(tmpdir(), 'bento-backfill-'))+const entries = new Map(), refused = [], unpinnable = []+try {+ for (const c of commits) {+ let payload+ try {+ payload = verifyEnvelope(git('show', `${c}:releases/${dir}/manifest.json`).toString(), pub)+ } catch (e) { refused.push(`${c.slice(0, 8)}: manifest signature (${e.message})`); continue }+ if (payload.app !== app) { refused.push(`${c.slice(0, 8)}: manifest is for ${payload.app}`); continue }+ if (entries.has(payload.version) || unpinnable.some((u) => u.startsWith(`${payload.version}:`))) continue // a re-signed manifest+ const file = payload.url.split('/').pop()+ let shell+ try { shell = git('show', `${c}:releases/${dir}/${file}`) } catch { refused.push(`${payload.version}: no shell ${file} in ${c.slice(0, 8)}`); continue }+ const sha256 = createHash('sha256').update(shell).digest('hex')+ if (sha256 !== payload.sha256) { refused.push(`${payload.version}: shell sha256 does not match its signed manifest`); continue }+ const html = shell.toString('utf8')+ const blocks = scanBlocks(html)+ const pinnable = ['bento-rt', 'bento-rt-css'].every((id) => blocks.filter((b) => b.id === id).length === 1) && executableScripts(blocks).length === 1+ if (!pinnable) { unpinnable.push(`${payload.version}: no compressed runtime blocks`); continue }+ const path = join(work, `${payload.version}.html`)+ writeFileSync(path, shell)+ const saved = await savedBy(browser, path)+ const pins = derivePins(html, saved, { historic: true })+ const self = checkAgainstPins(saved, pins)+ if (self.length) { refused.push(`${payload.version}: its own save does not match its pins (${self[0]})`); continue }+ entries.set(payload.version, { version: payload.version, sha256, at: payload.at, pins })+ console.log(` ${payload.version.padEnd(8)} pinned (remover ${pins.blocks.remover ? 'yes' : 'none'})`)+ }+} finally {+ await browser.close()+}+writeFileSync(out, JSON.stringify([...entries.values()], null, 2) + '\n')+console.log(`\n${commits.length} publications; ${entries.size} versions pinned; ${unpinnable.length} unpinnable; ${refused.length} refused`)+if (unpinnable.length) console.log(` unpinnable: ${unpinnable[0].split(':')[0]} … ${unpinnable.at(-1).split(':')[0]} (${unpinnable.length}): no compressed runtime blocks, so UNKNOWN to hosts`)+for (const r of refused) console.log(` REFUSED: ${r}`)+process.exit(refused.length ? 1 : 0)diff --git a/scripts/derive-pins.mjs b/scripts/derive-pins.mjsnew file mode 100644index 00000000..58cdb8bf--- /dev/null+++ b/scripts/derive-pins.mjs@@ -0,0 +1,69 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Derive a release's PINS from its own bytes (K4, security §18 / §36), and+// prove the release works under them.+//+// node scripts/derive-pins.mjs <shell.html> [--out pins.json] [--historic]+//+// 1. Boot the built shell in Chromium and SAVE through the app's real ⌘S+// download fallback (the File System Access picker is removed first). That+// is the only honest source for the preview remover, which exists only in+// saved files, and it doesn't depend on any app's scripting API (type's+// window.bento.serialize returns JSON, not a file).+// 2. Derive the pins (scripts/lib/release-pins.mjs): the code-block hashes and+// the CSP script hashes. The saved file must match them.+// 3. Boot the shell UNDER those pins and drive its UI (scripts/lib/csp-boot.mjs):+// any refusal other than the loader's two designed fallbacks fails it.+//+// --historic is for the backfill of releases signed before pins existed: a+// release from before the first-page preview may save no remover, and a boot+// refusal is reported, not fatal. A new release gets neither allowance.+//+// Needs Playwright (PLAYWRIGHT_MODULE) and Chromium (CHROME_PATH), as the+// browser rigs do. Exits non-zero on any mismatch: release.mjs relies on that.++import { readFileSync, writeFileSync } from 'node:fs'+import { derivePins, checkAgainstPins } from './lib/release-pins.mjs'+import { savedBy } from './lib/saved-by.mjs'+import { bootUnderPins, clickEverything } from './lib/csp-boot.mjs'++const args = process.argv.slice(2)+const shellPath = args.find((a) => !a.startsWith('--') && args[args.indexOf(a) - 1] !== '--out')+if (!shellPath) { console.error('usage: node scripts/derive-pins.mjs <shell.html> [--out pins.json] [--historic]'); process.exit(2) }+const historic = args.includes('--historic')+const outAt = args.indexOf('--out')+const out = outAt >= 0 ? args[outAt + 1] : null++const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')++const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })+let failed = false+try {+ const shell = readFileSync(shellPath, 'utf8')+ const saved = await savedBy(browser, shellPath)+ const pins = derivePins(shell, saved, { historic })+ const self = checkAgainstPins(saved, pins)+ if (self.length) throw new Error(`derive-pins: the saved file does not match its own pins: ${self.join('; ')}`)+ console.log(`pins loader ${pins.blocks.loader.slice(0, 12)}… remover ${pins.blocks.remover?.slice(0, 12) ?? '(none: before previews)'} rt ${pins.blocks['bento-rt'].slice(0, 12)}…`)++ const boot = await bootUnderPins(browser, shellPath, pins, async (p) => {+ await p.waitForTimeout(1500)+ await clickEverything(p)+ })+ console.log(`boot under the pinned policy: ${boot.expected.length} expected loader refusal(s), ${boot.unexpected.length} unexpected, ${boot.errors.length} page error(s)`)+ for (const v of boot.unexpected.slice(0, 5)) console.log(` unexpected: ${v.directive} ${v.blockedURI} from ${v.sourceFile}`)+ if (boot.unexpected.length || boot.errors.length) {+ if (historic) console.log(' (historic release: reported, not fatal)')+ else failed = true+ }+ if (out) writeFileSync(out, JSON.stringify(pins, null, 2) + '\n')+ else console.log(JSON.stringify(pins))+} catch (e) {+ console.error(e.message)+ failed = true+} finally {+ await browser.close()+}+process.exit(failed ? 1 : 0)diff --git a/scripts/lib/csp-boot.mjs b/scripts/lib/csp-boot.mjsnew file mode 100644index 00000000..973610f6--- /dev/null+++ b/scripts/lib/csp-boot.mjs@@ -0,0 +1,163 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// THE PINNED-CSP BOOT CHECK (K4, security §18 / §36 / §36a): a release must+// boot, and keep working while its UI is driven, under the script policy a+// host will serve it with:+//+// script-src 'sha256-<loader>' 'sha256-<remover>' blob:; style-src 'unsafe-inline'+//+// Scripts are hash-pinned, the boundary. Styles are NOT pinned in phase 1+// (§36a): a document's own svg <style> can't be release-pinned (measured), and+// the sanitizer is the style control. Every refusal fails the check except the+// loader's two DESIGNED fallbacks: an inline script, then `new Function`,+// before it settles on blob:. Both are matched on directive AND source: the+// document itself, where the loader lives. A runtime path that injects any+// other script would be refused, and this check would see it.+//+// The shell is served from a fixed https origin with a real header, the way a+// host serves it (a <meta> CSP is not what hosts send). Refusals are read from+// the browser's securitypolicyviolation events, cross-checked against the+// browser's own log over CDP: Playwright's 'console' event never carries the+// CSP engine's messages (measured while building this).++import { readFileSync } from 'node:fs'+import { createHash } from 'node:crypto'+import { scanBlocks } from './release-pins.mjs'++export const ORIGIN = 'https://bento-pins.test'+const DOC_URL = `${ORIGIN}/doc.bento.html`++/** The policy a host serves a verified document with (the script and style axes). */+export function pinnedPolicy(pins) {+ return [`script-src ${pins.scriptSrc.map((h) => `'${h}'`).join(' ')} blob:`, "style-src 'unsafe-inline'"].join('; ')+}++/** Open `shellPath` served from ORIGIN under `policy`, with violations and the browser's log collected. */+async function servedPage(browser, shellPath, policy) {+ const context = await browser.newContext({ viewport: { width: 1440, height: 900 } })+ const html = readFileSync(shellPath)+ await context.route('**/*', (route) => {+ if (route.request().url() === DOC_URL) {+ return route.fulfill({ status: 200, headers: { 'content-type': 'text/html; charset=utf-8', 'content-security-policy': policy }, body: html })+ }+ return route.abort()+ })+ const page = await context.newPage()+ const log = []+ const cdp = await context.newCDPSession(page)+ await cdp.send('Log.enable')+ cdp.on('Log.entryAdded', ({ entry }) => { if (entry.source === 'security') log.push({ text: entry.text, level: entry.level }) })+ const violations = []+ await page.exposeBinding('__bentoPinsViolation', (_s, v) => { violations.push(v) })+ await page.addInitScript(() => {+ document.addEventListener('securitypolicyviolation', (e) => {+ // eslint-disable-next-line no-undef+ __bentoPinsViolation({ directive: e.effectiveDirective, disposition: e.disposition, blockedURI: e.blockedURI, sourceFile: e.sourceFile, line: e.lineNumber, column: e.columnNumber })+ }, true)+ })+ const errors = []+ page.on('pageerror', (e) => errors.push(e.message))+ await page.goto(DOC_URL)+ await page.waitForFunction(() => window.bento?.doc, null, { timeout: 30000 })+ return { context, page, log, violations, errors }+}++/**+ * Boot `shellPath` under its pins and run `drive(page)`. Returns the loader's+ * expected refusals, every OTHER refusal (`unexpected`; [] = pass) and page+ * errors. Throws if the browser's log and its violation events disagree, since+ * then neither can be trusted to have seen everything.+ */+export async function bootUnderPins(browser, shellPath, pins, drive = async (p) => { await p.waitForTimeout(2000) }) {+ const s = await servedPage(browser, shellPath, pinnedPolicy(pins))+ try {+ await drive(s.page)+ await s.page.waitForTimeout(500)+ } finally {+ await s.context.close()+ }+ // The loader is the document's own inline script, so matching on the source+ // FILE alone would excuse ANY inline script in the document (measured: an+ // injected <script> passed as "the loader's fallback"). Whole LINES aren't+ // enough either: the loader's open and close tags share lines with other+ // markup (</body> sits on its closing line), and a script injected there was+ // excused (security, measured). So a refusal is the loader's only if its+ // line AND column fall inside the loader's own text, and at most ONE of each+ // fallback is excused: the loader tries each once.+ const span = loaderSpan(readFileSync(shellPath, 'utf8'), pins.scriptSrc[0])+ const inLoader = (v) => v.sourceFile === DOC_URL && within(span, v.line, v.column)+ const expected = [], unexpected = []+ let inline = 0, evals = 0+ const enforced = s.violations.filter((v) => v.disposition === 'enforce')+ for (const v of enforced) {+ if (inLoader(v) && v.directive === 'script-src-elem' && v.blockedURI === 'inline' && inline++ === 0) expected.push(v)+ else if (inLoader(v) && v.directive === 'script-src' && v.blockedURI === 'eval' && evals++ === 0) expected.push(v)+ else unexpected.push(v)+ }+ // Chrome LOGS every refusal except an eval one (measured, Chrome 150: a+ // refused `new Function` raises an EvalError the loader catches, and only the+ // violation event records it). So the cross-check covers the logged kinds;+ // eval refusals are judged from the events alone, which do fire for them.+ const logged = s.log.filter((m) => m.level === 'error' && /Content Security Policy/.test(m.text)).length+ const loggable = enforced.filter((v) => v.blockedURI !== 'eval').length+ if (logged !== loggable) throw new Error(`csp-boot: ${loggable} non-eval refusals fired but the browser logged ${logged}: cannot judge them`)+ return { expected, unexpected, errors: s.errors }+}++/**+ * Where the PINNED loader's text sits in the served HTML, as 1-based+ * {line, column} from its first character to its last: the executable inline+ * script whose CSP hash is the pins' first script hash. Identified by its hash,+ * not by being the only script, so a doctored file with an extra script still+ * finds the real loader (and the extra script stays unexcused).+ */+export function loaderSpan(html, loaderCspHash) {+ const loaders = scanBlocks(html).filter((b) => b.tag === 'script' && b.src === null &&+ `sha256-${createHash('sha256').update(b.text, 'utf8').digest('base64')}` === loaderCspHash)+ if (loaders.length !== 1) throw new Error(`csp-boot: ${loaders.length} scripts match the pinned loader; exactly one expected`)+ const pos = (offset) => {+ const before = html.slice(0, offset)+ const line = before.split('\n').length+ return { line, column: offset - before.lastIndexOf('\n') } // 1-based+ }+ return { from: pos(loaders[0].start), to: pos(loaders[0].start + loaders[0].text.length) }+}+const after = (a, b) => a.line > b.line || (a.line === b.line && a.column >= b.column)+/** Is (line, column), 1-based, inside the span? */+const within = (span, line, column) => after({ line, column }, span.from) && after(span.to, { line, column })++// --- driving --------------------------------------------------------------------+//+// A broad first-pass DRIVER for any app: click every visible control once and+// dismiss what opened. Deliberately dumb: an app's owner adds the surfaces it+// can't reach. Never a control that destroys, publishes or leaves.+const DENY = /\b(delete|remove|stop sharing|rotate|revoke|discard|reset|sign out|publish|share link|invite|start live|go live|leave|quit|update now|install|download|save|print|export|import|replace from|open file|duplicate as new|encrypt|password)\b/i+const CONTROLS = 'button, [role="button"], [role="menuitem"], [role="tab"], summary, select, [aria-haspopup]'++/** Click each visible, enabled, not-denied control under `root` once; Escape after each. */+export async function clickEverything(page, { root = 'body', max = 400, settle = 120 } = {}) {+ const seen = new Set()+ let clicked = 0+ for (let pass = 0; pass < 3 && clicked < max; pass++) {+ const handles = await page.$$(`${root} :is(${CONTROLS})`)+ let fresh = 0+ for (const h of handles) {+ if (clicked >= max) break+ const info = await h.evaluate((el) => {+ const r = el.getBoundingClientRect(), cs = getComputedStyle(el)+ const label = (el.getAttribute('aria-label') || el.getAttribute('title') || el.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60)+ return { visible: r.width > 0 && r.height > 0 && cs.visibility !== 'hidden' && cs.display !== 'none',+ disabled: el.disabled || el.getAttribute('aria-disabled') === 'true', label, key: `${el.tagName}|${el.className}|${label}` }+ }).catch(() => null)+ if (!info || !info.visible || info.disabled || DENY.test(info.label) || seen.has(info.key)) continue+ seen.add(info.key); fresh+++ await h.click({ timeout: 800, force: false }).catch(() => {})+ clicked+++ await page.waitForTimeout(settle)+ await page.keyboard.press('Escape').catch(() => {})+ }+ if (!fresh) break+ }+ return clicked+}diff --git a/scripts/lib/release-history.mjs b/scripts/lib/release-history.mjsnew file mode 100644index 00000000..77c3f4b2--- /dev/null+++ b/scripts/lib/release-history.mjs@@ -0,0 +1,119 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// THE SIGNED RELEASE HISTORY (K4, security §36): every release of an app still+// in the wild, with its pins, in one cumulative payload signed by the release+// key. It is what lets a host verify a file saved by ANY genuine release, not+// only the newest, without carrying every shell it trusts.+//+// releases/<app>/history.json = { payload: "<json>", sig } (the release envelope)+// payload = { app, v: 1, releases: [ { version, sha256, at, pins }, ... ] } newest first+//+// Three rules live here, each the one a host must apply:+// - nextHistory(): append-only. A history never loses an entry, never changes+// one, and a new release must be newer than every release it holds.+// - acceptHistory(): ANTI-ROLLBACK for hosts. A host keeps the newest history+// it has verified and refuses one that lacks an entry it holds or whose+// newest version is lower, so a replayed older signed history can't hide a+// release.+// - matchRelease(): a file matches a release only if ONE entry matches EVERY+// block (rt, rt-css, loader, remover) with exactly one block per id. Two+// releases sharing a runtime can't be confused, and anything partial is+// UNKNOWN: restricted mode or an update offer, never a borrowed pinned CSP.++import { checkAgainstPins, scanBlocks } from './release-pins.mjs'+import { createHash } from 'node:crypto'++export const HISTORY_V = 1++const SEMVER = /^(\d+)\.(\d+)\.(\d+)$/+export function cmpVersion(a, b) {+ const x = SEMVER.exec(a), y = SEMVER.exec(b)+ if (!x || !y) throw new Error(`release-history: not a version: ${!x ? a : b}`)+ for (let i = 1; i <= 3; i++) { const d = Number(x[i]) - Number(y[i]); if (d) return d }+ return 0+}++const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)+const entryOk = (e) => e && typeof e.version === 'string' && SEMVER.test(e.version) &&+ /^[0-9a-f]{64}$/.test(e.sha256 ?? '') && typeof e.at === 'string' && e.pins?.v === 1 && typeof e.pins.blocks === 'object'++/** Check a history payload's shape; returns the problems ([] = well-formed). */+export function historyProblems(h) {+ const p = []+ if (!h || h.v !== HISTORY_V) p.push(`version ${h?.v} (expected ${HISTORY_V})`)+ if (typeof h?.app !== 'string' || !h.app) p.push('no app')+ if (!Array.isArray(h?.releases)) { p.push('no releases'); return p }+ const seen = new Set()+ h.releases.forEach((e, i) => {+ if (!entryOk(e)) p.push(`entry ${i} is malformed`)+ else {+ if (seen.has(e.version)) p.push(`version ${e.version} appears twice`)+ seen.add(e.version)+ if (i > 0 && entryOk(h.releases[i - 1]) && cmpVersion(h.releases[i - 1].version, e.version) <= 0) p.push(`entries are not newest-first at ${e.version}`)+ }+ })+ return p+}++/**+ * The next history: `held` (null for the first) plus `entry` for a new release.+ * Re-signing the SAME release (same version and sha256 and pins) is a no-op. A+ * release that isn't newer than everything held, or a changed entry for a held+ * version, is refused: a history only grows.+ */+export function nextHistory(app, held, entry) {+ if (!entryOk(entry)) throw new Error('release-history: the new entry is malformed')+ const releases = held ? held.releases : []+ if (held) {+ const problems = historyProblems(held)+ if (problems.length) throw new Error(`release-history: the held history is malformed: ${problems.join('; ')}`)+ if (held.app !== app) throw new Error(`release-history: the held history is for ${held.app}, not ${app}`)+ }+ const existing = releases.find((e) => e.version === entry.version)+ if (existing) {+ if (same(existing, entry)) return { app, v: HISTORY_V, releases }+ throw new Error(`release-history: ${entry.version} is already in the history with different bytes: a history never changes an entry`)+ }+ if (releases.length && cmpVersion(entry.version, releases[0].version) <= 0) {+ throw new Error(`release-history: ${entry.version} is not newer than ${releases[0].version}: a history only grows forward`)+ }+ return { app, v: HISTORY_V, releases: [entry, ...releases] }+}++/**+ * A HOST's acceptance of an incoming (already signature-verified) history,+ * given the newest it holds. Returns { ok: true } or { ok: false, reason }.+ */+export function acceptHistory(held, incoming, app) {+ const problems = historyProblems(incoming)+ if (problems.length) return { ok: false, reason: `malformed: ${problems[0]}` }+ if (incoming.app !== app) return { ok: false, reason: `for ${incoming.app}, not ${app}` }+ if (!held) return { ok: true }+ if (!incoming.releases.length || (held.releases.length && cmpVersion(incoming.releases[0].version, held.releases[0].version) < 0)) {+ return { ok: false, reason: 'rollback: its newest release is older than the newest already held' }+ }+ for (const e of held.releases) {+ const there = incoming.releases.find((x) => x.version === e.version)+ if (!there) return { ok: false, reason: `rollback: it lacks ${e.version}, which is already held` }+ if (!same(there, e)) return { ok: false, reason: `${e.version} changed: a history never changes an entry` }+ }+ return { ok: true }+}++const blockHash = (html, id) => {+ const found = scanBlocks(html).filter((b) => b.id === id)+ return found.length === 1 ? createHash('sha256').update(found[0].text, 'utf8').digest('hex') : null+}++/**+ * Which release made this file? The ONE entry matching every block; null when+ * none does, or when more than one would (UNKNOWN either way).+ */+export function matchRelease(history, html) {+ const rt = blockHash(html, 'bento-rt')+ if (!rt) return null+ const candidates = history.releases.filter((e) => e.pins.blocks['bento-rt'] === rt)+ const full = candidates.filter((e) => checkAgainstPins(html, e.pins).length === 0)+ return full.length === 1 ? full[0] : null+}diff --git a/scripts/lib/release-pins.mjs b/scripts/lib/release-pins.mjsnew file mode 100644index 00000000..9c8374d6--- /dev/null+++ b/scripts/lib/release-pins.mjs@@ -0,0 +1,183 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// RELEASE PINS (K4, security §18 / §36): what a host needs to know a file's+// runtime is a genuine release's, derived from that release's own bytes.+//+// A host that SERVES a document (iOS, Android, desktop, the hosted runtime)+// checks the CODE blocks, which survive every save byte-identical because they+// are textContent, not markup:+// bento-rt, bento-rt-css the deflated runtime and stylesheet (data blocks+// the loader imports as blob: code, so the CSP cannot+// stop a swapped one, only this hash can)+// loader the one executable inline script in the shell+// remover the preview remover every save writes (constant)+// and serves the page with script-src pinned to the loader and the remover.+// A file matches a release only if ONE release matches EVERY block, with+// exactly one block per id; anything less is UNKNOWN (security §36).+//+// Pure string work, no DOM: this runs at release time on the built shell and a+// real saved file, and in CI on every PR's build.++import { createHash } from 'node:crypto'++const sha256hex = (s) => createHash('sha256').update(s, 'utf8').digest('hex')+const cspHash = (s) => `sha256-${createHash('sha256').update(s, 'utf8').digest('base64')}`++// THE GRAMMAR (security, 2026-10-21): a <script> is inert ONLY if its type is+// one of the exact data types Bento writes. Everything else is executable: no+// type, a JavaScript MIME type, "module", an unknown type, a differently cased+// data type, and ANY src=. An executable script must then be exactly the pinned+// loader or remover by hash, or the file is UNKNOWN. An allowlist, not a list of+// JavaScript types: a script type a browser treats as runnable tomorrow can't+// slip through as "data".+export const DATA_TYPES = new Set(['application/bento+json', 'application/bento+lang', 'bento/deflate-b64', 'bento/deflate-b86'])+export const isDataScript = (b) => b.tag === 'script' && b.src === null && b.type !== null && DATA_TYPES.has(b.type)++const attr = (attrs, name) => {+ const m = new RegExp(`(?:^|\\s)${name}(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+)))?(?=\\s|$)`, 'i').exec(attrs)+ if (!m) return null+ return m[1] ?? m[2] ?? m[3] ?? ''+}++/**+ * Every <script> and <style> element, with its raw text: a script's text ends at+ * the first `</script` (any case), which is how the HTML tokenizer ends it too.+ */+export function scanBlocks(html) {+ const out = []+ const open = /<(script|style)\b([^>]*)>/gi+ let m+ while ((m = open.exec(html))) {+ const tag = m[1].toLowerCase()+ const start = m.index + m[0].length+ const close = html.toLowerCase().indexOf(`</${tag}`, start)+ if (close < 0) throw new Error(`release-pins: unterminated <${tag}> at ${m.index}`)+ const attrs = m[2]+ out.push({+ tag, attrs, text: html.slice(start, close), start,+ type: attr(attrs, 'type'), id: attr(attrs, 'id'), src: attr(attrs, 'src'),+ preview: attr(attrs, 'data-bento-preview') !== null,+ })+ open.lastIndex = close+ }+ return out+}++/** Every script that is not one of Bento's data blocks: each must be the pinned loader or remover. */+export const executableScripts = (blocks) => blocks.filter((b) => b.tag === 'script' && !isDataScript(b))++/**+ * Markup a genuine Bento file never carries (security, 2026-10-21), anywhere+ * outside a script or style element's own text: <iframe>, <object>, <embed>,+ * <base>, a <meta> refresh or CSP, any on*= attribute, and a comment holding a+ * <script>. A data block containing "<" is refused too: Bento's never do (the+ * document JSON and language packs escape it, the b64/b86 alphabets exclude+ * it), and a "<!--<script" inside script text would put the browser's+ * tokenizer in a state where a later close tag doesn't end the element. Returns+ * the problems; [] = none.+ */+export function markupProblems(html) {+ const problems = []+ const lower = html.toLowerCase()+ let i = 0+ while ((i = html.indexOf('<', i)) !== -1) {+ if (html.startsWith('<!--', i)) {+ const end = html.indexOf('-->', i + 4)+ const body = lower.slice(i + 4, end < 0 ? html.length : end)+ if (body.includes('<script')) problems.push('a comment holds a <script>')+ if (end < 0) { problems.push('an unterminated comment'); break }+ i = end + 3; continue+ }+ const m = /^<([a-zA-Z][a-zA-Z0-9-]*)/.exec(html.slice(i, i + 64))+ if (!m) { i++; continue }+ const name = m[1].toLowerCase()+ // the tag's attributes, quote-aware, up to its closing '>'+ let j = i + m[0].length, q = null+ for (; j < html.length; j++) {+ const c = html[j]+ if (q) { if (c === q) q = null } else if (c === '"' || c === "'") q = c; else if (c === '>') break+ }+ const attrs = html.slice(i + m[0].length, j)+ if (['iframe', 'object', 'embed', 'base'].includes(name)) problems.push(`a <${name}>`)+ if (name === 'meta' && /http-equiv\s*=\s*["']?\s*(refresh|content-security-policy)/i.test(attrs)) problems.push('a <meta> refresh or CSP')+ if (/(^|[\s"'/])on[a-z0-9_-]*\s*=/i.test(attrs)) problems.push(`an on*= attribute on <${name}>`)+ if (name === 'script' || name === 'style') {+ const close = lower.indexOf(`</${name}`, j)+ if (close < 0) { problems.push(`an unterminated <${name}>`); break }+ // inert to a browser, but a scanner that doesn't special-case <style>+ // would count it: refuse, so every host's scanner reaches the same verdict+ if (name === 'style' && lower.slice(j, close).includes('<script')) problems.push('a <style> holds a <script>')+ i = close + 2; continue+ }+ i = j + 1+ }+ for (const b of scanBlocks(html)) if (isDataScript(b) && b.text.includes('<')) problems.push(`the ${b.type} block contains "<"`)+ return problems+}++const CODE_IDS = ['bento-rt', 'bento-rt-css']++/**+ * The pins for a release, from its BUILT shell and a REAL file that release+ * saved (the remover only exists in saved files). Throws, never guesses: the+ * shell has exactly one executable inline script (the loader); the saved file's+ * executable inline scripts are exactly that loader, byte for byte, plus one+ * preview remover; every code block appears once in each, identical in both.+ */+export function derivePins(shellHtml, savedHtml, { historic = false } = {}) {+ const shell = scanBlocks(shellHtml), saved = scanBlocks(savedHtml)+ const fail = (msg) => { throw new Error(`release-pins: ${msg}`) }+ for (const [what, html] of [['built shell', shellHtml], ['saved file', savedHtml]]) {+ const bad = markupProblems(html)+ if (bad.length) fail(`the ${what} carries markup a genuine file never does: ${bad.join('; ')}`)+ }++ const shellExec = executableScripts(shell)+ if (shellExec.length !== 1) fail(`the built shell has ${shellExec.length} executable inline scripts; exactly one (the loader) expected`)+ const loader = shellExec[0].text++ const savedExec = executableScripts(saved)+ const removers = savedExec.filter((b) => b.preview)+ const loaders = savedExec.filter((b) => !b.preview)+ if (loaders.length !== 1 || loaders[0].text !== loader) fail('the saved file does not carry exactly the shell\'s loader, byte for byte')+ // A release from before the first-page preview (slides < 1.0.18) saves no+ // remover. Only a HISTORIC release may lack one: a new release that saves+ // none has a broken preview, and signing it would pin the breakage.+ if (removers.length > 1 || (removers.length === 0 && !historic)) {+ fail(`the saved file has ${removers.length} preview removers; exactly one expected (save a document that gets a preview)`)+ }+ const remover = removers[0]?.text ?? null++ const blocks = { loader: sha256hex(loader), remover: remover === null ? null : sha256hex(remover) }+ for (const id of CODE_IDS) {+ const inShell = shell.filter((b) => b.id === id), inSaved = saved.filter((b) => b.id === id)+ if (inShell.length !== 1) fail(`the built shell has ${inShell.length} #${id} blocks; exactly one expected`)+ if (inSaved.length !== 1) fail(`the saved file has ${inSaved.length} #${id} blocks; exactly one expected`)+ if (inSaved[0].text !== inShell[0].text) fail(`#${id} changed between the shell and a saved file: code blocks must survive a save byte for byte`)+ blocks[id] = sha256hex(inShell[0].text)+ }+ return { v: 1, blocks, scriptSrc: remover === null ? [cspHash(loader)] : [cspHash(loader), cspHash(remover)] }+}++/**+ * Check a file against one release's pins, the way a host must (security §36):+ * exactly one block per code id, each hash equal, and the executable inline+ * scripts exactly the pinned loader and remover. Returns the problems; [] = match.+ */+export function checkAgainstPins(html, pins) {+ const problems = [...markupProblems(html)]+ const blocks = scanBlocks(html)+ for (const id of CODE_IDS) {+ const found = blocks.filter((b) => b.id === id)+ if (found.length !== 1) problems.push(`${found.length} #${id} blocks (exactly one expected)`)+ else if (sha256hex(found[0].text) !== pins.blocks[id]) problems.push(`#${id} does not match`)+ }+ const exec = executableScripts(blocks)+ const allowed = new Set([pins.blocks.loader, pins.blocks.remover].filter(Boolean))+ for (const s of exec) if (s.src !== null || !allowed.has(sha256hex(s.text))) problems.push(`an executable script that is neither the pinned loader nor the remover (${s.src !== null ? 'src=' + s.src : s.text.length + 'B'})`)+ if (!exec.some((s) => sha256hex(s.text) === pins.blocks.loader)) problems.push('no pinned loader')+ if (exec.filter((s) => sha256hex(s.text) === pins.blocks.loader).length > 1) problems.push('more than one loader')+ if (pins.blocks.remover && exec.filter((s) => sha256hex(s.text) === pins.blocks.remover).length > 1) problems.push('more than one remover')+ return problems+}diff --git a/scripts/lib/saved-by.mjs b/scripts/lib/saved-by.mjsnew file mode 100644index 00000000..3e6760aa--- /dev/null+++ b/scripts/lib/saved-by.mjs@@ -0,0 +1,31 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// A file an app's OWN save wrote: boot the shell in Chromium, press ⌘S with the+// File System Access picker removed, and take the download fallback. The only+// honest source for the bytes a release writes (the preview remover exists+// only in saved files), and it doesn't depend on any app's scripting API: type's+// window.bento.serialize returns JSON, not a file. Works on every slides+// release from 0.7.0 on (measured).++import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { pathToFileURL } from 'node:url'++export async function savedBy(browser, shellPath) {+ const context = await browser.newContext({ acceptDownloads: true })+ await context.route(/^https?:/, (r) => r.abort())+ await context.addInitScript(() => { delete window.showSaveFilePicker; delete window.showOpenFilePicker })+ const page = await context.newPage()+ try {+ await page.goto(pathToFileURL(resolve(shellPath)).href)+ await page.waitForFunction(() => window.bento?.doc, null, { timeout: 30000 })+ await page.waitForTimeout(1500)+ await page.locator('body').click({ position: { x: 5, y: 5 } }).catch(() => {})+ const download = page.waitForEvent('download', { timeout: 15000 })+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+s' : 'Control+s')+ return readFileSync(await (await download).path(), 'utf8')+ } finally {+ await context.close()+ }+}diff --git a/scripts/release.mjs b/scripts/release.mjsindex c14b11c2..df2352a6 100644--- a/scripts/release.mjs+++ b/scripts/release.mjs@@ -35,7 +35,8 @@// rebuild producing different bytes than what was signed.)import { execFileSync } from 'node:child_process'-import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'+import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'import { join, dirname, resolve } from 'node:path'import { fileURLToPath } from 'node:url'import { spliceDoc } from './guestbook-deck.mjs'@@ -170,6 +171,19 @@ if (app.agents && existsSync(join(root, app.agents))) {// scripts/shell-gate.mjs (shared with CI, which runs it on every PR build).gateShell(join(site, `releases/${app.dir}/${app.shell}`))+// PINS GATE (K4, security §18 / §36). Derive the release's pins from its OWN+// bytes, a real file it saved, and boot it under them while driving its UI.+// Any mismatch, any executable inline script in a saved file other than the+// pinned loader and remover, or any refusal beyond the loader's two designed+// fallbacks exits non-zero, and nothing below is signed. It needs Playwright+// and Chromium (PLAYWRIGHT_MODULE, CHROME_PATH). Without them the pins can't be+// checked, so the release stops there too: there's no unchecked path.+const pinsDir = mkdtempSync(join(tmpdir(), 'bento-pins-'))+const pinsPath = join(pinsDir, 'pins.json')+const stagedShell = join(site, `releases/${app.dir}/${app.shell}`)+console.log('• deriving and checking the release pins (derive-pins.mjs)…')+execFileSync('node', [join(root, 'scripts/derive-pins.mjs'), stagedShell, '--out', pinsPath], { stdio: 'inherit' })+const key = opt('key', null)/**@@ -293,9 +307,32 @@ const signArgs = []if (notes) signArgs.push('--notes', notes)if (notesFrom) signArgs.push('--notes-from', JSON.stringify(notesFrom))+signArgs.push('--pins', pinsPath)if (key) signArgs.push('--key', key)execFileSync('node', signArgs, { stdio: 'inherit' })+// THE RELEASE HISTORY (K4): the published history plus this release, signed+// with the same key. The held history came in with the seed from the live+// tree, and sign-history verifies its signature before building on it. The+// FIRST history is seeded by backfilling every earlier signed release from the+// live repository's git history, each shell checked against its own manifest.+{+ const historyPath = join(site, `releases/${app.dir}/history.json`)+ const historyArgs = [join(root, 'scripts/sign-history.mjs'), '--app', app.appId, '--version', version,+ '--shell', stagedShell, '--pins', pinsPath, '--out', historyPath]+ if (existsSync(historyPath)) historyArgs.push('--held', historyPath)+ else if (existsSync(join(published, '.git'))) {+ const seed = join(pinsDir, 'seed.json')+ console.log('• first release history: backfilling every earlier signed release (backfill-history.mjs)…')+ execFileSync('node', [join(root, 'scripts/backfill-history.mjs'), '--site', published, '--dir', app.dir, '--app', app.appId, '--out', seed], { stdio: 'inherit' })+ historyArgs.push('--seed', seed)+ } else {+ console.log('⚠ no published history and no live repository to backfill from: the history starts at this release')+ }+ if (key) historyArgs.push('--key', key)+ execFileSync('node', historyArgs, { stdio: 'inherit' })+}+// Language packs, for the apps that have a signed channel. build-i18n.mjs and// sign-packs.mjs are slides-hardcoded end to end (docs/i18n-packs.md), so an// app without a catalog stages none rather than staging UNSIGNED ones —diff --git a/scripts/sign-history.mjs b/scripts/sign-history.mjsnew file mode 100644index 00000000..6e13ace3--- /dev/null+++ b/scripts/sign-history.mjs@@ -0,0 +1,69 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Sign an app's release HISTORY (K4): the held history plus this release.+//+// node scripts/sign-history.mjs --app bento-slides --version 1.2.10 \+// --shell site/releases/slides/Bento_Slides.bento.html --pins pins.json \+// [--held site/releases/slides/history.json] [--seed entries.json] \+// [--key ~/.bento/release-key.json] --out site/releases/slides/history.json+//+// --held is the history currently published. Its signature is VERIFIED against+// the release public key before anything is built on it, so a tampered held+// file can't be laundered into a fresh signature. --seed takes the unsigned+// entries backfill-history.mjs produced, for the FIRST history only.+//+// The history only grows (scripts/lib/release-history.mjs nextHistory): a+// release that isn't newer than everything held is refused, as is a changed+// entry for a version already held. Signing uses the same offline key and+// envelope as the manifest (scripts/sign-payload.mjs), and like the manifest+// it is signed ONLY on the maintainer's machine, on an explicit release go.++import { createHash } from 'node:crypto'+import { existsSync, readFileSync, writeFileSync } from 'node:fs'+import { defaultKeyPath, envelopeJson, releasePublicKey, signPayload, verifyEnvelope } from './sign-payload.mjs'+import { nextHistory, historyProblems, cmpVersion, HISTORY_V } from './lib/release-history.mjs'++const args = process.argv.slice(2)+const opt = (name) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : undefined }+const need = (name) => { const v = opt(name); if (!v) { console.error(`sign-history: --${name} is required`); process.exit(2) } return v }++const app = need('app'), version = need('version'), shellPath = need('shell'), pinsPath = need('pins'), out = need('out')+const heldPath = opt('held'), seedPath = opt('seed'), keyPath = opt('key') ?? defaultKeyPath()+const publicJwk = opt('public') ? JSON.parse(readFileSync(opt('public'), 'utf8')) : releasePublicKey()++let held = null+if (heldPath && existsSync(heldPath)) {+ held = verifyEnvelope(readFileSync(heldPath, 'utf8'), publicJwk) // throws on a bad signature+ const problems = historyProblems(held)+ if (problems.length) { console.error(`sign-history: the held history is malformed: ${problems.join('; ')}`); process.exit(1) }+} else if (seedPath) {+ const entries = JSON.parse(readFileSync(seedPath, 'utf8'))+ entries.sort((a, b) => cmpVersion(b.version, a.version))+ held = { app, v: HISTORY_V, releases: entries }+ const problems = historyProblems(held)+ if (problems.length) { console.error(`sign-history: the seed is malformed: ${problems.join('; ')}`); process.exit(1) }+}++const shell = readFileSync(shellPath)+const entry = {+ version,+ sha256: createHash('sha256').update(shell).digest('hex'),+ at: new Date().toISOString(),+ pins: JSON.parse(readFileSync(pinsPath, 'utf8')),+}++let history+try {+ history = nextHistory(app, held, entry)+} catch (e) {+ console.error(e.message)+ process.exit(1)+}+// signPayload self-verifies against the key file's own public half, as the+// manifest's signing does. The HELD history was verified against the shipped+// release key above, which is the check that guards against laundering.+const envelope = signPayload(JSON.stringify(history), keyPath)+writeFileSync(out, envelopeJson(envelope))+console.log(`Signed ${app} history: ${history.releases.length} release(s), newest ${history.releases[0].version} → ${out}`)diff --git a/scripts/sign-release.mjs b/scripts/sign-release.mjsindex 1d2a6a7f..304b04a1 100644--- a/scripts/sign-release.mjs+++ b/scripts/sign-release.mjs@@ -61,6 +61,16 @@ if (notesFromRaw) {try { notesFrom = JSON.parse(notesFromRaw) }catch { console.error('sign-release: --notes-from is not valid JSON'); process.exit(1) }}+// The release's PINS (K4, security §36): its code-block hashes and CSP script+// hashes, from scripts/derive-pins.mjs. ADDITIVE: shipped shells' update check+// reads only app/version/sha256/url and ignores everything else.+const pinsPath = opt('pins', '')+let pins = null+if (pinsPath) {+ try { pins = JSON.parse(readFileSync(pinsPath, 'utf8')) }+ catch { console.error('sign-release: --pins is not a readable JSON file'); process.exit(1) }+ if (pins?.v !== 1 || !pins.blocks?.loader || !Array.isArray(pins.scriptSrc)) { console.error('sign-release: --pins is not a v1 pins object'); process.exit(1) }+}const keyPath = opt('key', defaultKeyPath())const outPath = opt('out', join(dirname(shellPath), 'manifest.json'))@@ -74,6 +84,7 @@ const payload = JSON.stringify({url,...(notes ? { notes } : {}),...(notesFrom ? { notesFrom } : {}),+ ...(pins ? { pins } : {}),at: new Date().toISOString(),})diff --git a/scripts/test-csp-boot-browser.mjs b/scripts/test-csp-boot-browser.mjsnew file mode 100644index 00000000..49acdfd4--- /dev/null+++ b/scripts/test-csp-boot-browser.mjs@@ -0,0 +1,86 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// THE PINNED-CSP BOOT CHECK, against doctored copies of a real build (K4,+// security §36). scripts/lib/csp-boot.mjs excuses only the loader's two+// designed fallbacks: one inline, one eval, from a line AND column inside the+// pinned loader's own text. These rows are the ways that excuse went wrong+// while it was being built:+// - matched on the source FILE: an injected <script> anywhere passed;+// - matched on whole LINES: a <script> on the loader's opening or closing+// line passed (the loader shares those lines with other markup).+// The pin derivation and the host check would refuse these files on their own;+// this proves the BOOT check refuses them too, as the backstop it is.+//+// npm run build:single --prefix slides && node scripts/test-csp-boot-browser.mjs++import { readFileSync, writeFileSync, mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { bootUnderPins } from './lib/csp-boot.mjs'+import { derivePins, scanBlocks, executableScripts } from './lib/release-pins.mjs'+import { savedBy } from './lib/saved-by.mjs'++const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')+const shellPath = new URL('../slides/dist-single/Bento_Slides.bento.html', import.meta.url).pathname+let failures = 0, checks = 0+const ok = (cond, what) => { checks++; if (cond) console.log(' ok ' + what); else { failures++; console.log(' FAIL ' + what) } }++const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })+try {+ const html = readFileSync(shellPath, 'utf8')+ const pins = derivePins(html, await savedBy(browser, shellPath))+ const dir = mkdtempSync(join(tmpdir(), 'bento-cspboot-'))+ const S = 'scr' + 'ipt', evil = `<${S}>window.__evil = 1</${S}>`+ const loader = executableScripts(scanBlocks(html)).find((b) => !b.preview)+ const openAt = html.lastIndexOf(`<${S}`, loader.start)+ const closeAt = html.indexOf('>', loader.start + loader.text.length) + 1+ const doctored = (name, text) => { const p = join(dir, `${name}.html`); writeFileSync(p, text); return p }++ const base = await bootUnderPins(browser, shellPath, pins)+ ok(base.expected.length === 2 && base.unexpected.length === 0, `genuine: exactly the loader's two fallbacks (${base.expected.length} expected, ${base.unexpected.length} unexpected)`)++ for (const [name, text] of [+ ['a <script> injected in <head>', html.replace('</head>', evil + '</head>')],+ ["a <script> on the loader's opening line, before it", html.slice(0, openAt) + evil + html.slice(openAt)],+ ["a <script> on the loader's closing line, after it", html.slice(0, closeAt) + evil + html.slice(closeAt)],+ ]) {+ const r = await bootUnderPins(browser, doctored(name.replace(/\W+/g, '-'), text), pins)+ // Not just "something was unexpected": the EXCUSED refusals must be the+ // loader's own (inside its text) and the injected one must be among the+ // UNEXPECTED. A count alone passes when a defence excuses the WRONG refusal+ // and the loader's own fallback is reported in its place (measured: the+ // column rule and the once-each cap each hid the other's removal that way).+ // On Chrome 149 the injected refusal's column is 0, inside the loader's+ // span, so there the ONCE-EACH CAP is the guard that catches it.+ // Positions are worked out HERE, independently of csp-boot.mjs, which is+ // the code under test (a rig reusing its helper would mutate with it).+ const at = text.indexOf(loader.text), stop = at + loader.text.length+ const offsetOf = (line, column) => {+ let o = 0+ for (let n = 1; n < line; n++) o = text.indexOf('\n', o) + 1+ return o + column - 1+ }+ const inLoaderText = (v) => { const o = offsetOf(v.line, v.column); return o >= at && o <= stop }+ // Where the injected script is. Refusal COLUMNS aren't reliable across+ // Chrome versions: Chrome Headless Shell 149 (CI's) reports this one at+ // column 0, inside the loader's span, while 155 reports its real column+ // (security, measured). So it's identified by its LINE, with its column+ // either matching or 0, never by an exact column.+ const injAt = text.indexOf(evil, name.includes('<head>') ? 0 : Math.max(0, openAt - 1))+ const injLine = text.slice(0, injAt).split('\n').length+ const injCol = injAt - text.lastIndexOf('\n', injAt - 1) // 1-based+ const isInjected = (v) => v.directive === 'script-src-elem' && v.line === injLine &&+ (v.column === 0 || (v.column >= injCol && v.column <= injCol + evil.length))+ const excusedAreLoaders = r.expected.every((v) => inLoaderText(v) && !isInjected(v))+ const injectedReported = r.unexpected.some(isInjected)+ ok(excusedAreLoaders && injectedReported, `refused and reported: ${name} (excused only the loader's own: ${excusedAreLoaders}; the injected one reported: ${injectedReported})`)+ }++ const wrong = { ...pins, scriptSrc: ['sha256-' + 'A'.repeat(43) + '=', pins.scriptSrc[1]] }+ ok(await bootUnderPins(browser, shellPath, wrong).then(() => false, () => true), 'a wrong loader pin: the app never boots')+} finally {+ await browser.close()+}+console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)diff --git a/scripts/test-release-channel.mjs b/scripts/test-release-channel.mjsindex 9f1041dd..f69291e0 100644--- a/scripts/test-release-channel.mjs+++ b/scripts/test-release-channel.mjs@@ -156,6 +156,27 @@ ok(payload.url === `https://bento.page/releases/${app.dir}/${app.shell}`,`the download URL is under the path the shell fetches (${payload.url})`)ok(typeof payload.at === 'string', 'the payload is stamped with a time')+// ---- 3b. the pins and the release history (K4) ------------------------------+//+// release.mjs derived the pins from the staged shell and a file it saved, and+// booted it under them (derive-pins.mjs) before signing. The manifest carries+// them, ADDITIVELY, and the signed history holds this release with the SAME+// pins: hosts check a file against either.+ok(payload.pins?.v === 1 && /^sha256-/.test(payload.pins.scriptSrc?.[0] ?? '') && /^[0-9a-f]{64}$/.test(payload.pins.blocks?.['bento-rt'] ?? ''),+ 'the manifest carries the release pins: the CSP script hashes and the code-block hashes')+{+ const { checkAgainstPins } = await import('./lib/release-pins.mjs')+ ok(checkAgainstPins(readFileSync(stagedShell, 'utf8'), payload.pins).length === 0,+ "the staged shell's code blocks and loader match the signed pins")+ const historyPath = join(site, `releases/${app.dir}/history.json`)+ ok(existsSync(historyPath), `the release signed a history at releases/${app.dir}/history.json`)+ const history = existsSync(historyPath) ? verifyEnvelope(readFileSync(historyPath, 'utf8'), pubJwk) : null+ const mine = history?.releases.find((e) => e.version === payload.version)+ ok(history?.app === app.appId && history.releases[0]?.version === payload.version, 'the history is for this app, newest release first')+ ok(!!mine && mine.sha256 === payload.sha256 && JSON.stringify(mine.pins) === JSON.stringify(payload.pins),+ 'the history entry for this release has the same shell sha256 and the same pins as the manifest')+}+// ---- 4. the verifier every shipped file runs --------------------------------//// kernel/src/update.ts, copied to a temp directory with ONE edit: the embeddeddiff --git a/scripts/test-release-history.ts b/scripts/test-release-history.tsnew file mode 100644index 00000000..c91bf13e--- /dev/null+++ b/scripts/test-release-history.ts@@ -0,0 +1,149 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// The signed release history (K4, security §36): append-only, anti-rollback,+// and a file matches a release only if ONE entry matches EVERY block.+//+// node scripts/test-release-history.ts+//+// Synthetic shells and saved files (tiny, deterministic) stand in for real+// releases, so this runs in CI without a browser. sign-history.mjs is driven+// end to end with a throwaway TEST key, never the release key.++import { execFileSync } from 'node:child_process'+import { generateKeyPairSync } from 'node:crypto'+import { mkdtempSync, writeFileSync, readFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'+import { derivePins } from './lib/release-pins.mjs'+import { nextHistory, acceptHistory, matchRelease, historyProblems } from './lib/release-history.mjs'+import { verifyEnvelope } from './sign-payload.mjs'++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 throws = (f: () => unknown, re?: RegExp) => { try { f(); return false } catch (e) { return !re || re.test((e as Error).message) } }++const S = 'scr' + 'ipt'+const html = (o: { rt?: string; css?: string; loader?: string; remover?: string | null; extra?: string }) =>+ `<!DOCTYPE html><html><head><${S} type="application/bento+json" id="bento-doc">{}</${S}>` ++ `<${S} type="bento/deflate-b86" id="bento-rt-css">${o.css ?? 'CSS1'}</${S}>` ++ `<${S} type="bento/deflate-b86" id="bento-rt">${o.rt ?? 'RT1'}</${S}>` ++ `<${S}>${o.loader ?? 'load1()'}</${S}>${o.extra ?? ''}</head><body>` ++ (o.remover === null ? '' : `<div data-bento-preview="1">p</div><${S} data-bento-preview="1">${o.remover ?? 'rm()'}</${S}>`) ++ '</body></html>'+const release = (version: string, o: Parameters<typeof html>[0] = {}) => {+ const shell = html({ ...o, remover: null }), saved = html(o)+ return { entry: { version, sha256: version.replace(/\./g, '').padEnd(64, 'a'), at: '2026-10-21T00:00:00.000Z', pins: derivePins(shell, saved) }, saved }+}++const r1 = release('1.0.0'), r2 = release('1.1.0', { loader: 'load2()' }), r3 = release('1.2.0', { rt: 'RT3', loader: 'load3()' })++console.log('\nthe history only grows (nextHistory)')+const h1 = nextHistory('bento-test', null, r1.entry)+ok(h1.releases.length === 1 && historyProblems(h1).length === 0, 'the first history holds the first release')+const h2 = nextHistory('bento-test', h1, r2.entry)+ok(h2.releases.map((e) => e.version).join() === '1.1.0,1.0.0', 'a newer release is added, newest first')+ok(nextHistory('bento-test', h2, r2.entry).releases.length === 2, 're-signing the same release is a no-op')+ok(throws(() => nextHistory('bento-test', h2, release('1.0.5').entry), /not newer/), 'a release older than the newest held is refused')+ok(throws(() => nextHistory('bento-test', h2, { ...r2.entry, sha256: 'b'.repeat(64) }), /different bytes/), 'a changed entry for a held version is refused')+ok(throws(() => nextHistory('bento-other', h2, release('2.0.0').entry), /is for bento-test/), "a history held for another app is refused")++console.log('\na host accepts a history only forward (acceptHistory)')+const h3 = nextHistory('bento-test', h2, r3.entry)+ok(acceptHistory(null, h1, 'bento-test').ok, 'the first history a host sees is accepted')+ok(acceptHistory(h2, h3, 'bento-test').ok, 'a newer history that keeps every held entry is accepted')+ok(acceptHistory(h2, h2, 'bento-test').ok, 'the same history again is accepted')+const lacks = { ...h3, releases: h3.releases.filter((e) => e.version !== '1.0.0') }+ok(!acceptHistory(h2, lacks, 'bento-test').ok && /lacks 1\.0\.0/.test(acceptHistory(h2, lacks, 'bento-test').reason ?? ''), 'ROLLBACK refused: a history lacking an entry the host holds')+ok(!acceptHistory(h3, h2, 'bento-test').ok && /older/.test(acceptHistory(h3, h2, 'bento-test').reason ?? ''), 'ROLLBACK refused: a replayed older history (lower newest version)')+const changed = { ...h3, releases: h3.releases.map((e) => (e.version === '1.0.0' ? { ...e, sha256: 'c'.repeat(64) } : e)) }+ok(!acceptHistory(h3, changed, 'bento-test').ok, 'a history that changes a held entry is refused')+ok(!acceptHistory(null, h3, 'bento-other').ok, "another app's history is refused")+ok(!acceptHistory(null, { ...h3, releases: [h3.releases[1], h3.releases[0]] }, 'bento-test').ok, 'a history not newest-first is refused')++console.log('\na file matches ONE release on EVERY block, or is UNKNOWN (matchRelease)')+ok(matchRelease(h3, r1.saved)?.version === '1.0.0', 'a 1.0.0 file matches 1.0.0')+ok(matchRelease(h3, r2.saved)?.version === '1.1.0', '1.0.0 and 1.1.0 share a runtime; the loader tells them apart')+ok(matchRelease(h3, html({ loader: 'loadX()' })) === null, 'a known runtime with an unknown loader is UNKNOWN (a partial match)')+ok(matchRelease(h3, html({ remover: 'rmX()' })) === null, 'an unknown remover is UNKNOWN')+ok(matchRelease(h3, html({ css: 'CSSX' })) === null, 'an unknown stylesheet block is UNKNOWN')+ok(matchRelease(h3, html({ extra: `<${S}>evil()</${S}>` })) === null, 'an extra executable script is UNKNOWN')+ok(matchRelease(h3, html({ extra: `<${S} type="bento/deflate-b86" id="bento-rt">RT1</${S}>` })) === null, 'two bento-rt blocks are UNKNOWN (exactly one per id)')+ok(matchRelease(h3, html({ rt: 'RTX' })) === null, 'an unknown runtime is UNKNOWN')+const twin = { ...h3, releases: [{ ...r1.entry, version: '1.3.0' }, ...h3.releases] }+ok(matchRelease(twin, r1.saved) === null, 'two entries with identical blocks are ambiguous: UNKNOWN')++console.log('\nthe grammar (security, 2026-10-21): only Bento data types are inert; foreign markup is UNKNOWN')+{+ const genuine = r1.saved+ ok(matchRelease(h3, genuine)?.version === '1.0.0', 'control: the genuine file matches')+ const head = (extra: string) => genuine.replace('</head>', extra + '</head>')+ const body = (extra: string) => genuine.replace('</body>', extra + '</body>')+ const rows: Array<[string, string]> = [+ ['an external <script src=…>', head(`<${S} src="https://evil.example/x.js"></${S}>`)],+ ['a script of an unknown type', head(`<${S} type="text/x-template">x</${S}>`)],+ ['an inline type="module" script', head(`<${S} type="module">x</${S}>`)],+ ['type="Module" (another case)', head(`<${S} type="Module">x</${S}>`)],+ ['type="text/JavaScript" (a JS type, mixed case)', head(`<${S} type="text/JavaScript">x</${S}>`)],+ ['a data type in different case', genuine.replace('type="application/bento+json"', 'type="Application/Bento+JSON"')],+ ['an uppercase <SCRIPT>', head(`<SCRIPT>x</SCRIPT>`)],+ ['a NUL inside the type attribute name', genuine.replace('type="bento/deflate-b86" id="bento-rt"', 'ty\u0000pe="bento/deflate-b86" id="bento-rt"')],+ ['an <iframe>', body('<iframe src="https://evil.example/"></iframe>')],+ ['an <object>', body('<object data="x"></object>')],+ ['an <embed>', body('<embed src="x">')],+ ['a <base>', head('<base href="https://evil.example/">')],+ ['a <meta> refresh', head('<meta http-equiv="refresh" content="0;url=https://evil.example/">')],+ ['a <meta> CSP', head(`<meta http-equiv='Content-Security-Policy' content="script-src *">`)],+ ['an on*= attribute', genuine.replace('<body>', '<body onload="evil()">')],+ ['a comment holding a <script>, before the loader', head(`<!-- <${S}>evil()</${S}> -->`)],+ ['a <script> inside <textarea>', body(`<textarea><${S}>x</${S}></textarea>`)],+ ['a <script> inside <title>', head(`<title><${S}>x</${S}></title>`)],+ ['a <script> inside <style>', head(`<style>/* <${S}>x</${S}> */</style>`)],+ // the DOCUMENT block isn't hashed (it holds the user's content), so only+ // the "<" rule can catch these: Bento always writes it <-escaped+ ['the document block holding a raw "<"', genuine.replace('id="bento-doc">{}<', 'id="bento-doc">{"x":"<b>"}<')],+ ['"<!--<script" inside the document block', genuine.replace('id="bento-doc">{}<', `id="bento-doc">{"x":"<!--<${S}>"}<`)],+ ]+ for (const [name, html] of rows) ok(matchRelease(h3, html) === null, `UNKNOWN: ${name}`)+ ok(matchRelease(h3, genuine.replace(/type="bento\/deflate-b86"/g, "type='bento/deflate-b86'"))?.version === '1.0.0', 'single-quoted attributes parse the same (still matches)')+ ok(matchRelease(h3, genuine.replace(/type="bento\/deflate-b86"/g, 'type=bento/deflate-b86'))?.version === '1.0.0', 'unquoted attributes parse the same (still matches)')+ ok(matchRelease(h3, genuine.replace(`id="bento-rt">RT1</${S}>`, `id="bento-rt">RT1</${S} >`))?.version === '1.0.0', '"</script >" closes a block like "</script>"')+}++console.log('\nsign-history.mjs, end to end with a TEST key')+{+ const dir = mkdtempSync(join(tmpdir(), 'bento-history-'))+ const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' })+ const pub = publicKey.export({ format: 'jwk' })+ writeFileSync(join(dir, 'key.json'), JSON.stringify({ private: privateKey.export({ format: 'jwk' }), public: pub }))+ writeFileSync(join(dir, 'public.json'), JSON.stringify(pub))+ const script = join(dirname(fileURLToPath(import.meta.url)), 'sign-history.mjs')+ const shell = join(dir, 'shell.html'); writeFileSync(shell, html({ remover: null }))+ const pins = join(dir, 'pins.json'); writeFileSync(pins, JSON.stringify(r1.entry.pins))+ const sign = (version: string, held: string | null, out: string) => {+ try {+ execFileSync('node', [script, '--app', 'bento-test', '--version', version, '--shell', shell, '--pins', pins,+ ...(held ? ['--held', held] : []), '--key', join(dir, 'key.json'), '--public', join(dir, 'public.json'), '--out', out], { stdio: 'pipe' })+ return true+ } catch { return false }+ }+ ok(sign('1.0.0', null, join(dir, 'h1.json')), 'the first history is signed')+ const first = verifyEnvelope(readFileSync(join(dir, 'h1.json'), 'utf8'), pub)+ ok(first.releases.length === 1 && first.releases[0].version === '1.0.0', 'and verifies, with the release in it')+ ok(sign('1.1.0', join(dir, 'h1.json'), join(dir, 'h2.json')), 'a newer release is appended to the held history')+ ok(verifyEnvelope(readFileSync(join(dir, 'h2.json'), 'utf8'), pub).releases.length === 2, 'and the new history holds both')+ ok(!sign('1.0.5', join(dir, 'h2.json'), join(dir, 'bad.json')), 'an older release is refused by the CLI')+ const tampered = JSON.parse(readFileSync(join(dir, 'h2.json'), 'utf8'))+ tampered.payload = tampered.payload.replace('1.0.0', '0.9.0')+ writeFileSync(join(dir, 'tampered.json'), JSON.stringify(tampered))+ ok(!sign('1.2.0', join(dir, 'tampered.json'), join(dir, 'bad2.json')), 'a held history with a broken signature is refused, never re-signed')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)