# Design ## Stack - **Language and versions:** TypeScript everywhere, with one npm package. Node 20+. Versions known to work: - wrangler 4.162, `@cloudflare/workers-types` - React 18.3, Vite 6, `@vitejs/plugin-react` - roughjs 4.6, perfect-freehand 1.2, fractional-indexing 4, `@fontsource/kalam` 5 - Vitest 3, Playwright 1.65 - **One Worker** (`src/worker/index.ts`) serves: - the built SPA from `dist/` through the assets binding - a small API under `/api/*` for share links and session images - WebSockets under `/api/rooms/:id/ws`, forwarded to the `Room` Durable Object - **Storage:** - Drawings and the library stay in the browser (localStorage + IndexedDB). - R2 holds only encrypted share links and encrypted session images. - Durable Object storage (SQLite-backed) holds each room's latest encrypted scene. - There is no database and no account data. - **No other services:** no email, no external fonts, no CDN scripts. Layout: ``` src/shared/ types.ts elements.ts geometry.ts reconcile.ts restore.ts actions.ts binding.ts history.ts crypto.ts protocol.ts settings.ts limits.ts (no DOM, no Worker APIs; used by both sides) src/worker/ index.ts (routes, limits) room.ts (Durable Object) http.ts src/client/ main.tsx Editor.tsx controller.ts store.ts render.ts paint.ts StylePanel.tsx dialogs.tsx pages.tsx share.tsx collab.ts persist.ts files.ts theme.ts ui.tsx api.ts style.css tests/ *.test.ts (Vitest, node environment) e2e/ *.spec.ts helpers.ts fixtures/ (Playwright) ``` `src/shared/settings.ts` imports `spekkr.inputs.json` and exports `settings`: `appName` (else "Whiteboard") and `accentColor` (`#rrggbb`, else `#4c6ef5`). `index.html` sets the title to `app_name` at build time (a Vite `transformIndexHtml` hook reads the inputs file). `main.tsx` sets the accent as a CSS variable. ## Cloudflare config `wrangler.jsonc`: ```jsonc { "name": "whiteboard", "main": "src/worker/index.ts", "compatibility_date": "2026-11-16", "assets": { "directory": "./dist", "binding": "ASSETS", "not_found_handling": "single-page-application", "run_worker_first": ["/api/*"] }, "r2_buckets": [{ "binding": "FILES", "bucket_name": "whiteboard-files" }], "durable_objects": { "bindings": [{ "name": "ROOMS", "class_name": "Room" }] }, "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Room"] }], "ratelimits": [ { "name": "LINK_LIMIT", "namespace_id": "1001", "simple": { "limit": 10, "period": 60 } }, { "name": "ROOM_LIMIT", "namespace_id": "1002", "simple": { "limit": 120, "period": 60 } }, { "name": "FILE_LIMIT", "namespace_id": "1003", "simple": { "limit": 120, "period": 60 } } ], "observability": { "enabled": true } } ``` `npm run types` (`wrangler types --strict-vars=false`) writes `worker-configuration.d.ts` for the `Env` type (`FILES`, `ROOMS`, `ASSETS`, and the three `RateLimit` bindings). There are two tsconfigs: - `tsconfig.json`: client, shared and tests, with DOM libs. - `tsconfig.worker.json`: worker and shared, with the generated types. `npm run typecheck` runs both. Scripts: ``` "build": "vite build", "dev": "npm run build && wrangler dev", "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.worker.json --noEmit", "test": "vitest run", "e2e": "playwright test", "deploy": "npm run build && wrangler deploy", "types": "wrangler types --strict-vars=false" ``` ## Deploy 1. `npx wrangler login` 2. `npx wrangler r2 bucket create whiteboard-files` 3. `npm run deploy`. The first deploy creates the `Room` class through migration `v1`. The README also explains: - the "Anyone with the URL can use sharing" note with the limits - that share links never expire (like Excalidraw), and that room data is deleted 24 hours after a room empties - Cloudflare Access as the way to restrict the whole site ## Storage In the browser (`src/client/persist.ts`): - `localStorage["whiteboard:local"]`: `{ elements (live only), appState }`, written 300 ms after a change and on `pagehide`. - IndexedDB `whiteboard-files`, object store `files` (key `id`): `{ id, mimeType, dataURL, created }`. After each write, files no live image uses are deleted. - `localStorage["whiteboard:library"]`: the library items array. - `localStorage["whiteboard:name"]`: the session name. - `localStorage["theme"]`: `light` | `dark` | `system` (absent = light). R2 keys: - `links/`: a share link's bytes, `IV ‖ AES-GCM(scene file JSON)`. The id is 16 random bytes as base64url. - `rooms//`: a session image, `IV ‖ AES-GCM(JSON {mimeType, dataURL})`. Room Durable Object storage (`src/worker/room.ts`): - `id`: the room id, saved on first contact. The alarm needs it to find the room's R2 images. - `snap:n` (chunk count) and `snap:0…snap:n-1`: the latest encrypted scene string, cut into 1,000,000-character chunks. - An alarm 24 h (`ROOM_IDLE_MS`) after the last socket closes or after an image upload with nobody connected. A new connection deletes the alarm. When it fires with nobody connected, it lists and deletes `rooms//` in R2 and calls `storage.deleteAll()`. - Each socket's attachment holds `{ id, name, color, hello }`. ## Element model These are the field names and meanings of the open `.excalidraw` format, version 2 (`src/shared/types.ts`). All elements: | field | type | notes | |---|---|---| | id | string | 21-char random (nanoid alphabet) for new elements; any string kept on import | | type | "rectangle" \| "diamond" \| "ellipse" \| "arrow" \| "line" \| "freedraw" \| "text" \| "image" | | | x, y, width, height | number | scene units; width/height ≥ 0. For shapes, text and images x, y is the box's top-left. For linear and freedraw elements x, y is the **first point** (which is always `[0, 0]`), not the box's corner; width/height are the size of the points' bounding box | | angle | number | radians, around the element centre | | strokeColor, backgroundColor | string | `#rgb`, `#rrggbb`, `#rrggbbaa` or `transparent` | | fillStyle | "hachure" \| "cross-hatch" \| "solid" \| "zigzag" | default "solid" | | strokeWidth | number | 1, 2, 4 (any 0.5–32 kept) | | strokeStyle | "solid" \| "dashed" \| "dotted" | | | roughness | number | 0, 1, 2 (0–3 kept) | | opacity | number | 0–100 | | roundness | null \| { type: 2 \| 3, value? } | | | seed | integer | rough seed | | version | integer | +1 on every change | | versionNonce | integer | random on every change | | index | string \| null | fractional-indexing key, increasing in array order | | isDeleted | boolean | tombstone | | groupIds | string[] | innermost first | | frameId | null | | | boundElements | {id, type:"arrow"}[] \| null | arrows bound to this element | | updated | number | ms timestamp of the last change | | link | string \| null | kept, not shown | | locked | boolean | | | customData | object (optional) | kept as is | Type-specific fields: - **arrow, line:** - `points: [x, y][]`, offsets from `x, y`. The first point is always `[0, 0]`; later points may be negative (a line drawn up and to the left has negative points). When a point edit moves the first point, the element's `x, y` moves to it and every point is shifted so the first is `[0, 0]` again. - `startBinding`, `endBinding: { elementId, fixedPoint: [fx, fy], mode: "orbit" } | null`. - `startArrowhead`, `endArrowhead: null | "arrow" | "triangle" | "triangle_outline" | "bar" | "circle" | "circle_outline" | "diamond" | "diamond_outline"`. - `elbowed: false`. Lines also have `polygon: boolean`. - **freedraw:** `points`, `pressures: number[]` (0–1, same length as points, or empty), `simulatePressure: boolean`. - **text:** - `text`, `originalText` (the same), `fontSize`, `fontFamily` (5 Hand-drawn, 6 Normal, 3 Code). - `textAlign: "left" | "center" | "right"`, `verticalAlign: "top"`, `containerId: null`. - `lineHeight` (1.25 / 1.35 / 1.2), `autoResize: true`. - **image:** `fileId` (SHA-1 hex), `status: "saved"`, `scale: [±1, ±1]`, `crop: null`. Scene files: `files: { [fileId]: { id, mimeType, dataURL, created } }`. The editor's appState that is saved: - `viewBackgroundColor` (default `#ffffff`) - `gridSize` (20) - `gridModeEnabled` (false) New elements (`newElement`) take the current style. The default style is: - stroke `#1e1e1e`, background `transparent`, fill `solid` - width 2, style `solid`, roughness 1, opacity 100, edges round - font 5, size 20, align left - arrowheads null → "arrow" They also get: - `seed` and `versionNonce`: random 31-bit integers - `version` 1, `updated`: now - `index`: a key after the last element - `groupIds` [], `boundElements` null, `link` null, `locked` false **`bump(e, patch)`** applies a change: it merges the patch, adds 1 to `version`, sets a new `versionNonce` and sets `updated` to now. Every change to an element goes through it. ## Restore (src/shared/restore.ts) `restoreElements(raw, keepDeleted = false)` returns `{ elements, skipped }`. For each item: - Non-objects are skipped and counted. - Types not in the list are skipped. They are counted unless they are deleted. - Deleted elements are dropped unless `keepDeleted`. Live sessions pass `true` so tombstones carry deletes. - A missing `id` gets a new one. So does an id already seen in the same file. - **Numbers:** a non-finite number gets its default (x/y/width/height/angle 0). strokeWidth is clamped to 0.5–32, roughness to 0–3, opacity to 0–100, and fontSize to 4–400. - **Integers:** a non-integer `seed`, `version` or `versionNonce` gets a random value (or 1 for version). - **Colours:** must match `^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$` (case-insensitive) or be `transparent`, else the default (`#1e1e1e` stroke, `transparent` background). - **Enums:** fillStyle, strokeStyle, textAlign and verticalAlign outside their sets get their defaults. An arrowhead outside the list becomes null, except `dot`, which becomes `circle`. - **roundness:** an object becomes `{ type, value? }`; anything else becomes null. - **groupIds:** keeps only the strings. **boundElements:** keeps `{ id, type }` entries whose type is `arrow` or `text`. - **Points:** keeps only finite `[x, y]` pairs. A line or arrow needs ≥ 2, and freedraw needs ≥ 1, else the item is skipped and counted. - **Bindings:** an object with a string `elementId` becomes `{ elementId, fixedPoint (default [0.5, 0.5]), mode: "inside" | "orbit" }`, else null. - **freedraw:** `pressures` are numbers; `simulatePressure` is true unless it is `false`. - **text:** `text` falls back to `originalText`. fontFamily, lineHeight (1.25) and autoResize are kept. - **image:** `status` becomes `"saved"`, `scale` defaults to `[1, 1]` and `crop` becomes null. - **Kept as is:** `link` (string, cut at 2048 characters) and `customData` (plain object). - **Order:** if every element has an `index`, they are sorted by it; otherwise the file's order is kept. Then `syncIndices` fixes missing or invalid keys. - **Bindings later:** the store runs `dropDeadBindings` (removes bindings to missing or deleted elements) and `syncBoundElements` on every load and commit. `restoreAppState(raw)` keeps `viewBackgroundColor` (a valid colour, else `#ffffff`), `gridSize` (a number, null, or 20) and `gridModeEnabled`. The file parsers: - **`parseSceneFile(text)`:** - Not JSON → `ImportError("That file is not valid JSON.")`. - `type: "excalidrawlib"` → "That is a library file. Open it from the library panel." - No `elements` array (the `type` may be missing or `"excalidraw"`) → "That file is not a drawing this app can open." - Otherwise it returns `{ elements, appState, files, skipped }`. - Files are kept only if `dataURL` matches `^data:(image/(png|jpeg|gif|webp|svg\+xml|bmp|avif));base64,[A-Za-z0-9+/=]+$`. The `id` is taken from the map key and `mimeType` from the data URL. - **`parseLibraryFile(text)`:** accepts version 2 `libraryItems` and version 1 `library: Element[][]` (each becomes an item with a new id). Each item's elements are restored, and items left with no elements are dropped. Anything else → "That file is not a library file." - **`serializeScene(elements, appState, files, source)`** writes the R19 JSON with 2-space indent: live elements, and only the files they use. **`serializeLibrary(items, source)`** writes version 2. ## Ordering (fractional indices) - **`syncIndices(els)`:** walks the array. A run of elements whose `index` is missing, or not greater than the previous valid key, gets new keys from `generateNKeysBetween(prevValid, nextValid, n)`. Every element that gets a new key also gets `version + 1` and a new `versionNonce`, so the new order reaches collaborators (who only take higher versions). Valid increasing keys are left alone. - **`sortByIndex`** sorts by `index`, then by `id`, so all clients agree. - **`reorder(els, ids, "front" | "back" | "forward" | "backward")`:** 1. Expands `ids` to whole groups. 2. For forward/backward (Excalidraw's rule), finds the next unselected live element above the selection's topmost member (or below its bottommost). It need not overlap the selection. If it has `groupIds`, the target becomes its whole outermost group. The selected block moves just past that target. For front/back, it moves to the end or start. 3. Gives only the moved elements new keys between their new neighbours, and bumps them. ## Reconcile (src/shared/reconcile.ts) `reconcile(local, remote, keepLocal)`: - For each id in remote: - If local lacks it, take remote. - Else if `keepLocal(id)`, keep local. - Else take remote when `remote.version > local.version`, or when the versions are equal and `remote.versionNonce < local.versionNonce`. - Elements only in local are kept. - The result is sorted by `index`. Elements with no `index` yet (a shape still being drawn locally) are put after all the others, in local order, rather than given a guessed key. Two clients therefore never hold the same key for different elements. Every client picks the same winner, so copies converge. Tombstones are elements like any other, so a delete with a higher version wins. ## Geometry and actions - **`hitTest(e, x, y, tol)`:** works in the element's unrotated frame. - Rectangles (and images and text, which always hit inside) hit inside when filled, else within `tol + strokeWidth/2` of an edge. - Ellipses use the inside/outside of the radii ± tol. - Diamonds use their four edges, or inside when filled. - Linear elements hit within tol of any segment. Closed lines also hit inside when filled. - Freedraw hits within tol of any segment. - **`bounds(e)`:** the axis-aligned box of the rotated element. **`commonBounds`** is the union. - **`edgePoint(e, toward, gap = 4)`:** works in e's unrotated frame (rotate `toward` by −angle about the centre). Take the unit direction `(dx, dy)` from the centre and half sizes `hw`, `hh`. The distance `t` to the real outline is: - ellipse: `1 / sqrt(dx²/hw² + dy²/hh²)` - diamond (rhombus through the edge midpoints): `1 / (|dx|/hw + |dy|/hh)` - rectangle, text, image: `min(hw/|dx|, hh/|dy|)` The point is `centre + (dx, dy) × (t + gap)`, rotated back by the angle. The gap is measured along the ray, not by growing the box. - **`actions.ts`:** - `align(els, ids, how, now)`, with how one of `"left" | "hcenter" | "right" | "top" | "vcenter" | "bottom"`: units are outermost groups or single elements. - `distribute(els, ids, "x" | "y")`: equal gaps; keeps the first and last. - `group(els, ids, now)` → `{ elements, groupId }`: appends a new id, then reorders the members to sit together at the topmost member's place. - `ungroup(els, ids, editingGroup)`: removes the outermost group id (or the edited group). - `flip(els, ids, "h" | "v")`: mirrors around the selection centre. Linear/freedraw points mirror, angles negate, and an image's `scale` component flips sign. - `expandToGroups(els, ids, editingGroup)` and `outerGroup(e, editingGroup)`. - **`binding.ts`:** - `bindTarget(els, x, y, tol, exclude)`: the topmost bindable, unlocked element whose outline is within tol or which contains the point. - `fixedPointOf(target, x, y)` - `placeBoundEnds(arrow, byId)`: per spec R4. - `updateBoundArrows(els, changedIds)`: re-places and bumps arrows bound to changed elements that did not move themselves. - `syncBoundElements(els)`: rebuilds every target's `boundElements` from the arrows' bindings, bumping only targets whose list changed. - `dropDeadBindings(els)` - When an arrow is moved without its targets, the controller sets the bindings of ends whose target didn't move to null. ## Undo history (src/shared/history.ts) - **`History`:** `record(before: Snap)` pushes onto the undo stack (max 100) and clears redo. A `Snap` is `{ elements, appState, selected }`. - **`undo(current)` / `redo(current)`:** pop a snap and push the current one on the other stack. - **`applySnap(current, snapElements, now, nonce)`:** - Every element whose copy differs from the snap's is replaced by the snap's copy with `version = max(snap, current) + 1`, a new nonce and `updated` set to now. - Elements in current but not in the snap become tombstones (bumped). - Unchanged elements are kept as they are. - This turns undo into ordinary newer edits that sync and save like any change. The store (`src/client/store.ts`): - **`commit(next, before)`:** records history, syncs indices and bound elements, and notifies. - **`preview(next)`:** live drag updates without history. - **`applyRemote(merged)`:** no history; it only notifies and redraws. - `onChange(kind)` drives saving to the browser canvas and sending to a session. ## Input constants (src/client/controller.ts) These are Excalidraw's values: - `DRAG_THRESHOLD = 10` screen px. A press that travels less than this between down and up is a click. With Rectangle, Diamond or Ellipse, a click makes the 100×100 default shape. With Arrow or Line, it starts multi-point mode. - `LINE_CONFIRM = 8` screen px. In multi-point mode, a click closer than this to the last fixed point finishes the line, as do a double-click, Enter and Escape. - **Arrow-key nudge:** grid off, 1 unit (Shift 5); grid on, `gridSize` (Shift 1). - **`wheelZoom(zoom, deltaY)`:** `zoom − clamp(deltaY, −10, 10)/100 + log10(max(1, zoom)) × −sign(deltaY) × min(1, |deltaY|/20)`, then clamped to 0.1–30 and rounded to 0.001. It is applied around the pointer. ## Rendering (src/client/render.ts, paint.ts) - **`shapeOf(e)`:** returns `ShapePath[]` (`{ d, stroke, strokeWidth, fill, dash?, fillRule }`) in the element's local frame. It is cached per id. The key is `JSON.stringify` of `[version, versionNonce, type, width, height, seed, strokeColor, backgroundColor, fillStyle, strokeWidth, strokeStyle, roughness, roundness, points, pressures, simulatePressure, polygon, startArrowhead, endArrowhead]`. Drag previews change points and size without a version bump, so the key must include them, or the preview would show stale paths. - **rectangle:** `gen.rectangle` (fills non-zero), or with roundness `gen.path` of a rounded-rect path with radius r (a rough path, so it fills even-odd). For type 3, r = `min(25 % of the short side, value ?? 32)`; for type 2, 25 %. - **diamond:** `gen.polygon` of the four side midpoints. With roundness, a path with quadratic corners (radius 0.6 × the corner radius, at most 45 % of a side). - **ellipse:** `gen.ellipse(w/2, h/2, w, h, { curveFitting: 1 })`. - **line/arrow:** `gen.linearPath`. With roundness and > 2 points, `gen.curve`. Closed lines use `gen.polygon`. - Arrowhead size is `min(20 + 2·strokeWidth (15 for bar), 0.75 × last segment)`. - "arrow" is two strokes at ±π/7. "triangle" is a filled polygon at ±π/9 (outline variant unfilled). "bar" is perpendicular. "circle" has diameter 2/3 of the size. "diamond" has an 0.9 × size long axis at ±π/8. - **freedraw:** a filled path from `getStroke` (spec R5), turned into `M … Q …` midpoints. A background adds a rough polygon of the points under it. - **Options:** from spec R8. Fill paths use `fillRule` "evenodd" for rough `curve`, `polygon` and `path` drawables and "nonzero" otherwise. Outline paths of non-solid strokes carry `dash`. - **`paint(ctx, store)`** draws, in order: 1. the view background 2. the grid when on 3. each live element in order (`drawElement`: alpha = opacity, rotate around the centre, then paths/text/image; elements marked by the eraser at 25 %; the text being edited is skipped) 4. selection boxes (dashed accent 1 px; groups one box) 5. handles (8 px white squares with accent border; rotate circle) 6. linear point handles 7. the bind target outline 8. the selection rectangle (accent at 8 % fill) 9. collaborators' selections (in their colours) 10. collaborators' cursors (arrow plus name tag) - **Text:** `fontString = "px "`. - Hand-drawn: `Kalam, "Comic Sans MS", "Segoe Print", cursive`. - Normal: `system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif`. - Code: `"Cascadia Code", "SFMono-Regular", Menlo, Consolas, monospace`. - Lines are drawn at `i·lh + lh/2 + 0.35·size`, with alignment by `textAlign`. - Kalam 400 is loaded through `@fontsource/kalam`, and the editor waits for `document.fonts.load` before measuring. - **Dark mode:** the canvas element gets the CSS filter `invert(93%) hue-rotate(180deg)` (spec R21). Each image is drawn with `ctx.filter = "invert(93%) hue-rotate(180deg)"` (the same filter), and the filter is reset to `"none"` right after. Applied twice, the hue rotations cancel and each channel `c` comes back as about `0.07 + 0.86·c`. ## Export (render.ts) - **`exportBounds(els, 10)`:** the common bounds plus 10 padding. - **`exportCanvas(els, images, { background, backgroundColor, dark, scale })`:** a canvas of `bounds × scale`. It fills the background if asked, translates and draws each element. If dark, the dark filter is applied with `ctx.filter`. - **`exportSvg(els, files, opts)`:** - `` - optional `` (the Latin 400 WOFF2 from `@fontsource/kalam`, fetched at export time) - optional background rect - for each element a `` with `` per ShapePath - text as `` per line (XML-escaped) - images as `` with a flip transform for negative scale - Dark output wraps everything in a group with an SVG filter equivalent to the CSS one. ## Encryption (src/shared/crypto.ts) - **`generateKey()`:** AES-GCM 128, exported as a JWK, returning `k` (22 base64url characters). - **`encrypt(k, data)`:** a random 12-byte IV, then `IV ‖ AES-GCM(ciphertext + tag)`. **`decrypt(k, payload)`** throws on a wrong key. **`decryptText`.** - **`toB64` / `fromB64`:** standard base64 for WebSocket payloads. - **`sealScene(k, json)`:** the share-link body, `encrypt(k, deflate(json))`. `deflate` is zlib deflate through the built-in `CompressionStream("deflate")`, the same format as Excalidraw's pako deflate. **`openScene(k, bytes)`** decrypts, then inflates with `DecompressionStream("deflate")`. A plaintext whose first byte is `{` is read as plain JSON. Live-session messages are not compressed, as in Excalidraw. - **`sha1Hex(bytes)`:** the image file id. ## Live session protocol (src/shared/protocol.ts) Client → server (JSON text frames): ```ts { t: "hello", name } // first, and again to rename { t: "broadcast", data: base64(IV‖ct), snapshot?: true } // scene payload, relayed; snapshot=true also stores it { t: "volatile", data: base64(IV‖ct) } // pointer payload; relayed, never stored { t: "save", data: base64(IV‖ct) } // full scene to store for later joiners; not relayed { t: "ping" } ``` Server → client: ```ts { t: "welcome", you: Peer, peers: Peer[], snapshot: string | null } { t: "peers", peers: Peer[] } // everyone who said hello, including you { t: "broadcast", from, data } | { t: "volatile", from, data } { t: "error", error } | { t: "pong" } // Peer = { id: 8 chars, name ≤ 40, color } ``` Constants: `MAX_PEERS` 32, `FULL_SYNC_MS` 20000, `SAVE_MS` 1000, `MAX_WS_MESSAGE` 4 MB + 4096, `PEER_COLORS` (spec R25). Decrypted payloads: ```ts { kind: "scene", elements: Element[], full?: boolean } // changed elements, or all with full { kind: "pointer", x, y, tool: "pointer" | "laser", button: "up" | "down", name, selected?: string[] } { kind: "idle", idle: boolean, name } ``` Client (`src/client/collab.ts`, class `Collab`): - **Ids:** `newRoomId()` gives 10 random bytes as hex. `generateKey()` gives the key. `roomLink(id, key)` = `/#room=,`. `parseRoomHash` / `parseJsonHash` check the formats (`[a-f0-9]{20}`, `[A-Za-z0-9_-]{22}`). - **Connecting:** connect, then send `hello` with the stored name. - **On `welcome`:** - Apply the snapshot if there is one. - If this client started the room and there is no snapshot, send the full scene with `snapshot: true`. Otherwise send local changes. - Start a 20 s timer that sends the full scene with `snapshot: true`. - **On `peers`:** update the collaborator list. If someone new appeared, send the full scene at once. - **On `broadcast`:** decrypt, restore with tombstones, reconcile (keeping elements being edited or dragged here), mark the merged versions as sent so they are not echoed, apply without history, then fetch any missing images. - **Sending changes:** on local change, send elements that have an `index` and whose version differs from the last sent version, at most every 50 ms. Then (re)start a 1 s timer that sends `save` with the full scene. Broadcasts never include elements without an `index`. - **Images:** for each live image not yet uploaded, PUT the encrypted `{mimeType, dataURL}` to `/api/rooms/:id/files/:fileId`. Missing images are fetched with up to 5 retries (1 s, 2 s, …) and decrypted. - **Pointer:** sent at most every 33 ms. - **`close()`:** if a `save` is pending, send it first, then close the socket (code 1000). - **Dropped connection:** status `reconnecting`, then reconnect after 0.5 s × 2ⁿ (max 10 s). Page (`src/client/pages.tsx`, `CanvasPage`): - `mode` is `local` (no hash, or the host after "Start session"), `room` (opened a `#room=` link) or `copy` (opened a `#json=` link). - Only `local` binds the browser canvas save. - "Start session" makes the id and key, sets the hash with `history.replaceState` and joins as starter. - "Stop session" closes and sets the address to `/`. - "Leave session" closes, sets `/` and shows the "You left the live session." banner. ## API All errors are JSON `{ error }`. There are no cookies or sign-in. | method | path | limit | does | |---|---|---|---| | GET | /api/health | — | `{ ok: true }` | | POST | /api/links | 10 MB, then `LINK_LIMIT` | raw encrypted (deflated) bytes → R2 `links/` → 201 `{ id }`. Never expires | | GET | /api/links/:id | — | the bytes (`application/octet-stream`, `cache-control: public, max-age=31536000, immutable`) or 404 "This link doesn't exist" | | GET | /api/rooms/:id/ws | `ROOM_LIMIT` | WebSocket upgrade → `ROOMS.idFromName(id)`. Without `Upgrade: websocket`: 426 `{"error":"Expected a WebSocket upgrade"}` | | PUT | /api/rooms/:id/files/:fileId | 4 MB + 64 B, 100 per room, then `FILE_LIMIT` | encrypted image → R2 `rooms//`. 201, or 200 if it already exists. Then pokes the room (`/touch`) so the image expires with it | | GET | /api/rooms/:id/files/:fileId | — | encrypted image (`private, max-age=86400`) or 404 "Image not found" | `src/worker/http.ts` has: - a tiny `Router` (`on(method, pattern, handler)` with `:params`; 404 "Not found" and 405 "Method not allowed") - `HttpError(status, message)` - `json(data, status, headers)` (always `cache-control: no-store`) ### Request checks (index.ts) - **Origin:** a request that is not GET/HEAD, or is a WebSocket upgrade, and whose `Origin` header is present but differs from the Worker's own origin gets 403 "Cross-site request refused". - **Ids:** link `^[A-Za-z0-9_-]{22}$`; room `^[a-f0-9]{20}$` (else 404 "Not a session link"); file `^[a-f0-9]{40}$` (PUT: 400 "Bad file id"). - **Order:** every check that can refuse a request runs before the rate limit, so a refused request (400, 403, 404, 413, 426) never spends a slot. `POST /api/links`: origin, body size, too short, then `LINK_LIMIT`. WebSocket: origin, room id, upgrade, then `ROOM_LIMIT`. Image PUT: origin, room id, file id, body size, already stored (200), session full, then `FILE_LIMIT`. - **Rate limits:** `limit(binding, req, what)` calls `binding.limit({ key: CF-Connecting-IP ?? "local" })`. On failure it throws 429 "Too many from your address. Wait a minute and try again." The error handler adds `retry-after: 60`. - **Bodies:** `readBytes(req, max, message)` rejects by `content-length` first, then by actual length (413). - **Stored blobs** are served with `content-security-policy: default-src 'none'; sandbox` and `x-content-type-options: nosniff`. - **Errors:** `HttpError`s become `{ error }` with their status. Anything else is logged and becomes 500 "Something went wrong on our side. Try again." ## Limits (src/shared/limits.ts) ```ts export const LIMITS = { fileBytes: 4 * 1024 * 1024, // one image encryptedLinkBytes: 10 * 1024 * 1024, // one encrypted share link (scene + images) roomFileBytes: 4 * 1024 * 1024 + 64, // one encrypted session image (IV + tag overhead) roomFiles: 100, // images per live session roomSnapshotBytes: 4 * 1024 * 1024, // the encrypted scene a room keeps for late joiners }; /** Requests per address per minute (wrangler.jsonc `ratelimits`). */ export const RATE_LIMITS = { links: 10, roomConnections: 120, roomFiles: 120 }; export const IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/svg+xml", "image/bmp", "image/avif"]; ``` Going over a size limit returns 413 with a sentence naming the limit; the client shows it as a toast. Messages in a room over 4 MB get `{ t: "error", error: "This drawing is too big for a live session" }`. ## Settings From `spekkr.inputs.json` at the repository root. Its full default contents, generated from the `customize.settings` defaults in `spekkr.json` when the file is missing, are `{ "app_name": "Whiteboard", "accent_color": "#4c6ef5" }`. Both keys are optional: - `app_name` (default "Whiteboard"): the page title and the welcome brand. Saved files use the site's origin as `source`. - `accent_color` (default `#4c6ef5`): `--accent` (buttons, selection, focus rings, handles). ## Screens Routes (client, `main.tsx`): - `/`: the canvas (spec R23), also `#json=` shareable links (R24) and `#room=` sessions (R25). A hash change to either reloads the page. - Anything else: "Page not found" with "Go to your canvas". The editor layout (desktop, width ≥ 768 px): - **Top left:** the main menu button (hamburger, `data-testid="main-menu"`). Next to it are the canvas name ("My canvas", "Live session" or "Shared drawing") and, in a session, the session status. - **Top centre:** the toolbar (role `toolbar`, name "Tools"). Buttons have `aria-label` = tool name and `title` = "Name — key". The lock button comes first, then hand, selection, rectangle, diamond, ellipse, arrow, line, draw, text, image and eraser. - **Top right:** the Share button (accent), then the Library button. - **Left:** the floating style panel (`.style-panel`), shown while a tool other than hand, selection or eraser is active, or while something is selected. The sections are the ones in R13, then layers, align (2+ selected) and actions. - **Bottom left:** zoom (−, percentage = reset, +), then undo and redo. - **Bottom right:** the Help button (`aria-label="Help"`). - **Collaborators:** while a session runs, round avatars with initials in the peer colours sit under the canvas name with "Live · N here", and the Share button shows a count badge. - **Banner:** top centre, below the toolbar (`role="status"`): the R24 and R25 banners with their buttons. - **Share dialog:** two sections, "Live collaboration" (name field, then Start session, or the session link with Copy link and Stop/Leave) and "Shareable link" (Create encrypted link, then the link with Copy). Phones (`(max-width: 767px)`): - The toolbar moves to the bottom, without key hints. - The style panel becomes a bottom sheet (up to 55 % of the height), opened by a "Style" button and closed by "Close style". - Library shows as an icon only. The Help button is hidden; the menu still offers the shortcuts. Text editor layer (R6, R22), as in Excalidraw's `.excalidraw-textEditorContainer`: - Markup: `
` (`position: absolute; inset: 0; overflow: hidden; z-index: 4; pointer-events: none`) holding the `