Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

Signed writes: enforced read-only over a still-blind relay (protocol layer)

nyblnet3b9af5d4e1d3
diff --git a/docs/collab-design.md b/docs/collab-design.md
index ee9fee4a..50a62ecc 100644
--- a/docs/collab-design.md
+++ b/docs/collab-design.md
@@ -266,6 +266,86 @@ verified names — layered ON TOP of the existing protocol (a signature field
in frames), relay still blind, local-first files unchanged. Nothing shipped
today constrains that design.
+## Signed writes — enforced read-only (v0.9.18)
+
+The relay's only gate today is `?tok = SHA-256(key)` — possession of the room
+key proves the right to *read and write*. That means "read-only" could only
+ever be a client-side courtesy: a viewer must hold the key to decrypt, and
+holding the key means being able to encrypt and send too. **Signed writes**
+split that single capability into two, so read-only becomes something the
+relay ENFORCES — while the relay stays blind to content.
+
+### The two capabilities
+
+- **Content key** (`collab.key`, symmetric AES-GCM, unchanged): the READ
+ capability. Every copy — writers and viewers — carries it. `?tok` still
+ proves possession so the relay won't even fan ciphertext to a stranger.
+- **Writer keypair** (ECDSA P-256, new): the WRITE capability. Minted once
+ per room at creation. `collab.writerPub` (raw SPKI, base64url) travels in
+ EVERY copy; `collab.writerPriv` (PKCS#8/JWK) travels ONLY in writer copies.
+ A **read-only copy is a writer copy with `writerPriv` stripped.**
+
+### Binding the pubkey to the room (trustless, no TOFU)
+
+The relay must know a room's writer pubkey without trusting the client that
+presents it — a viewer legitimately holds the room id, so first-writer TOFU
+would let a viewer pin *their own* key and become the writer. So the room id
+**commits** to the pubkey:
+
+ room name = "w" + base64url(SHA-256(writerPubRaw)) (new, signed)
+ room name = "r" + base64url(random) (legacy, v0.8–0.9.17)
+
+The leading char is the scheme selector. On connect a client passes
+`?w=<writerPubRaw>`; the relay checks `"w"+b64url(sha256(w)) === roomName`
+before pinning it. A viewer passes the same (correct) pubkey — it's public and
+in the file — but cannot forge signatures without the private half.
+
+### What is signed, and how
+
+Only the frames that mutate what a joiner sees are signed: **op batches**
+(`{p:1}`) and **snapshots** (`{snap:1}`). Ephemeral frames (hello / need /
+presence / bye) pass unsigned. The signature is ECDSA-P256/SHA-256 over the
+UTF-8 of `` `${i}.${d}` `` (iv + ciphertext, both base64url) and rides in a new
+envelope field `g`. **Encrypt-then-sign**: the signature covers ciphertext, so
+the relay verifies authorship without decrypting — blindness preserved. AES-GCM
+already gives key-holders content integrity; `g` adds *authorization*.
+
+### Relay enforcement (`w`-rooms only)
+
+ on connect (w-room): require ?w, verify "w"+b64url(sha256(w)) == name,
+ store `w` in DO storage (like `tok`; commitment-safe)
+ on {p:1} / {snap:1}: require valid `g` over `${i}.${d}` vs stored `w`,
+ else DROP the frame (no persist, no fan-out)
+ on ephemeral frames: unchanged
+ on r-rooms: unchanged (permissive) — legacy files keep working
+
+### Rollout & backward-compat (the reason to ship now)
+
+- **Client first, relay second, no breakage window.** New clients mint `w`
+ rooms and sign ops. The *current* relay ignores the extra `w`/`g` fields and
+ the `w` room name — so signed-scheme files work on the old relay
+ (permissively) until the new relay deploys and enforcement lights up.
+- **Legacy `r` rooms stay permissive forever** — existing shared files never
+ break. `rotateKeys()` mints a fresh (now `w`) room, i.e. rotation upgrades a
+ deck to enforced.
+- **Shipping the protocol now, before the read-only UX, is the point:** every
+ room created from here on is signed, so when "read-only viewer" and the
+ "presentation package" rename land, they need NO protocol change and break
+ NO existing session — read-only is just "save without `writerPriv`."
+
+### Threat model / limits
+
+- Enforcement is at the **relay**. Same-machine tab sync (BroadcastChannel)
+ can't be gated there — but same machine = same trust domain, so read-only is
+ cooperative locally (editing UI disabled), enforced over the network.
+- A malicious *relay* could still withhold/reorder frames or serve a stale
+ snapshot; it cannot forge writer ops (no private key) nor read content.
+ Optional client-side `g` verification (defence against a hostile relay
+ injecting old ciphertext) is a later, additive hardening — not required for
+ the read-only guarantee.
+- `writerPriv` in a writer file is only as protected as the file. Anyone with
+ a writer copy can write — expected: the writer file *is* the write cap.
+
## Offline mode
A viewer-side hard switch (localStorage `bento-offline`, toggle in About)
diff --git a/server/sync-worker/src/worker.js b/server/sync-worker/src/worker.js
index 397b7ac3..b975eef2 100644
--- a/server/sync-worker/src/worker.js
+++ b/server/sync-worker/src/worker.js
@@ -25,6 +25,32 @@ 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')}`
+// --- signed writes (see docs/collab-design.md) ------------------------------
+// A room whose name starts with 'w' is SIGNED: the name commits to an ECDSA
+// P-256 writer pubkey ('w' + base64url(SHA-256(pubRaw))). Clients present the
+// raw pubkey as ?w=; the relay pins it (commitment-checked, so a viewer can't
+// substitute their own) and thereafter requires a valid signature `g` over
+// `${i}.${d}` on every persisted frame (op batch / snapshot). Viewers hold the
+// pubkey but not the private half — their writes are dropped, so read-only is
+// ENFORCED here while the relay stays blind to content. 'r' rooms are legacy
+// and stay permissive.
+const b64uDec = (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 b64uEnc = (bytes) => {
+ let s = ''
+ for (const x of bytes) s += String.fromCharCode(x)
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
+}
+const EC_VERIFY = { name: 'ECDSA', namedCurve: 'P-256' }
+const SIG_ALG = { name: 'ECDSA', hash: 'SHA-256' }
+async function sha256b64u(bytes) {
+ return b64uEnc(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)))
+}
+
export default {
async fetch(req, env) {
const url = new URL(req.url)
@@ -53,6 +79,24 @@ export default {
export class Room {
constructor(state) {
this.state = state
+ this.verifyKey = null // imported writer pubkey, cached for this wake
+ }
+
+ /** Valid writer signature over `${i}.${d}` for a signed room? */
+ async verifySig(f) {
+ if (typeof f.g !== 'string') return false
+ if (!this.verifyKey) {
+ const w = await this.state.storage.get('w')
+ if (!w) return false
+ try {
+ this.verifyKey = await crypto.subtle.importKey('raw', b64uDec(w), EC_VERIFY, false, ['verify'])
+ } catch { return false }
+ }
+ try {
+ return await crypto.subtle.verify(
+ SIG_ALG, this.verifyKey, b64uDec(f.g), new TextEncoder().encode(`${f.i}.${f.d}`),
+ )
+ } catch { return false }
}
async fetch(req) {
@@ -66,6 +110,22 @@ export class Room {
if (saved === undefined) await this.state.storage.put('tok', tok)
else if (saved !== tok) return new Response('forbidden', { status: 403 })
+ // Signed rooms: the room name commits to the writer pubkey. Verify the
+ // presented ?w= against the commitment before pinning it, so the pinned
+ // key can't be substituted by a viewer.
+ const name = url.pathname.match(/^\/d\/([A-Za-z0-9._-]{1,80})$/)?.[1] || ''
+ const signed = name[0] === 'w'
+ if (signed) {
+ const w = url.searchParams.get('w') || ''
+ if (!/^[A-Za-z0-9_-]{80,200}$/.test(w)) return new Response('bad writer key', { status: 400 })
+ if ('w' + (await sha256b64u(b64uDec(w))) !== name) {
+ return new Response('writer key does not match room', { status: 403 })
+ }
+ const savedW = await this.state.storage.get('w')
+ if (savedW === undefined) await this.state.storage.put('w', w)
+ else if (savedW !== w) 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)
@@ -77,7 +137,7 @@ export class Room {
// Per-socket rate-limit state rides on the socket's serialized attachment
// (in-memory Maps don't survive hibernation).
this.state.acceptWebSocket(server)
- server.serializeAttachment({ count: 0, windowStart: Date.now() })
+ server.serializeAttachment({ count: 0, windowStart: Date.now(), signed })
await this.replay(server, since)
await this.state.storage.setAlarm(Date.now() + IDLE_TTL_MS)
@@ -137,6 +197,13 @@ export class Room {
}
if (typeof f.i !== 'string' || typeof f.d !== 'string') return
+ // Signed rooms: a persisted frame (op batch / snapshot) must carry a valid
+ // writer signature, else DROP it — this is what enforces read-only. A
+ // reader (no private key) can still send ephemeral frames (presence).
+ if (meta.signed && (f.p === 1 || f.snap === 1)) {
+ if (!(await this.verifySig(f))) return
+ }
+
const out = { i: f.i, d: f.d }
if (f.p === 1) {
const seq = ((await this.state.storage.get('seq')) || 0) + 1
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index 2936de56..0dd60934 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -496,10 +496,10 @@ export class Editor {
})
}
- private saveAsNewDeck() {
+ private async saveAsNewDeck() {
const clone = JSON.parse(JSON.stringify(this.store.doc)) as import('../model').BentoDoc
clone.docId = newDocId()
- clone.collab = mintCollab()
+ clone.collab = await mintCollab()
this.store.replaceDoc(clone)
this.toast(t('This is now a new deck — save it under a new name'))
void this.save(true)
@@ -618,16 +618,16 @@ export class Editor {
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, () => {
+ action(t('Start live session'), true, async () => {
if (!this.session) return
this.session.enableSharing()
- startSharing(this.session, this.store)
+ await startSharing(this.session, this.store)
this.wireOnlineStatus()
this.renderSharePanel()
})
- action(t('Rotate keys — cut off previously sent copies'), false, () => {
+ action(t('Rotate keys — cut off previously sent copies'), false, async () => {
if (!this.session) return
- rotateKeys(this.session, this.store)
+ await rotateKeys(this.session, this.store)
this.toast(t('New keys minted — only copies saved from now on can join'))
this.renderSharePanel()
})
diff --git a/slides/src/main.ts b/slides/src/main.ts
index 6cbae64d..c2a9a653 100644
--- a/slides/src/main.ts
+++ b/slides/src/main.ts
@@ -173,7 +173,7 @@ if (location.hash === '#present') {
transports: () => session.transportKinds,
/** start an online session (mints doc.collab, connects the relay) */
share: () => {
- startSharing(session, store)
+ void startSharing(session, store)
return store.doc.collab
},
unshare: () => stopSharing(session, store),
diff --git a/slides/src/model.ts b/slides/src/model.ts
index a53156b6..02826e81 100644
--- a/slides/src/model.ts
+++ b/slides/src/model.ts
@@ -361,6 +361,19 @@ export interface BentoDoc {
key: string
on?: boolean
sync?: import('./sync/crdt').SyncStateJSON
+ /**
+ * Signed writes (v0.9.18+): the WRITE capability is an ECDSA P-256 keypair,
+ * distinct from the symmetric `key` (the READ capability). `writerPub`
+ * (raw, base64url) travels in EVERY copy so the relay can verify authorship;
+ * `writerPriv` (PKCS#8, base64url) travels ONLY in writer copies. A
+ * read-only copy is a writer copy with `writerPriv` stripped — the relay
+ * (for `w`-scheme rooms) then drops any op it tries to send. Absent on
+ * legacy `r`-scheme rooms, which stay permissive. See docs/collab-design.md.
+ */
+ writerPub?: string
+ writerPriv?: string
+ /** 'reader' = this copy is a live viewer: receives updates, never sends. */
+ role?: 'writer' | 'reader'
}
/**
* Template file (.dotx-style): every OPEN instantiates a fresh document —
diff --git a/slides/src/sync/online.ts b/slides/src/sync/online.ts
index 0490c487..643ed6ca 100644
--- a/slides/src/sync/online.ts
+++ b/slides/src/sync/online.ts
@@ -37,20 +37,54 @@ export function mintRoomKey(): string {
return b64u.enc(bytes)
}
+const EC = { name: 'ECDSA', namedCurve: 'P-256' } as const
+const SIGN_ALG = { name: 'ECDSA', hash: 'SHA-256' } as const
+
+/** Import a writer private key (PKCS#8, base64url) for signing op frames. */
+export async function importSignKey(privB64: string): Promise<CryptoKey> {
+ return crypto.subtle.importKey('pkcs8', b64u.dec(privB64) as BufferSource, EC, false, ['sign'])
+}
+
+/** ECDSA-P256/SHA-256 signature over `${i}.${d}`, base64url. */
+export async function signFrame(key: CryptoKey, i: string, d: string): Promise<string> {
+ const sig = await crypto.subtle.sign(SIGN_ALG, key, new TextEncoder().encode(`${i}.${d}`))
+ return b64u.enc(new Uint8Array(sig))
+}
+
+export type CollabCreds = {
+ room: string
+ key: string
+ on: boolean
+ writerPub: string
+ writerPriv: string
+ role: 'writer'
+}
+
/**
* Fresh collaboration credentials, minted at DOCUMENT CREATION and LIVE by
* default (on:true): the moment identity and keys exist, any copy of the
* file joins the same room — "send first" needs no ceremony. "Stop sharing"
* in the Live popover turns it off; Offline mode hard-blocks regardless.
- * 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.
+ *
+ * Signed-writes scheme (v0.9.18+): the room id is the COMMITMENT to a fresh
+ * ECDSA writer pubkey — `w` + base64url(SHA-256(writerPubRaw)) — so the relay
+ * can pin the writer key trustlessly (a viewer holds the room id but can't
+ * substitute their own key). `key` is the separate symmetric READ capability.
+ * Async because keypair generation is. See docs/collab-design.md.
*/
-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: true }
+export async function mintCollab(): Promise<CollabCreds> {
+ const kp = (await crypto.subtle.generateKey(EC, true, ['sign', 'verify'])) as CryptoKeyPair
+ const pubRaw = new Uint8Array(await crypto.subtle.exportKey('raw', kp.publicKey))
+ const privPk = new Uint8Array(await crypto.subtle.exportKey('pkcs8', kp.privateKey))
+ const commit = new Uint8Array(await crypto.subtle.digest('SHA-256', pubRaw as BufferSource))
+ return {
+ room: `${syncHost()}/d/w${b64u.enc(commit)}`,
+ key: mintRoomKey(),
+ on: true,
+ writerPub: b64u.enc(pubRaw),
+ writerPriv: b64u.enc(privPk),
+ role: 'writer',
+ }
}
/** dev override for the relay host (e.g. ws://localhost:8787) */
@@ -70,6 +104,8 @@ export class OnlineTransport implements Transport {
onStatus: ((s: OnlineStatus) => void) | null = null
private ws: WebSocket | null = null
private key: CryptoKey | null = null
+ /** writer signing key — null for readers (they can decrypt but not author). */
+ private signKey: CryptoKey | null = null
private queue: string[] = []
private closed = false
private backoff = 800
@@ -93,6 +129,8 @@ export class OnlineTransport implements Transport {
/** replay done: (actor,seq) pairs the room holds; return true to upload a snapshot */
onReady: (seen: Set<string>, seq: number) => boolean
},
+ private writerPub?: string,
+ private writerPriv?: string,
) {
void docId
this.init(room)
@@ -109,7 +147,12 @@ export class OnlineTransport implements Transport {
])
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}`
+ // writers sign op frames; readers omit the key and the relay drops their
+ // writes. The pubkey (`w`) rides on the URL so the relay can pin+verify.
+ if (this.writerPriv) {
+ try { this.signKey = await importSignKey(this.writerPriv) } catch { this.signKey = null }
+ }
+ this.url = `${room}?tok=${tok}` + (this.writerPub ? `&w=${this.writerPub}` : '')
this.connect()
}
@@ -229,7 +272,9 @@ export class OnlineTransport implements Transport {
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 }))
+ const env: Record<string, unknown> = { snap: 1, q, i: text.i, d: text.d }
+ if (this.signKey) env.g = await signFrame(this.signKey, text.i, text.d)
+ this.ws.send(JSON.stringify(env))
}
} finally {
this.snapInFlight = false
@@ -252,7 +297,12 @@ export class OnlineTransport implements Transport {
void (async () => {
const enc = await this.encrypt(JSON.stringify(frame))
if (!enc) return
- const env = frame.t === 'ops' ? { p: 1, ...enc } : enc
+ let env: Record<string, unknown> = enc
+ if (frame.t === 'ops') {
+ env = { p: 1, ...enc }
+ // sign the ciphertext so the relay verifies authorship while blind.
+ if (this.signKey) env.g = await signFrame(this.signKey, enc.i, enc.d)
+ }
const text = JSON.stringify(env)
if (this.ws && this.ws.readyState === WebSocket.OPEN) this.ws.send(text)
else {
@@ -306,12 +356,15 @@ export function joinFromDoc(session: SyncSession, store: Store): OnlineTransport
return new NullTransport()
}
active?.close()
+ // readers carry writerPub (to name the room's writer key) but never the
+ // private half — so their op frames go unsigned and the relay drops them.
+ const priv = collab.role === 'reader' ? undefined : collab.writerPriv
active = new OnlineTransport(collab.room, collab.key, docId, onFrame, {
onSnap: (doc, state) => session.applySnapshot(doc, state),
getSnapshot: () => session.snapshot(),
onOpen: () => session.hello(),
onReady: (seen) => session.onRelayReady(seen),
- })
+ }, collab.writerPub, priv)
return active
})
return active
@@ -319,13 +372,14 @@ export function joinFromDoc(session: SyncSession, store: Store): OnlineTransport
/** 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 | null {
+export async function startSharing(session: SyncSession, store: Store): Promise<OnlineTransport | null> {
if (offlineEnabled()) return null
if (active) return active
- store.commit(() => {
- if (!store.doc.collab) store.doc.collab = mintCollab()
- store.doc.collab.on = true
- })
+ if (!store.doc.collab) {
+ const creds = await mintCollab()
+ store.commit(() => { store.doc.collab = creds })
+ }
+ store.commit(() => { store.doc.collab!.on = true })
return joinFromDoc(session, store)
}
@@ -357,10 +411,10 @@ export function stopSharing(session: SyncSession, store: Store) {
/** 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) {
+export async function rotateKeys(session: SyncSession, store: Store) {
stopSharing(session, store)
+ const fresh = await mintCollab()
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 0b2c3f58..e4489718 100644
--- a/slides/src/sync/session.ts
+++ b/slides/src/sync/session.ts
@@ -157,8 +157,10 @@ export class SyncSession {
this.bornWithCollab = !!doc.collab
this.explicitShare = false
// credentials are minted AT CREATION: any copy of the file can join once
- // it is live (on:true by default). See eligibility gate above.
- if (!doc.collab) doc.collab = mintCollab()
+ // it is live (on:true by default). Minting is async now (the writer
+ // keypair) — fine because a freshly-minted doc is never auto-connected, so
+ // the sub-frame gap before collab lands touches nothing. See eligibility.
+ if (!doc.collab) void this.ensureCollab()
const saved = doc.collab?.sync
if (saved && saved.v === SYNC_V) {
// this file was saved during/after a shared session: restore the CRDT
@@ -189,6 +191,15 @@ export class SyncSession {
}, HEARTBEAT_MS)
}
+ /** Mint collab credentials (incl. the writer keypair) for a doc created
+ * without them. Direct mutation (no undo entry), guarded against a race with
+ * a real collab arriving via loadDoc. */
+ private async ensureCollab() {
+ if (this.store.doc.collab) return
+ const creds = await mintCollab()
+ if (!this.store.doc.collab) this.store.doc.collab = creds
+ }
+
/** register a factory for an additional transport (online relay) and connect it */
addTransport(mk: (docId: string, onFrame: (f: Frame) => void) => Transport): Transport {
this.makeExtraTransports.push(mk)