Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

Release: publish a SIGNED pack index, not pack hashes in the manifest

nyblnet3fc7d425cc47
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1f0434b8..5a00623e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -51,6 +51,15 @@ jobs:
# packed.ts would silently ship yesterday's translations.
run: node scripts/build-i18n.mjs --check
+ - name: Language packs build and index cleanly
+ # Emits every pack and builds the index payload WITHOUT signing (--dry
+ # writes nothing and needs no key — signing stays local, see the header).
+ # Catches a malformed pack catalog (missing label, duplicate language,
+ # wrong app) here rather than mid-release.
+ run: |
+ node scripts/build-i18n.mjs --packs "$RUNNER_TEMP/packs"
+ node scripts/sign-packs.mjs "$RUNNER_TEMP/packs" --dry
+
- name: Typecheck
working-directory: slides
run: node_modules/.bin/tsc -b
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 1c7b816d..7a47a864 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -14,6 +14,30 @@ Decision. Why. Pointers.
---
+## 2026-07-26 — Language packs are published under a SIGNED INDEX, separate from the manifest
+
+Amends the "Signing and release" paragraph of `docs/i18n-packs.md`, which said
+the update manifest would gain a `packs` array. It does not.
+
+`release.mjs` emits the packs and signs **one index** over all of them at
+`releases/slides/packs.json` — the same `{payload, sig}` envelope, the same
+offline key, and literally the same signing code as the manifest (extracted to
+`scripts/sign-payload.mjs`). Each listing pins its pack's `sha256`; individual
+packs are not separately signed. Clients verify the index once, then hash each
+download against its signed hash.
+
+Why not inside the manifest: shipped files ignore a manifest that is not
+strictly newer than themselves (downgrade-replay protection), so pack hashes
+carried there could never be corrected **between** app releases — and a fixed
+translation is not a new app version. A separate index is re-issuable any day,
+and `manifest.json` keeps meaning exactly one thing: here is the app shell.
+Signed code and signed data stay two artifacts.
+
+Still one key, still local-only signing, and `publish-site.mjs` now gates the
+index the way it already gates the shell (indexed pack missing, hash drifted,
+or packs staged with no index = refuse to publish). Details and the exact
+payload shape: `docs/i18n-packs.md` §"Signing and release"; `scripts/sign-packs.mjs`.
+
## 2026-07-25 — i18n: a bundled core of 9 languages, everything else a signed pack
The 7 non-English catalogs cost **115,572 B** of the shell even after key-once
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index ce6efc31..0491f558 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -34,7 +34,8 @@ verify the manifest signature against the public key embedded in every shell.
shell and the manifest version — single source of truth).
2. Commit, tag: `git tag vX.Y.Z`.
3. `node scripts/release.mjs` — builds, signs, assembles `./site/`
- (CNAME, landing page, live demo, download, signed manifest).
+ (CNAME, landing page, live demo, download, signed manifest, language packs
+ + their signed index).
4. Publish `./site/` to the public site repo — one step:
```sh
@@ -77,10 +78,45 @@ verify the manifest signature against the public key embedded in every shell.
Check for updates → should offer the new version, and the downloaded copy
must boot with the document intact.
+## Language packs
+
+`release.mjs` also emits every non-core language pack
+(`scripts/build-i18n.mjs --packs`) into `site/releases/slides/packs/` and signs
+an INDEX over them at `site/releases/slides/packs.json`
+(`scripts/sign-packs.mjs`) — same envelope, same offline key and the same
+signing code as the manifest (`scripts/sign-payload.mjs`). The index pins each
+pack's sha256; shipped files verify the index signature once and then hash each
+downloaded pack against it. Design and payload shape: `docs/i18n-packs.md`.
+
+Both steps are no-ops until a pack catalog exists, so nothing changes for a
+release with no packs.
+
+Preview what would be signed, without the key and without writing anything:
+
+```sh
+node scripts/build-i18n.mjs --packs /tmp/packs
+node scripts/sign-packs.mjs /tmp/packs --dry # prints the exact payload
+```
+
+Re-publishing packs **without cutting an app release** is supported and is the
+reason the index is its own artifact (a corrected translation is not a new app
+version). Re-emit, re-sign the index, publish:
+
+```sh
+node scripts/sign-packs.mjs site/releases/slides/packs \
+ --out site/releases/slides/packs.json --version <app version>
+node scripts/publish-site.mjs "packs: fix the Korean plural forms"
+```
+
+`publish-site.mjs` refuses to push if any published pack does not match its
+signed hash, if an indexed pack is missing, or if packs are staged with no
+index at all — an unsigned pack must never reach the CDN.
+
## Rules
- Never edit files on `gh-pages` by hand — the manifest signature covers the
shell's exact bytes; any drift bricks the update check (integrity refusal).
+ The same holds for `packs.json` and everything under `packs/`.
- Version only goes up. Shipped files refuse manifests that aren't strictly
newer than themselves (downgrade-replay protection), so a "rollback" is a
new higher version that reverts the code.
diff --git a/docs/i18n-packs.md b/docs/i18n-packs.md
index ac7b0810..c31852bc 100644
--- a/docs/i18n-packs.md
+++ b/docs/i18n-packs.md
@@ -101,13 +101,65 @@ Per-language maps, not the bundled positional-array shape: a pack is edited
and reviewed as one language, and positional arrays would couple every pack to
a column order.
-### Signing and release
+### Signing and release — the signed pack index
-Packs reuse the existing release machinery **exactly** — ECDSA P-256 over the
-sha256, verified against the `PUBLIC_KEY_JWK` already embedded in every shell
-(`PLATFORM.md` §6). The private key stays offline; `release.mjs` emits and
-signs packs beside the shell, and the manifest gains a `packs` array listing
-`{lang, version, sha256, url}`. No new trust root, no second key.
+Packs reuse the existing release machinery **exactly** — ECDSA P-256 /
+SHA-256, verified against the `PUBLIC_KEY_JWK` already embedded in every shell
+(`PLATFORM.md` §6). The private key stays offline and `release.mjs` runs
+locally. No new trust root, no second key.
+
+**The INDEX is signed; individual packs are not.** `release.mjs` emits the
+packs and then signs one index over all of them:
+
+```
+https://bento.page/releases/slides/
+ manifest.json signed — the app shell
+ packs.json signed — the pack index
+ packs/bento-slides-1.0.11-ko.pack.json the packs themselves
+```
+
+`packs.json` is the same envelope as the manifest, produced by the same code
+(`scripts/sign-payload.mjs`, shared by `sign-release.mjs` and `sign-packs.mjs`):
+
+```json
+{ "payload": "<the exact json string that was signed>", "sig": "<base64>" }
+```
+
+and the payload is
+
+```json
+{ "app": "bento-slides", "version": "1.0.11", "at": "<iso>",
+ "packs": [ { "lang": "ko", "label": "한국어", "version": "1.0.11",
+ "url": "packs/bento-slides-1.0.11-ko.pack.json",
+ "sha256": "<hex, lowercase>", "bytes": 60114 } ] }
+```
+
+`sig` is ECDSA P-256 / SHA-256 over `payload`'s **UTF-8 string bytes**, IEEE
+P1363 (raw r‖s), base64 — byte-identical in construction to the manifest, so
+the client verifies both with the same handful of lines.
+
+The client's job is therefore the same two-step the shell already performs for
+its own update: **verify the index signature once, then hash each downloaded
+pack against its signed `sha256`.** A pack that does not match its pinned hash
+is refused. `url` is relative to the channel unless absolute — so a dev
+channel (`localStorage 'bento-packs-url'`) serves its own packs rather than
+silently reaching back to bento.page.
+
+Two reasons this is a separate artifact from `manifest.json` rather than a
+`packs` array inside it:
+
+- **Packs publish on their own clock.** A corrected translation is not a new
+ app version — but shipped files ignore a manifest that is not strictly
+ *newer* than themselves (downgrade-replay protection), so a hash carried in
+ the manifest could never be corrected *between* releases. A separate index is
+ re-issuable any day.
+- **The manifest keeps meaning one thing:** here is the app shell. The update
+ channel ships signed *code*; the pack channel ships signed *data*.
+
+`publish-site.mjs` gates on this before pushing: every indexed pack must exist
+and match its signed hash, no published pack may be missing from the index, and
+staged packs without an index refuse to publish at all. Signed bytes are served
+bytes — for the index exactly as for the shell.
### Loading
@@ -184,8 +236,11 @@ second one.
- [x] Pack format + `build-i18n.mjs --packs` emitting them — #81
- [x] Kernel `addPack()` loading path — #81
- [x] Korean, the first pack (662/662) — #81
-- [x] `release.mjs` emits packs; their hashes ride in the **signed manifest
- payload** — no second key, no second signature
+- [x] `release.mjs` emits packs and publishes `packs.json`, a **signed index**
+ pinning each pack's sha256 — same envelope, same offline key, no second
+ trust root. Gated at publish time.
+- [ ] Client: verify the index signature + each pack's pinned hash
+ (`slides/src/packs.ts` — the shape it must expect is specified above)
- [ ] In-app "Add language…" (fetch → verify → splice, compressed)
- [ ] **Update carries packs forward**
- [ ] Shell smoke check covers a pack-carrying shell (note: `shell-gate.mjs`
diff --git a/scripts/publish-site.mjs b/scripts/publish-site.mjs
index 2665f3f3..5e1909ca 100755
--- a/scripts/publish-site.mjs
+++ b/scripts/publish-site.mjs
@@ -25,6 +25,7 @@ import { createHash } from 'node:crypto'
import { dirname, join, resolve } from 'node:path'
import { tmpdir } from 'node:os'
import { fileURLToPath } from 'node:url'
+import { gatePackIndex } from './sign-packs.mjs'
const root = dirname(dirname(fileURLToPath(import.meta.url)))
const site = join(root, 'site')
@@ -87,6 +88,28 @@ if (existsSync(shellFile)) {
console.log(`• shell-consistency gate: ${decks.length} example deck(s) embed the released shell ✓`)
}
+// ---- gate: the pack index MUST describe the packs being published ----------
+// Same principle as the shell: signed bytes are served bytes. The index pins
+// each pack's sha256, so a pack rebuilt after signing (or one dropped into the
+// directory by hand) would be rejected by every client with an integrity error
+// the user cannot act on. Catch it here instead.
+const packIndex = join(site, 'releases/slides/packs.json')
+const packsDir = join(site, 'releases/slides/packs')
+if (existsSync(packIndex)) {
+ if (!existsSync(packsDir)) die(`${packIndex.slice(site.length + 1)} exists but there are no packs beside it — re-run release.mjs`)
+ try {
+ gatePackIndex(packIndex, packsDir)
+ console.log('• pack-index gate: every published pack matches its signed hash ✓')
+ } catch (e) {
+ die(`${e.message}\n Re-sign with: node scripts/sign-packs.mjs ${packsDir} --out ${packIndex}`)
+ }
+} else if (existsSync(packsDir) && readdirSync(packsDir).some((f) => f.endsWith('.pack.json'))) {
+ // Unsigned packs on the CDN are worse than no packs: nothing would verify
+ // them, and a client that fell back to "just fetch it" would be trusting
+ // the host. Refuse rather than publish an unverifiable language.
+ die(`language packs are staged at ${packsDir.slice(site.length + 1)} but packs.json is MISSING — an unsigned pack must never be published.\n Fix: node scripts/sign-packs.mjs ${packsDir} --out ${packIndex}`)
+}
+
// ---- mirror site/ → dest (authoritative; never touches dest/.git) ----------
const rsyncFlags = ['-a', '--delete', '--exclude', '.git']
if (dry) rsyncFlags.push('-n', '-v', '--itemize-changes')
diff --git a/scripts/release.mjs b/scripts/release.mjs
index cfa14ee1..14406524 100644
--- a/scripts/release.mjs
+++ b/scripts/release.mjs
@@ -13,8 +13,9 @@
// slides/index.html live demo (the shell itself)
// releases/slides/Bento_Slides.bento.html the download
// releases/slides/manifest.json signed update manifest
-// releases/slides/packs/*.pack.json language packs (hashes signed
-// inside the manifest payload)
+// releases/slides/packs/*.pack.json language packs
+// releases/slides/packs.json signed pack index (pins each
+// pack's sha256)
//
// The bytes that get SIGNED are the bytes that get SERVED — everything is
// staged from one local build, so the manifest sha256 always matches the
@@ -58,23 +59,32 @@ cpSync(shellSrc, join(site, 'slides/index.html'))
// scripts/shell-gate.mjs (shared with CI, which runs it on every PR build).
gateShell(join(site, 'releases/slides/Bento_Slides.bento.html'))
-// Language packs: every non-core language, emitted from its catalog and
-// staged beside the shell. Their hashes go INTO the signed manifest payload
-// (docs/i18n-packs.md), so no separate signing step and no second key.
-const packsOut = join(site, 'releases/slides/packs')
-execFileSync('node', [join(root, 'scripts/build-i18n.mjs'), '--packs', packsOut], { stdio: 'inherit' })
+const key = opt('key', null)
// Sign the manifest against the staged bytes.
const signArgs = [
join(root, 'scripts/sign-release.mjs'),
join(site, 'releases/slides/Bento_Slides.bento.html'),
'--out', join(site, 'releases/slides/manifest.json'),
- '--packs', packsOut,
]
-const key = opt('key', null)
if (key) signArgs.push('--key', key)
execFileSync('node', signArgs, { stdio: 'inherit' })
+// Language packs: every non-core language, emitted from its catalog, staged
+// beside the shell and listed in packs.json — a SIGNED index (same envelope,
+// same offline key as the manifest) that pins each pack's sha256. The index is
+// what "Add language…" reads; nothing is trusted without it.
+// Both steps are no-ops until a pack catalog exists (docs/i18n-packs.md).
+const packsOut = join(site, 'releases/slides/packs')
+execFileSync('node', [join(root, 'scripts/build-i18n.mjs'), '--packs', packsOut], { stdio: 'inherit' })
+const packArgs = [
+ join(root, 'scripts/sign-packs.mjs'), packsOut,
+ '--out', join(site, 'releases/slides/packs.json'),
+ '--version', version,
+]
+if (key) packArgs.push('--key', key)
+execFileSync('node', packArgs, { stdio: 'inherit' })
+
writeFileSync(join(site, 'CNAME'), 'bento.page\n')
// The site is fully pre-built static — disable Jekyll so every file is served
// verbatim. Without this, GitHub Pages' Jekyll processes .md files that carry
diff --git a/scripts/sign-packs.mjs b/scripts/sign-packs.mjs
new file mode 100644
index 00000000..0ad0b10d
--- /dev/null
+++ b/scripts/sign-packs.mjs
@@ -0,0 +1,167 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Build and sign the LANGUAGE PACK INDEX — releases/slides/packs.json.
+//
+// node scripts/sign-packs.mjs <packs-dir> [--out packs.json]
+// [--version 1.0.11] [--url-base packs] [--key ~/.bento/release-key.json]
+// [--dry]
+//
+// The index is `{ payload: "<json string>", sig: "<base64>" }` — the SAME
+// envelope, the same offline key and the same signing code as the update
+// manifest (scripts/sign-payload.mjs). The shell already verifies that shape.
+//
+// WHY THE INDEX IS SIGNED AND THE PACKS ARE NOT. A pack is a bag of UI
+// strings, so a forged one is not code execution — but it is a lie shown in
+// the user's own interface ("Anyone can edit this deck" where the app said the
+// opposite), which is quite bad enough. Signing each pack separately would
+// mean N signatures to verify, N chances to get an edge case wrong, and a
+// forged pack could still be swapped in by omitting it from an unsigned list.
+// So: ONE signature over the whole index, and every listing PINS its pack's
+// sha256. The client verifies the index once, then hashes each download
+// against its signed hash — exactly the two-step the shell already performs
+// for its own update (manifest signature, then shell hash). Adding a pack, or
+// changing one byte of one, changes the index and needs the offline key.
+//
+// WHY A SEPARATE ARTIFACT FROM manifest.json. Packs are published on their own
+// clock: a corrected translation is not a new app version, and shipped files
+// refuse a manifest that is not strictly NEWER than themselves (downgrade-
+// replay protection). Pack hashes carried in the manifest could therefore
+// never be updated BETWEEN releases — the correction would be invisible to
+// every file already on the current version. A separate signed index is
+// re-issuable at any time, and the manifest keeps meaning exactly one thing:
+// "here is the app shell".
+//
+// The private key never leaves the maintainer's machine; there is no CI
+// signing step (docs/RELEASING.md).
+
+import { createHash } from 'node:crypto'
+import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
+import { basename, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { defaultKeyPath, envelopeJson, haveKey, releasePublicKey, signPayload, verifyEnvelope } from './sign-payload.mjs'
+
+/** The app id in the SIGNED INDEX — same value the update manifest uses. */
+const INDEX_APP = 'bento-slides'
+/** The app id inside a PACK file, as build-i18n.mjs writes it. */
+const PACK_APP = 'slides'
+
+/**
+ * Read a directory of *.pack.json and describe each one for the index.
+ * Hex sha256 is lowercase — the client compares it lowercased, and a mixed
+ * case index would fail with a message no user could act on.
+ */
+export function listPacks(packsDir, { urlBase = 'packs' } = {}) {
+ const files = readdirSync(packsDir).filter((f) => f.endsWith('.pack.json')).sort()
+ const packs = []
+ const seen = new Map()
+ for (const name of files) {
+ const bytes = readFileSync(join(packsDir, name))
+ let pack
+ try {
+ pack = JSON.parse(bytes.toString('utf8'))
+ } catch {
+ throw new Error(`${name} is not valid JSON — refusing to index it`)
+ }
+ if (pack.app && pack.app !== PACK_APP) throw new Error(`${name} is for app "${pack.app}", not "${PACK_APP}"`)
+ if (!pack.lang || !pack.label) throw new Error(`${name} is missing lang and/or label`)
+ if (!pack.strings || typeof pack.strings !== 'object') throw new Error(`${name} has no strings`)
+ if (seen.has(pack.lang)) throw new Error(`two packs claim "${pack.lang}": ${seen.get(pack.lang)} and ${name}`)
+ seen.set(pack.lang, name)
+ packs.push({
+ lang: pack.lang,
+ label: pack.label,
+ version: pack.version,
+ // RELATIVE to the channel by default. The client resolves a relative url
+ // against channel(), so a local channel (localStorage 'bento-packs-url')
+ // serves its OWN packs instead of silently reaching back to bento.page —
+ // and the whole tree can be mirrored to another host unchanged. Pass
+ // --url-base <absolute> if a release ever needs absolute urls; the
+ // signed sha256 is what pins the bytes either way.
+ url: `${urlBase.replace(/\/$/, '')}/${name}`,
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ bytes: bytes.length,
+ strings: Object.keys(pack.strings).length,
+ })
+ }
+ return packs.sort((a, b) => a.lang.localeCompare(b.lang))
+}
+
+/** The exact string that gets signed. Deterministic given the same packs. */
+export const indexPayload = (packs, version) =>
+ JSON.stringify({
+ app: INDEX_APP,
+ version,
+ packs: packs.map(({ strings, ...listing }) => listing), // `strings` is a build stat, not a contract
+ at: new Date().toISOString(),
+ })
+
+/**
+ * GATE — an index must describe the packs actually sitting beside it.
+ * Called by publish-site.mjs before anything is pushed: signed bytes are
+ * served bytes, and that has to hold for the index too, not just the shell.
+ */
+export function gatePackIndex(indexPath, packsDir, publicJwk = releasePublicKey()) {
+ const payload = verifyEnvelope(readFileSync(indexPath, 'utf8'), publicJwk)
+ if (payload.app !== INDEX_APP) throw new Error(`GATE: pack index is for "${payload.app}"`)
+ if (!Array.isArray(payload.packs)) throw new Error('GATE: pack index has no packs array')
+ for (const listing of payload.packs) {
+ const file = join(packsDir, basename(listing.url))
+ if (!existsSync(file)) throw new Error(`GATE: ${listing.lang} is indexed but ${basename(listing.url)} is not published`)
+ const actual = createHash('sha256').update(readFileSync(file)).digest('hex')
+ if (actual !== listing.sha256) throw new Error(`GATE: ${basename(listing.url)} does not match its SIGNED hash — re-sign before publishing`)
+ }
+ const indexed = new Set(payload.packs.map((p) => basename(p.url)))
+ const orphans = readdirSync(packsDir).filter((f) => f.endsWith('.pack.json') && !indexed.has(f))
+ if (orphans.length) throw new Error(`GATE: pack file(s) published but NOT in the signed index: ${orphans.join(', ')}`)
+ console.log(`pack index gate: ${payload.packs.length} pack(s) signed and matching ✓`)
+ return payload
+}
+
+// ---- CLI -------------------------------------------------------------------
+if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
+ const args = process.argv.slice(2)
+ const opt = (name, fallback) => {
+ const i = args.indexOf(`--${name}`)
+ return i >= 0 && args[i + 1] ? args[i + 1] : fallback
+ }
+ const packsDir = args.find((a) => !a.startsWith('--'))
+ if (!packsDir) {
+ console.error('usage: node scripts/sign-packs.mjs <packs-dir> [--out packs.json] [--version V] [--url-base B] [--key K] [--dry]')
+ process.exit(2)
+ }
+ const dry = args.includes('--dry')
+ const outPath = opt('out', join(packsDir, '..', 'packs.json'))
+ const keyPath = opt('key', defaultKeyPath())
+
+ if (!existsSync(packsDir)) {
+ // Not an error: a release before any pack language exists simply has no
+ // index, and the client treats a missing index as "nothing on offer".
+ console.log(`no packs at ${packsDir} — no index written`)
+ process.exit(0)
+ }
+
+ const packs = listPacks(packsDir, { urlBase: opt('url-base', 'packs') })
+ if (!packs.length) {
+ console.log(`no *.pack.json in ${packsDir} — no index written`)
+ process.exit(0)
+ }
+ const version = opt('version', packs[0].version ?? '0.0.0')
+ const payload = indexPayload(packs, version)
+
+ const total = packs.reduce((n, p) => n + p.bytes, 0)
+ console.log(`${dry ? 'DRY RUN — ' : ''}pack index v${version}: ${packs.length} pack(s), ${(total / 1024).toFixed(0)} KB`)
+ for (const p of packs)
+ console.log(` ${p.lang.padEnd(8)} ${p.label.padEnd(12)} ${String(p.strings).padStart(4)} strings ${(p.bytes / 1024).toFixed(0).padStart(3)} KB ${p.sha256.slice(0, 16)}… ${p.url}`)
+
+ if (dry) {
+ console.log(`\npayload (${Buffer.byteLength(payload)} B, this is the exact string that gets signed):\n${payload}`)
+ console.log(haveKey(keyPath)
+ ? `\nwould sign with the offline key and write ${outPath} — nothing written (--dry)`
+ : `\nno signing key at ${keyPath} — nothing written (--dry). Releases are signed on the maintainer's machine only.`)
+ process.exit(0)
+ }
+
+ writeFileSync(outPath, envelopeJson(signPayload(payload, keyPath)))
+ console.log(` out ${outPath}`)
+}
diff --git a/scripts/sign-payload.mjs b/scripts/sign-payload.mjs
new file mode 100644
index 00000000..20a81648
--- /dev/null
+++ b/scripts/sign-payload.mjs
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The ONE signing primitive for Bento's release channel.
+//
+// Two artifacts are signed, both with the same offline key:
+//
+// releases/slides/manifest.json the app update manifest (sign-release.mjs)
+// releases/slides/packs.json the language-pack index (sign-packs.mjs)
+//
+// Both are `{ payload: "<json string>", sig: "<base64>" }`, where sig is
+// ECDSA P-256 / SHA-256 over the payload STRING's UTF-8 bytes in IEEE P1363
+// (raw r||s) form — the shape `crypto.subtle.verify` takes directly, so the
+// shipped shell verifies either artifact with the same few lines and the same
+// PUBLIC_KEY_JWK (kernel/src/update.ts).
+//
+// This module exists so those two are literally the same code rather than two
+// copies of it. A signature scheme that drifts between artifacts is a class of
+// bug nobody notices until shipped files start refusing valid releases — and
+// shipped files are frozen code, so the fix would arrive too late.
+//
+// NOTHING here reads, writes, prints or copies the private key beyond handing
+// it to node:crypto. Releases are signed locally by the maintainer; the key
+// never enters the repo or CI (docs/RELEASING.md).
+
+import { createPrivateKey, createPublicKey, sign, verify } from 'node:crypto'
+import { existsSync, readFileSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const root = dirname(dirname(fileURLToPath(import.meta.url)))
+
+/** Where the maintainer's offline signing key lives. Never in the repo. */
+export const defaultKeyPath = () => join(homedir(), '.bento', 'release-key.json')
+
+/** Is a signing key available on this machine? (For dry runs — never reads it.) */
+export const haveKey = (keyPath = defaultKeyPath()) => existsSync(keyPath)
+
+/**
+ * Sign a payload string, returning the envelope to write.
+ *
+ * Self-verifies against the key file's own public half before returning, so a
+ * corrupt key or a node/WebCrypto encoding mismatch fails HERE, on the
+ * maintainer's machine, instead of at every shipped file in the world.
+ */
+export function signPayload(payload, keyPath = defaultKeyPath()) {
+ if (typeof payload !== 'string') throw new Error('signPayload: payload must be the exact string to sign')
+ const keyFile = JSON.parse(readFileSync(keyPath, 'utf8'))
+ const bytes = Buffer.from(payload, 'utf8')
+ const sig = sign('sha256', bytes, {
+ key: createPrivateKey({ key: keyFile.private, format: 'jwk' }),
+ dsaEncoding: 'ieee-p1363', // WebCrypto's raw r||s format
+ })
+ const ok = verify('sha256', bytes, {
+ key: createPublicKey({ key: keyFile.public, format: 'jwk' }),
+ dsaEncoding: 'ieee-p1363',
+ }, sig)
+ if (!ok) throw new Error('self-verification failed — refusing to emit a signature this machine cannot verify')
+ return { payload, sig: sig.toString('base64') }
+}
+
+/** How every signed artifact is serialised. Same bytes, both artifacts. */
+export const envelopeJson = (envelope) => JSON.stringify(envelope, null, 2) + '\n'
+
+/**
+ * The public key EVERY shipped shell verifies against — read out of
+ * kernel/src/update.ts rather than copied here, so a gate that says "this
+ * verifies" is talking about the key the files in the wild actually hold.
+ */
+export function releasePublicKey() {
+ const src = readFileSync(join(root, 'kernel/src/update.ts'), 'utf8')
+ const m = src.match(/const PUBLIC_KEY_JWK = \{([\s\S]*?)\} as const/)
+ if (!m) throw new Error('could not find PUBLIC_KEY_JWK in kernel/src/update.ts')
+ const jwk = {}
+ for (const [, k, v] of m[1].matchAll(/(\w+):\s*'([^']*)'/g)) jwk[k] = v
+ if (jwk.kty !== 'EC' || !jwk.x || !jwk.y) throw new Error('PUBLIC_KEY_JWK in kernel/src/update.ts is not a P-256 public key')
+ return jwk
+}
+
+/**
+ * Verify an envelope against a public JWK — the same check the shell performs,
+ * available to the publish gate so a broken artifact is caught before it is
+ * served rather than by a user's failed update.
+ */
+export function verifyEnvelope(raw, publicJwk) {
+ const { payload, sig } = JSON.parse(raw)
+ if (typeof payload !== 'string' || typeof sig !== 'string') throw new Error('envelope is malformed')
+ const ok = verify('sha256', Buffer.from(payload, 'utf8'), {
+ key: createPublicKey({ key: publicJwk, format: 'jwk' }),
+ dsaEncoding: 'ieee-p1363',
+ }, Buffer.from(sig, 'base64'))
+ if (!ok) throw new Error('signature is INVALID')
+ return JSON.parse(payload)
+}
diff --git a/scripts/sign-release.mjs b/scripts/sign-release.mjs
index 6fc52226..6a103ed2 100644
--- a/scripts/sign-release.mjs
+++ b/scripts/sign-release.mjs
@@ -7,7 +7,7 @@
// node scripts/sign-release.mjs slides/dist-single/Bento_Slides.bento.html \
// [--url https://bento.page/releases/slides/Bento_Slides.bento.html] \
// [--version 0.2.0] [--notes "What changed"] [--key ~/.bento/release-key.json] \
-// [--out manifest.json] [--packs <dir>] [--packs-url <base>]
+// [--out manifest.json]
//
// The manifest is { payload: "<json string>", sig: "<base64>" } — the
// signature covers the exact payload string bytes (no canonicalization
@@ -15,12 +15,18 @@
// it with WebCrypto. The payload carries the shell's sha256, so the shipped
// app verifies BOTH the manifest signature and the downloaded shell hash.
// Version defaults to slides/package.json — keep them in lockstep.
+//
+// LANGUAGE PACKS are NOT listed here. They are published on their own clock
+// (a corrected translation is not a new app version, and shipped files ignore
+// a manifest that isn't strictly newer than themselves — so a hash carried
+// here could never be corrected between releases). They get their own signed
+// index, same envelope and same key: scripts/sign-packs.mjs.
-import { createHash, createPrivateKey, createPublicKey, sign, verify } from 'node:crypto'
-import { readFileSync, readdirSync, writeFileSync } from 'node:fs'
-import { homedir } from 'node:os'
+import { createHash } from 'node:crypto'
+import { readFileSync, writeFileSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
+import { defaultKeyPath, envelopeJson, signPayload } from './sign-payload.mjs'
const root = dirname(dirname(fileURLToPath(import.meta.url)))
@@ -38,70 +44,34 @@ const opt = (name, fallback) => {
const version = opt('version', JSON.parse(readFileSync(join(root, 'slides/package.json'), 'utf8')).version)
const url = opt('url', 'https://bento.page/releases/slides/Bento_Slides.bento.html')
const notes = opt('notes', '')
-const keyPath = opt('key', join(homedir(), '.bento', 'release-key.json'))
+const keyPath = opt('key', defaultKeyPath())
const outPath = opt('out', join(dirname(shellPath), 'manifest.json'))
const shell = readFileSync(shellPath)
const sha256 = createHash('sha256').update(shell).digest('hex')
-/**
- * Language packs ride INSIDE the signed payload (docs/i18n-packs.md).
- *
- * No second key and no second signature: the manifest signature covers the
- * whole payload string, so listing each pack's sha256 here means the hashes
- * are signed too. A client verifies the manifest once, then checks a
- * downloaded pack against its signed hash — exactly the two-step the shell
- * itself already goes through. Adding a separate pack-signing path would be
- * a new trust root to get wrong for no gain.
- */
-const packsDir = opt('packs', null)
-const packs = []
-if (packsDir) {
- const baseUrl = opt('packs-url', url.replace(/\/[^/]*$/, '/packs'))
- for (const name of readdirSync(packsDir).filter((f) => f.endsWith('.pack.json')).sort()) {
- const bytes = readFileSync(join(packsDir, name))
- const meta = JSON.parse(bytes.toString('utf8'))
- packs.push({
- lang: meta.lang,
- label: meta.label,
- version: meta.version,
- bytes: bytes.length,
- sha256: createHash('sha256').update(bytes).digest('hex'),
- url: `${baseUrl}/${name}`,
- })
- }
-}
-
const payload = JSON.stringify({
app: 'bento-slides',
version,
sha256,
url,
...(notes ? { notes } : {}),
- ...(packs.length ? { packs } : {}),
at: new Date().toISOString(),
})
-const keyFile = JSON.parse(readFileSync(keyPath, 'utf8'))
-const privateKey = createPrivateKey({ key: keyFile.private, format: 'jwk' })
-const sig = sign('sha256', Buffer.from(payload, 'utf8'), {
- key: privateKey,
- dsaEncoding: 'ieee-p1363', // WebCrypto's raw r||s format
-})
-
-// Self-check against the public half before writing anything.
-const publicKey = createPublicKey({ key: keyFile.public, format: 'jwk' })
-if (!verify('sha256', Buffer.from(payload, 'utf8'), { key: publicKey, dsaEncoding: 'ieee-p1363' }, sig)) {
- console.error('Self-verification failed — manifest NOT written.')
+// Signing (and its self-check against the public half) lives in
+// scripts/sign-payload.mjs — shared verbatim with the pack index, so the two
+// signed artifacts can never drift apart in how they are constructed.
+let envelope
+try {
+ envelope = signPayload(payload, keyPath)
+} catch (err) {
+ console.error(`Signing failed — manifest NOT written: ${err.message}`)
process.exit(1)
}
-writeFileSync(outPath, JSON.stringify({ payload, sig: sig.toString('base64') }, null, 2) + '\n')
+writeFileSync(outPath, envelopeJson(envelope))
console.log(`Signed release v${version}`)
console.log(` shell ${shellPath} (${(shell.length / 1024).toFixed(0)} KB, sha256 ${sha256.slice(0, 16)}…)`)
console.log(` url ${url}`)
-if (packs.length) {
- const total = packs.reduce((n, p) => n + p.bytes, 0)
- console.log(` packs ${packs.length} (${packs.map((p) => p.lang).join(', ')}) — ${(total / 1024).toFixed(0)} KB, hashes signed`)
-}
console.log(` out ${outPath}`)