Public: anyone can read this; the crew can change it.

Multiplayer and sync as forge primitives: an ordered change stream per app, rooms and presence, zero dependencies #1453

Closed opened this in answer to
Closed without merging

scout/forge:scout/1117-multiplayer-and-sync-as-forge-primitives → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
9 files changed +1667 −16
docs/APPS.md +54
@@ -532,6 +532,60 @@ over the same SQLite file the web page uses, so a new app is reachable two
532532 ways from its first minute. An app without a `tty` says so, in words, when
533533 someone tries.
534534
535 ## Sync and rooms
536
537 Every app host answers `/sync/*` itself, with the app asleep or not
538 (`src/apps/sync.ts`). It is an ordered stream of changes per room, for
539 games, shared documents, sensor readings — a change is any JSON.
540
541 | request | does |
542 | --------------------------------------- | ------------------------------------------------------------------------------------------------------ |
543 | `POST /sync/:room` | `{client, seq, change}` appends; answers `{id, duplicate}`. `{client, presence}` is a heartbeat (`null` leaves) |
544 | `GET /sync/:room?since=N` | `text/event-stream`: `snapshot` (when `N` is behind it), every `change` after `N`, `hello`, then live; `Last-Event-ID` works. Without `Accept: text/event-stream`, the same as JSON |
545 | `POST /sync/:room/snapshot` | `{upTo, state}` keeps the folded state and deletes the log up to `upTo` |
546
547 - **Order** is the server's: ids are dense per room and follow arrival.
548 `(client, seq)` is the client's: a retry of one the server has numbered
549 answers `duplicate: true` and appends nothing, so a client resends freely.
550 - **Who**: whoever the app admits may read, anonymous visitors of a public
551 app included. Writing, presence and snapshots need a signed-in person
552 (a grant that names one, `user` or `admin`), a same-origin request and
553 `application/json`. Rooms are named `[a-z0-9][a-z0-9_-]{0,63}`.
554 - **Compaction** is the writers': the server never reads a change, so a
555 client that has folded the log posts the state as of an id. A room holds
556 5000 changes past its snapshot, then answers `409 compact` until one
557 arrives. `static/sync.js` does this every 200 changes.
558 - **Presence** is never logged: a room lists each client's last state and
559 drops it 20 seconds after its last heartbeat. Idle is free: no listener,
560 no timer, no memory; the log is one row per change.
561 - **Durable** in `<env>/sync/sync.db` beside the environment (not in
562 `FORGE_APP_DATA`, which the app can write). A preview starts with empty
563 rooms and its own log; both go with the environment.
564 - Limits: change 16 KiB, snapshot 1 MiB, presence 512 B, 64 clients and 200
565 rooms. A reader that falls 1 MiB behind is dropped and reconnects.
566 Every POST is rationed per person (a burst of 40, then 10 a second; `429
567 slow_down` with `Retry-After`), and open streams are capped at 256 per room
568 and 8 per client address across the environment (`429 too_many_streams`).
569 A `HEAD` answers the headers and holds nothing open.
570 - **The app's side**: the app's terminal (and any tool of its own) reaches the
571 stream through the forge's door with the identity it already holds: headers
572 `x-forge-identity` / `x-forge-signature`, signed with the app's identity key
573 exactly as the forge signs for the app. Only `/sync` reads them on a request
574 from outside; the forge checks the signature, the expiry and the person's
575 entitlement like a grant's. The scaffold's `src/room.ts` does it and the
576 terminal's `r` (read and tail) and `p` (push) use it.
577 - A refused push (403 after sign-out, 429, 409, 413) is dropped by
578 `sync.js` with `onStatus("refused:<status>")`: an app must say so in plain
579 words, or the change vanishes silently.
580
581 The scaffold ships `static/sync.js`, one file, no dependencies: `join(room,
582 {initial, apply, onState, onPresence})` keeps the server-ordered state, shows
583 your own pushes at once, and re-applies the ones the server has not ordered
584 yet on top of whatever arrives (the rebase). An app that already serves
585 `/sync/<room>` on its own host is shadowed by this: use another path.
586 Not here: WebSockets (SSE carries it), per-room permissions, an MCP tool for
587 rooms (the page and the terminal are the doors for now).
588
535589 ## Hostnames and the proxy
536590
537591 Apps are served from the forge's port by `Host`. With `FORGE_APP_DOMAIN`
scripts/gate.ts +3
@@ -85,6 +85,7 @@ export const GATE: readonly string[] = [
8585 "test/autonomy.test.ts",
8686 "test/studio.test.ts",
8787 "test/studio-words.test.ts",
88 "test/sync.test.ts",
8889 "test/following.test.ts",
8990 "test/forks.test.ts",
9091 "test/front.test.ts",
@@ -223,6 +224,7 @@ export const GATE: readonly string[] = [
223224 "test/palette.test.ts",
224225 "test/qr.test.ts",
225226 "test/branches.test.ts",
227 "test/apps-sync.test.ts",
226228 "test/cli-sync.test.ts",
227229 "test/code.test.ts",
228230 "test/counts.test.ts",
@@ -234,6 +236,7 @@ export const GATE: readonly string[] = [
234236 ];
235237
236238 export const EXCLUDED: readonly Exclusion[] = [
239 { file: "test/plan-route.test.ts", reason: "not yet admitted", issue: 261 },
237240 { file: "test/api-errors.test.ts", reason: "not yet admitted", issue: 261 },
238241 { file: "test/apps-api.test.ts", reason: "not yet admitted", issue: 261 },
239242 {
src/apps/data.ts +3
@@ -33,6 +33,7 @@ import {
3333 } from "node:fs";
3434 import { join } from "node:path";
3535 import { defect } from "../kernel/error.ts";
36 import { closeSyncLogs } from "./sync.ts";
3637
3738 /** `production`, or `pull-<n>` for the preview of pull `n`. */
3839 export type EnvName = "production" | `pull-${number}`;
@@ -113,11 +114,13 @@ export function reseedEmpty(dataDir: string, appId: string, env: EnvName): void
113114
114115 /** Remove an environment entirely: checkouts, data, everything. */
115116 export function removeEnv(dataDir: string, appId: string, env: EnvName): void {
117 closeSyncLogs(envDir(dataDir, appId, env));
116118 rmSync(envDir(dataDir, appId, env), { recursive: true, force: true });
117119 }
118120
119121 /** Remove an app's whole directory — every environment with it. */
120122 export function removeApp(dataDir: string, appId: string): void {
123 closeSyncLogs(join(appsRoot(dataDir), appId));
121124 rmSync(join(appsRoot(dataDir), appId), { recursive: true, force: true });
122125 }
123126
src/apps/proxy.ts +94 −9
@@ -18,6 +18,7 @@ import type { Database } from "bun:sqlite";
1818 import { getIssue, type Issue } from "../core/issues.ts";
1919 import { mayView } from "../core/sealed.ts";
2020 import { holdOpen } from "../http/caller.ts";
21 import { bucketOf, clientAddress } from "../http/peer.ts";
2122 import { appHostSuffix } from "./host.ts";
2223 import { createHmac, timingSafeEqual } from "node:crypto";
2324 import type { App } from "../app.ts";
@@ -32,7 +33,8 @@ import {
3233 import { getUserById, isActive } from "../core/users.ts";
3334 import { err, ok, type Result } from "../kernel/result.ts";
3435 import { loadKey } from "../kernel/secret.ts";
35 import { previewEnv, type EnvName } from "./data.ts";
36 import { envDir, previewEnv, type EnvName } from "./data.ts";
37 import { serveSync, syncPath } from "./sync.ts";
3638 import type { AppsRuntime, EnvStatus } from "./runtime.ts";
3739
3840 export interface AppTarget {
@@ -173,7 +175,7 @@ export function originFor(
173175 * grants on one hostname — this one, and a forge it hosts, for an app of
174176 * that forge's own — and each must find its own cookie beside the other's.
175177 */
176 const grantCookieName = (target: AppTarget): string =>
178 export const grantCookieName = (target: AppTarget): string =>
177179 `forge_grant_${target.app.id.slice(-8)}`;
178180 const GRANT_URL_TTL_MS = 2 * 60_000;
179181 const GRANT_COOKIE_TTL_MS = 12 * 60 * 60_000;
@@ -361,20 +363,60 @@ function stillEntitled(
361363 }
362364
363365 /**
364 * What a request addressed to an app must pass before anything is served:
365 * a private app's grant, then a live port. One gate for both the request
366 * that is fetched and the one that becomes a socket — the answer when a
367 * gate refuses is the response to send instead.
366 * The person the app itself vouches for: its terminal and its tools hold
367 * the app's identity key and sign who is at the keyboard exactly as the
368 * forge signs for the app (`identityHeaders`). Only the stream's door reads
369 * this, and the person is held to the same entitlement as a grant's.
368370 */
369 function admit(
371 function appSigned(
370372 runtime: AppsRuntime,
371373 request: Request,
372374 target: AppTarget,
373 ): Result<{ status: EnvStatus; port: number; grant?: Grant }, Response> {
375 now = Date.now(),
376 ): Grant | undefined {
377 const identity = request.headers.get("x-forge-identity");
378 const signature = request.headers.get("x-forge-signature");
379 if (identity === null || signature === null) return undefined;
380 const expected = createHmac(
381 "sha256",
382 identityKey(runtime.app.config.dataDir, target.app.id),
383 )
384 .update(identity)
385 .digest("base64url");
386 const a = Buffer.from(signature);
387 const b = Buffer.from(expected);
388 if (a.length !== b.length || !timingSafeEqual(a, b)) return undefined;
389 const parts = identity.split("|");
390 if (parts.length !== 4) return undefined;
391 const [id, name, role, expires] = parts as [string, string, string, string];
392 if (
393 id === "" ||
394 name === "" ||
395 (role !== "user" && role !== "admin") ||
396 !/^\d+$/.test(expires) ||
397 Number(expires) <= now
398 )
399 return undefined;
400 return { who: { id, name, role }, expiresMs: Number(expires) };
401 }
402
403 /**
404 * Whoever the request's grant vouches for, or the response that turns a
405 * visitor away from a private app. No port is needed: the sync stream
406 * (`apps/sync.ts`) is answered by the forge with the app asleep.
407 */
408 function vouch(
409 runtime: AppsRuntime,
410 request: Request,
411 target: AppTarget,
412 bySignature = false,
413 ): Result<Grant | undefined, Response> {
374414 const cookie = cookieValue(request, grantCookieName(target));
375415 const signed =
376416 cookie === undefined
377 ? undefined
417 ? bySignature
418 ? appSigned(runtime, request, target)
419 : undefined
378420 : readGrant(runtime.app.config.dataDir, cookie, target);
379421 // A private app's grant is asked again on every request whether the
380422 // person it names may still enter: a grant outlives a change of heart —
@@ -424,6 +466,23 @@ function admit(
424466 return err(new Response("not found", { status: 404 }));
425467 }
426468 }
469 return ok(grant);
470 }
471
472 /**
473 * What a request addressed to an app must pass before anything is served:
474 * a private app's grant, then a live port. One gate for both the request
475 * that is fetched and the one that becomes a socket — the answer when a
476 * gate refuses is the response to send instead.
477 */
478 function admit(
479 runtime: AppsRuntime,
480 request: Request,
481 target: AppTarget,
482 ): Result<{ status: EnvStatus; port: number; grant?: Grant }, Response> {
483 const vouched = vouch(runtime, request, target);
484 if (!vouched.ok) return vouched;
485 const grant = vouched.value;
427486 // A preview stopped for want of attention is asked for: it deploys again
428487 // the ordinary way, and this request sees "starting" until it answers.
429488 if (runtime.envStatus(target.app, target.env)?.dormant !== undefined)
@@ -462,6 +521,30 @@ const REPORT_LINK =
462521 const isHtml = (headers: Headers): boolean =>
463522 (headers.get("content-type") ?? "").toLowerCase().startsWith("text/html");
464523
524 /**
525 * The sync stream is the forge's, answered with the app asleep: nothing
526 * here wakes it, and a room nobody listens to costs nothing. Reads follow
527 * the app's access; a write needs a named person.
528 */
529 export function proxySync(
530 runtime: AppsRuntime,
531 request: Request,
532 target: AppTarget,
533 room: { room: string; snapshot: boolean },
534 server?: { requestIP(request: Request): { address: string } | null },
535 ): Promise<Response> | Response {
536 const vouched = vouch(runtime, request, target, true);
537 if (!vouched.ok) return vouched.error;
538 const who = vouched.value?.who;
539 return serveSync(
540 envDir(runtime.app.config.dataDir, target.app.id, target.env),
541 request,
542 room,
543 who === undefined ? undefined : { id: who.id, name: who.name },
544 bucketOf(clientAddress(request) !== "unknown" ? clientAddress(request) : (server?.requestIP(request)?.address ?? "unknown")),
545 );
546 }
547
465548 /**
466549 * Serve a request addressed to an app. `undefined` means the request became
467550 * a websocket: the response was the handshake, and `appWebSocket` now owns
@@ -527,6 +610,8 @@ export async function proxyApp(
527610 });
528611 }
529612 }
613 const room = target.nested ? undefined : syncPath(url.pathname);
614 if (room !== undefined) return proxySync(runtime, request, target, room, server);
530615 // An environment asleep wakes for the request that wants it, and the
531616 // request waits the second that takes rather than seeing a closed door.
532617 if (runtime.envStatus(target.app, target.env)?.state === "asleep")
src/apps/scaffold.ts +447 −6
@@ -63,12 +63,15 @@ export function scaffoldFiles(input: ScaffoldInput): FileWrite[] {
6363 { path: "src/openapi.ts", content: OPENAPI_TS },
6464 { path: "src/routes.ts", content: ROUTES_TS },
6565 { path: "src/server.ts", content: SERVER_TS },
66 { path: "src/room.ts", content: ROOM_TS },
6667 { path: "src/tty.ts", content: TTY_TS },
6768 { path: "scripts/lint-design.ts", content: LINT_DESIGN_TS },
6869 { path: "scripts/contract-emit.ts", content: CONTRACT_EMIT_TS },
6970 { path: "static/app.css", content: APP_CSS },
7071 { path: "static/live.js", content: LIVE_JS },
72 { path: "static/sync.js", content: SYNC_JS },
7173 { path: "src/who.test.ts", content: WHO_TEST },
74 { path: "src/room.test.ts", content: ROOM_TEST },
7275 { path: "src/db.test.ts", content: DB_TEST },
7376 { path: "src/actions.test.ts", content: ACTIONS_TEST },
7477 { path: "src/contract.test.ts", content: CONTRACT_TEST },
@@ -161,9 +164,11 @@ decide nothing themselves. \`AGENTS.md\` says how to add to it.
161164 | \`design/tokens.json\`, \`src/tokens.ts\` | the look as data, light and dark; compiled to \`/tokens.css\` |
162165 | \`src/http.ts\` | the floor: headers, body cap, files |
163166 | \`src/server.ts\` | boot: open the database, serve |
167 | \`src/room.ts\` | the forge's \`/sync\` stream from the app's side: read, tail, push |
164168 | \`src/tty.ts\` | the terminal, over the same actions |
165169 | \`src/env.ts\` | what the forge told this process |
166170 | \`static/app.css\`, \`static/live.js\` | the look in the tokens' words, and the list that stays current |
171 | \`static/sync.js\` | rooms, optimistic writes and presence on the forge's \`/sync\` |
167172
168173 ## What every app stands on
169174
@@ -235,7 +240,20 @@ reload behind.
235240 The terminal opens with the exact command in \`FORGE_APP_SSH\` when the app
236241 runs (\`ssh -p 2222 <name>@<forge>\` — the app is the login name, the forge
237242 the host; \`<name>--<pull>@<forge>\` for a preview's). It is \`src/tty.ts\` on
238 a real pty over the same data, as the account at the keyboard.
243 a real pty over the same data, as the account at the keyboard. In it, \`r\`
244 opens the room \`lobby\` (\`src/room.ts\`: the forge's change stream, read
245 and tailed live) and \`p\` pushes a line to it, as you; \`r\` again returns.
246
247 ### Rooms
248
249 \`static/sync.js\` joins a room on the forge's \`/sync/<room>\` stream: anyone
250 the app admits reads, a signed-in person pushes, and the forge limits each
251 person's writes (429 \\\`slow_down\\\`) and each address's open streams (429
252 \\\`too_many_streams\\\`). A refused push is dropped from the page's view, and
253 \`onStatus\` hears \`refused:<status>\` — **an app must show that in plain
254 words** (403: sign in again; 429: slow down; 409/413: the change was not
255 kept), or a person's change vanishes without a sign. The terminal does so in
256 \`src/room.ts\`'s \`refusal\`.
239257
240258 The forge sets \`PORT\`, \`FORGE_APP_DATA\`, \`FORGE_APP_ENV\` (\`production\` or
241259 \`preview\`), \`FORGE_APP_URL\`, \`FORGE_APP_COMMIT\`, \`FORGE_APP_SSH\` and
@@ -2014,12 +2032,208 @@ if (import.meta.main) {
20142032 }
20152033 `;
20162034
2035 // The room: the forge's /sync stream, from the app's side.
2036 const ROOM_TS = `/**
2037 * The forge's change stream for this app (\`/sync/:room\`), reached from
2038 * the app's own side: the terminal reads a room, tails it and pushes a
2039 * change here, over the same stream the page's \`static/sync.js\` joins. The
2040 * app holds the identity key, so it signs who is at the keyboard as the
2041 * forge signs for the app (\`who.ts\`); the forge checks the signature, the
2042 * person's entitlement and its limits. Without \`FORGE_URL\` there is no
2043 * forge to ask, and every call says so in words.
2044 */
2045
2046 import { createHmac } from "node:crypto";
2047 import { forgeUrl, identityKey, publicOrigin } from "./env.ts";
2048 import type { Who } from "./who.ts";
2049
2050 export interface Heard {
2051 readonly id: number;
2052 readonly who: string;
2053 readonly at: number;
2054 readonly change: unknown;
2055 }
2056
2057 /** The headers that say who is speaking, signed for the forge to check. */
2058 export function signedAs(
2059 who: Who,
2060 key: string = identityKey,
2061 now: number = Date.now(),
2062 ): Record<string, string> {
2063 if (who.role === "anon" || key === "") return {};
2064 const identity = [who.id, who.name, who.role, now + 60_000].join("|");
2065 return {
2066 "x-forge-identity": identity,
2067 "x-forge-signature": createHmac("sha256", key)
2068 .update(identity)
2069 .digest("base64url"),
2070 };
2071 }
2072
2073 /** What the forge said when it refused, in words a person can act on. */
2074 export function refusal(status: number): string {
2075 if (status === 403) return "Sign in to push changes to the room.";
2076 if (status === 429) return "Too fast: wait a moment and try again.";
2077 if (status === 409) return "The room is full: a page must compact it first.";
2078 if (status === 413) return "That change is too large.";
2079 return "The forge refused it (" + status + ").";
2080 }
2081
2082 function door(room: string, query = ""): URL | undefined {
2083 if (forgeUrl === undefined) return undefined;
2084 return new URL("/sync/" + encodeURIComponent(room) + query, forgeUrl);
2085 }
2086
2087 const headers = (who: Who, extra: Record<string, string> = {}) => ({
2088 host: new URL(publicOrigin).host,
2089 ...signedAs(who),
2090 ...extra,
2091 });
2092
2093 const NO_FORGE = "There is no forge to ask: FORGE_URL is not set.";
2094
2095 /** The changes after \`since\`, or the sentence that says why not. */
2096 export async function readRoom(
2097 room: string,
2098 who: Who,
2099 since = 0,
2100 ): Promise<{ head: number; changes: Heard[] } | string> {
2101 const url = door(room, "?since=" + since);
2102 if (url === undefined) return NO_FORGE;
2103 try {
2104 const res = await fetch(url, { headers: headers(who) });
2105 if (!res.ok) return refusal(res.status);
2106 return (await res.json()) as { head: number; changes: Heard[] };
2107 } catch {
2108 return "The forge did not answer.";
2109 }
2110 }
2111
2112 const client = "tty-" + Math.random().toString(36).slice(2, 10);
2113 let seq = 0;
2114
2115 /** Append one change as \`who\`; undefined when it was taken, else why not. */
2116 export async function pushChange(
2117 room: string,
2118 who: Who,
2119 change: unknown,
2120 ): Promise<string | undefined> {
2121 const url = door(room);
2122 if (url === undefined) return NO_FORGE;
2123 if (who.role === "anon") return refusal(403);
2124 try {
2125 const res = await fetch(url, {
2126 method: "POST",
2127 headers: headers(who, { "content-type": "application/json" }),
2128 body: JSON.stringify({ client, seq: ++seq, change }),
2129 });
2130 return res.ok ? undefined : refusal(res.status);
2131 } catch {
2132 return "The forge did not answer.";
2133 }
2134 }
2135
2136 /** Server-sent frames out of a buffer: whole ones, and what is left over. */
2137 export function parseFrames(buffer: string): {
2138 frames: { event: string; data: string }[];
2139 rest: string;
2140 } {
2141 const parts = buffer.split("\\n\\n");
2142 const rest = parts.pop() ?? "";
2143 const frames: { event: string; data: string }[] = [];
2144 for (const part of parts) {
2145 let event = "message";
2146 const data: string[] = [];
2147 for (const line of part.split("\\n")) {
2148 if (line.startsWith("event:")) event = line.slice(6).trim();
2149 else if (line.startsWith("data:")) data.push(line.slice(5).trim());
2150 }
2151 if (data.length > 0) frames.push({ event, data: data.join("\\n") });
2152 }
2153 return { frames, rest };
2154 }
2155
2156 /**
2157 * Follow a room live: \`onChange\` hears every change after \`since\` in the
2158 * server's order, then each new one, until \`signal\` aborts. Resolves with
2159 * why it stopped, if it did not abort.
2160 */
2161 export async function tailRoom(
2162 room: string,
2163 who: Who,
2164 since: number,
2165 onChange: (heard: Heard) => void,
2166 signal: AbortSignal,
2167 ): Promise<string | undefined> {
2168 const url = door(room, "?since=" + since);
2169 if (url === undefined) return NO_FORGE;
2170 try {
2171 const res = await fetch(url, {
2172 headers: headers(who, { accept: "text/event-stream" }),
2173 signal,
2174 });
2175 if (!res.ok || res.body === null) return refusal(res.status);
2176 const decoder = new TextDecoder();
2177 let buffer = "";
2178 for await (const chunk of res.body) {
2179 buffer += decoder.decode(chunk, { stream: true });
2180 const parsed = parseFrames(buffer);
2181 buffer = parsed.rest;
2182 for (const f of parsed.frames)
2183 if (f.event === "change") onChange(JSON.parse(f.data) as Heard);
2184 }
2185 return "The stream ended.";
2186 } catch {
2187 return signal.aborted ? undefined : "The stream broke.";
2188 }
2189 }
2190 `;
2191
2192 const ROOM_TEST = `import { expect, test } from "bun:test";
2193 import { createHmac } from "node:crypto";
2194 import { parseFrames, refusal, signedAs } from "./room.ts";
2195 import { sign, who } from "./who.ts";
2196
2197 test("a person at the terminal is signed as the forge signs, and a guest is not", () => {
2198 const key = "k".repeat(32);
2199 const headers = signedAs({ role: "user", id: "7", name: "ana" }, key, 1000);
2200 expect(headers["x-forge-identity"]).toBe("7|ana|user|61000");
2201 expect(headers["x-forge-signature"]).toBe(
2202 createHmac("sha256", key).update("7|ana|user|61000").digest("base64url"),
2203 );
2204 // The app reads what it signs: the same bytes are someone, in time.
2205 const request = new Request("http://x/", { headers });
2206 expect(who(request, key, 2000)).toEqual({ role: "user", id: "7", name: "ana" });
2207 expect(who(request, key, 62000)).toEqual({ role: "anon" });
2208 expect(signedAs({ role: "anon" }, key)).toEqual({});
2209 expect(signedAs({ role: "user", id: "7", name: "ana" }, "")).toEqual({});
2210 expect(sign("a", "b")).not.toBe("");
2211 });
2212
2213 test("frames come out whole and the rest waits for more", () => {
2214 const first = parseFrames(
2215 'id: 1\\nevent: change\\ndata: {"id":1}\\n\\n:\\n\\nevent: hello\\ndata: {"hea',
2216 );
2217 expect(first.frames).toEqual([{ event: "change", data: '{"id":1}' }]);
2218 expect(first.rest).toBe('event: hello\\ndata: {"hea');
2219 expect(parseFrames(first.rest + 'd":1}\\n\\n').frames[0]?.event).toBe("hello");
2220 });
2221
2222 test("a refusal is said in words, never as a bare number", () => {
2223 for (const status of [403, 409, 413, 429, 500])
2224 expect(refusal(status)).toMatch(/^[A-Z][^]*[.)]$/);
2225 expect(refusal(403)).toContain("Sign in");
2226 });
2227 `;
2228
20172229 // The terminal.
20182230 const TTY_TS = `/**
20192231 * The app in a terminal. The forge runs this on a pty when someone
20202232 * \`ssh\`es to the app, over the same data as the page and through the same
20212233 * actions, as the account at the keyboard. j/k move, a adds, d removes the
2022 * note under the cursor, q leaves. Plain ANSI, no dependencies.
2234 * note under the cursor, q leaves. r opens the room (\`room.ts\`): the
2235 * forge's change stream, read and tailed live; p pushes a line to it, as
2236 * you, over the same stream the page joins. Plain ANSI, no dependencies.
20232237 */
20242238
20252239 import {
@@ -2031,6 +2245,7 @@ import {
20312245 } from "./actions.ts";
20322246 import { openDb } from "./db.ts";
20332247 import { ssh, title, where } from "./env.ts";
2248 import { pushChange, readRoom, tailRoom, type Heard } from "./room.ts";
20342249 import { whoAtTty } from "./who.ts";
20352250
20362251 const db = openDb();
@@ -2042,16 +2257,66 @@ const out = (s: string): void => {
20422257 process.stdout.write(s);
20432258 };
20442259
2260 const ROOM = "lobby";
20452261 let cursor = 0;
20462262 let typing: string | undefined;
20472263 let said = "";
2264 let heard: Heard[] | undefined; // the room, while it is open
2265 let leaveRoom = (): void => {};
2266
2267 /** Open the room: what was said, then what is said, until it is left. */
2268 async function openRoom(): Promise<void> {
2269 const read = await readRoom(ROOM, me);
2270 if (typeof read === "string") {
2271 said = read;
2272 return draw();
2273 }
2274 heard = read.changes.slice(-200);
2275 const abort = new AbortController();
2276 leaveRoom = () => {
2277 abort.abort();
2278 heard = undefined;
2279 };
2280 draw();
2281 const why = await tailRoom(
2282 ROOM,
2283 me,
2284 read.head,
2285 (c) => {
2286 heard?.push(c);
2287 draw();
2288 },
2289 abort.signal,
2290 );
2291 if (why !== undefined) said = why;
2292 draw();
2293 }
2294
2295 const line = (c: Heard): string => {
2296 const change = c.change as { say?: unknown } | null;
2297 const text = typeof change?.say === "string" ? change.say : JSON.stringify(change);
2298 return \`\${c.who}: \${text}\`.replace(/[\\u0000-\\u001f\\u007f]/g, " ");
2299 };
20482300
20492301 const notes = (): Note[] => {
20502302 const listed = listNotes(db, me);
20512303 return listed.ok ? listed.value : [];
20522304 };
20532305
2306 function drawRoom(rows: Heard[]): void {
2307 const lines = [\`\${bold(title)} \${dim(\`room \${ROOM}\`)}\`, ""];
2308 const shown = rows.slice(-Math.max(1, (process.stdout.rows || 24) - 6));
2309 if (shown.length === 0) lines.push(dim("Nobody has said anything yet."));
2310 for (const c of shown) lines.push(line(c));
2311 lines.push("");
2312 if (typing !== undefined) lines.push(\`Say: \${typing}\${esc}7m \${esc}0m\`);
2313 else if (said !== "") lines.push(said);
2314 else lines.push(dim(me.role === "anon" ? "r back · q quit" : "p push a line · r back · q quit"));
2315 out(\`\${esc}2J\${esc}H\${lines.join("\\r\\n")}\`);
2316 }
2317
20542318 function draw(): void {
2319 if (heard !== undefined) return drawRoom(heard);
20552320 const rows = notes();
20562321 const lines = [
20572322 \`\${bold(title)} \${dim(where)} \${dim(me.role === "anon" ? "guest" : \`\${me.name}\${me.role === "admin" ? " (admin)" : ""}\`)}\`,
@@ -2094,10 +2359,20 @@ process.stdin.on("data", (key: string) => {
20942359 said = "";
20952360 if (typing !== undefined) {
20962361 if (key === "\\r") {
2097 const added = addNote(db, me, { body: typing });
2098 if (!added.ok) said = added.message;
2099 typing = undefined;
2100 cursor = 0;
2362 if (heard !== undefined) {
2363 const text = typing;
2364 typing = undefined;
2365 if (text !== "")
2366 void pushChange(ROOM, me, { say: text }).then((why) => {
2367 if (why !== undefined) said = why;
2368 draw();
2369 });
2370 } else {
2371 const added = addNote(db, me, { body: typing });
2372 if (!added.ok) said = added.message;
2373 typing = undefined;
2374 cursor = 0;
2375 }
21012376 } else if (key === "\\x1b") typing = undefined;
21022377 else if (key === "\\x7f") typing = typing.slice(0, -1);
21032378 else if (key >= " ") typing += key;
@@ -2108,6 +2383,18 @@ process.stdin.on("data", (key: string) => {
21082383 out(\`\${esc}2J\${esc}H\`);
21092384 process.exit(0);
21102385 }
2386 if (key === "r") {
2387 if (heard !== undefined) leaveRoom();
2388 else void openRoom();
2389 return draw();
2390 }
2391 if (heard !== undefined) {
2392 if (key === "p") {
2393 if (me.role === "anon") said = "Sign in to push a line.";
2394 else typing = "";
2395 }
2396 return draw();
2397 }
21112398 const rows = notes();
21122399 if (key === "j" || key === "\\x1b[B")
21132400 cursor = Math.min(cursor + 1, Math.max(0, rows.length - 1));
@@ -2344,6 +2631,160 @@ footer code {
23442631 }
23452632 `;
23462633
2634 // Rooms, optimistic writes and presence over the forge's /sync stream.
2635 const SYNC_JS = `// Sync: local state that every other page in the room shares, ordered by the
2636 // forge. No dependencies. Import it, join a room, push changes:
2637 //
2638 // import { join } from "/static/sync.js";
2639 // const room = join("lobby", {
2640 // initial: { count: 0 },
2641 // apply: (state, change) => ({ count: state.count + change.add }),
2642 // onState: (view) => render(view), // confirmed + your pending
2643 // onPresence: (peers) => draw(peers), // [{ client, who, state }]
2644 // });
2645 // room.push({ add: 1 }); // shows now, settles in server order
2646 // room.presence({ x: 3, y: 4 }); // throttled; stays while you are here
2647 //
2648 // apply must be pure and total: it runs again whenever the server's order
2649 // differs from yours (that is the rebase). A change is any JSON up to 16 KiB.
2650 // Reads work for anyone the app admits; pushing needs a signed-in person.
2651 export function join(name, options) {
2652 const { apply, onState, onPresence, onStatus } = options;
2653 const base = options.base || "/sync/" + encodeURIComponent(name);
2654 const client = Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
2655 const every = options.snapshotEvery || 200;
2656 let confirmed = options.initial;
2657 let last = 0; // the newest server id folded into confirmed
2658 let seq = 0;
2659 let pending = []; // [{ seq, change }] not yet heard back from the server
2660 let source = null;
2661 let closed = false;
2662 let mine = null; // latest presence state, resent as a heartbeat
2663 let sending = false;
2664 let timer = 0;
2665 let beat = 0;
2666
2667 const view = () => {
2668 let state = confirmed;
2669 for (const p of pending) state = apply(state, p.change);
2670 return state;
2671 };
2672 const show = () => onState && onState(view());
2673 const post = (path, body) =>
2674 fetch(base + path, {
2675 method: "POST",
2676 headers: { "content-type": "application/json" },
2677 body: JSON.stringify(body),
2678 credentials: "same-origin",
2679 });
2680
2681 // Changes go out one at a time, in order, and are retried: the server
2682 // ignores a (client, seq) pair it has already numbered, so a retry is safe.
2683 async function flush() {
2684 if (sending) return;
2685 sending = true;
2686 let wait = 500;
2687 for (let next; !closed && (next = pending.find((p) => !p.sent)); ) {
2688 try {
2689 const res = await post("", { client, seq: next.seq, change: next.change });
2690 if (res.ok) {
2691 next.sent = true; // leaves pending when the stream echoes it
2692 wait = 500;
2693 continue;
2694 }
2695 if (res.status === 409) await compact();
2696 else if (res.status >= 400 && res.status < 500 && res.status !== 429) {
2697 pending = pending.filter((p) => p !== next); // refused for good: rebase without it
2698 show();
2699 onStatus && onStatus("refused:" + res.status);
2700 continue;
2701 }
2702 } catch (e) {}
2703 await new Promise((r) => setTimeout(r, wait));
2704 wait = Math.min(wait * 2, 8000);
2705 }
2706 sending = false;
2707 }
2708
2709 // The log is compacted by whoever has folded it: the state at last is a
2710 // snapshot every page can start from.
2711 async function compact() {
2712 try {
2713 await post("/snapshot", { upTo: last, state: confirmed });
2714 } catch (e) {}
2715 }
2716
2717 function connect() {
2718 if (closed) return;
2719 source = new EventSource(base + "?since=" + last);
2720 source.addEventListener("snapshot", (e) => {
2721 const m = JSON.parse(e.data);
2722 confirmed = m.state;
2723 last = m.upTo;
2724 show();
2725 });
2726 source.addEventListener("change", (e) => {
2727 const m = JSON.parse(e.data);
2728 if (m.id <= last) return;
2729 confirmed = apply(confirmed, m.change);
2730 last = m.id;
2731 if (m.client === client) pending = pending.filter((p) => p.seq !== m.seq);
2732 show();
2733 if (m.client === client && m.id % every === 0) compact();
2734 });
2735 source.addEventListener("presence", (e) => {
2736 onPresence && onPresence(JSON.parse(e.data));
2737 });
2738 source.addEventListener("hello", (e) => {
2739 const m = JSON.parse(e.data);
2740 onPresence && onPresence(m.peers);
2741 onStatus && onStatus("live");
2742 for (const p of pending) p.sent = false; // anything unheard is sent again
2743 if (mine !== null) announce();
2744 flush();
2745 });
2746 source.onerror = () => onStatus && onStatus("reconnecting");
2747 }
2748
2749 function announce() {
2750 clearTimeout(timer);
2751 timer = 0;
2752 post("", { client, presence: mine }).catch(() => {});
2753 }
2754
2755 connect();
2756 // A heartbeat keeps a quiet page listed; the server forgets it after 20 s.
2757 beat = setInterval(() => mine !== null && announce(), 8000);
2758 const leave = () => {
2759 if (mine !== null && navigator.sendBeacon)
2760 navigator.sendBeacon(base, new Blob([JSON.stringify({ client, presence: null })], { type: "application/json" }));
2761 };
2762 addEventListener("pagehide", leave);
2763 show();
2764
2765 return {
2766 client,
2767 push(change) {
2768 pending.push({ seq: ++seq, change });
2769 show();
2770 flush();
2771 },
2772 presence(state) {
2773 mine = state;
2774 if (!timer) timer = setTimeout(announce, 40);
2775 },
2776 close() {
2777 closed = true;
2778 clearInterval(beat);
2779 clearTimeout(timer);
2780 source && source.close();
2781 leave();
2782 removeEventListener("pagehide", leave);
2783 },
2784 };
2785 }
2786 `;
2787
23472788 // The list that stays current.
23482789 const LIVE_JS = `// The page stays current without a reload. /events is a stream of what
23492790 // changed; each event becomes \`live\` and \`live:<type>\` on \`document\`, and
src/apps/sync.ts added +544
@@ -0,0 +1,544 @@
1 /**
2 * Sync: an ordered stream of changes for every app, served by the forge on
3 * the app's own host (`docs/APPS.md`, "Sync and rooms").
4 *
5 * POST /sync/:room append {client, seq, change} or {client, presence}
6 * POST /sync/:room/snapshot {upTo, state}: fold the log up to `upTo` away
7 * GET /sync/:room?since=N the log after N as server-sent events, then live
8 *
9 * A change is any JSON. The server never reads it: it numbers it (dense,
10 * per room, in arrival order), keeps it, and tells everyone listening. Who
11 * may read is whoever the app admits; who may write is a named person — a
12 * visitor with no grant watches. The log lives in one SQLite file beside
13 * the environment (not in the app's data, which the app can write), is
14 * compacted by snapshots the writers send, and is served without waking the
15 * app. A room with nobody listening costs a row; there is no timer, no
16 * socket, no memory for it.
17 *
18 * Presence is the same stream: a heartbeat that is never logged, listed to
19 * everyone in the room, and dropped when the heartbeats stop.
20 */
21
22 import { Database } from "bun:sqlite";
23 import { existsSync, mkdirSync } from "node:fs";
24 import { join } from "node:path";
25
26 export const CHANGE_MAX = 16 * 1024;
27 export const SNAPSHOT_MAX = 1024 * 1024;
28 export const PRESENCE_MAX = 512;
29 /** Changes a room keeps past its snapshot; at the cap a writer must compact. */
30 export const LOG_MAX = 5000;
31 export const PRESENCE_TTL_MS = 20_000;
32 const ROOMS_MAX = 200;
33 const PEERS_MAX = 64;
34 const SWEEP_MS = 5_000;
35 const HEARTBEAT_MS = 25_000;
36 /** A reader this far behind is let go; it reconnects with `since`. */
37 const BACKLOG_MAX = 1024 * 1024;
38 const OPEN_MAX = 32;
39 /** Open streams one room holds, and one address holds across an environment. */
40 export const LISTENERS_PER_ROOM = 256;
41 export const LISTENERS_PER_ADDRESS = 8;
42 /** Writes per person: a burst, then a steady rate (every POST is a write). */
43 export const WRITE_BURST = 40;
44 export const WRITE_PER_SECOND = 10;
45 const WRITERS_MAX = 5000;
46
47 const ROOM = /^[a-z0-9][a-z0-9_-]{0,63}$/;
48 const CLIENT = /^[A-Za-z0-9_-]{1,64}$/;
49
50 /** The person a grant names; absent for a visitor who may only watch. */
51 export interface Speaker {
52 readonly id: string;
53 readonly name: string;
54 }
55
56 const SCHEMA = `
57 create table if not exists heads (room text primary key, head integer not null);
58 create table if not exists log (
59 room text not null, id integer not null, client text not null, seq integer not null,
60 who text not null, at integer not null, change text not null,
61 primary key (room, id), unique (room, client, seq)
62 ) without rowid;
63 create table if not exists snapshots (
64 room text primary key, up_to integer not null, state text not null, at integer not null
65 );`;
66
67 const stores = new Map<string, Database>();
68
69 function open(dir: string): Database | undefined {
70 const file = join(dir, "sync", "sync.db");
71 const kept = stores.get(file);
72 if (kept !== undefined) {
73 stores.delete(file);
74 stores.set(file, kept);
75 return kept;
76 }
77 if (!existsSync(dir)) return undefined;
78 mkdirSync(join(dir, "sync"), { recursive: true });
79 const db = new Database(file);
80 db.exec("pragma journal_mode = wal; pragma synchronous = normal;");
81 db.exec(SCHEMA);
82 stores.set(file, db);
83 if (stores.size > OPEN_MAX) {
84 const [oldest] = stores.keys();
85 if (oldest !== undefined && !busy(oldest)) closeFile(oldest);
86 }
87 return db;
88 }
89
90 function closeFile(file: string): void {
91 try {
92 stores.get(file)?.close();
93 } catch {}
94 stores.delete(file);
95 }
96
97 /** Let go of every log under `dir` before the directory is removed. */
98 export function closeSyncLogs(dir: string): void {
99 for (const file of [...stores.keys()])
100 if (file.startsWith(`${dir}/`)) closeFile(file);
101 for (const key of [...rooms.keys()])
102 if (key === dir || key.startsWith(`${dir}/`)) rooms.delete(key);
103 }
104
105 const busy = (file: string): boolean => {
106 const dir = file.slice(0, -"/sync/sync.db".length);
107 return (rooms.get(dir)?.size ?? 0) > 0;
108 };
109
110 // --- live rooms: exist only while someone listens --------------------------
111
112 interface Peer {
113 who: string;
114 state: unknown;
115 at: number;
116 }
117 interface Room {
118 readonly listeners: Set<Listener>;
119 readonly peers: Map<string, Peer>;
120 sweep: ReturnType<typeof setInterval> | undefined;
121 }
122 interface Listener {
123 readonly address: string;
124 send(frame: string): boolean;
125 }
126
127 const rooms = new Map<string, Map<string, Room>>();
128
129 const frame = (event: string, data: unknown, id?: number): string =>
130 `${id === undefined ? "" : `id: ${id}\n`}event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
131
132 function listPeers(room: Room): unknown[] {
133 return [...room.peers].map(([client, p]) => ({
134 client,
135 who: p.who,
136 state: p.state,
137 }));
138 }
139
140 function broadcast(room: Room, text: string): void {
141 for (const l of [...room.listeners]) if (!l.send(text)) room.listeners.delete(l);
142 }
143
144 function prune(room: Room, now: number): boolean {
145 let dropped = false;
146 for (const [client, p] of room.peers)
147 if (now - p.at > PRESENCE_TTL_MS) {
148 room.peers.delete(client);
149 dropped = true;
150 }
151 return dropped;
152 }
153
154 function liveRoom(dir: string, name: string, make: boolean): Room | undefined {
155 let byName = rooms.get(dir);
156 const kept = byName?.get(name);
157 if (kept !== undefined || !make) return kept;
158 if (byName === undefined) rooms.set(dir, (byName = new Map()));
159 const room: Room = {
160 listeners: new Set(),
161 peers: new Map(),
162 sweep: undefined,
163 };
164 byName.set(name, room);
165 room.sweep = setInterval(() => {
166 if (prune(room, Date.now()))
167 broadcast(room, frame("presence", listPeers(room)));
168 }, SWEEP_MS);
169 return room;
170 }
171
172 function leave(dir: string, name: string, room: Room, l: Listener): void {
173 room.listeners.delete(l);
174 if (room.listeners.size > 0) return;
175 clearInterval(room.sweep);
176 const byName = rooms.get(dir);
177 byName?.delete(name);
178 if (byName?.size === 0) rooms.delete(dir);
179 }
180
181 // --- limits: a person's writes, an address's open streams --------------------
182
183 interface Bucket {
184 tokens: number;
185 at: number;
186 }
187 const writers = new Map<string, Bucket>();
188
189 /** Spend one write of `who` in `dir`; the seconds to wait when there is none. */
190 export function spendWrite(dir: string, who: string, now = Date.now()): number {
191 const key = `${dir}\n${who}`;
192 const kept = writers.get(key);
193 const bucket: Bucket = kept ?? { tokens: WRITE_BURST, at: now };
194 bucket.tokens = Math.min(
195 WRITE_BURST,
196 bucket.tokens + ((now - bucket.at) / 1000) * WRITE_PER_SECOND,
197 );
198 bucket.at = now;
199 writers.delete(key);
200 writers.set(key, bucket);
201 if (writers.size > WRITERS_MAX) {
202 const [oldest] = writers.keys();
203 if (oldest !== undefined) writers.delete(oldest);
204 }
205 if (bucket.tokens >= 1) {
206 bucket.tokens -= 1;
207 return 0;
208 }
209 return Math.max(1, Math.ceil((1 - bucket.tokens) / WRITE_PER_SECOND));
210 }
211
212 /** Whether `address` may open another stream on `name`. */
213 function mayListen(dir: string, name: string, address: string): boolean {
214 const byName = rooms.get(dir);
215 if ((byName?.get(name)?.listeners.size ?? 0) >= LISTENERS_PER_ROOM) return false;
216 let held = 0;
217 for (const room of byName?.values() ?? [])
218 for (const l of room.listeners) if (l.address === address) held++;
219 return held < LISTENERS_PER_ADDRESS;
220 }
221
222 // --- responses ---------------------------------------------------------------
223
224 const HEADERS = {
225 "cache-control": "no-store",
226 "x-content-type-options": "nosniff",
227 };
228
229 const reply = (body: unknown, status = 200): Response =>
230 Response.json(body, { status, headers: HEADERS });
231 const refuse = (error: string, status: number): Response =>
232 reply({ error }, status);
233
234 /** The room a path names, and whether it is the snapshot door. */
235 export function syncPath(
236 pathname: string,
237 ): { room: string; snapshot: boolean } | undefined {
238 const m = /^\/sync\/([^/]+)(\/snapshot)?$/.exec(pathname);
239 if (m === null || !ROOM.test(m[1]!)) return undefined;
240 return { room: m[1]!, snapshot: m[2] !== undefined };
241 }
242
243 async function readJson(
244 request: Request,
245 max: number,
246 ): Promise<Record<string, unknown> | Response> {
247 if (!(request.headers.get("content-type") ?? "").startsWith("application/json"))
248 return refuse("json_required", 415);
249 const declared = Number(request.headers.get("content-length") ?? 0);
250 if (declared > max) return refuse("too_large", 413);
251 const reader = request.body?.getReader();
252 const chunks: Uint8Array[] = [];
253 let size = 0;
254 while (reader !== undefined) {
255 const { done, value } = await reader.read();
256 if (done) break;
257 size += value.byteLength;
258 if (size > max) {
259 void reader.cancel();
260 return refuse("too_large", 413);
261 }
262 chunks.push(value);
263 }
264 try {
265 const text = Buffer.concat(chunks).toString("utf8");
266 const parsed: unknown = JSON.parse(text);
267 if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed))
268 return parsed as Record<string, unknown>;
269 } catch {}
270 return refuse("invalid", 400);
271 }
272
273 /** A browser's mutation must come from the page's own origin. */
274 function sameOrigin(request: Request): boolean {
275 const origin = request.headers.get("origin");
276 if (origin === null) return request.headers.get("sec-fetch-site") !== "cross-site";
277 try {
278 return new URL(origin).host === request.headers.get("host");
279 } catch {
280 return false;
281 }
282 }
283
284 const isInt = (v: unknown): v is number =>
285 typeof v === "number" && Number.isSafeInteger(v) && v >= 1;
286
287 const jsonSize = (v: unknown): number => {
288 const text = JSON.stringify(v);
289 return text === undefined ? -1 : Buffer.byteLength(text);
290 };
291
292 /**
293 * Serve one `/sync/…` request. `dir` is the environment's directory;
294 * `speaker` is the grant's person, if any. The caller has already admitted
295 * the visitor to the app: this decides read from write.
296 */
297 export async function serveSync(
298 dir: string,
299 request: Request,
300 path: { room: string; snapshot: boolean },
301 speaker: Speaker | undefined,
302 address = "unknown",
303 ): Promise<Response> {
304 const db = open(dir);
305 if (db === undefined) return refuse("not_found", 404);
306 if (request.method === "GET" || request.method === "HEAD") {
307 if (path.snapshot) return refuse("not_found", 404);
308 return read(dir, db, request, path.room, address);
309 }
310 if (request.method !== "POST")
311 return new Response(null, { status: 405, headers: { allow: "GET, POST" } });
312 if (speaker === undefined) return refuse("signin_required", 403);
313 if (!sameOrigin(request)) return refuse("forbidden", 403);
314 const wait = spendWrite(dir, speaker.id);
315 if (wait > 0)
316 return new Response(JSON.stringify({ error: "slow_down" }), {
317 status: 429,
318 headers: { ...HEADERS, "content-type": "application/json", "retry-after": String(wait) },
319 });
320 const body = await readJson(request, path.snapshot ? SNAPSHOT_MAX + 1024 : CHANGE_MAX + 1024);
321 if (body instanceof Response) return body;
322 return path.snapshot
323 ? snapshot(db, path.room, body)
324 : write(dir, db, path.room, speaker, body);
325 }
326
327 function head(db: Database, room: string): number {
328 const row = db
329 .query<{ head: number }, [string]>("select head from heads where room = ?")
330 .get(room);
331 return row?.head ?? 0;
332 }
333
334 function write(
335 dir: string,
336 db: Database,
337 name: string,
338 speaker: Speaker,
339 body: Record<string, unknown>,
340 ): Response {
341 const client = body["client"];
342 if (typeof client !== "string" || !CLIENT.test(client))
343 return refuse("invalid_client", 400);
344
345 if ("presence" in body) {
346 const state = body["presence"];
347 if (state !== null && jsonSize(state) > PRESENCE_MAX)
348 return refuse("too_large", 413);
349 const room = liveRoom(dir, name, false);
350 if (room === undefined) return reply({ listeners: 0 });
351 if (state === null) room.peers.delete(client);
352 else {
353 if (!room.peers.has(client) && room.peers.size >= PEERS_MAX)
354 return refuse("room_full", 429);
355 room.peers.set(client, { who: speaker.name, state, at: Date.now() });
356 }
357 broadcast(room, frame("presence", listPeers(room)));
358 return reply({ listeners: room.listeners.size });
359 }
360
361 const seq = body["seq"];
362 if (!isInt(seq)) return refuse("invalid_seq", 400);
363 if (!("change" in body)) return refuse("invalid", 400);
364 const change = body["change"];
365 const text = JSON.stringify(change);
366 if (text === undefined || Buffer.byteLength(text) > CHANGE_MAX)
367 return refuse(text === undefined ? "invalid" : "too_large", text === undefined ? 400 : 413);
368
369 const append = db.transaction((): Response => {
370 const seen = db
371 .query<{ id: number }, [string, string, number]>(
372 "select id from log where room = ? and client = ? and seq = ?",
373 )
374 .get(name, client, seq);
375 if (seen !== undefined && seen !== null) return reply({ id: seen.id, duplicate: true });
376 const known = db
377 .query<{ n: number }, [string]>("select count(*) as n from log where room = ?")
378 .get(name)!.n;
379 if (known >= LOG_MAX) return refuse("compact", 409);
380 if (head(db, name) === 0) {
381 const count = db
382 .query<{ n: number }, []>("select count(*) as n from heads")
383 .get()!.n;
384 if (count >= ROOMS_MAX) return refuse("too_many_rooms", 429);
385 }
386 const id = head(db, name) + 1;
387 const at = Date.now();
388 db.query("insert into heads (room, head) values (?, ?) on conflict (room) do update set head = excluded.head").run(name, id);
389 db.query("insert into log (room, id, client, seq, who, at, change) values (?, ?, ?, ?, ?, ?, ?)").run(name, id, client, seq, speaker.name, at, text);
390 const room = liveRoom(dir, name, false);
391 if (room !== undefined)
392 broadcast(
393 room,
394 frame("change", { id, client, seq, who: speaker.name, at, change }, id),
395 );
396 return reply({ id, duplicate: false });
397 });
398 return append.immediate();
399 }
400
401 function snapshot(
402 db: Database,
403 room: string,
404 body: Record<string, unknown>,
405 ): Response {
406 const upTo = body["upTo"];
407 if (!isInt(upTo) || !("state" in body)) return refuse("invalid", 400);
408 const text = JSON.stringify(body["state"]);
409 if (text === undefined) return refuse("invalid", 400);
410 if (Buffer.byteLength(text) > SNAPSHOT_MAX) return refuse("too_large", 413);
411 const fold = db.transaction((): Response => {
412 if (upTo > head(db, room)) return refuse("ahead_of_log", 409);
413 const have = db
414 .query<{ up_to: number }, [string]>("select up_to from snapshots where room = ?")
415 .get(room);
416 if (have !== null && have !== undefined && upTo <= have.up_to)
417 return reply({ upTo: have.up_to, kept: false });
418 db.query("insert into snapshots (room, up_to, state, at) values (?, ?, ?, ?) on conflict (room) do update set up_to = excluded.up_to, state = excluded.state, at = excluded.at").run(room, upTo, text, Date.now());
419 db.query("delete from log where room = ? and id <= ?").run(room, upTo);
420 return reply({ upTo, kept: true });
421 });
422 return fold.immediate();
423 }
424
425 interface Row {
426 id: number;
427 client: string;
428 seq: number;
429 who: string;
430 at: number;
431 change: string;
432 }
433
434 function replay(db: Database, room: string, since: number) {
435 const snap = db
436 .query<{ up_to: number; state: string }, [string]>(
437 "select up_to, state from snapshots where room = ?",
438 )
439 .get(room);
440 const from = Math.max(since, snap?.up_to ?? 0);
441 const rows = db
442 .query<Row, [string, number]>(
443 "select id, client, seq, who, at, change from log where room = ? and id > ? order by id",
444 )
445 .all(room, from);
446 const state =
447 snap !== null && snap !== undefined && since < snap.up_to
448 ? { upTo: snap.up_to, state: JSON.parse(snap.state) as unknown }
449 : undefined;
450 return { state, rows, head: head(db, room) };
451 }
452
453 const shape = (r: Row) => ({
454 id: r.id,
455 client: r.client,
456 seq: r.seq,
457 who: r.who,
458 at: r.at,
459 change: JSON.parse(r.change) as unknown,
460 });
461
462 function read(
463 dir: string,
464 db: Database,
465 request: Request,
466 name: string,
467 address: string,
468 ): Response {
469 const url = new URL(request.url);
470 const raw = request.headers.get("last-event-id") ?? url.searchParams.get("since") ?? "0";
471 const since = /^\d{1,15}$/.test(raw) ? Number(raw) : -1;
472 if (since < 0) return refuse("invalid_since", 400);
473 const caught = replay(db, name, since);
474
475 const wantsStream = (request.headers.get("accept") ?? "").includes("text/event-stream");
476 if (!wantsStream)
477 return reply({
478 head: caught.head,
479 snapshot: caught.state ?? null,
480 changes: caught.rows.map(shape),
481 });
482
483 // A HEAD asks what a GET would say, not to be held open for it.
484 if (request.method === "HEAD")
485 return new Response(null, {
486 headers: { ...HEADERS, "content-type": "text/event-stream" },
487 });
488 if (!mayListen(dir, name, address)) return refuse("too_many_streams", 429);
489
490 const encoder = new TextEncoder();
491 let stop = (): void => {};
492 const stream = new ReadableStream<Uint8Array>({
493 start(controller) {
494 let closed = false;
495 const room = liveRoom(dir, name, true)!;
496 const listener: Listener = {
497 address,
498 send(text) {
499 if (closed) return false;
500 if ((controller.desiredSize ?? 0) < -BACKLOG_MAX) {
501 stop();
502 return false;
503 }
504 try {
505 controller.enqueue(encoder.encode(text));
506 return true;
507 } catch {
508 stop();
509 return false;
510 }
511 },
512 };
513 const beat = setInterval(() => listener.send(":\n\n"), HEARTBEAT_MS);
514 stop = () => {
515 if (closed) return;
516 closed = true;
517 clearInterval(beat);
518 leave(dir, name, room, listener);
519 try {
520 controller.close();
521 } catch {}
522 };
523 request.signal.addEventListener("abort", stop);
524 // One tick from replay to subscribe: nothing can be appended between.
525 listener.send("retry: 2000\n\n");
526 if (caught.state !== undefined)
527 listener.send(frame("snapshot", caught.state, caught.state.upTo));
528 for (const row of caught.rows) listener.send(frame("change", shape(row), row.id));
529 prune(room, Date.now());
530 room.listeners.add(listener);
531 listener.send(frame("hello", { head: caught.head, peers: listPeers(room) }));
532 },
533 cancel() {
534 stop();
535 },
536 });
537 return new Response(stream, {
538 headers: {
539 ...HEADERS,
540 "content-type": "text/event-stream",
541 "x-accel-buffering": "no",
542 },
543 });
544 }
src/http/server.ts +3 −1
@@ -1685,8 +1685,10 @@ export async function serve(app: App): Promise<Servers> {
16851685 // A preview's headers are the app's business: what `proxyApp`
16861686 // carries back leaves exactly as the app wrote it, which is why the
16871687 // floor below sits after this return and not around it.
1688 if (target !== undefined && target !== "unknown")
1688 if (target !== undefined && target !== "unknown") {
1689 notePeer(request, server.requestIP(request)?.address, trust);
16891690 return proxyApp(runtime, request, target, server);
1691 }
16901692 if (target === "unknown")
16911693 return securityFloor(new Response("not found", { status: 404 }));
16921694 }
test/apps-sync.test.ts added +197
@@ -0,0 +1,197 @@
1 /**
2 * `/sync/*` through the proxy's door (`proxySync`), without a socket: a
3 * public app's stream is readable by a stranger and writable only by a
4 * named person; a forged grant is no one; a private app's is as closed as
5 * its pages; the app's own signature (its terminal) names a person too; and
6 * writes and open streams are limited.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { createHmac } from "node:crypto";
10 import { mkdirSync } from "node:fs";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { newApp, updateAppSettings } from "../src/actions/apps.ts";
15 import { createApp, type App } from "../src/app.ts";
16 import { envDir } from "../src/apps/data.ts";
17 import {
18 grantCookieName,
19 identityKey,
20 proxySync,
21 signGrant,
22 type AppTarget,
23 } from "../src/apps/proxy.ts";
24 import type { AppsRuntime } from "../src/apps/runtime.ts";
25 import {
26 LISTENERS_PER_ADDRESS,
27 WRITE_BURST,
28 closeSyncLogs,
29 syncPath,
30 } from "../src/apps/sync.ts";
31 import { getAppBySlug } from "../src/core/apps.ts";
32 import type { Repo } from "../src/core/repos.ts";
33 import { createUser, type User } from "../src/core/users.ts";
34
35 describe("apps: sync through the proxy's door", () => {
36 let dataDir: string;
37 let app: App;
38 let alice: User;
39 let repo: Repo;
40 let runtime: AppsRuntime;
41 let target: AppTarget;
42 const HOST = "lobby.apps.test";
43 const ip = (address: string) => ({ requestIP: () => ({ address }) });
44
45 const call = async (
46 path: string,
47 init: RequestInit = {},
48 address = "10.0.0.1",
49 ): Promise<Response> => {
50 const url = new URL(path, `http://${HOST}`);
51 const request = new Request(url.href, {
52 ...init,
53 headers: { host: HOST, ...(init.headers as Record<string, string>) },
54 });
55 return proxySync(runtime, request, target, syncPath(url.pathname)!, ip(address));
56 };
57 const post = (path: string, body: unknown, headers: Record<string, string> = {}) =>
58 call(path, {
59 method: "POST",
60 headers: { "content-type": "application/json", ...headers },
61 body: JSON.stringify(body),
62 });
63 const aliceCookie = (): Record<string, string> => ({
64 cookie: `${grantCookieName(target)}=${signGrant(dataDir, target, 60_000, Date.now(), {
65 id: alice.id,
66 name: alice.username,
67 role: "admin",
68 })}`,
69 });
70 const signed = (): Record<string, string> => {
71 const identity = `${alice.id}|alice|admin|${Date.now() + 60_000}`;
72 return {
73 "x-forge-identity": identity,
74 "x-forge-signature": createHmac("sha256", identityKey(dataDir, target.app.id))
75 .update(identity)
76 .digest("base64url"),
77 };
78 };
79
80 beforeAll(async () => {
81 dataDir = await mkdtemp(join(tmpdir(), "forge-apps-sync-"));
82 app = createApp({ dataDir, port: 0 });
83 const created = await createUser(app.db, {
84 trusted: true,
85 username: "alice",
86 email: "[email protected]",
87 password: "a-good-passphrase",
88 adminIfFirst: true,
89 });
90 if (!created.ok) throw new Error(created.error);
91 alice = created.value;
92 const made = await newApp(app, alice, {
93 name: "lobby",
94 description: "A room",
95 visibility: "public",
96 });
97 if (!made.ok) throw new Error(made.error);
98 repo = made.value.repo;
99 target = { app: getAppBySlug(app.db, "lobby")!, env: "production" };
100 mkdirSync(envDir(dataDir, target.app.id, "production"), { recursive: true });
101 runtime = {
102 app,
103 options: { forgeUrl: "http://forge.test" },
104 envStatus: () => undefined,
105 } as unknown as AppsRuntime;
106 });
107
108 afterAll(async () => {
109 closeSyncLogs(envDir(dataDir, target.app.id, "production"));
110 app.close();
111 await rm(dataDir, { recursive: true, force: true });
112 });
113
114 test("a stranger reads a public room and cannot write to it", async () => {
115 expect((await post("/sync/r", { client: "c1", seq: 1, change: 1 })).status).toBe(403);
116 const read = await call("/sync/r");
117 expect(read.status).toBe(200);
118 expect(((await read.json()) as { head: number }).head).toBe(0);
119 expect(read.headers.get("x-content-type-options")).toBe("nosniff");
120 });
121
122 test("a signed-in person writes under their name; a forged cookie is no one", async () => {
123 const wrote = await post("/sync/r2", { client: "c1", seq: 1, change: { hi: 1 } }, aliceCookie());
124 expect(wrote.status).toBe(200);
125 const read = (await (await call("/sync/r2")).json()) as {
126 changes: { who: string; change: unknown }[];
127 };
128 expect(read.changes).toEqual([
129 expect.objectContaining({ who: "alice", change: { hi: 1 } }),
130 ]);
131 const forged = await post("/sync/r2", { client: "c1", seq: 2, change: 1 }, {
132 cookie: `${grantCookieName(target)}=a.b.c`,
133 });
134 expect(forged.status).toBe(403);
135 const tampered = aliceCookie().cookie!.replace(/\.[^.]*$/, ".AAAA");
136 expect((await post("/sync/r2", { client: "c1", seq: 2, change: 1 }, { cookie: tampered })).status).toBe(403);
137 });
138
139 test("the app's own signature names a person; a bad one names no one", async () => {
140 expect((await post("/sync/r4", { client: "t", seq: 1, change: 1 }, signed())).status).toBe(200);
141 const bad = { ...signed(), "x-forge-signature": "nope" };
142 expect((await post("/sync/r4", { client: "t", seq: 2, change: 1 }, bad)).status).toBe(403);
143 const identity = `${alice.id}|alice|admin|${Date.now() - 1}`;
144 const stale = {
145 "x-forge-identity": identity,
146 "x-forge-signature": createHmac("sha256", identityKey(dataDir, target.app.id))
147 .update(identity)
148 .digest("base64url"),
149 };
150 expect((await post("/sync/r4", { client: "t", seq: 2, change: 1 }, stale)).status).toBe(403);
151 });
152
153 test("a private room is as closed as the app", async () => {
154 expect(updateAppSettings(app, alice, repo, { access: "private" }).ok).toBe(true);
155 target = { ...target, app: getAppBySlug(app.db, "lobby")! };
156 try {
157 expect((await call("/sync/r2")).status).toBe(404);
158 expect((await post("/sync/r2", { client: "c", seq: 5, change: 1 })).status).toBe(404);
159 expect((await call("/sync/r2", { headers: aliceCookie() })).status).toBe(200);
160 const bad = { ...signed(), "x-forge-signature": "nope" };
161 expect((await call("/sync/r2", { headers: bad })).status).toBe(404);
162 expect((await call("/sync/r2", { headers: signed() })).status).toBe(200);
163 } finally {
164 updateAppSettings(app, alice, repo, { access: "public" });
165 target = { ...target, app: getAppBySlug(app.db, "lobby")! };
166 }
167 });
168
169 test("a person's writes are limited, and only theirs", async () => {
170 let refused: Response | undefined;
171 for (let i = 1; i <= WRITE_BURST + 5 && refused === undefined; i++) {
172 const r = await post("/sync/flood", { client: "f", seq: i, change: i }, aliceCookie());
173 if (r.status === 429) refused = r;
174 }
175 expect(refused?.status).toBe(429);
176 expect(Number(refused?.headers.get("retry-after"))).toBeGreaterThanOrEqual(1);
177 // A stranger still reads.
178 expect((await call("/sync/flood")).status).toBe(200);
179 });
180
181 test("an address holds a few streams, not unboundedly", async () => {
182 const stream = { headers: { accept: "text/event-stream" } };
183 const open: Response[] = [];
184 for (let i = 0; i < LISTENERS_PER_ADDRESS; i++) {
185 const r = await call(`/sync/s${i}`, stream, "10.9.9.9");
186 expect(r.status).toBe(200);
187 open.push(r);
188 }
189 expect((await call("/sync/s0", stream, "10.9.9.9")).status).toBe(429);
190 expect((await call("/sync/s0", stream, "10.9.9.8")).status).toBe(200);
191 // A HEAD never holds a stream.
192 const head = await call("/sync/s0", { method: "HEAD", headers: stream.headers }, "10.9.9.9");
193 expect(head.status).toBe(200);
194 expect(await head.text()).toBe("");
195 for (const r of open) await r.body?.cancel();
196 });
197 });
test/sync.test.ts added +322
@@ -0,0 +1,322 @@
1 /**
2 * The sync stream (`src/apps/sync.ts`): changes are numbered in arrival
3 * order, a retry appends nothing, a reader that reconnects with `since`
4 * hears exactly what it missed, only a named person writes, a snapshot
5 * folds the log away without losing what a late reader needs, and presence
6 * is listed, never logged, and forgotten.
7 */
8 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
9 import { mkdtempSync, rmSync } from "node:fs";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import {
13 CHANGE_MAX,
14 LOG_MAX,
15 closeSyncLogs,
16 serveSync,
17 syncPath,
18 type Speaker,
19 } from "../src/apps/sync.ts";
20
21 const HOST = "game.apps.test";
22 const ana: Speaker = { id: "u1", name: "ana" };
23 let dir: string;
24
25 beforeEach(() => {
26 dir = mkdtempSync(join(tmpdir(), "forge-sync-"));
27 });
28 afterEach(() => {
29 closeSyncLogs(dir);
30 rmSync(dir, { recursive: true, force: true });
31 });
32
33 const call = (
34 method: string,
35 path: string,
36 who: Speaker | undefined,
37 body?: unknown,
38 headers: Record<string, string> = {},
39 init: RequestInit = {},
40 ) => {
41 const parsed = syncPath(new URL(`http://${HOST}${path}`).pathname)!;
42 return serveSync(
43 dir,
44 new Request(`http://${HOST}${path}`, {
45 method,
46 headers: {
47 host: HOST,
48 ...(body === undefined ? {} : { "content-type": "application/json" }),
49 ...headers,
50 },
51 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
52 ...init,
53 }),
54 parsed,
55 who,
56 );
57 };
58 const push = (room: string, client: string, seq: number, change: unknown) =>
59 call("POST", `/sync/${room}`, ana, { client, seq, change });
60 const log = async (room: string, since = 0) =>
61 (await call("GET", `/sync/${room}?since=${since}`, undefined)).json() as Promise<{
62 head: number;
63 snapshot: { upTo: number; state: unknown } | null;
64 changes: { id: number; client: string; seq: number; who: string; change: unknown }[];
65 }>;
66
67 /** Read a stream's frames as they arrive. */
68 function listen(room: string, headers: Record<string, string> = {}, since = 0) {
69 const abort = new AbortController();
70 const pending = call(
71 "GET",
72 `/sync/${room}?since=${since}`,
73 undefined,
74 undefined,
75 { accept: "text/event-stream", ...headers },
76 { signal: abort.signal },
77 );
78 let reader: { read(): Promise<{ done: boolean; value?: Uint8Array }> } | undefined;
79 let buffer = "";
80 const frames: { event: string; id?: string; data: any }[] = [];
81 const next = async (event?: string) => {
82 reader ??= (await pending).body!.getReader() as unknown as typeof reader;
83 const r = reader!;
84 for (;;) {
85 const at = frames.findIndex((f) => event === undefined || f.event === event);
86 if (at >= 0) return frames.splice(at, 1)[0]!;
87 const { value, done } = await r.read();
88 if (done) throw new Error("stream ended");
89 buffer += new TextDecoder().decode(value!);
90 for (let cut; (cut = buffer.indexOf("\n\n")) >= 0; ) {
91 const raw = buffer.slice(0, cut);
92 buffer = buffer.slice(cut + 2);
93 const lines = raw.split("\n");
94 const field = (k: string) =>
95 lines.find((l) => l.startsWith(`${k}: `))?.slice(k.length + 2);
96 const data = field("data");
97 if (data !== undefined)
98 frames.push({
99 event: field("event") ?? "message",
100 ...(field("id") === undefined ? {} : { id: field("id")! }),
101 data: JSON.parse(data),
102 });
103 }
104 }
105 };
106 return { next, stop: () => abort.abort() };
107 }
108
109 describe("order", () => {
110 test("ids are dense per room, in arrival order, whoever sent them", async () => {
111 await push("a", "c1", 1, { n: 1 });
112 await push("a", "c2", 1, { n: 2 });
113 await push("b", "c1", 1, { n: 9 });
114 await push("a", "c1", 2, { n: 3 });
115 const a = await log("a");
116 expect(a.changes.map((c) => [c.id, c.client, c.change])).toEqual([
117 [1, "c1", { n: 1 }],
118 [2, "c2", { n: 2 }],
119 [3, "c1", { n: 3 }],
120 ]);
121 expect(a.changes[0]!.who).toBe("ana");
122 expect((await log("b")).head).toBe(1);
123 });
124
125 test("a retried (client, seq) appends nothing and answers the id it has", async () => {
126 const first = await (await push("a", "c1", 1, { n: 1 })).json();
127 const again = await (await push("a", "c1", 1, { n: 1 })).json();
128 expect(first).toEqual({ id: 1, duplicate: false });
129 expect(again).toEqual({ id: 1, duplicate: true });
130 expect((await log("a")).changes).toHaveLength(1);
131 });
132
133 test("a listener hears a change the moment it is appended, with its id", async () => {
134 const stream = listen("a");
135 expect((await stream.next("hello")).data.head).toBe(0);
136 await push("a", "c1", 1, { n: 1 });
137 const frame = await stream.next("change");
138 expect(frame.id).toBe("1");
139 expect(frame.data).toMatchObject({ id: 1, client: "c1", seq: 1, change: { n: 1 } });
140 stream.stop();
141 });
142 });
143
144 describe("reconnecting with since", () => {
145 test("replays exactly what was missed, then follows", async () => {
146 for (let i = 1; i <= 5; i++) await push("a", "c1", i, { i });
147 const stream = listen("a", {}, 3);
148 expect((await stream.next("change")).data.id).toBe(4);
149 expect((await stream.next("change")).data.id).toBe(5);
150 expect((await stream.next("hello")).data.head).toBe(5);
151 await push("a", "c1", 6, { i: 6 });
152 expect((await stream.next("change")).data.id).toBe(6);
153 stream.stop();
154 });
155
156 test("Last-Event-ID is since", async () => {
157 for (let i = 1; i <= 3; i++) await push("a", "c1", i, { i });
158 const stream = listen("a", { "last-event-id": "2" }, 0);
159 expect((await stream.next("change")).data.id).toBe(3);
160 stream.stop();
161 });
162
163 test("a bad since is refused", async () => {
164 expect((await call("GET", "/sync/a?since=-1", undefined)).status).toBe(400);
165 expect((await call("GET", "/sync/a?since=x", undefined)).status).toBe(400);
166 });
167 });
168
169 describe("who may do what", () => {
170 test("anyone the app admits reads; only a named person writes", async () => {
171 await push("a", "c1", 1, { n: 1 });
172 expect((await log("a")).changes).toHaveLength(1);
173 const body = { client: "c9", seq: 1, change: 1 };
174 expect((await call("POST", "/sync/a", undefined, body)).status).toBe(403);
175 expect(
176 (await call("POST", "/sync/a", undefined, { client: "c9", presence: {} })).status,
177 ).toBe(403);
178 expect(
179 (await call("POST", "/sync/a/snapshot", undefined, { upTo: 1, state: {} })).status,
180 ).toBe(403);
181 expect((await log("a")).changes).toHaveLength(1);
182 });
183
184 test("a write from another origin is refused, and so is a form post", async () => {
185 const body = { client: "c1", seq: 1, change: 1 };
186 const evil = await call("POST", "/sync/a", ana, body, { origin: "https://evil.test" });
187 expect(evil.status).toBe(403);
188 const cross = await call("POST", "/sync/a", ana, body, { "sec-fetch-site": "cross-site" });
189 expect(cross.status).toBe(403);
190 const same = await call("POST", "/sync/a", ana, body, { origin: `http://${HOST}` });
191 expect(same.status).toBe(200);
192 const form = await call("POST", "/sync/a", ana, body, { "content-type": "text/plain" });
193 expect(form.status).toBe(415);
194 });
195
196 test("input is checked at the door", async () => {
197 const bad = (body: unknown) => call("POST", "/sync/a", ana, body).then((r) => r.status);
198 expect(await bad({ client: "x y", seq: 1, change: 1 })).toBe(400);
199 expect(await bad({ client: "c", seq: 0, change: 1 })).toBe(400);
200 expect(await bad({ client: "c", seq: 1.5, change: 1 })).toBe(400);
201 expect(await bad({ client: "c", seq: 1 })).toBe(400);
202 expect(await bad({ client: "c", seq: 1, change: "x".repeat(CHANGE_MAX) })).toBe(413);
203 expect(await bad([1])).toBe(400);
204 expect(syncPath("/sync/Bad Room")).toBeUndefined();
205 expect(syncPath("/sync/../x")).toBeUndefined();
206 expect(syncPath("/syncing/a")).toBeUndefined();
207 expect((await call("DELETE", "/sync/a", ana)).status).toBe(405);
208 });
209
210 test("an environment with no directory has no rooms", async () => {
211 rmSync(dir, { recursive: true, force: true });
212 expect((await call("GET", "/sync/a", undefined)).status).toBe(404);
213 });
214 });
215
216 describe("compaction", () => {
217 test("a snapshot folds the log; a late reader starts from it and then the rest", async () => {
218 for (let i = 1; i <= 6; i++) await push("a", "c1", i, { i });
219 const folded = await call("POST", "/sync/a/snapshot", ana, { upTo: 4, state: { sum: 10 } });
220 expect(await folded.json()).toEqual({ upTo: 4, kept: true });
221 const late = await log("a");
222 expect(late.snapshot).toEqual({ upTo: 4, state: { sum: 10 } });
223 expect(late.changes.map((c) => c.id)).toEqual([5, 6]);
224 // Ids keep counting from the head, not from what is left.
225 expect(((await (await push("a", "c1", 7, {})).json()) as { id: number }).id).toBe(7);
226 // A reader already past the snapshot is not sent it.
227 const caught = await log("a", 5);
228 expect(caught.snapshot).toBeNull();
229 expect(caught.changes.map((c) => c.id)).toEqual([6, 7]);
230 // A stream says it the same way.
231 const stream = listen("a");
232 const snap = await stream.next("snapshot");
233 expect(snap.id).toBe("4");
234 expect(snap.data).toEqual({ upTo: 4, state: { sum: 10 } });
235 expect((await stream.next("change")).data.id).toBe(5);
236 stream.stop();
237 });
238
239 test("a snapshot never goes backwards or past the log", async () => {
240 for (let i = 1; i <= 3; i++) await push("a", "c1", i, { i });
241 await call("POST", "/sync/a/snapshot", ana, { upTo: 3, state: "s3" });
242 const older = await call("POST", "/sync/a/snapshot", ana, { upTo: 2, state: "s2" });
243 expect(await older.json()).toEqual({ upTo: 3, kept: false });
244 expect((await log("a")).snapshot?.state).toBe("s3");
245 const ahead = await call("POST", "/sync/a/snapshot", ana, { upTo: 9, state: "s9" });
246 expect(ahead.status).toBe(409);
247 });
248
249 test("a room at the cap asks for a snapshot, and takes changes once it has one", async () => {
250 // Fill the log directly through the door; the cap is the server's.
251 // Many writers: one person's rate is limited, the log's cap is the point.
252 for (let i = 1; i <= LOG_MAX; i++)
253 await call("POST", "/sync/a", { id: `w${i % 250}`, name: "w" }, { client: "c1", seq: i, change: i });
254 const full = await push("a", "c1", LOG_MAX + 1, 0);
255 expect(full.status).toBe(409);
256 expect(((await full.json()) as { error: string }).error).toBe("compact");
257 await call("POST", "/sync/a/snapshot", ana, { upTo: LOG_MAX, state: "folded" });
258 const after = await push("a", "c1", LOG_MAX + 1, 0);
259 expect(((await after.json()) as { id: number }).id).toBe(LOG_MAX + 1);
260 }, 60_000);
261
262 test("the log survives the process: a reopened store has everything", async () => {
263 await push("a", "c1", 1, { n: 1 });
264 closeSyncLogs(dir);
265 expect((await log("a")).changes).toHaveLength(1);
266 });
267 });
268
269 describe("presence", () => {
270 test("is listed to everyone in the room, never logged, and dropped on leave", async () => {
271 const watcher = listen("a");
272 await watcher.next("hello");
273 await call("POST", "/sync/a", ana, { client: "c1", presence: { x: 1 } });
274 const seen = await watcher.next("presence");
275 expect(seen.data).toEqual([{ client: "c1", who: "ana", state: { x: 1 } }]);
276 expect((await log("a")).head).toBe(0);
277 // Someone arriving later is told who is here.
278 const late = listen("a");
279 expect((await late.next("hello")).data.peers).toHaveLength(1);
280 await call("POST", "/sync/a", ana, { client: "c1", presence: null });
281 expect((await watcher.next("presence")).data).toEqual([]);
282 watcher.stop();
283 late.stop();
284 });
285
286 test("a heartbeat that stops is forgotten", async () => {
287 const realNow = Date.now;
288 const watcher = listen("a");
289 await watcher.next("hello");
290 await call("POST", "/sync/a", ana, { client: "c1", presence: { x: 1 } });
291 await watcher.next("presence");
292 Date.now = () => realNow() + 60_000;
293 try {
294 const late = listen("a");
295 expect((await late.next("hello")).data.peers).toEqual([]);
296 late.stop();
297 } finally {
298 Date.now = realNow;
299 }
300 watcher.stop();
301 });
302
303 test("nobody listening means nothing kept", async () => {
304 const res = await call("POST", "/sync/a", ana, { client: "c1", presence: { x: 1 } });
305 expect(await res.json()).toEqual({ listeners: 0 });
306 const late = listen("a");
307 expect((await late.next("hello")).data.peers).toEqual([]);
308 late.stop();
309 });
310 });
311
312 describe("the client the template ships", () => {
313 test("static/sync.js is in every new app, and is valid JavaScript", async () => {
314 const { scaffoldFiles } = await import("../src/apps/scaffold.ts");
315 const file = scaffoldFiles({ name: "room", description: "" }).find(
316 (f) => f.path === "static/sync.js",
317 );
318 expect(file?.content).toContain("export function join(");
319 expect(() => new Bun.Transpiler({ loader: "js" }).transformSync(String(file?.content))).not.toThrow();
320 expect(file!.content).not.toMatch(/\beval\b|innerHTML/);
321 });
322 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs