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

Build tempo #7

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/tempo:scout/1-build-tempo → main 3 commits fork 4 threads · 4 unresolved

  • Merged. scout/1-build-tempo was merged into main as d7370c2.

Review

Sign in to review this change.
14 files changed +809 −63
README.md +54 −17
@@ -1,8 +1,11 @@
11 # tempo
22
33 A snappy kanban board. Open `/`, create a board, and share its URL —
4 anyone with the link can see and change it, the same way a shared
5 document works. Each board keeps its own columns and cards, server-side.
4 anyone with the link can see and change it as a guest, the same way a
5 shared document works. Sign in through the forge and a board you create
6 or claim stays in your list at `/`, so you don't have to keep the link
7 yourself. Two people (and an agent, over MCP) on the same board see each
8 other's moves within a second, no reload.
69
710 ```sh
811 PORT=8080 FORGE_APP_DATA=./data bun run src/server.ts # run it here
@@ -13,7 +16,13 @@ FORGE_APP_DATA=./data bun run src/tty.ts # the terminal interface
1316 ## Using it
1417
1518 - **Create a board** from `/`, then share `/b/<id>` — that id is the
16 whole address; there are no accounts or private boards.
19 address anyone with the link uses; it is still the only thing that
20 controls access (see "What's simulated").
21 - **Sign in** (top right, a link to the forge — tempo has no sign-in
22 form of its own) and a board you create is yours from the start; an
23 existing guest board gets a "Keep this board" button that adds it to
24 your list the first time anyone signed in presses it. It never
25 changes hands after that.
1726 - **Cards**: type a title and press Enter to save it; drag a card to
1827 reorder or move it between columns, or focus it (click, or Tab) and
1928 press the arrow keys — the keyboard does everything dragging does.
@@ -27,25 +36,50 @@ FORGE_APP_DATA=./data bun run src/tty.ts # the terminal interface
2736 - **Undo**: reverses the last change to the board — a create, edit,
2837 move, or delete of a card or column. It is a shared, board-wide undo
2938 (there's no per-person history), which fits a board anyone can edit.
39 - **Live**: `static/board.js` opens `/b/<id>/events` (server-sent
40 events); when someone else changes the board, your page quietly
41 refetches and swaps in the fresh columns — no reload, and a change
42 you just made yourself isn't re-applied a second time.
43 - **Agents**: `POST /mcp` speaks MCP over plain JSON-RPC 2.0
44 (`initialize`, `tools/list`, `tools/call`) with four tools —
45 `list_boards`, `list_cards`, `add_card`, `move_card` — under the same
46 forge identity as the page. `list_boards` only ever returns boards
47 the caller has kept; the other three take a board id you already
48 have, exactly like the page does.
3049 - **Concurrent drags**: two people dragging cards at once never tear
3150 each other's write — every move runs in one transaction — and cards
3251 are ordered by position, then id, so even a rare tie still sorts the
3352 same way for everyone.
3453
3554 The first paint is plain server-rendered HTML; `static/board.js` (named
36 by its content hash, cached for a year) then adds drag-and-drop and
37 optimistic updates — every action updates the page immediately and
38 reconciles with the server in the background, reverting if it fails.
55 by its content hash, cached for a year) then adds drag-and-drop,
56 keyboard reordering, live updates and optimistic updates — every action
57 updates the page immediately and reconciles with the server in the
58 background, reverting if it fails.
3959
4060 ## What's simulated
4161
42 - No accounts, no per-user permissions: a board's id is its access
43 control, like a shared link. Undo is board-wide, not per-visitor.
44 - The terminal (`src/tty.ts`) mirrors the same actions with a
62 - A board's id is still its access control, exactly as before: signing
63 in adds *attribution and a list you can find it in later*, not
64 privacy. Anyone with the link can still see and edit any board,
65 signed in or not — tempo never asks a visitor to sign in just to use
66 a board they were given the link to.
67 - Because of that, `list_boards` over MCP is deliberately narrow: it
68 answers only with boards the caller has kept, never every board on
69 the server, so it can't be used to go discover a board by guessing.
70 - Undo is board-wide, not per-visitor, and unaffected by who's signed
71 in.
72 - The terminal (`src/tty.ts`) mirrors the board actions with a
4573 letter-key scheme (`j/k/h/l` move, `H/J/K/L` move the focused card,
4674 `a`/`e`/`d` add/edit/delete, `c`/`r`/`D` add/rename/delete a column,
4775 `f` filter, `u` undo) rather than drag-and-drop, since a terminal has
48 no mouse.
76 no mouse. It does not carry an identity or offer "keep this board" —
77 a real pty session doesn't get the forge's signed headers the way an
78 HTTP request does, and the tty already has the run of any board's id
79 it's given, same as the page.
80 - The event stream is this one process's: the terminal is a separate
81 process on the same database, so a change made there shows up on the
82 next page load, not live.
4983
5084 It also has a terminal: the exact command is in `FORGE_APP_SSH` when the app
5185 runs (`ssh -p 2222 <name>@<forge>` — the app is the login name, the forge is
@@ -53,14 +87,17 @@ the host; `<name>--<pull>@<forge>` for a preview's). It opens `src/tty.ts` on
5387 a real pty over the same data.
5488
5589 The forge sets `PORT`, `FORGE_APP_DATA`, `FORGE_APP_ENV`
56 (`production` or `preview`), `FORGE_APP_URL` and `FORGE_APP_COMMIT`
57 when it starts the app. `forge.json` says how.
90 (`production` or `preview`), `FORGE_APP_URL`, `FORGE_APP_COMMIT` and
91 `FORGE_APP_IDENTITY_KEY` when it starts the app. `forge.json` says how.
92 Identity comes only from `x-forge-identity` / `x-forge-signature`,
93 verified against `FORGE_APP_IDENTITY_KEY` (`src/who.ts`); unset, everyone
94 is anonymous.
5895
5996 ## Dependencies
6097
6198 The app itself has none. `happy-dom` is a dev-only dependency, used by
62 `src/drag.test.ts` to give `static/board.js` a real DOM outside a browser
63 so its dragstart/dragover/drop/dragend handlers run against real events —
64 hand-rolling that much of the DOM to test a few dozen lines of drag
65 handling would be more code, and less trustworthy, than the thing it's
66 testing.
99 `src/drag.test.ts` (and `src/theme.test.ts`) to give `static/board.js` a
100 real DOM outside a browser so its dragstart/dragover/drop/dragend
101 handlers run against real events — hand-rolling that much of the DOM to
102 test a few dozen lines of drag handling would be more code, and less
103 trustworthy, than the thing it's testing.
src/db.ts +47 −5
@@ -21,6 +21,8 @@ db.exec(`
2121 CREATE TABLE IF NOT EXISTS board (
2222 id TEXT PRIMARY KEY,
2323 name TEXT NOT NULL,
24 owner_id TEXT,
25 owner_name TEXT,
2426 created_at TEXT NOT NULL DEFAULT (datetime('now'))
2527 );
2628 CREATE TABLE IF NOT EXISTS board_column (
@@ -49,7 +51,19 @@ db.exec(`
4951 CREATE INDEX IF NOT EXISTS action_board_idx ON action(board_id);
5052 `);
5153
52 export type Board = { id: string; name: string; created_at: string };
54 // A board created before ownership existed has no owner_id/owner_name
55 // column yet; add them once, in place. CREATE TABLE IF NOT EXISTS above
56 // does nothing for a table that already exists without these columns.
57 const boardColumns = new Set(
58 db
59 .query<{ name: string }, []>("PRAGMA table_info(board)")
60 .all()
61 .map((c) => c.name),
62 );
63 if (!boardColumns.has("owner_id")) db.exec("ALTER TABLE board ADD COLUMN owner_id TEXT");
64 if (!boardColumns.has("owner_name")) db.exec("ALTER TABLE board ADD COLUMN owner_name TEXT");
65
66 export type Board = { id: string; name: string; owner_id: string | null; owner_name: string | null; created_at: string };
5367 export type Column = { id: string; board_id: string; name: string; position: number };
5468 export type Card = {
5569 id: string;
@@ -81,20 +95,48 @@ function logAction(boardId: string, payload: Payload): void {
8195 db.query("INSERT INTO action (board_id, payload) VALUES (?1, ?2)").run(boardId, JSON.stringify(payload));
8296 }
8397
84 export function createBoard(name: string): Board {
98 const BOARD_FIELDS = "id, name, owner_id, owner_name, created_at";
99
100 export function createBoard(name: string, owner?: { id: string; name: string }): Board {
85101 const id = randomId(8);
86 db.query("INSERT INTO board (id, name) VALUES (?1, ?2)").run(id, name);
102 db.query(`INSERT INTO board (id, name, owner_id, owner_name) VALUES (?1, ?2, ?3, ?4)`).run(
103 id,
104 name,
105 owner?.id ?? null,
106 owner?.name ?? null,
107 );
87108 const defaults = ["To do", "Doing", "Done"];
88109 defaults.forEach((columnName, i) => createColumn(id, columnName, i));
89110 return getBoard(id)!;
90111 }
91112
92113 export function listBoards(): Board[] {
93 return db.query<Board, []>("SELECT id, name, created_at FROM board ORDER BY created_at DESC").all();
114 return db.query<Board, []>(`SELECT ${BOARD_FIELDS} FROM board ORDER BY created_at DESC`).all();
115 }
116
117 /** The boards a signed-in person has kept — see `claimBoard`. */
118 export function listBoardsByOwner(ownerId: string): Board[] {
119 return db.query<Board, [string]>(`SELECT ${BOARD_FIELDS} FROM board WHERE owner_id = ?1 ORDER BY created_at DESC`).all(ownerId);
94120 }
95121
96122 export function getBoard(id: string): Board | null {
97 return db.query<Board, [string]>("SELECT id, name, created_at FROM board WHERE id = ?1").get(id);
123 return db.query<Board, [string]>(`SELECT ${BOARD_FIELDS} FROM board WHERE id = ?1`).get(id);
124 }
125
126 export type ClaimResult = "claimed" | "already_yours" | "owned_by_other" | "not_found";
127
128 /**
129 * A guest's board belongs to no one until someone signed in keeps it — the
130 * first person to claim an unowned board becomes its owner, so it shows up
131 * in their list from then on. It never changes hands after that.
132 */
133 export function claimBoard(boardId: string, owner: { id: string; name: string }): ClaimResult {
134 const board = getBoard(boardId);
135 if (!board) return "not_found";
136 if (board.owner_id === owner.id) return "already_yours";
137 if (board.owner_id !== null) return "owned_by_other";
138 db.query("UPDATE board SET owner_id = ?2, owner_name = ?3 WHERE id = ?1").run(boardId, owner.id, owner.name);
139 return "claimed";
98140 }
99141
100142 export function renameBoard(boardId: string, name: string): void {
src/drag.test.ts +1
@@ -17,6 +17,7 @@ import { join } from "node:path";
1717
1818 process.env.FORGE_APP_DATA = mkdtempSync(join(tmpdir(), "app-"));
1919 process.env.PORT = "0";
20 process.env.FORGE_APP_IDENTITY_KEY = "test-key";
2021 const { server } = await import("./server.ts");
2122 const base = `http://${server.hostname}:${server.port}`;
2223
src/live-refresh.test.ts added +126
@@ -0,0 +1,126 @@
1 /**
2 * Drives static/board.js's live-refresh path the way a browser would: a
3 * fake EventSource delivers another tab's write, and the guard that
4 * decides whether to redraw `.board` right away is checked against the
5 * two things that must survive it — an input mid-word, and keyboard focus
6 * on a card.
7 *
8 * happy-dom has no EventSource or DOMParser of its own recent enough for
9 * this; both are supplied on globalThis for the duration of the test,
10 * since board.js reads them as bare globals (see drag.test.ts for why
11 * fetch is wrapped instead of replaced the same way).
12 */
13 import { afterEach, beforeEach, expect, test } from "bun:test";
14 import { Window } from "happy-dom";
15 import { mkdtempSync } from "node:fs";
16 import { tmpdir } from "node:os";
17 import { join } from "node:path";
18
19 process.env.FORGE_APP_DATA = mkdtempSync(join(tmpdir(), "app-"));
20 process.env.PORT = "0";
21 process.env.FORGE_APP_IDENTITY_KEY = "test-key";
22 const { server } = await import("./server.ts");
23 const base = `http://${server.hostname}:${server.port}`;
24
25 const post = (path: string, body: Record<string, string> = {}) =>
26 fetch(base + path, { method: "POST", body: new URLSearchParams(body) });
27
28 let restoreEventSource: (() => void) | undefined;
29 let restoreDOMParser: (() => void) | undefined;
30 beforeEach(() => {
31 const previousES = (globalThis as Record<string, unknown>).EventSource;
32 restoreEventSource = () => {
33 (globalThis as Record<string, unknown>).EventSource = previousES;
34 };
35 const previousDP = (globalThis as Record<string, unknown>).DOMParser;
36 restoreDOMParser = () => {
37 (globalThis as Record<string, unknown>).DOMParser = previousDP;
38 };
39 });
40 afterEach(() => {
41 restoreEventSource?.();
42 restoreDOMParser?.();
43 });
44
45 class FakeEventSource {
46 onmessage: ((message: { data: string }) => void) | null = null;
47 constructor(_url: string) {
48 latestSource = this;
49 }
50 }
51 let latestSource: FakeEventSource | undefined;
52
53 async function run(boardId: string): Promise<{ window: Window; document: Document }> {
54 const html = await (await fetch(`${base}/b/${boardId}`)).text();
55 const [, scriptSrc] = html.match(/<script src="(\/static\/board[^"]+)"/)!;
56 const script = await (await fetch(base + scriptSrc)).text();
57
58 const window = new Window({ url: `${base}/b/${boardId}` });
59 const document = window.document;
60 document.open();
61 document.write(html);
62 document.close();
63
64 (globalThis as Record<string, unknown>).EventSource = FakeEventSource;
65 (globalThis as Record<string, unknown>).DOMParser = window.DOMParser;
66
67 new Function("document", "fetch", "location", "history", "CSS", script)(
68 document,
69 (path: string, init: RequestInit) => fetch(new URL(path, base), init),
70 window.location,
71 window.history,
72 window.CSS,
73 );
74 return { window, document };
75 }
76
77 test("a live refresh does not wipe an in-progress add-card title", async () => {
78 const created = await post("/boards", { name: "Live refresh test" });
79 const boardId = new URL(created.url).pathname.split("/")[2];
80 const { window, document } = await run(boardId);
81
82 const addInput = document.querySelector(".add-card input") as unknown as HTMLInputElement;
83 addInput.focus();
84 addInput.value = "half-typed";
85
86 // Someone else moves a card while this tab is mid-type.
87 await post(`/b/${boardId}/columns/${document.querySelector("[data-column-id]")!.getAttribute("data-column-id")}/cards`, {
88 title: "From elsewhere",
89 });
90 const hasNewCard = () => document.querySelector('.card[data-title="From elsewhere"]') !== null;
91
92 latestSource!.onmessage!({ data: JSON.stringify({ by: "someone-else" }) });
93 await new Promise((resolve) => setTimeout(resolve, 20));
94
95 expect((document.querySelector(".add-card input") as unknown as HTMLInputElement).value).toBe("half-typed");
96 expect(hasNewCard()).toBe(false);
97
98 // Leaving the input lets the deferred refresh through.
99 addInput.blur();
100 await new Promise((resolve) => setTimeout(resolve, 20));
101 expect(hasNewCard()).toBe(true);
102
103 await window.close();
104 });
105
106 test("a live refresh restores focus to a keyboard-focused card instead of deferring", async () => {
107 const created = await post("/boards", { name: "Live refresh focus test" });
108 const boardId = new URL(created.url).pathname.split("/")[2];
109 const columnId = (await (await fetch(`${base}/b/${boardId}`)).text()).match(/data-column-id="([a-z0-9]{12})"/)![1];
110 await post(`/b/${boardId}/columns/${columnId}/cards`, { title: "Keep focused" });
111 const { window, document } = await run(boardId);
112
113 const card = document.querySelector(".card") as unknown as HTMLElement & { dataset: DOMStringMap };
114 card.focus();
115 const cardId = card.dataset.cardId;
116
117 await post(`/b/${boardId}/columns/${columnId}/cards`, { title: "From elsewhere" });
118 latestSource!.onmessage!({ data: JSON.stringify({ by: "someone-else" }) });
119 await new Promise((resolve) => setTimeout(resolve, 20));
120
121 expect(document.querySelector('.card[data-title="From elsewhere"]')).not.toBeNull();
122 const refocused = document.querySelector(`[data-card-id="${cardId}"]`);
123 expect(refocused).toBe(document.activeElement as unknown as Element);
124
125 await window.close();
126 });
src/live.ts added +73
@@ -0,0 +1,73 @@
1 /**
2 * Realtime without a framework. A mutation calls `touch(boardId, by)`;
3 * `GET /b/:id/events` streams that to every open page on the same board as
4 * server-sent events, numbered, with the last hundred kept so a client that
5 * reconnects (the browser sends `Last-Event-ID` automatically) hears what
6 * it missed. `by` is the client that made the change, so its own page can
7 * skip re-fetching what it already applied optimistically.
8 */
9
10 export interface LiveEvent {
11 readonly id: number;
12 readonly boardId: string;
13 readonly by: string | null;
14 }
15
16 const KEEP = 100;
17 const HEARTBEAT_MS = 25_000;
18 const kept: LiveEvent[] = [];
19 const listeners = new Set<(event: LiveEvent) => void>();
20 let last = 0;
21
22 export function touch(boardId: string, by: string | null): LiveEvent {

x

23 const event: LiveEvent = { id: ++last, boardId, by };
24 kept.push(event);
25 if (kept.length > KEEP) kept.shift();
26 for (const listen of listeners) listen(event);
27 return event;
28 }
29
30 export function subscribe(listen: (event: LiveEvent) => void): () => void {
31 listeners.add(listen);
32 return () => listeners.delete(listen);
33 }
34
35 /** `GET /b/:id/events`: a stream scoped to one board, replaying what `since` missed. */
36 export function events(boardId: string, request: Request): Response {
37 const since = Number(request.headers.get("last-event-id") ?? new URL(request.url).searchParams.get("since") ?? 0);
38 const encoder = new TextEncoder();
39 let stop = (): void => {};
40 const stream = new ReadableStream<Uint8Array>({
41 start(controller) {
42 const write = (text: string): void => {
43 try {
44 controller.enqueue(encoder.encode(text));
45 } catch {
46 stop();
47 }
48 };
49 const send = (event: LiveEvent): void => {
50 if (event.boardId !== boardId) return;
51 write(`id: ${event.id}\ndata: ${JSON.stringify({ by: event.by })}\n\n`);
52 };
53 const heartbeat = setInterval(() => write(":\n\n"), HEARTBEAT_MS);
54 const unsubscribe = subscribe(send);
55 stop = () => {
56 clearInterval(heartbeat);
57 unsubscribe();
58 try {
59 controller.close();
60 } catch {}
61 };
62 request.signal.addEventListener("abort", stop);
63 write("retry: 2000\n\n");
64 for (const event of kept) if (event.id > since) send(event);
65 },
66 cancel() {
67 stop();
68 },
69 });
70 return new Response(stream, {
71 headers: { "content-type": "text/event-stream", "cache-control": "no-store", "x-accel-buffering": "no" },
72 });
73 }
src/mcp.ts added +134
@@ -0,0 +1,134 @@
1 /**
2 * An MCP server over plain HTTP: `POST /mcp` takes one JSON-RPC 2.0 message
3 * and answers with JSON (streamable HTTP without the stream — nothing here
4 * needs to push). Tools run with the caller's forge identity, same as the
5 * page: `list_boards` only ever shows boards the caller has kept (claimed
6 * by signing in — see db.ts), so an anonymous or unrelated caller cannot
7 * use it to discover a board it wasn't given the link to. The other tools
8 * take a board id directly, exactly like the page and the JSON forms do.
9 */
10
11 import * as db from "./db.ts";
12 import { touch } from "./live.ts";
13 import type { Who } from "./who.ts";
14
15 const BOARD_ID = /^[a-z0-9]{8}$/;
16 const ENTITY_ID = /^[a-z0-9]{12}$/;
17
18 type Result<T> = { ok: true; value: T } | { ok: false; error: string; message: string };
19 const ok = <T>(value: T): Result<T> => ({ ok: true, value });
20 const fail = <T>(error: string, message: string): Result<T> => ({ ok: false, error, message });
21
22 interface Tool {
23 readonly name: string;
24 readonly description: string;
25 readonly inputSchema: Record<string, unknown>;
26 readonly run: (who: Who, args: Record<string, unknown>) => Result<unknown>;
27 }
28
29 const boardOf = (args: Record<string, unknown>): db.Board | undefined => {
30 const id = String(args.board_id ?? "");
31 return BOARD_ID.test(id) ? (db.getBoard(id) ?? undefined) : undefined;
32 };
33
34 export const tools: readonly Tool[] = [
35 {
36 name: "list_boards",
37 description: "The boards you have kept by signing in. An anonymous caller sees none.",
38 inputSchema: { type: "object", properties: {} },
39 run: (who) => ok(who.role === "anon" ? [] : db.listBoardsByOwner(who.id)),
40 },
41 {
42 name: "list_cards",
43 description: "Every card on a board, each with the column it's in.",
44 inputSchema: { type: "object", properties: { board_id: { type: "string" } }, required: ["board_id"] },
45 run: (_who, args) => {
46 const board = boardOf(args);
47 if (!board) return fail("not_found", "no such board");
48 return ok(db.listCards(board.id));
49 },
50 },
51 {
52 name: "add_card",
53 description: "Add a card to a column on a board.",
54 inputSchema: {
55 type: "object",
56 properties: { board_id: { type: "string" }, column_id: { type: "string" }, title: { type: "string", maxLength: 200 } },
57 required: ["board_id", "column_id", "title"],
58 },
59 run: (_who, args) => {
60 const board = boardOf(args);
61 if (!board) return fail("not_found", "no such board");
62 const columnId = String(args.column_id ?? "");
63 if (!ENTITY_ID.test(columnId)) return fail("invalid", "column_id looks wrong");
64 const title = String(args.title ?? "").trim().slice(0, 200);
65 if (title === "") return fail("invalid", "a card needs a title");
66 const card = db.createCard(board.id, columnId, title);
67 if (!card) return fail("not_found", "no such column");
68 touch(board.id, null);
69 return ok(card);
70 },
71 },
72 {
73 name: "move_card",
74 description: "Move a card into a column, at a 0-based position among that column's cards.",
75 inputSchema: {
76 type: "object",
77 properties: {
78 board_id: { type: "string" },
79 card_id: { type: "string" },
80 column_id: { type: "string" },
81 index: { type: "integer", minimum: 0 },
82 },
83 required: ["board_id", "card_id", "column_id"],
84 },
85 run: (_who, args) => {
86 const board = boardOf(args);
87 if (!board) return fail("not_found", "no such board");
88 const cardId = String(args.card_id ?? "");
89 const columnId = String(args.column_id ?? "");
90 if (!ENTITY_ID.test(cardId) || !ENTITY_ID.test(columnId)) return fail("invalid", "card_id or column_id looks wrong");
91 const index = Number(args.index ?? 0);
92 if (!Number.isFinite(index) || index < 0) return fail("invalid", "index must be a non-negative number");
93 const moved = db.moveCard(board.id, cardId, columnId, Math.floor(index));
94 if (!moved) return fail("not_found", "no such card or column");
95 touch(board.id, null);
96 return ok({ id: cardId });
97 },
98 },
99 ];
100
101 /** A JSON object's fields, whatever the wire carried. */
102 const fields = (value: unknown): Record<string, unknown> =>
103 typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
104
105 /** One JSON-RPC message in, an HTTP status and a body out (a notification gets 202 and no body). */
106 export function rpc(who: Who, message: unknown): { status: number; body?: unknown } {
107 const m = fields(message);
108 const id = (m.id as unknown) ?? null;
109 const reply = (result: unknown) => ({ status: 200, body: { jsonrpc: "2.0", id, result } });
110 const refuse = (code: number, text: string) => ({ status: 200, body: { jsonrpc: "2.0", id, error: { code, message: text } } });
111 if (m.jsonrpc !== "2.0" || typeof m.method !== "string") return refuse(-32600, "not a JSON-RPC 2.0 request");
112 if (m.id === undefined) return { status: 202 };
113 const params = fields(m.params);
114 switch (m.method) {
115 case "initialize":
116 return reply({ protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "tempo", version: "1" } });
117 case "ping":
118 return reply({});
119 case "tools/list":
120 return reply({ tools: tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) });
121 case "tools/call": {
122 const tool = tools.find((t) => t.name === params.name);
123 if (tool === undefined) return refuse(-32602, `no tool named ${String(params.name)}`);
124 const result = tool.run(who, fields(params.arguments));
125 return reply(
126 result.ok
127 ? { content: [{ type: "text", text: JSON.stringify(result.value) }] }
128 : { content: [{ type: "text", text: `${result.error}: ${result.message}` }], isError: true },
129 );
130 }
131 default:
132 return refuse(-32601, `no method ${m.method}`);
133 }
134 }
src/pages/board.ts +40 −10
@@ -7,6 +7,7 @@
77 */
88
99 import type { Board, Card, Column } from "../db.ts";
10 import type { Who } from "../who.ts";
1011
1112 export const escape = (s: string): string =>
1213 s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c] ?? c);
@@ -23,17 +24,23 @@ const styles = `
2324 * { box-sizing: border-box; }
2425 body { margin: 0; padding: 1rem 1.5rem 3rem; }
2526 a { color: inherit; }
26 header.top { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; margin-bottom: .75rem; }
27 header.top { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; margin-bottom: .75rem; padding-right: 5.5rem; }
2728 header.top h1 { font-size: 1.1rem; margin: 0; }
2829 .env { display: inline-block; padding: .1rem .5rem; border-radius: 999px; font-size: .7rem;
2930 background: var(--accent); color: var(--accent-fg); }
31 .door { margin-left: auto; display: flex; align-items: center; gap: .5rem; font-size: .85rem; }

High — the new Sign in / Sign out control is partly unclickable on desktop. .door is margin-left:auto inside header.top, which lands it in exactly the corner .tools occupies (position:fixed; top:.75rem; right:.75rem; z-index:10, a few lines below). In the desktop screenshot the forge took at this head, the theme toggle and the ? button sit on top of the "Sign out" box: a click on the right half of that button opens the shortcuts dialog instead of signing out. It is on both / and /b/<id>, and it is the first thing on the first page.

Fix: reserve the corner for the fixed cluster — header.top { padding-right: 5.5rem; } — or render the door link inside the .tools div so the two lay out together. Then check at 1280px wide that the door's box no longer intersects the two fixed buttons. The phone layout already wraps below the buttons and is fine.

32 .who { opacity: .8; }
33 a.ghost { text-decoration: none; display: inline-block; }
34 .keep { font-size: .8rem; opacity: .85; display: flex; align-items: center; gap: .4rem; }
35 .boards { list-style: none; margin: 1rem 0 0; padding: 0; display: flex; flex-direction: column; gap: .4rem; }
36 .boards a { display: block; padding: .4rem .6rem; border: 1px solid #8884; border-radius: .4rem; }
3037 .hint { font-size: .8rem; opacity: .7; margin: 0 0 1rem; }
3138 .toolbar { display: flex; gap: .5rem; flex-wrap: wrap; margin-bottom: 1rem; align-items: center; }
3239 .toolbar form { display: flex; gap: .35rem; }
3340 input, select, button { font: inherit; }
3441 input, select { padding: .35rem .5rem; border: 1px solid #8884; border-radius: .4rem; background: transparent; color: inherit; }
3542 button { padding: .35rem .7rem; border: 0; border-radius: .4rem; background: var(--btn-bg); color: var(--btn-fg); cursor: pointer; }
36 button.ghost { background: transparent; color: inherit; border: 1px solid #8884; }
43 button.ghost, a.ghost { background: transparent; color: inherit; border: 1px solid #8884; padding: .35rem .7rem; border-radius: .4rem; }
3744 .tools { position: fixed; top: .75rem; right: .75rem; display: flex; gap: .4rem; z-index: 10; }
3845 .tools button { padding: .3rem .55rem; font-size: 1rem; line-height: 1; }
3946 .board { display: flex; gap: 1rem; align-items: flex-start; overflow-x: auto; padding-bottom: 1rem; }
@@ -103,21 +110,43 @@ ${shortcutsDialog(shortcuts)}
103110 <script src="/static/${THEME_JS}" defer></script>
104111 `;
105112
106 export function landingPage(env: string): string {
113 // Sign in is a link to the forge's own page, never a form of our own; who
114 // is asking comes back on every later request as a signed header (who.ts).
115 function doorLink(who: Who, path: string): string {
116 if (who.role === "anon") return `<span class="door"><a class="ghost" href="/__forge/signin?to=${encodeURIComponent(path)}">Sign in</a></span>`;
117 return `<span class="door"><span class="who">${escape(who.name)}${who.role === "admin" ? " · admin" : ""}</span><a class="ghost" href="/__forge/signout">Sign out</a></span>`;
118 }
119
120 export function landingPage(env: string, who: Who, boards: Board[]): string {
121 const list =
122 who.role === "anon"
123 ? ""
124 : boards.length === 0
125 ? `<p class="hint">Boards you keep will be listed here.</p>`
126 : `<ul class="boards">${boards.map((b) => `<li><a href="/b/${b.id}">${escape(b.name)}</a></li>`).join("")}</ul>`;
107127 return shell(
108128 "tempo",
109 `<header class="top"><h1>tempo</h1><span class="env">${escape(env)}</span></header>
110 <p class="hint">A snappy kanban board. Create one and share its URL — anyone with the link can see and edit it.</p>
129 `<header class="top"><h1>tempo</h1><span class="env">${escape(env)}</span>${doorLink(who, "/")}</header>
130 <p class="hint">A snappy kanban board. Create one and share its URL — anyone with the link can see and edit it as a guest; sign in to keep it in your list below.</p>
111131 <form method="post" action="/boards">
112132 <input name="name" placeholder="Board name" maxlength="100" autofocus>
113133 <button>Create board</button>
114 </form>`,
134 </form>
135 ${list}`,
115136 );
116137 }
117138
118 export type BoardData = { board: Board; columns: Column[]; cards: Card[]; query: string };
139 export type BoardData = { board: Board; columns: Column[]; cards: Card[]; query: string; who: Who };
119140
120 export function boardPage({ board, columns, cards, query }: BoardData): string {
141 // A guest's board belongs to no one until someone signed in keeps it
142 // (POST /b/:id/claim — see routes.ts and db.ts's claimBoard).
143 function keepHtml(board: Board, who: Who): string {
144 if (board.owner_name !== null) return `<span class="keep">Kept by ${escape(board.owner_name)}</span>`;
145 if (who.role === "anon") return `<span class="keep">Not kept by anyone yet — sign in to keep it.</span>`;
146 return `<form class="keep" method="post" action="/b/${board.id}/claim"><button class="ghost">Keep this board</button></form>`;
147 }
148
149 export function boardPage({ board, columns, cards, query, who }: BoardData): string {
121150 const q = query.trim().toLowerCase();
122151 const matches = (c: Card) => q === "" || c.title.toLowerCase().includes(q);
123152 const cardsFor = (columnId: string) => cards.filter((c) => c.column_id === columnId);
@@ -182,8 +211,9 @@ export function boardPage({ board, columns, cards, query }: BoardData): string {
182211 <input name="name" value="${escape(board.name)}" maxlength="100" aria-label="Board name">
183212 <button class="ghost">Rename</button>
184213 </form>
214 ${doorLink(who, `/b/${board.id}`)}
185215 </header>
186 <p class="hint">Share this board with its URL. Drag a card, or focus it (Tab) and press the arrow keys, to move it — no mouse needed. Type a title and press Enter to save it.</p>
216 <p class="hint">Share this board with its URL. Drag a card, or focus it (Tab) and press the arrow keys, to move it — no mouse needed. Type a title and press Enter to save it. ${keepHtml(board, who)}</p>
187217 <div class="toolbar">
188218 <form class="filter-form" method="get" action="/b/${board.id}">
189219 <input type="search" id="filter" name="q" value="${escape(query)}" placeholder="Filter cards">
@@ -217,5 +247,5 @@ const boardShortcuts: [string, string][] = [
217247
218248 // Named by content — a change to static/board.js gets a new hash here,
219249 // so the year-long cache on /static/ never serves a stale script.
220 export const BOARD_JS = "board.2992576250.js";
250 export const BOARD_JS = "board.519253746.js";
221251 export const THEME_JS = "theme.1025564933.js";
src/routes.ts +56 −15
@@ -5,11 +5,21 @@
55 */
66
77 import * as db from "./db.ts";
8 import * as live from "./live.ts";
9 import { rpc } from "./mcp.ts";
810 import { boardPage, landingPage } from "./pages/board.ts";
11 import type { Who } from "./who.ts";
912
1013 const BOARD_ID = /^[a-z0-9]{8}$/;
1114 const ENTITY_ID = /^[a-z0-9]{12}$/;
1215
16 // The client that made a write, so its own tab can skip re-fetching a
17 // live event it already applied optimistically. Purely informational —
18 // nothing here trusts it for anything but avoiding a redundant refetch.
19 const CLIENT_HEADER = "x-tempo-client";
20 const touch = (boardId: string, request: Request): void =>
outdated

Low — an unbounded client-supplied header is rebroadcast to everyone on the board. x-tempo-client is taken raw here and handed to live.touch, which keeps it in a hundred-event buffer and sends it to every listener on that board. An 8KB header is therefore stored a hundred times over and amplified to every open page. It is only ever compared for equality, so .slice(0, 64) at this boundary costs nothing and closes it.

While you are in live.ts: nothing caps concurrent /b/:id/events connections, and each one holds a subscriber plus a 25s interval, so a loop of curls is enough to weigh the process down. A ceiling with a 503 over it would be cheap insurance.

21 live.touch(boardId, request.headers.get(CLIENT_HEADER)?.slice(0, 64) ?? null);
22
1323 const html = (body: string, status = 200): Response =>
1424 new Response(body, { status, headers: { "content-type": "text/html; charset=utf-8" } });
1525 const json = (body: unknown, status = 200): Response =>
@@ -26,6 +36,11 @@ function done(request: Request, boardId: string, ok: boolean, extra: Record<stri
2636 if (wantsJson(request)) return ok ? json({ ok, ...extra }) : json({ ok }, 404);
2737 return ok ? Response.redirect(`/b/${boardId}`, 303) : new Response("not found", { status: 404 });
2838 }
39 // Every other page on this board hears about a write that actually happened.
40 function doneTouch(request: Request, boardId: string, ok: boolean, extra: Record<string, unknown> = {}): Response {
41 if (ok) touch(boardId, request);
42 return done(request, boardId, ok, extra);
43 }
2944
3045 function cleanText(value: FormDataEntryValue | null, max: number): string | null {
3146 const text = String(value ?? "").trim().slice(0, max);
@@ -36,19 +51,33 @@ async function form(request: Request): Promise<FormData> {
3651 return request.formData();
3752 }
3853
39 export async function route(request: Request, url: URL, env: string): Promise<Response | undefined> {
54 export async function route(request: Request, url: URL, env: string, who: Who): Promise<Response | undefined> {
4055 const method = request.method;
4156 const parts = url.pathname.split("/").filter(Boolean);
4257
43 if (method === "GET" && parts.length === 0) return html(landingPage(env));
58 if (method === "GET" && parts.length === 0) {
59 const boards = who.role === "anon" ? [] : db.listBoardsByOwner(who.id);
60 return html(landingPage(env, who, boards));
61 }
4462
4563 if (method === "POST" && parts.length === 1 && parts[0] === "boards") {
4664 const data = await form(request);
4765 const name = cleanText(data.get("name"), 100) ?? "New board";
48 const board = db.createBoard(name);
66 const owner = who.role === "anon" ? undefined : { id: who.id, name: who.name };
67 const board = db.createBoard(name, owner);
4968 return Response.redirect(`/b/${board.id}`, 303);
5069 }
5170
71 if (method === "POST" && parts.length === 1 && parts[0] === "mcp") {
72 const message = await request.json().catch(() => undefined);
73 if (message === undefined) return json({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } });
74 const { status, body } = rpc(who, message);
75 return body === undefined ? new Response(null, { status }) : json(body, status);
76 }
77 if (method === "GET" && parts.length === 1 && parts[0] === "mcp") {
78 return new Response("this endpoint speaks JSON-RPC over POST", { status: 405 });
79 }
80
5281 if (parts[0] !== "b" || parts.length < 2) return undefined;
5382 const boardId = parts[1];
5483 if (!BOARD_ID.test(boardId)) return undefined;
@@ -59,22 +88,34 @@ export async function route(request: Request, url: URL, env: string): Promise<Re
5988 const columns = db.listColumns(boardId);
6089 const cards = db.listCards(boardId);
6190 const query = url.searchParams.get("q") ?? "";
62 return html(boardPage({ board, columns, cards, query: query.slice(0, 200) }));
91 return html(boardPage({ board, columns, cards, query: query.slice(0, 200), who }));
92 }
93
94 if (method === "GET" && parts.length === 3 && parts[2] === "events") {
95 if (!db.getBoard(boardId)) return new Response("board not found", { status: 404 });
96 return live.events(boardId, request);
6397 }
6498
6599 if (!db.getBoard(boardId)) return new Response("board not found", { status: 404 });
66100
101 if (method === "POST" && parts.length === 3 && parts[2] === "claim") {
102 if (who.role === "anon") return new Response("sign in to keep a board", { status: 401 });
103 const result = db.claimBoard(boardId, { id: who.id, name: who.name });
104 if (result === "owned_by_other") return new Response("already kept by someone else", { status: 403 });
105 if (result === "claimed") touch(boardId, request);
106 return done(request, boardId, true);
107 }
108
67109 if (method === "POST" && parts.length === 3 && parts[2] === "rename") {
68110 const data = await form(request);
69111 const name = cleanText(data.get("name"), 100);
70112 if (!name) return bad("a board needs a name");
71113 db.renameBoard(boardId, name);
72 return done(request, boardId, true);
114 return doneTouch(request, boardId, true);
73115 }
74116
75117 if (method === "POST" && parts.length === 3 && parts[2] === "undo") {
76 const ok = db.undo(boardId);
77 return done(request, boardId, ok);
118 return doneTouch(request, boardId, db.undo(boardId));
78119 }
79120
80121 if (method === "POST" && parts.length === 3 && parts[2] === "columns") {
@@ -82,7 +123,7 @@ export async function route(request: Request, url: URL, env: string): Promise<Re
82123 const name = cleanText(data.get("name"), 60);
83124 if (!name) return bad("a column needs a name");
84125 const column = db.createColumn(boardId, name);
85 return done(request, boardId, true, { id: column.id });
126 return doneTouch(request, boardId, true, { id: column.id });
86127 }
87128
88129 if (parts.length >= 4 && parts[2] === "columns") {
@@ -93,18 +134,18 @@ export async function route(request: Request, url: URL, env: string): Promise<Re
93134 const data = await form(request);
94135 const name = cleanText(data.get("name"), 60);
95136 if (!name) return bad("a column needs a name");
96 return done(request, boardId, db.renameColumn(boardId, columnId, name));
137 return doneTouch(request, boardId, db.renameColumn(boardId, columnId, name));
97138 }
98139
99140 if (method === "POST" && parts.length === 5 && parts[4] === "move") {
100141 const data = await form(request);
101142 const direction = data.get("direction");
102143 if (direction !== "left" && direction !== "right") return bad("direction must be left or right");
103 return done(request, boardId, db.moveColumn(boardId, columnId, direction));
144 return doneTouch(request, boardId, db.moveColumn(boardId, columnId, direction));
104145 }
105146
106147 if (method === "POST" && parts.length === 5 && parts[4] === "delete") {
107 return done(request, boardId, db.deleteColumn(boardId, columnId));
148 return doneTouch(request, boardId, db.deleteColumn(boardId, columnId));
108149 }
109150
110151 if (method === "POST" && parts.length === 5 && parts[4] === "cards") {
@@ -112,7 +153,7 @@ export async function route(request: Request, url: URL, env: string): Promise<Re
112153 const title = cleanText(data.get("title"), 200);
113154 if (!title) return bad("a card needs a title");
114155 const card = db.createCard(boardId, columnId, title);
115 return done(request, boardId, card !== null, card ? { id: card.id } : {});
156 return doneTouch(request, boardId, card !== null, card ? { id: card.id } : {});
116157 }
117158 }
118159
@@ -124,7 +165,7 @@ export async function route(request: Request, url: URL, env: string): Promise<Re
124165 const data = await form(request);
125166 const title = cleanText(data.get("title"), 200);
126167 if (!title) return bad("a card needs a title");
127 return done(request, boardId, db.editCard(boardId, cardId, title));
168 return doneTouch(request, boardId, db.editCard(boardId, cardId, title));
128169 }
129170
130171 if (method === "POST" && parts.length === 5 && parts[4] === "move") {
@@ -133,11 +174,11 @@ export async function route(request: Request, url: URL, env: string): Promise<Re
133174 const index = Number(data.get("index"));
134175 if (!ENTITY_ID.test(columnId)) return bad("column_id is required");
135176 if (!Number.isFinite(index) || index < 0) return bad("index must be a non-negative number");
136 return done(request, boardId, db.moveCard(boardId, cardId, columnId, Math.floor(index)));
177 return doneTouch(request, boardId, db.moveCard(boardId, cardId, columnId, Math.floor(index)));
137178 }
138179
139180 if (method === "POST" && parts.length === 5 && parts[4] === "delete") {
140 return done(request, boardId, db.deleteCard(boardId, cardId));
181 return doneTouch(request, boardId, db.deleteCard(boardId, cardId));
141182 }
142183 }
143184
src/server.test.ts +137
@@ -5,7 +5,14 @@ import { join } from "node:path";
55
66 process.env.FORGE_APP_DATA = mkdtempSync(join(tmpdir(), "app-"));
77 process.env.PORT = "0";
8 process.env.FORGE_APP_IDENTITY_KEY = "test-key";
89 const { server } = await import("./server.ts");
10 const { sign } = await import("./who.ts");
11 const KEY = "test-key";
12 const identityHeaders = (id: string, name: string, role: "user" | "admin" = "user") => {
13 const identity = `${id}|${name}|${role}|${Date.now() + 60_000}`;
14 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
15 };
916 const base = `http://${server.hostname}:${server.port}`;
1017
1118 const j = { accept: "application/json", "content-type": "application/x-www-form-urlencoded" };
@@ -230,3 +237,133 @@ test("serves the board script with a year-long cache", async () => {
230237 expect(response.status).toBe(200);
231238 expect(response.headers.get("cache-control")).toContain("immutable");
232239 });
240
241 test("a signed-in creator's board is kept in their list, a guest's is not", async () => {
242 const created = await fetch(base + "/boards", {
243 method: "POST",
244 body: new URLSearchParams({ name: "Alice's board" }),
245 redirect: "manual",
246 headers: identityHeaders("u9", "alice"),
247 });
248 const location = created.headers.get("location")!;
249 const aliceList = await (await fetch(base + "/", { headers: identityHeaders("u9", "alice") })).text();
250 expect(aliceList).toContain(location);
251
252 const guestId = await newBoard();
253 const bobList = await (await fetch(base + "/", { headers: identityHeaders("u2", "bob") })).text();
254 expect(bobList).not.toContain(`/b/${guestId}`);
255 });
256
257 test("a guest's board is kept by the first signed-in person to claim it, and stays theirs", async () => {
258 const id = await newBoard();
259 const boardUrl = `/b/${id}`;
260
261 const anonClaim = await fetch(base + `${boardUrl}/claim`, { method: "POST" });
262 expect(anonClaim.status).toBe(401);
263
264 const aliceClaim = await fetch(base + `${boardUrl}/claim`, {
265 method: "POST",
266 redirect: "manual",
267 headers: identityHeaders("u1", "alice"),
268 });
269 expect(aliceClaim.status).toBe(303);
270 expect(await (await fetch(base + boardUrl)).text()).toContain("Kept by alice");
271
272 const bobClaim = await fetch(base + `${boardUrl}/claim`, {
273 method: "POST",
274 redirect: "manual",
275 headers: identityHeaders("u2", "bob"),
276 });
277 expect(bobClaim.status).toBe(403);
278
279 const aliceList = await (await fetch(base + "/", { headers: identityHeaders("u1", "alice") })).text();
280 expect(aliceList).toContain(boardUrl);
281 });
282
283 test("streams a live event over /events when a card moves, so another tab can catch up", async () => {
284 const id = await newBoard();
285 const boardUrl = `/b/${id}`;
286 const page = await (await fetch(base + boardUrl)).text();
287 const [todoId, doingId] = [...page.matchAll(/data-column-id="([a-z0-9]{12})"/g)].map((m) => m[1]);
288 const created = await post(`${boardUrl}/columns/${todoId}/cards`, { title: "Live card" });
289 const { id: cardId } = (await created.json()) as { id: string };
290
291 const stream = await fetch(base + `${boardUrl}/events`);
292 expect(stream.headers.get("content-type")).toBe("text/event-stream");
293 const reader = stream.body!.getReader();
294 const decoder = new TextDecoder();
295 let buffer = "";
296 async function nextChunk(): Promise<string> {
297 while (!buffer.includes("\n\n")) {
298 const { value, done } = await reader.read();
299 if (done) throw new Error("stream ended");
300 buffer += decoder.decode(value, { stream: true });
301 }
302 const at = buffer.indexOf("\n\n");
303 const chunk = buffer.slice(0, at);
304 buffer = buffer.slice(at + 2);
305 return chunk;
306 }
307
308 // The card just created already touched the bus before we connected.
309 let sawBacklog = false;
310 for (let i = 0; i < 5 && !sawBacklog; i++) if ((await nextChunk()).includes("data:")) sawBacklog = true;
311 expect(sawBacklog).toBe(true);
312
313 await post(`${boardUrl}/cards/${cardId}/move`, { column_id: doingId, index: "0" });
314 let sawMove = false;
315 for (let i = 0; i < 5 && !sawMove; i++) if ((await nextChunk()).includes("data:")) sawMove = true;
316 expect(sawMove).toBe(true);
317 await reader.cancel();
318 });
319
320 test("the MCP server lists its tools and calls add_card as JSON-RPC", async () => {
321 const id = await newBoard();
322 const page = await (await fetch(base + `/b/${id}`)).text();
323 const [, todoId] = page.match(/data-column-id="([a-z0-9]{12})"/)!;
324 const rpcCall = (body: unknown) =>
325 fetch(base + "/mcp", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
326
327 const init = await (await rpcCall({ jsonrpc: "2.0", id: 1, method: "initialize" })).json();
328 expect(init.result.serverInfo.name).toBe("tempo");
329
330 const listed = await (await rpcCall({ jsonrpc: "2.0", id: 2, method: "tools/list" })).json();
331 expect(listed.result.tools.map((t: { name: string }) => t.name)).toEqual(["list_boards", "list_cards", "add_card", "move_card"]);
332
333 const added = await (
334 await rpcCall({
335 jsonrpc: "2.0",
336 id: 3,
337 method: "tools/call",
338 params: { name: "add_card", arguments: { board_id: id, column_id: todoId, title: "From an agent" } },
339 })
340 ).json();
341 expect(added.result.content[0].text).toContain("From an agent");
342 expect(await (await fetch(base + `/b/${id}`)).text()).toContain("From an agent");
343
344 const missing = await (
345 await rpcCall({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "no_such_tool" } })
346 ).json();
347 expect(missing.error.code).toBe(-32602);
348 });
349
350 test("list_boards over MCP only ever shows the caller's own boards", async () => {
351 await fetch(base + "/boards", {
352 method: "POST",
353 body: new URLSearchParams({ name: "Mine" }),
354 redirect: "manual",
355 headers: identityHeaders("u5", "carol"),
356 });
357 const call = (headers: Record<string, string> = {}) =>
358 fetch(base + "/mcp", {
359 method: "POST",
360 headers: { "content-type": "application/json", ...headers },
361 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "list_boards", arguments: {} } }),
362 });
363
364 const anon = JSON.parse((await (await call()).json()).result.content[0].text);
365 expect(anon).toEqual([]);
366
367 const carol = JSON.parse((await (await call(identityHeaders("u5", "carol"))).json()).result.content[0].text);
368 expect(carol.some((b: { name: string }) => b.name === "Mine")).toBe(true);
369 });
src/server.ts +11 −3
@@ -9,18 +9,25 @@
99 import { join } from "node:path";
1010 import "./db.ts";
1111 import { route } from "./routes.ts";
12 import { who } from "./who.ts";
1213
1314 const env = process.env.FORGE_APP_ENV ?? "local";
15 const identityKey = process.env.FORGE_APP_IDENTITY_KEY ?? "";
16
17 // The app's public address is what the forge told us, never the socket's.
18 const publicOrigin = new URL(process.env.FORGE_APP_URL ?? "http://localhost").origin;
1419
1520 // The security floor every response stands on. Scripts and styles come from
1621 // this origin (inline styles allowed, inline scripts not), nothing frames us,
1722 // browsers never guess a content type, and referrers stay on this site.
23 // Once served over https, always: browsers remember for a year.
1824 const SECURITY = {
1925 "content-security-policy":
2026 "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
2127 "x-content-type-options": "nosniff",
2228 "referrer-policy": "strict-origin-when-cross-origin",
2329 "permissions-policy": "camera=(), microphone=(), geolocation=()",
30 ...(publicOrigin.startsWith("https:") ? { "strict-transport-security": "max-age=31536000" } : {}),
2431 };
2532 function withFloor(response: Response): Response {
2633 for (const [key, value] of Object.entries(SECURITY)) response.headers.set(key, value);
@@ -30,8 +37,6 @@ function withFloor(response: Response): Response {
3037 // A browser on another site can make a person's browser POST here; it cannot
3138 // make that request look same-origin. Browsers say where a request came from
3239 // (Sec-Fetch-Site, or Origin); a request that names another site is refused.
33 // The app's public address is what the forge told us, never the socket's.
34 const publicOrigin = new URL(process.env.FORGE_APP_URL ?? "http://localhost").origin;
3540 const sameOrigin = (request: Request): boolean => {
3641 const site = request.headers.get("sec-fetch-site");
3742 if (site !== null) return site === "same-origin" || site === "none";
@@ -42,11 +47,14 @@ const sameOrigin = (request: Request): boolean => {
4247 export const server = Bun.serve({
4348 port: Number(process.env.PORT ?? 8080),
4449 hostname: process.env.HOST ?? "127.0.0.1",
50 // A connection silent for a minute is dropped; /b/:id/events heartbeats
51 // every 25 seconds (src/live.ts) to stay well inside that.
52 idleTimeout: 60,
4553 async fetch(request) {
4654 const url = new URL(request.url);
4755 if (request.method === "POST" && !sameOrigin(request)) return withFloor(new Response("forbidden", { status: 403 }));
4856
49 const routed = await route(request, url, env);
57 const routed = await route(request, url, env, who(request, identityKey));
5058 if (routed) return withFloor(routed);
5159
5260 // Files under ./static are served as they are, cached for a year: name
src/theme.test.ts +1
@@ -12,6 +12,7 @@ import { join } from "node:path";
1212
1313 process.env.FORGE_APP_DATA = mkdtempSync(join(tmpdir(), "app-"));
1414 process.env.PORT = "0";
15 process.env.FORGE_APP_IDENTITY_KEY = "test-key";
1516 const { server } = await import("./server.ts");
1617 const base = `http://${server.hostname}:${server.port}`;
1718
src/who.test.ts added +25
@@ -0,0 +1,25 @@
1 import { expect, test } from "bun:test";
2 import { sign, who } from "./who.ts";
3
4 const KEY = "a-key-only-the-forge-holds";
5 const later = Date.now() + 60_000;
6 const request = (identity: string, signature: string): Request =>
7 new Request("http://app/", { headers: { "x-forge-identity": identity, "x-forge-signature": signature } });
8
9 test("a signed identity is who it says", () => {
10 const identity = `u1|alice|admin|${later}`;
11 expect(who(request(identity, sign(identity, KEY)), KEY)).toEqual({ role: "admin", id: "u1", name: "alice" });
12 });
13
14 test("a forged, tampered, expired or unsigned identity is anonymous", () => {
15 const identity = `u1|alice|admin|${later}`;
16 expect(who(request(identity, sign(identity, "another key")), KEY)).toEqual({ role: "anon" });
17 expect(who(request(`u1|alice|admin|${later + 1}`, sign(identity, KEY)), KEY)).toEqual({ role: "anon" });
18 const expired = `u1|alice|user|${Date.now() - 1}`;
19 expect(who(request(expired, sign(expired, KEY)), KEY)).toEqual({ role: "anon" });
20 const odd = `u1|alice|owner|${later}`;
21 expect(who(request(odd, sign(odd, KEY)), KEY)).toEqual({ role: "anon" });
22 expect(who(new Request("http://app/"), KEY)).toEqual({ role: "anon" });
23 // No key configured: nothing verifies, whoever signed it.
24 expect(who(request(identity, sign(identity, KEY)), "")).toEqual({ role: "anon" });
25 });
src/who.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * Who is asking. The forge signs every request it proxies to the app:
3 *
4 * x-forge-identity: <userId>|<username>|<role>|<expiresMs>
5 * x-forge-signature: base64url(HMAC-SHA256(FORGE_APP_IDENTITY_KEY, that string))
6 *
7 * `role` is `user` (signed in) or `admin`. The forge strips these two
8 * headers from whatever a client sends, so a signature that verifies is
9 * the only trust there is: no headers, no key, a bad signature or a stamp
10 * in the past all mean `anon`. Nothing here reads a cookie of its own.
11 */
12
13 import { createHmac, timingSafeEqual } from "node:crypto";
14
15 export type Who = { role: "anon" } | { role: "user" | "admin"; id: string; name: string };
16
17 export const ANON: Who = { role: "anon" };
18
19 export function who(request: Request, key: string, now = Date.now()): Who {
20 const identity = request.headers.get("x-forge-identity");
21 const signature = request.headers.get("x-forge-signature");
22 if (key === "" || identity === null || signature === null) return ANON;
23 if (!same(sign(identity, key), signature)) return ANON;
24 const parts = identity.split("|");
25 if (parts.length !== 4) return ANON;
26 const [id, name, role, expires] = parts as [string, string, string, string];
27 if (role !== "user" && role !== "admin") return ANON;
28 if (id === "" || name === "" || !/^\d+$/.test(expires) || Number(expires) <= now) return ANON;
29 return { role, id, name };
30 }
31
32 /** The signature the forge computes. Exported so a test can be the forge. */
33 export const sign = (identity: string, key: string): string => createHmac("sha256", key).update(identity).digest("base64url");
34
35 const same = (a: string, b: string): boolean => {
36 const x = Buffer.from(a);
37 const y = Buffer.from(b);
38 return x.length === y.length && timingSafeEqual(x, y);
39 };
static/board.2992576250.js → static/board.519253746.js renamed +65 −13
@@ -17,10 +17,17 @@
1717 toastTimer = setTimeout(() => toast.classList.remove("show"), 3000);
1818 }
1919
20 // A random id for this tab, sent on every write so its own live event
21 // (see "live" below) can be told apart from everyone else's.
22 const clientId = Math.random().toString(36).slice(2);
2023 function post(path, data) {
2124 return fetch(path, {
2225 method: "POST",
23 headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
26 headers: {
27 "content-type": "application/x-www-form-urlencoded",
28 accept: "application/json",
29 "x-tempo-client": clientId,
30 },
2431 body: new URLSearchParams(data),
2532 });
2633 }
@@ -99,20 +106,25 @@
99106 if (!dragging) return;
100107 e.preventDefault();
101108 });
102 for (const list of root.querySelectorAll(".cards")) {
103 list.addEventListener("dragover", (e) => {
104 if (!dragging) return;
105 e.preventDefault();
106 clearDropTargets();
107 list.closest(".column").classList.add("drop-target");
108 const after = cardsOf(list.closest(".column")).find((el) => {
109 if (el === dragging.el) return false;
110 const box = el.getBoundingClientRect();
111 return e.clientY < box.top + box.height / 2;
109 // A board refreshed from a live update (see "live" below) gets fresh
110 // `.cards` elements, so this attaches again rather than running once.
111 function attachDropListeners() {
112 for (const list of root.querySelectorAll(".cards")) {
113 list.addEventListener("dragover", (e) => {
114 if (!dragging) return;
115 e.preventDefault();
116 clearDropTargets();
117 list.closest(".column").classList.add("drop-target");
118 const after = cardsOf(list.closest(".column")).find((el) => {
119 if (el === dragging.el) return false;
120 const box = el.getBoundingClientRect();
121 return e.clientY < box.top + box.height / 2;
122 });
123 list.insertBefore(dragging.el, after || null);
112124 });
113 list.insertBefore(dragging.el, after || null);
114 });
125 }
115126 }
127 attachDropListeners();
116128
117129 // ---- keyboard: arrow keys move the focused card, no drag required ----
118130 root.addEventListener("keydown", (e) => {
@@ -273,4 +285,44 @@
273285 li.append(editForm, row);
274286 return li;
275287 }
288
289 // ---- live: other tabs' changes appear here within a second, no reload ----
290 // Guarded so this file still runs where EventSource doesn't exist (the
291 // drag test's synthetic environment); a real browser always has it.
292 if (typeof EventSource !== "undefined") {
293 let pending = false;
294 async function refreshBoard() {
295 // Any input inside the board (a card's title, a new-card box, a column
296 // rename) keeps its refresh until the input loses focus — replacing it
297 // mid-word would wipe what someone is typing. A card itself focused
298 // for keyboard navigation (not editing) is not an input, so it does
299 // not defer; its focus is restored after the swap instead.
300 const focused = root.querySelector(".board :focus");
301 if (dragging || (focused && focused.tagName === "INPUT")) {
302 pending = true;
303 return;
304 }
305 pending = false;
306 const focusedCardId = focused && focused.classList.contains("card") ? focused.dataset.cardId : null;
307 const response = await fetch(location.pathname + location.search, { headers: { accept: "text/html" } });
308 if (!response.ok) return;
309 const fresh = new DOMParser().parseFromString(await response.text(), "text/html");
310 const next = fresh.querySelector(".board");
311 const current = root.querySelector(".board");
312 if (!next || !current) return;
313 current.replaceWith(next);
314 attachDropListeners();
315 if (focusedCardId) root.querySelector(`.card[data-card-id="${CSS.escape(focusedCardId)}"]`)?.focus();
316 }
317 // A card mid-edit or mid-drag keeps its refresh until it's free again.
318 root.addEventListener("focusout", () => pending && refreshBoard());
319 root.addEventListener("dragend", () => pending && refreshBoard());
320
321 const source = new EventSource(`/b/${boardId}/events`);
322 source.onmessage = (message) => {
323 const { by } = JSON.parse(message.data);
324 if (by === clientId) return; // this tab already applied it optimistically
325 refreshBoard();
326 };
327 }
276328 })();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs