Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

bento-sync v0.8.1: creation-time credentials, identity fork, two-way offline merge

nyblnet52e43a73bbc8
diff --git a/CLAUDE.md b/CLAUDE.md
index b963f4dd..7c672607 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -161,13 +161,24 @@ One HTML file = the document + viewer + editor. See `README.md` for the vision.
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).
+ only with the CRDT state it was earned with). Credentials are minted AT
+ CREATION (session.attach → mintCollab: RANDOM room id, never docId —
+ re-share/fork rooms can't collide and the relay learns nothing), dormant
+ until `collab.on` (absent = true for v0.8.0 files); "Rotate keys" is
+ revocation. The saved FILE is the capability: opening a copy auto-joins
+ (editor.connectSync joinIfShared). Saves stamp `doc.collab.sync`
+ (SyncStateJSON via session.stampInto) so a copy edited OFFLINE rejoins as
+ a true fork: restored regs defend its edits, relay replay vv-dedups, and
+ a fork `snap` frame carries its state to peers (mergeSnapshot) — merge is
+ two-way, verified under partition. hello replies include a `need` (ops
+ minted before connecting flow back); onRelayReady re-sends log ops the
+ room's replay lacked. "Duplicate as new deck…" (About) = identity fork:
+ new docId + fresh creds, never syncs with its ancestor. Relay:
+ `server/sync-worker/` (blind DO, ciphertext-only storage — verified;
+ `npx wrangler dev --port 8787` + localStorage 'bento-sync-url' for local
+ testing; NEVER pipe wrangler dev through `head` — SIGPIPE kills it).
+ 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/architecture.md b/docs/architecture.md
index d63ad7f7..d57854cf 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -341,7 +341,12 @@ scripts/test-sync.ts property-based convergence rig (SEEDS/STEPS/
```
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.
+Online: credentials `doc.collab {room, key}` are minted at document
+CREATION (random room id) and stay dormant until Share flips `on` — so any
+copy sent BEFORE sharing started can still join, and "Rotate keys" revokes
+every previously sent copy. Saves stamp the CRDT state (`doc.collab.sync`),
+which is what lets a copy edited offline rejoin later and merge two-way:
+its registers defend its edits, the room's replay fills in what it missed.
+"Duplicate as new deck" re-mints identity for genuinely new documents.
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 5e506a5e..9267fb96 100644
--- a/docs/collab-design.md
+++ b/docs/collab-design.md
@@ -4,12 +4,18 @@
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.
+share links became **the file itself** — and since v0.8.1 credentials are
+minted at CREATION (random room ids, never docId), dormant behind
+`collab.on`, so "send the file first, share later" works and "Rotate keys"
+is revocation; a hosted `/s/` joiner page can wrap this later. Offline
+forks merge TWO-WAY: saves stamp the CRDT state into `doc.collab.sync`, a
+rejoining copy restores it, replay dedups by version vector, and a state
+snapshot frame carries the fork's edits to peers. "Duplicate as new deck"
+is the explicit identity fork (new docId + fresh credentials). 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
+(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/src/worker.js b/server/sync-worker/src/worker.js
index a29c61bb..2be875fc 100644
--- a/server/sync-worker/src/worker.js
+++ b/server/sync-worker/src/worker.js
@@ -79,7 +79,7 @@ export class Room {
const snap = await this.state.storage.get('snap')
let from = since
try {
- if (snap && snap.q > since) {
+ if (snap && (since === 0 || snap.q >= since)) {
ws.send(JSON.stringify({ snap: 1, q: snap.q, i: snap.i, d: snap.d }))
from = snap.q
}
diff --git a/slides/package.json b/slides/package.json
index 5bbec52a..3046a275 100644
--- a/slides/package.json
+++ b/slides/package.json
@@ -1,7 +1,7 @@
{
"name": "bento-slides",
"private": true,
- "version": "0.7.1",
+ "version": "0.8.0",
"type": "module",
"scripts": {
"dev": "vite",
@@ -21,4 +21,4 @@
"vite": "^7.1.1",
"vite-plugin-singlefile": "^2.3.3"
}
-}
+}
\ No newline at end of file
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index f2f9bd17..b1658e6b 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -5,7 +5,7 @@ import type { Store } from '../store'
import {
FORMAT_VERSION,
applyLayout, builtinLayouts, defaultChart, defaultImage, defaultShape, defaultText,
- instantiateLayout, layoutElementIds, uid,
+ instantiateLayout, layoutElementIds, newDocId, uid,
type ShapeKind, type Slide, type SlideElement,
} from '../model'
import { APP_VERSION, applyUpdate, applyUpdateInPlace, autoCheckEnabled, canUpdateInPlace, checkForUpdates, setAutoCheck } from '../update'
@@ -17,7 +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'
+import { joinFromDoc, mintCollab, onlineTransport, rotateKeys, sharingOn, startSharing, stopSharing } from '../sync/online'
const i18nT = t
@@ -81,7 +81,7 @@ export class Editor {
// 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()) {
+ if (sharingOn(this.store) && !onlineTransport()) {
joinFromDoc(session, this.store)
this.wireOnlineStatus()
}
@@ -324,8 +324,9 @@ export class Editor {
return b
}
const tr = onlineTransport()
- if (!this.store.doc.collab || !tr) {
+ if (!sharingOn(this.store) || !tr) {
note(t('Work on this deck together, live.'))
+ note(t('Any copy of this file can join once sharing is on — send it before or after, both work.'))
note(t('Everything is end-to-end encrypted — the relay only ever sees ciphertext.'))
action(t('Start live session'), true, () => {
if (!this.session) return
@@ -333,6 +334,12 @@ export class Editor {
this.wireOnlineStatus()
this.renderSharePanel()
})
+ action(t('Rotate keys — cut off previously sent copies'), false, () => {
+ if (!this.session) return
+ rotateKeys(this.session, this.store)
+ this.toast(t('New keys minted — only copies saved from now on can join'))
+ this.renderSharePanel()
+ })
} else {
const status = note('', 'ed-share-status')
const n = (this.session?.peers().length ?? 0) + 1
@@ -708,6 +715,9 @@ export class Editor {
async save(forcePicker: boolean) {
this.canvas.commitTextEdit()
+ // shared docs persist their CRDT state so the saved copy can rejoin
+ // as a true fork later (offline edits merge both ways)
+ this.session?.stampInto(this.store.doc)
try {
const result = await saveFile(this.store.doc, forcePicker)
if (result === 'cancelled') return
@@ -939,6 +949,7 @@ export class Editor {
inPlaceB.disabled = true
inPlaceB.textContent = t('Verifying…')
try {
+ this.session?.stampInto(this.store.doc)
const written = await applyUpdateInPlace(release, this.store.doc)
if (written) done()
else { inPlaceB.disabled = false; inPlaceB.textContent = t('Update this file…') }
@@ -954,6 +965,7 @@ export class Editor {
getB.disabled = true
getB.textContent = t('Verifying…')
try {
+ this.session?.stampInto(this.store.doc)
await applyUpdate(release, this.store.doc)
getB.textContent = t('Downloaded ✓')
const note = div('ed-about-notes')
@@ -1042,6 +1054,25 @@ export class Editor {
aiRow.append(copyB, replB)
box.appendChild(aiRow)
+ // identity fork: same content, brand-new document — new docId + fresh
+ // collab credentials, so it never syncs with its ancestor's copies
+ const dupRow = div('ed-about-row')
+ const dupB = document.createElement('button')
+ dupB.className = 'ed-btn'
+ dupB.textContent = t('Duplicate as new deck…')
+ dupB.title = t('Copies everything into an independent document with its own identity — it will never sync with this one.')
+ dupB.addEventListener('click', () => {
+ const clone = JSON.parse(JSON.stringify(this.store.doc)) as import('../model').BentoDoc
+ clone.docId = newDocId()
+ clone.collab = mintCollab()
+ this.store.replaceDoc(clone)
+ close()
+ this.toast(t('This is now a new deck — save it under a new name'))
+ void this.save(true)
+ })
+ dupRow.append(dupB)
+ box.appendChild(dupRow)
+
const fine = div('ed-about-fine')
fine.innerHTML =
`${t('Checks contact the release server and send nothing about you or this document — no ids, no telemetry.')}<br>` +
diff --git a/slides/src/i18n/de.ts b/slides/src/i18n/de.ts
index 6677fe31..b46a2afb 100644
--- a/slides/src/i18n/de.ts
+++ b/slides/src/i18n/de.ts
@@ -253,4 +253,10 @@ export const de: Catalog = {
"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",
+ "Any copy of this file can join once sharing is on — send it before or after, both work.": "Jede Kopie dieser Datei kann beitreten, sobald das Teilen aktiv ist — vorher oder nachher gesendet, beides funktioniert.",
+ "Rotate keys — cut off previously sent copies": "Schlüssel erneuern — bereits versandte Kopien aussperren",
+ "New keys minted — only copies saved from now on can join": "Neue Schlüssel erzeugt — nur ab jetzt gespeicherte Kopien können beitreten",
+ "Duplicate as new deck…": "Als neues Deck duplizieren…",
+ "Copies everything into an independent document with its own identity — it will never sync with this one.": "Kopiert alles in ein unabhängiges Dokument mit eigener Identität — es synchronisiert sich nie mit diesem.",
+ "This is now a new deck — save it under a new name": "Dies ist jetzt ein neues Deck — unter neuem Namen speichern",
}
diff --git a/slides/src/i18n/es.ts b/slides/src/i18n/es.ts
index fe322217..6ff487b2 100644
--- a/slides/src/i18n/es.ts
+++ b/slides/src/i18n/es.ts
@@ -253,4 +253,10 @@ export const es: Catalog = {
"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",
+ "Any copy of this file can join once sharing is on — send it before or after, both work.": "Cualquier copia de este archivo puede unirse cuando el uso compartido esté activo: da igual enviarla antes o después.",
+ "Rotate keys — cut off previously sent copies": "Rotar claves — cortar el acceso a copias ya enviadas",
+ "New keys minted — only copies saved from now on can join": "Claves nuevas generadas: solo podrán unirse las copias guardadas a partir de ahora",
+ "Duplicate as new deck…": "Duplicar como presentación nueva…",
+ "Copies everything into an independent document with its own identity — it will never sync with this one.": "Copia todo en un documento independiente con identidad propia: nunca se sincronizará con este.",
+ "This is now a new deck — save it under a new name": "Esta ya es una presentación nueva: guárdala con otro nombre",
}
diff --git a/slides/src/i18n/fr.ts b/slides/src/i18n/fr.ts
index bea106c4..e2762572 100644
--- a/slides/src/i18n/fr.ts
+++ b/slides/src/i18n/fr.ts
@@ -253,4 +253,10 @@ export const fr: Catalog = {
"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",
+ "Any copy of this file can join once sharing is on — send it before or after, both work.": "Toute copie de ce fichier peut rejoindre dès que le partage est actif — envoyée avant ou après, les deux marchent.",
+ "Rotate keys — cut off previously sent copies": "Renouveler les clés — couper l'accès aux copies déjà envoyées",
+ "New keys minted — only copies saved from now on can join": "Nouvelles clés générées — seules les copies enregistrées à partir de maintenant pourront rejoindre",
+ "Duplicate as new deck…": "Dupliquer comme nouveau diaporama…",
+ "Copies everything into an independent document with its own identity — it will never sync with this one.": "Copie tout dans un document indépendant avec sa propre identité — il ne se synchronisera jamais avec celui-ci.",
+ "This is now a new deck — save it under a new name": "C'est maintenant un nouveau diaporama — enregistrez-le sous un nouveau nom",
}
diff --git a/slides/src/i18n/it.ts b/slides/src/i18n/it.ts
index 44fd2ae3..86ab3680 100644
--- a/slides/src/i18n/it.ts
+++ b/slides/src/i18n/it.ts
@@ -253,4 +253,10 @@ export const it: Catalog = {
"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",
+ "Any copy of this file can join once sharing is on — send it before or after, both work.": "Qualsiasi copia di questo file può unirsi quando la condivisione è attiva: inviata prima o dopo, funziona comunque.",
+ "Rotate keys — cut off previously sent copies": "Ruota le chiavi — revoca le copie già inviate",
+ "New keys minted — only copies saved from now on can join": "Nuove chiavi generate: solo le copie salvate d'ora in poi potranno unirsi",
+ "Duplicate as new deck…": "Duplica come nuova presentazione…",
+ "Copies everything into an independent document with its own identity — it will never sync with this one.": "Copia tutto in un documento indipendente con identità propria: non si sincronizzerà mai con questo.",
+ "This is now a new deck — save it under a new name": "Ora è una nuova presentazione: salvala con un altro nome",
}
diff --git a/slides/src/i18n/ja.ts b/slides/src/i18n/ja.ts
index 8967bad4..ae765f51 100644
--- a/slides/src/i18n/ja.ts
+++ b/slides/src/i18n/ja.ts
@@ -253,4 +253,10 @@ export const ja: Catalog = {
"Offline — reconnecting…": "オフライン — 再接続中…",
"Save the file and send a copy — opening it joins this session automatically.": "ファイルを保存してコピーを送ってください — 開くだけでこのセッションに参加できます。",
"{n} connected": "{n} 人が接続中",
+ "Any copy of this file can join once sharing is on — send it before or after, both work.": "共有をオンにすると、このファイルのどのコピーからでも参加できます — 送るのは前でも後でも構いません。",
+ "Rotate keys — cut off previously sent copies": "キーを更新 — 送付済みコピーのアクセスを遮断",
+ "New keys minted — only copies saved from now on can join": "新しいキーを発行しました — 今後保存したコピーのみ参加できます",
+ "Duplicate as new deck…": "新しいデッキとして複製…",
+ "Copies everything into an independent document with its own identity — it will never sync with this one.": "すべてを独立した新しいドキュメントに複製します — 元のファイルと同期することはありません。",
+ "This is now a new deck — save it under a new name": "新しいデッキになりました — 新しい名前で保存してください",
}
diff --git a/slides/src/i18n/zh-Hans.ts b/slides/src/i18n/zh-Hans.ts
index 0c7f3504..6c64d0ad 100644
--- a/slides/src/i18n/zh-Hans.ts
+++ b/slides/src/i18n/zh-Hans.ts
@@ -253,4 +253,10 @@ export const zhHans: Catalog = {
"Offline — reconnecting…": "离线 — 正在重连…",
"Save the file and send a copy — opening it joins this session automatically.": "保存文件并发送副本 — 打开即可自动加入此会话。",
"{n} connected": "{n} 人已连接",
+ "Any copy of this file can join once sharing is on — send it before or after, both work.": "开启共享后,此文件的任何副本都能加入 — 先发后发都可以。",
+ "Rotate keys — cut off previously sent copies": "轮换密钥 — 切断此前发出的副本",
+ "New keys minted — only copies saved from now on can join": "已生成新密钥 — 只有此后保存的副本才能加入",
+ "Duplicate as new deck…": "复制为新演示文稿…",
+ "Copies everything into an independent document with its own identity — it will never sync with this one.": "将全部内容复制到具有独立身份的新文档 — 它永远不会与当前文档同步。",
+ "This is now a new deck — save it under a new name": "这已是新演示文稿 — 请用新名称保存",
}
diff --git a/slides/src/i18n/zh-Hant.ts b/slides/src/i18n/zh-Hant.ts
index e9fce8c1..5587ba3e 100644
--- a/slides/src/i18n/zh-Hant.ts
+++ b/slides/src/i18n/zh-Hant.ts
@@ -253,4 +253,10 @@ export const zhHant: Catalog = {
"Offline — reconnecting…": "離線 — 正在重新連線…",
"Save the file and send a copy — opening it joins this session automatically.": "儲存檔案並傳送副本 — 開啟即會自動加入此工作階段。",
"{n} connected": "{n} 人已連線",
+ "Any copy of this file can join once sharing is on — send it before or after, both work.": "開啟共用後,此檔案的任何副本都能加入 — 先傳後傳都可以。",
+ "Rotate keys — cut off previously sent copies": "輪替金鑰 — 切斷先前送出的副本",
+ "New keys minted — only copies saved from now on can join": "已產生新金鑰 — 只有之後儲存的副本才能加入",
+ "Duplicate as new deck…": "複製為新簡報…",
+ "Copies everything into an independent document with its own identity — it will never sync with this one.": "將全部內容複製到具有獨立身分的新文件 — 它永遠不會與目前文件同步。",
+ "This is now a new deck — save it under a new name": "這已是新簡報 — 請用新名稱儲存",
}
diff --git a/slides/src/main.ts b/slides/src/main.ts
index 9a86f8c7..95c816cb 100644
--- a/slides/src/main.ts
+++ b/slides/src/main.ts
@@ -60,7 +60,10 @@ if (location.hash === '#present') {
get doc() {
return store.doc
},
- serialize: () => serializeFile(store.doc),
+ serialize: () => {
+ session.stampInto(store.doc)
+ return serializeFile(store.doc)
+ },
undo: () => store.undo(),
redo: () => store.redo(),
get selection() {
@@ -106,8 +109,14 @@ if (location.hash === '#present') {
updates: {
version: APP_VERSION,
check: (url?: string) => checkForUpdates(url),
- build: (release: any) => buildUpdatedFile(release, store.doc),
- apply: (release: any) => applyUpdate(release, store.doc),
+ build: (release: any) => {
+ session.stampInto(store.doc)
+ return buildUpdatedFile(release, store.doc)
+ },
+ apply: (release: any) => {
+ session.stampInto(store.doc)
+ return applyUpdate(release, store.doc)
+ },
},
/**
* Flat list of every review comment thread — the entry point for tooling
diff --git a/slides/src/model.ts b/slides/src/model.ts
index 3c3b682a..2b44113a 100644
--- a/slides/src/model.ts
+++ b/slides/src/model.ts
@@ -257,13 +257,23 @@ export interface BentoDoc {
*/
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".
+ * Live-collaboration credentials (bento-sync), minted AT CREATION so any
+ * copy of the file can join once sharing is turned on ("send the file
+ * first, share later" just works). `room` is the relay WebSocket URL
+ * (random id — never derived from docId), `key` the base64url AES-GCM
+ * room key. `on` gates auto-join: absent = true (v0.8.0 files only carried
+ * collab while actively shared). Possession of a copy IS the capability;
+ * "Rotate keys" re-mints both to cut old copies off. `sync` is the saved
+ * CRDT state (registers/liveness/text) stamped at save-time on shared
+ * documents — it is what lets an offline-edited copy rejoin as a true
+ * fork and merge both ways. Never transmitted as sync ops.
*/
- collab?: { room: string; key: string }
+ collab?: {
+ room: string
+ key: string
+ on?: boolean
+ sync?: import('./sync/crdt').SyncStateJSON
+ }
slides: Slide[]
modified: string
}
diff --git a/slides/src/sync/online.ts b/slides/src/sync/online.ts
index cc129e0e..b6934f20 100644
--- a/slides/src/sync/online.ts
+++ b/slides/src/sync/online.ts
@@ -36,6 +36,19 @@ export function mintRoomKey(): string {
return b64u.enc(bytes)
}
+/**
+ * Fresh collaboration credentials, minted at DOCUMENT CREATION and dormant
+ * (on:false) until sharing starts. The room id is random — never derived
+ * from docId — so distinct sharing lineages can never collide on a room
+ * (and the relay learns nothing about document identity). Everyone else
+ * READS the room from the file; only minting is random.
+ */
+export function mintCollab(): { room: string; key: string; on: boolean } {
+ const id = new Uint8Array(12)
+ crypto.getRandomValues(id)
+ return { room: `${syncHost()}/d/r${b64u.enc(id)}`, key: mintRoomKey(), on: false }
+}
+
/** dev override for the relay host (e.g. ws://localhost:8787) */
export function syncHost(): string {
try {
@@ -73,12 +86,17 @@ export class OnlineTransport implements Transport {
onSnap: (doc: BentoDoc, state: SyncStateJSON) => void
getSnapshot: () => { doc: BentoDoc; state: SyncStateJSON }
onOpen: () => void
+ /** replay done: (actor,seq) pairs the room holds; return true to upload a snapshot */
+ onReady: (seen: Set<string>, seq: number) => boolean
},
) {
void docId
this.init(room)
}
+ /** (actor,seq) pairs seen in the current connection's replay */
+ private replaySeen = new Set<string>()
+
private async init(room: string) {
const raw = b64u.dec(this.keyB64)
this.key = await crypto.subtle.importKey('raw', raw as BufferSource, 'AES-GCM', false, [
@@ -117,6 +135,8 @@ export class OnlineTransport implements Transport {
this.ws = ws
ws.onopen = () => {
this.backoff = 800
+ this.inReplay = true
+ this.replaySeen = new Set()
this.setStatus('open')
for (const text of this.queue.splice(0)) ws.send(text)
this.hooks.onOpen()
@@ -152,6 +172,14 @@ export class OnlineTransport implements Transport {
this.saveSeq(env.q)
this.maybeSnapshot(env.q)
}
+ if (env.ctl === 'ready') {
+ this.inReplay = false
+ const wantSnap = this.hooks.onReady(this.replaySeen, env.q ?? 0)
+ this.replaySeen = new Set()
+ // fresh rooms and just-merged forks get a snapshot immediately so
+ // late joiners converge without needing the full op log
+ if (wantSnap || env.q === 0) void this.uploadSnapshot(env.q ?? 0)
+ }
return
}
if (!env.i || !env.d || !this.key) return
@@ -172,14 +200,26 @@ export class OnlineTransport implements Transport {
if (s && s.doc && s.state) this.hooks.onSnap(s.doc, s.state)
return
}
- this.onFrame(payload as Frame)
+ const frame = payload as Frame
+ if (this.inReplay && frame.t === 'ops') {
+ for (const op of frame.ops) this.replaySeen.add(`${op.a}:${op.s}`)
+ }
+ this.onFrame(frame)
}
+ private inReplay = true
+
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
+ private maybeSnapshot(q: number) {
+ if (q === 0 || q % SNAP_EVERY !== 0) return
+ void this.uploadSnapshot(q)
+ }
+
+ /** encrypt + store the current (doc, state) as the room's snapshot */
+ async uploadSnapshot(q: number) {
+ if (this.snapInFlight) return
this.snapInFlight = true
try {
const snap = this.hooks.getSnapshot()
@@ -241,15 +281,22 @@ class NullTransport implements Transport {
close() {}
}
-/** connect the session to the relay named in doc.collab (no-op without it) */
+/** does this document want its relay connected? (absent `on` = true: v0.8.0
+ * files only carried collab while actively shared) */
+export function sharingOn(store: Store): boolean {
+ const c = store.doc.collab
+ return !!c?.room && !!c.key && c.on !== false
+}
+
+/** connect the session to the relay in doc.collab (no-op unless sharing is on) */
export function joinFromDoc(session: SyncSession, store: Store): OnlineTransport | null {
if (active) return active
- if (!store.doc.collab?.room || !store.doc.collab.key) return null
+ if (!sharingOn(store)) 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
+ // CURRENT document — its collab config may differ or be off
const collab = store.doc.collab
- if (!collab?.room || !collab.key || store.doc.docId !== docId) {
+ if (!collab?.room || !collab.key || collab.on === false || store.doc.docId !== docId) {
active = null
return new NullTransport()
}
@@ -258,32 +305,45 @@ export function joinFromDoc(session: SyncSession, store: Store): OnlineTransport
onSnap: (doc, state) => session.applySnapshot(doc, state),
getSnapshot: () => session.snapshot(),
onOpen: () => session.hello(),
+ onReady: (seen) => session.onRelayReady(seen),
})
return active
})
return active
}
-/** mint a key, stamp doc.collab, connect — the "Start live session" action */
+/** flip sharing on and connect — the "Start live session" action.
+ * Credentials already exist (minted at creation); this only arms them. */
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 }
+ if (!store.doc.collab) store.doc.collab = mintCollab()
+ store.doc.collab.on = true
})
return joinFromDoc(session, store)!
}
-/** drop doc.collab and disconnect — the "Stop sharing" action */
+/** flip sharing off and disconnect. Credentials stay — copies saved during
+ * the session can rejoin if sharing is turned back on. */
export function stopSharing(session: SyncSession, store: Store) {
if (active) {
session.removeTransport(active)
active = null
}
- if (store.doc.collab) {
+ if (store.doc.collab && store.doc.collab.on !== false) {
store.commit(() => {
- delete store.doc.collab
+ store.doc.collab!.on = false
})
}
}
+
+/** revocation: mint a fresh room + key. Every previously sent copy loses
+ * access; only copies saved AFTER this can join future sessions. */
+export function rotateKeys(session: SyncSession, store: Store) {
+ stopSharing(session, store)
+ store.commit(() => {
+ const fresh = mintCollab()
+ const sync = store.doc.collab?.sync
+ store.doc.collab = sync ? { ...fresh, sync } : fresh
+ })
+}
diff --git a/slides/src/sync/session.ts b/slides/src/sync/session.ts
index 83279592..0067fa28 100644
--- a/slides/src/sync/session.ts
+++ b/slides/src/sync/session.ts
@@ -19,6 +19,7 @@ import type { Store } from '../store'
import type { BentoDoc, Slide } from '../model'
import { uid } from '../model'
import { SyncState, type Op } from './crdt'
+import { mintCollab } from './online'
export interface PresenceInfo {
name: string
@@ -41,7 +42,14 @@ interface OpsFrame { t: 'ops'; a: string; ops: Op[] }
interface NeedFrame { t: 'need'; a: string; vv: Record<string, number> }
interface PresFrame { t: 'p'; a: string; p: PresenceInfo }
interface ByeFrame { t: 'bye'; a: string }
-export type Frame = HelloFrame | OpsFrame | NeedFrame | PresFrame | ByeFrame
+/** state-based fork merge: a rejoining offline-edited copy announces itself */
+interface SnapFrame {
+ t: 'snap'
+ a: string
+ doc: BentoDoc
+ state: import('./crdt').SyncStateJSON
+}
+export type Frame = HelloFrame | OpsFrame | NeedFrame | PresFrame | ByeFrame | SnapFrame
export interface Transport {
readonly kind: string
@@ -114,18 +122,36 @@ export class SyncSession {
// --- lifecycle -----------------------------------------------------------
+ /** a restored offline fork still owes the room its snapshot */
+ private forkPending = false
+
private attach() {
this.docId = this.store.doc.docId
- this.state = new SyncState(this.actor)
- this.state.adopt(this.store.doc)
- this.shadow = JSON.stringify(this.store.doc)
+ const doc = this.store.doc
+ // credentials are minted AT CREATION (Andy's call): any copy of the
+ // file can join once sharing is turned on — "send first, share later"
+ // just works. Dormant (on:false) until the Share button flips it.
+ if (!doc.collab) doc.collab = mintCollab()
+ const saved = doc.collab?.sync
+ if (saved) {
+ // this file was saved during/after a shared session: restore the CRDT
+ // state so our offline edits carry real registers, remote replay
+ // dedups by version vector, and a state-based snapshot exchange can
+ // merge the fork BOTH ways (see docs/collab-design.md)
+ this.state = SyncState.fromJSON(this.actor, JSON.parse(JSON.stringify(saved)))
+ this.forkPending = true
+ } else {
+ this.state = new SyncState(this.actor)
+ }
+ this.state.adopt(doc)
+ this.shadow = JSON.stringify(doc)
this.log = []
this.peersMap.clear()
this.emitPeers()
for (const tr of this.transports) tr.close()
this.transports = [new BroadcastTransport(this.docId, (f) => this.onFrame(f))]
for (const mk of this.makeExtraTransports) this.transports.push(mk(this.docId, (f) => this.onFrame(f)))
- this.broadcast({ t: 'hello', a: this.actor, vv: this.state.vv, p: this.presence() })
+ this.hello() // announces + (for restored forks) broadcasts the state snapshot
if (this.heartbeat) clearInterval(this.heartbeat)
this.heartbeat = window.setInterval(() => {
this.pushPresence()
@@ -186,8 +212,11 @@ export class SyncSession {
switch (f.t) {
case 'hello': {
this.touchPeer(f.a, f.p)
- // answer so the newcomer learns us + catch them up from our log
+ // answer so the newcomer learns us + catch them up from our log,
+ // AND tell them our vv so ops they minted before connecting (which
+ // nothing else would push) flow back to us — need→ops terminates
this.send({ t: 'p', a: this.actor, p: this.presence() })
+ this.send({ t: 'need', a: this.actor, vv: this.state.vv })
const missing = this.state.missingFor(this.log, f.vv)
if (missing.length) this.send({ t: 'ops', a: this.actor, ops: missing })
break
@@ -203,6 +232,9 @@ export class SyncSession {
case 'p':
this.touchPeer(f.a, f.p)
break
+ case 'snap':
+ this.applySnapshot(f.doc, f.state)
+ break
case 'bye':
this.peersMap.delete(f.a)
this.emitPeers()
@@ -345,6 +377,37 @@ export class SyncSession {
/** re-announce (an online transport reconnected) */
hello() {
this.broadcast({ t: 'hello', a: this.actor, vv: this.state.vv, p: this.presence() })
+ if (this.forkPending) {
+ // rejoining offline fork: our contributions live in doc values +
+ // restored registers, not ops — a state snapshot is how they travel
+ const s = this.snapshot()
+ this.broadcast({ t: 'snap', a: this.actor, doc: s.doc, state: s.state })
+ }
+ }
+
+ /**
+ * Relay replay finished. `seen` holds the (actor,seq) pairs the room
+ * already has; anything in our log it lacks gets (re)sent for persistence
+ * — covers ops minted before the transport connected. Returns whether a
+ * fresh server snapshot should be uploaded (fork just merged).
+ */
+ onRelayReady(seen: Set<string>): boolean {
+ const missing = this.log.filter((o) => !seen.has(`${o.a}:${o.s}`))
+ if (missing.length) this.send({ t: 'ops', a: this.actor, ops: missing })
+ const fork = this.forkPending
+ this.forkPending = false
+ return fork
+ }
+
+ /**
+ * Stamp the CRDT state into doc.collab.sync so the SAVED file can rejoin
+ * as a true fork later. Called by the save/serialize paths; only shared
+ * documents carry it (never-shared files stay clean).
+ */
+ stampInto(doc: BentoDoc) {
+ if (!doc.collab || doc.collab.on === false) return
+ this.flush()
+ doc.collab.sync = JSON.parse(JSON.stringify(this.state.toJSON()))
}
// --- plumbing -------------------------------------------------------------