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

Boards belong to a person: a guest's board lives in their browser and is kept by signing in #35

Merged opened this

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

Merged

scout/tempo:scout/11-boards-belong-to-a-person-a-guest-s-boar → main 3 commits fork 6 threads · 6 unresolved

  • Merged. scout/11-boards-belong-to-a-person-a-guest-s-boar was merged into main as 8be902e.

Review

Sign in to review this change.
8 files changed +265 −24
README.md +28 −10
@@ -23,6 +23,17 @@ FORGE_APP_DATA=./data bun run src/tty.ts # the terminal interface
2323 existing guest board gets a "Keep this board" button that adds it to
2424 your list the first time anyone signed in presses it. It never
2525 changes hands after that.
26 - **A guest's boards** live in that browser only: `static/boards.js`
27 remembers, in `localStorage`, every board id (and name) you've opened
28 as a guest, and lists them on `/` with a note that they're local to
29 this browser and a Sign in link. It only records a visit made as a
30 guest, so signing out on a shared machine never leaves the next
31 anonymous visitor looking at someone else's board links; `/` lists
32 that same local set for a signed-in person too (labelled as not
33 necessarily theirs), so a board someone else owns that they merely
34 opened doesn't just disappear. Signing in doesn't move a board into
35 your kept list by itself — open one and press "Keep this board" to
36 add it for good.
2637 - **Cards**: type a title and press Enter to save it; drag a card to
2738 reorder or move it between columns, or focus it (click, or Tab) and
2839 press the arrow keys — the keyboard does everything dragging does.
@@ -73,10 +84,14 @@ background, reverting if it fails.
7384 letter-key scheme (`j/k/h/l` move, `H/J/K/L` move the focused card,
7485 `a`/`e`/`d` add/edit/delete, `c`/`r`/`D` add/rename/delete a column,
7586 `f` filter, `u` undo) rather than drag-and-drop, since a terminal has
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.
87 no mouse. An ssh session has no verified identity the way a browser's
88 `x-forge-identity` header does, so the terminal can't tell who's
89 typing: its board picker lists only unowned boards, and a board it
90 creates is unowned too, same as a guest's on the web. `o` opens a
91 board by id, the same way a shared link works on the page, so a kept
92 board someone hands you is still reachable. It has no "keep this
93 board" — ownership only ever changes through the web, where it can be
94 attributed to someone.
8095 - The event stream is this one process's: the terminal is a separate
8196 process on the same database, so a change made there shows up on the
8297 next page load, not live.
@@ -113,13 +128,16 @@ The forge sets `PORT`, `FORGE_APP_DATA`, `FORGE_APP_ENV`
113128 `FORGE_APP_IDENTITY_KEY` when it starts the app. `forge.json` says how.
114129 Identity comes only from `x-forge-identity` / `x-forge-signature`,
115130 verified against `FORGE_APP_IDENTITY_KEY` (`src/who.ts`); unset, everyone
116 is anonymous.
131 is anonymous. The terminal has no such header, and nothing else in this
132 repository names who is at the other end of an ssh session, so it never
133 claims an identity: every board it creates is a guest's, same as an
134 anonymous browser's.
117135
118136 ## Dependencies
119137
120138 The app itself has none. `happy-dom` is a dev-only dependency, used by
121 `src/drag.test.ts` (and `src/theme.test.ts`) to give `static/board.js` a
122 real DOM outside a browser so its dragstart/dragover/drop/dragend
123 handlers run against real events — hand-rolling that much of the DOM to
124 test a few dozen lines of drag handling would be more code, and less
125 trustworthy, than the thing it's testing.
139 `src/drag.test.ts` (and `src/theme.test.ts`, `src/boards.test.ts`) to give
140 `static/board.js` and `static/boards.js` a real DOM outside a browser so
141 their event handlers and `localStorage` calls run against the real thing
142 — hand-rolling that much of the DOM to test a few dozen lines of script
143 would be more code, and less trustworthy, than the thing it's testing.
src/boards.test.ts added +98
@@ -0,0 +1,98 @@
1 /**
2 * Drives static/boards.js the way a browser would: a real DOM (happy-dom)
3 * and its real localStorage, against the real server's HTML — a guest's
4 * board list lives only there, never in a request the server can read.
5 */
6 import { expect, test } from "bun:test";
7 import { Window } from "happy-dom";
8 import { mkdtempSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11
12 process.env.FORGE_APP_DATA = mkdtempSync(join(tmpdir(), "app-"));
13 process.env.PORT = "0";
14 process.env.FORGE_APP_IDENTITY_KEY = "test-key";
15 const { server } = await import("./server.ts");
16 const { sign } = await import("./who.ts");
17 const db = await import("./db.ts");
18 const KEY = "test-key";
19 const identityHeaders = (id: string, name: string) => {
20 const identity = `${id}|${name}|user|${Date.now() + 60_000}`;
21 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
22 };
23 const base = `http://${server.hostname}:${server.port}`;
24
25 async function run(html: string, localStorage: Storage): Promise<Document> {
26 const [, scriptSrc] = html.match(/<script src="(\/static\/boards[^"]+)"/)!;
27 const script = await (await fetch(base + scriptSrc)).text();
28 const window = new Window({ url: base + "/" });
29 const document = window.document;
30 document.open();
31 document.write(html);
32 document.close();
33 new Function("document", "localStorage", script)(document, localStorage);
34 const doc = document as unknown as Document;
35 await window.close();
36 return doc;
37 }
38
39 // Built directly against db.ts, not POST /boards: the board-creation
40 // throttle is process-wide (see limits.ts), and this file alone would
41 // otherwise spend a third of its budget just seeding boards.
42 test("visiting a board records its id and name in the browser's own storage, not the server's", async () => {
43 const id = db.createBoard("Kept locally").id;
44 const html = await (await fetch(base + `/b/${id}`)).text();
45
46 const window = new Window({ url: base + `/b/${id}` });
47 await run(html, window.localStorage as unknown as Storage);
48 const stored = JSON.parse(window.localStorage.getItem("tempo-boards")!);
49 expect(stored).toEqual([{ id, name: "Kept locally" }]);
50 await window.close();
51 });
52
53 test("a guest's landing page renders the boards this browser has visited, from that storage", async () => {
54 const id = db.createBoard("Guest board").id;
55 const landing = await (await fetch(base + "/")).text();
56 expect(landing).toContain('id="guest-boards"');
57
58 const window = new Window({ url: base + "/" });
59 window.localStorage.setItem("tempo-boards", JSON.stringify([{ id, name: "Guest board" }]));
60 const doc = await run(landing, window.localStorage as unknown as Storage);
61 const link = doc.querySelector(`#guest-boards a[href="/b/${id}"]`);
62 expect(link?.textContent).toBe("Guest board");
63 await window.close();
64 });
65
66 test("a signed-in visit is never recorded in this browser's storage — only a guest's is", async () => {
67 const id = db.createBoard("Someone else's").id;
68 const html = await (await fetch(base + `/b/${id}`, { headers: identityHeaders("u1", "Alice") })).text();
69 expect(html).not.toContain("data-guest");
70
71 const window = new Window({ url: base + `/b/${id}` });
72 await run(html, window.localStorage as unknown as Storage);
73 expect(window.localStorage.getItem("tempo-boards")).toBeNull();
74 await window.close();
75 });
76
77 test("a signed-in person's landing page also renders this browser's local list, labelled as not necessarily theirs", async () => {
78 const id = db.createBoard("Someone else's").id;
79 const landing = await (await fetch(base + "/", { headers: identityHeaders("u1", "Alice") })).text();
80 expect(landing).toContain('id="guest-boards"');
81
82 const window = new Window({ url: base + "/" });
83 window.localStorage.setItem("tempo-boards", JSON.stringify([{ id, name: "Someone else's" }]));
84 const doc = await run(landing, window.localStorage as unknown as Storage);
85 const link = doc.querySelector(`#guest-boards a[href="/b/${id}"]`);
86 expect(link?.textContent).toBe("Someone else's");
87 await window.close();
88 });
89
90 test("malformed storage never blanks the page — the guest list is just empty", async () => {
91 const landing = await (await fetch(base + "/")).text();
92 const window = new Window({ url: base + "/" });
93 window.localStorage.setItem("tempo-boards", "{not json");
94 const doc = await run(landing, window.localStorage as unknown as Storage);
95 expect(doc.getElementById("guest-boards")).not.toBeNull();
96 expect(doc.querySelectorAll("#guest-boards a").length).toBe(0);
97 await window.close();
98 });
src/db.test.ts +16
@@ -95,6 +95,22 @@ test("undo returns false with nothing to undo", () => {
9595 expect(db.undo("no-such-board")).toBe(false);
9696 });
9797
98 test("listBoardsForOwner is a person's own boards plus unowned ones, never another person's", () => {
99 const mine = db.createBoard("Mine", { id: "u1", name: "Alice" });
100 const unowned = db.createBoard("Unowned");
101 const theirs = db.createBoard("Theirs", { id: "u2", name: "Bob" });
102
103 const visibleToAlice = db.listBoardsForOwner("u1").map((b) => b.id);
104 expect(visibleToAlice).toContain(mine.id);
105 expect(visibleToAlice).toContain(unowned.id);
106 expect(visibleToAlice).not.toContain(theirs.id);
107
108 const visibleToGuest = db.listBoardsForOwner(null).map((b) => b.id);
109 expect(visibleToGuest).toContain(unowned.id);
110 expect(visibleToGuest).not.toContain(mine.id);
111 expect(visibleToGuest).not.toContain(theirs.id);
112 });
113
98114 // Simulates the ssh terminal and the web server as two separate processes
99115 // writing the same file at once: a second handle takes the write lock and
100116 // holds it while the module's own moveCard (a read-then-write) is asked to
src/db.ts +11 −4
@@ -123,15 +123,22 @@ export function createBoard(name: string, owner?: { id: string; name: string }):
123123 }).immediate();
124124 }
125125
126 export function listBoards(): Board[] {
127 return db.query<Board, []>(`SELECT ${BOARD_FIELDS} FROM board ORDER BY created_at DESC`).all();
128 }
129
130126 /** The boards a signed-in person has kept — see `claimBoard`. */
131127 export function listBoardsByOwner(ownerId: string): Board[] {
132128 return db.query<Board, [string]>(`SELECT ${BOARD_FIELDS} FROM board WHERE owner_id = ?1 ORDER BY created_at DESC`).all(ownerId);
133129 }
134130
131 // The terminal's board picker (src/tty.ts): the same rule the web page's
132 // `/` follows — a person's own boards plus anyone's unowned ones, never
133 // another person's. `ownerId` null (no FORGE_APP_USER) is a guest: only
134 // the unowned boards.
135 export function listBoardsForOwner(ownerId: string | null): Board[] {
136 if (ownerId === null) return db.query<Board, []>(`SELECT ${BOARD_FIELDS} FROM board WHERE owner_id IS NULL ORDER BY created_at DESC`).all();
137 return db
138 .query<Board, [string]>(`SELECT ${BOARD_FIELDS} FROM board WHERE owner_id = ?1 OR owner_id IS NULL ORDER BY created_at DESC`)
139 .all(ownerId);
140 }
141
135142 export function getBoard(id: string): Board | null {
136143 return db.query<Board, [string]>(`SELECT ${BOARD_FIELDS} FROM board WHERE id = ?1`).get(id);
137144 }
src/pages/board.ts +24 −7
@@ -126,13 +126,27 @@ function doorLink(who: Who, path: string): string {
126126 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>`;
127127 }
128128
129 // A guest has no owned boards to list — the ones they've opened live only
130 // in their browser (static/boards.js reads and renders them into
outdated

Low — a signed-in person loses shared boards entirely.

This branch renders #guest-boards only for anon, while the server list above is owned-only. Open a board someone else owns while signed in and it appears nowhere on /: not in the kept list (you don't own it), not in the local list (not rendered for you). With the data-guest gate from the boards.js comment, the local list would hold only unowned boards, so rendering it for everyone under something like "Opened in this browser" would close that gap safely. Your call — but the direction's "shared by link" flow currently has no history for the signed-in half of it.

131 // #guest-boards from localStorage; the server never sees that list). A
132 // signed-in person's own boards come from the server above, but a board
133 // someone else owns that they merely opened isn't in that list either, so
134 // the same local list is rendered for them too — it only ever holds boards
135 // visited as a guest (boards.js only writes to it then), so it can't leak
136 // another signed-in person's boards onto this one's page.
129137 export function landingPage(env: string, who: Who, boards: Board[], error?: string): string {
138 const guestBoardsDiv = `<div id="guest-boards"></div>`;
130139 const list =
131140 who.role === "anon"
132 ? ""
133 : boards.length === 0
134 ? `<p class="hint">Boards you keep will be listed here.</p>`
135 : `<ul class="boards">${boards.map((b) => `<li><a href="/b/${b.id}">${escape(b.name)}</a></li>`).join("")}</ul>`;
141 ? `<p class="hint">Boards you've opened live in this browser only. <a href="/__forge/signin?to=/">Sign in</a> to keep them.</p>
142 ${guestBoardsDiv}`
143 : `${
144 boards.length === 0
145 ? `<p class="hint">Boards you keep will be listed here.</p>`
146 : `<ul class="boards">${boards.map((b) => `<li><a href="/b/${b.id}">${escape(b.name)}</a></li>`).join("")}</ul>`
147 }
148 <p class="hint">Also opened in this browser as a guest, not necessarily yours:</p>
149 ${guestBoardsDiv}`;
136150 return shell(
137151 "tempo",
138152 `<header class="top"><h1>tempo</h1><span class="env">${escape(env)}</span>${doorLink(who, "/")}</header>
@@ -141,7 +155,8 @@ export function landingPage(env: string, who: Who, boards: Board[], error?: stri
141155 <input name="name" placeholder="Board name" maxlength="100" autofocus>
142156 <button>Create board</button>
143157 </form>
144 ${list}`,
158 ${list}
159 <script src="/static/${BOARDS_JS}" defer></script>`,
145160 [],
146161 error,
147162 );
@@ -215,7 +230,7 @@ export function boardPage({ board, columns, cards, query, who, error }: BoardDat
215230
216231 return shell(
217232 board.name,
218 `<div data-board="${escape(board.id)}">
233 `<div data-board="${escape(board.id)}"${who.role === "anon" ? " data-guest" : ""}>
219234 <header class="top">
220235 <h1>tempo</h1>
221236 <form method="post" action="/b/${board.id}/rename">
@@ -244,7 +259,8 @@ export function boardPage({ board, columns, cards, query, who, error }: BoardDat
244259 </section>
245260 </div>
246261 </div>
247 <script src="/static/${BOARD_JS}" defer></script>`,
262 <script src="/static/${BOARD_JS}" defer></script>
263 <script src="/static/${BOARDS_JS}" defer></script>`,
248264 boardShortcuts,
249265 error,
250266 );
@@ -261,3 +277,4 @@ const boardShortcuts: [string, string][] = [
261277 // so the year-long cache on /static/ never serves a stale script.
262278 export const BOARD_JS = "board.2031175319.js";
263279 export const THEME_JS = "theme.1025564933.js";
280 export const BOARDS_JS = "boards.608180649.js";
src/server.test.ts +12
@@ -313,6 +313,18 @@ test("a guest's board is kept by the first signed-in person to claim it, and sta
313313 expect(aliceList).toContain(boardUrl);
314314 });
315315
316 test("a board's link still edits it for someone who does not own it — sharing is unaffected by ownership", async () => {
317 const id = await newBoard();
318 const boardUrl = `/b/${id}`;
319 await fetch(base + `${boardUrl}/claim`, { method: "POST", headers: identityHeaders("u1", "alice") });
320
321 const page = await (await fetch(base + boardUrl, { headers: identityHeaders("u2", "bob") })).text();
322 const [, columnId] = page.match(/data-column-id="([a-z0-9]{12})"/)!;
323 const created = await post(`${boardUrl}/columns/${columnId}/cards`, { title: "Bob added this" }, { ...j, ...identityHeaders("u2", "bob") });
324 expect(created.status).toBe(200);
325 expect(await (await fetch(base + boardUrl)).text()).toContain("Bob added this");
326 });
327
316328 test("streams a live event over /events when a card moves, so another tab can catch up", async () => {
317329 const id = await newBoard();
318330 const boardUrl = `/b/${id}`;
src/tty.ts +25 −3
@@ -8,6 +8,15 @@
88 import * as db from "./db.ts";
99 import { MAX_CARDS_PER_BOARD, MAX_COLUMNS_PER_BOARD } from "./limits.ts";
1010
11 // The terminal has no verified identity — nothing here plays the part of
12 // the forge's signed x-forge-identity header — so it can't tell who is
13 // typing and must not mint ownership on their behalf. A board it creates
outdated

p

outdated

x

14 // is unowned, exactly like a guest's on the web; the picker lists only
outdated

High — this writes ownership from an identity nothing verifies, with a key the web can never match.

Everywhere else in this app a board's owner is who.id: the first field of x-forge-identity, an opaque user id (src/who.ts). Here owner is { id: FORGE_APP_USER, name: FORGE_APP_USER } — the same string for both, and FORGE_APP_USER is at best the username (the identity header's second field).

So a board created in the terminal gets owner_id = 'alice'. That same person, signed in on the web, is 01m1wz…: the board is not in their / list, the page says Kept by alice, and POST /b/:id/claim answers 403 already kept by someone else — there is no unclaim, so that row is stranded for good. This is the one to fix first.

Concretely: pass no owner here (db.createBoard(name), as before), so the terminal can never mint a row the web can't reconcile. If you do want terminal ownership, it has to key on the same value as who.id and the pull needs to say where that is documented — nothing else in this repository mentions FORGE_APP_USER, and there is no test that pins what the terminal hands to listBoardsForOwner with the variable set and unset.

15 // unowned boards, and a kept board is reached by its id (press o), the
16 // same way a shared link works on the page.
17 const visibleBoards = (): db.Board[] => db.listBoardsForOwner(null);
18 const boardIdRe = /^[a-z0-9]{8}$/;
19
1120 const esc = "\x1b[";
1221 const out = (s: string): void => {
1322 process.stdout.write(s);
@@ -40,7 +49,7 @@ function startPrompt(label: string, value: string, onSubmit: (text: string) => v
4049 function draw(): void {
4150 const lines: string[] = [];
4251 if (mode === "boards") {
43 const boards = db.listBoards();
52 const boards = visibleBoards();
4453 lines.push(`${esc}1mtempo${esc}0m ${esc}2mpick a board${esc}0m`);
4554 lines.push("");
4655 if (boards.length === 0) lines.push(`${esc}2mNo boards yet. Press n to create one.${esc}0m`);
@@ -50,7 +59,11 @@ function draw(): void {
5059 lines.push(`${mark} ${name} ${esc}2m/b/${b.id}${esc}0m`);
5160 });
5261 lines.push("");
53 lines.push(prompt ? `${prompt.label}: ${prompt.value}${esc}7m ${esc}0m` : `${esc}2mj/k move · enter open · n new board · q quit${esc}0m`);
62 lines.push(
63 prompt
64 ? `${prompt.label}: ${prompt.value}${esc}7m ${esc}0m`
65 : `${esc}2mj/k move · enter open · n new board · o open by id · q quit${esc}0m`,
66 );
5467 } else {
5568 const board = db.getBoard(boardId!)!;
5669 const columns = db.listColumns(boardId!);
@@ -113,7 +126,7 @@ function handlePromptKey(key: string): void {
113126 }
114127
115128 function handleBoardsKey(key: string): void {
116 const boards = db.listBoards();
129 const boards = visibleBoards();
117130 if (key === "j" || key === "\x1b[B") boardsCursor = Math.min(boardsCursor + 1, Math.max(0, boards.length - 1));
118131 else if (key === "k" || key === "\x1b[A") boardsCursor = Math.max(boardsCursor - 1, 0);
119132 else if (key === "n") startPrompt("New board name", "", (name) => {
@@ -123,6 +136,15 @@ function handleBoardsKey(key: string): void {
123136 columnCursor = 0;
124137 cardCursor = 0;
125138 });
139 else if (key === "o") startPrompt("Open board id", "", (text) => {
140 const found = boardIdRe.test(text) ? db.getBoard(text) : null;
141 if (!found) return;
142 boardId = found.id;
143 mode = "board";
144 columnCursor = 0;
145 cardCursor = 0;
146 filter = "";
147 });
126148 else if (key === "\r" && boards[boardsCursor]) {
127149 boardId = boards[boardsCursor].id;
128150 mode = "board";
static/boards.608180649.js added +51
@@ -0,0 +1,51 @@
1 // A guest's boards live only in this browser. On a board page this records
2 // the board's id and current name; on the landing page it renders that list
3 // (a guest's `/` has no owned boards to server-render — see landingPage).
4 (() => {
5 "use strict";
6 const KEY = "tempo-boards";
7 const MAX = 50;
8
9 function readList() {
10 try {
11 const parsed = JSON.parse(localStorage.getItem(KEY) || "[]");
12 return Array.isArray(parsed) ? parsed.filter((b) => b && typeof b.id === "string" && typeof b.name === "string") : [];
13 } catch {
14 return [];
15 }
16 }
17 function writeList(list) {
18 try {
19 localStorage.setItem(KEY, JSON.stringify(list.slice(0, MAX)));
20 } catch {
21 // A private-browsing tab may refuse storage; the list just won't
22 // survive a reload, which is a fine fallback for a memory aid.
23 }
24 }
25
26 const board = document.querySelector("[data-board]");
27 if (board && board.dataset.guest !== undefined) {
28 const id = board.dataset.board;
29 const nameInput = board.querySelector('input[name="name"]');
30 const name = nameInput ? nameInput.value : id;
31 writeList([{ id, name }, ...readList().filter((b) => b.id !== id)]);
32 }
33
34 const container = document.getElementById("guest-boards");
35 if (container) {
36 const list = readList();
37 if (list.length > 0) {
38 const ul = document.createElement("ul");
39 ul.className = "boards";
40 for (const b of list) {
41 const li = document.createElement("li");
42 const a = document.createElement("a");
43 a.href = `/b/${encodeURIComponent(b.id)}`;
44 a.textContent = b.name;
45 li.appendChild(a);
46 ul.appendChild(li);
47 }
48 container.replaceChildren(ul);
49 }
50 }
51 })();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs