gitflarePublicPartly agent-ready50
cf-durable-whiteboard
Realtime collaborative whiteboard on Cloudflare Durable Objects: presence cursors, WebSocket hibernation, SQLite storage, undo, PNG export.
- LicenseApache-2.0
- LanguageTypeScript
- Last landed
6eb4fbdOct 20, 2026
Keep board zoom and pan stable across reloads
6eb4fbdimport { isBoardId } from "./lib/ids";export { Board } from "./board"; declare global { interface Env { BOARD: DurableObjectNamespace; ASSETS: Fetcher }} const HEADERS: Record<string, string> = { "X-Content-Type-Options": "nosniff", "Referrer-Policy": "strict-origin-when-cross-origin", "X-Frame-Options": "DENY", "Permissions-Policy": "camera=(), microphone=(), geolocation=()", "Content-Security-Policy": "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:; frame-ancestors 'none'",}; export function withSecurity(res: Response): Response { if (res.status === 101) return res; const r = new Response(res.body, res); for (const [k, v] of Object.entries(HEADERS)) r.headers.set(k, v); return r;} export function jsonError(status: number, code: string, message: string): Response { return Response.json({ error: { code, message } }, { status });} function log(fields: Record<string, unknown>) { console.log(JSON.stringify({ ts: new Date().toISOString(), ...fields }));} async function route(req: Request, env: Env): Promise<Response> { const url = new URL(req.url); const p = url.pathname; if (p === "/health") return Response.json({ ok: true, service: "cf-durable-whiteboard" }); let m = p.match(/^\/ws\/([^/]+)$/); if (m) { if (!isBoardId(m[1])) return jsonError(400, "bad_board_id", "Invalid board id"); if (req.headers.get("Upgrade") !== "websocket") return jsonError(426, "upgrade_required", "Expected websocket"); return env.BOARD.get(env.BOARD.idFromName(m[1])).fetch(req); } m = p.match(/^\/api\/boards\/([^/]+)$/); if (m) { if (req.method !== "GET") return jsonError(405, "method_not_allowed", "Use GET"); if (!isBoardId(m[1])) return jsonError(400, "bad_board_id", "Invalid board id"); return env.BOARD.get(env.BOARD.idFromName(m[1])).fetch(new Request(new URL("/info", url))); } if (p.startsWith("/api/")) return jsonError(404, "not_found", "Unknown API route"); if (/^\/b\/[^/]+$/.test(p)) return env.ASSETS.fetch(new Request(new URL("/board", url), req)); return env.ASSETS.fetch(req);} export default { async fetch(req: Request, env: Env): Promise<Response> { const start = Date.now(); let res: Response; try { res = await route(req, env); } catch (e) { log({ level: "error", path: new URL(req.url).pathname, error: String(e) }); res = jsonError(500, "internal", "Internal error"); } log({ level: "info", method: req.method, path: new URL(req.url).pathname, status: res.status, ms: Date.now() - start }); return withSecurity(res); },} satisfies ExportedHandler<Env>;