Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

bento-sync M2+M3: E2EE blind relay, Share UI, live text merge

nyblnet711de20469db
diff --git a/CLAUDE.md b/CLAUDE.md
index 3aeb3796..b963f4dd 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -135,6 +135,39 @@ One HTML file = the document + viewer + editor. See `README.md` for the vision.
persisted per title in localStorage; Presenting/Interactivity/Layout
default closed. Add new panel content under a section header and the
accordion picks it up automatically.
+- `src/sync/` — **bento-sync live collaboration** (design: docs/collab-design.md).
+ `crdt.ts` is the engine (pure data, runs in node too): per-(node,key) LWW
+ regs ordered by (lamport, actor); liveness = births vs tombs (an INS is a
+ whole-node ASSIGNMENT — it resurrects by out-stamping the tomb and
+ supersedes all older property regs; slide-ins = slide assignment + an
+ independent element-ins per member, member processing must NEVER be
+ skipped by the slide-level LWW race); pos = fractional base-62 keys
+ (keyBetween midstrings, spreadKey for deterministic file adoption);
+ dead-window values park in a reg-stamped `stash` and replay on
+ resurrection ONLY while their reg is still the winner; element.html is a
+ token RGA whose seed = (max(reg,birth).l, contentHash) so concurrent
+ first-editors merge — a GENERATION duels plain sets as a unit, rebirths
+ void only seeds BELOW their lamport; delivery = per-actor contiguous `s`
+ + gap buffer + `pending` for not-yet-known nodes (drain on every liveness
+ event AND on txt progress — anchors/deletes can overtake their inserts).
+ Convergence rig: `node scripts/test-sync.ts` (SEEDS/STEPS/ACTORS env) —
+ run it after ANY crdt.ts change; it caught 15+ ordering bugs. Debug: set
+ `globalThis.__dbgEl = '<node-id>'` to trace one node through the gates.
+ `session.ts` bridges the store: local commits → debounced (90ms) shadow
+ diff → ops; remote ops apply surgically then re-emit the store events the
+ editor already listens to (zero editor rewrites). Actor ids are fresh PER
+ SESSION INSTANCE (a reloaded tab is a new replica; the engine skips "own"
+ ops on apply — a persisted actor id would make relay replay a no-op).
+ Same-machine tabs always sync (BroadcastChannel `bento-sync-<docId>`);
+ `online.ts` adds the E2EE relay (AES-GCM, key in `doc.collab.key`, ?tok=
+ hash-of-key possession proof; replay bookmark is MEMORY-ONLY — it's valid
+ only with the CRDT state it was earned with). The saved FILE is the
+ capability: doc.collab {room,key} rides in it, opening a copy auto-joins
+ (editor.connectSync joinIfShared). Relay: `server/sync-worker/` (blind DO,
+ ciphertext-only storage — verified; `npx wrangler dev --port 8787` +
+ localStorage 'bento-sync-url' for local testing). Undo under collab is
+ snapshot-based and may revert concurrent remote edits to the same
+ properties (documented LWW compromise).
- `src/editor/` — vanilla-TS editor. Moveable + Selecto handle manipulation.
Alt/Option-click digs through overlapping elements (capture-phase, beats
Moveable's control box). Fill/stroke colors carry alpha (color input + % pair,
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index f23740d0..0f44ec44 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -60,3 +60,31 @@ verify the manifest signature against the public key embedded in every shell.
new higher version that reverts the code.
- The update channel ships **signed code**; future sync/collab channels ship
**inert data**. Never blur the two.
+
+## Deploying the sync relay (one-time + on worker changes)
+
+The relay (`server/sync-worker/`) is separate from the static site — it
+lives on Cloudflare Workers and only needs redeploying when its code
+changes (client releases do NOT require it):
+
+```sh
+cd server/sync-worker
+npx wrangler login # one-time, opens the browser
+npx wrangler deploy # builds + publishes; prints the workers.dev URL
+```
+
+`wrangler.toml` requests the custom domain `sync.bento.page` — with the
+zone on the same Cloudflare account this is provisioned automatically at
+deploy (DNS + cert). Verify with:
+
+```sh
+curl https://sync.bento.page/ # → "bento-sync relay — see https://bento.page"
+```
+
+Local development: `npx wrangler dev --port 8787` (no account needed), and
+in the editor set `localStorage['bento-sync-url'] = 'ws://localhost:8787'`
+before starting a share session.
+
+The relay stores ONLY ciphertext (room-key-encrypted frames) and a hash of
+the room key; there are no secrets to manage server-side. Rooms self-delete
+after ~30 idle days — the file is the durable artifact.
diff --git a/docs/architecture.md b/docs/architecture.md
index e10dfdf3..d63ad7f7 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -21,6 +21,12 @@ trick, modernized with the File System Access API).
> (`charts-lite`, MIT) — ECharts/zrender removed. Diagrams below describe the
> uncompressed layout; sizes predate compression.
+> **v0.8.0 update**: live collaboration shipped — an in-house op-based CRDT
+> (**bento-sync**, §8) with automatic same-machine sync (BroadcastChannel)
+> and an optional end-to-end-encrypted blind relay (Cloudflare Durable
+> Objects, `sync.bento.page`). The saved file stays a complete standalone
+> document; `doc.collab {room, key}` is the only (additive) format change.
+
## 1. On-disk anatomy
A `.bento.html` file is ordinary, valid HTML. Its compartments, drawn
@@ -302,3 +308,40 @@ deliver downloaded as a NEW file — the on-disk original is its own rollback
default (per-browser opt-out in the About dialog) or on demand.
- Update channel = signed **code**; future sync channel = inert **data**
(invariant 3). Never mix the two.
+
+## 8. Live collaboration (bento-sync)
+
+The in-house CRDT designed in `collab-design.md`, shipped in v0.8.0.
+
+```
+slides/src/sync/crdt.ts engine: per-property LWW registers ordered by
+ (lamport, actor); birth/tomb liveness (an ins is
+ a whole-node assignment that resurrects by
+ out-stamping the tomb); fractional-index order
+ keys; dead-window value stash; token RGA for
+ element.html (deterministic content-hash seeds;
+ a generation duels plain sets AS A UNIT);
+ per-actor contiguous seq + gap buffering;
+ state-based mergeSnapshot for file forks
+slides/src/sync/session.ts the store bridge: local commits → debounced
+ shadow diff → ops out; remote ops → surgical
+ apply → the same store events the editor
+ already listens to. Presence, catch-up, peers.
+slides/src/sync/online.ts E2EE relay transport: AES-GCM under the room
+ key from doc.collab; ?tok= is a hash of the
+ key (possession proof); reconnect + backoff;
+ encrypted client-produced snapshots cap replay
+server/sync-worker/ Cloudflare Worker + one Durable Object per
+ docId: blind fan-out, encrypted op log, ~30-day
+ idle TTL. The only Bento server code.
+scripts/test-sync.ts property-based convergence rig (SEEDS/STEPS/
+ ACTORS env knobs) — random op interleavings
+ across simulated actors must converge to
+ byte-identical docs AND sync state
+```
+
+Same-machine tabs sync automatically (BroadcastChannel keyed by docId).
+Online: Share → Start live session mints `doc.collab {room, key}` — the
+saved FILE is the capability; anyone opening a copy joins and converges.
+The relay never sees plaintext, and every saved copy stays a complete,
+standalone document (sync is a layer beside the file, never a replacement).
diff --git a/docs/collab-design.md b/docs/collab-design.md
index b676afcf..5e506a5e 100644
--- a/docs/collab-design.md
+++ b/docs/collab-design.md
@@ -1,6 +1,15 @@
# Bento collaboration — CRDT design
-*Design document, July 2026. Status: proposed — implementation phased below.
+*Design document, July 2026. Status: **implemented** (M0–M3 shipped in
+v0.8.0) — `slides/src/sync/` (engine, session, online transport),
+`server/sync-worker/` (relay), `scripts/test-sync.ts` (convergence rig).
+Notable deviations from the proposal, all deliberate:
+share links became **the file itself** (doc.collab carries room + key —
+possession of a copy is the capability; a hosted `/s/` joiner page can wrap
+this later), actor ids are fresh per session instance (a reloaded tab is a
+new replica; the engine skips "own" ops on apply), the relay replay bookmark
+is memory-only (it is valid only alongside the CRDT state it was earned
+with), and M3 (text RGA) shipped with the engine rather than after it.
Companion to `architecture.md` §7 (updates) and the local-first principles in
`README.md`.*
diff --git a/server/sync-worker/.gitignore b/server/sync-worker/.gitignore
new file mode 100644
index 00000000..41a25789
--- /dev/null
+++ b/server/sync-worker/.gitignore
@@ -0,0 +1,2 @@
+.wrangler/
+node_modules/
diff --git a/server/sync-worker/src/worker.js b/server/sync-worker/src/worker.js
new file mode 100644
index 00000000..a29c61bb
--- /dev/null
+++ b/server/sync-worker/src/worker.js
@@ -0,0 +1,159 @@
+// bento-sync relay — the first (and only) Bento server code. One Durable
+// Object per docId room. The relay is BLIND by design:
+//
+// - every frame body is AES-GCM ciphertext produced by the clients; the
+// room key lives in the document file and never reaches this server
+// - auth is possession-proof: ?tok= is a hash of the room key. The first
+// client to open a room sets its token; everyone else must match it
+// - persisted state is an append-only list of encrypted op frames plus
+// the latest client-produced encrypted snapshot (the server cannot make
+// one — it can't read anything)
+// - rooms expire after ~30 idle days (the FILE is the durable artifact;
+// expiry costs convenience, never data)
+//
+// Envelope (JSON text frames, ≤ 1 MB):
+// client → server: { i, d } ephemeral (presence, hello, need)
+// { p:1, i, d } persist an op batch
+// { snap:1, q, i, d } encrypted snapshot covering seq ≤ q
+// server → clients: same frames fanned out, ops stamped with { q: seq };
+// on join: snapshot (if any) + ops since ?since= then
+// { ctl:'ready', q: latest }
+
+const IDLE_TTL_MS = 30 * 24 * 60 * 60 * 1000
+const MAX_FRAME = 1_000_000
+const RATE_BURST = 200 // frames per window per socket
+const RATE_WINDOW_MS = 10_000
+const OP_KEY = (seq) => `op:${String(seq).padStart(10, '0')}`
+
+export default {
+ async fetch(req, env) {
+ const url = new URL(req.url)
+ const m = url.pathname.match(/^\/d\/([A-Za-z0-9._-]{1,80})$/)
+ if (!m) {
+ return new Response('bento-sync relay — see https://bento.page', {
+ status: 200,
+ headers: { 'content-type': 'text/plain' },
+ })
+ }
+ const id = env.ROOM.idFromName(m[1])
+ return env.ROOM.get(id).fetch(req)
+ },
+}
+
+export class Room {
+ constructor(state) {
+ this.state = state
+ this.sockets = new Map() // ws → { count, windowStart }
+ }
+
+ async fetch(req) {
+ if (req.headers.get('Upgrade') !== 'websocket') {
+ return new Response('expected websocket', { status: 426 })
+ }
+ const url = new URL(req.url)
+ const tok = url.searchParams.get('tok') || ''
+ if (!/^[A-Za-z0-9_-]{10,64}$/.test(tok)) return new Response('bad token', { status: 400 })
+ const saved = await this.state.storage.get('tok')
+ if (saved === undefined) await this.state.storage.put('tok', tok)
+ else if (saved !== tok) return new Response('forbidden', { status: 403 })
+
+ const since = Math.max(0, parseInt(url.searchParams.get('since') || '0', 10) || 0)
+ const pair = new WebSocketPair()
+ const [client, server] = Object.values(pair)
+ server.accept()
+ this.sockets.set(server, { count: 0, windowStart: Date.now() })
+ server.addEventListener('message', (ev) => {
+ this.onMessage(server, ev).catch(() => {})
+ })
+ const drop = () => this.sockets.delete(server)
+ server.addEventListener('close', drop)
+ server.addEventListener('error', drop)
+
+ await this.replay(server, since)
+ await this.state.storage.setAlarm(Date.now() + IDLE_TTL_MS)
+ return new Response(null, { status: 101, webSocket: client })
+ }
+
+ async replay(ws, since) {
+ const seq = (await this.state.storage.get('seq')) || 0
+ const snap = await this.state.storage.get('snap')
+ let from = since
+ try {
+ if (snap && snap.q > since) {
+ ws.send(JSON.stringify({ snap: 1, q: snap.q, i: snap.i, d: snap.d }))
+ from = snap.q
+ }
+ if (seq > from) {
+ const ops = await this.state.storage.list({
+ start: OP_KEY(from + 1),
+ end: OP_KEY(seq + 1),
+ })
+ for (const [key, f] of ops) {
+ ws.send(JSON.stringify({ q: parseInt(key.slice(3), 10), i: f.i, d: f.d }))
+ }
+ }
+ ws.send(JSON.stringify({ ctl: 'ready', q: seq }))
+ } catch {
+ /* socket died mid-replay */
+ }
+ }
+
+ async onMessage(ws, ev) {
+ if (typeof ev.data !== 'string' || ev.data.length > MAX_FRAME) return
+ const meta = this.sockets.get(ws)
+ if (!meta) return
+ const now = Date.now()
+ if (now - meta.windowStart > RATE_WINDOW_MS) {
+ meta.windowStart = now
+ meta.count = 0
+ }
+ if (++meta.count > RATE_BURST) return
+ let f
+ try {
+ f = JSON.parse(ev.data)
+ } catch {
+ return
+ }
+ if (typeof f.i !== 'string' || typeof f.d !== 'string') return
+
+ const out = { i: f.i, d: f.d }
+ if (f.p === 1) {
+ const seq = ((await this.state.storage.get('seq')) || 0) + 1
+ await this.state.storage.put('seq', seq)
+ await this.state.storage.put(OP_KEY(seq), { i: f.i, d: f.d })
+ out.q = seq
+ // the sender needs its ack too (snapshot cadence keys off q)
+ try {
+ ws.send(JSON.stringify({ ctl: 'ack', q: seq }))
+ } catch {
+ /* gone */
+ }
+ } else if (f.snap === 1 && typeof f.q === 'number') {
+ // client-produced encrypted snapshot: keep the newest, prune covered ops
+ const cur = await this.state.storage.get('snap')
+ if (!cur || f.q > cur.q) {
+ await this.state.storage.put('snap', { q: f.q, i: f.i, d: f.d })
+ const dead = await this.state.storage.list({ start: OP_KEY(1), end: OP_KEY(f.q + 1) })
+ await this.state.storage.delete([...dead.keys()])
+ }
+ return // snapshots are storage-only, never fanned out
+ }
+
+ const text = JSON.stringify(out)
+ for (const [peer] of this.sockets) {
+ if (peer === ws) continue
+ try {
+ peer.send(text)
+ } catch {
+ this.sockets.delete(peer)
+ }
+ }
+ await this.state.storage.setAlarm(Date.now() + IDLE_TTL_MS)
+ }
+
+ async alarm() {
+ // ~30 days idle: the room evaporates. Files reopen fine — the document
+ // itself is the durable artifact; a fresh room re-forms on next join.
+ await this.state.storage.deleteAll()
+ }
+}
diff --git a/server/sync-worker/wrangler.toml b/server/sync-worker/wrangler.toml
new file mode 100644
index 00000000..34c3a69e
--- /dev/null
+++ b/server/sync-worker/wrangler.toml
@@ -0,0 +1,20 @@
+# bento-sync relay — Cloudflare Worker + one Durable Object room per docId.
+# Deploy: npx wrangler deploy (needs `npx wrangler login` once)
+# Dev: npx wrangler dev --port 8787 (fully local, no account needed)
+# Then point sync.bento.page at the worker (Custom Domain below, or a route).
+name = "bento-sync"
+main = "src/worker.js"
+compatibility_date = "2026-07-01"
+
+# workers.dev URL is fine to start; add the custom domain when ready:
+routes = [
+ { pattern = "sync.bento.page", custom_domain = true }
+]
+
+[[durable_objects.bindings]]
+name = "ROOM"
+class_name = "Room"
+
+[[migrations]]
+tag = "v1"
+new_sqlite_classes = ["Room"]
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index 5f9f1cd1..f2f9bd17 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -17,6 +17,7 @@ import { startPresentation } from '../present'
import { saveFile } from '../save'
import { ICONS } from '../icons'
import { t, setLocale, locale, LOCALE_CHOICES } from '../i18n'
+import { joinFromDoc, onlineTransport, startSharing, stopSharing } from '../sync/online'
const i18nT = t
@@ -39,6 +40,8 @@ export class Editor {
private presenting = false
private updatesB!: HTMLElement
private avatarsBox!: HTMLElement
+ private shareB!: HTMLElement
+ private shareWrap!: HTMLElement
private session: import('../sync/session').SyncSession | null = null
private updateFound: string | null = null
private lastAutoCheck: import('../update').UpdateCheck | null = null
@@ -66,7 +69,7 @@ export class Editor {
this.rebuildSidebar()
}
- /** wire the live-collaboration session (avatars, remote selections) */
+ /** wire the live-collaboration session (avatars, remote selections, relay) */
connectSync(session: import('../sync/session').SyncSession) {
this.session = session
session.onPeers(() => {
@@ -75,6 +78,28 @@ export class Editor {
})
this.canvas.onTextEditChange = (elId) => session.setEditing(elId)
this.store.on('current', () => this.canvas.setRemotePeers(session.peers()))
+ // a document that carries collab config joins its relay session — at
+ // boot AND whenever one is loaded (Replace-from-JSON, update splice…)
+ const joinIfShared = () => {
+ if (this.store.doc.collab && !onlineTransport()) {
+ joinFromDoc(session, this.store)
+ this.wireOnlineStatus()
+ }
+ }
+ joinIfShared()
+ this.store.on('doc', joinIfShared)
+ }
+
+ private wireOnlineStatus() {
+ const tr = onlineTransport()
+ if (!tr) {
+ this.shareB.classList.remove('ed-btn-live', 'ed-btn-connecting')
+ return
+ }
+ tr.onStatus = () => this.wireOnlineStatus()
+ this.shareB.classList.toggle('ed-btn-live', tr.status === 'open')
+ this.shareB.classList.toggle('ed-btn-connecting', tr.status !== 'open')
+ if (this.shareWrap.classList.contains('open')) this.renderSharePanel()
}
private renderAvatars() {
@@ -176,7 +201,7 @@ export class Editor {
const pdfB = btn(ICONS.pdf, '', () => this.exportPdf(), t('Export PDF (print)'))
const leftT = btn(ICONS.panelLeft, '', () => this.togglePanel('left'), t('Toggle slide list ([)'))
const rightT = btn(ICONS.panelRight, '', () => this.togglePanel('right'), t('Toggle properties (])'))
- actions.append(undoB, redoB, pdfB, this.updatesB, leftT, rightT, presentB, saveB, saveAsB)
+ actions.append(undoB, redoB, pdfB, this.shareDropdown(), this.updatesB, leftT, rightT, presentB, saveB, saveAsB)
this.avatarsBox = div('ed-avatars')
bar.append(logo, title, this.dirtyDot, this.avatarsBox, insert, actions)
@@ -264,6 +289,69 @@ export class Editor {
// the canvas wrap resizes; its ResizeObserver re-fits the stage
}
+ // --- live-collaboration Share popover ------------------------------------
+
+ private shareDropdown(): HTMLElement {
+ const wrap = div('ed-dropdown')
+ this.shareWrap = wrap
+ this.shareB = btn(ICONS.share, t('Share'), () => {
+ wrap.classList.toggle('open')
+ if (wrap.classList.contains('open')) this.renderSharePanel()
+ }, t('Live collaboration — work on this deck together'))
+ const panel = div('ed-menu ed-share-pop')
+ wrap.append(this.shareB, panel)
+ document.addEventListener('pointerdown', (ev) => {
+ if (!wrap.contains(ev.target as Node)) wrap.classList.remove('open')
+ })
+ return wrap
+ }
+
+ private renderSharePanel() {
+ const panel = this.shareWrap.querySelector<HTMLElement>('.ed-share-pop')!
+ panel.innerHTML = ''
+ const note = (txt: string, cls = 'ed-share-note') => {
+ const e = div(cls)
+ e.textContent = txt
+ panel.appendChild(e)
+ return e
+ }
+ const action = (label: string, primary: boolean, onClick: () => void) => {
+ const b = document.createElement('button')
+ b.className = primary ? 'ed-btn ed-btn-primary ed-share-btn' : 'ed-btn ed-share-btn'
+ b.textContent = label
+ b.addEventListener('click', onClick)
+ panel.appendChild(b)
+ return b
+ }
+ const tr = onlineTransport()
+ if (!this.store.doc.collab || !tr) {
+ note(t('Work on this deck together, live.'))
+ note(t('Everything is end-to-end encrypted — the relay only ever sees ciphertext.'))
+ action(t('Start live session'), true, () => {
+ if (!this.session) return
+ startSharing(this.session, this.store)
+ this.wireOnlineStatus()
+ this.renderSharePanel()
+ })
+ } else {
+ const status = note('', 'ed-share-status')
+ const n = (this.session?.peers().length ?? 0) + 1
+ status.textContent =
+ tr.status === 'open'
+ ? `● ${t('Live')} — ${t('{n} connected', { n })}`
+ : `● ${t('Offline — reconnecting…')}`
+ status.classList.toggle('ok', tr.status === 'open')
+ note(t('Save the file and send a copy — opening it joins this session automatically.'))
+ note(t('Everything is end-to-end encrypted — the relay only ever sees ciphertext.'))
+ action(t('Stop sharing'), false, () => {
+ if (!this.session) return
+ stopSharing(this.session, this.store)
+ this.wireOnlineStatus()
+ this.renderSharePanel()
+ })
+ }
+ }
+
private shapeDropdown(): HTMLElement {
const wrap = div('ed-dropdown')
const trigger = btn(ICONS.shapes, t('Shape'), () => wrap.classList.toggle('open'))
diff --git a/slides/src/i18n/de.ts b/slides/src/i18n/de.ts
index 6efda2c0..6677fe31 100644
--- a/slides/src/i18n/de.ts
+++ b/slides/src/i18n/de.ts
@@ -242,4 +242,15 @@ export const de: Catalog = {
"+ New state linked from this element": "+ Neuer Zustand, verlinkt von diesem Element",
"+ Save slide as layout…": "+ Folie als Layout speichern…",
"💬 whole slide": "💬 ganze Folie",
+ "{name} — on slide {n} (click to follow)": "{name} — auf Folie {n} (zum Folgen klicken)",
+ "Share": "Teilen",
+ "Live collaboration — work on this deck together": "Live-Zusammenarbeit — gemeinsam an diesem Deck arbeiten",
+ "Work on this deck together, live.": "Gemeinsam und live an diesem Deck arbeiten.",
+ "Everything is end-to-end encrypted — the relay only ever sees ciphertext.": "Alles ist Ende-zu-Ende-verschlüsselt — das Relay sieht nur Chiffretext.",
+ "Start live session": "Live-Sitzung starten",
+ "Stop sharing": "Freigabe beenden",
+ "Live": "Live",
+ "Offline — reconnecting…": "Offline — Verbindung wird wiederhergestellt…",
+ "Save the file and send a copy — opening it joins this session automatically.": "Datei speichern und eine Kopie senden — beim Öffnen tritt sie dieser Sitzung automatisch bei.",
+ "{n} connected": "{n} verbunden",
}
diff --git a/slides/src/i18n/es.ts b/slides/src/i18n/es.ts
index c1260684..fe322217 100644
--- a/slides/src/i18n/es.ts
+++ b/slides/src/i18n/es.ts
@@ -242,4 +242,15 @@ export const es: Catalog = {
"+ New state linked from this element": "+ Nuevo estado enlazado desde este elemento",
"+ Save slide as layout…": "+ Guardar diapositiva como diseño…",
"💬 whole slide": "💬 toda la diapositiva",
+ "{name} — on slide {n} (click to follow)": "{name} — en la diapositiva {n} (clic para seguir)",
+ "Share": "Compartir",
+ "Live collaboration — work on this deck together": "Colaboración en vivo — trabajad juntos en esta presentación",
+ "Work on this deck together, live.": "Trabajad juntos en esta presentación, en tiempo real.",
+ "Everything is end-to-end encrypted — the relay only ever sees ciphertext.": "Todo va cifrado de extremo a extremo: el relé solo ve texto cifrado.",
+ "Start live session": "Iniciar sesión en vivo",
+ "Stop sharing": "Dejar de compartir",
+ "Live": "En vivo",
+ "Offline — reconnecting…": "Sin conexión — reconectando…",
+ "Save the file and send a copy — opening it joins this session automatically.": "Guarda el archivo y envía una copia: al abrirla se une a esta sesión automáticamente.",
+ "{n} connected": "{n} conectados",
}
diff --git a/slides/src/i18n/fr.ts b/slides/src/i18n/fr.ts
index 7752f9ba..bea106c4 100644
--- a/slides/src/i18n/fr.ts
+++ b/slides/src/i18n/fr.ts
@@ -242,4 +242,15 @@ export const fr: Catalog = {
"+ New state linked from this element": "+ Nouvel état lié depuis cet élément",
"+ Save slide as layout…": "+ Enregistrer comme disposition…",
"💬 whole slide": "💬 toute la diapositive",
+ "{name} — on slide {n} (click to follow)": "{name} — sur la diapositive {n} (cliquer pour suivre)",
+ "Share": "Partager",
+ "Live collaboration — work on this deck together": "Collaboration en direct — travaillez ensemble sur ce diaporama",
+ "Work on this deck together, live.": "Travaillez ensemble sur ce diaporama, en direct.",
+ "Everything is end-to-end encrypted — the relay only ever sees ciphertext.": "Tout est chiffré de bout en bout — le relais ne voit que du texte chiffré.",
+ "Start live session": "Démarrer la session en direct",
+ "Stop sharing": "Arrêter le partage",
+ "Live": "En direct",
+ "Offline — reconnecting…": "Hors ligne — reconnexion…",
+ "Save the file and send a copy — opening it joins this session automatically.": "Enregistrez le fichier et envoyez une copie — l'ouvrir rejoint automatiquement cette session.",
+ "{n} connected": "{n} connectés",
}
diff --git a/slides/src/i18n/it.ts b/slides/src/i18n/it.ts
index f08d0dd4..44fd2ae3 100644
--- a/slides/src/i18n/it.ts
+++ b/slides/src/i18n/it.ts
@@ -242,4 +242,15 @@ export const it: Catalog = {
"+ New state linked from this element": "+ Nuovo stato collegato da questo elemento",
"+ Save slide as layout…": "+ Salva diapositiva come layout…",
"💬 whole slide": "💬 intera diapositiva",
+ "{name} — on slide {n} (click to follow)": "{name} — sulla diapositiva {n} (clic per seguire)",
+ "Share": "Condividi",
+ "Live collaboration — work on this deck together": "Collaborazione dal vivo — lavorate insieme su questa presentazione",
+ "Work on this deck together, live.": "Lavorate insieme su questa presentazione, in tempo reale.",
+ "Everything is end-to-end encrypted — the relay only ever sees ciphertext.": "Tutto è cifrato end-to-end: il relay vede solo testo cifrato.",
+ "Start live session": "Avvia sessione dal vivo",
+ "Stop sharing": "Interrompi condivisione",
+ "Live": "Dal vivo",
+ "Offline — reconnecting…": "Offline — riconnessione…",
+ "Save the file and send a copy — opening it joins this session automatically.": "Salva il file e invia una copia: aprendola ci si unisce automaticamente alla sessione.",
+ "{n} connected": "{n} connessi",
}
diff --git a/slides/src/i18n/ja.ts b/slides/src/i18n/ja.ts
index 09094618..8967bad4 100644
--- a/slides/src/i18n/ja.ts
+++ b/slides/src/i18n/ja.ts
@@ -242,4 +242,15 @@ export const ja: Catalog = {
"+ New state linked from this element": "+ この要素からリンクする新ステート",
"+ Save slide as layout…": "+ スライドをレイアウトとして保存…",
"💬 whole slide": "💬 スライド全体",
+ "{name} — on slide {n} (click to follow)": "{name} — スライド {n} を表示中(クリックで移動)",
+ "Share": "共有",
+ "Live collaboration — work on this deck together": "ライブ共同編集 — このデッキを一緒に編集",
+ "Work on this deck together, live.": "このデッキをリアルタイムで一緒に編集できます。",
+ "Everything is end-to-end encrypted — the relay only ever sees ciphertext.": "すべてエンドツーエンド暗号化 — 中継サーバーは暗号文しか見えません。",
+ "Start live session": "ライブセッションを開始",
+ "Stop sharing": "共有を停止",
+ "Live": "ライブ",
+ "Offline — reconnecting…": "オフライン — 再接続中…",
+ "Save the file and send a copy — opening it joins this session automatically.": "ファイルを保存してコピーを送ってください — 開くだけでこのセッションに参加できます。",
+ "{n} connected": "{n} 人が接続中",
}
diff --git a/slides/src/i18n/zh-Hans.ts b/slides/src/i18n/zh-Hans.ts
index e043497c..0c7f3504 100644
--- a/slides/src/i18n/zh-Hans.ts
+++ b/slides/src/i18n/zh-Hans.ts
@@ -242,4 +242,15 @@ export const zhHans: Catalog = {
"+ New state linked from this element": "+ 从此元素链接的新状态",
"+ Save slide as layout…": "+ 将幻灯片存为版式…",
"💬 whole slide": "💬 整张幻灯片",
+ "{name} — on slide {n} (click to follow)": "{name} — 正在第 {n} 页(点击跟随)",
+ "Share": "共享",
+ "Live collaboration — work on this deck together": "实时协作 — 一起编辑这套幻灯片",
+ "Work on this deck together, live.": "与他人实时共同编辑这套幻灯片。",
+ "Everything is end-to-end encrypted — the relay only ever sees ciphertext.": "全程端到端加密 — 中继服务器只能看到密文。",
+ "Start live session": "开始实时会话",
+ "Stop sharing": "停止共享",
+ "Live": "已连接",
+ "Offline — reconnecting…": "离线 — 正在重连…",
+ "Save the file and send a copy — opening it joins this session automatically.": "保存文件并发送副本 — 打开即可自动加入此会话。",
+ "{n} connected": "{n} 人已连接",
}
diff --git a/slides/src/i18n/zh-Hant.ts b/slides/src/i18n/zh-Hant.ts
index 5e63fe0c..e9fce8c1 100644
--- a/slides/src/i18n/zh-Hant.ts
+++ b/slides/src/i18n/zh-Hant.ts
@@ -242,4 +242,15 @@ export const zhHant: Catalog = {
"+ New state linked from this element": "+ 從此元素連結的新狀態",
"+ Save slide as layout…": "+ 將投影片存為版面配置…",
"💬 whole slide": "💬 整張投影片",
+ "{name} — on slide {n} (click to follow)": "{name} — 正在第 {n} 頁(點擊跟隨)",
+ "Share": "共用",
+ "Live collaboration — work on this deck together": "即時協作 — 一起編輯這份簡報",
+ "Work on this deck together, live.": "與他人即時共同編輯這份簡報。",
+ "Everything is end-to-end encrypted — the relay only ever sees ciphertext.": "全程端對端加密 — 中繼伺服器只會看到密文。",
+ "Start live session": "開始即時工作階段",
+ "Stop sharing": "停止共用",
+ "Live": "已連線",
+ "Offline — reconnecting…": "離線 — 正在重新連線…",
+ "Save the file and send a copy — opening it joins this session automatically.": "儲存檔案並傳送副本 — 開啟即會自動加入此工作階段。",
+ "{n} connected": "{n} 人已連線",
}
diff --git a/slides/src/icons.ts b/slides/src/icons.ts
index c1565e35..fcb68395 100644
--- a/slides/src/icons.ts
+++ b/slides/src/icons.ts
@@ -23,6 +23,7 @@ export const ICONS = {
panelRight: svg('<rect x="3" y="4" width="18" height="16" rx="2"/><line x1="15" y1="4" x2="15" y2="20"/>'),
pdf: svg('<polyline points="6 9 6 3 18 3 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/>'),
sync: svg('<path d="M21 12a9 9 0 1 1-2.64-6.36"/><polyline points="21 3 21 9 15 9"/>'),
+ share: svg('<circle cx="9" cy="8" r="3.2"/><path d="M3.5 20c.6-3.2 2.8-5 5.5-5s4.9 1.8 5.5 5"/><circle cx="17.5" cy="10.5" r="2.4"/><path d="M15.8 15.6c1.9.3 3.6 1.6 4.4 3.9"/>'),
// shape menu entries
rect: svg('<rect x="3" y="5" width="18" height="14" rx="2"/>'),
ellipse: svg('<ellipse cx="12" cy="12" rx="9" ry="7"/>'),
diff --git a/slides/src/main.ts b/slides/src/main.ts
index fceffad5..9a86f8c7 100644
--- a/slides/src/main.ts
+++ b/slides/src/main.ts
@@ -12,6 +12,7 @@ import { injectFonts } from './fonts'
import { Store } from './store'
import { Editor } from './editor/editor'
import { SyncSession } from './sync/session'
+import { onlineTransport, startSharing, stopSharing } from './sync/online'
capturePristine()
@@ -77,6 +78,13 @@ if (location.hash === '#present') {
peers: () => session.peers(),
flush: () => session.flush(),
transports: () => session.transportKinds,
+ /** start an online session (mints doc.collab, connects the relay) */
+ share: () => {
+ startSharing(session, store)
+ return store.doc.collab
+ },
+ unshare: () => stopSharing(session, store),
+ online: () => onlineTransport()?.status ?? 'off',
},
/**
* AI/tooling round-trip: replace the whole document from a JSON string
diff --git a/slides/src/model.ts b/slides/src/model.ts
index b3607e3f..3c3b682a 100644
--- a/slides/src/model.ts
+++ b/slides/src/model.ts
@@ -256,6 +256,14 @@ export interface BentoDoc {
* When absent, the editor offers its built-in starter layouts.
*/
layouts?: Slide[]
+ /**
+ * Live-collaboration room (bento-sync). Present only while a document is
+ * shared: `room` is the relay WebSocket URL, `key` the base64url AES-GCM
+ * room key. Possession of the file IS the capability — anyone who opens a
+ * copy joins the session (the relay itself only ever sees ciphertext).
+ * Never transmitted as sync ops; removed by "Stop sharing".
+ */
+ collab?: { room: string; key: string }
slides: Slide[]
modified: string
}
diff --git a/slides/src/styles.css b/slides/src/styles.css
index e4526324..4019a161 100644
--- a/slides/src/styles.css
+++ b/slides/src/styles.css
@@ -1053,3 +1053,36 @@ body.ed-col-resizing { cursor: col-resize; user-select: none; }
font: 600 11px/1.4 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
white-space: nowrap;
}
+.ed-share-pop {
+ min-width: 250px;
+ max-width: 290px;
+ padding: 12px;
+ gap: 9px;
+ right: 0;
+ left: auto;
+}
+.ed-share-note {
+ font-size: 12px;
+ line-height: 1.45;
+ color: var(--muted, #5d6b80);
+}
+.ed-share-status {
+ font-size: 12.5px;
+ font-weight: 600;
+ color: #b8860b;
+}
+.ed-share-status.ok { color: #2e8b57; }
+.ed-share-btn { justify-content: center; }
+.ed-btn-live { position: relative; }
+.ed-btn-live::after,
+.ed-btn-connecting::after {
+ content: '';
+ position: absolute;
+ top: 3px;
+ right: 3px;
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: #34a866;
+}
+.ed-btn-connecting::after { background: #d9a13b; }
diff --git a/slides/src/sync/online.ts b/slides/src/sync/online.ts
new file mode 100644
index 00000000..cc129e0e
--- /dev/null
+++ b/slides/src/sync/online.ts
@@ -0,0 +1,289 @@
+// bento-sync online transport — E2EE WebSocket to the blind relay
+// (server/sync-worker). Every session frame is AES-GCM encrypted with the
+// room key from doc.collab.key; the relay sees ciphertext, fan-out routing,
+// and nothing else. Auth is possession-proof: ?tok= is a hash of the key.
+//
+// Reconnects with backoff; frames queue while disconnected; op frames are
+// persisted server-side (envelope {p:1}) and replayed to joiners from their
+// last acked seq, with client-produced encrypted snapshots capping replay
+// length. See docs/collab-design.md.
+
+import type { Store } from '../store'
+import type { BentoDoc } from '../model'
+import type { SyncStateJSON } from './crdt'
+import type { Frame, SyncSession, Transport } from './session'
+
+export const DEFAULT_SYNC_HOST = 'wss://sync.bento.page'
+const SNAP_EVERY = 200 // ops between encrypted snapshot uploads
+
+const b64u = {
+ enc(bytes: Uint8Array): string {
+ let s = ''
+ for (const b of bytes) s += String.fromCharCode(b)
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
+ },
+ dec(s: string): Uint8Array {
+ 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
+ },
+}
+
+export function mintRoomKey(): string {
+ const bytes = new Uint8Array(32)
+ crypto.getRandomValues(bytes)
+ return b64u.enc(bytes)
+}
+
+/** dev override for the relay host (e.g. ws://localhost:8787) */
+export function syncHost(): string {
+ try {
+ return localStorage.getItem('bento-sync-url') || DEFAULT_SYNC_HOST
+ } catch {
+ return DEFAULT_SYNC_HOST
+ }
+}
+
+export type OnlineStatus = 'connecting' | 'open' | 'closed'
+
+export class OnlineTransport implements Transport {
+ readonly kind = 'online'
+ status: OnlineStatus = 'connecting'
+ onStatus: ((s: OnlineStatus) => void) | null = null
+ private ws: WebSocket | null = null
+ private key: CryptoKey | null = null
+ private queue: string[] = []
+ private closed = false
+ private backoff = 800
+ private url = ''
+ /**
+ * Replay bookmark — MEMORY ONLY, deliberately: it is valid only alongside
+ * the in-memory CRDT state it was earned with. A fresh join replays from
+ * the room's snapshot (or 0); reconnects of THIS session resume from here.
+ */
+ private seq = 0
+
+ constructor(
+ room: string,
+ private keyB64: string,
+ docId: string,
+ private onFrame: (f: Frame) => void,
+ private hooks: {
+ onSnap: (doc: BentoDoc, state: SyncStateJSON) => void
+ getSnapshot: () => { doc: BentoDoc; state: SyncStateJSON }
+ onOpen: () => void
+ },
+ ) {
+ void docId
+ this.init(room)
+ }
+
+ private async init(room: string) {
+ const raw = b64u.dec(this.keyB64)
+ this.key = await crypto.subtle.importKey('raw', raw as BufferSource, 'AES-GCM', false, [
+ 'encrypt',
+ 'decrypt',
+ ])
+ const tokDigest = new Uint8Array(await crypto.subtle.digest('SHA-256', raw as BufferSource))
+ const tok = b64u.enc(tokDigest.slice(0, 18))
+ this.url = `${room}?tok=${tok}`
+ this.connect()
+ }
+
+ private lastSeq(): number {
+ return this.seq
+ }
+
+ private saveSeq(q: number) {
+ if (q > this.seq) this.seq = q
+ }
+
+ private setStatus(s: OnlineStatus) {
+ this.status = s
+ this.onStatus?.(s)
+ }
+
+ private connect() {
+ if (this.closed) return
+ this.setStatus('connecting')
+ let ws: WebSocket
+ try {
+ ws = new WebSocket(`${this.url}&since=${this.lastSeq()}`)
+ } catch {
+ this.retry()
+ return
+ }
+ this.ws = ws
+ ws.onopen = () => {
+ this.backoff = 800
+ this.setStatus('open')
+ for (const text of this.queue.splice(0)) ws.send(text)
+ this.hooks.onOpen()
+ }
+ ws.onmessage = (ev) => {
+ this.onEnvelope(String(ev.data)).catch(() => {})
+ }
+ const drop = () => {
+ if (this.ws !== ws) return
+ this.ws = null
+ this.setStatus('closed')
+ this.retry()
+ }
+ ws.onclose = drop
+ ws.onerror = drop
+ }
+
+ private retry() {
+ if (this.closed) return
+ setTimeout(() => this.connect(), this.backoff)
+ this.backoff = Math.min(this.backoff * 1.8, 30000)
+ }
+
+ private async onEnvelope(text: string) {
+ let env: { i?: string; d?: string; q?: number; snap?: number; ctl?: string }
+ try {
+ env = JSON.parse(text)
+ } catch {
+ return
+ }
+ if (env.ctl === 'ack' || env.ctl === 'ready') {
+ if (typeof env.q === 'number') {
+ this.saveSeq(env.q)
+ this.maybeSnapshot(env.q)
+ }
+ return
+ }
+ if (!env.i || !env.d || !this.key) return
+ let payload: unknown
+ try {
+ const pt = await crypto.subtle.decrypt(
+ { name: 'AES-GCM', iv: b64u.dec(env.i) as BufferSource },
+ this.key,
+ b64u.dec(env.d) as BufferSource,
+ )
+ payload = JSON.parse(new TextDecoder().decode(pt))
+ } catch {
+ return // wrong key / corrupted — ignore
+ }
+ if (typeof env.q === 'number') this.saveSeq(env.q)
+ if (env.snap === 1) {
+ const s = payload as { doc: BentoDoc; state: SyncStateJSON }
+ if (s && s.doc && s.state) this.hooks.onSnap(s.doc, s.state)
+ return
+ }
+ this.onFrame(payload as Frame)
+ }
+
+ private snapInFlight = false
+
+ /** every SNAP_EVERY persisted ops, upload a fresh encrypted snapshot */
+ private async maybeSnapshot(q: number) {
+ if (q === 0 || q % SNAP_EVERY !== 0 || this.snapInFlight) return
+ this.snapInFlight = true
+ try {
+ const snap = this.hooks.getSnapshot()
+ const text = await this.encrypt(JSON.stringify(snap))
+ if (text && this.ws && this.ws.readyState === WebSocket.OPEN) {
+ this.ws.send(JSON.stringify({ snap: 1, q, i: text.i, d: text.d }))
+ }
+ } finally {
+ this.snapInFlight = false
+ }
+ }
+
+ private async encrypt(plain: string): Promise<{ i: string; d: string } | null> {
+ if (!this.key) return null
+ const iv = new Uint8Array(12)
+ crypto.getRandomValues(iv)
+ const ct = await crypto.subtle.encrypt(
+ { name: 'AES-GCM', iv: iv as BufferSource },
+ this.key,
+ new TextEncoder().encode(plain),
+ )
+ return { i: b64u.enc(iv), d: b64u.enc(new Uint8Array(ct)) }
+ }
+
+ send(frame: Frame) {
+ void (async () => {
+ const enc = await this.encrypt(JSON.stringify(frame))
+ if (!enc) return
+ const env = frame.t === 'ops' ? { p: 1, ...enc } : enc
+ const text = JSON.stringify(env)
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) this.ws.send(text)
+ else {
+ this.queue.push(text)
+ if (this.queue.length > 500) this.queue.shift()
+ }
+ })()
+ }
+
+ close() {
+ this.closed = true
+ this.ws?.close()
+ this.ws = null
+ this.setStatus('closed')
+ }
+}
+
+// --- share/join glue --------------------------------------------------------
+
+let active: OnlineTransport | null = null
+
+export function onlineTransport(): OnlineTransport | null {
+ return active
+}
+
+/** inert stand-in when a re-keyed document has no collab config */
+class NullTransport implements Transport {
+ readonly kind = 'off'
+ send() {}
+ close() {}
+}
+
+/** connect the session to the relay named in doc.collab (no-op without it) */
+export function joinFromDoc(session: SyncSession, store: Store): OnlineTransport | null {
+ if (active) return active
+ if (!store.doc.collab?.room || !store.doc.collab.key) return null
+ session.addTransport((docId, onFrame) => {
+ // re-invoked whenever the session re-keys (doc replaced): consult the
+ // CURRENT document — its collab config may differ or be absent
+ const collab = store.doc.collab
+ if (!collab?.room || !collab.key || store.doc.docId !== docId) {
+ active = null
+ return new NullTransport()
+ }
+ active?.close()
+ active = new OnlineTransport(collab.room, collab.key, docId, onFrame, {
+ onSnap: (doc, state) => session.applySnapshot(doc, state),
+ getSnapshot: () => session.snapshot(),
+ onOpen: () => session.hello(),
+ })
+ return active
+ })
+ return active
+}
+
+/** mint a key, stamp doc.collab, connect — the "Start live session" action */
+export function startSharing(session: SyncSession, store: Store): OnlineTransport {
+ if (active) return active
+ const room = `${syncHost()}/d/${encodeURIComponent(store.doc.docId)}`
+ const key = mintRoomKey()
+ store.commit(() => {
+ store.doc.collab = { room, key }
+ })
+ return joinFromDoc(session, store)!
+}
+
+/** drop doc.collab and disconnect — the "Stop sharing" action */
+export function stopSharing(session: SyncSession, store: Store) {
+ if (active) {
+ session.removeTransport(active)
+ active = null
+ }
+ if (store.doc.collab) {
+ store.commit(() => {
+ delete store.doc.collab
+ })
+ }
+}
diff --git a/slides/src/sync/session.ts b/slides/src/sync/session.ts
index 455ea635..83279592 100644
--- a/slides/src/sync/session.ts
+++ b/slides/src/sync/session.ts
@@ -73,18 +73,14 @@ const actorColor = (actor: string): string => {
return PEER_COLORS[h % PEER_COLORS.length]
}
-/** per-TAB actor id: two tabs on one file are two replicas */
+/**
+ * Actor id: fresh per SESSION INSTANCE, deliberately — a reloaded tab is a
+ * new replica with empty CRDT state, and the engine skips "own" ops on
+ * apply, so reusing an id would make relay replay of the previous
+ * incarnation's ops a no-op. Random ids sidestep the whole class.
+ */
function tabActor(): string {
- try {
- let a = sessionStorage.getItem('bento-actor')
- if (!a) {
- a = Math.random().toString(36).slice(2, 10)
- sessionStorage.setItem('bento-actor', a)
- }
- return a
- } catch {
- return Math.random().toString(36).slice(2, 10)
- }
+ return Math.random().toString(36).slice(2, 10)
}
const DIFF_DEBOUNCE_MS = 90
@@ -323,6 +319,34 @@ export class SyncSession {
this.peerListeners.forEach((fn) => fn())
}
+ // --- snapshots (online catch-up + file-fork merge) ------------------------
+
+ /** current (doc, sync-state) pair for an encrypted relay snapshot */
+ snapshot(): { doc: BentoDoc; state: import('./crdt').SyncStateJSON } {
+ this.flush()
+ return {
+ doc: JSON.parse(JSON.stringify(this.store.doc)) as BentoDoc,
+ state: JSON.parse(JSON.stringify(this.state.toJSON())),
+ }
+ }
+
+ /** merge a remote snapshot (relay replay for far-behind joiners) */
+ applySnapshot(rdoc: BentoDoc, rstate: import('./crdt').SyncStateJSON) {
+ this.flush()
+ this.applying = true
+ try {
+ const res = this.state.mergeSnapshot(this.store.doc, rdoc, rstate)
+ if (res.changed) this.afterRemoteChange(true)
+ } finally {
+ this.applying = false
+ }
+ }
+
+ /** re-announce (an online transport reconnected) */
+ hello() {
+ this.broadcast({ t: 'hello', a: this.actor, vv: this.state.vv, p: this.presence() })
+ }
+
// --- plumbing -------------------------------------------------------------
private send(frame: Frame) {