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

The app template is a repository: new apps start from trevato/app-template, and scaffold.ts's strings go #10398

Parked opened this in answer to
Closed without merging

mason/forge:mason/10305-the-app-template-is-a-repository-new-app → main 7 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
68 files changed +6521 −6132
Dockerfile +2
@@ -25,6 +25,8 @@ COPY docs/DESIGN.md ./docs/DESIGN.md
2525 COPY plugins/opencode ./plugins/opencode
2626 # The forge packs /packs lists and deploys (src/packs/catalog.ts reads packs/ at the root).
2727 COPY packs ./packs
28 # The app template new apps start from (src/apps/template.ts reads template/ at the root, #10305).
29 COPY template ./template
2830 # src/ alone: nothing under it imports scripts/ or test/ (test/src-imports.test.ts),
2931 # and the boot proof below fails the build if that ever stops being so (#2652).
3032
docs/APPS.md +1 −1
@@ -920,7 +920,7 @@ generous because the first boot migrates.
920920 ## What a new app starts as
921921
922922 **New app** writes a small, complete app into the repository
923 (`src/apps/scaffold.ts`): notes behind a page, a JSON API, an MCP server
923 (`template/`, read by `src/apps/template.ts`; docs/features/app-template.md): notes behind a page, a JSON API, an MCP server
924924 and a terminal, all over one set of actions, with no dependencies. What
925925 the forge already does for every app (identity, the grant, preview data,
926926 health polling, the terminal, the swap, sleep, the contract's wall) is not
docs/SPAWN.md +1 −1
@@ -78,7 +78,7 @@ A spawn may also name a `size`: `small`, `medium` or `large` (`src/spawn/sizes.t
7878
7979 ## Choosing a template (#7533)
8080
81 A template is a named starting point for a new forge's apps, listed in `src/spawn/templates.ts`: each has an `id`, a `title`, one sentence `says`, and a `source` — `builtin` (its files are this forge's code) or `repo` (read from `repo`, an `owner/name` on this forge; none yet, #7536). Built in are `blank`, the default and what a spawn has always made (the forked apps and an optional `fresh` one), and `starter`, the app `/apps/new` starts from (`scaffoldFiles`, `src/apps/scaffold.ts`).
81 A template is a named starting point for a new forge's apps, listed in `src/spawn/templates.ts`: each has an `id`, a `title`, one sentence `says`, and a `source` — `builtin` (its files are this forge's code) or `repo` (read from `repo`, an `owner/name` on this forge; none yet, #7536). Built in are `blank`, the default and what a spawn has always made (the forked apps and an optional `fresh` one), and `starter`, the app `/apps/new` starts from (`scaffoldFiles`, the copy of the app template in `template/`, `src/apps/template.ts`).
8282
8383 `POST /api/v1/forges` and the MCP `spawn` take an optional `template` id. An unknown id is a 422 on `template` naming the valid ids. Absent or `blank`, the plan is the one it always was; any other id is named in the plan, the ledger line, `parent.json` and the child's row in `GET /api/v1/forges` (absent there means `blank`). Because it is in the plan, a retry with another template is refused as a different child. A `starter` child begins with the template's files (#7535, `src/spawn/template_birth.ts`): one commit, no history and no upstream, in a new private repo of the child's organisation named for the `fresh` sentence (which becomes its description; no second repo) or `app`. `parent.json` records `template: {id}`. Only tracked files travel, nothing from the "never copied" list; a retry finds the repo and leaves it.
8484
docs/features/app-template.md added +18
@@ -0,0 +1,18 @@
1 # The app template is a repository
2
3 New apps start from files, not code (#10305).
4
5 - `template/` holds the template's files; the release image carries it (`Dockerfile`), so a forge, a child forge or a fresh install always makes apps. `src/apps/template.ts` reads it. `template/template.json` lists the files that hold the app's name and description and the literals to replace there (`app-template`, the description line); everything else is copied byte for byte and the manifest itself is left out. An empty description keeps the template's line ("A new app on the forge.") in `package.json` as well as the README (it was `""` in `package.json` before; `test/template.test.ts` pins it).
6 - `src/spawn/template_birth.ts` uses the same copy.
7 - `template/` is a **bootstrap copy**: it was generated from the strings `scaffold.ts` held, not copied from a commit of trevato/app-template, so it names no commit. Once that repository holds these files, refresh `template/` from its tracked files and write the commit into this doc.
8 - `template/` is not part of the forge's suite or type check: `bunfig.toml` roots `bun test` at `test/`, and `tsconfig.json` includes only `src`, `test`, `scripts`, `examples`. `test/scaffold.test.ts` writes an app out and runs its own tests; `scripts/gate.ts` covers the rest. `test/template.test.ts` keeps `template/src/can.ts` and `template/static/beacon.js` equal to the forge's own.
9
10 Not yet, each its own issue: New app copying a repository's tip instead of the image's copy (which needs a door to name the repository, a read check on the caller, and caps on what is copied); a pull check on trevato/app-template that births an app from the tip; admins marking several repositories as templates with a picker on New app (#7536).
11
12 ## Several templates (owner, 2026-11-09)
13
14 The owner wants templates as repositories he can fork and try (trevato/effect-template, a fork of app-template on Effect; trevato/exact-templates, several templates in one repository, each a folder with `TEMPLATE.md`), a picker on New app over the repositories an admin marks, and a repository holding several templates to offer each one. Decisions so far, for #10437, which builds it:
15
16 - A template is a folder: the repository root, or a subfolder holding `TEMPLATE.md`. Its files are copied and filled by the same `template.json` rule as above; a folder without a `template.json` is not offered.
17 - The forge does not run a template's own `bun new.mjs <template>`: that is a repository's code run with the forge's authority. A template that needs a script to become an app declares its substitutions in `template.json` instead, or is not offered.
18 - Rust builds for Exact are #10426, not this issue.
scripts/unreached-allow.json −1
@@ -15,7 +15,6 @@
1515 "src/flow/review_rounds.ts",
1616 "src/flow/shared_red.ts",
1717 "src/flow/stale_fold.ts",
18 "src/kernel/why_now.ts",
1918 "src/spawn/pod.ts",
2019 "src/tui/gallery.ts",
2120 "src/tui/ui/qr.ts",
src/actions/apps.ts +1 −1
@@ -22,7 +22,7 @@ import { appVitals, type AppVitals } from "../apps/vitals.ts";
2222 import { appsRuntime, envsFor, type EnvStatus } from "../apps/runtime.ts";
2323 import { grantUrl, originFor, sideForViewer, sideReader } from "../apps/proxy.ts";
2424 import { plainLine } from "../apps/side.ts";
25 import { scaffoldFiles } from "../apps/scaffold.ts";
25 import { scaffoldFiles } from "../apps/template.ts";
2626 import {
2727 envBuild,
2828 isEnvName,
src/apps/scaffold.ts deleted −6112

Diff not shown — 6,112 changed lines (limit 5,000). −6112

View file
src/apps/template.ts added +103
@@ -0,0 +1,103 @@
1 /**
2 * The app a new app starts as is a repository, not code: `template/` holds a
3 * pinned copy of trevato/app-template's tracked files (#10305), carried in
4 * every release so a forge without that repository can still make apps.
5 * `template.json` names the files that hold the app's name and description
6 * and the literals to replace there. Everything else travels byte for byte,
7 * and the template stays runnable and tested as it is.
8 */
9
10 import { readdirSync, readFileSync, statSync } from "node:fs";
11 import { join } from "node:path";
12 import type { FileWrite } from "../git/write.ts";
13
14 /** The bundled copy: `template/` at the root of the forge's source or image. */
15 export const BUNDLED_TEMPLATE = new URL("../../template/", import.meta.url).pathname;
16
17 /** The name a template gives its own manifest; it is not part of a new app. */
18 export const MANIFEST = "template.json";
19
20 export interface TemplateInput {
21 /** The repository name; also the title on the page. */
22 readonly name: string;
23 /** What the app should become. Shown on the page until it does. */
24 readonly description: string;
25 }
26
27 export interface Manifest {
28 /** Files holding the literals below. */
29 readonly files: readonly string[];
30 /** The name the template calls itself. */
31 readonly name: string;
32 /** The description line the template carries. */
33 readonly description: string;
34 }
35
36 /** Validate a parsed `template.json`; undefined when it is not one. */
37 export function parseManifest(text: string): Manifest | undefined {
38 let raw: unknown;
39 try {
40 raw = JSON.parse(text);
41 } catch {
42 return undefined;
43 }
44 if (typeof raw !== "object" || raw === null) return undefined;
45 const { files, name, description } = raw as Record<string, unknown>;
46 if (!Array.isArray(files) || !files.every((f) => typeof f === "string")) return undefined;
47 if (typeof name !== "string" || name === "") return undefined;
48 if (typeof description !== "string") return undefined;
49 return { files: files as string[], name, description };
50 }
51
52 /** Every file under `dir`, as paths relative to it, in a stable order. */
53 function walk(dir: string, rel = ""): string[] {
54 const out: string[] = [];
55 for (const entry of readdirSync(join(dir, rel)).sort()) {
56 if (entry === ".git" || entry === "node_modules") continue;
57 const path = rel === "" ? entry : `${rel}/${entry}`;
58 if (statSync(join(dir, path)).isDirectory()) out.push(...walk(dir, path));
59 else out.push(path);
60 }
61 return out;
62 }
63
64 /** Read a template directory into the files it holds, manifest included. */
65 export function readTemplateDir(dir: string): FileWrite[] {
66 return walk(dir).map((path) => ({ path, content: readFileSync(join(dir, path), "utf8") }));
67 }
68
69 const textOf = (content: FileWrite["content"]): string =>
70 content instanceof Uint8Array ? new TextDecoder().decode(content) : String(content);
71
72 const literal = (path: string, value: string): string =>
73 path.endsWith(".json") ? JSON.stringify(value).slice(1, -1) : value;
74
75 /**
76 * Fill a template's files for one app: the manifest's name and description
77 * literals are replaced in the files it lists, and the manifest itself is
78 * left out. An empty description keeps the template's own line.
79 */
80 export function fillTemplate(files: readonly FileWrite[], input: TemplateInput): FileWrite[] | undefined {
81 const manifestFile = files.find((f) => f.path === MANIFEST);
82 const manifest = manifestFile === undefined ? undefined : parseManifest(textOf(manifestFile.content));
83 if (manifest === undefined) return undefined;
84 const description = input.description.trim();
85 const listed = new Set(manifest.files);
86 return files
87 .filter((f) => f.path !== MANIFEST)
88 .map((f) => {
89 if (!listed.has(f.path)) return f;
90 let text = textOf(f.content);
91 // The name first: a name is a slug, a description may say anything.
92 text = text.replaceAll(literal(f.path, manifest.name), () => literal(f.path, input.name));
93 if (description !== "") text = text.replaceAll(literal(f.path, manifest.description), () => literal(f.path, description));
94 return { path: f.path, content: text };
95 });
96 }
97
98 /** The files of a new app, from the bundled copy of the template. */
99 export function scaffoldFiles(input: TemplateInput): FileWrite[] {
100 const files = fillTemplate(readTemplateDir(BUNDLED_TEMPLATE), input);
101 if (files === undefined) throw new Error("the bundled template has no valid template.json");
102 return files;
103 }
src/kernel/signin_words.ts +1 −1
@@ -2,7 +2,7 @@
22 * What a sign-in flow says when its return cannot be finished: the state
33 * did not come back to the browser that began, or the login it names is
44 * gone (spent, or past its time). The parent sign-in (`http/rp.ts`) and the
5 * sign-in an app's scaffold writes (`apps/scaffold.ts`) say the same thing,
5 * sign-in the app template carries (`template/src/signin.ts`) say the same thing,
66 * so it is said here once.
77 */
88 export const SIGNIN_NOT_THIS_BROWSER = "This sign-in did not start in this browser.";
src/spawn/template_birth.ts +1 −1
@@ -8,7 +8,7 @@
88 */
99
1010 import type { App } from "../app.ts";
11 import { scaffoldFiles } from "../apps/scaffold.ts";
11 import { scaffoldFiles } from "../apps/template.ts";
1212 import { createRepo, getRepo, updateRepoSettings } from "../core/repos.ts";
1313 import { runGit } from "../git/env.ts";
1414 import { repoDir } from "../git/repos.ts";
template/.gitignore added +4
@@ -0,0 +1,4 @@
1 node_modules/
2 *.db
3 *.db-wal
4 *.db-shm
template/AGENTS.md added +131
@@ -0,0 +1,131 @@
1 # Working on this app
2
3 You are one of the crew on this repository. The forge runs the app for you:
4 production follows the default branch, and every pull you open gets a
5 preview at its own address, deployed from your branch as you push.
6
7 ## The rules
8
9 - Work on the branch you were given. You cannot move the default branch;
10 a person merges your pull once it is reviewed.
11 - Keep state under `FORGE_APP_DATA`. Never write elsewhere at runtime.
12 - Run `bun test` before you push. `forge.json`'s `app.test` runs it beside
13 the app on every deploy, not before it: the preview comes up the moment
14 the app answers and says `live`, or `serving · tests failed` the moment
15 the suite disagrees. Every behaviour you add gets a test that would fail
16 without it.
17 - `src/tty.ts` is the app's terminal. The exact command that reaches it is
18 `FORGE_APP_SSH` at runtime; print that verbatim wherever the app tells
19 people how to connect. What a person can do on the page they can do here,
20 and nothing more: the terminal gates its reads and writes exactly as the
21 page does (`FORGE_APP_USER_ROLE` is the forge's word on who is there), and a
22 write made there reaches web viewers live like any other.
23 - Keep it dependency-free unless a dependency is clearly worth it, and say
24 why in the pull. A dependency is code you now maintain.
25 - When you are done, push and stop. Your last message becomes the pull's
26 description: say what changed, what you chose not to do, and what to look
27 at in the preview.
28
29 ## The shape
30
31 One implementation, many doors. Every operation is a function in
32 `src/actions.ts` — `(db, who, input)` in, data or a named failure out — and
33 the page (`src/routes.ts`, `src/page.ts`), the JSON API (`src/routes.ts`),
34 the MCP server (`src/mcp.ts`) and the terminal (`src/tty.ts`) call it. A
35 door reads its wire format and shapes the answer; it decides nothing. A
36 rule in an action holds at every door at once; a rule anywhere else is a
37 bug waiting for the door you forgot.
38
39 Identity comes from the forge (`src/who.ts`): `anon`, `user` or `admin`,
40 verified by signature, never by a cookie the app invents.
41
42 Every request passes the door (`src/security.ts`) before a route sees it:
43 writes are rationed, a write from another site is refused, and a request
44 under a resource's `api` path is refused — before its body is read — when
45 the table lets that person through that door for no row at all. The door
46 asks the same table the actions do; it never compares roles by hand, and
47 the action still decides about the real row. Do not route around it.
48
49 Every change is written down. An action that creates, updates or deletes
50 returns through `audited` (`src/actions.ts`), which appends a row to the
51 `audit` table — who, the resource and verb, the row, when, and whether
52 they were let — refused attempts included; the door records the writes it
53 turns away. Admins read it at `GET /api/audit` (the `audit` resource in
54 `contract.json`). Recording never fails a request: a row that cannot be
55 written is a log line.
56
57 Who may do what is a table, not code: `contract.json`. It declares the
58 roles — each names the roles below it, and how it is held: by everyone, by
59 the identity the forge signed, or by a row's column naming the person — and,
60 for every resource, the least role each of create, read, update, delete and
61 list needs. An action asks `permit(who, resource, verb, row)`
62 (`src/contract.ts`) and obeys the answer; it never compares `who.role`
63 itself. `src/can.ts` is the forge's evaluator, carried verbatim: do not
64 edit it. `src/contract.test.ts` acts as every identity at every door and
65 fails when a door and the table disagree.
66
67 A new kind of person is a new role in the table, under an existing one. A
68 change to a cell is a change of policy: say so in the pull's description.
69 A cell loosened — anything an identity could not do before that it can
70 after — is a wall: the forge shows the pull to a person and never lands it
71 on its own. Do not loosen a cell unless the issue asks for exactly that;
72 prefer a new role under an existing one, or a new resource, to widening a
73 door that was decided.
74
75 To add a concept:
76
77 - **An action** — a function in `src/actions.ts` that asks `permit`, its
78 resource's row in `contract.json`, its door in `src/contract.test.ts`,
79 and a test in `src/actions.test.ts` for what the table cannot say.
80 - **A migration** — append to `migrations` in `src/db.ts`. Never edit one
81 that has run. `bun run src/db.ts --check` shows the version.
82 - **A page** — a row in `src/routes.ts` and a function in `src/page.ts`.
83 With a second page, move them under `src/pages/` and keep one `layout`.
84 - **An API route** — a row in `src/routes.ts` that calls the action and
85 answers with `answer(...)`; the status follows the failure. Give it an
86 `api` entry beside it (a sentence, the body and answer as JSON Schema)
87 and run `bun run contract:emit`: `contract/openapi.json` is committed,
88 served at `/openapi.json`, and `bun test` fails while it is stale. A
89 resource's routes live under the `api` path its `contract.json` entry
90 names, so the door and the forge's probe find them.
91 - **A tool** — an entry in `tools` in `src/mcp.ts`: a name, one sentence,
92 a JSON schema, the action.
93 - **A terminal command** — a key in `src/tty.ts` that calls the action and
94 reports on the status line.
95 - **Something live** — `emit(type, data)` in the action, and
96 `data-live="<types>"` on the region of the page that shows it.
97 - **A colour, a space, a size** — a token in `design/tokens.json` (a
98 colour needs its dark value in `$extensions.mode.dark`), used as
99 `var(--…)`. `bun run lint:design` refuses a raw `#hex`, `rgb(` or
100 `hsl(` anywhere in `src/` or `static/`, and a `var(--…)` that names no
101 token; `src/design.test.ts` runs it, and holds every pair of colours a
102 person reads to 4.5:1 in both themes.
103
104 ## The bar
105
106 - Security: every input is validated at the boundary and every output is
107 escaped; every response carries the floor in `src/http.ts` (keep it,
108 extend it); a POST that is not same-origin is refused; writes are
109 rationed per person; secrets come from the environment (Settings → App →
110 Environment), never the repository; no `eval`, no shell built from user
111 text. A request body is capped by the bytes actually read (`readBody`),
112 never by a Content-Length. `HEAD` answers like `GET`. A private thing
113 needs an identity from `who`, and a cookie the app sets itself is
114 `HttpOnly; SameSite=Lax`.
115 - Speed: the first paint is server-rendered HTML; JavaScript is small, in
116 `static/`, linked by content (`asset()`) and cached for a year; no
117 layout shift; what changes arrives over `/events`, never by polling;
118 work that can wait is done after the response.
119 - A phone is a first-class client: the page works at 360px wide with no
120 horizontal scroll, every control is at least 44px on a side
121 (`--size-tap`), an input's text is never below 16px (a phone zooms into
122 a smaller one), focus is always visible, whoever asked for less motion
123 gets none, and the keyboard reaches everything a mouse does.
124 - Beauty is the tokens': light and dark both, from one file. A new page
125 uses `layout`, which carries the tokens, the description and the Open
126 Graph and card metadata a shared link unfurls with — pass the page's
127 path so `og:url` is its own.
128 - Finish: the app boots, `/healthz` answers `{ ok, version, uptime }`
129 (the forge polls it; keep it cheap and apart from the page), `/`
130 answers, `bun test` is green, the README says how to use it and what is
131 real versus simulated, `forge.json` says how to run it.
template/README.md added +155
@@ -0,0 +1,155 @@
1 # app-template
2
3 A new app on the forge.
4
5 This is an app: the forge runs it. Production follows the default branch;
6 every open pull gets a preview at its own address with its own copy of the
7 data. Everything the app keeps lives under `FORGE_APP_DATA`, which is what
8 makes "production data" and "preview data" two different things.
9
10 ```sh
11 PORT=8080 FORGE_APP_DATA=./data bun run src/server.ts # run it here
12 bun test # what `forge.json`'s app.test runs on every push
13 FORGE_APP_DATA=./data bun run src/tty.ts # the terminal
14 FORGE_APP_DATA=./data bun run src/db.ts --check # schema version, integrity
15 bun run lint:design # no colour but the tokens'
16 bun run contract:emit # rewrite contract/openapi.json from the routes
17 ```
18
19 `app.test` in `forge.json` runs beside `app.run` in every deploy, not before
20 it: the preview comes up the moment the app answers, and says `live`, or
21 `serving · tests failed` the moment the suite disagrees.
22
23 Every response carries `Content-Security-Policy`, `X-Content-Type-Options`,
24 `Referrer-Policy` and `Cross-Origin-Opener-Policy: same-origin` (the last
25 cuts a page off from any window that opened it); they are set in `src/http.ts`.
26
27 ## The shape
28
29 One implementation, many doors. `src/actions.ts` is every operation as a
30 plain function — `(db, who, input)` in, data or a named failure out — and
31 the page, the JSON API, the MCP server and the terminal all call it and
32 decide nothing themselves. `AGENTS.md` says how to add to it.
33
34 | file | what it is |
35 | ---------------------------------- | -------------------------------------------------------------- |
36 | `src/actions.ts` | list, add, delete; the audit trail, read |
37 | `contract.json` | who may do what: roles, and the least role each verb needs |
38 | `src/contract.ts`, `src/can.ts` | the table, read at boot; the forge's evaluator, verbatim |
39 | `src/security.ts` | the door: rationing, same origin, the table before the body |
40 | `src/audit.ts` | every change and every refused one, as a row |
41 | `src/who.ts` | who is asking, from the forge's signed headers |
42 | `src/signin.ts` | sign-in through the forge: OpenID Connect, code flow with PKCE |
43 | `src/db.ts` | SQLite under `FORGE_APP_DATA`, WAL, forward-only migrations |
44 | `src/live.ts` | the in-process bus and `GET /events` |
45 | `src/mcp.ts` | the actions as MCP tools at `POST /mcp` |
46 | `src/routes.ts` | every path, in one table, each API route described beside it |
47 | `src/openapi.ts` | the routes as OpenAPI; committed at `contract/openapi.json` |
48 | `src/page.ts` | the HTML, rendered on the server, with its share metadata |
49 | `src/site.ts` | icon, manifest, card, sitemap, llms.txt, structured data |
50 | `src/compress.ts` | gzip for text responses |
51 | `design/tokens.json`, `src/tokens.ts` | the look as data, light and dark; compiled to `/tokens.css` |
52 | `src/http.ts` | the floor: headers, body cap, files |
53 | `src/server.ts` | boot: open the database, serve |
54 | `src/tty.ts` | the terminal, over the same actions |
55 | `src/env.ts` | what the forge told this process |
56 | `static/app.css`, `static/live.js` | the look in the tokens' words, and the list that stays current |
57 | `static/beacon.js` | reports each page's load and INP to the forge, which counts visitors: no secret, no address kept |
58
59 ## What every app stands on
60
61 - **The door.** Before a route sees a request, `src/security.ts` rations
62 writes (and a stranger's API calls), refuses a write from another site,
63 and turns away — before the body is read — anyone the table lets through
64 a resource's door for no row at all: 401 for a stranger, 403 for anyone
65 else. The action still decides about the real row.
66 - **The audit trail.** Every change, and every change refused, is a row:
67 who, which resource and verb, which row, when, and whether they were
68 let. Admins read it at `GET /api/audit`. A row that cannot be written
69 is a log line, never a failed request.
70 - **The API, described.** `GET /openapi.json` is `contract/openapi.json`,
71 written from the routes by `bun run contract:emit`; each operation names
72 its cell of the table (`x-contract`). `bun test` fails while it is stale.
73 - **Up, or not.** `GET /healthz` answers `{ ok, version, uptime }`; the
74 forge waits on it before it sends anyone to a deploy.
75 - **The look.** `design/tokens.json` holds every colour, space and size,
76 light and dark; nothing else spells out a colour (`bun run lint:design`),
77 and every pair a person reads meets 4.5:1 in both themes.
78 - **The open web.** A shared link unfurls (description, Open Graph, a
79 large generated card at `/og.png`); every page names its canonical
80 address and carries `WebSite` structured data; there is an icon
81 (`/icon.svg`), a 180px home-screen icon and a manifest; `/sitemap.xml`
82 and `/llms.txt` describe the site; `/robots.txt` keeps crawlers to the
83 page (and names the sitemap), and out of previews entirely;
84 `/.well-known/security.txt` names the forge that runs the app as the
85 place to report; `/.well-known/change-password` sends people to it too.
86 A page carries an `ETag` and answers `If-None-Match` with 304. A
87 missing page and a failure are the app's own page, with the right
88 status. HSTS covers subdomains and is never a preload promise.
89 - **Reachable.** A skip link and `<main id="main">`, forced-colours
90 styles, and one `<h1>` with no skipped level (`src/site.test.ts` holds
91 all of it).
92 - **Small on the wire.** `src/compress.ts` gzips text of a kilobyte or
93 more for browsers that read gzip (never the event stream); a proxy in
94 front that compresses sees `content-encoding` and leaves it alone.
95 - **Left to the owner.** Telling AI crawlers what they may do, content
96 signals, an agent card and `.md` versions of pages are decisions about
97 who may read the site and for what; the template makes none of them.
98 Decide, then add them (and a test) deliberately. The card and icons are
99 flat shapes in the accent colour, not a drawn logo: swap in your own.
100
101 ## Who you are
102
103 The forge says who is asking on every request it proxies, and the app
104 verifies the signature (`src/who.ts`); nothing else is trusted. Three tiers:
105
106 - **anon** — anyone. Reads.
107 - **user** — signed in to the forge and able to see this app. Adds notes, as
108 themselves, and removes their own.
109 - **admin** — able to write this repository. Removes any note.
110
111 "Sign in" is `/signin`: the OpenID Connect code flow with PKCE against
112 `FORGE_URL` (`src/signin.ts`). The app registers its own redirect
113 address on first boot and keeps the client id in `FORGE_APP_DATA`, checks
114 the `id_token` itself, and keeps a session in an HttpOnly cookie. A person
115 signed in this way is a `user`; `admin` still comes from the forge's
116 signed headers (which win over a session), until those are retired. "Sign out" is a POST to `/signout`.
117 The forge answers `/__forge/report`: it sends anyone, with no account, to report a
118 problem on this app's repository, if that repository is public.
119
120 ## Any interface
121
122 The same actions, the same rules, at every door. A script is the person
123 whose forge grant it carries; a bare script is anonymous.
124
125 ```sh
126 curl https://<app>/api/notes
127 curl -X POST https://<app>/api/notes -H 'content-type: application/json' -d '{"body":"hi"}'
128 curl -X DELETE https://<app>/api/notes/1
129 ```
130
131 As an MCP server, for Claude Code or Claude Desktop — `list_notes`,
132 `add_note`, `delete_note`:
133
134 ```sh
135 claude mcp add --transport http __TITLE__ https://<app>/mcp
136 ```
137
138 ```json
139 {
140 "mcpServers": { "__TITLE__": { "type": "http", "url": "https://<app>/mcp" } }
141 }
142 ```
143
144 The page stays current over `/events`: a note someone else adds or removes
145 appears without a reload. Without JavaScript it is the same page, one
146 reload behind.
147
148 The terminal opens with the exact command in `FORGE_APP_SSH` when the app
149 runs (`ssh -p 2222 <name>@<forge>` — the app is the login name, the forge
150 the host; `<name>--<pull>@<forge>` for a preview's). It is `src/tty.ts` on
151 a real pty over the same data, as the account at the keyboard.
152
153 The forge sets `PORT`, `FORGE_APP_DATA`, `FORGE_APP_ENV` (`production` or
154 `preview`), `FORGE_APP_URL`, `FORGE_APP_COMMIT`, `FORGE_APP_SSH` and
155 `FORGE_APP_IDENTITY_KEY` when it starts the app. `forge.json` says how.
template/contract.json added +30
@@ -0,0 +1,30 @@
1 {
2 "roles": {
3 "anon": { "above": [], "held": { "by": "everyone" } },
4 "user": { "above": ["anon"], "held": { "by": "identity", "role": "user" } },
5 "author": { "above": ["user"], "held": { "by": "row", "column": "author_id" } },
6 "admin": { "above": ["author"], "held": { "by": "identity", "role": "admin" } }
7 },
8 "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 },
19 "audit": {
20 "api": "/api/audit",
21 "can": {
22 "create": "nobody",
23 "read": "admin",
24 "update": "nobody",
25 "delete": "nobody",
26 "list": "admin"
27 }
28 }
29 }
30 }
template/contract/openapi.json added +578
@@ -0,0 +1,578 @@
1 {
2 "openapi": "3.1.0",
3 "info": {
4 "title": "app-template",
5 "version": "0.1.0",
6 "description": "A new app on the forge."
7 },
8 "paths": {
9 "/api/notes": {
10 "get": {
11 "summary": "The notes, newest first.",
12 "operationId": "getApiNotes",
13 "parameters": [
14 {
15 "name": "limit",
16 "in": "query",
17 "schema": {
18 "type": "integer",
19 "minimum": 1,
20 "maximum": 500,
21 "default": 100
22 }
23 }
24 ],
25 "responses": {
26 "200": {
27 "description": "The notes, newest first.",
28 "content": {
29 "application/json": {
30 "schema": {
31 "type": "array",
32 "items": {
33 "$ref": "#/components/schemas/Note"
34 }
35 }
36 }
37 }
38 },
39 "default": {
40 "description": "{ error, message }: why not",
41 "content": {
42 "application/json": {
43 "schema": {
44 "$ref": "#/components/schemas/Error"
45 }
46 }
47 }
48 }
49 },
50 "x-contract": {
51 "resource": "note",
52 "verb": "list",
53 "least": "anon"
54 }
55 },
56 "post": {
57 "summary": "Add a note as the person asking.",
58 "operationId": "postApiNotes",
59 "requestBody": {
60 "required": true,
61 "content": {
62 "application/json": {
63 "schema": {
64 "type": "object",
65 "properties": {
66 "body": {
67 "type": "string",
68 "minLength": 1,
69 "maxLength": 500
70 }
71 },
72 "required": [
73 "body"
74 ]
75 }
76 }
77 }
78 },
79 "responses": {
80 "201": {
81 "description": "Add a note as the person asking.",
82 "content": {
83 "application/json": {
84 "schema": {
85 "$ref": "#/components/schemas/Note"
86 }
87 }
88 }
89 },
90 "default": {
91 "description": "{ error, message }: why not",
92 "content": {
93 "application/json": {
94 "schema": {
95 "$ref": "#/components/schemas/Error"
96 }
97 }
98 }
99 }
100 },
101 "x-contract": {
102 "resource": "note",
103 "verb": "create",
104 "least": "user"
105 }
106 }
107 },
108 "/api/notes/{id}": {
109 "get": {
110 "summary": "One note.",
111 "operationId": "getApiNotesId",
112 "parameters": [
113 {
114 "name": "id",
115 "in": "path",
116 "required": true,
117 "schema": {
118 "type": "integer"
119 }
120 }
121 ],
122 "responses": {
123 "200": {
124 "description": "One note.",
125 "content": {
126 "application/json": {
127 "schema": {
128 "$ref": "#/components/schemas/Note"
129 }
130 }
131 }
132 },
133 "default": {
134 "description": "{ error, message }: why not",
135 "content": {
136 "application/json": {
137 "schema": {
138 "$ref": "#/components/schemas/Error"
139 }
140 }
141 }
142 }
143 },
144 "x-contract": {
145 "resource": "note",
146 "verb": "read",
147 "least": "anon"
148 }
149 },
150 "patch": {
151 "summary": "Change a note's words.",
152 "operationId": "patchApiNotesId",
153 "parameters": [
154 {
155 "name": "id",
156 "in": "path",
157 "required": true,
158 "schema": {
159 "type": "integer"
160 }
161 }
162 ],
163 "requestBody": {
164 "required": true,
165 "content": {
166 "application/json": {
167 "schema": {
168 "type": "object",
169 "properties": {
170 "body": {
171 "type": "string",
172 "minLength": 1,
173 "maxLength": 500
174 }
175 },
176 "required": [
177 "body"
178 ]
179 }
180 }
181 }
182 },
183 "responses": {
184 "200": {
185 "description": "Change a note's words.",
186 "content": {
187 "application/json": {
188 "schema": {
189 "$ref": "#/components/schemas/Note"
190 }
191 }
192 }
193 },
194 "default": {
195 "description": "{ error, message }: why not",
196 "content": {
197 "application/json": {
198 "schema": {
199 "$ref": "#/components/schemas/Error"
200 }
201 }
202 }
203 }
204 },
205 "x-contract": {
206 "resource": "note",
207 "verb": "update",
208 "least": "author"
209 }
210 },
211 "delete": {
212 "summary": "Remove a note.",
213 "operationId": "deleteApiNotesId",
214 "parameters": [
215 {
216 "name": "id",
217 "in": "path",
218 "required": true,
219 "schema": {
220 "type": "integer"
221 }
222 }
223 ],
224 "responses": {
225 "200": {
226 "description": "Remove a note.",
227 "content": {
228 "application/json": {
229 "schema": {
230 "type": "object",
231 "properties": {
232 "id": {
233 "type": "integer"
234 }
235 },
236 "required": [
237 "id"
238 ]
239 }
240 }
241 }
242 },
243 "default": {
244 "description": "{ error, message }: why not",
245 "content": {
246 "application/json": {
247 "schema": {
248 "$ref": "#/components/schemas/Error"
249 }
250 }
251 }
252 }
253 },
254 "x-contract": {
255 "resource": "note",
256 "verb": "delete",
257 "least": "author"
258 }
259 }
260 },
261 "/api/audit": {
262 "get": {
263 "summary": "The audit trail, newest first; `before` pages back by id.",
264 "operationId": "getApiAudit",
265 "parameters": [
266 {
267 "name": "limit",
268 "in": "query",
269 "schema": {
270 "type": "integer",
271 "minimum": 1,
272 "maximum": 500,
273 "default": 100
274 }
275 },
276 {
277 "name": "before",
278 "in": "query",
279 "schema": {
280 "type": "integer"
281 }
282 }
283 ],
284 "responses": {
285 "200": {
286 "description": "The audit trail, newest first; `before` pages back by id.",
287 "content": {
288 "application/json": {
289 "schema": {
290 "type": "array",
291 "items": {
292 "$ref": "#/components/schemas/AuditRow"
293 }
294 }
295 }
296 }
297 },
298 "default": {
299 "description": "{ error, message }: why not",
300 "content": {
301 "application/json": {
302 "schema": {
303 "$ref": "#/components/schemas/Error"
304 }
305 }
306 }
307 }
308 },
309 "x-contract": {
310 "resource": "audit",
311 "verb": "list",
312 "least": "admin"
313 }
314 }
315 },
316 "/api/audit/{id}": {
317 "get": {
318 "summary": "One row of the audit trail.",
319 "operationId": "getApiAuditId",
320 "parameters": [
321 {
322 "name": "id",
323 "in": "path",
324 "required": true,
325 "schema": {
326 "type": "integer"
327 }
328 }
329 ],
330 "responses": {
331 "200": {
332 "description": "One row of the audit trail.",
333 "content": {
334 "application/json": {
335 "schema": {
336 "$ref": "#/components/schemas/AuditRow"
337 }
338 }
339 }
340 },
341 "default": {
342 "description": "{ error, message }: why not",
343 "content": {
344 "application/json": {
345 "schema": {
346 "$ref": "#/components/schemas/Error"
347 }
348 }
349 }
350 }
351 },
352 "x-contract": {
353 "resource": "audit",
354 "verb": "read",
355 "least": "admin"
356 }
357 }
358 },
359 "/mcp": {
360 "post": {
361 "summary": "One JSON-RPC 2.0 message to the MCP server; its tools are the actions.",
362 "operationId": "postMcp",
363 "requestBody": {
364 "required": true,
365 "content": {
366 "application/json": {
367 "schema": {
368 "type": "object",
369 "properties": {
370 "jsonrpc": {
371 "const": "2.0"
372 },
373 "id": {},
374 "method": {
375 "type": "string"
376 },
377 "params": {
378 "type": "object"
379 }
380 },
381 "required": [
382 "jsonrpc",
383 "method"
384 ]
385 }
386 }
387 }
388 },
389 "responses": {
390 "200": {
391 "description": "One JSON-RPC 2.0 message to the MCP server; its tools are the actions.",
392 "content": {
393 "application/json": {
394 "schema": {
395 "type": "object"
396 }
397 }
398 }
399 },
400 "default": {
401 "description": "{ error, message }: why not",
402 "content": {
403 "application/json": {
404 "schema": {
405 "$ref": "#/components/schemas/Error"
406 }
407 }
408 }
409 }
410 }
411 }
412 },
413 "/healthz": {
414 "get": {
415 "summary": "Whether the app is up: its version, commit, environment and seconds since it started.",
416 "operationId": "getHealthz",
417 "responses": {
418 "200": {
419 "description": "Whether the app is up: its version, commit, environment and seconds since it started.",
420 "content": {
421 "application/json": {
422 "schema": {
423 "type": "object",
424 "properties": {
425 "ok": {
426 "type": "boolean"
427 },
428 "version": {
429 "type": "string"
430 },
431 "commit": {
432 "type": "string"
433 },
434 "env": {
435 "type": "string"
436 },
437 "uptime": {
438 "type": "integer"
439 }
440 },
441 "required": [
442 "ok",
443 "version",
444 "uptime"
445 ]
446 }
447 }
448 }
449 },
450 "default": {
451 "description": "{ error, message }: why not",
452 "content": {
453 "application/json": {
454 "schema": {
455 "$ref": "#/components/schemas/Error"
456 }
457 }
458 }
459 }
460 }
461 }
462 }
463 },
464 "components": {
465 "schemas": {
466 "Note": {
467 "type": "object",
468 "properties": {
469 "id": {
470 "type": "integer"
471 },
472 "body": {
473 "type": "string",
474 "minLength": 1,
475 "maxLength": 500
476 },
477 "author_id": {
478 "type": "string"
479 },
480 "author_name": {
481 "type": "string"
482 },
483 "created_at": {
484 "type": "string",
485 "format": "date-time"
486 },
487 "updated_at": {
488 "type": "string",
489 "format": "date-time"
490 }
491 },
492 "required": [
493 "id",
494 "body",
495 "author_id",
496 "author_name",
497 "created_at",
498 "updated_at"
499 ]
500 },
501 "AuditRow": {
502 "type": "object",
503 "properties": {
504 "id": {
505 "type": "integer"
506 },
507 "at": {
508 "type": "string",
509 "format": "date-time"
510 },
511 "who_id": {
512 "type": [
513 "string",
514 "null"
515 ]
516 },
517 "who_name": {
518 "type": [
519 "string",
520 "null"
521 ]
522 },
523 "role": {
524 "enum": [
525 "anon",
526 "user",
527 "admin"
528 ]
529 },
530 "resource": {
531 "type": "string"
532 },
533 "verb": {
534 "type": "string"
535 },
536 "target": {
537 "type": [
538 "string",
539 "null"
540 ]
541 },
542 "allowed": {
543 "enum": [
544 0,
545 1
546 ]
547 },
548 "outcome": {
549 "type": "string"
550 }
551 },
552 "required": [
553 "id",
554 "at",
555 "role",
556 "resource",
557 "verb",
558 "allowed",
559 "outcome"
560 ]
561 },
562 "Error": {
563 "type": "object",
564 "properties": {
565 "error": {
566 "type": "string"
567 },
568 "message": {
569 "type": "string"
570 }
571 },
572 "required": [
573 "error"
574 ]
575 }
576 }
577 }
578 }
template/design/tokens.json added +95
@@ -0,0 +1,95 @@
1 {
2 "$description": "The look, as data (W3C design tokens). Every colour the app shows is here and nowhere else: src/tokens.ts compiles this to /tokens.css at boot, and bun run lint:design refuses a raw colour anywhere else. A colour's $value is the light theme; $extensions.mode.dark is the dark one.",
3 "color": {
4 "$type": "color",
5 "bg": {
6 "$value": "#f6f6f3",
7 "$extensions": { "mode": { "dark": "#131312" } }
8 },
9 "surface": {
10 "$value": "#ffffff",
11 "$extensions": { "mode": { "dark": "#1d1d1b" } }
12 },
13 "fg": {
14 "$value": "#1c1c1a",
15 "$extensions": { "mode": { "dark": "#ecece7" } }
16 },
17 "muted": {
18 "$value": "#6b6b65",
19 "$extensions": { "mode": { "dark": "#9a9a93" } }
20 },
21 "line": {
22 "$value": "#e3e3dd",
23 "$extensions": { "mode": { "dark": "#2c2c29" } }
24 },
25 "accent": {
26 "$value": "#2f5bea",
27 "$extensions": { "mode": { "dark": "#7c96ff" } }
28 },
29 "accent-fg": {
30 "$value": "#ffffff",
31 "$extensions": { "mode": { "dark": "#0f1a4d" } }
32 },
33 "danger": {
34 "$value": "#c2410c",
35 "$extensions": { "mode": { "dark": "#fb923c" } }
36 },
37 "toast-bg": {
38 "$value": "#1c1c1a",
39 "$extensions": { "mode": { "dark": "#ecece7" } }
40 },
41 "toast-fg": {
42 "$value": "#f6f6f3",
43 "$extensions": { "mode": { "dark": "#131312" } }
44 },
45 "shadow": {
46 "$value": "#0000002e",
47 "$extensions": { "mode": { "dark": "#00000080" } }
48 }
49 },
50 "space": {
51 "$type": "dimension",
52 "1": { "$value": "0.25rem" },
53 "2": { "$value": "0.5rem" },
54 "3": { "$value": "0.75rem" },
55 "4": { "$value": "1rem" },
56 "5": { "$value": "1.5rem" },
57 "6": { "$value": "2.5rem" }
58 },
59 "radius": {
60 "$type": "dimension",
61 "md": { "$value": "10px" },
62 "pill": { "$value": "999px" }
63 },
64 "size": {
65 "$type": "dimension",
66 "tap": {
67 "$value": "44px",
68 "$description": "The least a control measures on a side."
69 }
70 },
71 "font": {
72 "$type": "fontFamily",
73 "sans": {
74 "$value": ["system-ui", "-apple-system", "Segoe UI", "sans-serif"]
75 },
76 "mono": {
77 "$value": ["ui-monospace", "SFMono-Regular", "Menlo", "monospace"]
78 }
79 },
80 "text": {
81 "$type": "dimension",
82 "sm": { "$value": "0.875rem" },
83 "base": {
84 "$value": "1rem",
85 "$description": "Never below 16px: a phone zooms into a smaller input."
86 },
87 "lg": { "$value": "1.125rem" },
88 "xl": { "$value": "1.5rem" }
89 },
90 "leading": {
91 "$type": "number",
92 "body": { "$value": 1.55 },
93 "tight": { "$value": 1.2 }
94 }
95 }
template/forge.json added +8
@@ -0,0 +1,8 @@
1 {
2 "app": {
3 "run": "bun run src/server.ts",
4 "test": "bun test",
5 "health": "/healthz",
6 "tty": "bun run src/tty.ts"
7 }
8 }
template/package.json added +13
@@ -0,0 +1,13 @@
1 {
2 "name": "app-template",
3 "version": "0.1.0",
4 "description": "A new app on the forge.",
5 "private": true,
6 "type": "module",
7 "scripts": {
8 "start": "bun run src/server.ts",
9 "test": "bun test",
10 "lint:design": "bun run scripts/lint-design.ts",
11 "contract:emit": "bun run scripts/contract-emit.ts"
12 }
13 }
template/scripts/contract-emit.ts added +14
@@ -0,0 +1,14 @@
1 /**
2 * Write the API's description where git keeps it: contract/openapi.json,
3 * from the routes' own `api` entries (src/openapi.ts). Run it after
4 * changing a route or a cell of contract.json; the tests say when it is due.
5 */
6
7 import { mkdirSync, writeFileSync } from "node:fs";
8 import { join } from "node:path";
9 import { emit } from "../src/openapi.ts";
10
11 const dir = join(import.meta.dir, "..", "contract");
12 mkdirSync(dir, { recursive: true });
13 writeFileSync(join(dir, "openapi.json"), emit());
14 console.log("wrote contract/openapi.json");
template/scripts/lint-design.ts added +77
@@ -0,0 +1,77 @@
1 /**
2 * Every colour comes from `design/tokens.json`. This refuses a raw one —
3 * `#hex`, `rgb(`, `hsl(` — anywhere else the app draws from: `static/`
4 * and `src/`, tests aside. A colour spelled out in a stylesheet is a colour
5 * the dark theme never hears about. It refuses a `var(--…)` in a stylesheet
6 * that names no token, too: a typo there is a page quietly unstyled.
7 *
8 * bun run lint:design exit 1 and one line per raw colour, or silence
9 */
10
11 import { readdirSync, readFileSync } from "node:fs";
12 import { join } from "node:path";
13 import { tokens } from "../src/tokens.ts";
14
15 const RAW =
16 /(?<![\w&])#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})(?![\w-])|\b(?:rgba?|hsla?)\(/gi;
17
18 /** The raw colours in one file's text: `path:line: …`, one per find. */
19 export function rawColours(path: string, text: string): string[] {
20 return text
21 .split("\n")
22 .flatMap((line, i) =>
23 [...line.matchAll(RAW)].map(
24 (m) =>
25 `${path}:${i + 1}: raw colour ${m[0]} — name it in design/tokens.json and use var(--…)`,
26 ),
27 );
28 }
29
30 /** The custom properties a stylesheet uses that no token defines. */
31 export function unknownTokens(
32 path: string,
33 text: string,
34 known = new Set(tokens.map((t) => t.name)),
35 ): string[] {
36 return text
37 .split("\n")
38 .flatMap((line, i) =>
39 [...line.matchAll(/var\((--[\w-]+)/g)]
40 .filter((m) => !known.has(m[1]!))
41 .map(
42 (m) =>
43 `${path}:${i + 1}: ${m[1]} is not a token in design/tokens.json`,
44 ),
45 );
46 }
47
48 /** The files the lint reads: what the page is drawn from, never the tokens themselves or the tests. */
49 export function drawnFrom(root: string): string[] {
50 const walk = (dir: string): string[] =>
51 readdirSync(join(root, dir), { withFileTypes: true }).flatMap((entry) => {
52 const path = join(dir, entry.name);
53 if (entry.isDirectory()) return walk(path);
54 return /\.(css|js|ts|html)$/.test(entry.name) &&
55 !/\.test\.ts$/.test(entry.name)
56 ? [path]
57 : [];
58 });
59 return ["static", "src"].flatMap(walk);
60 }
61
62 export function lint(root: string): string[] {
63 return drawnFrom(root).flatMap((path) => {
64 const text = readFileSync(join(root, path), "utf8");
65 return [
66 ...rawColours(path, text),
67 ...(path.endsWith(".css") ? unknownTokens(path, text) : []),
68 ];
69 });
70 }
71
72 if (import.meta.main) {
73 const problems = lint(join(import.meta.dir, ".."));
74 // Generated app's lint CLI: stderr is its output.
75 for (const problem of problems) console.error(problem);
76 process.exit(problems.length === 0 ? 0 : 1);
77 }
template/src/actions.test.ts added +63
@@ -0,0 +1,63 @@
1 import { afterAll, expect, test } from "bun:test";
2 import { mkdtempSync, rmSync } 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 dir = mkdtempSync(join(tmpdir(), "app-actions-"));
10 const db = openDb(dir);
11 afterAll(() => {
12 db.close();
13 rmSync(dir, { recursive: true, force: true });
14 });
15 const anon: Who = { role: "anon" };
16 const alice: Who = { role: "user", id: "u1", name: "alice" };
17 const bob: Who = { role: "user", id: "u2", name: "bob" };
18 const root: Who = { role: "admin", id: "u0", name: "root" };
19
20 test("anyone reads; only a signed-in person adds, as themselves", () => {
21 expect(listNotes(db, anon)).toEqual({ ok: true, value: [] });
22 const refused = addNote(db, anon, { body: "hello" });
23 expect(refused.ok).toBe(false);
24 if (!refused.ok) expect(refused.error).toBe("signin_required");
25 const added = addNote(db, alice, { body: " hello " });
26 expect(added.ok).toBe(true);
27 if (!added.ok) return;
28 expect(added.value.body).toBe("hello");
29 expect(added.value.author_id).toBe("u1");
30 expect(added.value.author_name).toBe("alice");
31 const all = listNotes(db, anon);
32 expect(all.ok && all.value.length).toBe(1);
33 });
34
35 test("a note is one to five hundred characters", () => {
36 for (const body of ["", " ", "x".repeat(501)]) {
37 const r = addNote(db, alice, { body });
38 expect(r.ok).toBe(false);
39 if (!r.ok) expect(r.error).toBe("invalid");
40 }
41 });
42
43 test("only the author or an admin removes a note", () => {
44 const mine = addNote(db, alice, { body: "mine" });
45 if (!mine.ok) throw new Error(mine.message);
46 const byBob = deleteNote(db, bob, { id: mine.value.id });
47 expect(byBob.ok).toBe(false);
48 if (!byBob.ok) expect(byBob.error).toBe("forbidden");
49 const byAnon = deleteNote(db, anon, { id: mine.value.id });
50 expect(byAnon.ok).toBe(false);
51 if (!byAnon.ok) expect(byAnon.error).toBe("signin_required");
52 expect(deleteNote(db, alice, { id: mine.value.id }).ok).toBe(true);
53 const gone = deleteNote(db, alice, { id: mine.value.id });
54 expect(gone.ok).toBe(false);
55 if (!gone.ok) expect(gone.error).toBe("not_found");
56
57 const bobs = addNote(db, bob, { body: "bob's" });
58 if (!bobs.ok) throw new Error(bobs.message);
59 expect(deleteNote(db, root, { id: bobs.value.id }).ok).toBe(true);
60 const odd = deleteNote(db, root, { id: 1.5 });
61 expect(odd.ok).toBe(false);
62 if (!odd.ok) expect(odd.error).toBe("invalid");
63 });
template/src/actions.ts added +271
@@ -0,0 +1,271 @@
1 /**
2 * Everything the app can do, as plain functions: `(db, who, input)` in,
3 * data or a named failure out. The page, the JSON API, the MCP server and
4 * the terminal are doors onto these and decide nothing themselves — so a
5 * rule written here holds at every door, and a new door is only a new
6 * way to call.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { record, type AuditRow } from "./audit.ts";
11 import { permit } from "./contract.ts";
12 import { emit } from "./live.ts";
13 import type { Who } from "./who.ts";
14
15 export interface Note {
16 readonly id: number;
17 readonly body: string;
18 readonly author_id: string;
19 readonly author_name: string;
20 readonly created_at: string;
21 readonly updated_at: string;
22 }
23
24 export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid";
25 export type Result<T> =
26 | { ok: true; value: T }
27 | { ok: false; error: Failure; message: string };
28 const ok = <T>(value: T): Result<T> => ({ ok: true, value });
29 const fail = <T>(error: Failure, message: string): Result<T> => ({
30 ok: false,
31 error,
32 message,
33 });
34
35 export const BODY_MAX = 500;
36
37 /** The refusal for a "no": who is not signed in is asked to; who is, is told. */
38 const refuse = <T>(who: Who, signIn: string, no: string): Result<T> =>
39 who.role === "anon" ? fail("signin_required", signIn) : fail("forbidden", no);
40
41 /**
42 * A change, written into the audit trail whichever way it went: the row it
43 * made or touched, or the one it was refused. Every action that changes
44 * something returns through here, so the trail holds at every door.
45 */
46 const audited = <T extends { readonly id: number }>(
47 db: Database,
48 who: Who,
49 resource: string,
50 verb: "create" | "update" | "delete",
51 target: number | undefined,
52 result: Result<T>,
53 ): Result<T> => {
54 record(db, {
55 who,
56 resource,
57 verb,
58 target: result.ok ? result.value.id : target,
59 outcome: result.ok ? "ok" : result.error,
60 });
61 return result;
62 };
63
64 export function listNotes(
65 db: Database,
66 who: Who,
67 input: { limit?: number } = {},
68 ): Result<Note[]> {
69 const limit = Math.min(
70 Math.max(Math.trunc(input.limit ?? 100) || 100, 1),
71 500,
72 );
73 // "yes" is every note. When the table gives `list` to a role a row holds
74 // (`author`), the answer names the columns instead, and the list is the
75 // notes that name whoever asks. The names are the contract's, checked when
76 // it was read; the value is bound.
77 const may = permit(who, "note", "list");
78 if (may === "no")
79 return refuse(who, "Sign in to see notes.", "You may not see these notes.");
80 if (may === "yes")
81 return ok(
82 db
83 .query<Note, [number]>("SELECT * FROM note ORDER BY id DESC LIMIT ?1")
84 .all(limit),
85 );
86 const mine = may.where.map((column) => `${column} = ?2`).join(" OR ");
87 return ok(
88 db
89 .query<
90 Note,
91 [number, string]
92 >(`SELECT * FROM note WHERE ${mine} ORDER BY id DESC LIMIT ?1`)
93 .all(limit, who.role === "anon" ? "" : who.id),
94 );
95 }
96
97 export const addNote = (
98 db: Database,
99 who: Who,
100 input: { body: string },
101 ): Result<Note> =>
102 audited(db, who, "note", "create", undefined, add(db, who, input));
103
104 function add(db: Database, who: Who, input: { body: string }): Result<Note> {
105 // The table decides; the type only learns it here: whoever may create is
106 // signed in, and carries a name to write beside the note.
107 if (who.role === "anon" || permit(who, "note", "create") !== "yes")
108 return refuse(who, "Sign in to add a note.", "You may not add a note.");
109 const body = input.body.trim();
110 if (body.length === 0 || body.length > BODY_MAX)
111 return fail("invalid", `A note is 1 to ${BODY_MAX} characters.`);
112 const note = db
113 .query<
114 Note,
115 [string, string, string]
116 >("INSERT INTO note (body, author_id, author_name) VALUES (?1, ?2, ?3) RETURNING *")
117 .get(body, who.id, who.name)!;
118 emit("note.added", note);
119 return ok(note);
120 }
121
122 /**
123 * One note, for `who` to do `verb` to. The door is asked before the row is
124 * looked for, so whoever may not is told that and never learns whether the
125 * row exists; whoever may, and asked for nothing, hears `not_found`.
126 */
127 function noteFor(
128 db: Database,
129 who: Who,
130 verb: "read" | "update" | "delete",
131 id: number,
132 said: { signIn: string; no: string },
133 ): Result<Note> {
134 const note = Number.isInteger(id)
135 ? db.query<Note, [number]>("SELECT * FROM note WHERE id = ?1").get(id)
136 : null;
137 // With no row to show, the door is asked about a row of their own: whoever
138 // could not pass even then is refused, and learns nothing about what
139 // exists; whoever could is told there is no such note.
140 const row: Readonly<Record<string, unknown>> =
141 note === null ? { author_id: who.role === "anon" ? null : who.id } : { ...note };
142 if (permit(who, "note", verb, row) !== "yes")
143 return refuse(who, said.signIn, said.no);
144 if (note !== null) return ok(note);
145 if (!Number.isInteger(id))
146 return fail("invalid", "A note id is a whole number.");
147 return fail("not_found", "No such note.");
148 }
149
150 export function getNote(
151 db: Database,
152 who: Who,
153 input: { id: number },
154 ): Result<Note> {
155 return noteFor(db, who, "read", input.id, {
156 signIn: "Sign in to read this note.",
157 no: "You may not read this note.",
158 });
159 }
160
161 export const updateNote = (
162 db: Database,
163 who: Who,
164 input: { id: number; body: string },
165 ): Result<Note> =>
166 audited(db, who, "note", "update", input.id, update(db, who, input));
167
168 function update(
169 db: Database,
170 who: Who,
171 input: { id: number; body: string },
172 ): Result<Note> {
173 const found = noteFor(db, who, "update", input.id, {
174 signIn: "Sign in to edit a note.",
175 no: "Only the author or an admin can edit a note.",
176 });
177 if (!found.ok) return found;
178 const body = input.body.trim();
179 if (body.length === 0 || body.length > BODY_MAX)
180 return fail("invalid", `A note is 1 to ${BODY_MAX} characters.`);
181 const note = db
182 .query<
183 Note,
184 [string, number]
185 >("UPDATE note SET body = ?1, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE id = ?2 RETURNING *")
186 .get(body, found.value.id)!;
187 emit("note.changed", note);
188 return ok(note);
189 }
190
191 export const deleteNote = (
192 db: Database,
193 who: Who,
194 input: { id: number },
195 ): Result<{ id: number }> =>
196 audited(db, who, "note", "delete", input.id, remove(db, who, input));
197
198 function remove(
199 db: Database,
200 who: Who,
201 input: { id: number },
202 ): Result<{ id: number }> {
203 const found = noteFor(db, who, "delete", input.id, {
204 signIn: "Sign in to remove a note.",
205 no: "Only the author or an admin can remove a note.",
206 });
207 if (!found.ok) return found;
208 db.query("DELETE FROM note WHERE id = ?1").run(found.value.id);
209 emit("note.removed", { id: found.value.id });
210 return ok({ id: found.value.id });
211 }
212
213 /** Whether `who` may remove `note`: the table's answer, for the page and the terminal to draw from. */
214 export const canDelete = (who: Who, note: Note): boolean =>
215 permit(who, "note", "delete", { ...note }) === "yes";
216
217 /**
218 * The audit trail, newest first, for whoever the table lets read it (an
219 * admin, as the scaffold has it). `before` pages back by id. Audit rows name
220 * no author, so a cell that gave `list` to a row's role would find nothing
221 * of its own: anything but "yes" is a refusal here.
222 */
223 export function listAudit(
224 db: Database,
225 who: Who,
226 input: { limit?: number; before?: number } = {},
227 ): Result<AuditRow[]> {
228 if (permit(who, "audit", "list") !== "yes")
229 return refuse(
230 who,
231 "Sign in to read the audit trail.",
232 "Only an admin can read the audit trail.",
233 );
234 const limit = Math.min(
235 Math.max(Math.trunc(input.limit ?? 100) || 100, 1),
236 500,
237 );
238 const before = Number.isInteger(input.before)
239 ? input.before!
240 : Number.MAX_SAFE_INTEGER;
241 return ok(
242 db
243 .query<
244 AuditRow,
245 [number, number]
246 >("SELECT * FROM audit WHERE id < ?1 ORDER BY id DESC LIMIT ?2")
247 .all(before, limit),
248 );
249 }
250
251 export function getAudit(
252 db: Database,
253 who: Who,
254 input: { id: number },
255 ): Result<AuditRow> {
256 const row = Number.isInteger(input.id)
257 ? db
258 .query<AuditRow, [number]>("SELECT * FROM audit WHERE id = ?1")
259 .get(input.id)
260 : null;
261 if (permit(who, "audit", "read", { ...row }) !== "yes")
262 return refuse(
263 who,
264 "Sign in to read the audit trail.",
265 "Only an admin can read the audit trail.",
266 );
267 if (row !== null) return ok(row);
268 if (!Number.isInteger(input.id))
269 return fail("invalid", "An audit id is a whole number.");
270 return fail("not_found", "No such audit row.");
271 }
template/src/audit.test.ts added +188
@@ -0,0 +1,188 @@
1 /**
2 * The trail: an allowed change and a refused one each leave a row, through
3 * the real server; only an admin reads them; and a trail that cannot be
4 * written costs a log line, never the request.
5 */
6 import { afterAll, expect, spyOn, test } from "bun:test";
7 import { mkdtempSync, rmSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { addNote } from "./actions.ts";
11 import type { AuditRow } from "./audit.ts";
12 import { openDb } from "./db.ts";
13 import { serve } from "./server.ts";
14 import { sign } from "./who.ts";
15
16 const KEY = "a-key-only-the-forge-holds";
17 const dataDir = mkdtempSync(join(tmpdir(), "app-audit-"));
18 const server = serve({ port: 0, dataDir, identityKey: KEY });
19 const base = `http://${server.hostname}:${server.port}`;
20 afterAll(() => {
21 server.stop(true);
22 rmSync(dataDir, { recursive: true, force: true });
23 });
24
25 const as = (
26 id: string,
27 name: string,
28 role: "user" | "admin" = "user",
29 ): Record<string, string> => {
30 const identity = `${id}|${name}|${role}|${Date.now() + 60_000}`;
31 return {
32 "x-forge-identity": identity,
33 "x-forge-signature": sign(identity, KEY),
34 };
35 };
36 const alice = as("u1", "alice");
37 const bob = as("u2", "bob");
38 const root = as("u0", "root", "admin");
39 const call = (
40 path: string,
41 init: RequestInit = {},
42 who: Record<string, string> = {},
43 ) =>
44 fetch(base + path, {
45 ...init,
46 headers: { "content-type": "application/json", ...who },
47 });
48 const trail = async (): Promise<AuditRow[]> =>
49 (await (await call("/api/audit", {}, root)).json()) as AuditRow[];
50
51 test("an allowed change and a refused one each leave a row", async () => {
52 const made = await call(
53 "/api/notes",
54 { method: "POST", body: JSON.stringify({ body: "kept" }) },
55 alice,
56 );
57 expect(made.status).toBe(201);
58 const note = (await made.json()) as { id: number };
59 // Refused at the door: a stranger may create nothing.
60 expect(
61 (
62 await call("/api/notes", {
63 method: "POST",
64 body: JSON.stringify({ body: "x" }),
65 })
66 ).status,
67 ).toBe(401);
68 // Refused by the action: bob could delete a note of his own, not alice's.
69 expect(
70 (await call(`/api/notes/${note.id}`, { method: "DELETE" }, bob)).status,
71 ).toBe(403);
72 // Refused as cross-site, before the table is asked.
73 const forged = await fetch(`${base}/api/notes/${note.id}`, {
74 method: "DELETE",
75 headers: { ...alice, "sec-fetch-site": "cross-site" },
76 });
77 expect(forged.status).toBe(403);
78
79 const rows = (await trail()).slice(0, 4).reverse();
80 expect(
81 rows.map(
82 ({ who_name, role, resource, verb, target, allowed, outcome }) => ({
83 who_name,
84 role,
85 resource,
86 verb,
87 target,
88 allowed,
89 outcome,
90 }),
91 ),
92 ).toEqual([
93 {
94 who_name: "alice",
95 role: "user",
96 resource: "note",
97 verb: "create",
98 target: String(note.id),
99 allowed: 1,
100 outcome: "ok",
101 },
102 {
103 who_name: null,
104 role: "anon",
105 resource: "note",
106 verb: "create",
107 target: null,
108 allowed: 0,
109 outcome: "signin_required",
110 },
111 {
112 who_name: "bob",
113 role: "user",
114 resource: "note",
115 verb: "delete",
116 target: String(note.id),
117 allowed: 0,
118 outcome: "forbidden",
119 },
120 {
121 who_name: "alice",
122 role: "user",
123 resource: "note",
124 verb: "delete",
125 target: null,
126 allowed: 0,
127 outcome: "cross_site",
128 },
129 ]);
130 for (const row of rows)
131 expect(Date.parse(row.at)).toBeGreaterThan(Date.now() - 60_000);
132 });
133
134 test("reading is not an event: a GET leaves no row", async () => {
135 const before = (await trail()).length;
136 await call("/api/notes");
137 await call("/", {}, alice);
138 expect((await trail()).length).toBe(before);
139 });
140
141 test("only an admin reads the trail, at every door the table names", async () => {
142 expect((await call("/api/audit")).status).toBe(401);
143 expect((await call("/api/audit", {}, alice)).status).toBe(403);
144 const rows = await trail();
145 expect(rows.length).toBeGreaterThan(0);
146 expect((await call(`/api/audit/${rows[0]!.id}`, {}, root)).status).toBe(200);
147 expect((await call(`/api/audit/${rows[0]!.id}`, {}, alice)).status).toBe(403);
148 expect((await call("/api/audit/999999", {}, root)).status).toBe(404);
149 // Nobody writes the trail through a door: not even an admin.
150 expect(
151 (await call("/api/audit", { method: "POST", body: "{}" }, root)).status,
152 ).toBe(403);
153 expect(
154 (await call(`/api/audit/${rows[0]!.id}`, { method: "DELETE" }, root))
155 .status,
156 ).toBe(403);
157 // Paging back: `before` an id is everything older.
158 const older = (await (
159 await call(`/api/audit?before=${rows[0]!.id}&limit=1`, {}, root)
160 ).json()) as AuditRow[];
161 expect(older.map((r) => r.id)).toEqual([rows[1]!.id]);
162 });
163
164 test("a trail that cannot be written is a log line, and the change still happens", () => {
165 const db = openDb(mkdtempSync(join(dataDir, "broken-")));
166 db.exec("DROP TABLE audit");
167 const said = spyOn(console, "error").mockImplementation(() => {});
168 try {
169 const added = addNote(
170 db,
171 { role: "user", id: "u1", name: "alice" },
172 { body: "still here" },
173 );
174 expect(added.ok).toBe(true);
175 expect(said).toHaveBeenCalledTimes(1);
176 const line = JSON.parse(String(said.mock.calls[0]![0]));
177 expect(line.audit).toMatchObject({
178 who_name: "alice",
179 resource: "note",
180 verb: "create",
181 allowed: 1,
182 outcome: "ok",
183 });
184 expect(line.unrecorded).toContain("audit");
185 } finally {
186 said.mockRestore();
187 }
188 });
template/src/audit.ts added +90
@@ -0,0 +1,90 @@
1 /**
2 * The audit trail: every attempt to change something, as one row — who,
3 * what (a resource and a verb from the contract), on which row, when, and
4 * whether they were let. Refusals are rows too: a stranger knocking on a
5 * door that stays shut is exactly what an owner wants to read later.
6 *
7 * Recording never fails a request. A row that cannot be written becomes a
8 * line in the log, with everything the row would have said, and the
9 * request goes on; the log is where the forge keeps a run's output.
10 *
11 * Reads are not recorded (a page view is not an event), and neither is a
12 * request refused for coming too fast: a flood must not become the history,
13 * or push the real history out.
14 */
15
16 import type { Database } from "bun:sqlite";
17 import type { Who } from "./who.ts";
18
19 export interface AuditRow {
20 readonly id: number;
21 readonly at: string;
22 readonly who_id: string | null;
23 readonly who_name: string | null;
24 readonly role: string;
25 readonly resource: string;
26 readonly verb: string;
27 readonly target: string | null;
28 readonly allowed: 0 | 1;
29 /** `ok`, or the failure: `signin_required`, `forbidden`, `invalid`, `not_found`, `cross_site`. */
30 readonly outcome: string;
31 }
32
33 export interface Attempt {
34 readonly who: Who;
35 readonly resource: string;
36 readonly verb: string;
37 readonly target?: string | number | undefined;
38 readonly outcome: string;
39 }
40
41 /** The newest rows kept; older ones go as new ones come. */
42 export const KEEP = 50_000;
43
44 /** Was it let? Only the door says no; a bad body or a missing row got past it. */
45 export const allowed = (outcome: string): boolean =>
46 outcome !== "signin_required" &&
47 outcome !== "forbidden" &&
48 outcome !== "cross_site";
49
50 export function record(db: Database, attempt: Attempt): void {
51 const { who, resource, verb, target, outcome } = attempt;
52 const row = {
53 who_id: who.role === "anon" ? null : who.id,
54 who_name: who.role === "anon" ? null : who.name,
55 role: who.role,
56 resource,
57 verb,
58 target: target === undefined ? null : String(target),
59 allowed: allowed(outcome) ? 1 : 0,
60 outcome,
61 };
62 try {
63 const { lastInsertRowid } = db
64 .query(
65 "INSERT INTO audit (who_id, who_name, role, resource, verb, target, allowed, outcome) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
66 )
67 .run(
68 row.who_id,
69 row.who_name,
70 row.role,
71 row.resource,
72 row.verb,
73 row.target,
74 row.allowed,
75 row.outcome,
76 );
77 db.query("DELETE FROM audit WHERE id <= ?1").run(
78 Number(lastInsertRowid) - KEEP,
79 );
80 } catch (error) {
81 // Generated app: one JSON line to stderr, its own log.
82 console.error(
83 JSON.stringify({
84 audit: row,
85 at: new Date().toISOString(),
86 unrecorded: String(error),
87 }),
88 );
89 }
90 }
template/src/can.ts added +389
@@ -0,0 +1,389 @@
1 /**
2 * Who may do what, decided from a table.
3 *
4 * An app's permissions are data: `contract.json` declares its roles and, for
5 * every resource, the least role each of the five verbs needs. This file is
6 * the whole evaluator. It is self-contained on purpose — no imports, no
7 * classes, nothing but values and total functions — because it is carried
8 * verbatim into every app the forge scaffolds, read by the forge to audit an
9 * app without running it, and meant to be ported line for line.
10 *
11 * Roles form an order, not a list. `above` names the roles directly below a
12 * role, and a role may do whatever anything below it may. How a role is
13 * *held* is a value too: by everyone, by an identity the forge signed, or by
14 * the row naming the actor. Adding a role adds a line to the contract and
15 * nothing here: the evaluator is the same size for three roles or three
16 * hundred.
17 *
18 * Everything fails closed: an undeclared resource, verb or role is "no".
19 */
20
21 export type Verb = "create" | "read" | "update" | "delete" | "list";
22 export const VERBS: readonly Verb[] = [
23 "create",
24 "read",
25 "update",
26 "delete",
27 "list",
28 ];
29
30 /** The cell that lets nobody in. Not a role: nothing can be above it. */
31 export const NOBODY = "nobody";
32
33 /** How a role is held. */
34 export type Held =
35 /** By anyone at all, signed in or not. A contract has exactly one. */
36 | { readonly by: "everyone" }
37 /** By an identity the forge signed as carrying `role`. */
38 | { readonly by: "identity"; readonly role: string }
39 /** By the row: its `column` holds the actor's id. */
40 | { readonly by: "row"; readonly column: string };
41
42 export interface Role {
43 /** The roles directly below this one. */
44 readonly above: readonly string[];
45 readonly held: Held;
46 }
47
48 export interface Resource {
49 /** The least role each verb needs, or `nobody`. */
50 readonly can: Readonly<Record<Verb, string>>;
51 /**
52 * The collection path of this resource's JSON API, when it has one: five
53 * doors follow by convention (`GET api` lists, `POST api` creates,
54 * `GET`/`PATCH`/`DELETE api/<id>` read, update and delete one), which is
55 * how the forge can knock on a running app and compare with the table.
56 */
57 readonly api?: string;
58 }
59
60 export interface Contract {
61 readonly roles: Readonly<Record<string, Role>>;
62 readonly resources: Readonly<Record<string, Resource>>;
63 }
64
65 /**
66 * Who is asking: an id when signed in, and the roles the forge signed. An
67 * empty id is nobody: it never names a row, however a row was filled.
68 */
69 export interface Actor {
70 readonly id: string | null;
71 readonly roles: readonly string[];
72 }
73
74 /**
75 * The answer. `where` is for a verb with no row in hand (`list`): the actor
76 * may have exactly the rows whose named columns hold their id.
77 */
78 export type Decision = "yes" | "no" | { readonly where: readonly string[] };
79
80 /**
81 * A declared thing by name, and nothing else: `constructor` and its kin are
82 * on every object and are not roles.
83 */
84 function own<T>(of: Readonly<Record<string, T>>, name: string): T | undefined {
85 return Object.prototype.hasOwnProperty.call(of, name) ? of[name] : undefined;
86 }
87
88 /**
89 * Every role with everything at or below it, computed once per contract
90 * and kept beside it. A door is asked on every request, and an order of a
91 * few hundred roles must answer in the time a hash lookup takes, not the
92 * time a walk takes; the walk happens once, when a contract is first used.
93 * The cache is keyed by the contract object itself, so it needs no
94 * invalidation: a new contract is a new object.
95 */
96 const closures = new WeakMap<Contract, Map<string, Set<string>>>();
97
98 function closureOf(contract: Contract): Map<string, Set<string>> {
99 const kept = closures.get(contract);
100 if (kept !== undefined) return kept;
101 const out = new Map<string, Set<string>>();
102 for (const name of Object.keys(contract.roles)) {
103 const seen = new Set<string>([name]);
104 const walk = [name];
105 while (walk.length > 0) {
106 const at = walk.pop()!;
107 for (const below of own(contract.roles, at)?.above ?? [])
108 if (!seen.has(below)) {
109 seen.add(below);
110 walk.push(below);
111 }
112 }
113 out.set(name, seen);
114 }
115 closures.set(contract, out);
116 return out;
117 }
118
119 /** Whether role `low` is `high` or below it; an undeclared role is neither. */
120 export function atOrBelow(
121 contract: Contract,
122 low: string,
123 high: string,
124 ): boolean {
125 return closureOf(contract).get(high)?.has(low) ?? false;
126 }
127
128 export function decide(
129 contract: Contract,
130 resource: string,
131 verb: Verb,
132 actor: Actor,
133 row?: Readonly<Record<string, unknown>>,
134 ): Decision {
135 const can = own(contract.resources, resource)?.can;
136 const need = can === undefined ? undefined : own(can, verb);
137 if (need === undefined || own(contract.roles, need) === undefined)
138 return "no";
139 const where: string[] = [];
140 for (const name of Object.keys(contract.roles)) {
141 if (!atOrBelow(contract, need, name)) continue;
142 const held = contract.roles[name]!.held;
143 if (held.by === "everyone") return "yes";
144 if (held.by === "identity") {
145 if (actor.roles.includes(held.role)) return "yes";
146 continue;
147 }
148 if (actor.id === null || actor.id === "") continue;
149 if (row !== undefined) {
150 if (own(row, held.column) === actor.id) return "yes";
151 } else if (verb === "list" && !where.includes(held.column))
152 where.push(held.column);
153 }
154 return where.length > 0 ? { where } : "no";
155 }
156
157 /** `decide`, for the doors that only need yes or no about one row. */
158 export const may = (
159 contract: Contract,
160 resource: string,
161 verb: Verb,
162 actor: Actor,
163 row?: Readonly<Record<string, unknown>>,
164 ): boolean => decide(contract, resource, verb, actor, row) === "yes";
165
166 // ---- reading a contract: strict, total, every problem named ----
167
168 export type Read =
169 | { readonly ok: true; readonly contract: Contract }
170 | { readonly ok: false; readonly problems: readonly string[] };
171
172 const isObject = (v: unknown): v is Record<string, unknown> =>
173 typeof v === "object" && v !== null && !Array.isArray(v);
174 const NAME = /^[a-z][a-z0-9_]{0,39}$/;
175 /** An absolute path of plain segments: no query, no dot-segments, no host. */
176 const API_PATH = /^\/(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+$/;
177
178 function readHeld(v: unknown): Held | undefined {
179 if (!isObject(v)) return undefined;
180 if (v["by"] === "everyone") return { by: "everyone" };
181 if (v["by"] === "identity" && typeof v["role"] === "string")
182 return NAME.test(v["role"])
183 ? { by: "identity", role: v["role"] }
184 : undefined;
185 if (v["by"] === "row" && typeof v["column"] === "string")
186 return NAME.test(v["column"])
187 ? { by: "row", column: v["column"] }
188 : undefined;
189 return undefined;
190 }
191
192 /** Parse and check a contract from untrusted JSON text. */
193 export function readContract(text: string): Read {
194 let raw: unknown;
195 try {
196 raw = JSON.parse(text);
197 } catch {
198 return { ok: false, problems: ["contract.json is not JSON"] };
199 }
200 if (!isObject(raw) || !isObject(raw["roles"]) || !isObject(raw["resources"]))
201 return {
202 ok: false,
203 problems: ["a contract is an object with `roles` and `resources`"],
204 };
205 const problems: string[] = [];
206 const roles: Record<string, Role> = {};
207 for (const [name, v] of Object.entries(raw["roles"])) {
208 const held = isObject(v) ? readHeld(v["held"]) : undefined;
209 const above = isObject(v) ? (v["above"] ?? []) : undefined;
210 if (!NAME.test(name) || name === NOBODY)
211 problems.push(`role \`${name}\`: not a usable name`);
212 else if (
213 held === undefined ||
214 !Array.isArray(above) ||
215 !above.every((a): a is string => typeof a === "string")
216 )
217 problems.push(`role \`${name}\`: needs \`held\` and a list \`above\``);
218 else roles[name] = { above, held };
219 }
220 const resources: Record<string, Resource> = {};
221 for (const [name, v] of Object.entries(raw["resources"])) {
222 const can = isObject(v) && isObject(v["can"]) ? v["can"] : undefined;
223 if (!NAME.test(name) || !isObject(v) || can === undefined) {
224 problems.push(`resource \`${name}\`: needs a name and a \`can\` table`);
225 continue;
226 }
227 const cells = {} as Record<Verb, string>;
228 for (const verb of VERBS) {
229 const cell = can[verb];
230 if (typeof cell === "string") cells[verb] = cell;
231 else
232 problems.push(`${name}.${verb}: every verb names a role or \`nobody\``);
233 }
234 for (const extra of Object.keys(can))
235 if (!VERBS.includes(extra as Verb))
236 problems.push(`${name}.${extra}: not one of ${VERBS.join(", ")}`);
237 const api = v["api"];
238 if (api !== undefined && (typeof api !== "string" || !API_PATH.test(api)))
239 problems.push(
240 `resource \`${name}\`: \`api\` is an absolute path of plain segments, like /api/${name}s`,
241 );
242 resources[name] =
243 typeof api === "string" && API_PATH.test(api)
244 ? { can: cells, api }
245 : { can: cells };
246 }
247 const contract: Contract = { roles, resources };
248 problems.push(...check(contract));
249 // A cell read here and checked there is one problem, said once.
250 const unique = [...new Set(problems)];
251 return unique.length > 0
252 ? { ok: false, problems: unique }
253 : { ok: true, contract };
254 }
255
256 /** What is wrong with a contract that parsed. Empty means sound. */
257 export function check(contract: Contract): string[] {
258 const problems: string[] = [];
259 const names = Object.keys(contract.roles);
260 const floors = names.filter((n) => contract.roles[n]!.held.by === "everyone");
261 if (floors.length !== 1)
262 problems.push("exactly one role is held by everyone: the floor");
263 // Two roles held by one identity are one role with two names: the table
264 // would show two columns that are the same person.
265 const byIdentity = new Map<string, string>();
266 for (const name of names) {
267 const held = contract.roles[name]!.held;
268 if (held.by !== "identity") continue;
269 const other = byIdentity.get(held.role);
270 if (other !== undefined)
271 problems.push(
272 `roles \`${other}\` and \`${name}\` are both held by the identity \`${held.role}\``,
273 );
274 else byIdentity.set(held.role, name);
275 }
276 for (const name of names) {
277 for (const below of contract.roles[name]!.above) {
278 if (own(contract.roles, below) === undefined)
279 problems.push(
280 `role \`${name}\` is above \`${below}\`, which is not declared`,
281 );
282 else if (atOrBelow(contract, name, below))
283 problems.push(`role \`${name}\` is both above and below \`${below}\``);
284 }
285 const floor = floors[0];
286 if (floor !== undefined && !atOrBelow(contract, floor, name))
287 problems.push(
288 `role \`${name}\` does not stand on the floor \`${floor}\``,
289 );
290 }
291 for (const [resource, { can }] of Object.entries(contract.resources))
292 for (const verb of VERBS) {
293 const need = own(can, verb);
294 if (need === undefined) {
295 problems.push(
296 `${resource}.${verb}: every verb names a role or \`nobody\``,
297 );
298 continue;
299 }
300 if (need === NOBODY) continue;
301 const role = own(contract.roles, need);
302 if (role === undefined)
303 problems.push(
304 `${resource}.${verb} needs \`${need}\`, which is not declared`,
305 );
306 else if (verb === "create" && role.held.by === "row")
307 problems.push(
308 `${resource}.create needs \`${need}\`, which a row holds: there is no row yet`,
309 );
310 }
311 return problems;
312 }
313
314 // ---- the table: the contract as the audit reads it ----
315
316 export interface Cell {
317 readonly resource: string;
318 readonly verb: Verb;
319 /** Who is asking: the floor, or a role an identity carries. */
320 readonly as: string;
321 /** `own`: only the rows that name the actor. */
322 readonly answer: "yes" | "no" | "own";
323 }
324
325 /**
326 * Who someone can be. A role a row holds is not one of them: it is what an
327 * actor is *to a row*, and shows in the table as `own`.
328 */
329 export const identities = (contract: Contract): string[] =>
330 Object.keys(contract.roles).filter(
331 (name) => contract.roles[name]!.held.by !== "row",
332 );
333
334 /**
335 * The facts that make someone `identity` and nothing more: the forge acts as
336 * each identity this way, for the table here and for the audit's probes.
337 * `mine` is a row that names the actor wherever a row can; `theirs` names
338 * someone else. Anything that is not an identity acts as a stranger.
339 */
340 export function actingAs(
341 contract: Contract,
342 identity: string,
343 ): {
344 actor: Actor;
345 mine: Record<string, unknown>;
346 theirs: Record<string, unknown>;
347 } {
348 const held = own(contract.roles, identity)?.held;
349 const actor: Actor =
350 held?.by === "identity"
351 ? { id: "the-actor", roles: [held.role] }
352 : { id: null, roles: [] };
353 const mine: Record<string, unknown> = {};
354 const theirs: Record<string, unknown> = {};
355 for (const role of Object.values(contract.roles))
356 if (role.held.by === "row") {
357 mine[role.held.column] = "the-actor";
358 theirs[role.held.column] = "someone-else";
359 }
360 return { actor, mine, theirs };
361 }
362
363 /** Every resource, verb and identity, answered. The policy, as a table. */
364 export function table(contract: Contract): Cell[] {
365 const out: Cell[] = [];
366 for (const resource of Object.keys(contract.resources))
367 for (const verb of VERBS)
368 for (const as of identities(contract)) {
369 const { actor, mine, theirs } = actingAs(contract, as);
370 const rowless = verb === "create" || verb === "list";
371 const any = decide(
372 contract,
373 resource,
374 verb,
375 actor,
376 rowless ? undefined : theirs,
377 );
378 const owned = rowless
379 ? any
380 : decide(contract, resource, verb, actor, mine);
381 out.push({
382 resource,
383 verb,
384 as,
385 answer: any === "yes" ? "yes" : owned === "no" ? "no" : "own",
386 });
387 }
388 return out;
389 }
template/src/compress.ts added +37
@@ -0,0 +1,37 @@
1 /**
2 * Compression, in the app, so a deploy that no proxy sits in front of is
3 * still small on the wire. A response is gzipped when the person's browser
4 * said it reads gzip, the body is text (HTML, CSS, JS, JSON, XML, SVG)
5 * and is worth the trouble (1 KiB or more). The event stream is never
6 * touched — it must reach the browser as it is written — and neither is
7 * anything already encoded. A proxy that compresses for itself sees
8 * `content-encoding` and leaves the body alone.
9 */
10
11 /** The least body worth compressing; below it the headers outweigh the gain. */
12 export const MIN_BYTES = 1024;
13
14 const TEXTUAL = /^(text\/(?!event-stream)|application\/([\w.+-]*json|xml|javascript)|image\/svg\+xml)/i;
15
16 export async function compress(
17 request: Request,
18 response: Response,
19 ): Promise<Response> {
20 const type = response.headers.get("content-type") ?? "";
21 if (
22 request.method !== "GET" ||
23 response.body === null ||
24 response.headers.has("content-encoding") ||
25 !/\bgzip\b/i.test(request.headers.get("accept-encoding") ?? "") ||
26 !TEXTUAL.test(type)
27 )
28 return response;
29 const headers = new Headers(response.headers);
30 headers.append("vary", "accept-encoding");
31 const bytes = new Uint8Array(await response.arrayBuffer());
32 if (bytes.length < MIN_BYTES || response.status === 206)
33 return new Response(bytes, { status: response.status, headers });
34 headers.set("content-encoding", "gzip");
35 headers.delete("content-length");
36 return new Response(Bun.gzipSync(bytes), { status: response.status, headers });
37 }
template/src/contract.test.ts added +122
@@ -0,0 +1,122 @@
1 /**
2 * 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
4 * someone else — and calls the real actions. A rule written by hand in an
5 * action, or a cell changed without its door, fails here.
6 */
7 import { afterAll, expect, test } from "bun:test";
8 import { mkdtempSync, rmSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 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";
20 import { record } from "./audit.ts";
21 import { actingAs, identities, table, type Verb } from "./can.ts";
22 import { contract } from "./contract.ts";
23 import { openDb } from "./db.ts";
24 import type { Who } from "./who.ts";
25
26 const dir = mkdtempSync(join(tmpdir(), "app-contract-"));
27 const db = openDb(dir);
28 afterAll(() => {
29 db.close();
30 rmSync(dir, { recursive: true, force: true });
31 });
32
33 /** The identity the evaluator acts as, as the forge would have signed it. */
34 function whoIs(identity: string): Who {
35 const { actor } = actingAs(contract, identity);
36 const role = actor.roles[0];
37 if (actor.id === null || (role !== "user" && role !== "admin"))
38 return { role: "anon" };
39 return { role, id: actor.id, name: identity };
40 }
41
42 const noteBy = (authorId: string): number =>
43 db
44 .query<
45 { id: number },
46 [string]
47 >("INSERT INTO note (body, author_id, author_name) VALUES ('n', ?1, ?1) RETURNING id")
48 .get(authorId)!.id;
49
50 const auditRow = (): number => {
51 record(db, {
52 who: { role: "anon" },
53 resource: "note",
54 verb: "create",
55 outcome: "signin_required",
56 });
57 return db.query<{ id: number }, []>("SELECT max(id) AS id FROM audit").get()!
58 .id;
59 };
60
61 /** One door per verb an action serves: did it let `who` through, on `row`? */
62 const doors: Record<
63 string,
64 Partial<Record<Verb, (who: Who, authorId: string) => boolean>>
65 > = {
66 note: {
67 create: (who) => addNote(db, who, { body: "hello" }).ok,
68 list: (who) => listNotes(db, who).ok,
69 read: (who, authorId) => getNote(db, who, { id: noteBy(authorId) }).ok,
70 update: (who, authorId) =>
71 updateNote(db, who, { id: noteBy(authorId), body: "changed" }).ok,
72 delete: (who, authorId) => deleteNote(db, who, { id: noteBy(authorId) }).ok,
73 },
74 // The trail is written by the app itself, never through a door: there
75 // is no action that creates, changes or removes a row of it.
76 audit: {
77 list: (who) => listAudit(db, who).ok,
78 read: (who) => getAudit(db, who, { id: auditRow() }).ok,
79 create: () => false,
80 update: () => false,
81 delete: () => false,
82 },
83 };
84
85 test("the contract names the identities the forge signs", () => {
86 expect(identities(contract).sort()).toEqual(["admin", "anon", "user"]);
87 });
88
89 test("every resource in the contract has every door here", () => {
90 expect(Object.keys(doors).sort()).toEqual(
91 Object.keys(contract.resources).sort(),
92 );
93 for (const resource of Object.keys(contract.resources))
94 expect(Object.keys(doors[resource] ?? {}).sort()).toEqual([
95 "create",
96 "delete",
97 "list",
98 "read",
99 "update",
100 ]);
101 });
102
103 test("every door answers as the table says, as every identity", () => {
104 let asked = 0;
105 for (const cell of table(contract)) {
106 const door = doors[cell.resource]?.[cell.verb];
107 if (door === undefined) continue;
108 const who = whoIs(cell.as);
109 const { mine, theirs } = actingAs(contract, cell.as);
110 const onMine = door(who, String(mine["author_id"]));
111 const onTheirs = door(who, String(theirs["author_id"]));
112 const said = `${cell.resource}.${cell.verb} as ${cell.as}`;
113 asked++;
114 if (cell.answer === "yes")
115 expect([said, onMine, onTheirs]).toEqual([said, true, true]);
116 else if (cell.answer === "no")
117 expect([said, onMine, onTheirs]).toEqual([said, false, false]);
118 else if (cell.verb === "list") expect([said, onMine]).toEqual([said, true]);
119 else expect([said, onMine, onTheirs]).toEqual([said, true, false]);
120 }
121 expect(asked).toBeGreaterThan(0);
122 });
template/src/contract.ts added +40
@@ -0,0 +1,40 @@
1 /**
2 * Who may do what. `contract.json` is the table — the roles, and the least
3 * role each verb on each resource needs — and `src/can.ts` is the forge's
4 * evaluator, carried here verbatim. Actions ask `permit` and nothing else
5 * in the app decides who may do what, so the table *is* the policy: it can
6 * be read, compared and audited without running anything.
7 *
8 * A contract that does not read is not a warning. The app does not start.
9 */
10
11 import { readFileSync } from "node:fs";
12 import {
13 decide,
14 readContract,
15 type Actor,
16 type Decision,
17 type Verb,
18 } from "./can.ts";
19 import type { Who } from "./who.ts";
20
21 const read = readContract(
22 readFileSync(new URL("../contract.json", import.meta.url), "utf8"),
23 );
24 if (!read.ok) throw new Error(`contract.json: ${read.problems.join("; ")}`);
25
26 export const contract = read.contract;
27
28 /** The forge's word for who is asking, as the evaluator takes it. */
29 export const actorOf = (who: Who): Actor =>
30 who.role === "anon"
31 ? { id: null, roles: [] }
32 : { id: who.id, roles: [who.role] };
33
34 /** May `who` do `verb` to `resource` — to `row`, when there is one? */
35 export const permit = (
36 who: Who,
37 resource: string,
38 verb: Verb,
39 row?: Readonly<Record<string, unknown>>,
40 ): Decision => decide(contract, resource, verb, actorOf(who), row);
template/src/db.test.ts added +28
@@ -0,0 +1,28 @@
1 import { expect, test } from "bun:test";
2 import { mkdtempSync, rmSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { check, migrate, migrations, openDb } from "./db.ts";
6
7 test("migrations apply once, in order, and the file checks out", () => {
8 const dir = mkdtempSync(join(tmpdir(), "app-db-"));
9 const db = openDb(dir);
10 try {
11 expect(check(db).version).toBe(migrations.length);
12 // Opening again finds nothing to do — a migration that has run is history.
13 expect(migrate(db)).toBe(migrations.length);
14 expect(() => openDb(dir)).not.toThrow();
15 expect(check(db)).toEqual({ version: migrations.length, integrity: "ok" });
16 expect(
17 db.query<{ journal_mode: string }, []>("PRAGMA journal_mode").get()
18 ?.journal_mode,
19 ).toBe("wal");
20 expect(
21 db.query<{ foreign_keys: number }, []>("PRAGMA foreign_keys").get()
22 ?.foreign_keys,
23 ).toBe(1);
24 } finally {
25 db.close();
26 rmSync(dir, { recursive: true, force: true });
27 }
28 });
template/src/db.ts added +110
@@ -0,0 +1,110 @@
1 /**
2 * The database: one SQLite file under FORGE_APP_DATA, so production and
3 * every preview each have their own. WAL so readers never wait on the
4 * writer (the terminal is a second process on the same file), foreign keys
5 * on, and a forward-only list of migrations applied once, in a
6 * transaction, when the file is opened.
7 *
8 * bun run src/db.ts --check the schema version and an integrity check
9 */
10
11 import { Database } from "bun:sqlite";
12 import { mkdirSync } from "node:fs";
13 import { join } from "node:path";
14 import { dataDir } from "./env.ts";
15
16 /** Append, never edit: a migration that has run is history. */
17 export const migrations: string[] = [
18 `CREATE TABLE note (
19 id INTEGER PRIMARY KEY,
20 body TEXT NOT NULL CHECK (length(body) BETWEEN 1 AND 500),
21 author_id TEXT NOT NULL,
22 author_name TEXT NOT NULL,
23 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
24 updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
25 )`,
26 `CREATE INDEX note_author ON note (author_id)`,
27 // Who tried to change what, and whether they were let. Appended by
28 // src/audit.ts, never edited; read by admins at GET /api/audit.
29 `CREATE TABLE audit (
30 id INTEGER PRIMARY KEY,
31 at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
32 who_id TEXT,
33 who_name TEXT,
34 role TEXT NOT NULL,
35 resource TEXT NOT NULL,
36 verb TEXT NOT NULL,
37 target TEXT,
38 allowed INTEGER NOT NULL CHECK (allowed IN (0, 1)),
39 outcome TEXT NOT NULL
40 )`,
41 // Sign-in through the forge (src/signin.ts): a login in flight, and a
42 // session once it lands. Only hashes of the ids are kept.
43 `CREATE TABLE login (
44 state TEXT PRIMARY KEY,
45 verifier TEXT NOT NULL,
46 nonce TEXT NOT NULL,
47 expires_at INTEGER NOT NULL
48 )`,
49 `CREATE TABLE session (
50 hash TEXT PRIMARY KEY,
51 user_id TEXT NOT NULL,
52 user_name TEXT NOT NULL,
53 expires_at INTEGER NOT NULL
54 )`,
55 ];
56
57 export function openDb(dir = dataDir): Database {
58 mkdirSync(dir, { recursive: true });
59 const db = new Database(join(dir, "app.db"));
60 db.exec("PRAGMA journal_mode = WAL");
61 db.exec("PRAGMA foreign_keys = ON");
62 db.exec("PRAGMA busy_timeout = 5000");
63 migrate(db);
64 return db;
65 }
66
67 /** Apply the migrations past the recorded version, all or none. Returns the version. */
68 export function migrate(db: Database): number {
69 db.exec(
70 "CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')))",
71 );
72 return db.transaction(() => {
73 const current = db
74 .query<
75 { version: number },
76 []
77 >("SELECT coalesce(max(version), 0) AS version FROM schema_version")
78 .get()!.version;
79 migrations.slice(current).forEach((sql, i) => {
80 db.exec(sql);
81 db.query("INSERT INTO schema_version (version) VALUES (?1)").run(
82 current + i + 1,
83 );
84 });
85 return migrations.length;
86 })();
87 }
88
89 export function check(db: Database): { version: number; integrity: string } {
90 const version = db
91 .query<
92 { version: number },
93 []
94 >("SELECT max(version) AS version FROM schema_version")
95 .get()!.version;
96 const integrity = db
97 .query<{ integrity_check: string }, []>("PRAGMA integrity_check")
98 .get()!.integrity_check;
99 return { version, integrity };
100 }
101
102 if (import.meta.main) {
103 const db = openDb();
104 const { version, integrity } = check(db);
105 console.log(`schema version ${version}`);
106 if (process.argv.includes("--check")) {
107 console.log(`integrity ${integrity}`);
108 process.exit(integrity === "ok" ? 0 : 1);
109 }
110 }
template/src/design.test.ts added +115
@@ -0,0 +1,115 @@
1 /**
2 * The look holds: the tokens compile to both themes, every pair of colours
3 * a person must read meets WCAG AA in both, and no colour is spelled out
4 * anywhere but design/tokens.json.
5 */
6 import { expect, test } from "bun:test";
7 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { lint, rawColours, unknownTokens } from "../scripts/lint-design.ts";
11 import { compile, flatten, token, tokens, tokensCss } from "./tokens.ts";
12
13 test("the tokens compile: light on :root, dark for the system and for data-theme", () => {
14 expect(tokensCss).toContain(`--color-bg: ${token("color-bg")};`);
15 expect(tokensCss).toContain("--space-4: 1rem;");
16 expect(tokensCss).toContain(
17 '--font-sans: system-ui, -apple-system, "Segoe UI", sans-serif;',
18 );
19 expect(tokensCss).toContain("@media (prefers-color-scheme: dark)");
20 expect(tokensCss).toContain(':root:not([data-theme="light"])');
21 expect(tokensCss).toContain(':root[data-theme="dark"]');
22 // Every colour has a dark value, or the dark theme would inherit a light one.
23 for (const t of tokens.filter((t) => t.type === "color"))
24 expect([t.name, t.dark !== undefined]).toEqual([t.name, true]);
25 expect(
26 tokensCss.split(`--color-bg: ${token("color-bg", "dark")};`).length,
27 ).toBe(3);
28 });
29
30 test("tokens that do not read stop the app, with the path named", () => {
31 expect(() => flatten({ color: { bg: { $value: "#fff" } } })).toThrow(
32 "color.bg: no $type",
33 );
34 expect(() =>
35 flatten({
36 color: { $type: "color", bg: { $value: "red; } body { display: none" } },
37 }),
38 ).toThrow("color.bg: $value is not a CSS value");
39 expect(() =>
40 flatten({ color: { $type: "color", "b g": { $value: "#fff" } } }),
41 ).toThrow("not a name CSS can carry");
42 expect(
43 compile(flatten({ size: { $type: "dimension", tap: { $value: "44px" } } })),
44 ).toContain("--size-tap: 44px;");
45 });
46
47 // WCAG 2 relative luminance and contrast, from a #rrggbb.
48 const luminance = (hex: string): number => {
49 const [r, g, b] = [1, 3, 5].map((i) => {
50 const c = parseInt(hex.slice(i, i + 2), 16) / 255;
51 return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
52 }) as [number, number, number];
53 return 0.2126 * r + 0.7152 * g + 0.0722 * b;
54 };
55 const contrast = (a: string, b: string): number => {
56 const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p) as [
57 number,
58 number,
59 ];
60 return (x + 0.05) / (y + 0.05);
61 };
62
63 test("every pair a person reads is at least 4.5:1, in both themes", () => {
64 const pairs = [
65 ["color-fg", "color-bg"],
66 ["color-fg", "color-surface"],
67 ["color-muted", "color-bg"],
68 ["color-muted", "color-surface"],
69 ["color-accent", "color-bg"],
70 ["color-accent", "color-surface"],
71 ["color-accent-fg", "color-accent"],
72 ["color-toast-fg", "color-toast-bg"],
73 ] as const;
74 for (const mode of ["light", "dark"] as const)
75 for (const [fg, bg] of pairs) {
76 const ratio = contrast(token(fg, mode), token(bg, mode));
77 expect([mode, fg, bg, ratio >= 4.5]).toEqual([mode, fg, bg, true]);
78 }
79 });
80
81 test("the app spells out no colour but in its tokens", () => {
82 expect(lint(join(import.meta.dir, ".."))).toEqual([]);
83 });
84
85 test("the lint refuses a raw colour and a token that is not there", () => {
86 expect(
87 rawColours(
88 "a.css",
89 ".x { color: #ff0000; }\n.y { background: rgb(0 0 0); }",
90 ),
91 ).toEqual([
92 "a.css:1: raw colour #ff0000 — name it in design/tokens.json and use var(--…)",
93 "a.css:2: raw colour rgb( — name it in design/tokens.json and use var(--…)",
94 ]);
95 // Not colours: an entity, an id selector's word, a pull number.
96 expect(rawColours("a.ts", "`&#39;` #notes pull #12 #abcdefg")).toEqual([]);
97 expect(
98 unknownTokens(
99 "a.css",
100 ".x { color: var(--color-fg); gap: var(--spcae-2); }",
101 ),
102 ).toEqual(["a.css:1: --spcae-2 is not a token in design/tokens.json"]);
103 const root = mkdtempSync(join(tmpdir(), "app-lint-"));
104 try {
105 mkdirSync(join(root, "static"));
106 mkdirSync(join(root, "src"));
107 writeFileSync(join(root, "static", "extra.css"), "a {\n color: #fff;\n}\n");
108 writeFileSync(join(root, "src", "ok.test.ts"), "const red = '#f00';\n");
109 expect(lint(root)).toEqual([
110 "static/extra.css:2: raw colour #fff — name it in design/tokens.json and use var(--…)",
111 ]);
112 } finally {
113 rmSync(root, { recursive: true, force: true });
114 }
115 });
template/src/env.ts added +32
@@ -0,0 +1,32 @@
1 /**
2 * What the forge told this process, read once and named once. Every other
3 * module takes these from here, so nothing else spells an environment
4 * variable — and running the app by hand needs none of them.
5 */
6
7 import pkg from "../package.json";
8
9 export const title: string = pkg.name;
10 /** The app's own version (package.json): what `/healthz` and `/openapi.json` say. */
11 export const version: string = pkg.version ?? "0.0.0";
12 /** When this process started, for `/healthz`'s uptime. */
13 export const startedAt: number = Date.now();
14 export const description: string = pkg.description || "A new app on the forge.";
15 export const dataDir: string = process.env.FORGE_APP_DATA ?? "./data";
16 export const env: string = process.env.FORGE_APP_ENV ?? "local";
17 export const commit: string = (process.env.FORGE_APP_COMMIT ?? "").slice(0, 7);
18 /** Where this process runs, for a person: `production`, `preview of pull #3`, `local`. */
19 export const where: string =
20 env === "preview"
21 ? `preview of pull #${process.env.FORGE_APP_PULL ?? "?"}`
22 : env;
23 /** The exact command that opens this environment's terminal. Print it verbatim, never a guess. */
24 export const ssh: string | undefined = process.env.FORGE_APP_SSH;
25 /** The address the forge serves us at — what a browser sees, never the socket's. */
26 export const publicOrigin: string = new URL(
27 process.env.FORGE_APP_URL ?? "http://localhost",
28 ).origin;
29 /** The forge that runs us. Its own well-known files (security.txt) speak for its apps. */
30 export const forgeUrl: string | undefined = process.env.FORGE_URL;
31 /** The key the forge signs identities with (`who.ts`). Unset, everyone is anonymous. */
32 export const identityKey: string = process.env.FORGE_APP_IDENTITY_KEY ?? "";
template/src/http.ts added +233
@@ -0,0 +1,233 @@
1 /**
2 * 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
4 * come in at all is `security.ts`.
5 */
6
7 import { createHash } from "node:crypto";
8 import { existsSync, readFileSync } from "node:fs";
9 import { join } from "node:path";
10 import { env, publicOrigin } from "./env.ts";
11
12 // Scripts and styles come from this origin (inline styles allowed, inline
13 // scripts not), nothing frames us, browsers never guess a content type, and
14 // referrers stay on this site. Once served over https, always: browsers
15 // remember for a year, subdomains too (never preloaded: that is a promise
16 // the owner makes, not a template). Anything but production asks not to be
17 // indexed: a preview is a draft, and its address goes away with its pull.
18 export const SECURITY: Record<string, string> = {
19 "content-security-policy":
20 "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
21 "x-content-type-options": "nosniff",
22 "referrer-policy": "strict-origin-when-cross-origin",
23 "cross-origin-opener-policy": "same-origin",
24 "permissions-policy": "camera=(), microphone=(), geolocation=()",
25 ...(publicOrigin.startsWith("https:")
26 ? { "strict-transport-security": "max-age=31536000; includeSubDomains" }
27 : {}),
28 ...(env === "production" ? {} : { "x-robots-tag": "noindex" }),
29 };
30
31 export const escape = (s: string): string =>
32 s.replace(
33 /[&<>"']/g,
34 (c) =>
35 ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
36 c
37 ] ?? c,
38 );
39
40 export const html = (
41 body: string,
42 status = 200,
43 headers: Record<string, string> = {},
44 ): Response =>
45 new Response(body, {
46 status,
47 headers: {
48 "content-type": "text/html; charset=utf-8",
49 ...SECURITY,
50 ...headers,
51 },
52 });
53
54 export const json = (data: unknown, status = 200): Response =>
55 new Response(JSON.stringify(data), {
56 status,
57 headers: { "content-type": "application/json; charset=utf-8", ...SECURITY },
58 });
59
60 export const text = (body: string, status = 200): Response =>
61 new Response(body, {
62 status,
63 headers: { "content-type": "text/plain; charset=utf-8", ...SECURITY },
64 });
65
66 /**
67 * A page that has not changed costs a header, not a body: the HTML is given
68 * an ETag from its own bytes, and a request that already holds it is
69 * answered 304 (specification.website/#caching). Only a plain 200 page is
70 * tagged; one that sets a cookie is never answered from a stranger's copy.
71 */
72 export async function revalidate(
73 request: Request,
74 response: Response,
75 ): Promise<Response> {
76 if (
77 (request.method !== "GET" && request.method !== "HEAD") ||
78 response.status !== 200 ||
79 response.body === null ||
80 response.headers.has("etag") ||
81 response.headers.has("set-cookie") ||
82 !(response.headers.get("content-type") ?? "").startsWith("text/html")
83 )
84 return response;
85 const bytes = new Uint8Array(await response.arrayBuffer());
86 const headers = new Headers(response.headers);
87 const etag = `W/"${Bun.hash(bytes).toString(36)}"`;
88 headers.set("etag", etag);
89 const held = request.headers.get("if-none-match") ?? "";
90 if (held === "*" || held.split(",").some((t) => t.trim() === etag)) {
91 headers.delete("content-length");
92 return new Response(null, { status: 304, headers });
93 }
94 return new Response(bytes, { status: 200, headers });
95 }
96
97 /** Back to the page, with a word for it to show once (`readNotice`). */
98 export const back = (notice?: string): Response =>
99 new Response(null, {
100 status: 303,
101 headers: {
102 location: "/",
103 ...SECURITY,
104 ...(notice === undefined
105 ? {}
106 : { "set-cookie": cookie("notice", encodeURIComponent(notice), 30) }),
107 },
108 });
109
110 /** Go to `location` (one the app built, never the client's), setting these cookies on the way. */
111 export function redirectTo(location: string, ...cookies: string[]): Response {
112 const headers = new Headers({ location, ...SECURITY });
113 for (const value of cookies) headers.append("set-cookie", value);
114 return new Response(null, { status: 303, headers });
115 }
116
117 /** The notice a redirect left, and the header that clears it. */
118 export function readNotice(request: Request): {
119 notice?: string;
120 clear: Record<string, string>;
121 } {
122 const raw = /(?:^|;\s*)notice=([^;]*)/.exec(
123 request.headers.get("cookie") ?? "",
124 )?.[1];
125 if (raw === undefined) return { clear: {} };
126 return {
127 notice: decodeURIComponent(raw),
128 clear: { "set-cookie": cookie("notice", "", 0) },
129 };
130 }
131
132 // Every cookie the app sets itself is HttpOnly and SameSite=Lax, and Secure
133 // wherever the public address is https.
134 export const cookie = (name: string, value: string, maxAge: number): string =>
135 `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${publicOrigin.startsWith("https:") ? "; Secure" : ""}`;
136
137 // A request body is read up to a cap and no further, counting the bytes as
138 // they arrive. A declared Content-Length is a claim: a chunked request has
139 // none, and a lie is free. Undefined means "too large" — refuse it. Past the
140 // cap the rest is drained and dropped so the connection stays usable for
141 // the next request; past eight times the cap it is cut off instead.
142 export const BODY_MAX = 64 * 1024;
143 export async function readBody(
144 request: Request,
145 max = BODY_MAX,
146 ): Promise<Uint8Array | undefined> {
147 const reader = request.body?.getReader();
148 if (reader === undefined) return new Uint8Array();
149 const parts: Uint8Array[] = [];
150 let size = 0;
151 for (;;) {
152 const { done, value } = await reader.read();
153 if (done) break;
154 size += value.byteLength;
155 if (size > max) {
156 for (;;) {
157 const next = await reader.read();
158 if (next.done) return undefined;
159 size += next.value.byteLength;
160 if (size > max * 8) {
161 await reader.cancel();
162 return undefined;
163 }
164 }
165 }
166 parts.push(value);
167 }
168 const body = new Uint8Array(size);
169 let at = 0;
170 for (const part of parts) {
171 body.set(part, at);
172 at += part.byteLength;
173 }
174 return body;
175 }
176
177 /** The form fields of a capped body, decoded the way the browser sent them. */
178 export async function readForm(request: Request) {
179 const body = await readBody(request);
180 if (body === undefined) return undefined;
181 return new Request(request.url, {
182 method: "POST",
183 headers: { "content-type": request.headers.get("content-type") ?? "" },
184 body: new Uint8Array(body),
185 }).formData();
186 }
187
188 /** The JSON of a capped body: `undefined` when too large, `null` when not JSON. */
189 export async function readJson(request: Request): Promise<unknown> {
190 const body = await readBody(request);
191 if (body === undefined) return undefined;
192 try {
193 return JSON.parse(new TextDecoder().decode(body));
194 } catch {
195 return null;
196 }
197 }
198
199 /** A JSON object's fields, whatever the wire carried. */
200 export const fields = (value: unknown): Record<string, unknown> =>
201 typeof value === "object" && value !== null && !Array.isArray(value)
202 ? (value as Record<string, unknown>)
203 : {};
204
205 // Files under ./static are served as they are. A page links each one by
206 // its content (`/static/app.css?v=3f2a9c1e`), and that address is cached
207 // for a year: a change is a new address, never a stale cache.
208 const STATIC = join(import.meta.dir, "..", "static");
209 const versions = new Map<string, string>();
210 export function asset(name: string): string {
211 let v = versions.get(name);
212 if (v === undefined) {
213 v = createHash("sha256")
214 .update(readFileSync(join(STATIC, name)))
215 .digest("hex")
216 .slice(0, 8);
217 versions.set(name, v);
218 }
219 return `/static/${name}?v=${v}`;
220 }
221 export function staticFile(name: string, versioned: boolean): Response {
222 const path = join(STATIC, name);
223 if (name.includes("/") || name.includes("..") || !existsSync(path))
224 return text("not found", 404);
225 return new Response(Bun.file(path), {
226 headers: {
227 "cache-control": versioned
228 ? "public, max-age=31536000, immutable"
229 : "no-cache",
230 ...SECURITY,
231 },
232 });
233 }
template/src/live.ts added +81
@@ -0,0 +1,81 @@
1 /**
2 * Realtime without a framework. Actions `emit` what changed; `GET /events`
3 * streams it to every open page as server-sent events, numbered, with the
4 * last hundred kept so a client that reconnects with `Last-Event-ID` (or
5 * `?since=`) hears what it missed. `static/live.js` turns the stream into
6 * DOM events. The bus is this process's: the terminal is another process,
7 * and its writes show on the next load rather than live.
8 */
9
10 export interface LiveEvent {
11 readonly id: number;
12 readonly type: string;
13 readonly data: unknown;
14 }
15
16 const KEEP = 100;
17 const HEARTBEAT_MS = 25_000;
18 const kept: LiveEvent[] = [];
19 const listeners = new Set<(event: LiveEvent) => void>();
20 let last = 0;
21
22 export function emit(type: string, data: unknown): LiveEvent {
23 const event: LiveEvent = { id: ++last, type, data };
24 kept.push(event);
25 if (kept.length > KEEP) kept.shift();
26 for (const listen of listeners) listen(event);
27 return event;
28 }
29
30 export function subscribe(listen: (event: LiveEvent) => void): () => void {
31 listeners.add(listen);
32 return () => listeners.delete(listen);
33 }
34
35 /** `GET /events`: a stream that replays what `since` missed, then follows. */
36 export function events(request: Request): Response {
37 const since = Number(
38 request.headers.get("last-event-id") ??
39 new URL(request.url).searchParams.get("since") ??
40 0,
41 );
42 const encoder = new TextEncoder();
43 let stop = (): void => {};
44 const stream = new ReadableStream<Uint8Array>({
45 start(controller) {
46 const write = (text: string): void => {
47 try {
48 controller.enqueue(encoder.encode(text));
49 } catch {
50 stop();
51 }
52 };
53 const send = (event: LiveEvent): void =>
54 write(
55 `id: ${event.id}\ndata: ${JSON.stringify({ type: event.type, data: event.data })}\n\n`,
56 );
57 const heartbeat = setInterval(() => write(":\n\n"), HEARTBEAT_MS);
58 const unsubscribe = subscribe(send);
59 stop = () => {
60 clearInterval(heartbeat);
61 unsubscribe();
62 try {
63 controller.close();
64 } catch {}
65 };
66 request.signal.addEventListener("abort", stop);
67 write("retry: 2000\n\n");
68 for (const event of kept) if (event.id > since) send(event);
69 },
70 cancel() {
71 stop();
72 },
73 });
74 return new Response(stream, {
75 headers: {
76 "content-type": "text/event-stream",
77 "cache-control": "no-store",
78 "x-accel-buffering": "no",
79 },
80 });
81 }
template/src/mcp.ts added +123
@@ -0,0 +1,123 @@
1 /**
2 * An MCP server over plain HTTP: `POST /mcp` takes one JSON-RPC 2.0
3 * message and answers with JSON (streamable HTTP without the stream —
4 * nothing here needs to push). The tools are the actions, called with the
5 * same identity the page gets, so an agent speaking MCP through the forge
6 * is the person whose grant it carries, and a bare one is anonymous.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { addNote, deleteNote, listNotes, type Result } from "./actions.ts";
11 import { title } from "./env.ts";
12 import { fields } from "./http.ts";
13 import type { Who } from "./who.ts";
14
15 interface Tool {
16 readonly name: string;
17 readonly description: string;
18 readonly inputSchema: Record<string, unknown>;
19 readonly run: (
20 db: Database,
21 who: Who,
22 args: Record<string, unknown>,
23 ) => Result<unknown>;
24 }
25
26 export const tools: readonly Tool[] = [
27 {
28 name: "list_notes",
29 description: "The notes, newest first.",
30 inputSchema: {
31 type: "object",
32 properties: {
33 limit: {
34 type: "integer",
35 minimum: 1,
36 maximum: 500,
37 description: "At most this many (100).",
38 },
39 },
40 },
41 run: (db, who, args) =>
42 listNotes(db, who, { limit: Number(args.limit ?? 100) }),
43 },
44 {
45 name: "add_note",
46 description:
47 "Add a note as the signed-in person. Anonymous callers cannot.",
48 inputSchema: {
49 type: "object",
50 properties: { body: { type: "string", maxLength: 500 } },
51 required: ["body"],
52 },
53 run: (db, who, args) => addNote(db, who, { body: String(args.body ?? "") }),
54 },
55 {
56 name: "delete_note",
57 description: "Remove a note by id. Only its author or an admin can.",
58 inputSchema: {
59 type: "object",
60 properties: { id: { type: "integer" } },
61 required: ["id"],
62 },
63 run: (db, who, args) => deleteNote(db, who, { id: Number(args.id) }),
64 },
65 ];
66
67 /** One JSON-RPC message in, an HTTP status and a body out (a notification gets 202 and no body). */
68 export function rpc(
69 db: Database,
70 who: Who,
71 message: unknown,
72 ): { status: number; body?: unknown } {
73 const m = fields(message);
74 const id = m.id ?? null;
75 const reply = (result: unknown) => ({
76 status: 200,
77 body: { jsonrpc: "2.0", id, result },
78 });
79 const refuse = (code: number, text: string) => ({
80 status: 200,
81 body: { jsonrpc: "2.0", id, error: { code, message: text } },
82 });
83 if (m.jsonrpc !== "2.0" || typeof m.method !== "string")
84 return refuse(-32600, "not a JSON-RPC 2.0 request");
85 if (m.id === undefined) return { status: 202 };
86 const params = fields(m.params);
87 switch (m.method) {
88 case "initialize":
89 return reply({
90 protocolVersion: "2025-06-18",
91 capabilities: { tools: {} },
92 serverInfo: { name: title, version: "1" },
93 });
94 case "ping":
95 return reply({});
96 case "tools/list":
97 return reply({
98 tools: tools.map(({ name, description, inputSchema }) => ({
99 name,
100 description,
101 inputSchema,
102 })),
103 });
104 case "tools/call": {
105 const tool = tools.find((t) => t.name === params.name);
106 if (tool === undefined)
107 return refuse(-32602, `no tool named ${String(params.name)}`);
108 const result = tool.run(db, who, fields(params.arguments));
109 return reply(
110 result.ok
111 ? { content: [{ type: "text", text: JSON.stringify(result.value) }] }
112 : {
113 content: [
114 { type: "text", text: `${result.error}: ${result.message}` },
115 ],
116 isError: true,
117 },
118 );
119 }
120 default:
121 return refuse(-32601, `no method ${m.method}`);
122 }
123 }
template/src/openapi.test.ts added +76
@@ -0,0 +1,76 @@
1 /**
2 * The API's description is the routes' own, committed: emitting it twice
3 * says the same bytes, the file in git is what the table says now, and the
4 * app serves exactly that file.
5 */
6 import { afterAll, expect, test } from "bun:test";
7 import { mkdtempSync, readFileSync, rmSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { emit, openapi } from "./openapi.ts";
11 import { routes } from "./routes.ts";
12 import { serve } from "./server.ts";
13
14 const committed = readFileSync(
15 new URL("../contract/openapi.json", import.meta.url),
16 "utf8",
17 );
18
19 test("emission is stable", () => {
20 expect(emit()).toBe(emit());
21 });
22
23 test("contract/openapi.json is what the routes say now (else: bun run contract:emit)", () => {
24 const now = JSON.parse(emit());
25 const stale = !Bun.deepEquals(JSON.parse(committed), now);
26 if (stale)
27 // Generated app's contract CLI: stderr is its output.
28 console.error(
29 "contract/openapi.json is stale: run `bun run contract:emit` and commit it",
30 );
31 expect(stale).toBe(false);
32 });
33
34 test("every API route is described, and every door names its cell of the table", () => {
35 const doc = openapi() as {
36 paths: Record<
37 string,
38 Record<
39 string,
40 { "x-contract"?: { resource: string; verb: string; least: string } }
41 >
42 >;
43 };
44 for (const route of routes.filter((r) => r.path.startsWith("/api/"))) {
45 const op =
46 doc.paths[route.path.replace(/:(\w+)/g, "{$1}")]?.[
47 route.method.toLowerCase()
48 ];
49 expect([route.method, route.path, op !== undefined]).toEqual([
50 route.method,
51 route.path,
52 true,
53 ]);
54 expect(typeof op?.["x-contract"]?.least).toBe("string");
55 }
56 expect(doc.paths["/api/audit"]?.get?.["x-contract"]).toEqual({
57 resource: "audit",
58 verb: "list",
59 least: "admin",
60 });
61 });
62
63 test("GET /openapi.json serves the committed file", async () => {
64 const dataDir = mkdtempSync(join(tmpdir(), "app-openapi-"));
65 const server = serve({ port: 0, dataDir, identityKey: "k" });
66 afterAll(() => {
67 server.stop(true);
68 rmSync(dataDir, { recursive: true, force: true });
69 });
70 const response = await fetch(
71 `http://${server.hostname}:${server.port}/openapi.json`,
72 );
73 expect(response.status).toBe(200);
74 expect(response.headers.get("content-type")).toContain("application/json");
75 expect(await response.text()).toBe(committed);
76 });
template/src/openapi.ts added +102
@@ -0,0 +1,102 @@
1 /**
2 * The API, described: every route in `routes.ts` that declares `api`, as an
3 * OpenAPI 3.1 document. Each operation also names the contract cell it is
4 * (`x-contract`: the resource, the verb, and the least role the table asks
5 * for), so a change of policy is a change here too, and shows in the pull.
6 *
7 * bun run contract:emit write contract/openapi.json from the table
8 *
9 * `src/openapi.test.ts` fails when the committed file and the routes
10 * disagree: the description can go stale only in a commit that fails.
11 */
12
13 import { contract } from "./contract.ts";
14 import { description, title, version } from "./env.ts";
15 import { AUDIT_ROW, ERROR, NOTE, routes, type Schema } from "./routes.ts";
16 import { doorOf } from "./security.ts";
17
18 // The shapes said once, under components, and referred to wherever they appear.
19 const NAMED = new Map<Schema, string>([
20 [NOTE, "Note"],
21 [AUDIT_ROW, "AuditRow"],
22 [ERROR, "Error"],
23 ]);
24 const named = (schema: Schema): Schema => {
25 const name = NAMED.get(schema);
26 if (name !== undefined) return { $ref: `#/components/schemas/${name}` };
27 return Object.fromEntries(
28 Object.entries(schema).map(([key, value]) => [
29 key,
30 typeof value === "object" && value !== null && !Array.isArray(value)
31 ? named(value as Schema)
32 : value,
33 ]),
34 );
35 };
36 const content = (schema: Schema) => ({
37 "application/json": { schema: named(schema) },
38 });
39
40 export function openapi(): Record<string, unknown> {
41 const paths: Record<string, Record<string, unknown>> = {};
42 for (const route of routes) {
43 if (route.api === undefined) continue;
44 const { summary, body, answer, status, query } = route.api;
45 const path = route.path.replace(/:(\w+)/g, "{$1}");
46 const params = [...route.path.matchAll(/:(\w+)/g)].map(([, name]) => ({
47 name,
48 in: "path",
49 required: true,
50 schema: { type: "integer" },
51 }));
52 const door = doorOf(route.method, route.path.replace(/:\w+/g, "0"));
53 const least =
54 door === undefined
55 ? undefined
56 : contract.resources[door.resource]?.can[door.verb];
57 paths[path] ??= {};
58 paths[path][route.method.toLowerCase()] = {
59 summary,
60 operationId: `${route.method.toLowerCase()}${path.replace(/[{}]/g, "").replace(/(^|[/._-])(\w)/g, (_, __, c: string) => c.toUpperCase())}`,
61 ...(params.length > 0 || query !== undefined
62 ? {
63 parameters: [
64 ...params,
65 ...Object.entries(query ?? {}).map(([name, schema]) => ({
66 name,
67 in: "query",
68 schema: named(schema),
69 })),
70 ],
71 }
72 : {}),
73 ...(body === undefined
74 ? {}
75 : { requestBody: { required: true, content: content(body) } }),
76 responses: {
77 [String(status ?? 200)]: {
78 description: summary,
79 content: content(answer),
80 },
81 default: {
82 description: "{ error, message }: why not",
83 content: content(ERROR),
84 },
85 },
86 ...(door === undefined ? {} : { "x-contract": { ...door, least } }),
87 };
88 }
89 return {
90 openapi: "3.1.0",
91 info: { title, version, description },
92 paths,
93 components: {
94 schemas: Object.fromEntries(
95 [...NAMED].map(([schema, name]) => [name, schema]),
96 ),
97 },
98 };
99 }
100
101 /** The file's text: stable, so the same table always writes the same bytes. */
102 export const emit = (): string => `${JSON.stringify(openapi(), null, 2)}\n`;
template/src/page.ts added +166
@@ -0,0 +1,166 @@
1 /**
2 * The page, rendered on the server: the first paint is complete HTML, and
3 * `static/live.js` keeps the notes fresh afterwards. When a second page
4 * arrives, move `layout` to `src/pages/layout.ts` and give each page a file.
5 */
6
7 import { canDelete, type Note } from "./actions.ts";
8 import {
9 commit,
10 description,
11 env,
12 publicOrigin,
13 ssh,
14 title,
15 where,
16 } from "./env.ts";
17 import { asset, escape } from "./http.ts";
18 import { CARD, websiteLd } from "./site.ts";
19 import { token, tokensHref } from "./tokens.ts";
20 import type { Who } from "./who.ts";
21
22 /**
23 * The frame every page shares: the tokens and the look, who you are, and
24 * what a link to the page says when it is shared — a title, a sentence
25 * and the address, for Open Graph and the card a chat app unfurls. A page
26 * that is not a place to land (an error) says `indexable = false`: no
27 * canonical address, no structured data, and a request to stay out of
28 * search.
29 */
30 export function layout(
31 body: string,
32 who: Who,
33 path = "/",
34 indexable = true,
35 heading = title,
36 ): string {
37 const door =
38 who.role === "anon"
39 ? `<a class="button button-quiet" href="/signin">Sign in</a>`
40 : `<span class="you"><b>${escape(who.name)}</b>${who.role === "admin" ? " · admin" : ""}</span>
41 <form class="signout" method="post" action="/signout"><button class="button button-quiet">Sign out</button></form>`;
42 return `<!doctype html>
43 <html lang="en">
44 <meta charset="utf-8">
45 <meta name="viewport" content="width=device-width, initial-scale=1">
46 <meta name="color-scheme" content="light dark">
47 <meta name="theme-color" content="${token("color-bg")}" media="(prefers-color-scheme: light)">
48 <meta name="theme-color" content="${token("color-bg", "dark")}" media="(prefers-color-scheme: dark)">
49 <link rel="icon" href="/icon.svg" type="image/svg+xml">
50 <link rel="apple-touch-icon" href="/apple-touch-icon.png">
51 <link rel="manifest" href="/manifest.webmanifest">
52 <title>${escape(title)}</title>
53 <meta name="description" content="${escape(description)}">
54 ${
55 indexable
56 ? `<link rel="canonical" href="${escape(publicOrigin + path)}">`
57 : `<meta name="robots" content="noindex">`
58 }
59 <meta property="og:type" content="website">
60 <meta property="og:site_name" content="${escape(title)}">
61 <meta property="og:title" content="${escape(title)}">
62 <meta property="og:description" content="${escape(description)}">
63 <meta property="og:url" content="${escape(publicOrigin + path)}">
64 <meta property="og:image" content="${escape(publicOrigin)}/og.png">
65 <meta property="og:image:width" content="${CARD.width}">
66 <meta property="og:image:height" content="${CARD.height}">
67 <meta property="og:image:alt" content="${escape(title)}">
68 <meta name="twitter:card" content="summary_large_image">
69 <meta name="twitter:image" content="${escape(publicOrigin)}/og.png">
70 <meta name="twitter:title" content="${escape(title)}">
71 <meta name="twitter:description" content="${escape(description)}">
72 ${indexable ? `<script type="application/ld+json">${websiteLd(title, description, publicOrigin)}</script>` : ""}
73 <link rel="stylesheet" href="${tokensHref}">
74 <link rel="stylesheet" href="${asset("app.css")}">
75 <script defer src="${asset("beacon.js")}"></script>
76 <script type="module" src="${asset("live.js")}"></script>
77 <body>
78 <a class="skip" href="#main">Skip to content</a>
79 <div class="page">
80 <header class="head">
81 <div>
82 <h1>${escape(heading)}</h1>
83 <p class="muted">${escape(description)}</p>
84 </div>
85 <nav class="row">
86 <span class="pill" data-env="${escape(env)}">${escape(where)}</span>${commit ? `<span class="muted mono">${escape(commit)}</span>` : ""}
87 ${door}
88 </nav>
89 </header>
90 <main id="main" tabindex="-1">${body}</main>
91 <footer class="muted">
92 ${ssh === undefined ? "" : `<p>Terminal: <code>${escape(ssh)}</code></p>`}
93 <p>Also at <a href="/api/notes">/api/notes</a> (<a href="/openapi.json">described</a>) and <code>POST /mcp</code>, with the same rules.</p>
94 <p>Something wrong? <a href="/__forge/report">Report a problem</a>, no account needed.</p>
95 </footer>
96 </div>
97 </body>
98 </html>
99 `;
100 }
101
102 /** The page for a refusal or a failure: the same frame, a plain word, a way back. */
103 export function problem(status: 404 | 500, who: Who): string {
104 const [heading, sentence] =
105 status === 404
106 ? ["Not found", "There is nothing at this address."]
107 : ["Something went wrong", "It was not you. Try again in a moment."];
108 return layout(
109 `<section class="card">
110 <p>${escape(sentence)}</p>
111 <p><a href="/">Back to ${escape(title)}</a></p>
112 </section>`,
113 who,
114 "/",
115 false,
116 heading,
117 );
118 }
119
120 export function home(input: {
121 who: Who;
122 notes: readonly Note[];
123 notice?: string | undefined;
124 }): string {
125 const { who, notes, notice } = input;
126 const composer =
127 who.role === "anon"
128 ? `<p class="muted">Reading as a guest. <a href="/signin">Sign in</a> to add a note.</p>`
129 : `<form class="row" method="post" action="/notes">
130 <input class="input" name="body" placeholder="Write a note" aria-label="New note" required maxlength="500" autocomplete="off" autofocus>
131 <button class="button">Add</button>
132 </form>`;
133 const list =
134 notes.length === 0
135 ? `<p class="empty">No notes yet. Notes written here stay in ${escape(where)} data.</p>`
136 : `<ul class="list">${notes.map((note) => item(note, who)).join("")}</ul>`;
137 return layout(
138 `<section class="card">${composer}</section>
139 <section id="notes" data-live="note.added note.removed">${list}</section>
140 ${notice === undefined ? "" : `<p class="toast" role="status">${escape(notice)}</p>`}`,
141 who,
142 );
143 }
144
145 const item = (note: Note, who: Who): string => `<li class="note">
146 <div>
147 <p>${escape(note.body)}</p>
148 <small class="muted">${escape(note.author_name)} · <time datetime="${escape(note.created_at)}">${ago(note.created_at)}</time></small>
149 </div>
150 ${
151 canDelete(who, note)
152 ? `<form method="post" action="/notes/${note.id}/delete"><button class="button button-quiet" aria-label="Remove this note">Remove</button></form>`
153 : ""
154 }
155 </li>`;
156
157 const ago = (iso: string): string => {
158 const s = Math.max(0, (Date.now() - Date.parse(iso)) / 1000);
159 if (s < 60) return "just now";
160 if (s < 3600) return `${Math.floor(s / 60)}m ago`;
161 if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
162 return new Date(iso).toLocaleDateString("en", {
163 month: "short",
164 day: "numeric",
165 });
166 };
template/src/routes.ts added +575
@@ -0,0 +1,575 @@
1 /**
2 * Every path the app answers, in one table. A route reads its request,
3 * calls an action, and shapes the answer for its door — HTML for a
4 * browser, JSON for a script — and that is all a route does.
5 *
6 * A route that is part of the API says so beside itself (`api`): one
7 * sentence, and the shape of what it takes and gives, as JSON Schema.
8 * `bun run contract:emit` writes those into `contract/openapi.json`, the
9 * tests fail when the committed file and this table disagree, and
10 * `GET /openapi.json` serves it. The shapes describe; the checks that hold
11 * are still the actions' own.
12 */
13
14 import type { Database } from "bun:sqlite";
15 import { existsSync, readFileSync } from "node:fs";
16 import {
17 addNote,
18 BODY_MAX,
19 deleteNote,
20 getAudit,
21 getNote,
22 listAudit,
23 listNotes,
24 updateNote,
25 type Failure,
26 type Result,
27 } from "./actions.ts";
28 import { commit, env, forgeUrl, publicOrigin, startedAt, version } from "./env.ts";
29 import {
30 back,
31 cookie,
32 fields,
33 html,
34 json,
35 readForm,
36 readJson,
37 readNotice,
38 redirectTo,
39 SECURITY,
40 staticFile,
41 text,
42 } from "./http.ts";
43 import { events } from "./live.ts";
44 import { rpc } from "./mcp.ts";
45 import { home } from "./page.ts";
46 import { appleTouch, card, iconSvg, llmsTxt, manifest, securityTxt, sitemap } from "./site.ts";
47 import {
48 begin,
49 endSession,
50 finish,
51 LOGIN_COOKIE,
52 LOGIN_MAX_AGE,
53 SESSION_COOKIE,
54 SESSION_MAX_AGE,
55 type Signin,
56 } from "./signin.ts";
57 import { tokensCss } from "./tokens.ts";
58 import type { Who } from "./who.ts";
59
60 export interface Context {
61 readonly request: Request;
62 readonly url: URL;
63 readonly db: Database;
64 readonly who: Who;
65 readonly params: Record<string, string>;
66 /** Sign-in through the forge; undefined when the app does not know where the forge is. */
67 readonly signin?: Signin | undefined;
68 }
69
70 /** A JSON Schema, as plain data. */
71 export type Schema = Readonly<Record<string, unknown>>;
72
73 /** What an API route is, for the description: never consulted to decide anything. */
74 export interface Api {
75 readonly summary: string;
76 /** The body it reads. */
77 readonly body?: Schema;
78 /** What it answers when it succeeds, and with which status (200). */
79 readonly answer: Schema;
80 readonly status?: number;
81 /** The query parameters it reads. */
82 readonly query?: Readonly<Record<string, Schema>>;
83 }
84
85 export interface Route {
86 readonly method: "GET" | "POST" | "PATCH" | "DELETE";
87 readonly path: string;
88 readonly handle: (ctx: Context) => Response | Promise<Response>;
89 readonly api?: Api;
90 }
91
92 // The shapes the API speaks in, named once.
93 export const NOTE: Schema = {
94 type: "object",
95 properties: {
96 id: { type: "integer" },
97 body: { type: "string", minLength: 1, maxLength: BODY_MAX },
98 author_id: { type: "string" },
99 author_name: { type: "string" },
100 created_at: { type: "string", format: "date-time" },
101 updated_at: { type: "string", format: "date-time" },
102 },
103 required: [
104 "id",
105 "body",
106 "author_id",
107 "author_name",
108 "created_at",
109 "updated_at",
110 ],
111 };
112 const NOTE_BODY: Schema = {
113 type: "object",
114 properties: { body: { type: "string", minLength: 1, maxLength: BODY_MAX } },
115 required: ["body"],
116 };
117 export const AUDIT_ROW: Schema = {
118 type: "object",
119 properties: {
120 id: { type: "integer" },
121 at: { type: "string", format: "date-time" },
122 who_id: { type: ["string", "null"] },
123 who_name: { type: ["string", "null"] },
124 role: { enum: ["anon", "user", "admin"] },
125 resource: { type: "string" },
126 verb: { type: "string" },
127 target: { type: ["string", "null"] },
128 allowed: { enum: [0, 1] },
129 outcome: { type: "string" },
130 },
131 required: ["id", "at", "role", "resource", "verb", "allowed", "outcome"],
132 };
133 export const ERROR: Schema = {
134 type: "object",
135 properties: { error: { type: "string" }, message: { type: "string" } },
136 required: ["error"],
137 };
138 const LIMIT: Schema = {
139 type: "integer",
140 minimum: 1,
141 maximum: 500,
142 default: 100,
143 };
144 const list = (items: Schema): Schema => ({ type: "array", items });
145
146 const STATUS: Record<Failure, number> = {
147 signin_required: 401,
148 forbidden: 403,
149 not_found: 404,
150 invalid: 422,
151 };
152
153 /** A result as JSON: the value, or `{ error, message }` with the matching status. */
154 const answer = <T>(result: Result<T>, status = 200): Response =>
155 result.ok
156 ? json(result.value, status)
157 : json(
158 { error: result.error, message: result.message },
159 STATUS[result.error],
160 );
161
162 /** A result for a form: back to the page, with what went wrong if it did. */
163 const done = <T>(result: Result<T>): Response =>
164 result.ok ? back() : back(result.message);
165
166 const DAY = 86400;
167
168 /** A generated file, with the floor and how long it may be kept. */
169 const file = (
170 body: string | Uint8Array,
171 type: string,
172 maxAge = 0,
173 ): Response =>
174 new Response(body as BodyInit, {
175 headers: {
176 "content-type": type,
177 "cache-control": maxAge > 0 ? `public, max-age=${maxAge}` : "no-cache",
178 ...SECURITY,
179 },
180 });
181
182 /** A whole number from the query, or undefined. */
183 const whole = (value: string | null): number | undefined =>
184 value !== null && /^\d+$/.test(value) ? Number(value) : undefined;
185
186 // The API's description, read from git once: what the tests hold equal to this table.
187 const OPENAPI = new URL("../contract/openapi.json", import.meta.url);
188 const openapi = existsSync(OPENAPI) ? readFileSync(OPENAPI, "utf8") : undefined;
189
190 export const routes: readonly Route[] = [
191 // Sign in through the forge (OpenID Connect, code flow with PKCE): out to
192 // the forge, back with a code, a session in an HttpOnly cookie.
193 {
194 method: "GET",
195 path: "/signin",
196 handle: async (c) => {
197 if (c.signin === undefined)
198 return text("sign-in is off: FORGE_URL is not set", 503);
199 try {
200 const { location, state } = await begin(c.db, c.signin);
201 return redirectTo(location, cookie(LOGIN_COOKIE, state, LOGIN_MAX_AGE));
202 } catch (error) {
203 console.error(error);
204 return text("the forge could not be reached to sign you in", 502);
205 }
206 },
207 },
208 {
209 method: "GET",
210 path: "/signin/callback",
211 handle: async (c) => {
212 if (c.signin === undefined) return text("sign-in is off", 503);
213 const done = await finish(c.db, c.signin, c.request, c.url);
214 if (!done.ok)
215 return redirectTo(
216 "/",
217 cookie(LOGIN_COOKIE, "", 0),
218 cookie("notice", encodeURIComponent(done.message), 30),
219 );
220 return redirectTo(
221 "/",
222 cookie(LOGIN_COOKIE, "", 0),
223 cookie(SESSION_COOKIE, done.session, SESSION_MAX_AGE),
224 );
225 },
226 },
227 {
228 method: "POST",
229 path: "/signout",
230 handle: (c) => {
231 endSession(c.db, c.request);
232 return redirectTo(
233 env === "local" ? "/" : "/__forge/signout?to=/",
234 cookie(SESSION_COOKIE, "", 0),
235 );
236 },
237 },
238
239 // The page. Forms post and come back; the list stays live over /events.
240 {
241 method: "GET",
242 path: "/",
243 handle: (c) => {
244 const { notice, clear } = readNotice(c.request);
245 const notes = listNotes(c.db, c.who);
246 return html(
247 home({ who: c.who, notes: notes.ok ? notes.value : [], notice }),
248 200,
249 clear,
250 );
251 },
252 },
253 {
254 method: "POST",
255 path: "/notes",
256 handle: async (c) => {
257 const form = await readForm(c.request);
258 if (form === undefined) return text("too large", 413);
259 return done(
260 addNote(c.db, c.who, { body: String(form.get("body") ?? "") }),
261 );
262 },
263 },
264 {
265 method: "POST",
266 path: "/notes/:id/delete",
267 handle: (c) => done(deleteNote(c.db, c.who, { id: Number(c.params.id) })),
268 },
269
270 // The JSON API: the same actions, the same identity, plain status codes.
271 {
272 method: "GET",
273 path: "/api/notes",
274 handle: (c) =>
275 answer(
276 listNotes(c.db, c.who, {
277 limit: Number(c.url.searchParams.get("limit") ?? 100),
278 }),
279 ),
280 api: {
281 summary: "The notes, newest first.",
282 query: { limit: LIMIT },
283 answer: list(NOTE),
284 },
285 },
286 {
287 method: "POST",
288 path: "/api/notes",
289 handle: async (c) => {
290 const body = await readJson(c.request);
291 if (body === undefined) return json({ error: "too_large" }, 413);
292 return answer(
293 addNote(c.db, c.who, { body: String(fields(body).body ?? "") }),
294 201,
295 );
296 },
297 api: {
298 summary: "Add a note as the person asking.",
299 body: NOTE_BODY,
300 answer: NOTE,
301 status: 201,
302 },
303 },
304 {
305 method: "GET",
306 path: "/api/notes/:id",
307 handle: (c) => answer(getNote(c.db, c.who, { id: Number(c.params.id) })),
308 api: { summary: "One note.", answer: NOTE },
309 },
310 {
311 method: "PATCH",
312 path: "/api/notes/:id",
313 handle: async (c) => {
314 const body = await readJson(c.request);
315 if (body === undefined) return json({ error: "too_large" }, 413);
316 return answer(
317 updateNote(c.db, c.who, {
318 id: Number(c.params.id),
319 body: String(fields(body).body ?? ""),
320 }),
321 );
322 },
323 api: { summary: "Change a note's words.", body: NOTE_BODY, answer: NOTE },
324 },
325 {
326 method: "DELETE",
327 path: "/api/notes/:id",
328 handle: (c) => answer(deleteNote(c.db, c.who, { id: Number(c.params.id) })),
329 api: {
330 summary: "Remove a note.",
331 answer: {
332 type: "object",
333 properties: { id: { type: "integer" } },
334 required: ["id"],
335 },
336 },
337 },
338
339 // Who tried to change what: the audit trail, for whoever the table lets read it.
340 {
341 method: "GET",
342 path: "/api/audit",
343 handle: (c) =>
344 answer(
345 listAudit(c.db, c.who, {
346 limit: whole(c.url.searchParams.get("limit")) ?? 100,
347 ...(whole(c.url.searchParams.get("before")) === undefined
348 ? {}
349 : { before: whole(c.url.searchParams.get("before"))! }),
350 }),
351 ),
352 api: {
353 summary: "The audit trail, newest first; `before` pages back by id.",
354 query: { limit: LIMIT, before: { type: "integer" } },
355 answer: list(AUDIT_ROW),
356 },
357 },
358 {
359 method: "GET",
360 path: "/api/audit/:id",
361 handle: (c) => answer(getAudit(c.db, c.who, { id: Number(c.params.id) })),
362 api: { summary: "One row of the audit trail.", answer: AUDIT_ROW },
363 },
364
365 // Live events, and the MCP server (the tools are the actions too).
366 { method: "GET", path: "/events", handle: (c) => events(c.request) },
367 {
368 method: "POST",
369 path: "/mcp",
370 handle: async (c) => {
371 const message = await readJson(c.request);
372 if (message === undefined) return json({ error: "too_large" }, 413);
373 if (message === null)
374 return json({
375 jsonrpc: "2.0",
376 id: null,
377 error: { code: -32700, message: "parse error" },
378 });
379 const { status, body } = rpc(c.db, c.who, message);
380 return body === undefined
381 ? new Response(null, { status })
382 : json(body, status);
383 },
384 api: {
385 summary:
386 "One JSON-RPC 2.0 message to the MCP server; its tools are the actions.",
387 body: {
388 type: "object",
389 properties: {
390 jsonrpc: { const: "2.0" },
391 id: {},
392 method: { type: "string" },
393 params: { type: "object" },
394 },
395 required: ["jsonrpc", "method"],
396 },
397 answer: { type: "object" },
398 },
399 },
400 {
401 method: "GET",
402 path: "/mcp",
403 handle: () => text("this endpoint speaks JSON-RPC over POST", 405),
404 },
405
406 // Up or not, for the forge and for anyone watching: a separate path from
407 // the page, so a health check never renders it.
408 {
409 method: "GET",
410 path: "/healthz",
411 handle: (c) => {
412 let ok = true;
413 try {
414 c.db.query("SELECT 1").get();
415 } catch {
416 ok = false;
417 }
418 const uptime = Math.floor((Date.now() - startedAt) / 1000);
419 return new Response(
420 JSON.stringify({ ok, version, commit, env, uptime }),
421 {
422 status: ok ? 200 : 503,
423 headers: {
424 "content-type": "application/json; charset=utf-8",
425 "cache-control": "no-store",
426 ...SECURITY,
427 },
428 },
429 );
430 },
431 api: {
432 summary:
433 "Whether the app is up: its version, commit, environment and seconds since it started.",
434 answer: {
435 type: "object",
436 properties: {
437 ok: { type: "boolean" },
438 version: { type: "string" },
439 commit: { type: "string" },
440 env: { type: "string" },
441 uptime: { type: "integer" },
442 },
443 required: ["ok", "version", "uptime"],
444 },
445 },
446 },
447 {
448 method: "GET",
449 path: "/openapi.json",
450 handle: () =>
451 openapi === undefined
452 ? text("not found", 404)
453 : new Response(openapi, {
454 headers: {
455 "content-type": "application/json; charset=utf-8",
456 "cache-control": "no-cache",
457 ...SECURITY,
458 },
459 }),
460 },
461
462 // The look: design/tokens.json, compiled at boot, cached for a year when linked by content.
463 {
464 method: "GET",
465 path: "/tokens.css",
466 handle: (c) =>
467 new Response(tokensCss, {
468 headers: {
469 "content-type": "text/css; charset=utf-8",
470 "cache-control": c.url.searchParams.has("v")
471 ? "public, max-age=31536000, immutable"
472 : "no-cache",
473 ...SECURITY,
474 },
475 }),
476 },
477
478 // What the web expects of a site (specification.website). Crawlers read
479 // the page, not the API; a preview is a draft and is read by nobody.
480 // Where to report a vulnerability is the forge's to say: it runs this app.
481 {
482 method: "GET",
483 path: "/robots.txt",
484 handle: () =>
485 text(
486 env === "production"
487 ? `User-agent: *\nDisallow: /api/\nDisallow: /mcp\nDisallow: /events\nDisallow: /__forge/\n\nSitemap: ${publicOrigin}/sitemap.xml\n`
488 : `User-agent: *\nDisallow: /\n\nSitemap: ${publicOrigin}/sitemap.xml\n`,
489 ),
490 },
491 {
492 method: "GET",
493 path: "/sitemap.xml",
494 handle: () => file(sitemap(), "application/xml; charset=utf-8"),
495 },
496 {
497 method: "GET",
498 path: "/llms.txt",
499 handle: () => file(llmsTxt(), "text/plain; charset=utf-8"),
500 },
501 // The app's face outside the page: the tab's icon, the home-screen icon
502 // and install manifest, and the card a shared link unfurls. Drawn from
503 // the tokens and the app's name, so they change when those do.
504 {
505 method: "GET",
506 path: "/icon.svg",
507 handle: () => file(iconSvg(), "image/svg+xml", DAY),
508 },
509 {
510 method: "GET",
511 path: "/apple-touch-icon.png",
512 handle: () => file(appleTouch(), "image/png", DAY),
513 },
514 {
515 method: "GET",
516 path: "/og.png",
517 handle: () => file(card(), "image/png", DAY),
518 },
519 {
520 method: "GET",
521 path: "/manifest.webmanifest",
522 handle: () => file(manifest(), "application/manifest+json", DAY),
523 },
524 // There is no password here: accounts are the forge's, so that is where
525 // a person goes to change one (specification.website/#change-password).
526 {
527 method: "GET",
528 path: "/.well-known/change-password",
529 handle: () =>
530 new Response(null, {
531 status: 302,
532 headers: { location: forgeUrl ?? "/", ...SECURITY },
533 }),
534 },
535 {
536 method: "GET",
537 path: "/.well-known/security.txt",
538 handle: () => text(securityTxt()),
539 },
540
541 // Files under ./static, cached for a year when linked by content (`asset`).
542 {
543 method: "GET",
544 path: "/static/:file",
545 handle: (c) => staticFile(c.params.file ?? "", c.url.searchParams.has("v")),
546 },
547 ];
548
549 /** The route for a method and path, with what its `:names` matched. */
550 export function match(
551 method: string,
552 pathname: string,
553 ): { route: Route; params: Record<string, string> } | undefined {
554 const parts = pathname.split("/");
555 for (const route of routes) {
556 if (route.method !== method) continue;
557 const pattern = route.path.split("/");
558 if (pattern.length !== parts.length) continue;
559 const params: Record<string, string> = {};
560 const hit = pattern.every((p, i) => {
561 if (p.startsWith(":")) {
562 // A malformed escape is no match, never a thrown error.
563 try {
564 params[p.slice(1)] = decodeURIComponent(parts[i] ?? "");
565 return true;
566 } catch {
567 return false;
568 }
569 }
570 return p === parts[i];
571 });
572 if (hit) return { route, params };
573 }
574 return undefined;
575 }
template/src/security.test.ts added +187
@@ -0,0 +1,187 @@
1 /**
2 * The door turns away, before a byte of the body is read, exactly who the
3 * table says could never pass — and nobody it would let through.
4 */
5 import { afterAll, expect, test } from "bun:test";
6 import { mkdtempSync, rmSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { readContract } from "./can.ts";
10 import { openDb } from "./db.ts";
11 import {
12 allow,
13 door,
14 doorOf,
15 mayKnock,
16 openToStrangers,
17 SIGNINS,
18 STRANGERS,
19 } from "./security.ts";
20 import { serve } from "./server.ts";
21 import { sign } from "./who.ts";
22
23 const KEY = "a-key-only-the-forge-holds";
24 const dataDir = mkdtempSync(join(tmpdir(), "app-door-"));
25 const server = serve({ port: 0, dataDir, identityKey: KEY });
26 const base = `http://${server.hostname}:${server.port}`;
27 afterAll(() => {
28 server.stop(true);
29 rmSync(dataDir, { recursive: true, force: true });
30 });
31 const as = (id: string, role: "user" | "admin"): Record<string, string> => {
32 const identity = `${id}|${id}|${role}|${Date.now() + 60_000}`;
33 return {
34 "x-forge-identity": identity,
35 "x-forge-signature": sign(identity, KEY),
36 };
37 };
38
39 test("a path is a resource's door by the contract's api, and nothing else is", () => {
40 expect(doorOf("GET", "/api/notes")).toEqual({
41 resource: "note",
42 verb: "list",
43 });
44 expect(doorOf("POST", "/api/notes")).toEqual({
45 resource: "note",
46 verb: "create",
47 });
48 expect(doorOf("GET", "/api/notes/7")).toEqual({
49 resource: "note",
50 verb: "read",
51 });
52 expect(doorOf("PATCH", "/api/notes/7")).toEqual({
53 resource: "note",
54 verb: "update",
55 });
56 expect(doorOf("DELETE", "/api/notes/7")).toEqual({
57 resource: "note",
58 verb: "delete",
59 });
60 expect(doorOf("GET", "/api/audit")).toEqual({
61 resource: "audit",
62 verb: "list",
63 });
64 for (const [method, path] of [
65 ["PUT", "/api/notes"],
66 ["GET", "/api/notes/7/x"],
67 ["GET", "/api/notesy"],
68 ["GET", "/api/notes/"],
69 ["POST", "/notes"],
70 ] as const)
71 expect(doorOf(method, path)).toBeUndefined();
72 });
73
74 test("the door refuses only what no row would open", () => {
75 const anon = { role: "anon" } as const;
76 const alice = { role: "user", id: "u1", name: "alice" } as const;
77 const root = { role: "admin", id: "u0", name: "root" } as const;
78 expect(mayKnock(anon, "note", "list")).toBe(true);
79 expect(mayKnock(anon, "note", "create")).toBe(false);
80 expect(mayKnock(anon, "note", "delete")).toBe(false);
81 // alice may delete a note of her own, so the door lets her ask; the action decides which.
82 expect(mayKnock(alice, "note", "delete")).toBe(true);
83 expect(mayKnock(alice, "audit", "list")).toBe(false);
84 expect(mayKnock(root, "audit", "list")).toBe(true);
85 expect(mayKnock(root, "audit", "create")).toBe(false);
86 });
87
88 test("a stranger is refused /api before the body is read, when the contract closes it", async () => {
89 // A body past the cap: read, it would be 413. The door answers first.
90 const huge = "x".repeat(128 * 1024);
91 const refused = await fetch(`${base}/api/notes`, {
92 method: "POST",
93 headers: { "content-type": "application/json" },
94 body: huge,
95 });
96 expect(refused.status).toBe(401);
97 const signedIn = await fetch(`${base}/api/notes`, {
98 method: "POST",
99 headers: { "content-type": "application/json", ...as("u1", "user") },
100 body: huge,
101 });
102 expect(signedIn.status).toBe(413);
103 expect(await refused.json()).toEqual({
104 error: "signin_required",
105 message: "Sign in first.",
106 });
107 expect((await fetch(`${base}/api/audit`)).status).toBe(401);
108 expect((await fetch(`${base}/api/audit/1`)).status).toBe(401);
109 expect(
110 (await fetch(`${base}/api/audit`, { headers: as("u1", "user") })).status,
111 ).toBe(403);
112 // What the table opens stays open.
113 expect((await fetch(`${base}/api/notes`)).status).toBe(200);
114 expect((await fetch(`${base}/api/notes/0`)).status).toBe(404);
115 expect((await fetch(`${base}/openapi.json`)).status).toBe(200);
116 });
117
118 test("the API's description is shut to strangers when the table opens them no door", () => {
119 const closed = readContract(
120 JSON.stringify({
121 roles: {
122 anon: { above: [], held: { by: "everyone" } },
123 user: { above: ["anon"], held: { by: "identity", role: "user" } },
124 },
125 resources: {
126 note: {
127 api: "/api/notes",
128 can: {
129 create: "user",
130 read: "user",
131 update: "user",
132 delete: "user",
133 list: "user",
134 },
135 },
136 },
137 }),
138 );
139 if (!closed.ok) throw new Error(closed.problems.join("; "));
140 expect(openToStrangers(closed.contract)).toBe(false);
141 expect(openToStrangers()).toBe(true);
142 });
143
144 test("strangers are rationed at the API, reads too", () => {
145 const db = openDb(mkdtempSync(join(dataDir, "rate-")));
146 const knock = () =>
147 door(
148 db,
149 new Request("http://app/api/notes"),
150 new URL("http://app/api/notes"),
151 { role: "anon" },
152 "203.0.113.7",
153 );
154 const answers = Array.from({ length: STRANGERS.burst + 5 }, knock);
155 expect(answers.slice(0, STRANGERS.burst).every((a) => a === undefined)).toBe(
156 true,
157 );
158 expect(answers.at(-1)?.status).toBe(429);
159 // The page itself is not the API: a stranger reading it is never rationed here.
160 expect(
161 door(
162 db,
163 new Request("http://app/"),
164 new URL("http://app/"),
165 { role: "anon" },
166 "203.0.113.7",
167 ),
168 ).toBeUndefined();
169 // Starting a sign-in writes a row, so it is rationed per address, signed in or not.
170 const start = (from: string) =>
171 door(
172 db,
173 new Request("http://app/signin"),
174 new URL("http://app/signin"),
175 { role: "anon" },
176 from,
177 );
178 const starts = Array.from({ length: SIGNINS.burst + 5 }, () => start("198.51.100.9"));
179 expect(starts.slice(0, SIGNINS.burst).every((a) => a === undefined)).toBe(true);
180 expect(starts.at(-1)?.status).toBe(429);
181 expect(start("198.51.100.10")).toBeUndefined();
182 // A bucket refills.
183 const t = Date.now();
184 for (let i = 0; i < 25; i++) allow("k", { burst: 20, perSecond: 2 }, t);
185 expect(allow("k", { burst: 20, perSecond: 2 }, t)).toBe(false);
186 expect(allow("k", { burst: 20, perSecond: 2 }, t + 1000)).toBe(true);
187 });
template/src/security.ts added +193
@@ -0,0 +1,193 @@
1 /**
2 * The door: what every request passes before a route sees it, and before
3 * a byte of its body is read. Three checks, in order:
4 *
5 * 1. **Rationing.** Writes are rationed per person (per address, for a
6 * stranger), and a stranger's calls to the API are rationed too.
7 * 2. **Same origin.** A write that a browser says came from another site
8 * is refused: that is another page making this person's browser act.
9 * 3. **The contract.** A request under a resource's `api` is that
10 * resource's verb (see docs/CONTRACT.md in the forge: `GET api` lists,
11 * `POST api` creates, `GET|PATCH|DELETE api/<id>` read, update,
12 * delete). If the table lets this person through that door for no row
13 * at all, they are refused here — 401 for a stranger, 403 for anyone
14 * else. The action asks again, about the real row; the door only turns
15 * away who could never pass. `/openapi.json` is shut to strangers when
16 * the table opens no door to them.
17 *
18 * Nothing here compares roles by hand: the answer is `decide`'s, from the
19 * same table the actions read. Refused writes go into the audit trail.
20 */
21
22 import type { Database } from "bun:sqlite";
23 import { record } from "./audit.ts";
24 import { decide, VERBS, type Contract, type Verb } from "./can.ts";
25 import { actorOf, contract } from "./contract.ts";
26 import { publicOrigin } from "./env.ts";
27 import { json, text } from "./http.ts";
28 import type { Who } from "./who.ts";
29
30 // A browser on another site can make a person's browser POST here; it cannot
31 // make that request look same-origin. Browsers say where a request came from
32 // (Sec-Fetch-Site, or Origin); a request that names another site is refused.
33 // A script sends neither and is judged by its identity instead.
34 export const sameOrigin = (request: Request): boolean => {
35 const site = request.headers.get("sec-fetch-site");
36 if (site !== null) return site === "same-origin" || site === "none";
37 const origin = request.headers.get("origin");
38 return origin === null || origin === publicOrigin;
39 };
40
41 // A bucket of `burst` tokens that refills at `perSecond`. In memory, so a
42 // restart forgets — which is the right size for one process on one machine.
43 export interface Rate {
44 readonly burst: number;
45 readonly perSecond: number;
46 }
47 export const WRITES: Rate = { burst: 20, perSecond: 2 };
48 /** A stranger's API calls, reads too. Behind the forge every stranger shares one address, so this is all of them together. */
49 export const STRANGERS: Rate = { burst: 60, perSecond: 10 };
50 /** Each start of a sign-in writes a row; one address may not flush the rest. Behind the forge this is everyone together. */
51 export const SIGNINS: Rate = { burst: 20, perSecond: 1 };
52 const buckets = new Map<string, { tokens: number; at: number }>();
53 export function allow(
54 key: string,
55 rate: Rate = WRITES,
56 now = Date.now(),
57 ): boolean {
58 const bucket = buckets.get(key) ?? { tokens: rate.burst, at: now };
59 bucket.tokens = Math.min(
60 rate.burst,
61 bucket.tokens + ((now - bucket.at) / 1000) * rate.perSecond,
62 );
63 bucket.at = now;
64 buckets.set(key, bucket);
65 if (buckets.size > 10_000)
66 for (const [k, b] of buckets) if (now - b.at > 60_000) buckets.delete(k);
67 if (bucket.tokens < 1) return false;
68 bucket.tokens -= 1;
69 return true;
70 }
71
72 const ROW_VERB: Readonly<Record<string, Verb>> = {
73 GET: "read",
74 PATCH: "update",
75 DELETE: "delete",
76 };
77 const SET_VERB: Readonly<Record<string, Verb>> = {
78 GET: "list",
79 POST: "create",
80 };
81
82 /** The resource and verb a request is, by the contract's `api` paths; undefined for any other path. */
83 export function doorOf(
84 method: string,
85 pathname: string,
86 table: Contract = contract,
87 ): { resource: string; verb: Verb } | undefined {
88 for (const [resource, { api }] of Object.entries(table.resources)) {
89 if (api === undefined) continue;
90 if (pathname === api) {
91 const verb = SET_VERB[method];
92 return verb === undefined ? undefined : { resource, verb };
93 }
94 const rest = pathname.startsWith(`${api}/`)
95 ? pathname.slice(api.length + 1)
96 : undefined;
97 if (rest !== undefined && rest !== "" && !rest.includes("/")) {
98 const verb = ROW_VERB[method];
99 return verb === undefined ? undefined : { resource, verb };
100 }
101 }
102 return undefined;
103 }
104
105 /**
106 * Could `who` pass this door for any row at all? The door asks about a row
107 * that names them in every column a role is held by — the best row they
108 * could hope for — so it refuses only what no row would open.
109 */
110 export function mayKnock(
111 who: Who,
112 resource: string,
113 verb: Verb,
114 table: Contract = contract,
115 ): boolean {
116 const actor = actorOf(who);
117 const columns = Object.values(table.roles).flatMap((role) =>
118 role.held.by === "row" ? [role.held.column] : [],
119 );
120 const best =
121 verb === "list" || verb === "create" || actor.id === null
122 ? undefined
123 : Object.fromEntries(columns.map((column) => [column, actor.id]));
124 return decide(table, resource, verb, actor, best) !== "no";
125 }
126
127 /** Does the table open any door with an `api` to a stranger? Then the API's description is theirs to read. */
128 export const openToStrangers = (table: Contract = contract): boolean =>
129 Object.entries(table.resources).some(
130 ([resource, { api }]) =>
131 api !== undefined &&
132 VERBS.some((verb) => mayKnock({ role: "anon" }, resource, verb, table)),
133 );
134 const describedToStrangers = openToStrangers();
135
136 /**
137 * The door. `undefined` lets the request through to its route; a response
138 * is the refusal. `from` is the caller's address, for rationing a stranger.
139 */
140 export function door(
141 db: Database,
142 request: Request,
143 url: URL,
144 who: Who,
145 from: string,
146 ): Response | undefined {
147 const method = request.method === "HEAD" ? "GET" : request.method;
148 const writing = method !== "GET";
149 const stranger = who.role === "anon";
150 const api =
151 url.pathname.startsWith("/api/") ||
152 url.pathname === "/mcp" ||
153 url.pathname === "/openapi.json";
154 const key = stranger ? `ip:${from}` : `user:${who.id}`;
155
156 if (writing && !allow(key)) return text("too many requests", 429);
157 if (url.pathname === "/signin" && !allow(`signin:${from}`, SIGNINS))
158 return text("too many requests", 429);
159 if (stranger && api && !allow(`api:${from}`, STRANGERS))
160 return text("too many requests", 429);
161
162 const found = doorOf(method, url.pathname);
163 if (writing && !sameOrigin(request)) {
164 record(db, {
165 who,
166 resource: found?.resource ?? url.pathname,
167 verb: found?.verb ?? method,
168 outcome: "cross_site",
169 });
170 return text("forbidden", 403);
171 }
172
173 const shut =
174 found === undefined
175 ? url.pathname === "/openapi.json" && stranger && !describedToStrangers
176 : !mayKnock(who, found.resource, found.verb);
177 if (!shut) return undefined;
178 const outcome = stranger ? "signin_required" : "forbidden";
179 if (writing && found !== undefined)
180 record(db, {
181 who,
182 resource: found.resource,
183 verb: found.verb,
184 target:
185 url.pathname === contract.resources[found.resource]?.api
186 ? undefined
187 : url.pathname.split("/").at(-1),
188 outcome,
189 });
190 return stranger
191 ? json({ error: outcome, message: "Sign in first." }, 401)
192 : json({ error: outcome, message: "You may not." }, 403);
193 }
template/src/server.test.ts added +376
@@ -0,0 +1,376 @@
1 import { afterAll, expect, test } from "bun:test";
2 import { mkdtempSync, rmSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { openDb } from "./db.ts";
6 import { env, publicOrigin } from "./env.ts";
7 import { serve } from "./server.ts";
8 import { sign } from "./who.ts";
9
10 const KEY = "a-key-only-the-forge-holds";
11 const dataDir = mkdtempSync(join(tmpdir(), "app-"));
12 const server = serve({ port: 0, dataDir, identityKey: KEY });
13 const base = `http://${server.hostname}:${server.port}`;
14 afterAll(() => {
15 server.stop(true);
16 rmSync(dataDir, { recursive: true, force: true });
17 });
18
19 /** The headers the forge sends for a signed-in person. */
20 const as = (
21 id: string,
22 name: string,
23 role: "user" | "admin" = "user",
24 ): Record<string, string> => {
25 const identity = `${id}|${name}|${role}|${Date.now() + 60_000}`;
26 return {
27 "x-forge-identity": identity,
28 "x-forge-signature": sign(identity, KEY),
29 };
30 };
31 const alice = as("u1", "alice");
32 const bob = as("u2", "bob");
33 const root = as("u0", "root", "admin");
34 const jsonBody = (body: unknown): RequestInit => ({
35 headers: { "content-type": "application/json" },
36 body: JSON.stringify(body),
37 });
38 const api = (
39 path: string,
40 init: RequestInit = {},
41 who: Record<string, string> = {},
42 ) =>
43 fetch(base + path, {
44 ...init,
45 headers: { ...(init.headers as Record<string, string>), ...who },
46 });
47 const rpc = (message: unknown, who: Record<string, string> = {}) =>
48 api("/mcp", { method: "POST", ...jsonBody(message) }, who).then(
49 (r) => r.json() as Promise<any>,
50 );
51
52 test("a session signs a person in, and a signed header from the forge outranks it", async () => {
53 openDb(dataDir)
54 .query("INSERT INTO session VALUES (?1, 'u1', 'sam', ?2)")
55 .run(
56 new Bun.CryptoHasher("sha256").update("sess").digest("hex"),
57 Date.now() + 60_000,
58 );
59 const session = { cookie: "session=sess" };
60 const alone = await (await api("/", {}, session)).text();
61 expect(alone).toContain("<b>sam</b>");
62 expect(alone).not.toContain("admin");
63 // An admin who signs in this way keeps being an admin while the forge says so.
64 const both = await (await api("/", {}, { ...session, ...root })).text();
65 expect(both).toContain("<b>root</b> · admin");
66 expect(both).not.toContain("<b>sam</b>");
67 // A forged header does not outrank anything.
68 const forged = await (
69 await api("/", {}, { ...session, "x-forge-identity": "u0|root|admin|9999999999999", "x-forge-signature": "nope" })
70 ).text();
71 expect(forged).toContain("<b>sam</b>");
72 });
73
74 test("the page knows who you are and offers the right door", async () => {
75 const guest = await (await fetch(base + "/")).text();
76 expect(guest).toContain("<h1>");
77 expect(guest).toContain('href="/signin"');
78 expect(guest).toContain('href="/__forge/report"');
79 expect(guest).not.toContain('action="/notes"');
80 const signed = await (await api("/", {}, alice)).text();
81 expect(signed).toContain("<b>alice</b>");
82 expect(signed).toContain('action="/signout"');
83 expect(signed).toContain('action="/notes"');
84 });
85
86 test("a form post adds as the person; a guest is sent to sign in", async () => {
87 const form = new FormData();
88 form.set("body", "hello from a form");
89 const refused = await api("/notes", {
90 method: "POST",
91 body: form,
92 redirect: "manual",
93 });
94 expect(refused.status).toBe(303);
95 expect(refused.headers.get("set-cookie")).toContain("notice=");
96 expect(refused.headers.get("set-cookie")).toContain("SameSite=Lax");
97 expect(await (await fetch(base + "/")).text()).not.toContain(
98 "hello from a form",
99 );
100 const posted = await api(
101 "/notes",
102 { method: "POST", body: form, redirect: "manual" },
103 alice,
104 );
105 expect(posted.status).toBe(303);
106 expect(posted.headers.get("set-cookie")).toBeNull();
107 const page = await (await api("/", {}, alice)).text();
108 expect(page).toContain("hello from a form");
109 expect(page).toContain("alice ·");
110 });
111
112 test("the JSON API is the same actions with the same identity", async () => {
113 const created = await api(
114 "/api/notes",
115 { method: "POST", ...jsonBody({ body: "over the api" }) },
116 alice,
117 );
118 expect(created.status).toBe(201);
119 const note = (await created.json()) as { id: number; author_name: string };
120 expect(note.author_name).toBe("alice");
121 const listed = (await (await fetch(base + "/api/notes")).json()) as {
122 id: number;
123 }[];
124 expect(listed.map((n) => n.id)).toContain(note.id);
125 expect(
126 (await api("/api/notes", { method: "POST", ...jsonBody({ body: "anon" }) }))
127 .status,
128 ).toBe(401);
129 expect(
130 (await api(`/api/notes/${note.id}`, { method: "DELETE" }, bob)).status,
131 ).toBe(403);
132 expect(
133 (await api(`/api/notes/${note.id}`, { method: "DELETE" }, alice)).status,
134 ).toBe(200);
135 expect(
136 (await api(`/api/notes/${note.id}`, { method: "DELETE" }, alice)).status,
137 ).toBe(404);
138 expect(
139 (
140 await api(
141 "/api/notes",
142 { method: "POST", ...jsonBody({ body: "" }) },
143 alice,
144 )
145 ).status,
146 ).toBe(422);
147 });
148
149 test("the MCP server lists the tools and calls them as the caller", async () => {
150 const hello = await rpc({
151 jsonrpc: "2.0",
152 id: 1,
153 method: "initialize",
154 params: {},
155 });
156 expect(hello.result.capabilities).toEqual({ tools: {} });
157 const listed = await rpc({ jsonrpc: "2.0", id: 2, method: "tools/list" });
158 expect(listed.result.tools.map((t: { name: string }) => t.name)).toEqual([
159 "list_notes",
160 "add_note",
161 "delete_note",
162 ]);
163 const call = (name: string, args: unknown, who = {}) =>
164 rpc(
165 {
166 jsonrpc: "2.0",
167 id: 3,
168 method: "tools/call",
169 params: { name, arguments: args },
170 },
171 who,
172 );
173 const refused = await call("add_note", { body: "as nobody" });
174 expect(refused.result.isError).toBe(true);
175 const added = await call("add_note", { body: "over mcp" }, root);
176 expect(added.result.isError).toBeUndefined();
177 const note = JSON.parse(added.result.content[0].text);
178 expect(note.author_name).toBe("root");
179 const notes = JSON.parse(
180 (await call("list_notes", {})).result.content[0].text,
181 );
182 expect(notes.map((n: { id: number }) => n.id)).toContain(note.id);
183 expect(
184 (await call("delete_note", { id: note.id }, root)).result.isError,
185 ).toBeUndefined();
186 expect(
187 (await rpc({ jsonrpc: "2.0", id: 4, method: "nothing" })).error.code,
188 ).toBe(-32601);
189 const notified = await api("/mcp", {
190 method: "POST",
191 ...jsonBody({ jsonrpc: "2.0", method: "notifications/initialized" }),
192 });
193 expect(notified.status).toBe(202);
194 });
195
196 test("a change is on the event stream, and a late client hears what it missed", async () => {
197 const stream = await fetch(base + "/events");
198 expect(stream.headers.get("content-type")).toBe("text/event-stream");
199 const reader = stream.body!.getReader();
200 const next = async (): Promise<{ id: string; type: string }> => {
201 let buffer = "";
202 for (;;) {
203 const { value } = await reader.read();
204 buffer += new TextDecoder().decode(value);
205 const frame = /id: (\d+)\ndata: (.*)\n\n/.exec(buffer);
206 if (frame) return { id: frame[1]!, type: JSON.parse(frame[2]!).type };
207 }
208 };
209 await api(
210 "/api/notes",
211 { method: "POST", ...jsonBody({ body: "live" }) },
212 alice,
213 );
214 const heard = await next();
215 expect(heard.type).toBe("note.added");
216 await reader.cancel();
217 const late = await fetch(base + "/events", {
218 headers: { "last-event-id": String(Number(heard.id) - 1) },
219 });
220 const replay = new TextDecoder().decode(
221 (await late.body!.getReader().read()).value,
222 );
223 expect(replay).toContain(`id: ${heard.id}\n`);
224 expect(replay).toContain("note.added");
225 });
226
227 test("writes are rationed per person", async () => {
228 const flood = as("u9", "flood");
229 const answers = await Promise.all(
230 Array.from({ length: 40 }, () =>
231 api(
232 "/api/notes",
233 { method: "POST", ...jsonBody({ body: "again" }) },
234 flood,
235 ),
236 ),
237 );
238 const codes = answers.map((r) => r.status);
239 expect(codes).toContain(201);
240 expect(codes).toContain(429);
241 });
242
243 test("stands on the security floor", async () => {
244 const response = await fetch(base + "/");
245 expect(response.headers.get("content-security-policy")).toContain(
246 "default-src 'self'",
247 );
248 expect(response.headers.get("x-content-type-options")).toBe("nosniff");
249 expect(
250 (await fetch(base + "/api/notes")).headers.get("content-security-policy"),
251 ).toContain("default-src");
252 });
253
254 test("a body is capped by the bytes read, whatever it claims", async () => {
255 const response = await api(
256 "/notes",
257 {
258 method: "POST",
259 headers: { "content-type": "application/x-www-form-urlencoded" },
260 body: "body=" + "x".repeat(1024 * 1024),
261 },
262 alice,
263 );
264 expect(response.status).toBe(413);
265 });
266
267 test("HEAD sees the app up", async () => {
268 const response = await fetch(base + "/", { method: "HEAD" });
269 expect(response.status).toBe(200);
270 expect(await response.text()).toBe("");
271 });
272
273 test("refuses a cross-site post", async () => {
274 const form = new FormData();
275 form.set("body", "from another site");
276 const posted = await api(
277 "/notes",
278 {
279 method: "POST",
280 body: form,
281 redirect: "manual",
282 headers: {
283 origin: "https://evil.example",
284 "sec-fetch-site": "cross-site",
285 },
286 },
287 alice,
288 );
289 expect(posted.status).toBe(403);
290 });
291
292 test("static files are cached for a year when linked by content", async () => {
293 const page = await (await fetch(base + "/")).text();
294 const href = /href="(\/static\/app\.css\?v=[0-9a-f]{8})"/.exec(page)?.[1];
295 expect(href).toBeDefined();
296 const css = await fetch(base + href!);
297 expect(css.headers.get("cache-control")).toContain("immutable");
298 expect(
299 (await fetch(base + "/static/app.css")).headers.get("cache-control"),
300 ).toBe("no-cache");
301 expect((await fetch(base + "/static/..%2Fpackage.json")).status).toBe(404);
302 });
303
304 test("/healthz says up, apart from the page", async () => {
305 const response = await fetch(base + "/healthz");
306 expect(response.status).toBe(200);
307 expect(response.headers.get("cache-control")).toBe("no-store");
308 const health = (await response.json()) as Record<string, unknown>;
309 expect(health.ok).toBe(true);
310 expect(health.version).toMatch(/^\d+\.\d+\.\d+/);
311 expect(Number.isInteger(health.uptime)).toBe(true);
312 expect((await fetch(base + "/healthz", { method: "HEAD" })).status).toBe(200);
313 });
314
315 test("a link to the page unfurls: description, Open Graph, a card", async () => {
316 const page = await (await fetch(base + "/")).text();
317 for (const meta of [
318 'name="description"',
319 'property="og:title"',
320 'property="og:description"',
321 'property="og:url"',
322 'property="og:type" content="website"',
323 'name="twitter:card" content="summary_large_image"',
324 'name="theme-color"',
325 ])
326 expect([meta, page.includes(meta)]).toEqual([meta, true]);
327 });
328
329 test("the look is the tokens: /tokens.css is linked by content and cached for a year", async () => {
330 const page = await (await fetch(base + "/")).text();
331 const href = /href="(\/tokens\.css\?v=[0-9a-f]{8})"/.exec(page)?.[1];
332 expect(href).toBeDefined();
333 const css = await fetch(base + href!);
334 expect(css.headers.get("content-type")).toContain("text/css");
335 expect(css.headers.get("cache-control")).toContain("immutable");
336 expect(await css.text()).toContain("--color-bg:");
337 // The tokens come first, so every rule after them can use them.
338 expect(page.indexOf("/tokens.css")).toBeLessThan(
339 page.indexOf("/static/app.css"),
340 );
341 });
342
343 test("a page carries an ETag and answers 304 to a copy already held", async () => {
344 const first = await fetch(base + "/");
345 const etag = first.headers.get("etag");
346 expect(etag).toMatch(/^W\/"/);
347 const again = await fetch(base + "/", { headers: { "if-none-match": etag! } });
348 expect(again.status).toBe(304);
349 expect(again.headers.get("etag")).toBe(etag);
350 expect((await fetch(base + "/", { headers: { "if-none-match": 'W/"x"' } })).status).toBe(200);
351 });
352
353 test("what the web expects: robots.txt, and security.txt from the forge that runs us", async () => {
354 // Production is read by crawlers, the API is not; anything else is a
355 // draft and asks not to be indexed at all.
356 const robots = await (await fetch(base + "/robots.txt")).text();
357 const noindex = (await fetch(base + "/")).headers.get("x-robots-tag");
358 if (env === "production") {
359 expect(robots).toContain("Disallow: /api/\n");
360 expect(noindex).toBeNull();
361 } else {
362 expect(robots).toContain("User-agent: *\nDisallow: /\n");
363 expect(noindex).toBe("noindex");
364 }
365 const security = await fetch(base + "/.well-known/security.txt");
366 expect(security.status).toBe(200);
367 const body = await security.text();
368 expect(body).toContain(`Contact: ${process.env.FORGE_URL ?? publicOrigin}/`);
369 const expires = /^Expires: (\S+)$/m.exec(body)?.[1] ?? "";
370 expect(Date.parse(expires)).toBeGreaterThan(Date.now());
371 const password = await fetch(base + "/.well-known/change-password", {
372 redirect: "manual",
373 });
374 expect(password.status).toBe(302);
375 expect(password.headers.get("location")).toBe(process.env.FORGE_URL ?? "/");
376 });
template/src/server.ts added +124
@@ -0,0 +1,124 @@
1 /**
2 * The process the forge runs. `serve` opens the database and listens:
3 * every request gets the floor (`http.ts`), an identity (`who.ts`), the
4 * door (`security.ts`) and one route (`routes.ts`) — so a request from
5 * another site, from someone going too fast, or from someone the contract
6 * turns away is refused before a byte of it is read. Run directly, it
7 * serves what the forge said; a test calls `serve` with its own.
8 */
9
10 import { openDb } from "./db.ts";
11 import {
12 dataDir,
13 forgeUrl,
14 identityKey,
15 publicOrigin,
16 title,
17 where,
18 } from "./env.ts";
19 import { compress } from "./compress.ts";
20 import { html, revalidate, text } from "./http.ts";
21 import { problem } from "./page.ts";
22 import { match } from "./routes.ts";
23 import { door } from "./security.ts";
24 import { ensureClient, sessionWho, type Signin } from "./signin.ts";
25 import { ANON, who } from "./who.ts";
26
27 export interface ServeOptions {
28 readonly port: number;
29 readonly hostname?: string | undefined;
30 readonly dataDir: string;
31 readonly identityKey: string;
32 /** Where people sign in; undefined turns sign-in off. */
33 readonly signin?: Signin | undefined;
34 }
35
36 export function serve(options: ServeOptions) {
37 const db = openDb(options.dataDir);
38 // Register with the forge on first boot; a forge that is not up yet is
39 // tried again at the first sign-in.
40 options.signin !== undefined &&
41 ensureClient(options.signin).catch((error) => console.error(error));
42 return Bun.serve({
43 port: options.port,
44 hostname: options.hostname ?? "127.0.0.1",
45 // A connection that says nothing for a minute is dropped. The event
46 // stream heartbeats every 25 seconds to stay well inside that.
47 idleTimeout: 60,
48 async fetch(request, server) {
49 const url = new URL(request.url);
50 // A signed header from the forge says more than a session can (a
51 // session is always a user; the header may say admin), so it wins.
52 const signed = who(request, options.identityKey);
53 const me =
54 signed.role !== "anon" ? signed : (sessionWho(db, request) ?? signed);
55 const refused = door(
56 db,
57 request,
58 url,
59 me,
60 server.requestIP(request)?.address ?? "?",
61 );
62 if (refused !== undefined)
63 return head(request, await compress(request, refused));
64 const found = match(
65 request.method === "HEAD" ? "GET" : request.method,
66 url.pathname,
67 );
68 // A browser is shown the app's own page; a script gets the word.
69 if (found === undefined)
70 return head(
71 request,
72 await compress(
73 request,
74 (request.headers.get("accept") ?? "").includes("text/html")
75 ? html(problem(404, me), 404)
76 : text("not found", 404),
77 ),
78 );
79 const response = await found.route.handle({
80 request,
81 url,
82 db,
83 who: me,
84 params: found.params,
85 signin: options.signin,
86 });
87 return head(request, await compress(request, await revalidate(request, response)));
88 },
89 // A bug answers with the floor and nothing else: never the runtime's
90 // own error page, which carries source and paths, and never without
91 // the headers. The detail goes to the log, where it belongs.
92 error(error) {
93 // Inside the generated app, which has no forge log module.
94 console.error(error);
95 try {
96 return html(problem(500, ANON), 500);
97 } catch {
98 return html("<h1>Something went wrong</h1>", 500);
99 }
100 },
101 });
102 }
103
104 // HEAD is GET without the body: a health check sees the app up.
105 const head = (request: Request, response: Response): Response =>
106 request.method === "HEAD"
107 ? new Response(null, { status: response.status, headers: response.headers })
108 : response;
109
110 if (import.meta.main) {
111 const server = serve({
112 port: Number(process.env.PORT ?? 8080),
113 hostname: process.env.HOST,
114 dataDir,
115 identityKey,
116 signin:
117 forgeUrl === undefined
118 ? undefined
119 : { forge: forgeUrl, origin: publicOrigin, dataDir, name: `${title} (${where})` },
120 });
121 console.log(
122 `${title} listening on http://${server.hostname}:${server.port} (${where})`,
123 );
124 }
template/src/signin.test.ts added +159
@@ -0,0 +1,159 @@
1 import { afterAll, beforeAll, expect, test } from "bun:test";
2 import { mkdtempSync, rmSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { openDb } from "./db.ts";
6 import { begin, finish, sessionWho, verify, type Signin } from "./signin.ts";
7
8 const dir = mkdtempSync(join(tmpdir(), "app-"));
9 const db = openDb(dir);
10 afterAll(() => {
11 db.close();
12 rmSync(dir, { recursive: true, force: true });
13 });
14 const ISS = "https://forge.test";
15 const b64 = (v: unknown): string => Buffer.from(JSON.stringify(v)).toString("base64url");
16 const generate = () =>
17 crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);
18
19 let good: CryptoKeyPair;
20 let other: CryptoKeyPair;
21 let jwk: JsonWebKey;
22 beforeAll(async () => {
23 good = await generate();
24 other = await generate();
25 jwk = await crypto.subtle.exportKey("jwk", good.publicKey);
26 });
27
28 /** An id_token as the forge would sign it, then spoiled one way at a time. */
29 async function mint(
30 claims: Record<string, unknown> = {},
31 opts: { alg?: string; kid?: string; key?: CryptoKey } = {},
32 ): Promise<string> {
33 const head = b64({ alg: opts.alg ?? "ES256", typ: "JWT", kid: opts.kid ?? "k1" });
34 const body = b64({
35 iss: ISS,
36 aud: "c1",
37 nonce: "n1",
38 sub: "u1",
39 preferred_username: "alice",
40 exp: Math.floor(Date.now() / 1000) + 600,
41 ...claims,
42 });
43 const sig = await crypto.subtle.sign(
44 { name: "ECDSA", hash: "SHA-256" },
45 opts.key ?? good.privateKey,
46 new TextEncoder().encode(`${head}.${body}`),
47 );
48 return `${head}.${body}.${Buffer.from(sig).toString("base64url")}`;
49 }
50
51 // A forge that registers a client, publishes one key, and trades any code for `token`.
52 let token = "";
53 const forge = (async (url: string | URL | Request) => {
54 const path = new URL(String(url)).pathname;
55 if (path === "/oauth/register") return Response.json({ client_id: "c1" }, { status: 201 });
56 if (path === "/oauth/jwks") return Response.json({ keys: [{ ...jwk, kid: "k1" }] });
57 if (path === "/oauth/token") return Response.json({ id_token: token });
58 return new Response("no", { status: 404 });
59 }) as unknown as typeof fetch;
60 const signin: Signin = {
61 forge: ISS,
62 origin: "https://app.test",
63 dataDir: dir,
64 name: "app",
65 fetch: forge,
66 };
67
68 test("sign-in goes out with PKCE, state and nonce, to the registered redirect", async () => {
69 const { location, state } = await begin(db, signin);
70 const to = new URL(location);
71 expect(`${to.origin}${to.pathname}`).toBe(`${ISS}/oauth/authorize`);
72 expect(to.searchParams.get("client_id")).toBe("c1");
73 expect(to.searchParams.get("redirect_uri")).toBe("https://app.test/signin/callback");
74 expect(to.searchParams.get("code_challenge_method")).toBe("S256");
75 expect(to.searchParams.get("state")).toBe(state);
76 expect(to.searchParams.get("nonce")?.length).toBeGreaterThan(16);
77 });
78
79 test("verify accepts the forge's token, and refuses each way it can be wrong", async () => {
80 expect(await verify(signin, await mint(), "n1")).toEqual({
81 sub: "u1",
82 preferred_username: "alice",
83 });
84 const past = Math.floor(Date.now() / 1000) - 1;
85 const refused: [string, string][] = [
86 ["alg is not ES256", await mint({}, { alg: "HS256" })],
87 ["alg none", await mint({}, { alg: "none" })],
88 ["signed by another key", await mint({}, { key: other.privateKey })],
89 ["unknown kid", await mint({}, { kid: "zz" })],
90 ["wrong issuer", await mint({ iss: "https://evil.test" })],
91 ["wrong audience", await mint({ aud: "c2" })],
92 ["wrong nonce", await mint({ nonce: "n2" })],
93 ["no nonce", await mint({ nonce: undefined })],
94 ["expired", await mint({ exp: past })],
95 ["no expiry", await mint({ exp: undefined })],
96 ["empty sub", await mint({ sub: "" })],
97 ["no sub", await mint({ sub: undefined })],
98 ["not a jwt", "a.b"],
99 ["garbage", "a.b.c"],
100 ];
101 for (const [why, jwt] of refused)
102 expect([why, await verify(signin, jwt, "n1")]).toEqual([why, undefined]);
103 // A payload swapped under a good signature is not the signed one.
104 const [h, , s] = (await mint()).split(".");
105 const swapped = `${h}.${b64({ iss: ISS, aud: "c1", nonce: "n1", sub: "root", exp: past + 900 })}.${s}`;
106 expect(await verify(signin, swapped, "n1")).toBeUndefined();
107 });
108
109 /** Start a sign-in and come back with an id_token; the request carries the cookie of the browser that began it. */
110 async function comeBack(spoil?: (nonce: string) => Promise<string>, cookie?: (state: string) => string) {
111 const { location, state } = await begin(db, signin);
112 const nonce = new URL(location).searchParams.get("nonce")!;
113 token = spoil === undefined ? await mint({ nonce }) : await spoil(nonce);
114 const url = new URL(`https://app.test/signin/callback?code=x&state=${state}`);
115 const request = new Request(url, {
116 headers: { cookie: cookie === undefined ? `signin=${state}` : cookie(state) },
117 });
118 return { state, url, request };
119 }
120
121 test("a return opens a session once, and the same return again opens nothing", async () => {
122 const { url, request } = await comeBack();
123 const done = await finish(db, signin, request, url);
124 expect(done.ok).toBe(true);
125 if (done.ok)
126 expect(
127 sessionWho(db, new Request("http://x", { headers: { cookie: `session=${done.session}` } })),
128 ).toEqual({ role: "user", id: "u1", name: "alice" });
129 expect((await finish(db, signin, request, url)).ok).toBe(false);
130 });
131
132 test("a return is refused when the browser, the time or the token is not the sign-in's own", async () => {
133 const stranger = await comeBack(undefined, () => "signin=other");
134 expect((await finish(db, signin, stranger.request, stranger.url)).ok).toBe(false);
135 const bare = await comeBack(undefined, () => "");
136 expect((await finish(db, signin, bare.request, bare.url)).ok).toBe(false);
137
138 const late = await comeBack();
139 db.query("UPDATE login SET expires_at = ?1").run(Date.now() - 1);
140 expect((await finish(db, signin, late.request, late.url)).ok).toBe(false);
141
142 const wrongNonce = await comeBack(() => mint({ nonce: "not-this-sign-in" }));
143 expect((await finish(db, signin, wrongNonce.request, wrongNonce.url)).ok).toBe(false);
144
145 const denied = await comeBack();
146 const url = new URL(`https://app.test/signin/callback?error=access_denied&state=${denied.state}`);
147 expect((await finish(db, signin, denied.request, url)).ok).toBe(false);
148 });
149
150 test("a session is a cookie that names a person, and only until it expires", () => {
151 db.query("INSERT INTO session VALUES (?1, 'u2', 'bob', ?2)").run(
152 new Bun.CryptoHasher("sha256").update("abc").digest("hex"),
153 Date.now() + 1000,
154 );
155 const req = (cookie: string) => new Request("http://x", { headers: { cookie } });
156 expect(sessionWho(db, req("session=abc"))).toEqual({ role: "user", id: "u2", name: "bob" });
157 expect(sessionWho(db, req("session=abd"))).toBeUndefined();
158 expect(sessionWho(db, req("session=abc"), Date.now() + 5000)).toBeUndefined();
159 });
template/src/signin.ts added +285
@@ -0,0 +1,285 @@
1 /**
2 * Sign-in through the forge, which is an OpenID provider: the code flow
3 * with PKCE against FORGE_URL. The first time it is needed the app
4 * registers its own redirect address (production and each preview have
5 * their own) and keeps the client id in FORGE_APP_DATA. A person is sent
6 * to the forge, comes back with a one-time code, and the app trades it for
7 * an id_token whose signature, issuer, audience, expiry and nonce it
8 * checks itself against the forge's published keys. What it keeps is a
9 * session: a random id in an HttpOnly cookie, the hash of it in the
10 * database. Plain data in, plain data out; `fetch` is a parameter so a
11 * test can be anywhere.
12 */
13
14 import type { Database } from "bun:sqlite";
15 import { createHash, randomBytes } from "node:crypto";
16 import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
17 import { join } from "node:path";
18 import type { Who } from "./who.ts";
19
20 export interface Signin {
21 /** The forge's address, as the app was told it (FORGE_URL). */
22 readonly forge: string;
23 /** This app's own public origin (FORGE_APP_URL). */
24 readonly origin: string;
25 readonly dataDir: string;
26 /** What the forge is told this client is called. */
27 readonly name: string;
28 readonly fetch?: typeof fetch;
29 }
30
31 export const SESSION_COOKIE = "session";
32 export const LOGIN_COOKIE = "signin";
33 const SESSION_S = 12 * 3600;
34 const LOGIN_S = 600;
35 const LOGIN_MAX = 1000;
36 const SCOPE = "openid profile";
37
38 const rand = (bytes: number): string => randomBytes(bytes).toString("base64url");
39 const hash = (s: string): string => createHash("sha256").update(s).digest("hex");
40 const fetcher = (s: Signin): typeof fetch => s.fetch ?? fetch;
41 const issuer = (s: Signin): string => new URL(s.forge).origin;
42 export const redirectUri = (s: Signin): string => `${s.origin}/signin/callback`;
43
44 /** The cookie a request carries by that name, if any. */
45 export function cookieOf(request: Request, name: string): string | undefined {
46 const found = new RegExp(`(?:^|;\\s*)${name}=([^;]*)`).exec(
47 request.headers.get("cookie") ?? "",
48 );
49 return found?.[1];
50 }
51
52 // The client id, per redirect address, in one small file. Registering again
53 // for an address already known would make a second client; this makes one.
54 const registered = new Map<string, Promise<string>>();
55
56 export function ensureClient(s: Signin): Promise<string> {
57 const uri = redirectUri(s);
58 const key = `${s.dataDir}\0${uri}`;
59 const pending = registered.get(key);
60 if (pending !== undefined) return pending;
61 const attempt = register(s, uri);
62 registered.set(key, attempt);
63 // A failed attempt is forgotten, so the next sign-in tries again.
64 attempt.catch(() => registered.delete(key));
65 return attempt;
66 }
67
68 async function register(s: Signin, uri: string): Promise<string> {
69 const file = join(s.dataDir, "oidc-client.json");
70 let known: Record<string, string> = {};
71 try {
72 known = JSON.parse(readFileSync(file, "utf8")) as Record<string, string>;
73 } catch {
74 // First boot: nothing registered yet.
75 }
76 const had = known[uri];
77 if (typeof had === "string" && had !== "") return had;
78 const res = await fetcher(s)(`${issuer(s)}/oauth/register`, {
79 method: "POST",
80 headers: { "content-type": "application/json" },
81 body: JSON.stringify({ client_name: s.name, redirect_uris: [uri] }),
82 redirect: "error",
83 signal: AbortSignal.timeout(5000),
84 });
85 const body = (await res.json()) as { client_id?: unknown };
86 if (res.status !== 201 || typeof body.client_id !== "string")
87 throw new Error(`the forge refused to register ${uri} (${res.status})`);
88 mkdirSync(s.dataDir, { recursive: true });
89 const next = `${file}.${process.pid}`;
90 writeFileSync(next, JSON.stringify({ ...known, [uri]: body.client_id }));
91 renameSync(next, file);
92 return body.client_id;
93 }
94
95 /** Start: the address at the forge to send the person to, and the cookie that binds this browser to it. */
96 export async function begin(
97 db: Database,
98 s: Signin,
99 now = Date.now(),
100 ): Promise<{ location: string; state: string }> {
101 const clientId = await ensureClient(s);
102 const state = rand(24);
103 const verifier = rand(48);
104 const nonce = rand(24);
105 db.query("DELETE FROM login WHERE expires_at <= ?1").run(now);
106 db.query(
107 "DELETE FROM login WHERE state IN (SELECT state FROM login ORDER BY expires_at LIMIT max(0, (SELECT count(*) FROM login) - ?1))",
108 ).run(LOGIN_MAX - 1);
109 db.query(
110 "INSERT INTO login (state, verifier, nonce, expires_at) VALUES (?1, ?2, ?3, ?4)",
111 ).run(hash(state), verifier, nonce, now + LOGIN_S * 1000);
112 const query = new URLSearchParams({
113 response_type: "code",
114 client_id: clientId,
115 redirect_uri: redirectUri(s),
116 scope: SCOPE,
117 state,
118 nonce,
119 code_challenge: createHash("sha256").update(verifier).digest("base64url"),
120 code_challenge_method: "S256",
121 });
122 return { location: `${issuer(s)}/oauth/authorize?${query}`, state };
123 }
124
125 export type Finished =
126 | { ok: true; session: string; who: Who }
127 | { ok: false; message: string };
128
129 const refuse = (message: string): Finished => ({ ok: false, message });
130
131 /** The return: check the state twice, trade the code, verify the id_token, open a session. */
132 export async function finish(
133 db: Database,
134 s: Signin,
135 request: Request,
136 url: URL,
137 now = Date.now(),
138 ): Promise<Finished> {
139 if (url.searchParams.has("error"))
140 return refuse("The forge did not sign you in.");
141 const state = url.searchParams.get("state") ?? "";
142 const code = url.searchParams.get("code") ?? "";
143 if (state === "" || code === "" || state !== cookieOf(request, LOGIN_COOKIE))
144 return refuse("This sign-in did not start in this browser.");
145 const row = db
146 .query<{ verifier: string; nonce: string; expires_at: number }, [string]>(
147 "DELETE FROM login WHERE state = ?1 RETURNING verifier, nonce, expires_at",
148 )
149 .get(hash(state));
150 if (row === null || row.expires_at <= now)
151 return refuse("This sign-in took too long or was already used.");
152 try {
153 const res = await fetcher(s)(`${issuer(s)}/oauth/token`, {
154 method: "POST",
155 body: new URLSearchParams({
156 grant_type: "authorization_code",
157 code,
158 client_id: await ensureClient(s),
159 redirect_uri: redirectUri(s),
160 code_verifier: row.verifier,
161 }),
162 redirect: "error",
163 signal: AbortSignal.timeout(5000),
164 });
165 const body = (await res.json()) as { id_token?: unknown };
166 if (!res.ok || typeof body.id_token !== "string")
167 return refuse("The forge did not accept the sign-in.");
168 const claims = await verify(s, body.id_token, row.nonce, now);
169 if (claims === undefined) return refuse("The forge's answer did not verify.");
170 const who: Who = {
171 role: "user",
172 id: claims.sub,
173 name: claims.preferred_username ?? claims.sub,
174 };
175 const session = rand(32);
176 db.query(
177 "INSERT INTO session (hash, user_id, user_name, expires_at) VALUES (?1, ?2, ?3, ?4)",
178 ).run(hash(session), who.id, who.name, now + SESSION_S * 1000);
179 db.query("DELETE FROM session WHERE expires_at <= ?1").run(now);
180 return { ok: true, session, who };
181 } catch {
182 return refuse("The forge could not be reached.");
183 }
184 }
185
186 interface Claims {
187 readonly sub: string;
188 readonly preferred_username?: string;
189 }
190
191 type Key = Record<string, unknown>;
192 const keys = new Map<string, { at: number; list: Key[] }>();
193
194 async function jwks(s: Signin, kid: unknown, now: number): Promise<Key | undefined> {
195 const cached = keys.get(issuer(s));
196 const fresh = cached !== undefined && now - cached.at < 600_000;
197 const hit = fresh ? cached.list.find((k) => k["kid"] === kid) : undefined;
198 if (hit !== undefined) return hit;
199 // An unknown kid may be a rotation; look again, but not more than once a minute.
200 if (cached !== undefined && now - cached.at < 60_000) return undefined;
201 const res = await fetcher(s)(`${issuer(s)}/oauth/jwks`, {
202 redirect: "error",
203 signal: AbortSignal.timeout(5000),
204 });
205 const list = ((await res.json()) as { keys?: Key[] }).keys ?? [];
206 keys.set(issuer(s), { at: now, list });
207 return list.find((k) => k["kid"] === kid);
208 }
209
210 /** The claims of an id_token that is the forge's, for this app, for this sign-in and not yet expired. */
211 export async function verify(
212 s: Signin,
213 jwt: string,
214 nonce: string,
215 now = Date.now(),
216 ): Promise<Claims | undefined> {
217 const parts = jwt.split(".");
218 if (parts.length !== 3) return undefined;
219 try {
220 const head = JSON.parse(Buffer.from(parts[0]!, "base64url").toString());
221 if (head.alg !== "ES256") return undefined;
222 const jwk = await jwks(s, head.kid, now);
223 if (jwk === undefined) return undefined;
224 const pub = await crypto.subtle.importKey(
225 "jwk",
226 jwk as JsonWebKey,
227 { name: "ECDSA", namedCurve: "P-256" },
228 false,
229 ["verify"],
230 );
231 const good = await crypto.subtle.verify(
232 { name: "ECDSA", hash: "SHA-256" },
233 pub,
234 Buffer.from(parts[2]!, "base64url"),
235 new TextEncoder().encode(`${parts[0]}.${parts[1]}`),
236 );
237 if (!good) return undefined;
238 const claims = JSON.parse(Buffer.from(parts[1]!, "base64url").toString());
239 if (
240 claims.iss !== issuer(s) ||
241 claims.aud !== (await ensureClient(s)) ||
242 claims.nonce !== nonce ||
243 typeof claims.exp !== "number" ||
244 claims.exp * 1000 <= now ||
245 typeof claims.sub !== "string" ||
246 claims.sub === ""
247 )
248 return undefined;
249 return {
250 sub: claims.sub,
251 ...(typeof claims.preferred_username === "string" &&
252 claims.preferred_username !== ""
253 ? { preferred_username: claims.preferred_username }
254 : {}),
255 };
256 } catch {
257 return undefined;
258 }
259 }
260
261 /** The person a session cookie names, or undefined. */
262 export function sessionWho(
263 db: Database,
264 request: Request,
265 now = Date.now(),
266 ): Who | undefined {
267 const id = cookieOf(request, SESSION_COOKIE);
268 if (id === undefined || id === "") return undefined;
269 const row = db
270 .query<{ user_id: string; user_name: string }, [string, number]>(
271 "SELECT user_id, user_name FROM session WHERE hash = ?1 AND expires_at > ?2",
272 )
273 .get(hash(id), now);
274 return row === null
275 ? undefined
276 : { role: "user", id: row.user_id, name: row.user_name };
277 }
278
279 export function endSession(db: Database, request: Request): void {
280 const id = cookieOf(request, SESSION_COOKIE);
281 if (id !== undefined) db.query("DELETE FROM session WHERE hash = ?1").run(hash(id));
282 }
283
284 export const SESSION_MAX_AGE = SESSION_S;
285 export const LOGIN_MAX_AGE = LOGIN_S;
template/src/site.test.ts added +191
@@ -0,0 +1,191 @@
1 /**
2 * The specification a site is held to, as the template keeps it: the head
3 * a crawler and a chat app read, the files they ask for, the pages that
4 * are not the page, and the shape of the headings. A generated app
5 * inherits every one of these and fails its own `bun test` if it loses one.
6 */
7 import { afterAll, expect, test } from "bun:test";
8 import { mkdtempSync, readFileSync, rmSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { compress, MIN_BYTES } from "./compress.ts";
12 import { env, publicOrigin, title } from "./env.ts";
13 import { SECURITY } from "./http.ts";
14 import { problem } from "./page.ts";
15 import { CARD, websiteLd } from "./site.ts";
16 import { serve } from "./server.ts";
17 import { ANON } from "./who.ts";
18
19 const dataDir = mkdtempSync(join(tmpdir(), "app-"));
20 const server = serve({
21 port: 0,
22 dataDir,
23 identityKey: "a-key-only-the-forge-holds",
24 });
25 const base = `http://${server.hostname}:${server.port}`;
26 afterAll(() => {
27 server.stop(true);
28 rmSync(dataDir, { recursive: true, force: true });
29 });
30 const get = (path: string, headers: Record<string, string> = {}) =>
31 fetch(base + path, { headers, redirect: "manual" });
32
33 /** The heading levels in a page, in order. */
34 const levels = (page: string): number[] =>
35 [...page.matchAll(/<h([1-6])[\s>]/g)].map((m) => Number(m[1]));
36
37 /** One h1, and no level skipped on the way down: what a screen reader's outline needs. */
38 const outlineProblems = (page: string): string[] => {
39 const all = levels(page);
40 const problems: string[] = [];
41 if (all.filter((n) => n === 1).length !== 1)
42 problems.push("a page has exactly one h1");
43 all.forEach((n, i) => {
44 if (n > (all[i - 1] ?? 0) + 1) problems.push(`h${n} follows h${all[i - 1] ?? 0}`);
45 });
46 return problems;
47 };
48
49 test("the head says where the page lives, what it looks like and what it is", async () => {
50 const page = await (await get("/")).text();
51 expect(page).toContain(`<link rel="canonical" href="${publicOrigin}/">`);
52 expect(page).toContain('<link rel="icon" href="/icon.svg" type="image/svg+xml">');
53 expect(page).toContain('<link rel="apple-touch-icon" href="/apple-touch-icon.png">');
54 expect(page).toContain('<link rel="manifest" href="/manifest.webmanifest">');
55 expect(page).not.toContain('href="data:,"');
56 expect(page).toContain(`<meta property="og:image" content="${publicOrigin}/og.png">`);
57 expect(page).toContain(`<meta property="og:image:width" content="${CARD.width}">`);
58 expect(page).toContain('<meta name="twitter:card" content="summary_large_image">');
59 const ld = /<script type="application\/ld\+json">(.*?)<\/script>/s.exec(page)?.[1];
60 expect(JSON.parse(ld ?? "null")).toMatchObject({
61 "@type": "WebSite",
62 name: title,
63 url: `${publicOrigin}/`,
64 });
65 });
66
67 test("structured data cannot close its own tag", () => {
68 const out = websiteLd("</script><b>", "a & b", "https://x.test");
69 expect(out).not.toContain("<");
70 expect(JSON.parse(out).name).toBe("</script><b>");
71 });
72
73 test("the first stop for a keyboard skips to the main landmark", async () => {
74 const page = await (await get("/")).text();
75 expect(page.indexOf('<a class="skip" href="#main">')).toBeLessThan(page.indexOf("<header"));
76 expect(page).toContain('<main id="main" tabindex="-1">');
77 const css = readFileSync(join(import.meta.dir, "..", "static", "app.css"), "utf8");
78 expect(css).toContain("@media (forced-colors: active)");
79 });
80
81 test("the icon, the home-screen icon, the manifest and the card are real files", async () => {
82 const svg = await get("/icon.svg");
83 expect(svg.headers.get("content-type")).toBe("image/svg+xml");
84 expect(await svg.text()).toStartWith("<svg ");
85 const size = async (path: string) => {
86 const r = await get(path);
87 expect(r.status).toBe(200);
88 expect(r.headers.get("content-type")).toBe("image/png");
89 expect(r.headers.get("x-content-type-options")).toBe("nosniff");
90 const b = new Uint8Array(await r.arrayBuffer());
91 expect([...b.slice(0, 8)]).toEqual([137, 80, 78, 71, 13, 10, 26, 10]);
92 const view = new DataView(b.buffer);
93 return [view.getUint32(16), view.getUint32(20)];
94 };
95 expect(await size("/apple-touch-icon.png")).toEqual([180, 180]);
96 expect(await size("/og.png")).toEqual([CARD.width, CARD.height]);
97 const m = await (await get("/manifest.webmanifest")).json();
98 expect(m).toMatchObject({ name: title, start_url: "/" });
99 expect(m.icons.map((i: { src: string }) => i.src)).toContain("/apple-touch-icon.png");
100 });
101
102 test("sitemap.xml lists the page, robots.txt points at it where crawlers are welcome, llms.txt introduces the site", async () => {
103 const sitemap = await (await get("/sitemap.xml")).text();
104 expect(sitemap).toContain(`<loc>${publicOrigin}/</loc>`);
105 expect((await get("/sitemap.xml")).headers.get("content-type")).toContain("xml");
106 const robots = await (await get("/robots.txt")).text();
107 if (env === "production") expect(robots).toContain(`Sitemap: ${publicOrigin}/sitemap.xml\n`);
108 else expect(robots).toBe(`User-agent: *\nDisallow: /\n\nSitemap: ${publicOrigin}/sitemap.xml\n`);
109 const llms = await get("/llms.txt");
110 expect(llms.headers.get("content-type")).toContain("text/plain");
111 const body = await llms.text();
112 expect(body).toStartWith(`# ${title}\n\n> `);
113 expect(body).toContain(`(${publicOrigin}/openapi.json)`);
114 });
115
116 test("HSTS covers subdomains and is never a preload promise", () => {
117 const hsts = SECURITY["strict-transport-security"];
118 if (publicOrigin.startsWith("https:")) {
119 expect(hsts).toContain("includeSubDomains");
120 expect(hsts).not.toContain("preload");
121 } else expect(hsts).toBeUndefined();
122 });
123
124 test("a missing page is the app's own page with a 404, and a script gets the word", async () => {
125 const browser = await get("/no/such/page", { accept: "text/html,*/*" });
126 expect(browser.status).toBe(404);
127 expect(browser.headers.get("content-type")).toContain("text/html");
128 expect(browser.headers.get("content-security-policy")).not.toBeNull();
129 const page = await browser.text();
130 expect(page).toContain("<h1>Not found</h1>");
131 expect(page).toContain('<meta name="robots" content="noindex">');
132 expect(page).not.toContain('rel="canonical"');
133 expect(outlineProblems(page)).toEqual([]);
134 const script = await get("/no/such/page", { accept: "application/json" });
135 expect(script.status).toBe(404);
136 expect(await script.text()).toBe("not found");
137 });
138
139 test("a failure is the same frame with nothing of the cause in it", () => {
140 const page = problem(500, ANON);
141 expect(page).toContain("<h1>Something went wrong</h1>");
142 expect(page).toContain('<meta name="robots" content="noindex">');
143 expect(outlineProblems(page)).toEqual([]);
144 });
145
146 test("the home page has one h1 and no skipped level", async () => {
147 expect(outlineProblems(await (await get("/")).text())).toEqual([]);
148 expect(outlineProblems("<h1>a</h1><h3>b</h3>")).toEqual(["h3 follows h1"]);
149 expect(outlineProblems("<h2>a</h2>")).toContain("a page has exactly one h1");
150 });
151
152 test("text over a kilobyte is gzipped for a browser that reads gzip, and nothing else is touched", async () => {
153 const big = "x".repeat(MIN_BYTES * 2);
154 const ask = (encoding?: string) =>
155 new Request("http://x.test/", encoding ? { headers: { "accept-encoding": encoding } } : {});
156 const html = () => new Response(big, { headers: { "content-type": "text/html" } });
157 const squeezed = await compress(ask("gzip, br"), html());
158 expect(squeezed.headers.get("content-encoding")).toBe("gzip");
159 expect(squeezed.headers.get("vary")).toContain("accept-encoding");
160 expect(Bun.gunzipSync(new Uint8Array(await squeezed.arrayBuffer()))).toEqual(new TextEncoder().encode(big));
161 // Not asked for, too small, a stream, or an image: as they were.
162 expect((await compress(ask(), html())).headers.get("content-encoding")).toBeNull();
163 const small = new Response("tiny", { headers: { "content-type": "text/html" } });
164 expect(await (await compress(ask("gzip"), small)).text()).toBe("tiny");
165 const stream = new Response(big, { headers: { "content-type": "text/event-stream" } });
166 expect((await compress(ask("gzip"), stream)).headers.get("content-encoding")).toBeNull();
167 const png = new Response(big, { headers: { "content-type": "image/png" } });
168 expect((await compress(ask("gzip"), png)).headers.get("content-encoding")).toBeNull();
169 });
170
171 // decompress: false keeps fetch from decoding the body behind the test's back.
172 const raw = (path: string, headers: Record<string, string>) =>
173 fetch(base + path, { headers, redirect: "manual", decompress: false } as RequestInit);
174
175 test("the server gzips a large asset for a browser that reads gzip, and not for one that does not", async () => {
176 const zipped = await raw("/static/app.css", { "accept-encoding": "gzip" });
177 expect(zipped.headers.get("content-encoding")).toBe("gzip");
178 expect(zipped.headers.get("vary")).toContain("accept-encoding");
179 const bytes = new Uint8Array(await zipped.arrayBuffer());
180 expect(new TextDecoder().decode(Bun.gunzipSync(bytes))).toContain(".button");
181 const plain = await raw("/static/app.css", { "accept-encoding": "identity" });
182 expect(plain.headers.get("content-encoding")).toBeNull();
183 expect(await plain.text()).toContain(".button");
184 });
185
186 test("the event stream is never compressed", async () => {
187 const r = await raw("/events", { "accept-encoding": "gzip" });
188 expect(r.headers.get("content-type")).toContain("text/event-stream");
189 expect(r.headers.get("content-encoding")).toBeNull();
190 await r.body?.cancel();
191 });
template/src/site.ts added +157
@@ -0,0 +1,157 @@
1 /**
2 * What the web expects of a site beyond its pages, each drawn from the
3 * app's name and its tokens so nothing here is edited by hand: the icon,
4 * the home-screen icon and install manifest, the card a shared link
5 * unfurls, the sitemap, `/llms.txt` for agents that read, and the
6 * structured data a search engine reads from the page. Plain data in,
7 * a string or bytes out; `routes.ts` serves them.
8 *
9 * The cards are PNGs written here with `node:zlib`, since a link
10 * unfurler will not draw an SVG and a dependency to draw text is more
11 * than a starting point needs. They carry the app's colours and a mark,
12 * not its name; put a designed `og.png` in `static/` and point
13 * `og:image` at it when there is one.
14 */
15
16 import { deflateSync } from "node:zlib";
17 import { description, forgeUrl, publicOrigin, title } from "./env.ts";
18 import { token } from "./tokens.ts";
19
20 /** The size a link card is drawn at, and what `og:image:width`/`height` say. */
21 export const CARD = { width: 1200, height: 630 } as const;
22
23 type Channels = readonly [number, number, number];
24
25 /** `#rrggbb` (the tokens' only colour form) as three bytes. */
26 function channels(hex: string): Channels {
27 const m = /^#([0-9a-f]{6})$/i.exec(hex);
28 if (m === null) throw new Error(`${hex}: the site files need a #rrggbb token`);
29 const n = parseInt(m[1]!, 16);
30 return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
31 }
32
33 /** The mark: the app's first letter, in the accent. */
34 const letter = (): string => [...title][0]?.toUpperCase() ?? "A";
35
36 export const iconSvg = (): string =>
37 `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="${token("color-accent")}"/><text x="32" y="45" text-anchor="middle" font-family="system-ui, sans-serif" font-size="38" font-weight="700" fill="${token("color-accent-fg")}">${xml(letter())}</text></svg>\n`;
38
39 export const manifest = (): string =>
40 JSON.stringify({
41 name: title,
42 short_name: title.slice(0, 12),
43 description,
44 start_url: "/",
45 display: "standalone",
46 background_color: token("color-bg"),
47 theme_color: token("color-bg"),
48 icons: [
49 { src: "/icon.svg", sizes: "any", type: "image/svg+xml" },
50 { src: "/apple-touch-icon.png", sizes: "180x180", type: "image/png" },
51 ],
52 });
53
54 export const sitemap = (): string =>
55 `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n <url><loc>${xml(publicOrigin)}/</loc></url>\n</urlset>\n`;
56
57 /**
58 * Where to report a vulnerability: the forge that runs the app, or this
59 * site when there is none. Expires a year out, so it is never stale.
60 */
61 export const securityTxt = (): string =>
62 `Contact: ${forgeUrl ?? publicOrigin}/\nExpires: ${new Date(Date.now() + 365 * 864e5).toISOString()}\nPreferred-Languages: en\nCanonical: ${publicOrigin}/.well-known/security.txt\n`;
63
64 /** `/llms.txt`: what the site is and where its machine-readable parts are, in the format llmstxt.org describes. */
65 export const llmsTxt = (): string =>
66 `# ${oneLine(title)}\n\n> ${oneLine(description)}\n\n## Pages\n\n- [Home](${publicOrigin}/): the notes, and who may add them\n\n## For programs\n\n- [API description](${publicOrigin}/openapi.json): every endpoint, as OpenAPI\n- [MCP endpoint](${publicOrigin}/mcp): the same actions as tools, POST JSON-RPC\n- [Health](${publicOrigin}/healthz): whether the app is up\n`;
67
68 /** The page as a `WebSite`, for a `<script type="application/ld+json">`. A `<` cannot close the tag: it is written \\u003c. */
69 export const websiteLd = (name: string, about: string, origin: string): string =>
70 JSON.stringify({
71 "@context": "https://schema.org",
72 "@type": "WebSite",
73 name,
74 description: about,
75 url: `${origin}/`,
76 }).replace(/</g, "\\u003c");
77
78 /** The 180px icon iOS puts on a home screen. */
79 export const appleTouch = (): Uint8Array => cached("apple", () => draw(180, 180, "icon"));
80
81 /** The card a shared link unfurls. */
82 export const card = (): Uint8Array => cached("card", () => draw(CARD.width, CARD.height, "card"));
83
84 const made = new Map<string, Uint8Array>();
85 function cached(key: string, make: () => Uint8Array): Uint8Array {
86 let bytes = made.get(key);
87 if (bytes === undefined) made.set(key, (bytes = make()));
88 return bytes;
89 }
90
91 const xml = (s: string): string =>
92 s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
93 const oneLine = (s: string): string => s.replace(/\s+/g, " ").trim();
94
95 /** A flat PNG: the accent, with the accent's foreground as a mark at the middle (a square frame with a block inside). */
96 function draw(w: number, h: number, kind: "icon" | "card"): Uint8Array {
97 const bg = channels(token("color-accent"));
98 const fg = channels(token("color-accent-fg"));
99 const side = Math.round(Math.min(w, h) * (kind === "icon" ? 0.5 : 0.4));
100 const x0 = Math.round((w - side) / 2);
101 const y0 = Math.round((h - side) / 2);
102 const edge = Math.max(2, Math.round(side / 10));
103 const row = 1 + w * 3;
104 const raw = new Uint8Array(row * h);
105 for (let y = 0; y < h; y++) {
106 for (let x = 0; x < w; x++) {
107 const inside = x >= x0 && x < x0 + side && y >= y0 && y < y0 + side;
108 const ring =
109 inside &&
110 (x < x0 + edge || x >= x0 + side - edge || y < y0 + edge || y >= y0 + side - edge);
111 const block =
112 inside && x >= x0 + 3 * edge && x < x0 + side - 3 * edge && y >= y0 + 3 * edge && y < y0 + side - 3 * edge;
113 const c = ring || block ? fg : bg;
114 raw.set(c, y * row + 1 + x * 3);
115 }
116 }
117 const header = new Uint8Array(13);
118 const view = new DataView(header.buffer);
119 view.setUint32(0, w);
120 view.setUint32(4, h);
121 header.set([8, 2, 0, 0, 0], 8); // 8-bit, truecolour, no interlace
122 return join([
123 Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10),
124 chunk("IHDR", header),
125 chunk("IDAT", deflateSync(raw)),
126 chunk("IEND", new Uint8Array(0)),
127 ]);
128 }
129
130 const TABLE = Array.from({ length: 256 }, (_, n) => {
131 let c = n;
132 for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
133 return c >>> 0;
134 });
135 function crc(bytes: Uint8Array): number {
136 let c = 0xffffffff;
137 for (const b of bytes) c = TABLE[(c ^ b) & 255]! ^ (c >>> 8);
138 return (c ^ 0xffffffff) >>> 0;
139 }
140 function chunk(type: string, data: Uint8Array): Uint8Array {
141 const body = join([new TextEncoder().encode(type), data]);
142 const out = new Uint8Array(8 + data.length + 4);
143 const view = new DataView(out.buffer);
144 view.setUint32(0, data.length);
145 out.set(body, 4);
146 view.setUint32(8 + data.length, crc(body));
147 return out;
148 }
149 function join(parts: Uint8Array[]): Uint8Array {
150 const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
151 let at = 0;
152 for (const p of parts) {
153 out.set(p, at);
154 at += p.length;
155 }
156 return out;
157 }
template/src/tokens.ts added +109
@@ -0,0 +1,109 @@
1 /**
2 * The look, compiled. `design/tokens.json` is the app's design tokens in the
3 * W3C format — groups, `$value`, a `$type` a group hands down — and this
4 * turns them into custom properties once, at boot: `color.bg` becomes
5 * `--color-bg`. A colour's `$value` is the light theme and
6 * `$extensions.mode.dark` the dark one; dark follows the system unless
7 * `<html data-theme="light|dark">` decides. The page links the result as
8 * `/tokens.css`, and every other stylesheet speaks only in `var(--…)`.
9 *
10 * Tokens that do not read are not a warning. The app does not start.
11 */
12
13 import { createHash } from "node:crypto";
14 import { readFileSync } from "node:fs";
15
16 export interface Token {
17 /** The custom property: `--color-bg`. */
18 readonly name: string;
19 readonly type: string;
20 readonly light: string;
21 readonly dark?: string;
22 }
23
24 const isGroup = (v: unknown): v is Record<string, unknown> =>
25 typeof v === "object" && v !== null && !Array.isArray(v);
26
27 /** Every token in the tree, in order, with its type and both themes' values. */
28 export function flatten(
29 tree: unknown,
30 path: string[] = [],
31 type = "",
32 ): Token[] {
33 if (!isGroup(tree))
34 throw new Error(`${path.join(".") || "tokens"}: not a group`);
35 const here = typeof tree.$type === "string" ? tree.$type : type;
36 if ("$value" in tree) {
37 const name = `--${path.join("-")}`;
38 if (!/^--[a-z0-9-]+$/.test(name))
39 throw new Error(`${path.join(".")}: not a name CSS can carry`);
40 if (here === "") throw new Error(`${path.join(".")}: no $type`);
41 const dark =
42 isGroup(tree.$extensions) && isGroup(tree.$extensions.mode)
43 ? tree.$extensions.mode.dark
44 : undefined;
45 return [
46 {
47 name,
48 type: here,
49 light: css(tree.$value, path),
50 ...(dark === undefined ? {} : { dark: css(dark, path) }),
51 },
52 ];
53 }
54 return Object.entries(tree)
55 .filter(([key]) => !key.startsWith("$"))
56 .flatMap(([key, child]) => flatten(child, [...path, key], here));
57 }
58
59 // A value is a string, a number, or a font stack; nothing in it may close
60 // the declaration it sits in.
61 function css(value: unknown, path: string[]): string {
62 const text = Array.isArray(value)
63 ? value
64 .map((f) =>
65 /^[\w-]+$/.test(String(f)) ? String(f) : JSON.stringify(String(f)),
66 )
67 .join(", ")
68 : typeof value === "string" || typeof value === "number"
69 ? String(value)
70 : "";
71 if (text === "" || /[;{}<]/.test(text))
72 throw new Error(`${path.join(".")}: $value is not a CSS value`);
73 return text;
74 }
75
76 /** The stylesheet: every token on `:root`, the dark ones twice — for the system's choice and for the page's. */
77 export function compile(tokens: readonly Token[]): string {
78 const block = (selector: string, lines: string[]): string =>
79 `${selector} {\n${lines.map((l) => ` ${l}\n`).join("")}}\n`;
80 const light = tokens.map((t) => `${t.name}: ${t.light};`);
81 const dark = tokens.flatMap((t) =>
82 t.dark === undefined ? [] : [`${t.name}: ${t.dark};`],
83 );
84 return [
85 block(":root", ["color-scheme: light dark;", ...light]),
86 block(':root[data-theme="light"]', ["color-scheme: light;"]),
87 `@media (prefers-color-scheme: dark) {\n${block(':root:not([data-theme="light"])', dark)}}\n`,
88 block(':root[data-theme="dark"]', ["color-scheme: dark;", ...dark]),
89 ].join("\n");
90 }
91
92 export const tokens: readonly Token[] = flatten(
93 JSON.parse(
94 readFileSync(new URL("../design/tokens.json", import.meta.url), "utf8"),
95 ),
96 );
97 export const tokensCss: string = compile(tokens);
98 /** `/tokens.css`, addressed by its content, so it can be cached for a year. */
99 export const tokensHref = `/tokens.css?v=${createHash("sha256").update(tokensCss).digest("hex").slice(0, 8)}`;
100
101 /** One token's value, for the few places a colour must be spelled out (the browser's own chrome). */
102 export const token = (
103 name: string,
104 mode: "light" | "dark" = "light",
105 ): string => {
106 const found = tokens.find((t) => t.name === `--${name}`);
107 if (found === undefined) throw new Error(`no token ${name}`);
108 return mode === "dark" ? (found.dark ?? found.light) : found.light;
109 };
template/src/tty.ts added +115
@@ -0,0 +1,115 @@
1 /**
2 * The app in a terminal. The forge runs this on a pty when someone
3 * `ssh`es to the app, over the same data as the page and through the same
4 * actions, as the account at the keyboard. j/k move, a adds, d removes the
5 * note under the cursor, q leaves. Plain ANSI, no dependencies.
6 */
7
8 import {
9 addNote,
10 canDelete,
11 deleteNote,
12 listNotes,
13 type Note,
14 } from "./actions.ts";
15 import { openDb } from "./db.ts";
16 import { ssh, title, where } from "./env.ts";
17 import { whoAtTty } from "./who.ts";
18
19 const db = openDb();
20 const me = whoAtTty();
21 const esc = "\x1b[";
22 const dim = (s: string): string => `${esc}2m${s}${esc}0m`;
23 const bold = (s: string): string => `${esc}1m${s}${esc}0m`;
24 const out = (s: string): void => {
25 process.stdout.write(s);
26 };
27
28 let cursor = 0;
29 let typing: string | undefined;
30 let said = "";
31
32 const notes = (): Note[] => {
33 const listed = listNotes(db, me);
34 return listed.ok ? listed.value : [];
35 };
36
37 function draw(): void {
38 const rows = notes();
39 const lines = [
40 `${bold(title)} ${dim(where)} ${dim(me.role === "anon" ? "guest" : `${me.name}${me.role === "admin" ? " (admin)" : ""}`)}`,
41 ssh === undefined ? "" : dim(`connect: ${ssh}`),
42 "",
43 ];
44 if (rows.length === 0)
45 lines.push(
46 dim(
47 me.role === "anon"
48 ? "No notes yet."
49 : "No notes yet. Press a to add one.",
50 ),
51 );
52 rows.forEach((note, i) => {
53 const body = i === cursor ? bold(note.body) : note.body;
54 lines.push(
55 `${i === cursor ? "▸" : " "} ${body} ${dim(`${note.author_name} · ${note.created_at.slice(0, 16).replace("T", " ")}`)}`,
56 );
57 });
58 lines.push("");
59 if (typing !== undefined) lines.push(`New note: ${typing}${esc}7m ${esc}0m`);
60 else if (said !== "") lines.push(said);
61 else
62 lines.push(
63 dim(
64 me.role === "anon"
65 ? "j/k move · q quit · sign in with a key the forge knows to add"
66 : "j/k move · a add · d delete · q quit",
67 ),
68 );
69 out(`${esc}2J${esc}H${lines.join("\r\n")}`);
70 }
71
72 process.stdin.setRawMode?.(true);
73 process.stdin.resume();
74 process.stdin.setEncoding("utf8");
75 draw();
76 process.stdin.on("data", (key: string) => {
77 said = "";
78 if (typing !== undefined) {
79 if (key === "\r") {
80 const added = addNote(db, me, { body: typing });
81 if (!added.ok) said = added.message;
82 typing = undefined;
83 cursor = 0;
84 } else if (key === "\x1b") typing = undefined;
85 else if (key === "\x7f") typing = typing.slice(0, -1);
86 else if (key >= " ") typing += key;
87 draw();
88 return;
89 }
90 if (key === "q" || key === "\x03") {
91 out(`${esc}2J${esc}H`);
92 process.exit(0);
93 }
94 const rows = notes();
95 if (key === "j" || key === "\x1b[B")
96 cursor = Math.min(cursor + 1, Math.max(0, rows.length - 1));
97 if (key === "k" || key === "\x1b[A") cursor = Math.max(cursor - 1, 0);
98 if (key === "a") {
99 if (me.role === "anon") said = "Sign in to add a note.";
100 else typing = "";
101 }
102 if (key === "d") {
103 const note = rows[cursor];
104 if (note === undefined) said = "Nothing to remove.";
105 else if (!canDelete(me, note))
106 said = "Only the author or an admin can remove a note.";
107 else {
108 const removed = deleteNote(db, me, { id: note.id });
109 if (!removed.ok) said = removed.message;
110 cursor = Math.min(cursor, Math.max(0, rows.length - 2));
111 }
112 }
113 draw();
114 });
115 process.stdout.on("resize", draw);
template/src/who.test.ts added +59
@@ -0,0 +1,59 @@
1 import { expect, test } from "bun:test";
2 import { sign, who, whoAtTty } from "./who.ts";
3
4 const KEY = "a-key-only-the-forge-holds";
5 const later = Date.now() + 60_000;
6 const request = (identity: string, signature: string): Request =>
7 new Request("http://app/", {
8 headers: { "x-forge-identity": identity, "x-forge-signature": signature },
9 });
10
11 test("a signed identity is who it says", () => {
12 const identity = `u1|alice|admin|${later}`;
13 expect(who(request(identity, sign(identity, KEY)), KEY)).toEqual({
14 role: "admin",
15 id: "u1",
16 name: "alice",
17 });
18 });
19
20 test("a forged, tampered, expired or unsigned identity is anonymous", () => {
21 const identity = `u1|alice|admin|${later}`;
22 expect(who(request(identity, sign(identity, "another key")), KEY)).toEqual({
23 role: "anon",
24 });
25 expect(
26 who(request(`u1|alice|admin|${later + 1}`, sign(identity, KEY)), KEY),
27 ).toEqual({ role: "anon" });
28 const expired = `u1|alice|user|${Date.now() - 1}`;
29 expect(who(request(expired, sign(expired, KEY)), KEY)).toEqual({
30 role: "anon",
31 });
32 const odd = `u1|alice|owner|${later}`;
33 expect(who(request(odd, sign(odd, KEY)), KEY)).toEqual({ role: "anon" });
34 expect(who(new Request("http://app/"), KEY)).toEqual({ role: "anon" });
35 // No key configured: nothing verifies, whoever signed it.
36 expect(who(request(identity, sign(identity, KEY)), "")).toEqual({
37 role: "anon",
38 });
39 });
40
41 test("the terminal trusts its environment", () => {
42 expect(whoAtTty({})).toEqual({ role: "anon" });
43 expect(whoAtTty({ FORGE_APP_USER: "alice" })).toEqual({
44 role: "user",
45 id: "alice",
46 name: "alice",
47 });
48 expect(
49 whoAtTty({
50 FORGE_APP_USER: "alice",
51 FORGE_APP_USER_ID: "u1",
52 FORGE_APP_USER_ROLE: "admin",
53 }),
54 ).toEqual({
55 role: "admin",
56 id: "u1",
57 name: "alice",
58 });
59 });
template/src/who.ts added +67
@@ -0,0 +1,67 @@
1 /**
2 * Who is asking. The forge signs every request it proxies to the app:
3 *
4 * x-forge-identity: <userId>|<username>|<role>|<expiresMs>
5 * x-forge-signature: base64url(HMAC-SHA256(FORGE_APP_IDENTITY_KEY, that string))
6 *
7 * `role` is `user` (signed in and allowed to see this app) or `admin`
8 * (allowed to write its repository). The forge strips these two headers
9 * from whatever a client sends, so a signature that verifies is the only
10 * trust there is: no headers, no key, a bad signature or a stamp in the
11 * past all mean `anon`. Nothing here reads a cookie.
12 */
13
14 import { createHmac, timingSafeEqual } from "node:crypto";
15
16 export type Who =
17 | { role: "anon" }
18 | { role: "user" | "admin"; id: string; name: string };
19
20 export const ANON: Who = { role: "anon" };
21
22 export function who(request: Request, key: string, now = Date.now()): Who {
23 const identity = request.headers.get("x-forge-identity");
24 const signature = request.headers.get("x-forge-signature");
25 if (key === "" || identity === null || signature === null) return ANON;
26 if (!same(sign(identity, key), signature)) return ANON;
27 const parts = identity.split("|");
28 if (parts.length !== 4) return ANON;
29 const [id, name, role, expires] = parts as [string, string, string, string];
30 if (role !== "user" && role !== "admin") return ANON;
31 if (
32 id === "" ||
33 name === "" ||
34 !/^\d+$/.test(expires) ||
35 Number(expires) <= now
36 )
37 return ANON;
38 return { role, id, name };
39 }
40
41 /** The signature the forge computes. Exported so a test can be the forge. */
42 export const sign = (identity: string, key: string): string =>
43 createHmac("sha256", key).update(identity).digest("base64url");
44
45 const same = (a: string, b: string): boolean => {
46 const x = Buffer.from(a);
47 const y = Buffer.from(b);
48 return x.length === y.length && timingSafeEqual(x, y);
49 };
50
51 /**
52 * The person at the terminal. A tty session is started by the forge itself,
53 * so its environment is trusted: `FORGE_APP_USER` is the account at the
54 * keyboard (empty for a guest), `FORGE_APP_USER_ID` and `FORGE_APP_USER_ROLE`
55 * say the rest when the forge knows them.
56 */
57 export function whoAtTty(
58 env: Record<string, string | undefined> = process.env,
59 ): Who {
60 const name = env.FORGE_APP_USER ?? "";
61 if (name === "") return ANON;
62 return {
63 role: env.FORGE_APP_USER_ROLE === "admin" ? "admin" : "user",
64 id: env.FORGE_APP_USER_ID ?? name,
65 name,
66 };
67 }
template/static/app.css added +244
@@ -0,0 +1,244 @@
1 /* The look, in the tokens' words. Every value that is a choice — a colour, a
2 space, a radius, a size — is a var(--…) from /tokens.css, which
3 design/tokens.json compiles to at boot; `bun run lint:design` refuses a raw
4 colour here. Light and dark are the tokens' business, not this file's. */
5
6 /* The page. */
7 html {
8 -webkit-text-size-adjust: 100%;
9 text-size-adjust: 100%;
10 }
11 body {
12 margin: 0;
13 background: var(--color-bg);
14 color: var(--color-fg);
15 font: var(--text-base) / var(--leading-body) var(--font-sans);
16 }
17 .page {
18 max-width: 40rem;
19 margin: 0 auto;
20 padding: var(--space-5) var(--space-4) var(--space-6);
21 }
22 .head {
23 display: flex;
24 flex-wrap: wrap;
25 justify-content: space-between;
26 align-items: flex-start;
27 gap: var(--space-3) var(--space-4);
28 margin-bottom: var(--space-5);
29 }
30 h1 {
31 margin: 0;
32 font-size: var(--text-xl);
33 font-weight: 650;
34 letter-spacing: -0.01em;
35 line-height: var(--leading-tight);
36 }
37 p {
38 margin: 0;
39 }
40 a {
41 color: var(--color-accent);
42 text-decoration-thickness: 1px;
43 text-underline-offset: 0.15em;
44 }
45 code,
46 .mono {
47 font-family: var(--font-mono);
48 font-size: var(--text-sm);
49 }
50 :focus-visible {
51 outline: 2px solid var(--color-accent);
52 outline-offset: 2px;
53 }
54 .muted {
55 color: var(--color-muted);
56 }
57 /* The first thing a keyboard reaches: a way past the header, seen only when focused. */
58 .skip {
59 position: absolute;
60 left: var(--space-3);
61 top: var(--space-3);
62 transform: translateY(-300%);
63 padding: var(--space-2) var(--space-3);
64 background: var(--color-accent);
65 color: var(--color-accent-fg);
66 border-radius: var(--radius-md);
67 }
68 .skip:focus {
69 transform: none;
70 }
71 main:focus {
72 outline: none;
73 }
74 .you {
75 color: var(--color-muted);
76 white-space: nowrap;
77 }
78 .signout {
79 display: inline;
80 }
81
82 /* Blocks. */
83 .card {
84 background: var(--color-surface);
85 border: 1px solid var(--color-line);
86 border-radius: var(--radius-md);
87 padding: var(--space-4);
88 margin-bottom: var(--space-5);
89 }
90 .row {
91 display: flex;
92 align-items: center;
93 gap: var(--space-2);
94 }
95 .list {
96 list-style: none;
97 margin: 0;
98 padding: 0;
99 }
100 .note {
101 display: flex;
102 justify-content: space-between;
103 align-items: flex-start;
104 gap: var(--space-3);
105 padding: var(--space-3) 0;
106 border-top: 1px solid var(--color-line);
107 }
108 .note:first-child {
109 border-top: 0;
110 }
111 .note p {
112 overflow-wrap: anywhere;
113 }
114 .note small {
115 font-size: var(--text-sm);
116 }
117 .empty {
118 padding: var(--space-6) var(--space-4);
119 text-align: center;
120 color: var(--color-muted);
121 border: 1px dashed var(--color-line);
122 border-radius: var(--radius-md);
123 }
124 footer {
125 margin-top: var(--space-6);
126 font-size: var(--text-sm);
127 display: grid;
128 gap: var(--space-1);
129 }
130 footer code {
131 overflow-wrap: anywhere;
132 }
133
134 /* Controls: at least 44px on a side, keyboard and mouse alike. */
135 .input {
136 flex: 1;
137 min-width: 0;
138 min-height: var(--size-tap);
139 padding: 0 var(--space-3);
140 font: inherit;
141 font-size: max(16px, var(--text-base));
142 color: inherit;
143 background: var(--color-bg);
144 border: 1px solid var(--color-line);
145 border-radius: var(--radius-md);
146 }
147 .input::placeholder {
148 color: var(--color-muted);
149 }
150 .button {
151 min-height: var(--size-tap);
152 padding: 0 var(--space-4);
153 font: inherit;
154 font-weight: 600;
155 color: var(--color-accent-fg);
156 background: var(--color-accent);
157 border: 1px solid transparent;
158 border-radius: var(--radius-md);
159 cursor: pointer;
160 white-space: nowrap;
161 text-decoration: none;
162 display: inline-flex;
163 align-items: center;
164 }
165 .button:hover {
166 filter: brightness(1.08);
167 }
168 .button-quiet {
169 color: var(--color-muted);
170 background: transparent;
171 padding: 0 var(--space-3);
172 }
173 .button-quiet:hover {
174 color: var(--color-fg);
175 border-color: var(--color-line);
176 filter: none;
177 }
178 .pill {
179 display: inline-block;
180 padding: 0.1rem 0.6rem;
181 font-size: var(--text-sm);
182 font-weight: 600;
183 color: var(--color-muted);
184 border: 1px solid var(--color-line);
185 border-radius: var(--radius-pill);
186 }
187 .pill[data-env="production"] {
188 color: var(--color-accent);
189 border-color: currentColor;
190 }
191
192 /* A word from the last request, shown once, gone in a moment. */
193 .toast {
194 position: fixed;
195 left: 50%;
196 bottom: var(--space-5);
197 transform: translateX(-50%);
198 max-width: calc(100% - 2 * var(--space-4));
199 padding: var(--space-3) var(--space-4);
200 color: var(--color-toast-fg);
201 background: var(--color-toast-bg);
202 border-radius: var(--radius-pill);
203 box-shadow: 0 8px 24px var(--color-shadow);
204 animation: toast 6s forwards;
205 }
206 @keyframes toast {
207 0%,
208 85% {
209 opacity: 1;
210 }
211 100% {
212 opacity: 0;
213 visibility: hidden;
214 }
215 }
216 /* Forced colours replace ours with the person's own; what only a background
217 or a shadow drew gets a border, so it is still there to see. */
218 @media (forced-colors: active) {
219 .card,
220 .input,
221 .button,
222 .pill,
223 .toast,
224 .skip {
225 border: 1px solid CanvasText;
226 }
227 :focus-visible {
228 outline-color: Highlight;
229 }
230 }
231 /* Motion is a courtesy: whoever asked for less gets none. */
232 @media (prefers-reduced-motion: reduce) {
233 *,
234 *::before,
235 *::after {
236 animation-duration: 0.01ms !important;
237 animation-iteration-count: 1 !important;
238 transition-duration: 0.01ms !important;
239 scroll-behavior: auto !important;
240 }
241 .toast {
242 animation: none;
243 }
244 }
template/static/beacon.js added +13
@@ -0,0 +1,13 @@
1 !function(n,d,w){
2 if(n.doNotTrack=="1"||/(^|; )forge_measure=off/.test(d.cookie)||!n.sendBeacon||!w.PerformanceObserver)return;
3 var c=0,i=0,l=0,x=0,u="",a=location.pathname;
4 function o(t,f,e){try{new PerformanceObserver(function(s){s.getEntries().forEach(f)}).observe(Object.assign({type:t,buffered:true},e))}catch(_){}}
5 o("largest-contentful-paint",function(e){l=e.startTime});
6 o("layout-shift",function(e){e.hadRecentInput||(c+=e.value)});
7 o("event",function(e){e.interactionId&&e.duration>i&&(i=e.duration)},{durationThreshold:40});
8 d.addEventListener("click",function(e){var t=e.target,k=t&&t.closest&&t.closest("a[href]");k&&k.hostname&&k.hostname!=location.hostname&&(u=k.hostname)},true);
9 function s(){if(x)return;x=1;var v=performance.getEntriesByType("navigation")[0]||{};
10 n.sendBeacon("/__forge/measure",JSON.stringify({path:a,ttfb:v.responseStart||0,load:v.loadEventEnd||0,lcp:l,inp:i,cls:c,ref:d.referrer.slice(0,300),q:location.search.slice(0,300),out:u}))}
11 d.addEventListener("visibilitychange",function(){d.visibilityState=="hidden"&&s()});
12 w.addEventListener("pagehide",s)
13 }(navigator,document,window)
template/static/live.js added +68
@@ -0,0 +1,68 @@
1 // The page stays current without a reload. /events is a stream of what
2 // changed; each event becomes `live` and `live:<type>` on `document`, and
3 // any element with data-live="<types>" is refetched and swapped when one of
4 // its types arrives — server-rendered, so the page never renders twice.
5 // Without this file the page is the same page, one reload behind.
6
7 let since = "";
8 let tries = 0;
9 let source;
10
11 function connect() {
12 source = new EventSource(since ? `/events?since=${since}` : "/events");
13 source.onopen = () => {
14 if (tries > 0) refresh(); // Reconnected: whatever was missed, catch up.
15 tries = 0;
16 };
17 source.onmessage = (message) => {
18 since = message.lastEventId;
19 const { type, data } = JSON.parse(message.data);
20 document.dispatchEvent(new CustomEvent("live", { detail: { type, data } }));
21 document.dispatchEvent(new CustomEvent(`live:${type}`, { detail: data }));
22 };
23 // The browser retries a dropped connection itself; a refused one it gives
24 // up on, and then we try again, later each time.
25 source.onerror = () => {
26 if (source.readyState !== EventSource.CLOSED) return;
27 source.close();
28 setTimeout(connect, Math.min(30_000, 1000 * 2 ** tries++));
29 };
30 }
31
32 let refreshing = false;
33 let again = false;
34 async function refresh(types) {
35 const regions = [...document.querySelectorAll("[data-live]")].filter(
36 (el) =>
37 types === undefined ||
38 el.dataset.live.split(" ").some((t) => types.includes(t)),
39 );
40 if (regions.length === 0) return;
41 if (refreshing) {
42 again = true;
43 return;
44 }
45 refreshing = true;
46 try {
47 const response = await fetch(location.href, {
48 headers: { accept: "text/html" },
49 });
50 const fresh = new DOMParser().parseFromString(
51 await response.text(),
52 "text/html",
53 );
54 for (const el of regions) {
55 const next = fresh.getElementById(el.id);
56 if (next) el.replaceWith(next);
57 }
58 } finally {
59 refreshing = false;
60 if (again) {
61 again = false;
62 refresh();
63 }
64 }
65 }
66
67 document.addEventListener("live", (event) => refresh([event.detail.type]));
68 connect();
template/template.json added +5
@@ -0,0 +1,5 @@
1 {
2 "files": ["package.json", "README.md", "contract/openapi.json"],
3 "name": "app-template",
4 "description": "A new app on the forge."
5 }
test/apps-measure.test.ts +1 −1
@@ -12,7 +12,7 @@ import { join } from "node:path";
1212 import { createApp, type App } from "../src/app.ts";
1313 import { newApp } from "../src/actions/apps.ts";
1414 import { AppsRuntime } from "../src/apps/runtime.ts";
15 import { scaffoldFiles } from "../src/apps/scaffold.ts";
15 import { scaffoldFiles } from "../src/apps/template.ts";
1616 import { appVisitors } from "../src/actions/apps.ts";
1717 import { createToken } from "../src/core/tokens.ts";
1818 import { getRepo } from "../src/core/repos.ts";
test/apps-new.test.ts +1 −1
@@ -24,7 +24,7 @@ import { getRepo } from "../src/core/repos.ts";
2424 import { createUser, type User } from "../src/core/users.ts";
2525 import { serve, type Servers } from "../src/http/server.ts";
2626
27 import { scaffoldFiles } from "../src/apps/scaffold.ts";
27 import { scaffoldFiles } from "../src/apps/template.ts";
2828 import { parseCheck } from "../src/apps/manifest.ts";
2929 import {
3030 appNameJs,
test/apps-token.test.ts +1 −1
@@ -23,7 +23,7 @@ import {
2323 renewAppToken,
2424 revokeAppToken,
2525 } from "../src/apps/token.ts";
26 import { scaffoldFiles } from "../src/apps/scaffold.ts";
26 import { scaffoldFiles } from "../src/apps/template.ts";
2727 import { newApp } from "../src/actions/apps.ts";
2828 import { openIssue } from "../src/actions/issues.ts";
2929 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
test/contract.test.ts +1 −1
@@ -10,7 +10,7 @@
1010 */
1111 import { describe, expect, test } from "bun:test";
1212 import { readFileSync } from "node:fs";
13 import { scaffoldFiles } from "../src/apps/scaffold.ts";
13 import { scaffoldFiles } from "../src/apps/template.ts";
1414 import { policyLines, taskPrompt } from "../src/crew/brief.ts";
1515 import {
1616 NOBODY,
test/probe.test.ts +1 −1
@@ -12,7 +12,7 @@ import { createApp, type App } from "../src/app.ts";
1212 import { newApp } from "../src/actions/apps.ts";
1313 import { commitToBranch } from "../src/actions/repos.ts";
1414 import { AppsRuntime, appsRuntime } from "../src/apps/runtime.ts";
15 import { scaffoldFiles } from "../src/apps/scaffold.ts";
15 import { scaffoldFiles } from "../src/apps/template.ts";
1616 import { audit } from "../src/contract/audit.ts";
1717 import { probe, type Probed } from "../src/contract/probe.ts";
1818 import { getAppByRepo } from "../src/core/apps.ts";
test/probes.test.ts +1 −1
@@ -11,7 +11,7 @@ import { createApp, type App } from "../src/app.ts";
1111 import { newApp } from "../src/actions/apps.ts";
1212 import { commitToBranch } from "../src/actions/repos.ts";
1313 import { AppsRuntime } from "../src/apps/runtime.ts";
14 import { scaffoldFiles } from "../src/apps/scaffold.ts";
14 import { scaffoldFiles } from "../src/apps/template.ts";
1515 import {
1616 PROBE_ISSUE_TITLE,
1717 latestProbes,
test/scaffold-webspec.test.ts +1 −1
@@ -8,7 +8,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test";
88 import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
99 import { tmpdir } from "node:os";
1010 import { dirname, join } from "node:path";
11 import { scaffoldFiles } from "../src/apps/scaffold.ts";
11 import { scaffoldFiles } from "../src/apps/template.ts";
1212 import { webspec, type Finding } from "../src/release/webspec.ts";
1313
1414 /** Today's gaps, each with its specification.website section. None: the scaffold meets it. */
test/scaffold.test.ts +1 −1
@@ -23,7 +23,7 @@ import { parseManifest } from "../src/apps/manifest.ts";
2323 import { createSession } from "../src/core/sessions.ts";
2424 import { createUser } from "../src/core/users.ts";
2525 import { serve } from "../src/http/server.ts";
26 import { scaffoldFiles } from "../src/apps/scaffold.ts";
26 import { scaffoldFiles } from "../src/apps/template.ts";
2727
2828 /** How long the written-out app's `bun test` may take, wall clock. */
2929 const SUITE_BUDGET_MS = 3_000;
test/signin-words.test.ts +11 −2
@@ -1,14 +1,18 @@
11 /**
22 * A sign-in flow's expiry sentences are said from one place
33 * (`src/kernel/signin_words.ts`). Each is a real sentence, and neither the
4 * parent sign-in nor an app's scaffold types its own copy back in.
4 * parent sign-in types its own copy back in; the app template carries the
5 * same sentences as text.
56 */
67 import { describe, expect, test } from "bun:test";
78 import { readFileSync } from "node:fs";
89 import { join } from "node:path";
910 import * as words from "../src/kernel/signin_words.ts";
1011
11 const READERS = ["src/http/rp.ts", "src/apps/scaffold.ts"];
12 const READERS = ["src/http/rp.ts"];
13 // The template is a repository (#10305): its sign-in cannot import the
14 // forge's words, so it carries the same sentences, and must not drift.
15 const TEMPLATE = "template/src/signin.ts";
1216 const source = (path: string): string =>
1317 readFileSync(join(import.meta.dir, "..", path), "utf8");
1418
@@ -32,4 +36,9 @@ describe("a sign-in flow's expiry sentences", () => {
3236 expect(text).not.toContain(sentence);
3337 }
3438 });
39
40 test(`${TEMPLATE} says exactly the same sentences`, () => {
41 const text = source(TEMPLATE);
42 for (const [, sentence] of sentences) expect(text).toContain(JSON.stringify(sentence).slice(1, -1));
43 });
3544 });
test/spawn-template-birth.test.ts +1 −1
@@ -11,7 +11,7 @@ import { join } from "node:path";
1111 import { createRepo } from "../src/actions/repos.ts";
1212 import { childDirOf, spawnForge, type SpawnDeps } from "../src/actions/spawn.ts";
1313 import { createApp, type App } from "../src/app.ts";
14 import { scaffoldFiles } from "../src/apps/scaffold.ts";
14 import { scaffoldFiles } from "../src/apps/template.ts";
1515 import { getAppByRepo } from "../src/core/apps.ts";
1616 import { getRepo } from "../src/core/repos.ts";
1717 import { createToken } from "../src/core/tokens.ts";
test/template.test.ts added +73
@@ -0,0 +1,73 @@
1 /**
2 * The app template is a repository's worth of files in `template/` (#10305):
3 * its manifest names what is filled in, the forge's own evaluator and
4 * beacon stay in step with the copies it carries, and filling never
5 * touches a file the manifest does not list.
6 */
7 import { describe, expect, test } from "bun:test";
8 import { readFileSync } from "node:fs";
9 import { beaconJs } from "../src/web/beacon.ts";
10 import {
11 BUNDLED_TEMPLATE,
12 fillTemplate,
13 MANIFEST,
14 parseManifest,
15 readTemplateDir,
16 scaffoldFiles,
17 } from "../src/apps/template.ts";
18
19 const read = (p: string): string => readFileSync(p, "utf8");
20 const root = new URL("..", import.meta.url).pathname;
21
22 describe("the bundled template", () => {
23 const files = readTemplateDir(BUNDLED_TEMPLATE);
24 const manifest = parseManifest(read(`${BUNDLED_TEMPLATE}${MANIFEST}`));
25
26 test("has a valid manifest whose files exist and hold the literals", () => {
27 expect(manifest).toBeDefined();
28 for (const path of manifest!.files) {
29 const f = files.find((x) => x.path === path);
30 expect(f).toBeDefined();
31 expect(String(f!.content)).toContain(manifest!.name);
32 }
33 });
34
35 test("carries the forge's evaluator and beacon unchanged", () => {
36 expect(read(`${BUNDLED_TEMPLATE}src/can.ts`)).toBe(read(`${root}src/contract/can.ts`));
37 expect(read(`${BUNDLED_TEMPLATE}static/beacon.js`)).toBe(beaconJs.replace("/_measure", "/__forge/measure") + "\n");
38 });
39
40 test("a new app has the template's files except the manifest, with its own name", () => {
41 const made = scaffoldFiles({ name: "my-notes", description: "Notes for me" });
42 expect(made.length).toBe(files.length - 1);
43 expect(made.some((f) => f.path === MANIFEST)).toBe(false);
44 const pkg = JSON.parse(String(made.find((f) => f.path === "package.json")!.content));
45 expect(pkg.name).toBe("my-notes");
46 expect(pkg.description).toBe("Notes for me");
47 expect(String(made.find((f) => f.path === "README.md")!.content)).toContain("# my-notes");
48 for (const f of made) if (!manifest!.files.includes(f.path)) expect(f.content).toBe(files.find((x) => x.path === f.path)!.content);
49 });
50
51 test("an empty description leaves the template's own line in package.json and the README", () => {
52 const made = scaffoldFiles({ name: "x-app", description: " " });
53 const pkg = JSON.parse(String(made.find((f) => f.path === "package.json")!.content));
54 expect(pkg.description).toBe("A new app on the forge.");
55 expect(String(made.find((f) => f.path === "README.md")!.content)).toContain("A new app on the forge.");
56 });
57
58 test("a description with quotes stays valid JSON, and cannot reintroduce the name", () => {
59 const made = scaffoldFiles({ name: "x-app", description: 'say "hi" to app-template' });
60 const pkg = JSON.parse(String(made.find((f) => f.path === "package.json")!.content));
61 expect(pkg.description).toBe('say "hi" to app-template');
62 JSON.parse(String(made.find((f) => f.path === "contract/openapi.json")!.content));
63 });
64 });
65
66 describe("a template without a usable manifest", () => {
67 test("is refused, not guessed at", () => {
68 expect(fillTemplate([{ path: "a.txt", content: "a" }], { name: "n", description: "" })).toBeUndefined();
69 expect(parseManifest("not json")).toBeUndefined();
70 expect(parseManifest('{"files":[1],"name":"a","description":""}')).toBeUndefined();
71 expect(parseManifest('{"files":[],"name":"","description":""}')).toBeUndefined();
72 });
73 });
test/tui-scorecard-spend.test.ts +2 −2
@@ -48,9 +48,9 @@ test("each agent's row carries its own spend, and an agent that spent nothing sh
4848 tokensIn: 1, tokensOut: 1, costUsd, wallMs: 1, outcome: "ok",
4949 at: new Date(Date.now() - ageMs).toISOString(),
5050 });
51 spend("smith", 1.5, 60_000);
51 spend("smith", 1.5, 1_000);
5252 spend("smith", 2, 6 * 86_400_000);
53 spend("jones", 7.25, 60_000);
53 spend("jones", 7.25, 1_000);
5454
5555 const open = async (username: string) => {
5656 const { app: tui } = createForgeApp(

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs