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

A shared board cannot be used to fill the disk: bound the undo log, a board's size, and board creation #27

Merged opened this

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

Merged

scout/tempo:scout/16-a-shared-board-cannot-be-used-to-fill-th → main 3 commits fork 1 thread · 1 unresolved

  • Merged. scout/16-a-shared-board-cannot-be-used-to-fill-th was merged into main as 3709e3d.

Review

Sign in to review this change.
13 files changed +395 −42
README.md +22
@@ -81,6 +81,28 @@ background, reverting if it fails.
8181 process on the same database, so a change made there shows up on the
8282 next page load, not live.
8383
84 ## Limits
85
86 A board anyone can open and change has nothing else standing between it
87 and the disk, so `src/limits.ts` names a floor:
88
89 - **Undo** keeps only the newest 200 actions per board; past that, undoing
90 just runs out ("nothing to undo"), the same path as an empty log.
91 - **Columns**: a board holds at most 50. The 51st is refused with a
92 message naming the number, both on the page and in the terminal.
93 - **Cards**: a board holds at most 500 total, refused the same way.
94 - **Board creation** is throttled by a single, in-memory token bucket for
95 the whole process (30 a minute) — a crude, app-wide brake against a
96 flood of new boards, *not* per-person fairness: it isn't keyed by IP,
97 identity, or anything else a caller controls, because a limiter keyed by
98 caller is itself an unbounded map. Going over it answers `429` with a
99 `retry-after` header and recovers on its own.
100 - **Request bodies** over 64KB are refused before they're read.
101
102 These are process-wide numbers chosen to comfortably fit real use of one
103 board; hitting one always says the number in the error, so it reads as a
104 limit rather than a broken app.
105
84106 It also has a terminal: the exact command is in `FORGE_APP_SSH` when the app
85107 runs (`ssh -p 2222 <name>@<forge>` — the app is the login name, the forge is
86108 the host; `<name>--<pull>@<forge>` for a preview's). It opens `src/tty.ts` on
src/db.test.ts +19 −10
@@ -2,11 +2,20 @@ import { expect, test } from "bun:test";
22 import { existsSync, mkdtempSync, rmSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
5 import type { Card } from "./db.ts";
56
67 const dataDir = mkdtempSync(join(tmpdir(), "app-"));
78 process.env.FORGE_APP_DATA = dataDir;
89 const db = await import("./db.ts");
910
11 // createCard can answer "not_found" or "full" instead of a Card; asserting
12 // here (instead of `as Card`) means a regression that starts returning one
13 // of those sentinels fails the test it broke, not just the type checker.
14 function assertCard(result: Card | "not_found" | "full"): Card {
15 if (typeof result === "string") throw new Error(`expected a Card, got ${JSON.stringify(result)}`);
16 return result;
17 }
18
1019 function setup() {
1120 const board = db.createBoard("Board");
1221 const column = db.listColumns(board.id)[0];
@@ -15,14 +24,14 @@ function setup() {
1524
1625 test("two cards created back to back get distinct positions in creation order", () => {
1726 const { boardId, columnId } = setup();
18 const a = db.createCard(boardId, columnId, "First")!;
19 const b = db.createCard(boardId, columnId, "Second")!;
27 const a = assertCard(db.createCard(boardId, columnId, "First"));
28 const b = assertCard(db.createCard(boardId, columnId, "Second"));
2029 expect(a.position).toBeLessThan(b.position);
2130 });
2231
2332 test("moving a card into a column that does not exist fails cleanly and writes no orphan", () => {
2433 const { boardId, columnId } = setup();
25 const card = db.createCard(boardId, columnId, "Homeless")!;
34 const card = assertCard(db.createCard(boardId, columnId, "Homeless"));
2635 const moved = db.moveCard(boardId, card.id, "no-such-column", 0);
2736 expect(moved).toBe(false);
2837 expect(db.getCard(boardId, card.id)!.column_id).toBe(columnId);
@@ -35,7 +44,7 @@ test("repeated midpoint drops into the same slot cannot collapse positions", ()
3544
3645 let last!: { id: string };
3746 for (let i = 0; i < 60; i++) {
38 last = db.createCard(boardId, columnId, `c${i}`)!;
47 last = assertCard(db.createCard(boardId, columnId, `c${i}`));
3948 db.moveCard(boardId, last.id, columnId, 1);
4049 }
4150
@@ -51,12 +60,12 @@ test("undo of a renormalising move restores every renormalised card, not just th
5160 db.createCard(boardId, columnId, "lo");
5261 db.createCard(boardId, columnId, "hi");
5362 for (let i = 0; i < 60; i++) {
54 const c = db.createCard(boardId, columnId, `c${i}`)!;
63 const c = assertCard(db.createCard(boardId, columnId, `c${i}`));
5564 db.moveCard(boardId, c.id, columnId, 1);
5665 }
5766 const before = db.listCards(boardId).filter((c) => c.column_id === columnId);
5867
59 const mover = db.createCard(boardId, columnId, "mover")!;
68 const mover = assertCard(db.createCard(boardId, columnId, "mover"));
6069 const moverBefore = db.getCard(boardId, mover.id)!;
6170 db.moveCard(boardId, mover.id, columnId, 1);
6271 const afterMove = db.listCards(boardId).filter((c) => c.column_id === columnId);
@@ -70,8 +79,8 @@ test("undo of a renormalising move restores every renormalised card, not just th
7079
7180 test("ties are ordered consistently by position then id", () => {
7281 const { boardId, columnId } = setup();
73 const a = db.createCard(boardId, columnId, "A")!;
74 const b = db.createCard(boardId, columnId, "B")!;
82 const a = assertCard(db.createCard(boardId, columnId, "A"));
83 const b = assertCard(db.createCard(boardId, columnId, "B"));
7584 // Force a tie directly, as no code path in db.ts produces one; the
7685 // reader must still agree on one order if it ever happens.
7786 db.db.query("UPDATE card SET position = 1 WHERE id = ?1 OR id = ?2").run(a.id, b.id);
@@ -93,8 +102,8 @@ test("undo returns false with nothing to undo", () => {
93102 // throws "database is locked" at once; with them, it waits and both writes land.
94103 test("a write from another process holding the write lock does not fail moveCard, it waits", async () => {
95104 const { boardId, columnId } = setup();
96 const held = db.createCard(boardId, columnId, "held")!;
97 const mover = db.createCard(boardId, columnId, "mover")!;
105 const held = assertCard(db.createCard(boardId, columnId, "held"));
106 const mover = assertCard(db.createCard(boardId, columnId, "mover"));
98107
99108 const dbPath = db.db.filename;
100109 const markerPath = join(dataDir, "locked.marker");
src/db.ts +26 −6
@@ -11,6 +11,7 @@
1111 import { Database } from "bun:sqlite";
1212 import { mkdirSync } from "node:fs";
1313 import { join } from "node:path";
14 import { MAX_CARDS_PER_BOARD, MAX_COLUMNS_PER_BOARD, MAX_UNDO_DEPTH } from "./limits.ts";
1415
1516 const dataDir = process.env.FORGE_APP_DATA ?? "./data";
1617 mkdirSync(dataDir, { recursive: true });
@@ -92,8 +93,17 @@ type Payload = {
9293 deleteCardIds?: string[];
9394 };
9495
96 // Runs inside the same transaction as the write that logged the action, so
97 // undo never sees a row this trim already removed. Keeping only the
98 // newest MAX_UNDO_DEPTH means undoing past that horizon takes the
99 // existing "nothing to undo" path (undo() just finds no row).
95100 function logAction(boardId: string, payload: Payload): void {
96101 db.query("INSERT INTO action (board_id, payload) VALUES (?1, ?2)").run(boardId, JSON.stringify(payload));
102 db.query(
103 `DELETE FROM action WHERE board_id = ?1 AND id NOT IN (
104 SELECT id FROM action WHERE board_id = ?1 ORDER BY id DESC LIMIT ?2
105 )`,
106 ).run(boardId, MAX_UNDO_DEPTH);
97107 }
98108
99109 const BOARD_FIELDS = "id, name, owner_id, owner_name, created_at";
@@ -166,8 +176,17 @@ function nextPosition(rows: { position: number }[]): number {
166176 return rows.length === 0 ? 1 : Math.max(...rows.map((r) => r.position)) + 1;
167177 }
168178
169 export function createColumn(boardId: string, name: string, explicitPosition?: number): Column {
170 return db.transaction((): Column => {
179 function countColumns(boardId: string): number {
180 return db.query<{ n: number }, [string]>("SELECT COUNT(*) as n FROM board_column WHERE board_id = ?1").get(boardId)!.n;
181 }
182
183 function countCards(boardId: string): number {
184 return db.query<{ n: number }, [string]>("SELECT COUNT(*) as n FROM card WHERE board_id = ?1").get(boardId)!.n;
185 }
186
187 export function createColumn(boardId: string, name: string, explicitPosition?: number): Column | "full" {
188 return db.transaction((): Column | "full" => {
189 if (countColumns(boardId) >= MAX_COLUMNS_PER_BOARD) return "full";
171190 const id = randomId(12);
172191 const position = explicitPosition ?? nextPosition(listColumns(boardId));
173192 db.query("INSERT INTO board_column (id, board_id, name, position) VALUES (?1, ?2, ?3, ?4)").run(
@@ -223,10 +242,11 @@ export function deleteColumn(boardId: string, columnId: string): boolean {
223242 }).immediate();
224243 }
225244
226 export function createCard(boardId: string, columnId: string, title: string): Card | null {
227 return db.transaction((): Card | null => {
245 export function createCard(boardId: string, columnId: string, title: string): Card | "not_found" | "full" {
246 return db.transaction((): Card | "not_found" | "full" => {
228247 const column = getColumn(boardId, columnId);
229 if (!column) return null;
248 if (!column) return "not_found";
249 if (countCards(boardId) >= MAX_CARDS_PER_BOARD) return "full";
230250 const id = randomId(12);
231251 const position = nextPosition(listCards(boardId).filter((c) => c.column_id === columnId));
232252 db.query("INSERT INTO card (id, board_id, column_id, title, position) VALUES (?1, ?2, ?3, ?4, ?5)").run(
@@ -237,7 +257,7 @@ export function createCard(boardId: string, columnId: string, title: string): Ca
237257 position,
238258 );
239259 logAction(boardId, { deleteCardIds: [id] });
240 return getCard(boardId, id);
260 return getCard(boardId, id)!;
241261 }).immediate();
242262 }
243263
src/limits.test.ts added +81
@@ -0,0 +1,81 @@
1 import { expect, test } from "bun:test";
2 import { mkdtempSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { MAX_CARDS_PER_BOARD, MAX_COLUMNS_PER_BOARD, MAX_UNDO_DEPTH, TokenBucket } from "./limits.ts";
6
7 process.env.FORGE_APP_DATA = mkdtempSync(join(tmpdir(), "app-"));
8 const db = await import("./db.ts");
9
10 test("a board cannot grow past its column limit, and a refused create writes no row", () => {
11 const board = db.createBoard("Board");
12 for (let i = db.listColumns(board.id).length; i < MAX_COLUMNS_PER_BOARD; i++) db.createColumn(board.id, `c${i}`);
13 expect(db.listColumns(board.id).length).toBe(MAX_COLUMNS_PER_BOARD);
14
15 expect(db.createColumn(board.id, "one too many")).toBe("full");
16 expect(db.listColumns(board.id).length).toBe(MAX_COLUMNS_PER_BOARD);
17 });
18
19 test("a board cannot grow past its card limit, and a refused create writes no row", () => {
20 const board = db.createBoard("Board");
21 const column = db.listColumns(board.id)[0];
22 for (let i = 0; i < MAX_CARDS_PER_BOARD; i++) db.createCard(board.id, column.id, `c${i}`);
23 expect(db.listCards(board.id).length).toBe(MAX_CARDS_PER_BOARD);
24
25 expect(db.createCard(board.id, column.id, "one too many")).toBe("full");
26 expect(db.listCards(board.id).length).toBe(MAX_CARDS_PER_BOARD);
27 });
28
29 test("the undo log keeps only the newest N actions per board, oldest dropped, newest undo still works", () => {
30 const board = db.createBoard("Board");
31 const column = db.listColumns(board.id)[0];
32 const total = MAX_UNDO_DEPTH + 25;
33 for (let i = 0; i < total; i++) db.renameColumn(board.id, column.id, `name-${i}`);
34
35 const rowCount = (db.db.query("SELECT COUNT(*) as n FROM action WHERE board_id = ?1").get(board.id) as { n: number }).n;
36 expect(rowCount).toBe(MAX_UNDO_DEPTH);
37
38 // The newest change is still reachable...
39 expect(db.undo(board.id)).toBe(true);
40 expect(db.getColumn(board.id, column.id)!.name).toBe(`name-${total - 2}`);
41
42 // ...but the log holds exactly N actions — one more undo than that runs out.
43 for (let i = 1; i < MAX_UNDO_DEPTH; i++) expect(db.undo(board.id)).toBe(true);
44 expect(db.undo(board.id)).toBe(false);
45 });
46
47 test("a token bucket refuses once its tokens run out", () => {
48 let now = 0;
49 const bucket = new TokenBucket(3, () => now);
50 expect(bucket.take()).toBe(true);
51 expect(bucket.take()).toBe(true);
52 expect(bucket.take()).toBe(true);
53 expect(bucket.take()).toBe(false);
54 });
55
56 test("a token bucket recovers on its own once its clock moves on, with no sleep", () => {
57 let now = 0;
58 const bucket = new TokenBucket(60, () => now); // 60/minute = 1 token/second
59 for (let i = 0; i < 60; i++) expect(bucket.take()).toBe(true);
60 expect(bucket.take()).toBe(false);
61
62 now += 500; // half a second: not enough for a full token yet
63 expect(bucket.take()).toBe(false);
64
65 now += 1_000; // a second and a half total: one token has refilled
66 expect(bucket.take()).toBe(true);
67 expect(bucket.take()).toBe(false);
68
69 now += 60_000; // a full minute later, the bucket is back to capacity
70 for (let i = 0; i < 60; i++) expect(bucket.take()).toBe(true);
71 expect(bucket.take()).toBe(false);
72 });
73
74 test("a token bucket says how long until the next token, in whole seconds", () => {
75 let now = 0;
76 const bucket = new TokenBucket(60, () => now);
77 for (let i = 0; i < 60; i++) bucket.take();
78 expect(bucket.retryAfterSeconds()).toBe(1);
79 now += 1_000;
80 expect(bucket.retryAfterSeconds()).toBe(0);
81 });
src/limits.ts added +74
@@ -0,0 +1,74 @@
1 /**
2 * Every limit that stands between a shared, unauthenticated board and the
3 * disk. Named constants only, plus the token bucket that needs a little
4 * state to refill over time — nothing else belongs in this file.
5 */
6
7 // A shared, board-wide undo log otherwise only shrinks when someone
8 // undoes; capping it means a busy board can't grow the action table
9 // forever just by being used.
10 export const MAX_UNDO_DEPTH = 200;
11
12 // Past this many columns a board stops being something a person can scan,
13 // and it bounds how much work rendering and drag-reordering do per request.
14 export const MAX_COLUMNS_PER_BOARD = 50;
15
16 // Same reasoning as columns, for the cards a board can hold in total.
17 export const MAX_CARDS_PER_BOARD = 500;
18
19 // Board creation writes a row that nothing ever deletes; this bounds how
20 // fast the whole process can be made to write new ones.
21 export const MAX_BOARDS_CREATED_PER_MINUTE = 30;
22
23 // A request body bigger than this is refused before it is read, so a
24 // giant upload can't be used to exhaust memory parsing it.
25 export const MAX_REQUEST_BODY_BYTES = 64 * 1024;
26
27 /**
28 * A token bucket: `capacityPerMinute` tokens to start, refilled at
29 * `capacityPerMinute` per minute, never exceeding that capacity. It is a
30 * single counter, not a map keyed by caller — keying it by anything a
31 * caller controls (IP, header, board id) would just move the unbounded
32 * growth this ticket is about into the limiter itself.
33 */
34 export class TokenBucket {
35 private tokens: number;
36 private last: number;
37
38 constructor(
39 private readonly capacityPerMinute: number,
40 private readonly now: () => number = Date.now,
41 ) {
42 this.tokens = capacityPerMinute;
43 this.last = now();
44 }
45
46 private refill(): void {
47 const at = this.now();
48 const elapsedMinutes = (at - this.last) / 60_000;
49 if (elapsedMinutes <= 0) return;
50 this.tokens = Math.min(this.capacityPerMinute, this.tokens + elapsedMinutes * this.capacityPerMinute);
51 this.last = at;
52 }
53
54 /** Spends one token if one is available; true if it did. */
55 take(): boolean {
56 this.refill();
57 if (this.tokens < 1) return false;
58 this.tokens -= 1;
59 return true;
60 }
61
62 /** Seconds until the next token is available, for a `retry-after` header. */
63 retryAfterSeconds(): number {
64 this.refill();
65 const missing = 1 - this.tokens;
66 if (missing <= 0) return 0;
67 return Math.max(1, Math.ceil((missing / this.capacityPerMinute) * 60));
68 }
69 }
70
71 // One bucket for the whole process — see the class comment on why it is
72 // not keyed by caller. This is a crude, app-wide brake against a flood of
73 // board creation, not fairness between people (see README).
74 export const boardCreationBucket = new TokenBucket(MAX_BOARDS_CREATED_PER_MINUTE);

Approving: this does what #16 asked, it holds up in the preview, and it keeps the shape of the repo — one small module named for one concept, no dependency, the limit enforced in db.ts so the terminal and MCP inherit it rather than in routes.ts alone.

What I verified. 55 tests pass at the pull head. On the preview I filled a board to 50 columns: the 51st answered 400 this board is full — 50 columns, the board page was unchanged, and the refusal carried the full security floor (CSP, nosniff, referrer-policy, HSTS). A 70KB body answered 413 before anything read it; a cross-origin POST still answered 403. A 45-way burst of POST /boards answered 429 with retry-after: 2 and recovered on its own inside a minute. Every logAction call site is inside a db.transaction, so the trim really is atomic with the write it follows, and the DELETE is parameterised. I also probed the early 413/429 returns for the classic bug they invite — answering before the body is read can desync a keep-alive connection — with sequential and 12-way concurrent keep-alive clients against the app locally: 72 interleaved GETs, all 200, no desync. Clean.

Findings, ranked, none blocking.

  1. The front door's only button is a shared fuse. One process-wide bucket means 30 creates from anyone — or a script at one per second, indefinitely — makes Create board answer 429 for everybody, signed in or not. #16 specified exactly this and the README is honest that it is a crude app-wide brake, so I am not blocking on it; but if it ever bites in production, the fix that stays bounded is a second, larger allowance for a verified identity (the forge's signature makes it not caller-controlled) with this global bucket kept as the outer ceiling.
  1. The refusals are plain-text dead ends for a browser. POST /b/:id/columns is a plain form navigation — static/board.519253746.js only intercepts edit/move/delete/add-card — so hitting 50 columns replaces the board with a white page reading this board is full — 50 columns and a Back button. Same for 429 on the landing page. This is the one I would fix first: re-render the board page (or the landing page) with the sentence in the slot the page already has, keeping the 400/429 status, instead of bad()'s bare body.
  1. The card ceiling loses its sentence on the web. The add-card path rejects any non-ok response and shows the generic Could not add the card., so a person who hits 500 cards never sees the number — only the terminal and MCP do, which is backwards from where most people are. Return the message on the accept: application/json path and hand it to showError.
  1. Two full scans per card add. createCard now calls listCards(boardId) for the cap and again inside nextPosition. SELECT COUNT(*) for the cap, or one call shared between the two, keeps a 500-card board's add cheap.
  1. Nit: db.test.ts trades ! for as Card. The cast would let a future "full"/"not_found" regression sail through those tests as a Card rather than fail them.

One observation, not attributed to this change: bursting POST /boards 45-way through the preview's edge produced a handful of bare 400s with no app headers and an empty body, and only in bursts that hit 429 — 45-way GET bursts and 45-way /rename bursts were clean. I could not reproduce it against the app locally under the same shape of load, so it reads as the platform edge reacting to a burst of 429s rather than app code. Worth knowing if anyone sees it again.

The undo horizon, the retry-after header, the sentinel returns instead of null, and keeping createBoard's three default columns unaffected all look right to me.

src/mcp.ts +3 −1
@@ -10,6 +10,7 @@
1010
1111 import * as db from "./db.ts";
1212 import { touch } from "./live.ts";
13 import { MAX_CARDS_PER_BOARD } from "./limits.ts";
1314 import type { Who } from "./who.ts";
1415
1516 const BOARD_ID = /^[a-z0-9]{8}$/;
@@ -64,7 +65,8 @@ export const tools: readonly Tool[] = [
6465 const title = String(args.title ?? "").trim().slice(0, 200);
6566 if (title === "") return fail("invalid", "a card needs a title");
6667 const card = db.createCard(board.id, columnId, title);
67 if (!card) return fail("not_found", "no such column");
68 if (card === "not_found") return fail("not_found", "no such column");
69 if (card === "full") return fail("full", `this board is full — ${MAX_CARDS_PER_BOARD} cards`);
6870 touch(board.id, null);
6971 return ok(card);
7072 },
src/pages/board.test.ts added +27
@@ -0,0 +1,27 @@
1 import { expect, test } from "bun:test";
2 import { ANON } from "../who.ts";
3 import { boardPage, landingPage } from "./board.ts";
4
5 // The board-creation throttle (POST /boards) and a few board mutations
6 // (rename, "Add column") are plain form submits with no script watching
7 // the response, so their refusal has to be visible on the re-rendered
8 // page itself — this is that rendering, isolated from the shared,
9 // process-wide bucket the HTTP-level test can't drain without starving
10 // every other test in the file (see server.test.ts).
11 test("landingPage shows a refusal already, with no JavaScript required to see it", () => {
12 const shown = landingPage("test", ANON, [], "too many boards created just now — try again shortly");
13 expect(shown).toContain('id="toast" role="status" aria-live="polite" class="show"');
14 expect(shown).toContain("too many boards created just now");
15 });
16
17 test("landingPage's toast is empty and hidden when there is nothing to report", () => {
18 const clean = landingPage("test", ANON, []);
19 expect(clean).toContain('<div id="toast" role="status" aria-live="polite"></div>');
20 });
21
22 test("boardPage's refusal message is escaped like every other piece of user-facing text", () => {
23 const board = { id: "abcd1234", name: "Board", owner_id: null, owner_name: null, created_at: "" };
24 const shown = boardPage({ board, columns: [], cards: [], query: "", who: ANON, error: "<script>bad</script>" });
25 expect(shown).not.toContain("<script>bad</script>");
26 expect(shown).toContain("&lt;script&gt;bad&lt;/script&gt;");
27 });
src/pages/board.ts +14 −6
@@ -95,7 +95,12 @@ const shortcutsDialog = (extra: [string, string][]): string => {
9595
9696 // static/theme.js runs before the stylesheet below is parsed, so a stored
9797 // preference applies to the first paint — no flash of the other theme.
98 const shell = (title: string, body: string, shortcuts: [string, string][] = []): string => `<!doctype html>
98 //
99 // `error`, when given, is a refusal (a full board, a throttled create)
100 // that a plain form navigation just hit. It renders straight into the
101 // toast, already shown — no JavaScript required to see why the action
102 // didn't happen. static/board.js's own toast calls reuse the same element.
103 const shell = (title: string, body: string, shortcuts: [string, string][] = [], error?: string): string => `<!doctype html>
99104 <meta charset="utf-8">
100105 <script src="/static/${THEME_JS}"></script>
101106 <meta name="viewport" content="width=device-width, initial-scale=1">
@@ -107,7 +112,7 @@ const shell = (title: string, body: string, shortcuts: [string, string][] = []):
107112 </div>
108113 ${body}
109114 ${shortcutsDialog(shortcuts)}
110 <div id="toast" role="status" aria-live="polite"></div>
115 <div id="toast" role="status" aria-live="polite"${error ? ' class="show"' : ""}>${error ? escape(error) : ""}</div>
111116 <script src="/static/${THEME_JS}" defer></script>
112117 `;
113118
@@ -121,7 +126,7 @@ function doorLink(who: Who, path: string): string {
121126 return `<span class="door"><span class="who"><span class="name" title="${name}">${name}</span>${who.role === "admin" ? " · admin" : ""}</span><a class="ghost" href="/__forge/signout?to=${encodeURIComponent(path)}">Sign out</a></span>`;
122127 }
123128
124 export function landingPage(env: string, who: Who, boards: Board[]): string {
129 export function landingPage(env: string, who: Who, boards: Board[], error?: string): string {
125130 const list =
126131 who.role === "anon"
127132 ? ""
@@ -137,10 +142,12 @@ export function landingPage(env: string, who: Who, boards: Board[]): string {
137142 <button>Create board</button>
138143 </form>
139144 ${list}`,
145 [],
146 error,
140147 );
141148 }
142149
143 export type BoardData = { board: Board; columns: Column[]; cards: Card[]; query: string; who: Who };
150 export type BoardData = { board: Board; columns: Column[]; cards: Card[]; query: string; who: Who; error?: string };
144151
145152 // A guest's board belongs to no one until someone signed in keeps it
146153 // (POST /b/:id/claim — see routes.ts and db.ts's claimBoard).
@@ -150,7 +157,7 @@ function keepHtml(board: Board, who: Who): string {
150157 return `<form class="keep" method="post" action="/b/${board.id}/claim"><button class="ghost">Keep this board</button></form>`;
151158 }
152159
153 export function boardPage({ board, columns, cards, query, who }: BoardData): string {
160 export function boardPage({ board, columns, cards, query, who, error }: BoardData): string {
154161 const q = query.trim().toLowerCase();
155162 const matches = (c: Card) => q === "" || c.title.toLowerCase().includes(q);
156163 const cardsFor = (columnId: string) => cards.filter((c) => c.column_id === columnId);
@@ -239,6 +246,7 @@ export function boardPage({ board, columns, cards, query, who }: BoardData): str
239246 </div>
240247 <script src="/static/${BOARD_JS}" defer></script>`,
241248 boardShortcuts,
249 error,
242250 );
243251 }
244252
@@ -251,5 +259,5 @@ const boardShortcuts: [string, string][] = [
251259
252260 // Named by content — a change to static/board.js gets a new hash here,
253261 // so the year-long cache on /static/ never serves a stale script.
254 export const BOARD_JS = "board.519253746.js";
262 export const BOARD_JS = "board.2031175319.js";
255263 export const THEME_JS = "theme.1025564933.js";
src/routes.ts +48 −12
@@ -5,6 +5,7 @@
55 */
66
77 import * as db from "./db.ts";
8 import { boardCreationBucket, MAX_CARDS_PER_BOARD, MAX_COLUMNS_PER_BOARD } from "./limits.ts";
89 import * as live from "./live.ts";
910 import { rpc } from "./mcp.ts";
1011 import { boardPage, landingPage } from "./pages/board.ts";
@@ -32,9 +33,8 @@ const html = (body: string, status = 200): Response =>
3233 vary: "x-forge-identity",
3334 },
3435 });
35 const json = (body: unknown, status = 200): Response =>
36 new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
37 const bad = (message: string): Response => new Response(message, { status: 400 });
36 const json = (body: unknown, status = 200, extraHeaders: Record<string, string> = {}): Response =>
37 new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...extraHeaders } });
3838 const methodNotAllowed = (allow: string): Response => new Response("method not allowed", { status: 405, headers: { allow } });
3939
4040 // Thrown by form() and caught once, at the door, so a handler never has to
@@ -64,6 +64,23 @@ function doneTouch(request: Request, boardId: string, ok: boolean, extra: Record
6464 return done(request, boardId, ok, extra);
6565 }
6666
67 // A rejected form field or a limit hit on a board (a full column list, a
68 // full card list) answers the caller the way it asked: the board's own
69 // script sends `accept: application/json` and reads `error` to toast it
70 // (see static/board.js); everyone else — the "Add column" and board-rename
71 // forms, and a browser with JavaScript off — gets a plain POST navigation,
72 // so it needs the board re-rendered with the sentence already in it rather
73 // than a bare text response replacing the whole page.
74 function boardBad(request: Request, who: Who, boardId: string, message: string, status = 400): Response {
75 if (wantsJson(request)) return json({ error: message }, status);
76 const board = db.getBoard(boardId);
77 if (!board) return new Response(message, { status });
78 return html(
79 boardPage({ board, columns: db.listColumns(boardId), cards: db.listCards(boardId), query: "", who, error: message }),
80 status,
81 );
82 }
83
6784 function cleanText(value: FormDataEntryValue | null, max: number): string | null {
6885 const text = String(value ?? "").trim().slice(0, max);
6986 return text === "" ? null : text;
@@ -103,6 +120,23 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
103120 }
104121
105122 if (method === "POST" && parts.length === 1 && parts[0] === "boards") {
123 if (!boardCreationBucket.take()) {
124 const retryAfter = String(boardCreationBucket.retryAfterSeconds());
125 const message = "too many boards created just now — try again shortly";
126 // "Create board" is a plain form (no script runs on the landing
127 // page), so the refusal has to land back on that same page with the
128 // sentence already in it, not a bare-text response replacing it.
129 const boards = who.role === "anon" ? [] : db.listBoardsByOwner(who.id);
130 return new Response(landingPage(env, who, boards, message), {
131 status: 429,
132 headers: {
133 "content-type": "text/html; charset=utf-8",
134 "cache-control": "private, no-store",
135 vary: "x-forge-identity",
136 "retry-after": retryAfter,
137 },
138 });
139 }
106140 const data = await form(request);
107141 const name = cleanText(data.get("name"), 100) ?? "New board";
108142 const owner = who.role === "anon" ? undefined : { id: who.id, name: who.name };
@@ -152,7 +186,7 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
152186 if (method === "POST" && parts.length === 3 && parts[2] === "rename") {
153187 const data = await form(request);
154188 const name = cleanText(data.get("name"), 100);
155 if (!name) return bad("a board needs a name");
189 if (!name) return boardBad(request, who, boardId, "a board needs a name");
156190 db.renameBoard(boardId, name);
157191 return doneTouch(request, boardId, true);
158192 }
@@ -164,8 +198,9 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
164198 if (method === "POST" && parts.length === 3 && parts[2] === "columns") {
165199 const data = await form(request);
166200 const name = cleanText(data.get("name"), 60);
167 if (!name) return bad("a column needs a name");
201 if (!name) return boardBad(request, who, boardId, "a column needs a name");
168202 const column = db.createColumn(boardId, name);
203 if (column === "full") return boardBad(request, who, boardId, `this board is full — ${MAX_COLUMNS_PER_BOARD} columns`);
169204 return doneTouch(request, boardId, true, { id: column.id });
170205 }
171206
@@ -176,14 +211,14 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
176211 if (method === "POST" && parts.length === 4) {
177212 const data = await form(request);
178213 const name = cleanText(data.get("name"), 60);
179 if (!name) return bad("a column needs a name");
214 if (!name) return boardBad(request, who, boardId, "a column needs a name");
180215 return doneTouch(request, boardId, db.renameColumn(boardId, columnId, name));
181216 }
182217
183218 if (method === "POST" && parts.length === 5 && parts[4] === "move") {
184219 const data = await form(request);
185220 const direction = data.get("direction");
186 if (direction !== "left" && direction !== "right") return bad("direction must be left or right");
221 if (direction !== "left" && direction !== "right") return boardBad(request, who, boardId, "direction must be left or right");
187222 return doneTouch(request, boardId, db.moveColumn(boardId, columnId, direction));
188223 }
189224
@@ -194,9 +229,10 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
194229 if (method === "POST" && parts.length === 5 && parts[4] === "cards") {
195230 const data = await form(request);
196231 const title = cleanText(data.get("title"), 200);
197 if (!title) return bad("a card needs a title");
232 if (!title) return boardBad(request, who, boardId, "a card needs a title");
198233 const card = db.createCard(boardId, columnId, title);
199 return doneTouch(request, boardId, card !== null, card ? { id: card.id } : {});
234 if (card === "full") return boardBad(request, who, boardId, `this board is full — ${MAX_CARDS_PER_BOARD} cards`);
235 return doneTouch(request, boardId, card !== "not_found", card !== "not_found" ? { id: card.id } : {});
200236 }
201237 }
202238
@@ -207,7 +243,7 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
207243 if (method === "POST" && parts.length === 4) {
208244 const data = await form(request);
209245 const title = cleanText(data.get("title"), 200);
210 if (!title) return bad("a card needs a title");
246 if (!title) return boardBad(request, who, boardId, "a card needs a title");
211247 return doneTouch(request, boardId, db.editCard(boardId, cardId, title));
212248 }
213249
@@ -215,8 +251,8 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
215251 const data = await form(request);
216252 const columnId = String(data.get("column_id") ?? "");
217253 const index = Number(data.get("index"));
218 if (!ENTITY_ID.test(columnId)) return bad("column_id is required");
219 if (!Number.isFinite(index) || index < 0) return bad("index must be a non-negative number");
254 if (!ENTITY_ID.test(columnId)) return boardBad(request, who, boardId, "column_id is required");
255 if (!Number.isFinite(index) || index < 0) return boardBad(request, who, boardId, "index must be a non-negative number");
220256 return doneTouch(request, boardId, db.moveCard(boardId, cardId, columnId, Math.floor(index)));
221257 }
222258
src/server.test.ts +59
@@ -8,6 +8,8 @@ process.env.PORT = "0";
88 process.env.FORGE_APP_IDENTITY_KEY = "test-key";
99 const { server } = await import("./server.ts");
1010 const { sign } = await import("./who.ts");
11 const { MAX_CARDS_PER_BOARD, MAX_COLUMNS_PER_BOARD } = await import("./limits.ts");
12 const db = await import("./db.ts");
1113 const KEY = "test-key";
1214 const identityHeaders = (id: string, name: string, role: "user" | "admin" = "user") => {
1315 const identity = `${id}|${name}|${role}|${Date.now() + 60_000}`;
@@ -378,6 +380,63 @@ test("the MCP server lists its tools and calls add_card as JSON-RPC", async () =
378380 expect(missing.error.code).toBe(-32602);
379381 });
380382
383 test("a board cannot grow past its column limit, and the board is left unchanged", async () => {
384 const id = await newBoard();
385 const boardUrl = `/b/${id}`;
386 for (let count = 3; count < MAX_COLUMNS_PER_BOARD; count++) {
387 const created = await post(`${boardUrl}/columns`, { name: `Column ${count}` });
388 expect(created.status).toBe(200);
389 }
390 const before = await (await fetch(base + boardUrl)).text();
391
392 const refused = await post(`${boardUrl}/columns`, { name: "One too many" });
393 expect(refused.status).toBe(400);
394 expect(await refused.text()).toContain(`${MAX_COLUMNS_PER_BOARD} columns`);
395
396 const after = await (await fetch(base + boardUrl)).text();
397 expect(after).toBe(before);
398 });
399
400 test("the same column-limit refusal, hit without JavaScript, re-renders the board with the sentence already in it", async () => {
401 // Built directly against db.ts, not POST /boards: the board-creation
402 // bucket is shared, process-wide state (see limits.ts), and every test
403 // file in this suite runs against the same one — spending a token here
404 // for a test that has nothing to do with that bucket would just narrow
405 // the margin left for the tests that do exercise board creation.
406 const id = db.createBoard("No-JS board").id;
407 const boardUrl = `/b/${id}`;
408 for (let count = 3; count < MAX_COLUMNS_PER_BOARD; count++) {
409 const created = await post(`${boardUrl}/columns`, { name: `Column ${count}` });
410 expect(created.status).toBe(200);
411 }
412
413 // No `accept: application/json` — a plain browser form submit, the way
414 // the "Add column" form actually works (it isn't intercepted by board.js).
415 const refused = await post(`${boardUrl}/columns`, { name: "One too many" }, { "content-type": "application/x-www-form-urlencoded" });
416 expect(refused.status).toBe(400);
417 expect(refused.headers.get("content-type")).toContain("text/html");
418 const body = await refused.text();
419 expect(body).toContain(`${MAX_COLUMNS_PER_BOARD} columns`);
420 expect(body).toContain("No-JS board"); // the board itself, not a bare error page
421 expect(body).toContain('id="toast" role="status" aria-live="polite" class="show"');
422 });
423
424 test("a board cannot grow past its card limit; the AJAX path gets the sentence back to toast, not a generic message", async () => {
425 const id = db.createBoard("Full of cards").id; // see the note above on why not POST /boards
426 const columnId = db.listColumns(id)[0].id;
427 for (let i = 0; i < MAX_CARDS_PER_BOARD; i++) db.createCard(id, columnId, `c${i}`);
428
429 const refused = await post(`/b/${id}/columns/${columnId}/cards`, { title: "one too many" });
430 expect(refused.status).toBe(400);
431 const data = await refused.json();
432 expect(data.error).toContain(`${MAX_CARDS_PER_BOARD} cards`);
433 });
434
435 test("refuses a request body larger than the size cap before parsing it", async () => {
436 const response = await post("/boards", { name: "x".repeat(100_000) });
437 expect(response.status).toBe(413);
438 });
439
381440 test("a POST with the wrong content-type is refused before formData() runs, and the server keeps answering", async () => {
382441 const response = await fetch(base + "/boards", {
383442 method: "POST",
src/server.ts +10 −1
@@ -8,6 +8,7 @@
88
99 import { join } from "node:path";
1010 import "./db.ts";
11 import { MAX_REQUEST_BODY_BYTES } from "./limits.ts";
1112 import { route } from "./routes.ts";
1213 import { who } from "./who.ts";
1314
@@ -54,7 +55,15 @@ export const server = Bun.serve({
5455 development: false,
5556 async fetch(request) {
5657 const url = new URL(request.url);
57 if (request.method === "POST" && !sameOrigin(request)) return withFloor(new Response("forbidden", { status: 403 }));
58 if (request.method === "POST") {
59 // Cheap and early: a body this large is refused by its declared
60 // length, before anything reads it into memory. A request with no
61 // content-length (chunked) falls through to each handler's own
62 // field-length limits instead.
63 const length = Number(request.headers.get("content-length") ?? "0");
64 if (length > MAX_REQUEST_BODY_BYTES) return withFloor(new Response("request body too large", { status: 413 }));
65 if (!sameOrigin(request)) return withFloor(new Response("forbidden", { status: 403 }));
66 }
5867
5968 // A HEAD answers exactly like the matching GET, minus the body: route
6069 // and serve as GET, then strip the body but keep status and headers.
src/tty.ts +7 −2
@@ -6,6 +6,7 @@
66 */
77
88 import * as db from "./db.ts";
9 import { MAX_CARDS_PER_BOARD, MAX_COLUMNS_PER_BOARD } from "./limits.ts";
910
1011 const esc = "\x1b[";
1112 const out = (s: string): void => {
@@ -159,7 +160,9 @@ function handleBoardKey(key: string): void {
159160 cardCursor = Math.max(0, cardCursor - 1);
160161 } else if (key === "a" && column) {
161162 startPrompt("New card", "", (title) => {
162 if (title) db.createCard(boardId!, column.id, title);
163 if (!title) return;
164 const result = db.createCard(boardId!, column.id, title);
165 if (result === "full") message = `this board is full — ${MAX_CARDS_PER_BOARD} cards`;
163166 });
164167 } else if (key === "e" && card) {
165168 startPrompt("Edit card", card.title, (title) => {
@@ -187,7 +190,9 @@ function handleBoardKey(key: string): void {
187190 cardCursor = index;
188191 } else if (key === "c") {
189192 startPrompt("New column", "", (name) => {
190 if (name) db.createColumn(boardId!, name);
193 if (!name) return;
194 const result = db.createColumn(boardId!, name);
195 if (result === "full") message = `this board is full — ${MAX_COLUMNS_PER_BOARD} columns`;
191196 });
192197 } else if (key === "r" && column) {
193198 startPrompt("Rename column", column.name, (name) => {
static/board.519253746.js → static/board.2031175319.js renamed +5 −4
@@ -213,15 +213,16 @@
213213 columnEl.querySelector(".cards").appendChild(li);
214214 updateCounts();
215215 post(`/b/${boardId}/columns/${columnId}/cards`, { title })
216 .then((r) => (r.ok ? r.json() : Promise.reject()))
217 .then((data) => {
216 .then(async (r) => {
217 const data = await r.json();
218 if (!r.ok) throw new Error(data.error || "Could not add the card.");
218219 li.dataset.cardId = data.id;
219220 for (const el of li.querySelectorAll("[action]")) el.action = el.action.replace(tempId, data.id);
220221 })
221 .catch(() => {
222 .catch((err) => {
222223 li.remove();
223224 updateCounts();
224 showError("Could not add the card.");
225 showError(err.message || "Could not add the card.");
225226 });
226227 }
227228 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs