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

The template's notes scaffold is gone, so every door is about deals #8

Merged opened this

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

Merged

mason/deal-clock:mason/7-the-template-s-notes-scaffold-is-gone-so → main 3 commits fork

  • Merged. mason/7-the-template-s-notes-scaffold-is-gone-so was merged into main as ab2ee77.

Review

Sign in to review this change.
17 files changed +115 −796
AGENTS.md +1 −1
@@ -30,7 +30,7 @@ preview at its own address, deployed from your branch as you push.
3030
3131 One implementation, many doors. Every operation is a function in
3232 `src/deals.ts` (deals, their dates, parties and reminders) or
33 `src/actions.ts` (notes, the audit trail) — `(db, who, input)` in, data or
33 `src/actions.ts` (the audit trail) — `(db, who, input)` in, data or
3434 a named failure out, shaped by `src/result.ts` — and
3535 the pages (`src/routes.ts`, `src/pages/`), the JSON API (`src/routes.ts`),
3636 the MCP server (`src/mcp.ts`) and the terminal (`src/tty.ts`) call it. A
README.md +6 −5
@@ -110,7 +110,7 @@ decide nothing themselves. `AGENTS.md` says how to add to it.
110110 | `src/reminders.ts`, `src/ics.ts` | reminder drafts and `/tick`; the calendar file |
111111 | `src/sample.ts` | the four sample deals a new database starts with |
112112 | `src/result.ts` | what an action answers, and the audit habit they share |
113 | `src/actions.ts` | notes (the API scaffold); the audit trail, read |
113 | `src/actions.ts` | the audit trail, read |
114114 | `contract.json` | who may do what: roles, and the least role each verb needs |
115115 | `src/contract.ts`, `src/can.ts` | the table, read at boot; the forge's evaluator, verbatim |
116116 | `src/security.ts` | the door: rationing, same origin, the table before the body |
@@ -143,6 +143,8 @@ decide nothing themselves. `AGENTS.md` says how to add to it.
143143 - **The API, described.** `GET /openapi.json` is `contract/openapi.json`,
144144 written from the routes by `bun run contract:emit`; each operation names
145145 its cell of the table (`x-contract`). `bun test` fails while it is stale.
146 It needs a signed-in user: no door of the table is open to a stranger, and
147 the description is shut to them when none is.
146148 - **Up, or not.** `GET /healthz` answers `{ ok, version, uptime }`; the
147149 forge waits on it before it sends anyone to a deploy.
148150 - **The look.** `design/tokens.json` holds every colour, space and size,
@@ -162,8 +164,8 @@ verifies the signature (`src/who.ts`); nothing else is trusted. Three tiers:
162164 - **user** — signed in to the forge and able to see this app. Reads every
163165 deal, its parties and their contacts. Opens deals,
164166 marks dates done, moves them, adds dates and parties, sends reminders;
165 removes the deals they opened (and their own notes).
166 - **admin** — able to write this repository. Removes any deal or note.
167 removes the deals they opened.
168 - **admin** — able to write this repository. Removes any deal.
167169
168170 "Sign in" is `/__forge/signin?to=<path>` and "Sign out" is
169171 `/__forge/signout`; the forge answers both on the app's own host, and
@@ -181,8 +183,7 @@ curl -X POST https://<app>/tick
181183 curl https://<app>/deals/1/ics
182184 ```
183185
184 As an MCP server, for Claude Code or Claude Desktop — the deal tools above,
185 and `list_notes`, `add_note`, `delete_note`:
186 As an MCP server, for Claude Code or Claude Desktop — the deal tools:
186187
187188 ```sh
188189 claude mcp add --transport http deal-clock https://<app>/mcp
contract.json −10
@@ -6,16 +6,6 @@
66 "admin": { "above": ["author"], "held": { "by": "identity", "role": "admin" } }
77 },
88 "resources": {
9 "note": {
10 "api": "/api/notes",
11 "can": {
12 "create": "user",
13 "read": "anon",
14 "update": "author",
15 "delete": "author",
16 "list": "anon"
17 }
18 },
199 "deal": {
2010 "api": "/api/deals",
2111 "can": {
contract/openapi.json −287
@@ -50,258 +50,6 @@
5050 }
5151 }
5252 },
53 "/api/notes": {
54 "get": {
55 "summary": "The notes, newest first.",
56 "operationId": "getApiNotes",
57 "parameters": [
58 {
59 "name": "limit",
60 "in": "query",
61 "schema": {
62 "type": "integer",
63 "minimum": 1,
64 "maximum": 500,
65 "default": 100
66 }
67 }
68 ],
69 "responses": {
70 "200": {
71 "description": "The notes, newest first.",
72 "content": {
73 "application/json": {
74 "schema": {
75 "type": "array",
76 "items": {
77 "$ref": "#/components/schemas/Note"
78 }
79 }
80 }
81 }
82 },
83 "default": {
84 "description": "{ error, message }: why not",
85 "content": {
86 "application/json": {
87 "schema": {
88 "$ref": "#/components/schemas/Error"
89 }
90 }
91 }
92 }
93 },
94 "x-contract": {
95 "resource": "note",
96 "verb": "list",
97 "least": "anon"
98 }
99 },
100 "post": {
101 "summary": "Add a note as the person asking.",
102 "operationId": "postApiNotes",
103 "requestBody": {
104 "required": true,
105 "content": {
106 "application/json": {
107 "schema": {
108 "type": "object",
109 "properties": {
110 "body": {
111 "type": "string",
112 "minLength": 1,
113 "maxLength": 500
114 }
115 },
116 "required": [
117 "body"
118 ]
119 }
120 }
121 }
122 },
123 "responses": {
124 "201": {
125 "description": "Add a note as the person asking.",
126 "content": {
127 "application/json": {
128 "schema": {
129 "$ref": "#/components/schemas/Note"
130 }
131 }
132 }
133 },
134 "default": {
135 "description": "{ error, message }: why not",
136 "content": {
137 "application/json": {
138 "schema": {
139 "$ref": "#/components/schemas/Error"
140 }
141 }
142 }
143 }
144 },
145 "x-contract": {
146 "resource": "note",
147 "verb": "create",
148 "least": "user"
149 }
150 }
151 },
152 "/api/notes/{id}": {
153 "get": {
154 "summary": "One note.",
155 "operationId": "getApiNotesId",
156 "parameters": [
157 {
158 "name": "id",
159 "in": "path",
160 "required": true,
161 "schema": {
162 "type": "integer"
163 }
164 }
165 ],
166 "responses": {
167 "200": {
168 "description": "One note.",
169 "content": {
170 "application/json": {
171 "schema": {
172 "$ref": "#/components/schemas/Note"
173 }
174 }
175 }
176 },
177 "default": {
178 "description": "{ error, message }: why not",
179 "content": {
180 "application/json": {
181 "schema": {
182 "$ref": "#/components/schemas/Error"
183 }
184 }
185 }
186 }
187 },
188 "x-contract": {
189 "resource": "note",
190 "verb": "read",
191 "least": "anon"
192 }
193 },
194 "patch": {
195 "summary": "Change a note's words.",
196 "operationId": "patchApiNotesId",
197 "parameters": [
198 {
199 "name": "id",
200 "in": "path",
201 "required": true,
202 "schema": {
203 "type": "integer"
204 }
205 }
206 ],
207 "requestBody": {
208 "required": true,
209 "content": {
210 "application/json": {
211 "schema": {
212 "type": "object",
213 "properties": {
214 "body": {
215 "type": "string",
216 "minLength": 1,
217 "maxLength": 500
218 }
219 },
220 "required": [
221 "body"
222 ]
223 }
224 }
225 }
226 },
227 "responses": {
228 "200": {
229 "description": "Change a note's words.",
230 "content": {
231 "application/json": {
232 "schema": {
233 "$ref": "#/components/schemas/Note"
234 }
235 }
236 }
237 },
238 "default": {
239 "description": "{ error, message }: why not",
240 "content": {
241 "application/json": {
242 "schema": {
243 "$ref": "#/components/schemas/Error"
244 }
245 }
246 }
247 }
248 },
249 "x-contract": {
250 "resource": "note",
251 "verb": "update",
252 "least": "author"
253 }
254 },
255 "delete": {
256 "summary": "Remove a note.",
257 "operationId": "deleteApiNotesId",
258 "parameters": [
259 {
260 "name": "id",
261 "in": "path",
262 "required": true,
263 "schema": {
264 "type": "integer"
265 }
266 }
267 ],
268 "responses": {
269 "200": {
270 "description": "Remove a note.",
271 "content": {
272 "application/json": {
273 "schema": {
274 "type": "object",
275 "properties": {
276 "id": {
277 "type": "integer"
278 }
279 },
280 "required": [
281 "id"
282 ]
283 }
284 }
285 }
286 },
287 "default": {
288 "description": "{ error, message }: why not",
289 "content": {
290 "application/json": {
291 "schema": {
292 "$ref": "#/components/schemas/Error"
293 }
294 }
295 }
296 }
297 },
298 "x-contract": {
299 "resource": "note",
300 "verb": "delete",
301 "least": "author"
302 }
303 }
304 },
30553 "/api/deals": {
30654 "get": {
30755 "summary": "Every deal with its dates, parties and sent reminders, soonest closing first.",
@@ -803,41 +551,6 @@
803551 },
804552 "components": {
805553 "schemas": {
806 "Note": {
807 "type": "object",
808 "properties": {
809 "id": {
810 "type": "integer"
811 },
812 "body": {
813 "type": "string",
814 "minLength": 1,
815 "maxLength": 500
816 },
817 "author_id": {
818 "type": "string"
819 },
820 "author_name": {
821 "type": "string"
822 },
823 "created_at": {
824 "type": "string",
825 "format": "date-time"
826 },
827 "updated_at": {
828 "type": "string",
829 "format": "date-time"
830 }
831 },
832 "required": [
833 "id",
834 "body",
835 "author_id",
836 "author_name",
837 "created_at",
838 "updated_at"
839 ]
840 },
841554 "Deal": {
842555 "type": "object",
843556 "properties": {
src/actions.test.ts deleted −58
@@ -1,58 +0,0 @@
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 { addNote, deleteNote, listNotes } from "./actions.ts";
6 import { openDb } from "./db.ts";
7 import type { Who } from "./who.ts";
8
9 const db = openDb(mkdtempSync(join(tmpdir(), "app-actions-")));
10 const anon: Who = { role: "anon" };
11 const alice: Who = { role: "user", id: "u1", name: "alice" };
12 const bob: Who = { role: "user", id: "u2", name: "bob" };
13 const root: Who = { role: "admin", id: "u0", name: "root" };
14
15 test("anyone reads; only a signed-in person adds, as themselves", () => {
16 expect(listNotes(db, anon)).toEqual({ ok: true, value: [] });
17 const refused = addNote(db, anon, { body: "hello" });
18 expect(refused.ok).toBe(false);
19 if (!refused.ok) expect(refused.error).toBe("signin_required");
20 const added = addNote(db, alice, { body: " hello " });
21 expect(added.ok).toBe(true);
22 if (!added.ok) return;
23 expect(added.value.body).toBe("hello");
24 expect(added.value.author_id).toBe("u1");
25 expect(added.value.author_name).toBe("alice");
26 const all = listNotes(db, anon);
27 expect(all.ok && all.value.length).toBe(1);
28 });
29
30 test("a note is one to five hundred characters", () => {
31 for (const body of ["", " ", "x".repeat(501)]) {
32 const r = addNote(db, alice, { body });
33 expect(r.ok).toBe(false);
34 if (!r.ok) expect(r.error).toBe("invalid");
35 }
36 });
37
38 test("only the author or an admin removes a note", () => {
39 const mine = addNote(db, alice, { body: "mine" });
40 if (!mine.ok) throw new Error(mine.message);
41 const byBob = deleteNote(db, bob, { id: mine.value.id });
42 expect(byBob.ok).toBe(false);
43 if (!byBob.ok) expect(byBob.error).toBe("forbidden");
44 const byAnon = deleteNote(db, anon, { id: mine.value.id });
45 expect(byAnon.ok).toBe(false);
46 if (!byAnon.ok) expect(byAnon.error).toBe("signin_required");
47 expect(deleteNote(db, alice, { id: mine.value.id }).ok).toBe(true);
48 const gone = deleteNote(db, alice, { id: mine.value.id });
49 expect(gone.ok).toBe(false);
50 if (!gone.ok) expect(gone.error).toBe("not_found");
51
52 const bobs = addNote(db, bob, { body: "bob's" });
53 if (!bobs.ok) throw new Error(bobs.message);
54 expect(deleteNote(db, root, { id: bobs.value.id }).ok).toBe(true);
55 const odd = deleteNote(db, root, { id: 1.5 });
56 expect(odd.ok).toBe(false);
57 if (!odd.ok) expect(odd.error).toBe("invalid");
58 });
src/actions.ts +1 −162
@@ -9,172 +9,11 @@
99 import type { Database } from "bun:sqlite";
1010 import type { AuditRow } from "./audit.ts";
1111 import { permit } from "./contract.ts";
12 import { emit } from "./live.ts";
13 import { audited, fail, ok, refuse, type Result } from "./result.ts";
12 import { fail, ok, refuse, type Result } from "./result.ts";
1413 import type { Who } from "./who.ts";
1514
1615 export type { Failure, Result } from "./result.ts";
1716
18 export interface Note {
19 readonly id: number;
20 readonly body: string;
21 readonly author_id: string;
22 readonly author_name: string;
23 readonly created_at: string;
24 readonly updated_at: string;
25 }
26
27 export const BODY_MAX = 500;
28
29 export function listNotes(
30 db: Database,
31 who: Who,
32 input: { limit?: number } = {},
33 ): Result<Note[]> {
34 const limit = Math.min(
35 Math.max(Math.trunc(input.limit ?? 100) || 100, 1),
36 500,
37 );
38 // "yes" is every note. When the table gives `list` to a role a row holds
39 // (`author`), the answer names the columns instead, and the list is the
40 // notes that name whoever asks. The names are the contract's, checked when
41 // it was read; the value is bound.
42 const may = permit(who, "note", "list");
43 if (may === "no")
44 return refuse(who, "Sign in to see notes.", "You may not see these notes.");
45 if (may === "yes")
46 return ok(
47 db
48 .query<Note, [number]>("SELECT * FROM note ORDER BY id DESC LIMIT ?1")
49 .all(limit),
50 );
51 const mine = may.where.map((column) => `${column} = ?2`).join(" OR ");
52 return ok(
53 db
54 .query<
55 Note,
56 [number, string]
57 >(`SELECT * FROM note WHERE ${mine} ORDER BY id DESC LIMIT ?1`)
58 .all(limit, who.role === "anon" ? "" : who.id),
59 );
60 }
61
62 export const addNote = (
63 db: Database,
64 who: Who,
65 input: { body: string },
66 ): Result<Note> =>
67 audited(db, who, "note", "create", undefined, add(db, who, input));
68
69 function add(db: Database, who: Who, input: { body: string }): Result<Note> {
70 // The table decides; the type only learns it here: whoever may create is
71 // signed in, and carries a name to write beside the note.
72 if (who.role === "anon" || permit(who, "note", "create") !== "yes")
73 return refuse(who, "Sign in to add a note.", "You may not add a note.");
74 const body = input.body.trim();
75 if (body.length === 0 || body.length > BODY_MAX)
76 return fail("invalid", `A note is 1 to ${BODY_MAX} characters.`);
77 const note = db
78 .query<
79 Note,
80 [string, string, string]
81 >("INSERT INTO note (body, author_id, author_name) VALUES (?1, ?2, ?3) RETURNING *")
82 .get(body, who.id, who.name)!;
83 emit("note.added", note);
84 return ok(note);
85 }
86
87 /**
88 * One note, for `who` to do `verb` to. The door is asked before the row is
89 * looked for, so whoever may not is told that and never learns whether the
90 * row exists; whoever may, and asked for nothing, hears `not_found`.
91 */
92 function noteFor(
93 db: Database,
94 who: Who,
95 verb: "read" | "update" | "delete",
96 id: number,
97 said: { signIn: string; no: string },
98 ): Result<Note> {
99 const note = Number.isInteger(id)
100 ? db.query<Note, [number]>("SELECT * FROM note WHERE id = ?1").get(id)
101 : null;
102 // With no row to show, the door is asked about a row of their own: whoever
103 // could not pass even then is refused, and learns nothing about what
104 // exists; whoever could is told there is no such note.
105 const row: Readonly<Record<string, unknown>> =
106 note === null ? { author_id: who.role === "anon" ? null : who.id } : { ...note };
107 if (permit(who, "note", verb, row) !== "yes")
108 return refuse(who, said.signIn, said.no);
109 if (note !== null) return ok(note);
110 if (!Number.isInteger(id))
111 return fail("invalid", "A note id is a whole number.");
112 return fail("not_found", "No such note.");
113 }
114
115 export function getNote(
116 db: Database,
117 who: Who,
118 input: { id: number },
119 ): Result<Note> {
120 return noteFor(db, who, "read", input.id, {
121 signIn: "Sign in to read this note.",
122 no: "You may not read this note.",
123 });
124 }
125
126 export const updateNote = (
127 db: Database,
128 who: Who,
129 input: { id: number; body: string },
130 ): Result<Note> =>
131 audited(db, who, "note", "update", input.id, update(db, who, input));
132
133 function update(
134 db: Database,
135 who: Who,
136 input: { id: number; body: string },
137 ): Result<Note> {
138 const found = noteFor(db, who, "update", input.id, {
139 signIn: "Sign in to edit a note.",
140 no: "Only the author or an admin can edit a note.",
141 });
142 if (!found.ok) return found;
143 const body = input.body.trim();
144 if (body.length === 0 || body.length > BODY_MAX)
145 return fail("invalid", `A note is 1 to ${BODY_MAX} characters.`);
146 const note = db
147 .query<
148 Note,
149 [string, number]
150 >("UPDATE note SET body = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE id = ?2 RETURNING *")
151 .get(body, found.value.id)!;
152 emit("note.changed", note);
153 return ok(note);
154 }
155
156 export const deleteNote = (
157 db: Database,
158 who: Who,
159 input: { id: number },
160 ): Result<{ id: number }> =>
161 audited(db, who, "note", "delete", input.id, remove(db, who, input));
162
163 function remove(
164 db: Database,
165 who: Who,
166 input: { id: number },
167 ): Result<{ id: number }> {
168 const found = noteFor(db, who, "delete", input.id, {
169 signIn: "Sign in to remove a note.",
170 no: "Only the author or an admin can remove a note.",
171 });
172 if (!found.ok) return found;
173 db.query("DELETE FROM note WHERE id = ?1").run(found.value.id);
174 emit("note.removed", { id: found.value.id });
175 return ok({ id: found.value.id });
176 }
177
17817 /**
17918 * The audit trail, newest first, for whoever the table lets read it (an
18019 * admin, as the scaffold has it). `before` pages back by id. Audit rows name
src/audit.test.ts +32 −19
@@ -7,7 +7,7 @@ import { afterAll, expect, spyOn, test } from "bun:test";
77 import { mkdtempSync } from "node:fs";
88 import { tmpdir } from "node:os";
99 import { join } from "node:path";
10 import { addNote } from "./actions.ts";
10 import { createDeal } from "./deals.ts";
1111 import type { AuditRow } from "./audit.ts";
1212 import { openDb } from "./db.ts";
1313 import { serve } from "./server.ts";
@@ -36,6 +36,13 @@ const as = (
3636 const alice = as("u1", "alice");
3737 const bob = as("u2", "bob");
3838 const root = as("u0", "root", "admin");
39 const DEAL = {
40 address: "1 Test St",
41 buyer: "B",
42 seller: "S",
43 contract_date: "2026-10-01",
44 closing_date: "2026-11-01",
45 };
3946 const call = (
4047 path: string,
4148 init: RequestInit = {},
@@ -50,27 +57,27 @@ const trail = async (): Promise<AuditRow[]> =>
5057
5158 test("an allowed change and a refused one each leave a row", async () => {
5259 const made = await call(
53 "/api/notes",
54 { method: "POST", body: JSON.stringify({ body: "kept" }) },
60 "/api/deals",
61 { method: "POST", body: JSON.stringify(DEAL) },
5562 alice,
5663 );
5764 expect(made.status).toBe(201);
58 const note = (await made.json()) as { id: number };
65 const deal = (await made.json()) as { id: number };
5966 // Refused at the door: a stranger may create nothing.
6067 expect(
6168 (
62 await call("/api/notes", {
69 await call("/api/deals", {
6370 method: "POST",
64 body: JSON.stringify({ body: "x" }),
71 body: JSON.stringify(DEAL),
6572 })
6673 ).status,
6774 ).toBe(401);
68 // Refused by the action: bob could delete a note of his own, not alice's.
75 // Refused by the action: bob could delete a deal of his own, not alice's.
6976 expect(
70 (await call(`/api/notes/${note.id}`, { method: "DELETE" }, bob)).status,
77 (await call(`/api/deals/${deal.id}`, { method: "DELETE" }, bob)).status,
7178 ).toBe(403);
7279 // Refused as cross-site, before the table is asked.
73 const forged = await fetch(`${base}/api/notes/${note.id}`, {
80 const forged = await fetch(`${base}/api/deals/${deal.id}`, {
7481 method: "DELETE",
7582 headers: { ...alice, "sec-fetch-site": "cross-site" },
7683 });
@@ -93,16 +100,16 @@ test("an allowed change and a refused one each leave a row", async () => {
93100 {
94101 who_name: "alice",
95102 role: "user",
96 resource: "note",
103 resource: "deal",
97104 verb: "create",
98 target: String(note.id),
105 target: String(deal.id),
99106 allowed: 1,
100107 outcome: "ok",
101108 },
102109 {
103110 who_name: null,
104111 role: "anon",
105 resource: "note",
112 resource: "deal",
106113 verb: "create",
107114 target: null,
108115 allowed: 0,
@@ -111,16 +118,16 @@ test("an allowed change and a refused one each leave a row", async () => {
111118 {
112119 who_name: "bob",
113120 role: "user",
114 resource: "note",
121 resource: "deal",
115122 verb: "delete",
116 target: String(note.id),
123 target: String(deal.id),
117124 allowed: 0,
118125 outcome: "forbidden",
119126 },
120127 {
121128 who_name: "alice",
122129 role: "user",
123 resource: "note",
130 resource: "deal",
124131 verb: "delete",
125132 target: null,
126133 allowed: 0,
@@ -133,7 +140,7 @@ test("an allowed change and a refused one each leave a row", async () => {
133140
134141 test("reading is not an event: a GET leaves no row", async () => {
135142 const before = (await trail()).length;
136 await call("/api/notes");
143 await call("/api/deals");
137144 await call("/", {}, alice);
138145 expect((await trail()).length).toBe(before);
139146 });
@@ -166,17 +173,23 @@ test("a trail that cannot be written is a log line, and the change still happens
166173 db.exec("DROP TABLE audit");
167174 const said = spyOn(console, "error").mockImplementation(() => {});
168175 try {
169 const added = addNote(
176 const added = createDeal(
170177 db,
171178 { role: "user", id: "u1", name: "alice" },
172 { body: "still here" },
179 {
180 address: "1 Test St",
181 buyer: "B",
182 seller: "S",
183 contractDate: "2026-10-01",
184 closingDate: "2026-11-01",
185 },
173186 );
174187 expect(added.ok).toBe(true);
175188 expect(said).toHaveBeenCalledTimes(1);
176189 const line = JSON.parse(String(said.mock.calls[0]![0]));
177190 expect(line.audit).toMatchObject({
178191 who_name: "alice",
179 resource: "note",
192 resource: "deal",
180193 verb: "create",
181194 allowed: 1,
182195 outcome: "ok",
src/contract.test.ts +3 −27
@@ -1,6 +1,6 @@
11 /**
22 * Every door answers as the table says. The test acts as each identity the
3 * contract declares — on a note that names them and on one that names
3 * contract declares — on a deal that names them and on one that names
44 * someone else — and calls the real actions. A rule written by hand in an
55 * action, or a cell changed without its door, fails here.
66 */
@@ -8,15 +8,7 @@ import { expect, test } from "bun:test";
88 import { mkdtempSync } from "node:fs";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
11 import {
12 addNote,
13 deleteNote,
14 getAudit,
15 getNote,
16 listAudit,
17 listNotes,
18 updateNote,
19 } from "./actions.ts";
11 import { getAudit, listAudit } from "./actions.ts";
2012 import { record } from "./audit.ts";
2113 import {
2214 createDeal,
@@ -41,14 +33,6 @@ function whoIs(identity: string): Who {
4133 return { role, id: actor.id, name: identity };
4234 }
4335
44 const noteBy = (authorId: string): number =>
45 db
46 .query<
47 { id: number },
48 [string]
49 >("INSERT INTO note (body, author_id, author_name) VALUES ('n', ?1, ?1) RETURNING id")
50 .get(authorId)!.id;
51
5236 const dealBy = (authorId: string): number =>
5337 db
5438 .query<
@@ -60,7 +44,7 @@ const dealBy = (authorId: string): number =>
6044 const auditRow = (): number => {
6145 record(db, {
6246 who: { role: "anon" },
63 resource: "note",
47 resource: "deal",
6448 verb: "create",
6549 outcome: "signin_required",
6650 });
@@ -73,14 +57,6 @@ const doors: Record<
7357 string,
7458 Partial<Record<Verb, (who: Who, authorId: string) => boolean>>
7559 > = {
76 note: {
77 create: (who) => addNote(db, who, { body: "hello" }).ok,
78 list: (who) => listNotes(db, who).ok,
79 read: (who, authorId) => getNote(db, who, { id: noteBy(authorId) }).ok,
80 update: (who, authorId) =>
81 updateNote(db, who, { id: noteBy(authorId), body: "changed" }).ok,
82 delete: (who, authorId) => deleteNote(db, who, { id: noteBy(authorId) }).ok,
83 },
8460 deal: {
8561 create: (who) =>
8662 createDeal(db, who, {
src/db.ts +2
@@ -91,6 +91,8 @@ export const migrations: string[] = [
9191 UNIQUE (deadline_id, party_id, moment, due)
9292 )`,
9393 `CREATE TABLE app_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
94 // The template's notes scaffold is gone; nothing reads the table.
95 `DROP TABLE note`,
9496 ];
9597
9698 export function openDb(dir = dataDir): Database {
src/http.ts +1 −1
@@ -1,6 +1,6 @@
11 /**
22 * The floor every response stands on, and the few things a route needs to
3 * read a request safely. Nothing in here knows what a note is; who may
3 * read a request safely. Nothing in here knows what a deal is; who may
44 * come in at all is `security.ts`.
55 */
66
src/mcp.ts +1 −39
@@ -7,7 +7,7 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import { addNote, deleteNote, listNotes, type Result } from "./actions.ts";
10 import type { Result } from "./actions.ts";
1111 import { today } from "./dates.ts";
1212 import { getDeal, listDeals, markDone, moveDeadline, sendReminder } from "./deals.ts";
1313 import { agent, title } from "./env.ts";
@@ -27,44 +27,6 @@ interface Tool {
2727 }
2828
2929 export const tools: readonly Tool[] = [
30 {
31 name: "list_notes",
32 description: "The notes, newest first.",
33 inputSchema: {
34 type: "object",
35 properties: {
36 limit: {
37 type: "integer",
38 minimum: 1,
39 maximum: 500,
40 description: "At most this many (100).",
41 },
42 },
43 },
44 run: (db, who, args) =>
45 listNotes(db, who, { limit: Number(args.limit ?? 100) }),
46 },
47 {
48 name: "add_note",
49 description:
50 "Add a note as the signed-in person. Anonymous callers cannot.",
51 inputSchema: {
52 type: "object",
53 properties: { body: { type: "string", maxLength: 500 } },
54 required: ["body"],
55 },
56 run: (db, who, args) => addNote(db, who, { body: String(args.body ?? "") }),
57 },
58 {
59 name: "delete_note",
60 description: "Remove a note by id. Only its author or an admin can.",
61 inputSchema: {
62 type: "object",
63 properties: { id: { type: "integer" } },
64 required: ["id"],
65 },
66 run: (db, who, args) => deleteNote(db, who, { id: Number(args.id) }),
67 },
6830 {
6931 name: "list_deals",
7032 description: "Every deal with its dates, parties and sent reminders, soonest closing first.",
src/openapi.test.ts +8 −3
@@ -10,6 +10,7 @@ import { join } from "node:path";
1010 import { emit, openapi } from "./openapi.ts";
1111 import { routes } from "./routes.ts";
1212 import { serve } from "./server.ts";
13 import { sign } from "./who.ts";
1314
1415 const committed = readFileSync(
1516 new URL("../contract/openapi.json", import.meta.url),
@@ -67,9 +68,13 @@ test("GET /openapi.json serves the committed file", async () => {
6768 identityKey: "k",
6869 });
6970 afterAll(() => server.stop(true));
70 const response = await fetch(
71 `http://${server.hostname}:${server.port}/openapi.json`,
72 );
71 const url = `http://${server.hostname}:${server.port}/openapi.json`;
72 // No door is open to a stranger, so neither is the description.
73 expect((await fetch(url)).status).toBe(401);
74 const identity = `u1|alice|user|${Date.now() + 60_000}`;
75 const response = await fetch(url, {
76 headers: { "x-forge-identity": identity, "x-forge-signature": sign(identity, "k") },
77 });
7378 expect(response.status).toBe(200);
7479 expect(response.headers.get("content-type")).toContain("application/json");
7580 expect(await response.text()).toBe(committed);
src/openapi.ts +1 −2
@@ -12,12 +12,11 @@
1212
1313 import { contract } from "./contract.ts";
1414 import { description, title, version } from "./env.ts";
15 import { AUDIT_ROW, DEAL, DRAFT, ERROR, NOTE, routes, type Schema } from "./routes.ts";
15 import { AUDIT_ROW, DEAL, DRAFT, ERROR, routes, type Schema } from "./routes.ts";
1616 import { doorOf } from "./security.ts";
1717
1818 // The shapes said once, under components, and referred to wherever they appear.
1919 const NAMED = new Map<Schema, string>([
20 [NOTE, "Note"],
2120 [DEAL, "Deal"],
2221 [DRAFT, "Reminder"],
2322 [AUDIT_ROW, "AuditRow"],
src/routes.ts −97
@@ -14,14 +14,8 @@
1414 import type { Database } from "bun:sqlite";
1515 import { existsSync, readFileSync } from "node:fs";
1616 import {
17 addNote,
18 BODY_MAX,
19 deleteNote,
2017 getAudit,
21 getNote,
2218 listAudit,
23 listNotes,
24 updateNote,
2519 type Failure,
2620 type Result,
2721 } from "./actions.ts";
@@ -94,30 +88,6 @@ export interface Route {
9488 }
9589
9690 // The shapes the API speaks in, named once.
97 export const NOTE: Schema = {
98 type: "object",
99 properties: {
100 id: { type: "integer" },
101 body: { type: "string", minLength: 1, maxLength: BODY_MAX },
102 author_id: { type: "string" },
103 author_name: { type: "string" },
104 created_at: { type: "string", format: "date-time" },
105 updated_at: { type: "string", format: "date-time" },
106 },
107 required: [
108 "id",
109 "body",
110 "author_id",
111 "author_name",
112 "created_at",
113 "updated_at",
114 ],
115 };
116 const NOTE_BODY: Schema = {
117 type: "object",
118 properties: { body: { type: "string", minLength: 1, maxLength: BODY_MAX } },
119 required: ["body"],
120 };
12191 export const AUDIT_ROW: Schema = {
12292 type: "object",
12393 properties: {
@@ -442,73 +412,6 @@ export const routes: readonly Route[] = [
442412 },
443413
444414 // The JSON API: the same actions, the same identity, plain status codes.
445 {
446 method: "GET",
447 path: "/api/notes",
448 handle: (c) =>
449 answer(
450 listNotes(c.db, c.who, {
451 limit: Number(c.url.searchParams.get("limit") ?? 100),
452 }),
453 ),
454 api: {
455 summary: "The notes, newest first.",
456 query: { limit: LIMIT },
457 answer: list(NOTE),
458 },
459 },
460 {
461 method: "POST",
462 path: "/api/notes",
463 handle: async (c) => {
464 const body = await readJson(c.request);
465 if (body === undefined) return json({ error: "too_large" }, 413);
466 return answer(
467 addNote(c.db, c.who, { body: String(fields(body).body ?? "") }),
468 201,
469 );
470 },
471 api: {
472 summary: "Add a note as the person asking.",
473 body: NOTE_BODY,
474 answer: NOTE,
475 status: 201,
476 },
477 },
478 {
479 method: "GET",
480 path: "/api/notes/:id",
481 handle: (c) => answer(getNote(c.db, c.who, { id: Number(c.params.id) })),
482 api: { summary: "One note.", answer: NOTE },
483 },
484 {
485 method: "PATCH",
486 path: "/api/notes/:id",
487 handle: async (c) => {
488 const body = await readJson(c.request);
489 if (body === undefined) return json({ error: "too_large" }, 413);
490 return answer(
491 updateNote(c.db, c.who, {
492 id: Number(c.params.id),
493 body: String(fields(body).body ?? ""),
494 }),
495 );
496 },
497 api: { summary: "Change a note's words.", body: NOTE_BODY, answer: NOTE },
498 },
499 {
500 method: "DELETE",
501 path: "/api/notes/:id",
502 handle: (c) => answer(deleteNote(c.db, c.who, { id: Number(c.params.id) })),
503 api: {
504 summary: "Remove a note.",
505 answer: {
506 type: "object",
507 properties: { id: { type: "integer" } },
508 required: ["id"],
509 },
510 },
511 },
512415
513416 {
514417 method: "GET",
src/security.test.ts +29 −30
@@ -36,24 +36,24 @@ const as = (id: string, role: "user" | "admin"): Record<string, string> => {
3636 };
3737
3838 test("a path is a resource's door by the contract's api, and nothing else is", () => {
39 expect(doorOf("GET", "/api/notes")).toEqual({
40 resource: "note",
39 expect(doorOf("GET", "/api/deals")).toEqual({
40 resource: "deal",
4141 verb: "list",
4242 });
43 expect(doorOf("POST", "/api/notes")).toEqual({
44 resource: "note",
43 expect(doorOf("POST", "/api/deals")).toEqual({
44 resource: "deal",
4545 verb: "create",
4646 });
47 expect(doorOf("GET", "/api/notes/7")).toEqual({
48 resource: "note",
47 expect(doorOf("GET", "/api/deals/7")).toEqual({
48 resource: "deal",
4949 verb: "read",
5050 });
51 expect(doorOf("PATCH", "/api/notes/7")).toEqual({
52 resource: "note",
51 expect(doorOf("PATCH", "/api/deals/7")).toEqual({
52 resource: "deal",
5353 verb: "update",
5454 });
55 expect(doorOf("DELETE", "/api/notes/7")).toEqual({
56 resource: "note",
55 expect(doorOf("DELETE", "/api/deals/7")).toEqual({
56 resource: "deal",
5757 verb: "delete",
5858 });
5959 expect(doorOf("GET", "/api/audit")).toEqual({
@@ -61,11 +61,11 @@ test("a path is a resource's door by the contract's api, and nothing else is", (
6161 verb: "list",
6262 });
6363 for (const [method, path] of [
64 ["PUT", "/api/notes"],
65 ["GET", "/api/notes/7/x"],
66 ["GET", "/api/notesy"],
67 ["GET", "/api/notes/"],
68 ["POST", "/notes"],
64 ["PUT", "/api/deals"],
65 ["GET", "/api/deals/7/x"],
66 ["GET", "/api/dealsy"],
67 ["GET", "/api/deals/"],
68 ["POST", "/deals"],
6969 ] as const)
7070 expect(doorOf(method, path)).toBeUndefined();
7171 });
@@ -74,11 +74,11 @@ test("the door refuses only what no row would open", () => {
7474 const anon = { role: "anon" } as const;
7575 const alice = { role: "user", id: "u1", name: "alice" } as const;
7676 const root = { role: "admin", id: "u0", name: "root" } as const;
77 expect(mayKnock(anon, "note", "list")).toBe(true);
78 expect(mayKnock(anon, "note", "create")).toBe(false);
79 expect(mayKnock(anon, "note", "delete")).toBe(false);
80 // alice may delete a note of her own, so the door lets her ask; the action decides which.
81 expect(mayKnock(alice, "note", "delete")).toBe(true);
77 expect(mayKnock(anon, "deal", "list")).toBe(false);
78 expect(mayKnock(anon, "deal", "create")).toBe(false);
79 expect(mayKnock(anon, "deal", "delete")).toBe(false);
80 // alice may delete a deal of her own, so the door lets her ask; the action decides which.
81 expect(mayKnock(alice, "deal", "delete")).toBe(true);
8282 expect(mayKnock(alice, "audit", "list")).toBe(false);
8383 expect(mayKnock(root, "audit", "list")).toBe(true);
8484 expect(mayKnock(root, "audit", "create")).toBe(false);
@@ -87,13 +87,13 @@ test("the door refuses only what no row would open", () => {
8787 test("a stranger is refused /api before the body is read, when the contract closes it", async () => {
8888 // A body past the cap: read, it would be 413. The door answers first.
8989 const huge = "x".repeat(128 * 1024);
90 const refused = await fetch(`${base}/api/notes`, {
90 const refused = await fetch(`${base}/api/deals`, {
9191 method: "POST",
9292 headers: { "content-type": "application/json" },
9393 body: huge,
9494 });
9595 expect(refused.status).toBe(401);
96 const signedIn = await fetch(`${base}/api/notes`, {
96 const signedIn = await fetch(`${base}/api/deals`, {
9797 method: "POST",
9898 headers: { "content-type": "application/json", ...as("u1", "user") },
9999 body: huge,
@@ -109,9 +109,8 @@ test("a stranger is refused /api before the body is read, when the contract clos
109109 (await fetch(`${base}/api/audit`, { headers: as("u1", "user") })).status,
110110 ).toBe(403);
111111 // What the table opens stays open.
112 expect((await fetch(`${base}/api/notes`)).status).toBe(200);
113 expect((await fetch(`${base}/api/notes/0`)).status).toBe(404);
114 expect((await fetch(`${base}/openapi.json`)).status).toBe(200);
112 // With no door open to a stranger, the API's description is shut to them too.
113 expect((await fetch(`${base}/openapi.json`)).status).toBe(401);
115114 });
116115
117116 test("the API's description is shut to strangers when the table opens them no door", () => {
@@ -122,8 +121,8 @@ test("the API's description is shut to strangers when the table opens them no do
122121 user: { above: ["anon"], held: { by: "identity", role: "user" } },
123122 },
124123 resources: {
125 note: {
126 api: "/api/notes",
124 deal: {
125 api: "/api/deals",
127126 can: {
128127 create: "user",
129128 read: "user",
@@ -137,7 +136,7 @@ test("the API's description is shut to strangers when the table opens them no do
137136 );
138137 if (!closed.ok) throw new Error(closed.problems.join("; "));
139138 expect(openToStrangers(closed.contract)).toBe(false);
140 expect(openToStrangers()).toBe(true);
139 expect(openToStrangers()).toBe(false);
141140 });
142141
143142 test("strangers are rationed at the API, reads too", () => {
@@ -145,8 +144,8 @@ test("strangers are rationed at the API, reads too", () => {
145144 const knock = () =>
146145 door(
147146 db,
148 new Request("http://app/api/notes"),
149 new URL("http://app/api/notes"),
147 new Request("http://app/mcp"),
148 new URL("http://app/mcp"),
150149 { role: "anon" },
151150 "203.0.113.7",
152151 );
src/server.test.ts +30 −38
@@ -96,37 +96,45 @@ test("a form post opens a deal as the person; a guest is sent to sign in", async
9696 expect(page).toContain("Ann Buyer");
9797 });
9898
99 const NEW_DEAL = {
100 address: "9 Api Lane",
101 buyer: "B",
102 seller: "S",
103 contract_date: "2026-10-01",
104 closing_date: "2026-11-01",
105 };
106
99107 test("the JSON API is the same actions with the same identity", async () => {
100108 const created = await api(
101 "/api/notes",
102 { method: "POST", ...jsonBody({ body: "over the api" }) },
109 "/api/deals",
110 { method: "POST", ...jsonBody(NEW_DEAL) },
103111 alice,
104112 );
105113 expect(created.status).toBe(201);
106 const note = (await created.json()) as { id: number; author_name: string };
107 expect(note.author_name).toBe("alice");
108 const listed = (await (await fetch(base + "/api/notes")).json()) as {
114 const deal = (await created.json()) as { id: number; author_name: string };
115 expect(deal.author_name).toBe("alice");
116 expect((await fetch(base + "/api/deals")).status).toBe(401);
117 const listed = (await (await api("/api/deals", {}, bob)).json()) as {
109118 id: number;
110119 }[];
111 expect(listed.map((n) => n.id)).toContain(note.id);
120 expect(listed.map((d) => d.id)).toContain(deal.id);
112121 expect(
113 (await api("/api/notes", { method: "POST", ...jsonBody({ body: "anon" }) }))
114 .status,
122 (await api("/api/deals", { method: "POST", ...jsonBody(NEW_DEAL) })).status,
115123 ).toBe(401);
116124 expect(
117 (await api(`/api/notes/${note.id}`, { method: "DELETE" }, bob)).status,
125 (await api(`/api/deals/${deal.id}`, { method: "DELETE" }, bob)).status,
118126 ).toBe(403);
119127 expect(
120 (await api(`/api/notes/${note.id}`, { method: "DELETE" }, alice)).status,
128 (await api(`/api/deals/${deal.id}`, { method: "DELETE" }, alice)).status,
121129 ).toBe(200);
122130 expect(
123 (await api(`/api/notes/${note.id}`, { method: "DELETE" }, alice)).status,
131 (await api(`/api/deals/${deal.id}`, { method: "DELETE" }, alice)).status,
124132 ).toBe(404);
125133 expect(
126134 (
127135 await api(
128 "/api/notes",
129 { method: "POST", ...jsonBody({ body: "" }) },
136 "/api/deals",
137 { method: "POST", ...jsonBody({ ...NEW_DEAL, address: "" }) },
130138 alice,
131139 )
132140 ).status,
@@ -143,9 +151,6 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
143151 expect(hello.result.capabilities).toEqual({ tools: {} });
144152 const listed = await rpc({ jsonrpc: "2.0", id: 2, method: "tools/list" });
145153 expect(listed.result.tools.map((t: { name: string }) => t.name)).toEqual([
146 "list_notes",
147 "add_note",
148 "delete_note",
149154 "list_deals",
150155 "get_deal",
151156 "reminders_today",
@@ -163,19 +168,6 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
163168 },
164169 who,
165170 );
166 const refused = await call("add_note", { body: "as nobody" });
167 expect(refused.result.isError).toBe(true);
168 const added = await call("add_note", { body: "over mcp" }, root);
169 expect(added.result.isError).toBeUndefined();
170 const note = JSON.parse(added.result.content[0].text);
171 expect(note.author_name).toBe("root");
172 const notes = JSON.parse(
173 (await call("list_notes", {})).result.content[0].text,
174 );
175 expect(notes.map((n: { id: number }) => n.id)).toContain(note.id);
176 expect(
177 (await call("delete_note", { id: note.id }, root)).result.isError,
178 ).toBeUndefined();
179171 expect((await call("list_deals", {})).result.isError).toBe(true);
180172 const deals = JSON.parse((await call("list_deals", {}, alice)).result.content[0].text);
181173 const open = deals[0].deadlines.find((d: { done_at: unknown }) => d.done_at === null);
@@ -203,17 +195,17 @@ test("a change is on the event stream, and a late client hears what it missed",
203195 buffer += new TextDecoder().decode(value);
204196 // Earlier tests' events replay first; this one listens for its own.
205197 for (const frame of buffer.matchAll(/id: (\d+)\ndata: (.*)\n\n/g))
206 if (JSON.parse(frame[2]!).type === "note.added")
207 return { id: frame[1]!, type: "note.added" };
198 if (JSON.parse(frame[2]!).type === "deal.changed")
199 return { id: frame[1]!, type: "deal.changed" };
208200 }
209201 };
210202 await api(
211 "/api/notes",
212 { method: "POST", ...jsonBody({ body: "live" }) },
203 "/api/deals",
204 { method: "POST", ...jsonBody(NEW_DEAL) },
213205 alice,
214206 );
215207 const heard = await next();
216 expect(heard.type).toBe("note.added");
208 expect(heard.type).toBe("deal.changed");
217209 await reader.cancel();
218210 const late = await fetch(base + "/events", {
219211 headers: { "last-event-id": String(Number(heard.id) - 1) },
@@ -222,7 +214,7 @@ test("a change is on the event stream, and a late client hears what it missed",
222214 (await late.body!.getReader().read()).value,
223215 );
224216 expect(replay).toContain(`id: ${heard.id}\n`);
225 expect(replay).toContain("note.added");
217 expect(replay).toContain("deal.changed");
226218 });
227219
228220 test("writes are rationed per person", async () => {
@@ -230,8 +222,8 @@ test("writes are rationed per person", async () => {
230222 const answers = await Promise.all(
231223 Array.from({ length: 40 }, () =>
232224 api(
233 "/api/notes",
234 { method: "POST", ...jsonBody({ body: "again" }) },
225 "/api/deals",
226 { method: "POST", ...jsonBody(NEW_DEAL) },
235227 flood,
236228 ),
237229 ),
@@ -248,7 +240,7 @@ test("stands on the security floor", async () => {
248240 );
249241 expect(response.headers.get("x-content-type-options")).toBe("nosniff");
250242 expect(
251 (await fetch(base + "/api/notes")).headers.get("content-security-policy"),
243 (await fetch(base + "/api/deals")).headers.get("content-security-policy"),
252244 ).toContain("default-src");
253245 });
254246
static/app.css −17
@@ -98,23 +98,6 @@ code,
9898 margin: 0;
9999 padding: 0;
100100 }
101 .note {
102 display: flex;
103 justify-content: space-between;
104 align-items: flex-start;
105 gap: var(--space-3);
106 padding: var(--space-3) 0;
107 border-top: 1px solid var(--color-line);
108 }
109 .note:first-child {
110 border-top: 0;
111 }
112 .note p {
113 overflow-wrap: anywhere;
114 }
115 .note small {
116 font-size: var(--text-sm);
117 }
118101 .empty {
119102 padding: var(--space-6) var(--space-4);
120103 text-align: center;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs