Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
Guestbook daemon on Cloudflare: Worker + KV, cron archivist, epoch rolls
nyblnet3de8074f9e1f
diff --git a/.gitignore b/.gitignoreindex fd107f7c..9d6177a1 100644--- a/.gitignore+++ b/.gitignore@@ -11,3 +11,4 @@ testing/*.tsbuildinfosite/working/+.dev.varsdiff --git a/scripts/build-example-decks.mjs b/scripts/build-example-decks.mjsindex d0e7a05d..7a3d1596 100644--- a/scripts/build-example-decks.mjs+++ b/scripts/build-example-decks.mjs@@ -31,13 +31,23 @@ const FONTS = {}const FR = "Fraunces, Georgia, serif"const IN = "'Instrument Sans', 'Helvetica Neue', sans-serif"-const MONO = "'SF Mono', 'Courier New', monospace"+// Robust monospace stack. 'SF Mono' alone falls straight through to an ugly+// 'Courier New' in Chrome on macOS (Apple doesn't expose SF Mono to the web),+// so lead with ui-monospace and name the fonts that ARE reachable per platform.+const MONO_STACK = "ui-monospace, 'SF Mono', Menlo, Consolas, 'Liberation Mono', 'Courier New', monospace"+const MONO = MONO_STACK// public-domain photos (see scripts/gallery-photos/SOURCES.md), embedded as// data-URI assets so the decks stay fully self-containedconst photo = (name) =>'data:image/jpeg;base64,' + readFileSync(join(root, 'scripts/gallery-photos', name)).toString('base64')+// embedded webfont files (woff2) — same technique as photo(), so a deck that+// wants a specific typeface stays self-contained instead of leaning on a+// system font that may not exist in the viewer's browser+const fontFile = (name) =>+ 'data:font/woff2;base64,' + readFileSync(join(root, 'scripts/gallery-fonts', name)).toString('base64')+// ——— tiny builders ———————————————————————————————————————————————let uid = 0const id = (p) => `${p}-${(++uid).toString(36)}`@@ -100,8 +110,8 @@ const doc = (o) => ({format: 'bento/slides', version: 1, title: o.title,size: { width: 1280, height: 720 },theme: o.theme, template: true,- ...(o.withFonts ? { assets: { ...FONTS.assets, ...(o.assets ?? {}) }, fonts: FONTS.fonts }- : (o.assets ? { assets: o.assets } : {})),+ ...(o.withFonts ? { assets: { ...FONTS.assets, ...(o.assets ?? {}) }, fonts: [...FONTS.fonts, ...(o.fonts ?? [])] }+ : (o.assets ? { assets: o.assets, ...(o.fonts ? { fonts: o.fonts } : {}) } : {})),...(o.present ? { present: o.present } : {}),slides: o.slides, modified: new Date().toISOString(),})@@ -169,15 +179,15 @@ function deckSignal() {const s3b = slide({id: 'sig-floor', background: INK, transition: 'fade',- notes: 'The photo essay beat. A full-bleed public-domain photograph (Marjory Collins, NYT composing room, 1942 — Library of Congress) with a slow ken-burns drift, an ink scrim, and one serif line. Swap the photo, keep the recipe: image → scrim → words.',+ notes: 'The photo essay beat. A full-bleed public-domain photograph (Marjory Collins, New York Times pressroom, 1942 — Library of Congress) with a slow ken-burns drift, an ink scrim, and one serif line. A DIFFERENT frame from the cover shot on purpose — the cover sets the type, this beat prints it. Swap the photo, keep the recipe: image → scrim → words.',elements: [- img({ asset: 'ph-press', x: 0, y: 0, w: 1280, h: 720, fx: { ambient: 'kenburns', ken: { dir: 'drift', scale: 1.09, duration: 22 } } }),+ img({ asset: 'ph-press2', x: 0, y: 0, w: 1280, h: 720, fx: { ambient: 'kenburns', ken: { dir: 'drift', scale: 1.09, duration: 22 } } }),shape('rect', { x: 0, y: 0, w: 1280, h: 720, fill: 'rgba(15,14,11,0.58)' }),shape('rect', { x: 0, y: 430, w: 1280, h: 290, fill: 'rgba(15,14,11,0.4)', fillGradient: grad(180, [0, 'rgba(15,14,11,0)'], [1, 'rgba(15,14,11,0.85)']) }),kick(96, 96, 'THE FLOOR'),shape('rect', { x: 96, y: 130, w: 220, h: 2, fill: RED }),text({ x: 90, y: 420, w: 1000, h: 220, html: 'Set by hand,<br>read by thousands.', fontSize: 76, fontFamily: FR, fontWeight: 900, color: BONE, lineHeight: 1.02, fx: { enter: 'fade-up' } }),- text({ x: 96, y: 640, w: 900, h: 24, html: 'COMPOSING ROOM, 1942 · LIBRARY OF CONGRESS — PUBLIC DOMAIN', fontSize: 10, fontWeight: 600, letterSpacing: 3, color: 'rgba(239,237,228,0.55)', fx: { enter: 'fade-up', order: 2 } }),+ text({ x: 96, y: 640, w: 900, h: 24, html: 'NEW YORK TIMES PRESSROOM, 1942 · LIBRARY OF CONGRESS — PUBLIC DOMAIN', fontSize: 10, fontWeight: 600, letterSpacing: 3, color: 'rgba(239,237,228,0.55)', fx: { enter: 'fade-up', order: 2 } }),text({ x: 1150, y: 654, w: 80, h: 24, html: '04', fontSize: 13, fontWeight: 600, color: 'rgba(239,237,228,0.6)', align: 'right', fontFamily: MONO }),],})@@ -230,7 +240,10 @@ function deckSignal() {return doc({title: 'Signal — editorial type template', withFonts: true,- assets: { 'ph-press': photo('signal-press.jpg') },+ assets: {+ 'ph-press': photo('signal-press.jpg'),+ 'ph-press2': photo('signal-press2.jpg'),+ },theme: { background: BONE, color: INK, accent: RED, fontFamily: IN },slides: [s1, s2, s3, s3b, s4, s5, s6],})@@ -353,6 +366,11 @@ function deckTerra() {// Void black, electric cyan→violet gradients, glow, orbiting particles.// ═══════════════════════════════════════════════════════════════════════function deckOrbital() {+ // Orbital embeds Space Mono (OFL) for its HUD-style technical labels — the+ // deck's mono was the one place a system font ('SF Mono') showed through as+ // Courier in Chrome. Embedding keeps the readouts crisp and on-brand+ // everywhere; MONO shadows the module const for this deck only.+ const MONO = "'Space Mono', " + MONO_STACKconst VOID = '#05060E', DEEP = '#0B0E1E', CYAN = '#38E1FF', VIOLET = '#7A5CFF', MAG = '#FF4FA3'const DIM = 'rgba(178,196,224,0.62)'const GRAD_CY = grad(30, [0, CYAN], [1, VIOLET])@@ -483,7 +501,13 @@ function deckOrbital() {'ph-earth': photo('orbital-earth.jpg'), 'ph-nebula': photo('orbital-nebula.jpg'),'ph-stars': photo('orbital-stars.jpg'), 'ph-aurora': photo('orbital-aurora.jpg'),'ph-dragon': photo('orbital-dragon.jpg'),+ 'font-spacemono': fontFile('SpaceMono-400-latin.woff2'),+ 'font-spacemono-bold': fontFile('SpaceMono-700-latin.woff2'),},+ fonts: [+ { family: 'Space Mono', asset: 'font-spacemono', weight: '400' },+ { family: 'Space Mono', asset: 'font-spacemono-bold', weight: '700' },+ ],theme: { background: VOID, color: '#EAF4FF', accent: CYAN, fontFamily: IN },present: { progress: true },slides: [s1, s2, s2b, s3, st1, st2, s4, s5],diff --git a/scripts/build-guestbook.mjs b/scripts/build-guestbook.mjsindex 013ed6bc..462971a4 100644--- a/scripts/build-guestbook.mjs+++ b/scripts/build-guestbook.mjs@@ -1,20 +1,21 @@#!/usr/bin/env node// U2: the public guestbook deck — one live-collab file anyone can open and// sign. Minting fresh credentials IS the reset mechanism ("epochs, not-// moderation" — see working/guestbook-design.md).+// moderation" — see working/guestbook-design.md). The deck definition lives+// in scripts/guestbook-deck.mjs, shared with the Cloudflare daemon+// (server/guestbook-daemon/) which is the SUSTAINABLE home of rolls and+// snapshots — this local builder remains for seeding and as a fallback.//// node scripts/build-guestbook.mjs [--host wss://sync.bento.page] [--out <file>]//-// Behaviour: if the out file already exists, it is archived to-// working/guestbook-epochs/ and the new build gets epoch N+1 with FRESH-// room + key (the old room orphans instantly). Default out:-// working/guestbook-live/guestbook.bento.html — release.mjs ships that-// file to bento.page/guestbook.bento.html when it exists.+// If the out file exists it is archived to working/guestbook-epochs/ and the+// new build gets epoch N+1 with FRESH room + key.import { webcrypto as crypto } from 'node:crypto'import { existsSync, mkdirSync, readFileSync, writeFileSync, copyFileSync } from 'node:fs'import { dirname, join } from 'node:path'import { fileURLToPath } from 'node:url'+import { buildGuestbookDoc, spliceDoc } from './guestbook-deck.mjs'const root = dirname(dirname(fileURLToPath(import.meta.url)))const args = process.argv.slice(2)@@ -29,13 +30,10 @@ const shell = readFileSync(join(root, 'slides/dist-single/Bento_Slides.bento.htmconst fontSrc = readFileSync(join(root, 'slides/src/fontdata.ts'), 'utf8')const font = (n) => fontSrc.match(new RegExp(`export const ${n}\\s*=\\s*'(data:[^']+)'`))[1]-// ——— credentials, exactly like the app mints them (online.ts) ———————const b64u = (bytes) => Buffer.from(bytes).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')const rnd = (n) => { const b = new Uint8Array(n); crypto.getRandomValues(b); return b }const collab = { room: `${host}/d/r${b64u(rnd(12))}`, key: b64u(rnd(32)), on: true }-const docId = crypto.randomUUID()-// ——— epoch bookkeeping ————————————————————————————————————————————let epoch = 1if (existsSync(out)) {const prev = readFileSync(out, 'utf8')@@ -48,116 +46,15 @@ if (existsSync(out)) {console.log(`archived epoch ${epoch - 1} → working/guestbook-epochs/`)}-// ——— the deck ————————————————————————————————————————————————————-const INK = '#0D1B2E', PANEL = '#16273E', PEACH = '#FF9E8A', PAPER = '#F2F0EA'-const STEEL = '#5E7699', TILE = '#F0EBE0', MIST = 'rgba(182,193,210,0.9)', MIST_DIM = 'rgba(182,193,210,0.5)'-const FR = 'Fraunces, Georgia, serif'-const IN = "'Instrument Sans', 'Helvetica Neue', sans-serif"--let uid = 0-const id = (p) => `${p}-${(++uid).toString(36)}`-const text = (o) => ({- id: o.id ?? id('t'), type: 'text', x: o.x, y: o.y, w: o.w, h: o.h,- rotation: o.rotation ?? 0, opacity: o.opacity ?? 1, html: o.html,- fontSize: o.fontSize ?? 24, fontFamily: o.fontFamily ?? IN,- fontWeight: o.fontWeight ?? 400, color: o.color ?? '#fff',- align: o.align ?? 'left', valign: o.valign ?? 'top', lineHeight: o.lineHeight ?? 1.3,- ...(o.letterSpacing != null ? { letterSpacing: o.letterSpacing } : {}),-})-const rect = (o) => ({- id: o.id ?? id('s'), type: 'shape', shape: o.shape ?? 'rect', x: o.x, y: o.y, w: o.w, h: o.h,- rotation: o.rotation ?? 0, opacity: o.opacity ?? 1, fill: o.fill ?? 'rgba(0,0,0,0)',- stroke: o.stroke ?? 'none', strokeWidth: o.strokeWidth ?? 0, radius: o.radius ?? 0,- ...(o.strokeStyle ? { strokeStyle: o.strokeStyle } : {}),+const doc = buildGuestbookDoc({+ epoch, docId: crypto.randomUUID(), collab,+ fonts: { fraunces: font('FRAUNCES_900'), instrument: font('INSTRUMENT_VAR') },})-const kick = (x, y, s, color = PEACH) =>- text({ x, y, w: 900, h: 24, html: s, fontSize: 13, fontWeight: 700, letterSpacing: 5, color })--const s1 = {- id: 'gb-welcome', background: INK, transition: 'none',- notes: 'The public guestbook: everyone holding this file is in the same live room, end-to-end encrypted. House rules on the slide. Epochs reset the room on a schedule — good walls are archived, vandalism simply evaporates.',- elements: [- rect({ id: 'gb-tile-a', x: 980, y: 110, w: 170, h: 170, fill: PEACH, radius: 30 }),- rect({ id: 'gb-tile-b', x: 1080, y: 310, w: 100, h: 150, fill: STEEL, radius: 22 }),- rect({ id: 'gb-tile-c', x: 930, y: 330, w: 100, h: 100, fill: TILE, radius: 20 }),- kick(96, 90, `THE GUESTBOOK — EPOCH ${epoch} · A PUBLIC EXPERIMENT`),- text({ x: 88, y: 140, w: 900, h: 220, html: 'Leave a mark.', fontSize: 110, fontFamily: FR, fontWeight: 900, color: '#fff', lineHeight: 1 }),- text({ x: 96, y: 360, w: 780, h: 100, html: 'Everyone with this file open is <b>in this deck with you, live</b> — end-to-end encrypted, no accounts. Pick a wall (→), add a note, a shape, a doodle. Set your name via the <b>Live</b> button so your cursor has one.', fontSize: 19, color: MIST, lineHeight: 1.6 }),- text({ x: 96, y: 500, w: 900, h: 120, fontSize: 16, color: MIST_DIM, lineHeight: 1.9, html:- '<b>House rules:</b> add, don’t wipe · be kind · anything goes except cruelty<br>' +- 'The room resets on a schedule — beautiful walls get archived forever, everything else evaporates.' }),- text({ x: 96, y: 655, w: 1000, h: 24, html: '→ THE WALLS ARE THAT WAY', fontSize: 12, fontWeight: 700, letterSpacing: 3, color: 'rgba(255,158,138,0.85)' }),- ],-}--const seeds = [- { html: 'the file is the room 🤯', color: PEACH, rot: -3 },- { html: 'hello from epoch ' + epoch, color: TILE, rot: 2 },- { html: 'no login. no cloud. just us.', color: STEEL, rot: -1 },- { html: 'sign below ↓', color: PEACH, rot: 1 },- { html: 'archive me, i’m beautiful', color: TILE, rot: -2 },- { html: 'CRDTs are magic', color: STEEL, rot: 3 },-]-const walls = seeds.map((seed, i) => ({- id: `gb-wall-${i + 1}`, background: i % 2 ? PANEL : INK, transition: 'fade',- notes: `Wall ${i + 1} of ${seeds.length}. Everything here was left by someone holding this file. Add yours anywhere — double-click to write, or drop shapes from the toolbar.`,- elements: [- text({ x: 40, y: 40, w: 600, h: 200, html: String(i + 1).padStart(2, '0'), fontSize: 180, fontFamily: FR, fontWeight: 900, color: i % 2 ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.045)' }),- kick(96, 84, `WALL ${String(i + 1).padStart(2, '0')} — SIGN ANYWHERE`, 'rgba(255,158,138,0.6)'),- rect({ x: 60, y: 130, w: 1160, h: 540, stroke: 'rgba(182,193,210,0.18)', strokeWidth: 1.5, radius: 18, strokeStyle: 'dashed' }),- text({ x: 140 + (i * 137) % 700, y: 190 + (i * 211) % 350, w: 420, h: 60, html: seed.html, fontSize: 30, fontFamily: i % 2 ? FR : IN, fontWeight: i % 2 ? 900 : 700, color: seed.color, rotation: seed.rot }),- ],-}))--const s8 = {- id: 'gb-how', background: PAPER, transition: 'fade',- notes: 'How it works: the collab keys live inside this file — possession is membership. The relay only ever sees ciphertext. Epochs: fresh keys are minted on reset, which orphans the old room instantly; saved copies keep working offline, which is rather the point.',- elements: [- kick(96, 96, 'HOW THIS WORKS', '#C25A43'),- text({ x: 90, y: 140, w: 1000, h: 110, html: 'The file is the room.', fontSize: 64, fontFamily: FR, fontWeight: 900, color: INK, lineHeight: 1 }),- text({ x: 96, y: 280, w: 1040, h: 260, fontSize: 20, color: 'rgba(20,34,54,0.78)', lineHeight: 1.85, html:- '· The encryption keys travel <b>inside this file</b> — opening it is joining it<br>' +- '· Edits sync end-to-end encrypted; the relay stores ciphertext and learns nothing<br>' +- '· Every reset mints fresh keys — the old room simply stops existing<br>' +- '· Your saved copy keeps working forever, offline, like any Bento deck' }),- text({ x: 96, y: 600, w: 1000, h: 30, html: 'THIS IS THE SAME COLLAB THAT SHIPS IN EVERY DECK — NOTHING SPECIAL WAS BUILT FOR THIS STUNT', fontSize: 12, fontWeight: 700, letterSpacing: 2.5, color: 'rgba(20,34,54,0.5)' }),- ],-}--const s9 = {- id: 'gb-close', background: INK, transition: 'morph',- notes: 'The pitch, quietly. Save a copy of the guestbook as a souvenir of this epoch — or start a deck of your own.',- elements: [- rect({ id: 'gb-tile-a', x: 540, y: 110, w: 200, h: 200, fill: PEACH, radius: 36 }),- rect({ id: 'gb-tile-b', x: 464, y: 230, w: 120, h: 180, fill: STEEL, radius: 26 }),- rect({ id: 'gb-tile-c', x: 700, y: 250, w: 120, h: 120, fill: TILE, radius: 24 }),- text({ x: 140, y: 380, w: 1000, h: 120, html: 'Make a deck of your own.', fontSize: 66, fontFamily: FR, fontWeight: 900, color: '#fff', align: 'center', lineHeight: 1 }),- text({ x: 140, y: 520, w: 1000, h: 60, html: '<b>bento.page</b> — templates, the app, the whole story. One file each.', fontSize: 19, color: MIST, align: 'center', lineHeight: 1.6 }),- text({ x: 140, y: 620, w: 1000, h: 24, html: 'SAVE A COPY OF THIS GUESTBOOK — IT’S YOUR SOUVENIR OF EPOCH ' + epoch, fontSize: 12, fontWeight: 700, letterSpacing: 2.5, color: 'rgba(255,158,138,0.8)', align: 'center' }),- ],-}--const doc = {- format: 'bento/slides', version: 1, title: `The Guestbook — epoch ${epoch}`,- docId, collab, guestbookEpoch: epoch,- size: { width: 1280, height: 720 },- theme: { background: INK, color: '#fff', accent: PEACH, fontFamily: IN },- assets: { 'font-fraunces': font('FRAUNCES_900'), 'font-instrument': font('INSTRUMENT_VAR') },- fonts: [- { family: 'Fraunces', asset: 'font-fraunces', weight: '900' },- { family: 'Instrument Sans', asset: 'font-instrument', weight: '100 900' },- ],- slides: [s1, ...walls, s8, s9],- modified: new Date().toISOString(),-}--const blockRe = /<script type="application\/bento\+json" id="bento-doc">[\s\S]*?<\/script>/-const json = JSON.stringify(doc).replace(/</g, '\\u003c')-const spliced = shell.replace(blockRe, `<script type="application/bento+json" id="bento-doc">\n${json}\n</scr` + 'ipt>')-if (!spliced.includes(json)) throw new Error('splice failed')+const spliced = spliceDoc(shell, doc)mkdirSync(dirname(out), { recursive: true })writeFileSync(out, spliced)console.log(`guestbook epoch ${epoch} → ${out} (${Math.round(spliced.length / 1024)} KB)`)console.log(`room: ${collab.room}`)-console.log('next: publish the site (release --no-build + rsync + push) so the new epoch replaces the old file')+console.log('note: the Cloudflare daemon (server/guestbook-daemon) is authoritative once seeded —')+console.log(' seed it via PUT /guestbook-admin/seed after building locally')diff --git a/scripts/gallery-fonts/SpaceMono-400-latin.woff2 b/scripts/gallery-fonts/SpaceMono-400-latin.woff2new file mode 100644index 00000000..44de035aBinary files /dev/null and b/scripts/gallery-fonts/SpaceMono-400-latin.woff2 differdiff --git a/scripts/gallery-fonts/SpaceMono-700-latin.woff2 b/scripts/gallery-fonts/SpaceMono-700-latin.woff2new file mode 100644index 00000000..fcb9b937Binary files /dev/null and b/scripts/gallery-fonts/SpaceMono-700-latin.woff2 differdiff --git a/scripts/gallery-photos/SOURCES.md b/scripts/gallery-photos/SOURCES.mdindex 4a84572d..b5f67c4a 100644--- a/scripts/gallery-photos/SOURCES.md+++ b/scripts/gallery-photos/SOURCES.md@@ -24,3 +24,22 @@ Added 2026-07-18 (v4 — cover backgrounds):| file | source | credit / provenance ||---|---|---|| picnic-fairwide.jpg | Wikimedia Commons / Library of Congress (LCCN2017877389) | Jack Delano, backstage at the Vermont state fair, Rutland, 1941 Kodachrome, FSA/OWI — public domain (film mount cropped) |++Added 2026-07-18 (v5 — quality pass):++The five `orbital-*.jpg` files were re-rendered from the full-resolution NASA+originals (images-assets.nasa.gov / eol.jsc.nasa.gov IIIF) at 2200 px on the+long edge, q88 — the earlier renditions were heavily compressed. Same frames,+same crops (orbital-stars re-cropped a touch lower to drop the ISS-hardware+strip). New second photo for the Signal deck so slide 4 no longer repeats the+cover:++| file | source | credit / provenance |+|---|---|---|+| signal-press2.jpg | Wikimedia Commons / Library of Congress (fsa 8d22695, IIIF full-res) | Marjory Collins, "Pressroom of the New York Times" — freshly printed papers off the press, 1942, FSA/OWI — public domain (scan border + caption strip cropped) |++Embedded webfont (`scripts/gallery-fonts/`, used by the Orbital deck):++| file | source | licence |+|---|---|---|+| SpaceMono-{400,700}-latin.woff2 | Google Fonts (fonts.gstatic.com), latin subset | Space Mono, SIL Open Font License 1.1 |diff --git a/scripts/gallery-photos/orbital-aurora.jpg b/scripts/gallery-photos/orbital-aurora.jpgindex a1b87941..355138d7 100644Binary files a/scripts/gallery-photos/orbital-aurora.jpg and b/scripts/gallery-photos/orbital-aurora.jpg differdiff --git a/scripts/gallery-photos/orbital-dragon.jpg b/scripts/gallery-photos/orbital-dragon.jpgindex e1d4ad34..12f84c3f 100644Binary files a/scripts/gallery-photos/orbital-dragon.jpg and b/scripts/gallery-photos/orbital-dragon.jpg differdiff --git a/scripts/gallery-photos/orbital-earth.jpg b/scripts/gallery-photos/orbital-earth.jpgindex 645efb78..4120d866 100644Binary files a/scripts/gallery-photos/orbital-earth.jpg and b/scripts/gallery-photos/orbital-earth.jpg differdiff --git a/scripts/gallery-photos/orbital-nebula.jpg b/scripts/gallery-photos/orbital-nebula.jpgindex e310756a..b1e96fae 100644Binary files a/scripts/gallery-photos/orbital-nebula.jpg and b/scripts/gallery-photos/orbital-nebula.jpg differdiff --git a/scripts/gallery-photos/orbital-stars.jpg b/scripts/gallery-photos/orbital-stars.jpgindex 300798ff..9ac89636 100644Binary files a/scripts/gallery-photos/orbital-stars.jpg and b/scripts/gallery-photos/orbital-stars.jpg differdiff --git a/scripts/gallery-photos/signal-press2.jpg b/scripts/gallery-photos/signal-press2.jpgnew file mode 100644index 00000000..a83cdb67Binary files /dev/null and b/scripts/gallery-photos/signal-press2.jpg differdiff --git a/scripts/guestbook-archivist.ts b/scripts/guestbook-archivist.tsnew file mode 100644index 00000000..3942f346--- /dev/null+++ b/scripts/guestbook-archivist.ts@@ -0,0 +1,110 @@+#!/usr/bin/env node+// Headless guestbook archivist: joins the room READ-ONLY (sends nothing),+// replays the encrypted op log through the real CRDT engine, and writes an+// archive file containing what people actually signed — not the pristine+// seed. Archives are frozen artifacts: collab.on is set to false in them.+//+// node scripts/guestbook-archivist.ts [--in <file>] [--out <file>]+//+// Defaults: in = working/guestbook-live/guestbook.bento.html+// out = working/guestbook-epochs/epoch-<n>-content-<stamp>.bento.html++import { webcrypto as crypto } from 'node:crypto'+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { SyncState } from '../slides/src/sync/crdt.ts'+import type { Op } from '../slides/src/sync/crdt.ts'++const root = dirname(dirname(fileURLToPath(import.meta.url)))+const args = process.argv.slice(2)+const opt = (name: string, fallback: string) => {+ const i = args.indexOf(`--${name}`)+ return i >= 0 && args[i + 1] ? args[i + 1] : fallback+}+const inFile = opt('in', join(root, 'working/guestbook-live/guestbook.bento.html'))++const b64u = {+ enc: (b: Uint8Array) => Buffer.from(b).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''),+ dec: (s: string) => new Uint8Array(Buffer.from(s.replace(/-/g, '+').replace(/_/g, '/'), 'base64')),+}++const shellText = readFileSync(inFile, 'utf8')+const blockRe = /<script type="application\/bento\+json" id="bento-doc">\s*([\s\S]*?)\s*<\/script>/+const m = shellText.match(blockRe)+if (!m) throw new Error('no #bento-doc block in ' + inFile)+const doc = JSON.parse(m[1])+const { room, key: keyB64 } = doc.collab ?? {}+if (!room || !keyB64) throw new Error('file has no collab credentials')+const epoch = doc.guestbookEpoch ?? 0++const countEls = (d: any) => d.slides.reduce((n: number, s: any) => n + (s.elements?.length ?? 0), 0)+const seedCount = countEls(doc)++const actor = 'archivist-' + Math.random().toString(36).slice(2, 8)+const state = new SyncState(actor)+state.adopt(doc)++const raw = b64u.dec(keyB64)+const key = await crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['decrypt'])+const tok = b64u.enc(new Uint8Array(await crypto.subtle.digest('SHA-256', raw)).slice(0, 18))++let opsApplied = 0+let gotSnap = false+let done = false++const finish = (reason: string) => {+ if (done) return+ done = true+ try { ws.close() } catch { /* already closed */ }+ const total = countEls(doc)+ const stamp = new Date().toISOString().slice(0, 16).replace(/[:T]/g, '-')+ const out = opt('out', join(root, `working/guestbook-epochs/epoch-${epoch}-content-${stamp}.bento.html`))+ const frozen = JSON.parse(JSON.stringify(doc))+ if (frozen.collab) frozen.collab.on = false // archives are frozen artifacts+ frozen.title = `The Guestbook — epoch ${epoch} (archived)`+ const json = JSON.stringify(frozen).replace(/</g, '\\u003c')+ const spliced = shellText.replace(blockRe, `<script type="application/bento+json" id="bento-doc">\n${json}\n</scr` + 'ipt>')+ mkdirSync(dirname(out), { recursive: true })+ writeFileSync(out, spliced)+ console.log(`archived epoch ${epoch} → ${out}`)+ console.log(` ${reason} · snapshot: ${gotSnap} · ops applied: ${opsApplied} · elements: ${seedCount} seed → ${total} now (${total - seedCount} signed)`)+ process.exit(0)+}++setTimeout(() => finish('timeout (30s) — partial capture'), 30000)++const ws = new WebSocket(`${room}?tok=${tok}&since=0`)+ws.onopen = () => console.log('connected (read-only) to', room.slice(0, 48) + '…')+ws.onerror = () => { console.error('websocket error'); process.exit(1) }+ws.onclose = () => { if (!done) { console.error('closed before ready'); process.exit(1) } }+ws.onmessage = async (ev: MessageEvent) => {+ let env: { i?: string; d?: string; q?: number; snap?: number; ctl?: string }+ try { env = JSON.parse(String(ev.data)) } catch { return }+ if (env.ctl === 'ready') {+ // replay complete — linger briefly for in-flight live frames+ setTimeout(() => finish('replay complete'), 2500)+ return+ }+ if (env.ctl === 'ack' || !env.i || !env.d) return+ let payload: any+ try {+ const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: b64u.dec(env.i) }, key, b64u.dec(env.d))+ payload = JSON.parse(new TextDecoder().decode(pt))+ } catch { return }+ if (env.snap === 1) {+ if (payload?.doc && payload?.state) {+ state.mergeSnapshot(doc, payload.doc, payload.state)+ gotSnap = true+ }+ return+ }+ if (payload?.t === 'ops' && Array.isArray(payload.ops)) {+ state.apply(doc, payload.ops as Op[])+ opsApplied += payload.ops.length+ }+ if (payload?.t === 'snap' && payload.doc && payload.state) {+ state.mergeSnapshot(doc, payload.doc, payload.state)+ gotSnap = true+ }+}diff --git a/scripts/guestbook-deck.mjs b/scripts/guestbook-deck.mjsnew file mode 100644index 00000000..1865f5e2--- /dev/null+++ b/scripts/guestbook-deck.mjs@@ -0,0 +1,133 @@+// The guestbook deck definition, shared by the local builder+// (scripts/build-guestbook.mjs) and the Cloudflare daemon+// (server/guestbook-daemon/) so epochs look identical wherever they are+// minted. Pure function: no I/O, no crypto — callers supply identity.+//+// NOTE: element ids are unique ACROSS slides on purpose — shared ids+// collapse under live collab until the CRDT morph-id fix lands.++const INK = '#0D1B2E', PANEL = '#16273E', PEACH = '#FF9E8A', PAPER = '#F2F0EA'+const STEEL = '#5E7699', TILE = '#F0EBE0'+const MIST = 'rgba(182,193,210,0.9)', MIST_DIM = 'rgba(182,193,210,0.5)'+const FR = 'Fraunces, Georgia, serif'+const IN = "'Instrument Sans', 'Helvetica Neue', sans-serif"++/**+ * @param {{ epoch: number, docId: string,+ * collab: { room: string, key: string, on: boolean },+ * fonts: { fraunces: string, instrument: string } }} p+ */+export function buildGuestbookDoc({ epoch, docId, collab, fonts }) {+ let uid = 0+ const id = (p) => `${p}-${(++uid).toString(36)}`+ const text = (o) => ({+ id: o.id ?? id('t'), type: 'text', x: o.x, y: o.y, w: o.w, h: o.h,+ rotation: o.rotation ?? 0, opacity: o.opacity ?? 1, html: o.html,+ fontSize: o.fontSize ?? 24, fontFamily: o.fontFamily ?? IN,+ fontWeight: o.fontWeight ?? 400, color: o.color ?? '#fff',+ align: o.align ?? 'left', valign: o.valign ?? 'top', lineHeight: o.lineHeight ?? 1.3,+ ...(o.letterSpacing != null ? { letterSpacing: o.letterSpacing } : {}),+ })+ const rect = (o) => ({+ id: o.id ?? id('s'), type: 'shape', shape: o.shape ?? 'rect', x: o.x, y: o.y, w: o.w, h: o.h,+ rotation: o.rotation ?? 0, opacity: o.opacity ?? 1, fill: o.fill ?? 'rgba(0,0,0,0)',+ stroke: o.stroke ?? 'none', strokeWidth: o.strokeWidth ?? 0, radius: o.radius ?? 0,+ ...(o.strokeStyle ? { strokeStyle: o.strokeStyle } : {}),+ })+ const kick = (x, y, s, color = PEACH) =>+ text({ x, y, w: 900, h: 24, html: s, fontSize: 13, fontWeight: 700, letterSpacing: 5, color })++ const s1 = {+ id: 'gb-welcome', background: INK, transition: 'none',+ notes: 'The public guestbook: everyone holding this file is in the same live room, end-to-end encrypted. House rules on the slide. Epochs reset the room on a schedule — good walls are archived, vandalism simply evaporates.',+ elements: [+ rect({ id: 'gb-tile-a', x: 980, y: 110, w: 170, h: 170, fill: PEACH, radius: 30 }),+ rect({ id: 'gb-tile-b', x: 1080, y: 310, w: 100, h: 150, fill: STEEL, radius: 22 }),+ rect({ id: 'gb-tile-c', x: 930, y: 330, w: 100, h: 100, fill: TILE, radius: 20 }),+ kick(96, 90, `THE GUESTBOOK — EPOCH ${epoch} · A PUBLIC EXPERIMENT`),+ text({ x: 88, y: 140, w: 900, h: 220, html: 'Leave a mark.', fontSize: 110, fontFamily: FR, fontWeight: 900, color: '#fff', lineHeight: 1 }),+ text({ x: 96, y: 360, w: 780, h: 100, html: 'Everyone with this file open is <b>in this deck with you, live</b> — end-to-end encrypted, no accounts. Pick a wall (→), add a note, a shape, a doodle. Set your name via the <b>Live</b> button so your cursor has one.', fontSize: 19, color: MIST, lineHeight: 1.6 }),+ text({ x: 96, y: 500, w: 900, h: 120, fontSize: 16, color: MIST_DIM, lineHeight: 1.9, html:+ '<b>House rules:</b> add, don’t wipe · be kind · anything goes except cruelty<br>' ++ 'The room resets on a schedule — beautiful walls get archived forever, everything else evaporates. An archivist bot snapshots the room daily.' }),+ text({ x: 96, y: 655, w: 1000, h: 24, html: '→ THE WALLS ARE THAT WAY', fontSize: 12, fontWeight: 700, letterSpacing: 3, color: 'rgba(255,158,138,0.85)' }),+ ],+ }++ const seeds = [+ { html: 'the file is the room 🤯', color: PEACH, rot: -3 },+ { html: 'hello from epoch ' + epoch, color: TILE, rot: 2 },+ { html: 'no login. no cloud. just us.', color: STEEL, rot: -1 },+ { html: 'sign below ↓', color: PEACH, rot: 1 },+ { html: 'archive me, i’m beautiful', color: TILE, rot: -2 },+ { html: 'CRDTs are magic', color: STEEL, rot: 3 },+ ]+ const walls = seeds.map((seed, i) => ({+ id: `gb-wall-${i + 1}`, background: i % 2 ? PANEL : INK, transition: 'fade',+ notes: `Wall ${i + 1} of ${seeds.length}. Everything here was left by someone holding this file. Add yours anywhere — double-click to write, or drop shapes from the toolbar.`,+ elements: [+ text({ x: 40, y: 40, w: 600, h: 200, html: String(i + 1).padStart(2, '0'), fontSize: 180, fontFamily: FR, fontWeight: 900, color: i % 2 ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.045)' }),+ kick(96, 84, `WALL ${String(i + 1).padStart(2, '0')} — SIGN ANYWHERE`, 'rgba(255,158,138,0.6)'),+ rect({ x: 60, y: 130, w: 1160, h: 540, stroke: 'rgba(182,193,210,0.18)', strokeWidth: 1.5, radius: 18, strokeStyle: 'dashed' }),+ text({ x: 140 + (i * 137) % 700, y: 190 + (i * 211) % 350, w: 420, h: 60, html: seed.html, fontSize: 30, fontFamily: i % 2 ? FR : IN, fontWeight: i % 2 ? 900 : 700, color: seed.color, rotation: seed.rot }),+ ],+ }))++ const s8 = {+ id: 'gb-how', background: PAPER, transition: 'fade',+ notes: 'How it works: the collab keys live inside this file — possession is membership. The relay only ever sees ciphertext. Epochs: fresh keys are minted on reset, which orphans the old room instantly; saved copies keep working offline, which is rather the point.',+ elements: [+ kick(96, 96, 'HOW THIS WORKS', '#C25A43'),+ text({ x: 90, y: 140, w: 1000, h: 110, html: 'The file is the room.', fontSize: 64, fontFamily: FR, fontWeight: 900, color: INK, lineHeight: 1 }),+ text({ x: 96, y: 280, w: 1040, h: 260, fontSize: 20, color: 'rgba(20,34,54,0.78)', lineHeight: 1.85, html:+ '· The encryption keys travel <b>inside this file</b> — opening it is joining it<br>' ++ '· Edits sync end-to-end encrypted; the relay stores ciphertext and learns nothing<br>' ++ '· Every reset mints fresh keys — the old room simply stops existing<br>' ++ '· Your saved copy keeps working forever, offline, like any Bento deck' }),+ text({ x: 96, y: 600, w: 1000, h: 30, html: 'THIS IS THE SAME COLLAB THAT SHIPS IN EVERY DECK — NOTHING SPECIAL WAS BUILT FOR THIS STUNT', fontSize: 12, fontWeight: 700, letterSpacing: 2.5, color: 'rgba(20,34,54,0.5)' }),+ ],+ }++ const s9 = {+ id: 'gb-close', background: INK, transition: 'fade',+ notes: 'The pitch, quietly. Save a copy of the guestbook as a souvenir of this epoch — or start a deck of your own. (Deliberately NO shared ids with the welcome slide: in a live-collab deck, element ids must be unique across slides until the morph/CRDT id fix lands.)',+ elements: [+ rect({ id: 'gb-close-a', x: 540, y: 110, w: 200, h: 200, fill: PEACH, radius: 36 }),+ rect({ id: 'gb-close-b', x: 464, y: 230, w: 120, h: 180, fill: STEEL, radius: 26 }),+ rect({ id: 'gb-close-c', x: 700, y: 250, w: 120, h: 120, fill: TILE, radius: 24 }),+ text({ x: 140, y: 380, w: 1000, h: 120, html: 'Make a deck of your own.', fontSize: 66, fontFamily: FR, fontWeight: 900, color: '#fff', align: 'center', lineHeight: 1 }),+ text({ x: 140, y: 520, w: 1000, h: 60, html: '<b>bento.page</b> — templates, the app, the whole story. One file each.', fontSize: 19, color: MIST, align: 'center', lineHeight: 1.6 }),+ text({ x: 140, y: 620, w: 1000, h: 24, html: 'SAVE A COPY OF THIS GUESTBOOK — IT’S YOUR SOUVENIR OF EPOCH ' + epoch, fontSize: 12, fontWeight: 700, letterSpacing: 2.5, color: 'rgba(255,158,138,0.8)', align: 'center' }),+ ],+ }++ return {+ format: 'bento/slides', version: 1, title: `The Guestbook — epoch ${epoch}`,+ docId, collab, guestbookEpoch: epoch,+ size: { width: 1280, height: 720 },+ theme: { background: INK, color: '#fff', accent: PEACH, fontFamily: IN },+ assets: { 'font-fraunces': fonts.fraunces, 'font-instrument': fonts.instrument },+ fonts: [+ { family: 'Fraunces', asset: 'font-fraunces', weight: '900' },+ { family: 'Instrument Sans', asset: 'font-instrument', weight: '100 900' },+ ],+ slides: [s1, ...walls, s8, s9],+ modified: new Date().toISOString(),+ }+}++/** splice a doc into a shell (the format's one contract) */+export function spliceDoc(shellText, doc) {+ const blockRe = /<script type="application\/bento\+json" id="bento-doc">[\s\S]*?<\/script>/+ const json = JSON.stringify(doc).replace(/</g, '\\u003c')+ const out = shellText.replace(blockRe, `<script type="application/bento+json" id="bento-doc">\n${json}\n</scr` + 'ipt>')+ if (!out.includes(json)) throw new Error('splice failed')+ return out+}++/** extract the doc JSON from a .bento.html file's plaintext block */+export function extractDoc(shellText) {+ const m = shellText.match(/<script type="application\/bento\+json" id="bento-doc">\s*([\s\S]*?)\s*<\/script>/)+ if (!m) throw new Error('no #bento-doc block')+ return JSON.parse(m[1])+}diff --git a/scripts/guestbook-roll.mjs b/scripts/guestbook-roll.mjsnew file mode 100644index 00000000..829699de--- /dev/null+++ b/scripts/guestbook-roll.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+// The guestbook daemon's one command. Two modes:+//+// node scripts/guestbook-roll.mjs --snapshot-only+// → join the live room read-only, archive what people actually signed+// (working/guestbook-epochs/epoch-N-content-*.bento.html). No publish.+//+// node scripts/guestbook-roll.mjs+// → full epoch roll: content archive, then mint epoch N+1 with FRESH+// room+key (kill switch semantics — the published file stops pointing+// at the old room), publish to bento-site AND refresh site/ staging.+//+// Scheduling: a Claude Code scheduled task runs --snapshot-only daily.+// Rolls are run on demand (or schedule this same command for launch week).++import { execFileSync } from 'node:child_process'+import { copyFileSync, existsSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'++const root = dirname(dirname(fileURLToPath(import.meta.url)))+const live = join(root, 'working/guestbook-live/guestbook.bento.html')+const siteRepo = join(root, '../bento-site')+const run = (cmd, args, cwd = root) => execFileSync(cmd, args, { cwd, stdio: 'inherit' })++if (!existsSync(live)) {+ console.error('guestbook is not armed (working/guestbook-live/ empty) — nothing to do')+ process.exit(1)+}++// 1 · capture what the room actually holds (read-only join + replay)+run('node', [join(root, 'scripts/guestbook-archivist.ts')])++if (process.argv.includes('--snapshot-only')) process.exit(0)++// 2 · mint the next epoch (archives the pristine file, fresh credentials)+run('node', [join(root, 'scripts/build-guestbook.mjs')])++// 3 · publish: the live site repo directly (fast path), plus site/ staging+// so the next full release carries the same epoch+copyFileSync(live, join(siteRepo, 'guestbook.bento.html'))+copyFileSync(join(root, 'site-src/guestbook.html'), join(siteRepo, 'guestbook/index.html'))+if (existsSync(join(root, 'site/guestbook.bento.html'))) copyFileSync(live, join(root, 'site/guestbook.bento.html'))+run('git', ['add', 'guestbook.bento.html', 'guestbook/index.html'], siteRepo)+run('git', ['commit', '-m', 'Guestbook: roll epoch'], siteRepo)+run('git', ['push'], siteRepo)+console.log('epoch rolled and published — old room orphaned from the published file')diff --git a/server/guestbook-daemon/README.md b/server/guestbook-daemon/README.mdnew file mode 100644index 00000000..88cf90aa--- /dev/null+++ b/server/guestbook-daemon/README.md@@ -0,0 +1,53 @@+# bento-guestbook-daemon++The sustainable home of the public guestbook (see `working/guestbook-design.md`):+a Cloudflare Worker that serves the current epoch from R2, archives the live+room daily (read-only CRDT replay), and rolls epochs with fresh credentials.++## One-time setup++```bash+cd server/guestbook-daemon+npx wrangler kv namespace create STORE # paste the id into wrangler.toml+openssl rand -hex 24 | npx wrangler secret put ADMIN_KEY # keep a copy+npx wrangler deploy+```++DNS: the `bento.page` apex record must be **proxied** (orange cloud) for the+`bento.page/guestbook.bento.html` route to shadow GitHub Pages. Until then,+the worker is still reachable on its workers.dev URL (admin + cron work).++## Arming / operating++```bash+# seed the current epoch (built locally by scripts/build-guestbook.mjs)+curl -X PUT https://bento.page/guestbook-admin/seed \+ -H "Authorization: Bearer $ADMIN_KEY" \+ --data-binary @../../working/guestbook-live/guestbook.bento.html++curl -H "Authorization: Bearer $ADMIN_KEY" https://bento.page/guestbook-admin/status+curl -X POST -H "Authorization: Bearer $ADMIN_KEY" https://bento.page/guestbook-admin/snapshot+curl -X POST -H "Authorization: Bearer $ADMIN_KEY" https://bento.page/guestbook-admin/roll+curl -X POST -H "Authorization: Bearer $ADMIN_KEY" https://bento.page/guestbook-admin/kill+```++- **snapshot** — join the room read-only, archive real content to KV+ `archives/` (pruned to the newest 90). Runs daily at 01:00 UTC via cron regardless.+- **roll** — snapshot, then mint epoch N+1 with fresh room+key and a fresh+ shell fetched from the live release. Old room orphans instantly.+ Automatic cadence: set `ROLL_HOURS` in wrangler.toml (0 = manual).+- **kill** — serve a redirect to /404.html instead of the file. Un-kill by+ seeding or rolling.++## Notes++- The CRDT engine is bundled from `slides/src/sync/crdt.ts`; the deck+ definition is shared with the local builder via `scripts/guestbook-deck.mjs`.+ Epoch fonts carry forward from the previous epoch's embedded assets.+- The daemon holds the room key — as does everyone with the file. The+ guestbook's key is public by design; this is no privacy regression.+- The static copy in the bento-site repo remains as a fallback for when KV+ is empty and as the pre-proxy path. After the route is live, the daemon's+ KV copy is authoritative.+- Local dev: `npx wrangler dev --port 8788` (+ `.dev.vars` with ADMIN_KEY).+ Never pipe wrangler dev output through `head` (SIGPIPE kills it).diff --git a/server/guestbook-daemon/src/worker.js b/server/guestbook-daemon/src/worker.jsnew file mode 100644index 00000000..05038c40--- /dev/null+++ b/server/guestbook-daemon/src/worker.js@@ -0,0 +1,226 @@+// bento-guestbook-daemon — the sustainable home of the public guestbook.+// Storage: Workers KV (R2 is not enabled on this account; KV fits — values+// are ~500 KB against a 25 MB limit, archives pruned to the newest 90).+//+// · serves bento.page/guestbook.bento.html from KV (current epoch)+// · cron: daily read-only archivist snapshot of the room → KV archives/+// · rolls epochs (fresh room+key, seeded deck) on demand or on cadence+// · admin surface under /guestbook-admin/* (Authorization: Bearer ADMIN_KEY)+//+// The daemon joins the relay room exactly like any client (WebSocket ++// AES-GCM with the key from the file) and replays ops through the real CRDT+// engine — bundled from slides/src/sync/crdt.ts. It holds the room key, but+// so does everyone with the file: the guestbook's key is public by design.++import { SyncState } from '../../../slides/src/sync/crdt.ts'+import { buildGuestbookDoc, spliceDoc, extractDoc } from '../../../scripts/guestbook-deck.mjs'++const CURRENT = 'current.bento.html'+const META = 'meta.json'++const b64u = {+ enc(bytes) {+ let s = ''+ for (const b of bytes) s += String.fromCharCode(b)+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')+ },+ dec(s) {+ const b = atob(s.replace(/-/g, '+').replace(/_/g, '/'))+ const out = new Uint8Array(b.length)+ for (let i = 0; i < b.length; i++) out[i] = b.charCodeAt(i)+ return out+ },+}++const meta = async (env) => JSON.parse((await env.STORE.get(META, 'text')) ?? '{}')+const putMeta = (env, m) => env.STORE.put(META, JSON.stringify(m, null, 2))++// ——— archivist: read-only join, replay, return the room's real doc ———————+async function captureRoom(env) {+ const shellText = await env.STORE.get(CURRENT, 'text')+ if (!shellText) throw new Error('no current guestbook in KV')+ const doc = extractDoc(shellText)+ const { room, key: keyB64 } = doc.collab ?? {}+ if (!room || !keyB64) throw new Error('current file has no collab creds')++ const raw = b64u.dec(keyB64)+ const key = await crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['decrypt'])+ const tok = b64u.enc(new Uint8Array(await crypto.subtle.digest('SHA-256', raw)).slice(0, 18))++ const httpsUrl = room.replace(/^wss:/, 'https:') + `?tok=${tok}&since=0`+ const resp = await fetch(httpsUrl, { headers: { Upgrade: 'websocket' } })+ const ws = resp.webSocket+ if (!ws) throw new Error('relay refused websocket upgrade (' + resp.status + ')')+ ws.accept()++ const state = new SyncState('daemon-' + Math.random().toString(36).slice(2, 8))+ state.adopt(doc)+ const seedCount = doc.slides.reduce((n, s) => n + (s.elements?.length ?? 0), 0)+ let opsApplied = 0+ let gotSnap = false++ await new Promise((resolve, reject) => {+ const timer = setTimeout(() => resolve('timeout'), 20000)+ let graceTimer = null+ ws.addEventListener('error', () => { clearTimeout(timer); reject(new Error('ws error')) })+ ws.addEventListener('message', async (ev) => {+ let env2+ try { env2 = JSON.parse(String(ev.data)) } catch { return }+ if (env2.ctl === 'ready') {+ graceTimer = setTimeout(() => { clearTimeout(timer); resolve('ready') }, 2000)+ return+ }+ if (env2.ctl === 'ack' || !env2.i || !env2.d) return+ let payload+ try {+ const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: b64u.dec(env2.i) }, key, b64u.dec(env2.d))+ payload = JSON.parse(new TextDecoder().decode(pt))+ } catch { return }+ if (env2.snap === 1 || (payload?.t === 'snap' && payload.doc)) {+ const p = env2.snap === 1 ? payload : payload+ if (p?.doc && p?.state) { state.mergeSnapshot(doc, p.doc, p.state); gotSnap = true }+ return+ }+ if (payload?.t === 'ops' && Array.isArray(payload.ops)) {+ state.apply(doc, payload.ops)+ opsApplied += payload.ops.length+ if (graceTimer) { clearTimeout(graceTimer); graceTimer = setTimeout(() => { clearTimeout(timer); resolve('ready') }, 1500) }+ }+ })+ })+ try { ws.close() } catch { /* fine */ }++ const total = doc.slides.reduce((n, s) => n + (s.elements?.length ?? 0), 0)+ return { doc, shellText, stats: { epoch: doc.guestbookEpoch ?? 0, seedCount, total, signed: total - seedCount, opsApplied, gotSnap } }+}++async function snapshot(env) {+ const { doc, shellText, stats } = await captureRoom(env)+ const frozen = JSON.parse(JSON.stringify(doc))+ if (frozen.collab) frozen.collab.on = false+ frozen.title = `The Guestbook — epoch ${stats.epoch} (archived)`+ const stamp = new Date().toISOString().slice(0, 16).replace(/[:T]/g, '-')+ const name = `archives/epoch-${stats.epoch}-${stamp}.bento.html`+ await env.STORE.put(name, spliceDoc(shellText, frozen))+ // prune: keep the newest 90 archives (KV free tier is 1 GB)+ const list = await env.STORE.list({ prefix: 'archives/' })+ const names = list.keys.map((k) => k.name).sort()+ for (const old of names.slice(0, Math.max(0, names.length - 90))) await env.STORE.delete(old)+ const m = await meta(env)+ m.lastSnapshot = { at: new Date().toISOString(), name, ...stats }+ await putMeta(env, m)+ return { name, ...stats }+}++async function roll(env) {+ // 1 · archive what the room holds right now+ let archived = null+ try { archived = await snapshot(env) } catch (e) { archived = { error: String(e) } }++ // 2 · mint the next epoch; fonts carry forward from the current file's doc+ const curText = await env.STORE.get(CURRENT, 'text')+ if (!curText) throw new Error('no current guestbook in KV')+ const prevDoc = extractDoc(curText)+ const epoch = (prevDoc.guestbookEpoch ?? 0) + 1+ const fonts = { fraunces: prevDoc.assets['font-fraunces'], instrument: prevDoc.assets['font-instrument'] }+ const rnd = (n) => { const b = new Uint8Array(n); crypto.getRandomValues(b); return b }+ const collab = { room: `${env.SYNC_HOST}/d/r${b64u.enc(rnd(12))}`, key: b64u.enc(rnd(32)), on: true }+ const doc = buildGuestbookDoc({ epoch, docId: crypto.randomUUID(), collab, fonts })++ // 3 · splice into a FRESH shell (so epochs pick up app releases too)+ const shellResp = await fetch(env.SHELL_URL)+ if (!shellResp.ok) throw new Error('shell fetch failed: ' + shellResp.status)+ const spliced = spliceDoc(await shellResp.text(), doc)+ await env.STORE.put(CURRENT, spliced)++ const m = await meta(env)+ m.epoch = epoch+ m.lastRoll = new Date().toISOString()+ m.killed = false+ await putMeta(env, m)+ return { epoch, archived, size: spliced.length }+}++// ——— entrypoints ————————————————————————————————————————————————————+export default {+ async fetch(req, env) {+ const url = new URL(req.url)++ if (url.pathname === '/guestbook.bento.html') {+ const m = await meta(env)+ if (m.killed) return Response.redirect(url.origin + '/404.html', 302)+ const cur = await env.STORE.get(CURRENT, 'stream')+ if (cur) {+ return new Response(cur, {+ headers: {+ 'content-type': 'text/html; charset=utf-8',+ 'cache-control': 'no-cache', // epochs must propagate immediately+ },+ })+ }+ // KV empty: fall through to the static copy on GitHub Pages+ return fetch(env.ORIGIN_FALLBACK + '/guestbook.bento.html')+ }++ if (url.pathname.startsWith('/guestbook-admin/')) {+ const auth = req.headers.get('authorization') ?? ''+ if (!env.ADMIN_KEY || auth !== `Bearer ${env.ADMIN_KEY}`) {+ return new Response('unauthorized', { status: 401 })+ }+ const action = url.pathname.slice('/guestbook-admin/'.length)+ const json = (o, s = 200) => new Response(JSON.stringify(o, null, 2), { status: s, headers: { 'content-type': 'application/json' } })+ try {+ if (action === 'status') {+ const m = await meta(env)+ const list = await env.STORE.list({ prefix: 'archives/' })+ return json({ ...m, archives: list.keys.map((k) => k.name) })+ }+ if (action === 'snapshot' && req.method === 'POST') return json(await snapshot(env))+ if (action === 'roll' && req.method === 'POST') return json(await roll(env))+ if (action === 'kill' && req.method === 'POST') {+ const m = await meta(env)+ m.killed = true+ await putMeta(env, m)+ return json({ killed: true })+ }+ if (action === 'seed' && req.method === 'PUT') {+ // initial arming: PUT the current epoch file built locally+ const body = await req.text()+ const doc = extractDoc(body) // validates+ await env.STORE.put(CURRENT, body)+ const m = await meta(env)+ m.epoch = doc.guestbookEpoch ?? 0+ m.killed = false+ m.seededAt = new Date().toISOString()+ await putMeta(env, m)+ return json({ seeded: true, epoch: m.epoch, bytes: body.length })+ }+ if (action.startsWith('archives/')) {+ const obj = await env.STORE.get(action, 'stream')+ if (!obj) return json({ error: 'not found' }, 404)+ return new Response(obj, { headers: { 'content-type': 'text/html; charset=utf-8' } })+ }+ return json({ error: 'unknown action', actions: ['status', 'POST snapshot', 'POST roll', 'POST kill', 'PUT seed', 'archives/<key>'] }, 404)+ } catch (e) {+ return json({ error: String(e) }, 500)+ }+ }++ return new Response('bento-guestbook-daemon', { status: 200 })+ },++ async scheduled(_ctrl, env, ctx) {+ ctx.waitUntil((async () => {+ const m = await meta(env)+ if (m.killed) return+ try { await snapshot(env) } catch (e) { console.log('snapshot failed:', String(e)) }+ const rollHours = Number(env.ROLL_HOURS || '0')+ if (rollHours > 0) {+ const last = m.lastRoll ? Date.parse(m.lastRoll) : 0+ if (Date.now() - last >= rollHours * 3600_000) {+ try { await roll(env) } catch (e) { console.log('roll failed:', String(e)) }+ }+ }+ })())+ },+}diff --git a/server/guestbook-daemon/wrangler.toml b/server/guestbook-daemon/wrangler.tomlnew file mode 100644index 00000000..10cb58c1--- /dev/null+++ b/server/guestbook-daemon/wrangler.toml@@ -0,0 +1,32 @@+name = "bento-guestbook-daemon"+main = "src/worker.js"+workers_dev = true+compatibility_date = "2026-06-01"++# Serves the current guestbook epoch from R2 (shadows GitHub Pages for this+# one path — apex must be proxied/orange-cloud) + the admin surface.+routes = [+ { pattern = "bento.page/guestbook.bento.html", zone_name = "bento.page" },+ { pattern = "bento.page/guestbook-admin/*", zone_name = "bento.page" },+]++# Daily archivist snapshot. Cron is UTC: 01:00 UTC ≈ 09:00 HKT.+[triggers]+crons = ["0 1 * * *"]++[[kv_namespaces]]+binding = "STORE"+id = "ac9eeb2800ea4e848ccf303e31d6620f"++[vars]+# where a fresh shell is fetched from at roll time (never bundled)+SHELL_URL = "https://bento.page/releases/slides/Bento_Slides.bento.html"+# fallback origin if R2 has no current file (GitHub Pages direct)+ORIGIN_FALLBACK = "https://nyblnet.github.io/bento-site"+# relay host baked into newly minted epochs+SYNC_HOST = "wss://sync.bento.page"+# automatic roll cadence in hours; 0 = manual rolls only (admin endpoint)+ROLL_HOURS = "0"++# secrets (set with `npx wrangler secret put ADMIN_KEY`):+# ADMIN_KEY — bearer for /guestbook-admin/*