Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

Verify language packs before trusting them

nyblnetab3cace23b19
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1f0434b8..6e5a55c2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -84,6 +84,12 @@ jobs:
- name: Splice conformance gate (spaces)
run: node scripts/shell-gate.mjs spaces/dist-single/Bento_Spaces.bento.html
+ - 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.
+ # Tampered pack, tampered index, unsigned index — each must be refused.
+ run: node scripts/test-packs.ts
+
- name: CRDT convergence rig
# 40 seeds locally; deeper on CI where the seconds are free.
run: SEEDS=300 node scripts/test-sync.ts
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 1c7b816d..161e1571 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -14,6 +14,35 @@ Decision. Why. Pointers.
---
+## 2026-07-26 — Side-loaded artifacts: sign the index, pin the bytes, fail closed
+
+Language packs are fetched over the network, so they get the **same two-step
+the app shell's own update already gets**: an envelope signed with the release
+key (`{payload, sig}`, ECDSA P-256 / SHA-256) whose payload pins each
+artifact's `sha256`, and a download that is accepted only if its bytes hash to
+that pin. Signature over the pin, pin over the bytes. **No second key and no
+second trust root** — `PUBLIC_KEY_JWK` in `kernel/src/update.ts` is it.
+
+The mechanism lives in the kernel (`verifySigned`, `fetchPinned`) because it is
+the same for anything side-loaded; the *policy* stays in the app
+(`slides/src/packs.ts`). Keep that boundary: the kernel helpers verify BYTES,
+they do not decide what is safe to use. Packs are DATA with a bounded failure
+mode (wrong words on screen), which is why a pack that fails a refresh is kept
+at its existing version rather than dropped. Anything side-loaded that ever
+carries CODE needs stricter policy — pinned at install, never auto-refreshed —
+and must not inherit the pack rules by reusing the same fetch.
+
+**Fail closed, no legacy path.** An unsigned or unpinned index yields no
+listings at all. Nothing is published yet, so there is no permissive fallback
+to keep — and one added later would mean whoever answers for the channel picks
+the strings in the UI.
+
+**A pack already inside a file is NOT re-verified** (`readPacksFromShell`). It
+was verified at the door, and once spliced it carries exactly the trust the
+document does — anyone who can rewrite that block can rewrite the checking
+code too. Re-verifying would need the network at boot, which breaks offline
+use. Proof rig: `node scripts/test-packs.ts` (throwaway key, real crypto).
+
## 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/i18n-packs.md b/docs/i18n-packs.md
index 40a2b0f2..68b2c9b4 100644
--- a/docs/i18n-packs.md
+++ b/docs/i18n-packs.md
@@ -109,6 +109,51 @@ sha256, verified against the `PUBLIC_KEY_JWK` already embedded in every shell
signs packs beside the shell, and the manifest gains a `packs` array listing
`{lang, version, sha256, url}`. No new trust root, no second key.
+### What the client checks (implemented)
+
+The INDEX is signed; individual packs are not separately signed. The index is
+a signed envelope — `{payload: "<json string>", sig: "<base64>"}`, the exact
+shape `sign-release.mjs` already emits for the update manifest — and every
+listing in it pins its pack's `sha256`. So:
+
+```
+embedded release key -> signs the index
+index -> pins each pack's sha256
+pinned sha256 -> the bytes we accept
+```
+
+You cannot substitute a pack without breaking its hash, and you cannot fix the
+hash without breaking the signature. Two kernel helpers do it, and nothing
+else in the codebase does release-channel crypto:
+
+- `verifySigned(raw, what?)` — envelope + signature, returns the payload.
+- `fetchPinned(url, sha256)` — fetch, hash, compare; `null` on any mismatch.
+
+They verify BYTES. They do not decide what is safe to use — that policy is the
+caller's, and packs are DATA (see the decision log entry, 2026-07-26).
+
+`slides/src/packs.ts` composes them and **fails closed**: an unsigned index, a
+listing with no pin, or bytes that don't match yield nothing to add and a
+`'unverified'` error in the UI. There is no permissive fallback for an
+unsigned index — nothing is published yet, so there is nothing to be
+compatible with. The index payload may be a listing array or an object with a
+`packs` array, which is the manifest's own shape, so one signed file can serve
+as both.
+
+Two things deliberately NOT checked:
+
+- **Packs already inside a file** (`readPacksFromShell`). Verified at the
+ door; once spliced, a pack carries the trust the document does, and
+ re-verifying would require the network at boot — the opposite of the
+ product's promise.
+- **A refresh that fails.** `refreshPacksForVersion` keeps the pack the file
+ already holds rather than dropping it. The unverified bytes are refused; the
+ previously verified ones stay. Degraded beats absent.
+
+Rig: `node scripts/test-packs.ts` — tampered pack, tampered index, unsigned
+index, missing pin, and the good path, against real WebCrypto with a
+throwaway key standing in for the release key.
+
### Loading
`registerI18n` already accepts a packed table (kernel). Pack loading adds a
diff --git a/kernel/src/update.ts b/kernel/src/update.ts
index 2eb77483..02e62831 100644
--- a/kernel/src/update.ts
+++ b/kernel/src/update.ts
@@ -107,18 +107,33 @@ export function compareVersions(a: string, b: string): number {
}
/**
- * Verify the manifest signature and return its payload. The signature covers
- * the payload's exact string bytes — no JSON canonicalization involved.
+ * Verify a SIGNED ENVELOPE and return its parsed payload.
+ *
+ * The envelope is `{ payload: "<json string>", sig: "<base64>" }` and the
+ * signature (ECDSA P-256 / SHA-256, made offline by scripts/sign-release.mjs)
+ * covers the payload's exact UTF-8 bytes — no JSON canonicalization involved,
+ * which is why the payload travels as a string rather than as an object.
+ *
+ * This is the ONLY place in the kernel that does release-channel crypto.
+ * Anything else the channel serves — the release manifest, the language-pack
+ * index (slides/src/packs.ts) — verifies through here against the SAME
+ * embedded key, then applies its own shape checks to the payload. One trust
+ * root, one code path: a second implementation is a second thing to get
+ * wrong, and a signature check that is subtly wrong looks exactly like one
+ * that is right.
+ *
+ * Throws on anything short of a good signature. `what` only names the thing
+ * in those messages.
*/
-async function verifyManifest(raw: string): Promise<ReleaseInfo> {
+export async function verifySigned(raw: string, what = 'signed file'): Promise<unknown> {
let payload: string, sig: string
try {
;({ payload, sig } = JSON.parse(raw))
} catch {
- throw new Error('the release manifest is not valid JSON')
+ throw new Error(`the ${what} is not valid JSON`)
}
if (typeof payload !== 'string' || typeof sig !== 'string')
- throw new Error('the release manifest is malformed')
+ throw new Error(`the ${what} is malformed`)
const key = await crypto.subtle.importKey(
'jwk', PUBLIC_KEY_JWK as JsonWebKey,
@@ -128,9 +143,58 @@ async function verifyManifest(raw: string): Promise<ReleaseInfo> {
{ name: 'ECDSA', hash: 'SHA-256' }, key,
b64ToBytes(sig), new TextEncoder().encode(payload),
)
- if (!ok) throw new Error('the release signature is INVALID — refusing this update')
+ if (!ok) throw new Error(`the ${what} signature is INVALID — refusing it`)
+
+ try {
+ return JSON.parse(payload)
+ } catch {
+ throw new Error(`the ${what} payload is not valid JSON`)
+ }
+}
- const info = JSON.parse(payload)
+/** Lowercase hex sha256 of some bytes — the digest form every pin uses. */
+const sha256Hex = async (bytes: BufferSource): Promise<string> =>
+ hex(await crypto.subtle.digest('SHA-256', bytes))
+
+/**
+ * Fetch an artifact and hand it back ONLY if its bytes hash to `sha256`.
+ * Returns null on anything else: unreachable, non-200, malformed pin, or a
+ * digest that doesn't match. Fail closed — the caller decides what a refusal
+ * means, but it never gets unverified bytes to decide with.
+ *
+ * The pinned digest must itself come from something signed (a manifest, a
+ * signed index) — verifySigned above. Signature over the pin, pin over the
+ * bytes: that chain is what makes a plain https GET from a CDN trustworthy,
+ * and it is the same two steps the app shell's own update goes through.
+ *
+ * SCOPE, deliberately: these two helpers verify BYTES. They do not decide
+ * what those bytes are, or what is safe to do with them — that is the
+ * caller's policy and it is not one-size-fits-all. Language packs are DATA
+ * with a bounded failure mode (wrong words on screen), so packs.ts can keep a
+ * stale pack when a refresh fails. Anything side-loaded that carries CODE
+ * would need much stricter policy — pinned at install, never auto-refreshed —
+ * and must not inherit the pack rules by accident just because it reuses this
+ * fetch.
+ */
+export async function fetchPinned(url: string, sha256: string): Promise<ArrayBuffer | null> {
+ if (!/^[0-9a-f]{64}$/i.test(sha256 ?? '')) return null
+ let bytes: ArrayBuffer
+ try {
+ const res = await fetch(url, { cache: 'no-store' })
+ if (!res.ok) return null
+ bytes = await res.arrayBuffer()
+ } catch {
+ return null
+ }
+ return (await sha256Hex(bytes)) === sha256.toLowerCase() ? bytes : null
+}
+
+/**
+ * Verify the manifest signature and return its payload: the signature check
+ * above, plus the shape checks that make a payload a release.
+ */
+async function verifyManifest(raw: string): Promise<ReleaseInfo> {
+ const info = (await verifySigned(raw, 'release manifest')) as any
if (
info?.app !== appConfig().appId ||
typeof info.version !== 'string' ||
@@ -179,7 +243,9 @@ export async function buildUpdatedFile(release: ReleaseInfo, doc: KernelDoc): Pr
const res = await fetch(release.url, { cache: 'no-store' })
if (!res.ok) throw new Error(`downloading the update failed (${res.status})`)
const bytes = await res.arrayBuffer()
- const digest = hex(await crypto.subtle.digest('SHA-256', bytes))
+ // Same pin as fetchPinned, spelled out here because THIS path distinguishes
+ // "the download failed" from "the download was tampered with" for the user.
+ const digest = await sha256Hex(bytes)
if (digest !== release.sha256.toLowerCase())
throw new Error('the downloaded update failed its integrity check — refusing it')
diff --git a/scripts/test-packs.ts b/scripts/test-packs.ts
new file mode 100644
index 00000000..a4a1eacf
--- /dev/null
+++ b/scripts/test-packs.ts
@@ -0,0 +1,225 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Language-pack verification rig.
+//
+// node scripts/test-packs.ts (Node ≥ 23.6 strips types natively)
+//
+// WHAT THIS PROVES. Packs are fetched from the network, so the only thing
+// standing between a hostile (or merely broken) release channel and the
+// strings in someone's UI is the chain in slides/src/packs.ts:
+//
+// embedded release key -> signs the index
+// index -> pins each pack's sha256
+// pinned sha256 -> the bytes we accept
+//
+// Break any link and the pack must be REFUSED, not used. Each case below
+// breaks exactly one link and asserts the refusal, plus a good-path case so
+// the suite cannot pass by refusing everything.
+//
+// THE KEY. Verification runs against the real PUBLIC_KEY_JWK baked into
+// kernel/src/update.ts, whose private half lives offline with the maintainer
+// and is never available here (nor should it be). So the harness swaps the
+// TRUST ROOT for a throwaway keypair generated in-process — crypto.subtle
+// .importKey hands back the test public key instead of the shipped one. That
+// is the only substitution: the envelope parsing, the real WebCrypto ECDSA
+// verify, the hashing and every decision in packs.ts are the shipped code.
+
+import { webcrypto } from 'node:crypto'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) {
+ failures++
+ console.error(` ✗ ${msg}`)
+ } else {
+ console.log(` ✓ ${msg}`)
+ }
+}
+
+const subtle = webcrypto.subtle
+const enc = new TextEncoder()
+
+// --- the throwaway release key ---------------------------------------------
+const keys = await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify'])
+const testPubJwk = await subtle.exportKey('jwk', keys.publicKey)
+
+const sign = async (payload: string): Promise<string> =>
+ Buffer.from(
+ await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, keys.privateKey, enc.encode(payload)),
+ ).toString('base64')
+
+/** A signed envelope, exactly as sign-release.mjs emits one. */
+const envelope = async (value: unknown): Promise<string> => {
+ const payload = JSON.stringify(value)
+ return JSON.stringify({ payload, sig: await sign(payload) })
+}
+
+const sha256Hex = async (bytes: Uint8Array): Promise<string> =>
+ [...new Uint8Array(await subtle.digest('SHA-256', bytes))]
+ .map((b) => b.toString(16).padStart(2, '0'))
+ .join('')
+
+// --- browser globals the module graph expects -------------------------------
+Object.defineProperty(globalThis, 'localStorage', {
+ configurable: true,
+ value: { getItem: () => null, setItem: () => {}, removeItem: () => {} },
+})
+
+// Swap ONLY the trust root: any EC JWK import (there is exactly one call site,
+// verifySigned's) resolves to the test public key. Everything else passes
+// through to real WebCrypto.
+Object.defineProperty(globalThis, 'crypto', {
+ configurable: true,
+ value: {
+ ...webcrypto,
+ subtle: {
+ digest: subtle.digest.bind(subtle),
+ verify: subtle.verify.bind(subtle),
+ importKey: (fmt: string, data: any, algo: any, ext: boolean, usages: string[]) =>
+ subtle.importKey(
+ fmt as 'jwk',
+ fmt === 'jwk' && data?.kty === 'EC' ? testPubJwk : data,
+ algo,
+ ext,
+ usages as any,
+ ),
+ },
+ },
+})
+
+// --- the channel ------------------------------------------------------------
+const CHANNEL = 'https://bento.page/releases/slides'
+const PACK_URL = 'packs/bento-slides-1.0.0-xx.pack.json'
+
+const pack = {
+ app: 'slides',
+ version: '1.0.0',
+ lang: 'xx',
+ label: 'Testish',
+ strings: { Delete: 'Deletish', Close: 'Closish' },
+}
+const packBytes = enc.encode(JSON.stringify(pack))
+const packHash = await sha256Hex(packBytes)
+
+/** The bytes an attacker would rather we ran. */
+const evilPack = { ...pack, strings: { Delete: 'PWNED', Close: 'PWNED' } }
+const evilBytes = enc.encode(JSON.stringify(evilPack))
+
+/** What the fake channel currently serves; each case rewrites these. */
+let servedIndex: string | null = null
+let servedPack: Uint8Array | null = packBytes
+
+const res = (body: Uint8Array | string, status = 200) => ({
+ ok: status >= 200 && status < 300,
+ status,
+ text: async () => (typeof body === 'string' ? body : new TextDecoder().decode(body)),
+ arrayBuffer: async () =>
+ typeof body === 'string' ? enc.encode(body).buffer : body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength),
+})
+
+Object.defineProperty(globalThis, 'fetch', {
+ configurable: true,
+ value: async (url: string, init?: { method?: string }) => {
+ if (url === `${CHANNEL}/packs.json`) return servedIndex === null ? res('', 404) : res(servedIndex)
+ if (url === `${CHANNEL}/${PACK_URL}`) {
+ if (servedPack === null) return res('', 404)
+ // HEAD is the reachability probe packs.ts makes on the failure path.
+ return init?.method === 'HEAD' ? res('') : res(servedPack)
+ }
+ return res('', 404)
+ },
+})
+
+// Imported AFTER the globals exist — module scope must find them in place.
+const packs = await import('../slides/src/packs.ts')
+
+const goodIndex = async (sha256 = packHash) =>
+ envelope([{ lang: 'xx', label: 'Testish', url: PACK_URL, version: '1.0.0', sha256 }])
+
+// --- 1. the good path -------------------------------------------------------
+console.log('\nsigned index, matching hash')
+servedIndex = await goodIndex()
+servedPack = packBytes
+let listed = await packs.availablePacks()
+ok(listed.length === 1 && listed[0].lang === 'xx', 'a signed listing is offered')
+let got = await packs.fetchPack(listed[0])
+ok(typeof got !== 'string' && got.lang === 'xx', 'a pack matching its pinned hash is accepted')
+ok(typeof got !== 'string' && got.strings.Delete === 'Deletish', 'and it is the pack we asked for')
+
+// --- 2. tampered pack, untouched index -------------------------------------
+// The channel (or anyone between it and us) swaps the pack bytes but cannot
+// re-sign the index that pins them.
+console.log('\ntampered pack bytes')
+servedPack = evilBytes
+got = await packs.fetchPack(listed[0])
+ok(got === 'unverified', 'a pack whose bytes do not match the pinned hash is REFUSED')
+ok(got !== 'offline', 'and it is reported as a failed check, not as a network problem')
+
+// --- 3. tampered index ------------------------------------------------------
+// The forger also rewrites the index to pin the forged pack's hash — which is
+// the only way to make case 2 pass — and the signature no longer verifies.
+console.log('\ntampered index (hash re-pinned to the forged pack)')
+servedPack = evilBytes
+const forgedHash = await sha256Hex(evilBytes)
+const honest = JSON.parse(await goodIndex())
+const forged = JSON.stringify({
+ payload: JSON.stringify([{ lang: 'xx', label: 'Testish', url: PACK_URL, version: '1.0.0', sha256: forgedHash }]),
+ sig: honest.sig, // the old signature, over the old payload
+})
+servedIndex = forged
+ok((await packs.availablePacks()).length === 0, 'an index whose signature fails offers NOTHING')
+
+// --- 4. unsigned index ------------------------------------------------------
+console.log('\nunsigned index')
+servedIndex = JSON.stringify([{ lang: 'xx', label: 'Testish', url: PACK_URL, sha256: packHash }])
+ok((await packs.availablePacks()).length === 0, 'a bare (unsigned) listing array is refused — fail closed')
+servedIndex = await envelope([{ lang: 'xx', label: 'Testish', url: PACK_URL }])
+ok((await packs.availablePacks()).length === 0, 'a signed listing with NO pinned hash is not offered')
+
+// --- 5. no pin at the fetch itself -----------------------------------------
+console.log('\nlisting with no usable pin, handed straight to fetchPack')
+ok(
+ (await packs.fetchPack({ lang: 'xx', label: 'Testish', url: PACK_URL, sha256: '' } as any)) === 'unverified',
+ 'fetchPack refuses an unpinned listing without even downloading',
+)
+ok(
+ (await packs.fetchPack({ lang: 'xx', label: 'Testish', url: PACK_URL, sha256: 'nonsense' } as any)) === 'unverified',
+ 'and refuses a malformed pin',
+)
+
+// --- 6. offline is still offline -------------------------------------------
+console.log('\nunreachable pack')
+servedIndex = await goodIndex()
+servedPack = null
+ok((await packs.fetchPack((await packs.availablePacks())[0])) === 'offline', 'a missing download is reported as offline, not as tampering')
+
+// --- 7. refresh keeps a verified pack when the new one fails ---------------
+// The update flow's rule: degraded beats absent. A pack already in the file
+// was verified when it was added, so a refresh that cannot be verified must
+// leave it exactly where it is — and must never write the unverified bytes.
+console.log('\nrefresh with a tampered pack on the channel')
+servedIndex = await goodIndex()
+servedPack = packBytes
+const fresh = await packs.fetchPack((await packs.availablePacks())[0])
+ok(typeof fresh !== 'string' && packs.stageForFile(fresh), 'stage the verified pack into the file')
+servedPack = evilBytes // channel turns hostile between install and update
+servedIndex = await envelope([
+ { lang: 'xx', label: 'Testish', url: PACK_URL, version: '1.0.1', sha256: packHash },
+])
+const out = await packs.refreshPacksForVersion('1.0.1')
+ok(out.kept.includes('xx') && !out.refreshed.includes('xx'), 'the pack is KEPT, not refreshed')
+const inFile = packs.packsInFile().find((p) => p.lang === 'xx')
+ok(inFile?.version === '1.0.0', 'the file still holds the version that was verified')
+ok(
+ JSON.stringify(inFile?.strings) === JSON.stringify(pack.strings),
+ 'and the forged strings never reached the file',
+)
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) {
+ console.error(`${failures} FAILED`)
+ process.exit(1)
+}
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index 9cc724d5..96ace65e 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -2483,7 +2483,7 @@ export class Editor {
* Turn a pack-install failure into a sentence. Built at display time because
* t() must never be frozen into a module-level const.
*/
-function languageInstallError(code: 'offline' | 'bad-pack' | 'wrong-app'): string {
+function languageInstallError(code: import('../packs').PackError): string {
switch (code) {
case 'offline':
return t('Couldn’t download that language — check your connection and try again.')
@@ -2491,6 +2491,11 @@ function languageInstallError(code: 'offline' | 'bad-pack' | 'wrong-app'): strin
return t('That language pack couldn’t be read.')
case 'wrong-app':
return t('That language pack was built for a different Bento app.')
+ // Says what happened and what was done about it, without pretending to
+ // know whether it was an attack or a bungled upload — we cannot tell, and
+ // the answer is the same either way: it was not installed.
+ case 'unverified':
+ return t('That language pack failed its security check, so it wasn’t added.')
}
}
diff --git a/slides/src/i18n/de.ts b/slides/src/i18n/de.ts
index 7e10c0a9..d4d8ca20 100644
--- a/slides/src/i18n/de.ts
+++ b/slides/src/i18n/de.ts
@@ -675,6 +675,7 @@ export const de: Catalog = {
"Available to add": "Zum Hinzufügen verfügbar",
"Adding…": "Wird hinzugefügt…",
"That language pack couldn’t be read.": "Dieses Sprachpaket konnte nicht gelesen werden.",
+ "That language pack failed its security check, so it wasn’t added.": "Dieses Sprachpaket hat die Sicherheitsprüfung nicht bestanden und wurde daher nicht hinzugefügt.",
"That language pack was built for a different Bento app.": "Dieses Sprachpaket wurde für eine andere Bento-App erstellt.",
"Manage languages…": "Sprachen verwalten…",
"In this file": "In dieser Datei",
diff --git a/slides/src/i18n/es.ts b/slides/src/i18n/es.ts
index aa482249..1cb73d5b 100644
--- a/slides/src/i18n/es.ts
+++ b/slides/src/i18n/es.ts
@@ -675,6 +675,7 @@ export const es: Catalog = {
"Available to add": "Disponibles para añadir",
"Adding…": "Añadiendo…",
"That language pack couldn’t be read.": "No se pudo leer ese paquete de idioma.",
+ "That language pack failed its security check, so it wasn’t added.": "Ese paquete de idioma no superó la comprobación de seguridad, así que no se añadió.",
"That language pack was built for a different Bento app.": "Ese paquete de idioma se creó para otra aplicación de Bento.",
"Manage languages…": "Gestionar idiomas…",
"In this file": "En este archivo",
diff --git a/slides/src/i18n/fr.ts b/slides/src/i18n/fr.ts
index 10b0c859..2ab9b2bc 100644
--- a/slides/src/i18n/fr.ts
+++ b/slides/src/i18n/fr.ts
@@ -675,6 +675,7 @@ export const fr: Catalog = {
"Available to add": "Disponibles à l’ajout",
"Adding…": "Ajout…",
"That language pack couldn’t be read.": "Ce pack de langue n’a pas pu être lu.",
+ "That language pack failed its security check, so it wasn’t added.": "Ce pack de langue n’a pas passé le contrôle de sécurité, il n’a donc pas été ajouté.",
"That language pack was built for a different Bento app.": "Ce pack de langue a été conçu pour une autre application Bento.",
"Manage languages…": "Gérer les langues…",
"In this file": "Dans ce fichier",
diff --git a/slides/src/i18n/it.ts b/slides/src/i18n/it.ts
index ea24d516..417b3a92 100644
--- a/slides/src/i18n/it.ts
+++ b/slides/src/i18n/it.ts
@@ -675,6 +675,7 @@ export const it: Catalog = {
"Available to add": "Disponibili da aggiungere",
"Adding…": "Aggiunta…",
"That language pack couldn’t be read.": "Non è stato possibile leggere quel pacchetto lingua.",
+ "That language pack failed its security check, so it wasn’t added.": "Quel pacchetto lingua non ha superato il controllo di sicurezza, quindi non è stato aggiunto.",
"That language pack was built for a different Bento app.": "Quel pacchetto lingua è stato creato per un’altra app Bento.",
"Manage languages…": "Gestisci lingue…",
"In this file": "In questo file",
diff --git a/slides/src/i18n/ja.ts b/slides/src/i18n/ja.ts
index 0dbc20c3..5ea9642d 100644
--- a/slides/src/i18n/ja.ts
+++ b/slides/src/i18n/ja.ts
@@ -675,6 +675,7 @@ export const ja: Catalog = {
"Available to add": "追加できる言語",
"Adding…": "追加中…",
"That language pack couldn’t be read.": "その言語パックを読み取れませんでした。",
+ "That language pack failed its security check, so it wasn’t added.": "その言語パックはセキュリティ検証に失敗したため、追加されませんでした。",
"That language pack was built for a different Bento app.": "その言語パックは別の Bento アプリ用です。",
"Manage languages…": "言語を管理…",
"In this file": "このファイル内",
diff --git a/slides/src/i18n/packed.ts b/slides/src/i18n/packed.ts
index 5971e8db..c53f1bd9 100644
--- a/slides/src/i18n/packed.ts
+++ b/slides/src/i18n/packed.ts
@@ -681,6 +681,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Available to add": ["追加できる言語","可添加","可新增","Disponibles para añadir","Disponibles à l’ajout","Zum Hinzufügen verfügbar","Disponibili da aggiungere","Disponíveis para adicionar"],
"Adding…": ["追加中…","正在添加…","正在新增…","Añadiendo…","Ajout…","Wird hinzugefügt…","Aggiunta…","Adicionando…"],
"That language pack couldn’t be read.": ["その言語パックを読み取れませんでした。","无法读取该语言包。","無法讀取該語言包。","No se pudo leer ese paquete de idioma.","Ce pack de langue n’a pas pu être lu.","Dieses Sprachpaket konnte nicht gelesen werden.","Non è stato possibile leggere quel pacchetto lingua.","Não foi possível ler esse pacote de idioma."],
+ "That language pack failed its security check, so it wasn’t added.": ["その言語パックはセキュリティ検証に失敗したため、追加されませんでした。","该语言包未通过安全校验,因此未被添加。","該語言包未通過安全檢查,因此未加入。","Ese paquete de idioma no superó la comprobación de seguridad, así que no se añadió.","Ce pack de langue n’a pas passé le contrôle de sécurité, il n’a donc pas été ajouté.","Dieses Sprachpaket hat die Sicherheitsprüfung nicht bestanden und wurde daher nicht hinzugefügt.","Quel pacchetto lingua non ha superato il controllo di sicurezza, quindi non è stato aggiunto.","Esse pacote de idioma não passou na verificação de segurança, por isso não foi adicionado."],
"That language pack was built for a different Bento app.": ["その言語パックは別の Bento アプリ用です。","该语言包是为另一个 Bento 应用构建的。","該語言包是為另一個 Bento 應用程式建置的。","Ese paquete de idioma se creó para otra aplicación de Bento.","Ce pack de langue a été conçu pour une autre application Bento.","Dieses Sprachpaket wurde für eine andere Bento-App erstellt.","Quel pacchetto lingua è stato creato per un’altra app Bento.","Esse pacote de idioma foi criado para outro aplicativo Bento."],
"Manage languages…": ["言語を管理…","管理语言…","管理語言…","Gestionar idiomas…","Gérer les langues…","Sprachen verwalten…","Gestisci lingue…","Gerenciar idiomas…"],
"In this file": ["このファイル内","此文件内","此檔案內","En este archivo","Dans ce fichier","In dieser Datei","In questo file","Neste arquivo"],
diff --git a/slides/src/i18n/pt.ts b/slides/src/i18n/pt.ts
index d3112217..6854fc86 100644
--- a/slides/src/i18n/pt.ts
+++ b/slides/src/i18n/pt.ts
@@ -673,6 +673,7 @@ export const pt: Catalog = {
"Available to add": "Disponíveis para adicionar",
"Adding…": "Adicionando…",
"That language pack couldn’t be read.": "Não foi possível ler esse pacote de idioma.",
+ "That language pack failed its security check, so it wasn’t added.": "Esse pacote de idioma não passou na verificação de segurança, por isso não foi adicionado.",
"That language pack was built for a different Bento app.": "Esse pacote de idioma foi criado para outro aplicativo Bento.",
"Manage languages…": "Gerenciar idiomas…",
"In this file": "Neste arquivo",
diff --git a/slides/src/i18n/zh-Hans.ts b/slides/src/i18n/zh-Hans.ts
index 72fbc769..c054bf02 100644
--- a/slides/src/i18n/zh-Hans.ts
+++ b/slides/src/i18n/zh-Hans.ts
@@ -675,6 +675,7 @@ export const zhHans: Catalog = {
"Available to add": "可添加",
"Adding…": "正在添加…",
"That language pack couldn’t be read.": "无法读取该语言包。",
+ "That language pack failed its security check, so it wasn’t added.": "该语言包未通过安全校验,因此未被添加。",
"That language pack was built for a different Bento app.": "该语言包是为另一个 Bento 应用构建的。",
"Manage languages…": "管理语言…",
"In this file": "此文件内",
diff --git a/slides/src/i18n/zh-Hant.ts b/slides/src/i18n/zh-Hant.ts
index a5858d14..acc0652d 100644
--- a/slides/src/i18n/zh-Hant.ts
+++ b/slides/src/i18n/zh-Hant.ts
@@ -675,6 +675,7 @@ export const zhHant: Catalog = {
"Available to add": "可新增",
"Adding…": "正在新增…",
"That language pack couldn’t be read.": "無法讀取該語言包。",
+ "That language pack failed its security check, so it wasn’t added.": "該語言包未通過安全檢查,因此未加入。",
"That language pack was built for a different Bento app.": "該語言包是為另一個 Bento 應用程式建置的。",
"Manage languages…": "管理語言…",
"In this file": "此檔案內",
diff --git a/slides/src/packs.ts b/slides/src/packs.ts
index 519ab6fc..5c19e9b3 100644
--- a/slides/src/packs.ts
+++ b/slides/src/packs.ts
@@ -20,7 +20,10 @@
import { addPack, removePack, type LanguagePack } from '../../kernel/src/i18n.ts'
import { readShellBlocks, type ShellBlock } from '../../kernel/src/save.ts'
-import { PACKED } from './i18n/packed'
+import { fetchPinned, verifySigned } from '../../kernel/src/update.ts'
+// Extension-explicit like the kernel imports above, so this module also loads
+// under plain node — scripts/test-packs.ts exercises the real thing.
+import { PACKED } from './i18n/packed.ts'
/**
* Where the release channel publishes the pack index and the packs.
@@ -38,9 +41,11 @@ export interface PackListing {
url: string
/** app version the pack was built against, for display */
version?: string
+ /** hex sha256 of the pack's bytes, PINNED by the signed index */
+ sha256: string
}
-export type PackError = 'offline' | 'bad-pack' | 'wrong-app'
+export type PackError = 'offline' | 'bad-pack' | 'wrong-app' | 'unverified'
/** The block type carrying a pack inside a saved shell. */
const BLOCK_TYPE = 'application/bento+lang'
@@ -55,6 +60,14 @@ const pending = new Set<string>()
* Read packs already embedded in this file and register them. Runs at boot
* from the i18n facade, before the first t(): a deck that arrives carrying
* Japanese must show Japanese immediately, offline, with nothing fetched.
+ *
+ * DELIBERATELY NOT RE-VERIFIED. A pack was verified when it was added
+ * (signed index, pinned hash — fetchIndex/fetchPack below); once spliced it
+ * is part of the file, carrying exactly the trust the document itself does.
+ * Anyone who can rewrite this block can rewrite the whole shell — including
+ * the code doing the checking — so a check here would buy nothing, while
+ * requiring the network at boot would break offline use, which is the
+ * product's core promise. Verification belongs at the door, not in the room.
*/
export function readPacksFromShell(): number {
let n = 0
@@ -94,16 +107,44 @@ export function packsInFile(): Array<LanguagePack & { pending: boolean }> {
return [...inFile.values()].map((p) => ({ ...p, pending: pending.has(p.lang) }))
}
-/** Download and validate a pack. Does not decide where it goes. */
+/**
+ * Download and validate a pack. Does not decide where it goes.
+ *
+ * The bytes are accepted only if they hash to the sha256 the SIGNED index
+ * pinned for this listing (kernel fetchPinned). So the chain is: our embedded
+ * release key signed the index, the index pins this pack — substituting a
+ * pack means breaking the hash, and fixing the hash means breaking the
+ * signature. A hash we cannot match is 'unverified' and the pack is refused
+ * outright; there is no path where unverified strings reach the UI.
+ *
+ * A network failure and a failed check are told apart on purpose: one is
+ * "try again later", the other is "something is wrong with that download",
+ * and telling a user to check their connection when they are being served a
+ * forged pack would be a lie.
+ */
export async function fetchPack(listing: PackListing): Promise<LanguagePack | PackError> {
const url = /^https?:/.test(listing.url) ? listing.url : `${channel()}/${listing.url}`
+ if (!/^[0-9a-f]{64}$/i.test(listing.sha256 ?? '')) return 'unverified'
+
+ const bytes = await fetchPinned(url, listing.sha256)
+ if (!bytes) {
+ // fetchPinned refuses unreachable and unmatched alike — correct for it,
+ // useless for the sentence we have to show. One cheap HEAD on the FAILURE
+ // path only (the happy path stays a single download) separates "you are
+ // offline / it isn't published" from "those bytes are not the pack we
+ // were promised". Either way nothing unverified is returned.
+ try {
+ return (await fetch(url, { cache: 'no-store', method: 'HEAD' })).ok ? 'unverified' : 'offline'
+ } catch {
+ return 'offline'
+ }
+ }
+
let pack: LanguagePack
try {
- const res = await fetch(url, { cache: 'no-store' })
- if (!res.ok) return 'offline'
- pack = (await res.json()) as LanguagePack
+ pack = JSON.parse(new TextDecoder().decode(bytes)) as LanguagePack
} catch {
- return 'offline' // no network, blocked, or not JSON
+ return 'bad-pack'
}
if (!pack?.lang || !pack.strings || typeof pack.strings !== 'object') return 'bad-pack'
if (pack.app && pack.app !== 'slides') return 'wrong-app'
@@ -150,13 +191,41 @@ export function shellBlocksForPacks(): ShellBlock[] {
}))
}
-/** The channel's whole index, unfiltered. [] if unpublished or unreachable. */
+/**
+ * The channel's whole index, unfiltered. [] if unpublished, unreachable, or
+ * NOT PROPERLY SIGNED.
+ *
+ * The index is a signed envelope — `{payload, sig}`, ECDSA P-256 over the
+ * payload's bytes, verified against the release key already embedded in this
+ * shell (kernel verifySigned). It is the whole trust anchor for packs: every
+ * listing pins its pack's sha256, so signing the index signs the hashes, and
+ * a fetched pack is checked against its pinned hash. Same shape as the update
+ * manifest, same key, no second trust root.
+ *
+ * FAIL CLOSED, no legacy path. An unsigned or badly signed index yields NO
+ * listings — the Languages dialog then says there is nothing to add, which is
+ * exactly right: an index we cannot authenticate is an index we know nothing
+ * about. Nothing is published yet, so there is no old plain-array index in the
+ * world to be compatible with, and adding a permissive fallback would mean
+ * anyone who can answer for the channel picks the strings in your UI.
+ *
+ * The payload is a listing array, or an object carrying one under `packs` —
+ * which is the shape of the signed release manifest itself (sign-release.mjs
+ * puts pack hashes in the manifest payload), so one signed file can serve as
+ * both if the channel prefers that. Same envelope either way.
+ */
async function fetchIndex(): Promise<PackListing[]> {
try {
const res = await fetch(`${channel()}/packs.json`, { cache: 'no-store' })
if (!res.ok) return []
- const list = (await res.json()) as PackListing[]
- return Array.isArray(list) ? list.filter((p) => p?.lang && p?.url) : []
+ const payload = await verifySigned(await res.text(), 'language pack index')
+ const list = Array.isArray(payload) ? payload : (payload as { packs?: unknown })?.packs
+ if (!Array.isArray(list)) return []
+ // A listing with no usable pin can never be verified, so it can never be
+ // offered — drop it here rather than let it fail later at the Add button.
+ return (list as PackListing[]).filter(
+ (p) => p?.lang && p?.url && /^[0-9a-f]{64}$/i.test(p?.sha256 ?? ''),
+ )
} catch {
return []
}
@@ -185,6 +254,13 @@ export async function availablePacks(): Promise<PackListing[]> {
*
* Refusing to fail is the whole point: any pack we cannot re-fetch is simply
* KEPT at its current version. Degraded beats absent.
+ *
+ * That includes a pack that fails VERIFICATION — an unsigned index, or bytes
+ * that don't match their pinned hash. Keeping is not laxity: the pack already
+ * in the file was verified when it was added and has been travelling with the
+ * document ever since, so it is strictly the more trustworthy of the two. The
+ * new bytes are refused; the old ones stay. What must never happen — and does
+ * not — is an unverified pack being written into the file by the update flow.
*/
export async function refreshPacksForVersion(version: string): Promise<{ refreshed: string[]; kept: string[] }> {
const refreshed: string[] = []