Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

bento.page/convert: rescue a file onto the latest version of its own app (#738)

nyblnet18845fc4bb96
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e8ad53e4..85712a8c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,16 @@ pre-1.0.
## [Unreleased]
+- **A password-protected deck that won't open can be moved to the latest
+ version on bento.page/convert.** Drop the `.bento.html` and choose "The
+ same file, on the latest version". The page puts the file's document,
+ still encrypted and byte for byte, into the newest signed release of its
+ app. It never asks for the password and never decrypts anything. Open the
+ new file and enter your password as usual. It works for any Bento file
+ whose app has a published release, encrypted or not. As always, nothing is
+ uploaded. An encrypted deck is only moved onto a release that can open it
+ (1.2.9 or later).
+
## [1.2.8] — 2026-10-16
- **Indent and outdent bullets.** While editing text, Tab moves the bullet
diff --git a/convert/page/convert-page.ts b/convert/page/convert-page.ts
index bd8346f4..fb70bfdc 100644
--- a/convert/page/convert-page.ts
+++ b/convert/page/convert-page.ts
@@ -20,6 +20,7 @@
import { detect, describe, optionsFor, nothingFor, LimitError, type Detected, type Conversion, type Env } from '../src/pairs.ts'
import { fetchVerifiedShell, LIMITS } from '../src/api.ts'
+import { APPS, manifestPath } from '../src/deliver.ts'
import { foldReport, type FidelityReport } from '../src/report.ts'
import { loadDocJson } from './load-json.ts'
import { rasteriseToPng } from './rasterise.ts'
@@ -56,16 +57,21 @@ function say(text: string, kind: 'busy' | 'error' | 'idle' = 'busy') {
// A verified shell is fetched once per page load and reused. A refused shell
// is forgotten, never retried into a fallback.
-let shell: Promise<{ version: string; html: string }> | null = null
+const shells = new Map<string, Promise<{ version: string; html: string }>>()
const env: Env = {
- shell() {
- say('Fetching the latest bento/slides and checking its signature…')
+ shell(appId = 'bento-slides') {
+ say(`Fetching the latest ${APPS[appId]?.name ?? appId} and checking its signature…`)
// Both requests go to THIS origin: the manifest by relative path, and the
// shell by re-rooting the signed URL's path here (deliver.ts `resolve`).
// That is what lets the CSP be `connect-src 'self'` with no exceptions.
- shell ??= fetchVerifiedShell('/releases/slides/manifest.json', fetch,
- (u) => new URL(new URL(u).pathname, location.href).href)
- return shell
+ let p = shells.get(appId)
+ if (!p) {
+ p = fetchVerifiedShell(manifestPath(appId), fetch, (u) => new URL(new URL(u).pathname, location.href).href, appId)
+ shells.set(appId, p)
+ // a refused shell is forgotten, never kept as a settled answer
+ p.catch(() => shells.delete(appId))
+ }
+ return p
},
loadDocJson,
rasterise: rasteriseToPng,
@@ -124,7 +130,6 @@ async function run() {
status.hidden = true
show(c, r.fileName, r.mime, r.bytes, r.report, r.stats, r.meta)
} catch (err) {
- if (c.network) shell = null
const msg = err instanceof LimitError
? `This file was refused: ${err.message}.`
: /signature|pin|manifest|release server/i.test(String((err as Error)?.message))
@@ -178,6 +183,7 @@ const PLAIN: Record<string, string> = {
'path-approximated': 'A drawn shape could not be read in full, so it stops where the problem began.',
'image-fit-approximated': 'Some pictures are stretched to their frame, where bento crops them to fit.',
'missing-image': 'Some pictures could not be included (an unsupported format, or a missing file).',
+ 'language-packs-not-carried': 'Extra languages added to this file are not in the updated copy. Add them again from About.',
'states-as-hidden-slides': 'Interactive states are hidden slides, right after the slide they belong to. Links still lead to them, and the show skips them.',
'image-converted-png': 'WebP and similar pictures were converted to PNG for PowerPoint. They look the same; the file is a little larger.',
'text-height-provisional': 'Some text boxes had no height, so they start one line tall. Select one in bento/slides and use Fit height to text.',
diff --git a/convert/src/deliver.ts b/convert/src/deliver.ts
index b6b45e49..40d137f1 100644
--- a/convert/src/deliver.ts
+++ b/convert/src/deliver.ts
@@ -58,6 +58,27 @@ export const SLIDES_MANIFEST = 'https://bento.page/releases/slides/manifest.json
export const MIN_SHELL_VERSION = '1.2.5'
const APP_ID = 'bento-slides'
+/** Every Bento app, by the id its shells carry (`<meta name="generator">`)
+ * and its signed manifest declares: where its releases live, its name, and
+ * the document format it writes. An app with no published release yet has
+ * no manifest there, and a rescue onto it says so. */
+export const APPS: Record<string, { key: string; name: string; format: string }> = {
+ 'bento-slides': { key: 'slides', name: 'bento/slides', format: 'bento/slides' },
+ 'bento-spaces': { key: 'spaces', name: 'bento/spaces', format: 'bento/spaces' },
+ 'bento-dash': { key: 'dash', name: 'bento/dash', format: 'bento/dash' },
+ 'bento-type': { key: 'type', name: 'bento/type', format: 'bento/type' },
+}
+/** The oldest release of each app that can OPEN a password-protected file.
+ * Slides 1.2.0–1.2.8 shipped a loader that refuses every path over the
+ * password gate, so moving an encrypted deck onto one of those would hand
+ * back a file exactly as broken as the one dropped. */
+export const ENC_OPEN_MIN: Record<string, string> = { 'bento-slides': '1.2.9' }
+export const opensEncrypted = (appId: string, version: string) =>
+ !ENC_OPEN_MIN[appId] || compareVersions(version, ENC_OPEN_MIN[appId]) >= 0
+
+/** The signed manifest's path for an app, relative to bento.page. */
+export const manifestPath = (appId: string) => `/releases/${APPS[appId].key}/manifest.json`
+
// verifySigned reads the app identity (and a fork's key override) from
// configureApp. Calling it here makes this module self-sufficient; the values
// are the upstream slides identity, the same ones slides/src/main.ts sets.
@@ -83,6 +104,8 @@ export async function fetchVerifiedShell(
* different bytes is refused by fetchPinned exactly as a tampered CDN would be.
*/
resolve: (url: string) => string = (u) => u,
+ /** the app whose shell this must be; the signed payload's app must match */
+ appId: string = APP_ID,
): Promise<VerifiedShell> {
const res = await net(manifestUrl, { cache: 'no-store' })
if (!res.ok) throw new Error(`could not reach the release server (${res.status})`)
@@ -91,7 +114,7 @@ export async function fetchVerifiedShell(
// signed payload a slides release".
const info = (await verifySigned(await res.text(), 'release manifest')) as Record<string, unknown>
if (
- info?.app !== APP_ID ||
+ info?.app !== appId ||
typeof info.version !== 'string' ||
typeof info.sha256 !== 'string' || !/^[0-9a-f]{64}$/i.test(info.sha256) ||
typeof info.url !== 'string'
@@ -101,8 +124,9 @@ export async function fetchVerifiedShell(
// compareVersions would read its non-numeric parts as 0.
if (!/^\d+(\.\d+)*$/.test(info.version))
throw new Error(`the release server offered a bento/slides version this converter does not recognise ("${info.version.slice(0, 40)}") — refusing it.`)
- if (compareVersions(info.version, MIN_SHELL_VERSION) < 0)
- throw new Error(`the release server offered bento/slides ${info.version}, which is older than ${MIN_SHELL_VERSION}, the oldest version this converter will build on — refusing it. Try again later.`)
+ const floor = appId === APP_ID ? MIN_SHELL_VERSION : undefined
+ if (floor && compareVersions(info.version, floor) < 0)
+ throw new Error(`the release server offered ${APPS[appId]?.name ?? appId} ${info.version}, which is older than ${floor}, the oldest version this converter will build on — refusing it. Try again later.`)
const bytes = await fetchPinned(resolve(info.url), info.sha256)
if (!bytes) throw new Error('the downloaded shell does not match its signed pin — refusing it')
return { version: info.version, html: new TextDecoder().decode(bytes) }
@@ -168,3 +192,99 @@ export function extractDoc(html: string): unknown {
if (!text) throw new Error('the #bento-doc block is empty — a fresh shell, not a deck')
try { return JSON.parse(text) } catch { throw new Error('the #bento-doc block is not valid JSON') }
}
+
+// --- rescue: the same document, in the latest shell of its own app ----------
+//
+// A file whose shell cannot boot cannot update itself (About → Update runs
+// inside the app). The rescue does what the self-updater does, without the
+// app: put the file's document into the newest signed shell of the SAME app.
+// The document block is carried VERBATIM, byte for byte, never parsed into a
+// document and never re-serialised. So an encrypted file's bento/enc envelope
+// stays exactly as it was: no password is asked for, nothing is decrypted.
+//
+// What is carried: the #bento-doc block, and (for an unencrypted file only)
+// the file's own <title>.
+// What is not: anything else the old shell held. Language packs
+// (application/bento+lang) are reported, and can be added again from About;
+// a first-page preview is regenerated on the next save (and encrypted files
+// never have one).
+
+const DOC_ID_ATTR = ' id="bento-doc"'
+
+/** The raw text of the one #bento-doc block, exactly as written, with where
+ * it sits. Found the way the kernel finds it (save.ts embeddedDocBlock: the
+ * exact id attribute with a leading space, then the next script close). */
+function docBlock(html: string): { start: number; end: number; body: string } {
+ const at = html.indexOf(DOC_ID_ATTR)
+ if (at < 0) throw new Error('not a Bento file (no #bento-doc block)')
+ if (html.indexOf(DOC_ID_ATTR, at + 1) >= 0) throw new Error('the file carries more than one #bento-doc block')
+ const tagStart = html.lastIndexOf('<script', at)
+ const gt = html.indexOf('>', at)
+ if (tagStart < 0 || gt < 0 || !/type="application\/bento\+json"/.test(html.slice(tagStart, gt)))
+ throw new Error('the #bento-doc block is not a Bento data block')
+ const end = html.indexOf(SCRIPT_CLOSE, gt + 1)
+ if (end < 0) throw new Error('the #bento-doc block is not closed')
+ return { start: gt + 1, end, body: html.slice(gt + 1, end) }
+}
+
+/** Which app a saved file belongs to: its shell's generator, or, for an
+ * unencrypted file from a shell that predates the generator tag, the
+ * document's own format. Null when neither says. */
+export function fileApp(html: string): string | null {
+ const gen = /<meta\s+name="generator"\s+content="(bento-[a-z]+)"/i.exec(html.slice(0, 64 * 1024))?.[1]
+ if (gen && APPS[gen]) return gen
+ try {
+ const fmt = (JSON.parse(docBlock(html).body.trim()) as { format?: unknown }).format
+ for (const [id, a] of Object.entries(APPS)) if (a.format === fmt) return id
+ } catch { /* fall through */ }
+ return null
+}
+
+export interface Rescued {
+ html: string
+ /** the block held a bento/enc envelope: carried unopened */
+ encrypted: boolean
+ /** language-pack blocks the old file carried that the new one does not */
+ packsLeft: number
+}
+
+/**
+ * Put `fileHtml`'s document block, byte for byte, into `shellHtml`, a
+ * verified shell of the same app. Refuses rather than guesses:
+ * - the block must be in the form Bento writes, with no `<` at all (every
+ * Bento writer escapes it), so it cannot change how the new shell parses;
+ * - it must be JSON naming a bento/ format;
+ * - the shell must belong to `appId`, and so must the file.
+ * The belts are the same as the other splice: the script-close count is
+ * unchanged, and the block reads back exactly as it was.
+ */
+export function spliceVerbatim(shellHtml: string, fileHtml: string, appId: string): Rescued {
+ const src = docBlock(fileHtml)
+ if (!src.body.trim()) throw new Error('the file has an empty document block: a fresh app, not a saved document')
+ if (src.body.includes('<')) throw new Error('the document block is not in the form Bento writes, so it is not carried')
+ let fmt: unknown
+ try { fmt = (JSON.parse(src.body.trim()) as { format?: unknown }).format } catch {
+ throw new Error('the document block is not valid JSON')
+ }
+ if (typeof fmt !== 'string' || !fmt.startsWith('bento/')) throw new Error('the document block is not a Bento document')
+ const encrypted = fmt === 'bento/enc'
+ const own = fileApp(fileHtml)
+ if (own !== appId) throw new Error(`this file belongs to ${own ? APPS[own].name : 'an unknown app'}, not ${APPS[appId]?.name ?? appId}`)
+ if (!encrypted && fmt !== APPS[appId].format) throw new Error(`the document is ${fmt}, but the file's app is ${APPS[appId].name}`)
+ const shellGen = /<meta\s+name="generator"\s+content="(bento-[a-z]+)"/i.exec(shellHtml.slice(0, 64 * 1024))?.[1]
+ if (shellGen !== appId) throw new Error(`the downloaded shell is ${shellGen ?? 'unmarked'}, not ${appId}`)
+ const dst = docBlock(shellHtml)
+ let out = shellHtml.slice(0, dst.start) + src.body + shellHtml.slice(dst.end)
+ // the file's own title, when it is plain text (a <title> is raw text, so
+ // anything with < in it is left out rather than escaped into something else),
+ // and NEVER for an encrypted body: builds before 1.2.9 wrote an encrypted
+ // deck's real title into <title> in clear, so carrying it would re-publish
+ // the very thing the password hides. Those keep the shell's neutral title.
+ const title = encrypted ? undefined : /<title>([^<]*)<\/title>/.exec(fileHtml)?.[1]
+ if (title !== undefined) out = out.replace(/<title>[^<]*<\/title>/, () => `<title>${title}</title>`)
+ if (out.split(SCRIPT_CLOSE).length !== shellHtml.split(SCRIPT_CLOSE).length)
+ throw new Error('splice changed the script-close count — refusing the output')
+ if (docBlock(out).body !== src.body) throw new Error('the document block does not read back byte for byte — refusing the output')
+ const packs = (fileHtml.match(/<script[^>]*type="application\/bento\+lang"/g) ?? []).length
+ return { html: out, encrypted, packsLeft: packs }
+}
diff --git a/convert/src/pairs.ts b/convert/src/pairs.ts
index 1e33c9b1..00e90294 100644
--- a/convert/src/pairs.ts
+++ b/convert/src/pairs.ts
@@ -13,7 +13,7 @@
import { pptxToBento, LimitError } from './api.ts'
import { bentoToPptx } from './export.ts'
-import { extractDoc, spliceIntoShell } from './deliver.ts'
+import { extractDoc, spliceIntoShell, spliceVerbatim, fileApp, opensEncrypted, APPS } from './deliver.ts'
import type { FidelityReport } from './report.ts'
import type { BentoDoc } from '../../slides/src/model.ts'
@@ -88,7 +88,10 @@ export function describe(d: Detected): { title: string; meta: string } {
if (d.kind === 'pptx') return { title: d.name, meta: `PowerPoint presentation · ${size(d.bytes.length)}` }
if (d.kind === 'unknown') return { title: d.name, meta: d.reason }
const app = APP_NAMES[d.format] ?? d.format
- if (d.format === 'bento/enc') return { title: d.name, meta: 'A password-protected Bento file' }
+ if (d.format === 'bento/enc') {
+ const own = fileApp(d.text)
+ return { title: d.name, meta: `A password-protected ${own ? APPS[own].name : 'Bento'} file. It can be moved to the latest version without the password: it stays encrypted.` }
+ }
const title = typeof d.doc.title === 'string' && d.doc.title ? d.doc.title : d.name
const slides = Array.isArray(d.doc.slides) ? d.doc.slides.filter((s) => !(s as { stateOf?: unknown })?.stateOf).length : 0
const sz = d.doc.size as { width?: unknown; height?: unknown } | undefined
@@ -111,7 +114,7 @@ const size = (n: number) => n < 1024 * 1024 ? `${Math.max(1, Math.round(n / 1024
export interface Env {
/** the current signed bento/slides shell (deliver.ts fetchVerifiedShell) */
- shell(): Promise<{ version: string; html: string }>
+ shell(appId?: string): Promise<{ version: string; html: string }>
/** document JSON → a full, gated slides document, expanding a compact one.
* The page passes its own loader (convert/page/load-json.ts: slides'
* expansion and gate). `provisional` lists the slide id of each text box
@@ -237,6 +240,44 @@ export const CONVERSIONS: Conversion[] = [
}
},
},
+ {
+ id: 'update-shell',
+ label: 'The same file, on the latest version (.bento.html)',
+ hint: 'Puts this document into the latest release of its app, signature checked. Use it when a file won’t open, or can’t update itself.',
+ network: true,
+ accepts: (d) => {
+ if (d.kind !== 'bento' || d.source !== 'html') return false
+ if (!fileApp(d.text)) return 'This file doesn’t say which Bento app made it, so there is no release to move it to.'
+ return true
+ },
+ async run(d, env) {
+ if (d.kind !== 'bento') throw new Error('not a Bento file')
+ const appId = fileApp(d.text)
+ if (!appId) throw new Error('this file does not say which Bento app made it')
+ let s: { version: string; html: string }
+ try { s = await env.shell(appId) } catch (e) {
+ if (/\(404\)/.test(String((e as Error).message)))
+ throw new Error(`there is no published release of ${APPS[appId].name} yet, so this file can’t be moved to one`)
+ throw e
+ }
+ const r = spliceVerbatim(s.html, d.text, appId)
+ if (r.encrypted && !opensEncrypted(appId, s.version))
+ throw new Error(`the latest ${APPS[appId].name} is ${s.version}, which can’t open password-protected files either. The fixed version isn’t out yet; try again once it is. Your file is unchanged`)
+ const report = emptyReport()
+ if (r.packsLeft) {
+ report.entries.push({ code: 'language-packs-not-carried', verdict: 'approximated', where: 'document',
+ detail: `${r.packsLeft} language pack(s) the file carried are not in the updated copy; add them again from About`, count: r.packsLeft })
+ report.counts.approximated += r.packsLeft
+ }
+ const name = d.name.replace(/(\.bento)?\.html?$/i, '') + '.bento.html'
+ return {
+ bytes: enc.encode(r.html), fileName: name, mime: 'text/html', report, stats: [],
+ meta: `Now on ${APPS[appId].name} ${s.version}, signature verified. ` + (r.encrypted
+ ? 'The document came across byte for byte, still encrypted: no password was needed, and nothing was decrypted.'
+ : 'The document came across byte for byte.'),
+ }
+ },
+ },
]
/** Every conversion that applies to this input: available ones, and ones that
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 7d59d512..3cd1e0b3 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -10435,6 +10435,49 @@ choices are dash's and are recorded because a later change could undo them:
`recoveryLooksOlder` is read against the workbook AS LOADED, because dash
stamps `modified` on every edit.
+## 2026-10-17 — Rescue: a file moved onto the latest shell of its own app, its document block carried byte for byte
+
+Slides 1.2.4–1.2.8 cannot open password-protected decks: the loader refuses
+every path over the password gate. A fixed shell can't reach those files,
+because About → Update runs inside the app and the file never boots.
+bento.page/convert therefore offers every Bento `.bento.html` "The same
+file, on the latest version". `deliver.ts spliceVerbatim` puts the file's
+`#bento-doc` block, BYTE FOR BYTE, into the newest signed and pinned shell of
+the file's own app.
+
+- **Never parsed into a document, never re-serialised, never decrypted.** A
+ `bento/enc` envelope stays exactly as it was, so no password is involved.
+ The rig decrypts the carried envelope with the original password to prove
+ it was untouched. A re-serialising splice was hidden by compact-JSON
+ fixtures (JSON.stringify reproduces them byte for byte), so the rig also
+ carries a pretty-printed envelope and a plain deck with `\u003c` escapes.
+ A re-serialising mutant fails on both, and the splice's own read-back
+ refuses it.
+- **Which app:** the file's shell `<meta name="generator">`, or, for a plain
+ file from a shell older than that tag, the document's format. The signed
+ manifest's `app` and the downloaded shell's generator must both match the
+ file's, or the rescue is refused. `fetchVerifiedShell` takes the app id; the
+ version floor stays slides-only.
+- **Refused rather than guessed:** a block containing a raw `<` (every Bento
+ writer escapes it, and a raw one could change how the new shell parses),
+ an empty block, a block that isn't JSON, and a document whose format isn't
+ the app's.
+- **Carried:** the block, and for an UNENCRYPTED file its own `<title>`. An
+ encrypted file keeps the shell's neutral title: builds before 1.2.9 wrote
+ an encrypted deck's real title in clear, and carrying it would re-publish
+ what the password hides (security review). **Not carried:**
+ anything else the old shell held. Language packs are reported and can be
+ added again; a first-page preview is regenerated on the next save, and
+ encrypted files never have one.
+- An app with no published release says so plainly.
+- **Never onto a shell that cannot open the file.** `ENC_OPEN_MIN` holds the
+ oldest release of each app that opens encrypted files (slides 1.2.9; 1.2.0–
+ 1.2.8 all refuse). An encrypted file is not moved onto an older latest
+ release, so the rescue only goes live with 1.2.9. Plain files may still
+ move onto 1.2.8. Measured on slides' hotfix build: encrypted fixtures from
+ live 1.2.8 and from 1.2.0–1.2.3 show three gates and the loader refusal as
+ they are. Rescued, each shows ONE gate and unlocks to the whole deck.
+
## 2026-10-17 — the loader reads what the app published: running, locked or refused
diff --git a/scripts/test-convert/pairs.ts b/scripts/test-convert/pairs.ts
index 2aa7cd56..bd8f3270 100644
--- a/scripts/test-convert/pairs.ts
+++ b/scripts/test-convert/pairs.ts
@@ -48,7 +48,7 @@ const pptx = await fxMinimal()
ok(d.kind === 'pptx' && JSON.stringify(ids(d)) === '["pptx-to-slides"]', `a .pptx is offered a bento/slides deck (${ids(d)})`)
ok(detect('deck.xlsx', pptx).kind === 'unknown', 'a zip that is not a .pptx is not taken for one')
const html = detect('deck.bento.html', enc.encode(wrap(sample)))
- ok(html.kind === 'bento' && html.source === 'html' && JSON.stringify(ids(html)) === '["slides-to-pptx"]', `a .bento.html deck is offered PowerPoint (${ids(html)})`)
+ ok(html.kind === 'bento' && html.source === 'html' && JSON.stringify(ids(html)) === '["slides-to-pptx","update-shell"]', `a .bento.html deck is offered PowerPoint, and the latest version of itself (${ids(html)})`)
const json = detect('deck.json', enc.encode(SAMPLE_DECK))
ok(json.kind === 'bento' && json.source === 'json' && JSON.stringify(ids(json)) === '["slides-to-pptx","json-to-slides"]',
`document JSON is offered PowerPoint AND a deck (${ids(json)})`)
@@ -59,10 +59,17 @@ const pptx = await fxMinimal()
ok(!!pp && !pp.ok && /compact/.test(pp.why) && c.some((o) => o.ok && o.conversion.id === 'json-to-slides'),
'compact JSON: PowerPoint is shown but explained, and making a deck is offered')
const spaces = detect('notes.bento.html', enc.encode(wrap({ format: 'bento/spaces', pages: [] })))
- ok(spaces.kind === 'bento' && optionsFor(spaces).length === 0 && /^There is no conversion for bento\/spaces files yet\.$/.test(nothingFor(spaces)),
- `another app's file is recognised and told plainly ("${nothingFor(spaces)}")`)
+ ok(spaces.kind === 'bento' && JSON.stringify(ids(spaces)) === '["update-shell"]',
+ `another app's file is recognised, and offered only the move to its own app's latest release (${ids(spaces)})`)
+ // an encrypted file whose shell does not say which app made it: the rescue
+ // is shown, but cannot run (there is no app to move it to); the password
+ // wording covers the JSON-only case, which has no shell at all
const locked = detect('locked.bento.html', enc.encode(wrap({ format: 'bento/enc', v: 1 })))
- ok(optionsFor(locked).length === 0 && /password/.test(nothingFor(locked)), 'a password-protected file is told what to do')
+ const lo = optionsFor(locked)
+ ok(lo.length === 1 && lo[0].conversion.id === 'update-shell' && !lo[0].ok && /which Bento app/.test(lo[0].why),
+ `an encrypted file with no app named: the rescue is shown and explained (${lo[0] && !lo[0].ok ? lo[0].why : 'not shown'})`)
+ const lockedJson = detect('locked.json', enc.encode(JSON.stringify({ format: 'bento/enc', v: 1 })))
+ ok(optionsFor(lockedJson).length === 0 && /password/.test(nothingFor(lockedJson)), 'an encrypted document as bare JSON is told what to do')
ok(detect('x.html', enc.encode('<p>hello</p>')).kind === 'unknown', 'an ordinary web page is not a Bento file')
ok(detect('x.json', enc.encode('{"a":')).kind === 'unknown', 'broken JSON is refused in words')
}
diff --git a/scripts/test-convert/rescue.ts b/scripts/test-convert/rescue.ts
new file mode 100644
index 00000000..5d3a1771
--- /dev/null
+++ b/scripts/test-convert/rescue.ts
@@ -0,0 +1,132 @@
+// @bundle — reaches the kernel's save module and slides' model (extensionless imports)
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The rescue: a Bento file whose shell cannot boot, moved onto the latest
+// signed shell of its own app, with the document block carried BYTE FOR BYTE.
+// The case it exists for: a password-protected deck saved by a slides
+// release whose loader cannot open encrypted files. Its owner cannot reach
+// About → Update, because the file never boots.
+//
+// The encrypted fixture is real: the kernel's own encodeDocBody (PBKDF2 +
+// AES-GCM), inside a real built slides shell. After the rescue, the rig
+// decrypts the carried envelope with the original password, which proves
+// nothing was re-encrypted or altered on the way.
+
+import fs from 'node:fs'
+import path from 'node:path'
+import { spliceVerbatim, fileApp } from '../../convert/src/deliver.ts'
+import { detect, optionsFor, CONVERSIONS, type Env } from '../../convert/src/pairs.ts'
+import { setEncryptionPassword, encodeDocBody, parseEnvelope, decryptEnvelope } from '../../kernel/src/save.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+let root = process.cwd()
+while (!fs.existsSync(path.join(root, 'scripts/test-convert')) && path.dirname(root) !== root) root = path.dirname(root)
+const shellPath = path.join(root, 'slides/dist-single/Bento_Slides.bento.html')
+const inCI = !!process.env.CI || !!process.env.GITHUB_ACTIONS
+if (!fs.existsSync(shellPath)) {
+ if (inCI) { console.log(' FAIL no built slides shell — cannot skip in CI'); process.exit(1) }
+ console.log(' ⚠ SKIPPED — no built shell (cd slides && npm run build:single)'); process.exit(0)
+}
+const SHELL = fs.readFileSync(shellPath, 'utf8')
+const OPEN = '<script type="application/bento+json" id="bento-doc">'
+const CLOSE = '</' + 'script>'
+const block = (html: string) => { const s = html.indexOf(OPEN) + OPEN.length; return html.slice(s, html.indexOf(CLOSE, s)) }
+const withBlock = (shell: string, body: string, title = 'Board pack — Q3') => {
+ const s = shell.indexOf(OPEN) + OPEN.length
+ return (shell.slice(0, s) + body + shell.slice(shell.indexOf(CLOSE, s))).replace(/<title>[^<]*<\/title>/, `<title>${title}</title>`)
+}
+// "the latest shell": the same build, marked so the two are told apart
+const LATEST = SHELL.replace('<head>', '<head><!-- latest -->')
+
+const doc = { format: 'bento/slides', version: 1, title: 'Board pack — Q3', docId: 'd-rescue', size: { width: 1280, height: 720 },
+ theme: { background: '#fff', color: '#111', accent: '#f60', fontFamily: 'Inter' }, slides: [{ id: 's1', background: '#fff', elements: [] }] }
+setEncryptionPassword('correct horse')
+const envelope = await encodeDocBody(doc as never)
+setEncryptionPassword(null)
+const body = '\n' + envelope + '\n'
+const encrypted = withBlock(SHELL, body)
+
+console.log('an encrypted deck, rescued')
+{
+ ok(parseEnvelope(envelope) !== null && !envelope.includes('Board pack'), 'the fixture is a real bento/enc envelope (the title is not in it in clear)')
+ ok(fileApp(encrypted) === 'bento-slides', 'the file says which app it belongs to (its shell\'s generator)')
+ const r = spliceVerbatim(LATEST, encrypted, 'bento-slides')
+ ok(r.encrypted && r.html.includes('<!-- latest -->'), 'the result is the latest shell, and it knows the block is encrypted')
+ ok(block(r.html) === body, 'the #bento-doc block is BYTE-IDENTICAL to the original')
+ const back = await decryptEnvelope(parseEnvelope(block(r.html).trim())!, 'correct horse')
+ ok(back !== null && JSON.parse(back).docId === 'd-rescue', 'the carried envelope still opens with the original password, to the same document')
+ // the fixture's <title> is the deck's real name IN CLEAR, as builds before
+ // 1.2.9 wrote it beside the ciphertext: it must not survive the rescue
+ const shellTitle = /<title>[^<]*<\/title>/.exec(LATEST)![0]
+ ok(r.html.includes(shellTitle) && !r.html.includes('Board pack'), `an encrypted file's plaintext title is NOT carried: the shell's neutral ${shellTitle} stays, and the old title is nowhere in the output`)
+ ok(r.html.split(CLOSE).length === LATEST.split(CLOSE).length, 'the script-close count is the shell\'s')
+}
+
+console.log('byte for byte, even where re-serialising would change the bytes')
+{
+ // A Bento writer's block is usually compact JSON, which JSON.stringify
+ // reproduces, so a re-serialising splice could hide behind it. These two
+ // are not: a pretty-printed envelope (still a valid one), and a plain deck
+ // whose text carries the \u003c escape every writer uses for '<'.
+ const pretty = '\n' + JSON.stringify(JSON.parse(envelope), null, 2) + '\n'
+ const r1 = spliceVerbatim(LATEST, withBlock(SHELL, pretty), 'bento-slides')
+ ok(block(r1.html) === pretty, 'a pretty-printed envelope comes across exactly as written')
+ const back = await decryptEnvelope(parseEnvelope(block(r1.html).trim())!, 'correct horse')
+ ok(back !== null, 'and still opens with the password')
+ const escaped = '\n' + JSON.stringify({ ...doc, title: 'a \u003c b' }).replace(/\\\\u003c/g, '\\u003c').replace(/</g, '\\u003c') + '\n'
+ const r2 = spliceVerbatim(LATEST, withBlock(SHELL, escaped), 'bento-slides')
+ ok(escaped.includes('\\u003c') && block(r2.html) === escaped, 'a plain deck\'s \\u003c escapes stay escapes (re-serialising would turn them into a raw <)')
+}
+
+console.log('refusals')
+const refuses = (f: () => unknown, re: RegExp, msg: string) => {
+ let m = ''
+ try { f() } catch (e) { m = (e as Error).message }
+ ok(re.test(m), `${msg} ("${m}")`)
+}
+refuses(() => spliceVerbatim(LATEST.replace('content="bento-slides"', 'content="bento-dash"'), encrypted, 'bento-slides'), /shell is bento-dash/, 'a shell of another app is refused')
+refuses(() => spliceVerbatim(LATEST, encrypted.replace('content="bento-slides"', 'content="bento-dash"'), 'bento-slides'), /belongs to bento\/dash/, 'a file of another app is refused')
+refuses(() => spliceVerbatim(LATEST, withBlock(SHELL, '{"format":"bento/slides","title":"<b>x</b>"}'), 'bento-slides'), /not in the form Bento writes/, 'a block with a raw < is not carried (Bento always escapes it)')
+refuses(() => spliceVerbatim(LATEST, withBlock(SHELL, '\n'), 'bento-slides'), /empty document block/, 'an empty block (a fresh app) is refused')
+refuses(() => spliceVerbatim(LATEST, withBlock(SHELL, '{nope'), 'bento-slides'), /not valid JSON/, 'a block that is not JSON is refused')
+refuses(() => spliceVerbatim(LATEST, withBlock(SHELL, '{"format":"bento/spaces","pages":[]}'), 'bento-slides'), /document is bento\/spaces/, 'a document of another format is refused')
+
+console.log('on the page: the conversion table')
+{
+ const asked: string[] = []
+ const env: Env = { async shell(appId) { asked.push(appId ?? ''); return { version: '9.9.9', html: LATEST } } }
+ const d = detect('Board pack.bento.html', new TextEncoder().encode(encrypted))
+ const opts = optionsFor(d).filter((o) => o.ok).map((o) => o.conversion.id)
+ ok(JSON.stringify(opts) === '["update-shell"]', `an encrypted file is offered exactly the rescue (${opts})`)
+ const c = CONVERSIONS.find((x) => x.id === 'update-shell')!
+ const r = await c.run(d, env)
+ ok(asked.join() === 'bento-slides' && block(new TextDecoder().decode(r.bytes)) === body, 'it fetches the shell of the file\'s own app and carries the block byte for byte')
+ ok(/still encrypted/.test(r.meta ?? '') && /no password was needed/.test(r.meta ?? ''), `it says so in words ("${r.meta}")`)
+ const plain = detect('deck.bento.html', new TextEncoder().encode(withBlock(SHELL, '\n' + JSON.stringify(doc) + '\n')))
+ ok(optionsFor(plain).filter((o) => o.ok).map((o) => o.conversion.id).includes('update-shell'), 'a plain deck is offered it too, beside PowerPoint')
+ const old: Env = { async shell() { return { version: '1.2.8', html: LATEST } } }
+ let mo = ''
+ try { await c.run(d, old) } catch (e) { mo = (e as Error).message }
+ ok(/1\.2\.8, which can’t open password-protected files/.test(mo), `an encrypted deck is NOT moved onto a release that can't open it ("${mo}")`)
+ const r9 = await c.run(d, { async shell() { return { version: '1.2.9', html: LATEST } } })
+ ok(block(new TextDecoder().decode(r9.bytes)) === body, 'onto 1.2.9 it is')
+ const rp = await c.run(plain, old)
+ ok(/<title>Board pack — Q3<\/title>/.test(new TextDecoder().decode(rp.bytes)), 'a plain deck\'s own title does come along')
+ ok(rp.bytes.length > 0, 'a plain deck may still move onto 1.2.8 (only opening encrypted files was broken)')
+ const nope: Env = { async shell() { throw new Error('could not reach the release server (404)') } }
+ const sp = detect('notes.bento.html', new TextEncoder().encode(withBlock(SHELL.replace('content="bento-slides"', 'content="bento-spaces"'), '{"format":"bento/spaces","pages":[]}')))
+ let m = ''
+ try { await c.run(sp, nope) } catch (e) { m = (e as Error).message }
+ ok(/no published release of bento\/spaces yet/.test(m), `an app with no published release says so plainly ("${m}")`)
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/site-src/convert.html b/site-src/convert.html
index 6a4f6229..2307aa48 100644
--- a/site-src/convert.html
+++ b/site-src/convert.html
@@ -104,12 +104,12 @@ footer{border-top:1px solid var(--line);margin-top:56px;padding:22px 0;color:var
<p class="private"><span aria-hidden="true">🔒</span><span><strong>Your file never leaves this device.</strong>
Conversion runs entirely in this browser tab. Nothing is uploaded, and this page runs no analytics.
- When it makes a bento/slides deck, it downloads the latest bento/slides app and its signed release record, so that the app it puts your deck into is verified as genuine. Nothing else is downloaded.</span></p>
+ When it makes a Bento file, it downloads the latest version of that Bento app and its signed release record, so that the app it puts your document into is verified as genuine. Nothing else is downloaded.</span></p>
<h2 class="step"><span class="num">1</span> Choose a file</h2>
<label id="drop">
<strong id="drop-title">Drop a file here, or choose one</strong>
- <span class="hint" id="drop-hint">A PowerPoint deck (.pptx), a bento/slides deck (.bento.html), or a deck’s document JSON. Up to <span id="limit">100 MB</span>.</span>
+ <span class="hint" id="drop-hint">A PowerPoint deck (.pptx), any Bento file (.bento.html), including one that won’t open, or a deck’s document JSON. Up to <span id="limit">100 MB</span>.</span>
<input id="file" type="file" accept=".pptx,.html,.htm,.json,application/vnd.openxmlformats-officedocument.presentationml.presentation,text/html,application/json">
</label>
<p class="sample">Just looking? <button type="button" class="linkbtn" id="sample">Try it with a sample deck</button></p>