Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

Signed self-update: About dialog, offline-key release signing, stable docId

nyblnetcc76b365743d
diff --git a/CLAUDE.md b/CLAUDE.md
index 43b2658f..5a3e6baf 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -31,6 +31,17 @@ One HTML file = the document + viewer + editor. See `README.md` for the vision.
visually on canvas (`editor/patheditor.ts`): draggable anchors auto-smoothed
Catmull-Rom→cubic bezier; the stored path is RELATIVE to the element's rest
position (first anchor = rest position; committing moves the element there).
+- `src/update.ts` — signed self-update: About dialog (topbar logo) checks a
+ release manifest ON USER CLICK ONLY (`bento.page`; dev override localStorage
+ 'bento-update-url'), verifies ECDSA P-256 signature against the embedded
+ PUBLIC_KEY_JWK + sha256 of the fetched shell + version monotonicity, then
+ re-splices the current doc into the new shell (`save.serializeWith`) and
+ downloads it as a NEW file (original untouched = rollback). APP_VERSION baked
+ from package.json via vite define. Private key: `scripts/keygen.mjs` →
+ `~/.bento/release-key.json` (offline, NEVER commit/CI); sign releases with
+ `scripts/sign-release.mjs`. Docs carry a stable `docId` (uuid, minted at
+ creation/load) — identity for future sync/merge; never regenerate it.
+ Scripting: `window.bento.updates.{version,check,build,apply}`.
- `src/charts.ts` — ECharts (Apache-2.0, svg renderer only, tree-shaken:
bar/line/pie/scatter + grid/tooltip/legend/dataZoom/title/dataset). A `chart`
element stores a PURE-JSON option (template-string formatters, never
diff --git a/docs/architecture.md b/docs/architecture.md
index 428c47fd..44237988 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -263,3 +263,33 @@ Things generators and future format revisions must not break:
for future hosting).
5. Motion paths are stored relative to the element's rest position; the first
path point is that position by definition.
+6. Every document carries a stable `docId` (uuid, minted at creation, minted
+ on load for pre-docId files). It is identity for future sync/share/merge —
+ never derive it from content, never regenerate it on save.
+
+## 7. Self-update (signed releases)
+
+A shipped file pins its runtime forever — it never needs the network. On
+**user request only** (About dialog via the topbar logo, or
+`window.bento.updates`), it can ask the release origin for a newer shell and
+rebuild itself as *same document, newer app*:
+
+```
+check GET manifest.json { payload: "<json string>", sig: base64 }
+verify ECDSA P-256 / SHA-256 over the payload's exact bytes, against
+ PUBLIC_KEY_JWK embedded in every shell (src/update.ts); then
+ require payload.version > APP_VERSION (no downgrade replay)
+fetch GET payload.url → bytes; sha256(bytes) must equal payload.sha256
+splice DOMParser the new shell → save.serializeWith(shell, doc)
+deliver downloaded as a NEW file — the on-disk original is its own rollback
+```
+
+- `APP_VERSION` is baked at build from `slides/package.json` (vite `define`).
+- The private key lives offline (`scripts/keygen.mjs` →
+ `~/.bento/release-key.json`, never in repo or CI); `scripts/sign-release.mjs`
+ hashes the built shell and writes the signed manifest. A compromised release
+ host cannot forge an update without that key. Rotating the key orphans every
+ shipped file — guard the key instead.
+- Privacy: the check is a bare GET with no identifiers, never automatic.
+- Update channel = signed **code**; future sync channel = inert **data**
+ (invariant 3). Never mix the two.
diff --git a/scripts/keygen.mjs b/scripts/keygen.mjs
new file mode 100644
index 00000000..577c6162
--- /dev/null
+++ b/scripts/keygen.mjs
@@ -0,0 +1,36 @@
+#!/usr/bin/env node
+// One-time: generate the Bento release signing keypair (ECDSA P-256).
+//
+// node scripts/keygen.mjs [key-file]
+//
+// The PRIVATE key is written to ~/.bento/release-key.json (chmod 600) —
+// it must never enter the repository or any CI secret store; releases are
+// signed locally with scripts/sign-release.mjs. The PUBLIC key is printed
+// for embedding in slides/src/update.ts (PUBLIC_KEY_JWK). Every shipped
+// Bento file verifies update manifests against that embedded public key,
+// so a compromised release host cannot push code without this private key.
+
+import { generateKeyPairSync } from 'node:crypto'
+import { mkdirSync, writeFileSync, existsSync, chmodSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join, dirname } from 'node:path'
+
+const keyPath = process.argv[2] ?? join(homedir(), '.bento', 'release-key.json')
+if (existsSync(keyPath)) {
+ console.error(`Refusing to overwrite existing key at ${keyPath}`)
+ console.error('If you really mean to rotate keys, move the old file away first —')
+ console.error('files already shipped only trust the OLD public key.')
+ process.exit(1)
+}
+
+const { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' })
+const priv = privateKey.export({ format: 'jwk' })
+const pub = publicKey.export({ format: 'jwk' })
+
+mkdirSync(dirname(keyPath), { recursive: true })
+writeFileSync(keyPath, JSON.stringify({ kind: 'bento-release-key', private: priv, public: pub }, null, 2) + '\n')
+chmodSync(keyPath, 0o600)
+
+console.log(`Private key written to ${keyPath} (keep offline, never commit).`)
+console.log('\nEmbed this public key as PUBLIC_KEY_JWK in slides/src/update.ts:\n')
+console.log(JSON.stringify(pub, null, 2))
diff --git a/scripts/sign-release.mjs b/scripts/sign-release.mjs
new file mode 100644
index 00000000..2b05c313
--- /dev/null
+++ b/scripts/sign-release.mjs
@@ -0,0 +1,72 @@
+#!/usr/bin/env node
+// Sign a Bento Slides release: produce the manifest.json that shipped files
+// poll (on user request only) to learn about updates.
+//
+// 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]
+//
+// The manifest is { payload: "<json string>", sig: "<base64>" } — the
+// signature covers the exact payload string bytes (no canonicalization
+// games), ECDSA P-256 / SHA-256 in IEEE P1363 form so browsers can verify
+// 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.
+
+import { createHash, createPrivateKey, createPublicKey, sign, verify } from 'node:crypto'
+import { readFileSync, writeFileSync } 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)))
+
+const args = process.argv.slice(2)
+const shellPath = args.find((a) => !a.startsWith('--'))
+if (!shellPath) {
+ console.error('Usage: node scripts/sign-release.mjs <shell.html> [--url U] [--version V] [--notes N] [--key K] [--out O]')
+ process.exit(1)
+}
+const opt = (name, fallback) => {
+ const i = args.indexOf(`--${name}`)
+ return i >= 0 && args[i + 1] ? args[i + 1] : 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 outPath = opt('out', join(dirname(shellPath), 'manifest.json'))
+
+const shell = readFileSync(shellPath)
+const sha256 = createHash('sha256').update(shell).digest('hex')
+
+const payload = JSON.stringify({
+ app: 'bento-slides',
+ version,
+ sha256,
+ url,
+ ...(notes ? { notes } : {}),
+ 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.')
+ process.exit(1)
+}
+
+writeFileSync(outPath, JSON.stringify({ payload, sig: sig.toString('base64') }, null, 2) + '\n')
+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}`)
+console.log(` out ${outPath}`)
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index 3a42e6a3..58828969 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -3,10 +3,12 @@
import type { Store } from '../store'
import {
+ FORMAT_VERSION,
applyLayout, builtinLayouts, defaultChart, defaultImage, defaultShape, defaultText,
instantiateLayout, layoutElementIds, uid,
type ShapeKind, type Slide, type SlideElement,
} from '../model'
+import { APP_VERSION, applyUpdate, checkForUpdates } from '../update'
import { CHART_PRESETS } from '../charts'
import { renderSlide, renderThumbnail } from '../render'
import { SlideCanvas } from './canvas'
@@ -72,6 +74,9 @@ export class Editor {
`<rect x="14" y="5" width="13" height="10" rx="2.5" fill="#F7A600"/>` +
`<rect x="14" y="17" width="13" height="10" rx="2.5" fill="#E9EDF3"/>` +
`</svg> <b>Bento</b>&nbsp;Slides`
+ logo.title = 'About Bento Slides — version, updates, licenses'
+ logo.style.cursor = 'pointer'
+ logo.addEventListener('click', () => this.openAbout())
const title = document.createElement('input')
title.className = 'ed-title'
title.value = this.store.doc.title
@@ -697,6 +702,97 @@ export class Editor {
// --- toast ------------------------------------------------------------------
+ // --- about & updates ------------------------------------------------------
+
+ /** About dialog: version, user-initiated update check, licenses. */
+ private openAbout() {
+ document.querySelector('.ed-about-overlay')?.remove()
+ const overlay = div('ed-about-overlay')
+ const box = div('ed-about')
+
+ const head = div('ed-about-head')
+ head.innerHTML =
+ `<svg viewBox="0 0 32 32" width="28" height="28" aria-hidden="true">` +
+ `<rect width="32" height="32" rx="7" fill="#1E2A3A"/>` +
+ `<rect x="5" y="5" width="6" height="22" rx="2.5" fill="#5B8DEF"/>` +
+ `<rect x="14" y="5" width="13" height="10" rx="2.5" fill="#F7A600"/>` +
+ `<rect x="14" y="17" width="13" height="10" rx="2.5" fill="#E9EDF3"/>` +
+ `</svg><div><b>Bento Slides</b><span>v${APP_VERSION} · format v${FORMAT_VERSION}</span></div>`
+ box.appendChild(head)
+
+ const status = div('ed-about-status')
+ status.textContent = 'This file carries its own app — it works offline, forever, as is.'
+
+ const row = div('ed-about-row')
+ const checkB = document.createElement('button')
+ checkB.className = 'ed-btn'
+ checkB.textContent = 'Check for updates'
+ checkB.addEventListener('click', async () => {
+ checkB.disabled = true
+ status.textContent = 'Checking…'
+ const result = await checkForUpdates()
+ checkB.disabled = false
+ if (result.status === 'current') {
+ status.textContent = `You're on the latest version (v${result.version}).`
+ } else if (result.status === 'error') {
+ status.textContent = `Couldn't check: ${result.message}`
+ } else {
+ const { release } = result
+ status.textContent = ''
+ const line = div('ed-about-new')
+ line.textContent = `Version ${release.version} is available.`
+ status.appendChild(line)
+ if (release.notes) {
+ const notes = div('ed-about-notes')
+ notes.textContent = release.notes
+ status.appendChild(notes)
+ }
+ const getB = document.createElement('button')
+ getB.className = 'ed-btn ed-btn-primary'
+ getB.textContent = 'Download updated copy'
+ getB.title = 'Verifies the new app’s signature, puts this document inside it, and downloads the result. The file you have now is not touched.'
+ getB.addEventListener('click', async () => {
+ getB.disabled = true
+ getB.textContent = 'Verifying…'
+ try {
+ await applyUpdate(release, this.store.doc)
+ getB.textContent = 'Downloaded ✓'
+ this.toast('Updated copy downloaded — replace your old file with it')
+ } catch (err: any) {
+ getB.remove()
+ status.textContent = `Update failed: ${err?.message ?? err}`
+ }
+ })
+ status.appendChild(getB)
+ }
+ })
+ row.appendChild(checkB)
+ box.append(row, status)
+
+ const fine = div('ed-about-fine')
+ fine.innerHTML =
+ `Checking contacts the release server once and sends nothing about you or this document.<br>` +
+ `Includes reveal.js, Moveable, Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) — full notices travel in this file’s source.`
+ box.appendChild(fine)
+
+ overlay.appendChild(box)
+ const close = () => {
+ overlay.remove()
+ document.removeEventListener('keydown', onKey, true)
+ }
+ const onKey = (ev: KeyboardEvent) => {
+ if (ev.key === 'Escape') {
+ ev.stopPropagation()
+ close()
+ }
+ }
+ overlay.addEventListener('click', (ev) => {
+ if (ev.target === overlay) close()
+ })
+ document.addEventListener('keydown', onKey, true)
+ document.body.appendChild(overlay)
+ }
+
toast(message: string) {
document.querySelector('.ed-toast')?.remove()
const t = div('ed-toast')
diff --git a/slides/src/main.ts b/slides/src/main.ts
index 5ad1ad4f..7c746596 100644
--- a/slides/src/main.ts
+++ b/slides/src/main.ts
@@ -4,6 +4,7 @@
import './styles.css'
import { anim } from './anim'
import { capturePristine, readEmbeddedDoc, serializeFile } from './save'
+import { APP_VERSION, checkForUpdates, buildUpdatedFile, applyUpdate } from './update'
import { parseDoc, starterDoc } from './model'
import { injectFonts } from './fonts'
import { Store } from './store'
@@ -58,6 +59,18 @@ if (location.hash === '#present') {
},
/** animation engine, exposed for scripting/diagnostics */
anim,
+ /**
+ * Self-update surface (all user/tooling-initiated, never automatic):
+ * check() fetches + signature-verifies the release manifest; build()
+ * returns the updated file's html (this doc inside the new shell);
+ * apply() downloads it. check(url) accepts an override for testing.
+ */
+ updates: {
+ version: APP_VERSION,
+ check: (url?: string) => checkForUpdates(url),
+ build: (release: any) => buildUpdatedFile(release, store.doc),
+ apply: (release: any) => applyUpdate(release, store.doc),
+ },
/**
* Flat list of every review comment thread — the entry point for tooling
* and AI agents processing the deck ("fix everything people flagged"):
diff --git a/slides/src/model.ts b/slides/src/model.ts
index 02548968..fd5b9b2a 100644
--- a/slides/src/model.ts
+++ b/slides/src/model.ts
@@ -206,6 +206,12 @@ export interface Slide {
export interface BentoDoc {
format: typeof FORMAT
version: number
+ /**
+ * Stable per-document identity (uuid), minted at creation and preserved
+ * for the document's whole life — the rendezvous key for future
+ * sync / share / merge features. Never derived from content.
+ */
+ docId: string
title: string
/** slide coordinate space, px */
size: { width: number; height: number }
@@ -459,10 +465,14 @@ export function layoutElementIds(doc: BentoDoc): Set<string> {
return ids
}
+export const newDocId = (): string =>
+ typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : uid('doc')
+
export function newDoc(): BentoDoc {
return {
format: FORMAT,
version: FORMAT_VERSION,
+ docId: newDocId(),
title: 'Untitled',
size: { width: 1280, height: 720 },
theme: {
@@ -480,6 +490,9 @@ export function parseDoc(json: string): BentoDoc | null {
try {
const doc = JSON.parse(json)
if (doc && doc.format === FORMAT && Array.isArray(doc.slides) && doc.slides.length > 0) {
+ // Documents from before docId existed get one minted here; it persists
+ // on the next save and stays stable from then on.
+ if (typeof doc.docId !== 'string' || !doc.docId) doc.docId = newDocId()
return doc as BentoDoc
}
} catch {
diff --git a/slides/src/save.ts b/slides/src/save.ts
index 3f23c05e..b27aa7d4 100644
--- a/slides/src/save.ts
+++ b/slides/src/save.ts
@@ -25,10 +25,13 @@ export function readEmbeddedDoc(): string | null {
return text || null
}
-/** The full .bento.html file content with `doc` embedded. */
-export function serializeFile(doc: BentoDoc): string {
- if (!pristine) throw new Error('capturePristine() was not called at boot')
- const clone = pristine.cloneNode(true) as Document
+/**
+ * Serialize `doc` into an arbitrary app shell (a parsed Bento HTML document).
+ * Used with the boot-time pristine copy on every save, and by the self-update
+ * flow with a freshly fetched NEWER shell — same document, new app around it.
+ */
+export function serializeWith(shell: Document, doc: BentoDoc): string {
+ const clone = shell.cloneNode(true) as Document
let block = clone.getElementById(DATA_BLOCK_ID)
if (!block) {
@@ -43,15 +46,21 @@ export function serializeFile(doc: BentoDoc): string {
const title = clone.querySelector('title')
if (title) title.textContent = doc.title + ' — Bento Slides'
- let html = '<!DOCTYPE html>\n' + clone.documentElement.outerHTML
+ const html = '<!DOCTYPE html>\n' + clone.documentElement.outerHTML
// Belt-and-braces: an unescaped close tag anywhere in generated output would
// corrupt the file; this should never trigger given the escaping above.
- if (html.split(SCRIPT_CLOSE).length !== pristine.querySelectorAll('script').length + 1) {
+ if (html.split(SCRIPT_CLOSE).length !== clone.querySelectorAll('script').length + 1) {
console.warn('bento: unexpected script-close count in serialized file')
}
return html
}
+/** The full .bento.html file content with `doc` embedded. */
+export function serializeFile(doc: BentoDoc): string {
+ if (!pristine) throw new Error('capturePristine() was not called at boot')
+ return serializeWith(pristine, doc)
+}
+
export function suggestedFileName(doc: BentoDoc): string {
const base = doc.title.replace(/[^\w\d-]+/g, '_').replace(/^_+|_+$/g, '') || 'Untitled'
return `${base}.bento.html`
@@ -88,7 +97,7 @@ async function writeHandle(handle: FsFileHandle, html: string) {
await writable.close()
}
-function download(html: string, name: string) {
+export function downloadFile(html: string, name: string) {
const url = URL.createObjectURL(new Blob([html], { type: 'text/html' }))
const a = document.createElement('a')
a.href = url
@@ -114,7 +123,7 @@ export async function saveFile(doc: BentoDoc, forcePicker = false): Promise<Save
await writeHandle(fileHandle, html)
return 'saved'
}
- download(html, suggestedFileName(doc))
+ downloadFile(html, suggestedFileName(doc))
return 'downloaded'
}
diff --git a/slides/src/styles.css b/slides/src/styles.css
index 14e7349e..7108ee0f 100644
--- a/slides/src/styles.css
+++ b/slides/src/styles.css
@@ -411,6 +411,63 @@ html, body {
}
.ed-hint code { font-size: 10.5px; word-break: break-all; }
+/* ————— about dialog ————— */
+
+.ed-about-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 1500;
+ background: rgb(15 23 36 / 0.38);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+.ed-about {
+ width: 360px;
+ background: #fff;
+ border-radius: 14px;
+ box-shadow: 0 18px 50px rgb(15 23 36 / 0.3);
+ padding: 20px;
+ font-size: 13px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+.ed-about-head {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+.ed-about-head b { font-size: 15px; display: block; }
+.ed-about-head span { font-size: 11.5px; color: var(--muted); }
+.ed-about-row { display: flex; gap: 8px; }
+.ed-about-status {
+ min-height: 18px;
+ color: var(--ink);
+ line-height: 1.5;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ align-items: flex-start;
+}
+.ed-about-new { font-weight: 600; }
+.ed-about-notes {
+ color: var(--muted);
+ background: var(--chrome);
+ border-radius: 8px;
+ padding: 7px 10px;
+ white-space: pre-wrap;
+ max-height: 140px;
+ overflow: auto;
+}
+.ed-about-fine {
+ font-size: 10.5px;
+ line-height: 1.5;
+ color: var(--muted);
+ border-top: 1px solid var(--chrome);
+ padding-top: 10px;
+}
+
/* ————— toast ————— */
.ed-toast {
diff --git a/slides/src/update.ts b/slides/src/update.ts
new file mode 100644
index 00000000..a5943880
--- /dev/null
+++ b/slides/src/update.ts
@@ -0,0 +1,143 @@
+// Self-update: a shipped Bento file can, ON USER REQUEST ONLY, ask the
+// release origin whether a newer app shell exists, and rebuild itself as
+// "same document, newer app" — the data block re-spliced into the fetched
+// shell via the exact machinery every save already uses.
+//
+// Trust model (see docs/architecture.md):
+// - The manifest is SIGNED (ECDSA P-256 / SHA-256) with an offline key; the
+// matching public key is embedded below in every shipped shell. A
+// compromised host or repo cannot forge a release without that key.
+// - The manifest pins the new shell's sha256; the download is hashed and
+// compared before anything is spliced.
+// - Only strictly NEWER versions are ever offered (no downgrade replay).
+// - Nothing is automatic and nothing identifies the user or the document:
+// the check is a bare GET, fired only from the About dialog / scripting.
+//
+// The result is always a NEW downloaded file — the update flow never touches
+// the file on disk, so the original is its own rollback.
+
+import type { BentoDoc } from './model'
+import { serializeWith, suggestedFileName, downloadFile } from './save'
+
+declare const __APP_VERSION__: string
+
+/** Version of the running app shell (baked in at build from package.json). */
+export const APP_VERSION: string = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '0.0.0'
+
+/** Where shipped files look for releases. Dev override: localStorage 'bento-update-url'. */
+export const UPDATE_MANIFEST_URL = 'https://bento.page/releases/slides/manifest.json'
+
+// Release signing PUBLIC key. The private half lives offline with the
+// maintainer (scripts/keygen.mjs → ~/.bento/release-key.json) and signs
+// manifests via scripts/sign-release.mjs. Rotating this key orphans every
+// previously shipped file — guard the private key instead.
+const PUBLIC_KEY_JWK = {
+ kty: 'EC',
+ crv: 'P-256',
+ x: 'GMHSKwWcAoJVq-Dz1ZxWZM6TXATWIKbaQBpjoTystH8',
+ y: 'flFNzbdXCmJN8RQYCeG71rBZnnbN-MCEnp1EbCLFrj0',
+} as const
+
+export interface ReleaseInfo {
+ app: string
+ version: string
+ /** hex sha256 of the release shell's bytes */
+ sha256: string
+ /** absolute URL of the release shell */
+ url: string
+ notes?: string
+ at?: string
+}
+
+export type UpdateCheck =
+ | { status: 'current'; version: string }
+ | { status: 'update'; release: ReleaseInfo }
+ | { status: 'error'; message: string }
+
+const b64ToBytes = (b64: string) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0))
+const hex = (buf: ArrayBuffer) =>
+ [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('')
+
+/** Dotted-numeric compare: 0.2.0 > 0.1.9 > 0.1 — positive when a > b. */
+export function compareVersions(a: string, b: string): number {
+ const pa = a.split('.').map(Number)
+ const pb = b.split('.').map(Number)
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
+ const d = (pa[i] || 0) - (pb[i] || 0)
+ if (d) return d
+ }
+ return 0
+}
+
+/**
+ * Verify the manifest signature and return its payload. The signature covers
+ * the payload's exact string bytes — no JSON canonicalization involved.
+ */
+async function verifyManifest(raw: string): Promise<ReleaseInfo> {
+ let payload: string, sig: string
+ try {
+ ;({ payload, sig } = JSON.parse(raw))
+ } catch {
+ throw new Error('the release manifest is not valid JSON')
+ }
+ if (typeof payload !== 'string' || typeof sig !== 'string')
+ throw new Error('the release manifest is malformed')
+
+ const key = await crypto.subtle.importKey(
+ 'jwk', PUBLIC_KEY_JWK as JsonWebKey,
+ { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify'],
+ )
+ const ok = await crypto.subtle.verify(
+ { name: 'ECDSA', hash: 'SHA-256' }, key,
+ b64ToBytes(sig), new TextEncoder().encode(payload),
+ )
+ if (!ok) throw new Error('the release signature is INVALID — refusing this update')
+
+ const info = JSON.parse(payload)
+ if (
+ info?.app !== 'bento-slides' ||
+ typeof info.version !== 'string' ||
+ !/^[0-9a-f]{64}$/i.test(info.sha256 ?? '') ||
+ typeof info.url !== 'string'
+ )
+ throw new Error('the release manifest payload is malformed')
+ return info as ReleaseInfo
+}
+
+/** Ask the release origin for the latest version. User-initiated only. */
+export async function checkForUpdates(manifestUrl?: string): Promise<UpdateCheck> {
+ const url = manifestUrl ?? localStorage.getItem('bento-update-url') ?? UPDATE_MANIFEST_URL
+ try {
+ const res = await fetch(url, { cache: 'no-store' })
+ if (!res.ok) throw new Error(`release server answered ${res.status}`)
+ const release = await verifyManifest(await res.text())
+ if (compareVersions(release.version, APP_VERSION) <= 0)
+ return { status: 'current', version: APP_VERSION }
+ return { status: 'update', release }
+ } catch (err: any) {
+ return { status: 'error', message: err?.message ?? String(err) }
+ }
+}
+
+/**
+ * Fetch the release shell, verify its hash against the signed manifest, and
+ * return the full updated .bento.html: this document inside the new app.
+ */
+export async function buildUpdatedFile(release: ReleaseInfo, doc: BentoDoc): Promise<string> {
+ 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))
+ if (digest !== release.sha256.toLowerCase())
+ throw new Error('the downloaded update failed its integrity check — refusing it')
+
+ const shell = new DOMParser().parseFromString(new TextDecoder().decode(bytes), 'text/html')
+ if (!shell.getElementById('bento-doc'))
+ throw new Error('the downloaded update is not a Bento shell')
+ return serializeWith(shell, doc)
+}
+
+/** Build the updated file and hand it to the user as a fresh download. */
+export async function applyUpdate(release: ReleaseInfo, doc: BentoDoc): Promise<void> {
+ downloadFile(await buildUpdatedFile(release, doc), suggestedFileName(doc))
+}
diff --git a/slides/vite.config.ts b/slides/vite.config.ts
index f401d5ab..166672d6 100644
--- a/slides/vite.config.ts
+++ b/slides/vite.config.ts
@@ -1,11 +1,17 @@
import { defineConfig } from 'vite'
import { viteSingleFile } from 'vite-plugin-singlefile'
+import { readFileSync } from 'node:fs'
+
+const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
// base './' so builds open from file:// or any static host.
// SINGLEFILE=1 → everything (JS, CSS, assets) inlined into one HTML file:
// that file IS the Bento document format.
export default defineConfig({
base: './',
+ // The app version baked into every shipped shell — what update checks
+ // compare against the release manifest. Single source: package.json.
+ define: { __APP_VERSION__: JSON.stringify(pkg.version) },
plugins: [...(process.env.SINGLEFILE ? [viteSingleFile()] : [])],
build: {
// Keep asset inlining aggressive; a Bento file must have zero external requests.