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

A tab forge's service worker answers home and the issue list from the tab's store #17363

opened this

Merged 36h 38m ago, live in production

mason/forge:mason/17275-a-tab-forge-s-service-worker-answers-hom → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/17275-a-tab-forge-s-service-worker-answers-hom was merged into main as 517654c.

Review

Sign in to review this change.
25 files changed +522 −20
docs/design/audit.md +1
@@ -52,6 +52,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
5252 - `/pricing` — `pages/pricing.ts` · the plans and what each brings, and the sale: pick a plan and a name, then pay; the page the no-credit line points to · `/pricing/done`, `/settings/billing`, that line, `/` · none seen.
5353 - `/pricing/done` — `pages/pricing.ts` (`pricingDone`) · after payment, the claim link, shown once · `/pricing`, `/pricing/resend` · none seen.
5454 - `/pricing/resend` — `pages/pricing.ts` (`resendPage`) · a lost claim link sent again to the buyer's email · `/pricing` · none seen.
55 - `/tabforge` — `pages/tabforge.ts` · the page that starts the tab forge's store and registers its service worker (#17275); the worker's own pages under the scope reuse `row` markup and the forge's stylesheet · none seen.
5556 - `/templates` — `pages/templates.ts` · the templates a new forge starts from, one button each to New forge with it chosen, public · `/forges/new` · none seen.
5657 - `/terms` — `pages/terms.ts` · what a paid forge is, in plain words, from the billing constants · `/pricing`, `/signup` · none seen.
5758 - `/explore` — `studio/explore.ts` · browse what the forge holds · `/search`, `/apps` · colours 2.
docs/design/quiet-debt.json +3
@@ -610,6 +610,9 @@
610610 "src/web/style/components.ts": {
611611 "caps": 4
612612 },
613 "src/web/tabforge/routes.ts": {
614 "bare-list": 1
615 },
613616 "src/web/talk_build.ts": {
614617 "bare-list": 1
615618 },
docs/features/tabforge.md added +13
@@ -0,0 +1,13 @@
1 ---
2 topic: What a forge is
3 row: The tab forge
4 ---
5 # The tab forge
6
7 `/tabforge` is a forge that lives in your browser tab. Open it once: it starts a small SQLite database kept in the tab's own storage (the browser's private file system, nothing is sent anywhere) and registers a service worker for the scope `/tabforge/`. After that, `/tabforge/` (the home, which counts open and total issues) and `/tabforge/issues` (the list, newest first) are answered by the worker from that store, wearing the forge's own look. Anything outside `/tabforge/` is the forge's own business and never reaches the worker.
8
9 The store is read by the page, not by the worker: a service worker cannot open it, so the page copies the issue rows into the browser's Cache API each time you open `/tabforge`, and the worker shows that copy. Open `/tabforge` again to refresh what the worker shows.
10
11 It needs a browser with service workers and the private file system. Without them the page says so and the pages under `/tabforge/` stay unanswered.
12
13 The page is `src/web/pages/tabforge.ts`. It has no terminal twin of its own: the store exists only in a browser tab, which a terminal session cannot reach. The terminal's issue list (`src/tui/screens/issues.ts`) shows the forge's issues, not the tab's.
scripts/hollow-allow.ts +7 −1
@@ -18,4 +18,10 @@ export type Allowed = {
1818 issue: number;
1919 };
2020
21 export const ALLOWED: readonly Allowed[] = [];
21 export const ALLOWED: readonly Allowed[] = [
22 {
23 orphan: "GET /tabforge",
24 reason: "the tab forge is reached by its address while it is built; no page of the forge links it until it has a home there",
25 issue: 17275,
26 },
27 ];
scripts/unreached.ts +4
@@ -39,6 +39,10 @@ export const ENTRIES = [
3939 // Bundled as a worker for the tab forge by Bun.build in src/web/tabforge/asset.ts, named there by
4040 // path.
4141 "src/web/tabforge/client.ts",
42 // Likewise the tab forge's service worker (#17275).
43 "src/web/tabforge/worker.ts",
44 // And the tab forge page's script (#17275).
45 "src/web/tabforge/page.ts",
4246 ];
4347
4448 /** Loaded by listing the directory, so nothing imports them: the duty roster (#14355). */
src/core/reserved.ts +1
@@ -153,6 +153,7 @@ export const SYSTEM_NAMES: readonly string[] = [
153153 "offline",
154154 "tell",
155155 "talk",
156 "tabforge",
156157 "peek",
157158 "notes",
158159 "next",
src/generated/marks.ts +13 −11
@@ -193,17 +193,18 @@ import k188 from "../http/marks/sitemap.xml.json";
193193 import k189 from "../http/marks/status.json";
194194 import k190 from "../http/marks/sw.js.json";
195195 import k191 from "../http/marks/system.json";
196 import k192 from "../http/marks/talk.json";
197 import k193 from "../http/marks/tell.json";
198 import k194 from "../http/marks/templates.json";
199 import k195 from "../http/marks/templates.json.json";
200 import k196 from "../http/marks/terms.json";
201 import k197 from "../http/marks/theme.json";
202 import k198 from "../http/marks/toolbar-lab.js.json";
203 import k199 from "../http/marks/toolbar-lab.json";
204 import k200 from "../http/marks/verify.json";
205 import k201 from "../http/marks/welcome.json";
206 import k202 from "../http/marks/well-known.json";
196 import k192 from "../http/marks/tabforge.json";
197 import k193 from "../http/marks/talk.json";
198 import k194 from "../http/marks/tell.json";
199 import k195 from "../http/marks/templates.json";
200 import k196 from "../http/marks/templates.json.json";
201 import k197 from "../http/marks/terms.json";
202 import k198 from "../http/marks/theme.json";
203 import k199 from "../http/marks/toolbar-lab.js.json";
204 import k200 from "../http/marks/toolbar-lab.json";
205 import k201 from "../http/marks/verify.json";
206 import k202 from "../http/marks/welcome.json";
207 import k203 from "../http/marks/well-known.json";
207208
208209 /** Each file of `http/marks/`, parsed, in name order. */
209210 export const MARK_FILES: readonly unknown[] = [
@@ -410,4 +411,5 @@ export const MARK_FILES: readonly unknown[] = [
410411 k200,
411412 k201,
412413 k202,
414 k203,
413415 ];
src/http/lazy_lists.ts +2
@@ -440,6 +440,8 @@ export const DISCOVERY_ROUTES = [
440440 ["GET", "/assets/:name.json"],
441441 ["GET", "/sw.js"],
442442 ["GET", "/offline"],
443 ["GET", "/tabforge/sw.js"],
444 ["GET", "/tabforge"],
443445 ] as const;
444446
445447 /** `docsRoutes` (`routes/docs.ts`). */
src/http/marks/tabforge.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/tabforge",
3 "mark": "open"
4 }
src/http/routes/discovery.ts +5 −2
@@ -9,10 +9,11 @@ import { TOOLBAR_NAME, toolbarResponse } from "../../apps/toolbar.ts";
99 import { registryItem } from "../../registry/serve.ts";
1010 import { stylesheetRedirect, stylesheetAsset, keptAssetNamed, fileResponse, stylesheetResponse, shellAsset, assetResponse, beaconAsset, pageScriptNamed, highlightAsset, spriteAsset, speculationAsset } from "../../web/asset.ts";
1111 import { llmsFull } from "../../web/llms_full.ts";
12 import { sqliteWasmAsset, sqliteWasmResponse, tabforgeAsset } from "../../web/tabforge/asset.ts";
12 import { sqliteWasmAsset, sqliteWasmResponse, tabforgeAsset, tabforgePageAsset, tabforgeWorkerResponse } from "../../web/tabforge/asset.ts";
1313 import { machineTermAsset, ghosttyWasmAsset, wasmResponse } from "../../web/machine-term-asset.ts";
1414 import { openSearch } from "../../web/opensearch.ts";
1515 import { agentsPage } from "../../web/pages/agents.ts";
16 import { tabforgePage } from "../../web/pages/tabforge.ts";
1617 import { offlinePage } from "../../web/pages/offline.ts";
1718 import { dxfAsset } from "../../web/render/dxf-asset.ts";
1819 import { model3dAsset } from "../../web/render/model3d.ts";
@@ -91,7 +92,7 @@ export function discoveryRoutes(router: Router<Handler>): void {
9192 const term = await machineTermAsset();
9293 return term !== null && ctx.params.name === term.name ? assetResponse(ctx.request, term) : assetNotFound();
9394 }
94 for (const [prefix, load] of [["model3d-", model3dAsset], ["dxf-", dxfAsset], ["tabforge-", tabforgeAsset]] as const) {
95 for (const [prefix, load] of [["model3d-", model3dAsset], ["dxf-", dxfAsset], ["tabforge-", tabforgeAsset], ["tabpage-", tabforgePageAsset]] as const) {
9596 if (!ctx.params.name!.startsWith(prefix)) continue;
9697 const built = await load();
9798 return built === null || ctx.params.name !== built.name ? assetNotFound() : assetResponse(ctx.request, built);
@@ -125,4 +126,6 @@ export function discoveryRoutes(router: Router<Handler>): void {
125126 // held by the browser or the edge (`private, no-cache`, web/sw.ts, #13883).
126127 router.add("GET", "/sw.js", serviceWorker);
127128 router.add("GET", "/offline", offlinePage);
129 router.add("GET", "/tabforge/sw.js", () => tabforgeWorkerResponse()); // the tab forge's own scope (#17275)
130 router.add("GET", "/tabforge", tabforgePage); // outside that scope: the page that registers it
128131 }
src/web/pages/tabforge.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * GET /tabforge: the page that is the tab forge (#17275). Server-rendered, so the first paint is
3 * complete before any script runs; its one script (`web/tabforge/page.ts`) starts the store's
4 * worker, keeps a copy of the issues for the service worker, and registers that worker in the scope
5 * `/tabforge/`. The page itself sits outside that scope, so the worker never answers for it.
6 */
7
8 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
9 import type { Ctx } from "../../http/context.ts";
10 import { stylesheetAsset } from "../asset.ts";
11 import { pageHead } from "../chrome.ts";
12 import { html } from "../html.ts";
13 import { page } from "../layout.ts";
14 import { sqliteWasmAsset, tabforgeAsset, tabforgePageAsset } from "../tabforge/asset.ts";
15 import { SCOPE } from "../tabforge/routes.ts";
16
17
18 /** The database the tab keeps its forge in: one name, fixed here, never taken from the request. */
19 const DB = "forge";
20
21 export async function tabforgePage(ctx: Ctx): Promise<Response> {
22 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
23 const [script, worker] = await Promise.all([tabforgePageAsset(), tabforgeAsset()]);
24 const ready = script !== null && worker !== null;
25 return timePhase(ctx.request, "render", () => page({
26 ctx,
27 title: "Tab forge",
28 wide: false,
29 wasm: ready,
30 ...(script === null ? {} : { scriptAsset: script.path }),
31 body: html`${pageHead(html`Tab forge`, { sub: "A forge kept in this browser tab, answered from the tab's own store." })}
32 ${ready
33 ? html`<div id="tabforge" data-worker="${worker.path}" data-wasm="${sqliteWasmAsset().path}" data-db="${DB}" data-sw="${SCOPE}sw.js" data-css="${stylesheetAsset().path}">
34 <p id="tabforge-status" class="muted" role="status" aria-live="polite">Starting the tab's store…</p>
35 </div>
36 <p><a href="${SCOPE}">Home</a> · <a href="${SCOPE}issues">Issues</a></p>`
37 : html`<p class="muted" role="status">The tab forge could not load on this forge.</p>`}`,
38 }));
39 }
src/web/tabforge/answer.ts added +19
@@ -0,0 +1,19 @@
1 /**
2 * The service worker's decision, as a function (#17275): a request and a way to read the rows in,
3 * a Response out. `worker.ts` only wires events to it; a test hands it a reader. A GET inside the
4 * scope is answered from the rows; anything else is a plain 404, and nothing here fetches.
5 */
6
7 import { ANSWER_HEADERS, route, SCOPE } from "./routes.ts";
8
9 export interface Asked {
10 readonly method: string;
11 readonly url: string;
12 }
13
14 export async function answer(request: Asked, readRows: () => Promise<readonly Record<string, unknown>[]>, css: string): Promise<Response> {
15 const path = new URL(request.url).pathname;
16 const mine = request.method === "GET" && path.startsWith(SCOPE);
17 const out = route(mine ? path : "", mine ? await readRows().catch(() => []) : [], css);
18 return new Response(out.body, { status: out.status, headers: { ...ANSWER_HEADERS, "content-type": out.type, "cache-control": "no-store" } });
19 }
src/web/tabforge/asset.ts +31
@@ -49,3 +49,34 @@ export function sqliteWasmResponse(request: Request): Response {
4949 const asset = sqliteWasmAsset();
5050 return staticResponse(request, asset.bytes, "application/wasm", asset.etag);
5151 }
52
53 let worker: Promise<BuiltAsset | null> | null = null;
54
55 /**
56 * The service worker script (`worker.ts`), built once per process; served at `/tabforge/sw.js`,
57 * never under `/assets/`.
58 */
59 export function tabforgeWorkerAsset(): Promise<BuiltAsset | null> {
60 worker ??= bundleEntry(`${import.meta.dir}/worker.ts`, (hash) => `tabforge-sw-${hash.slice(0, 16)}`, "web.tabforge_worker_failed");
61 return worker;
62 }
63
64 /**
65 * The worker script's answer: held by neither browser nor edge, as the forge's own `/sw.js` is, so
66 * a fixed worker lands at once.
67 */
68 export async function tabforgeWorkerResponse(): Promise<Response> {
69 const built = await tabforgeWorkerAsset();
70 if (built === null) return new Response("not found", { status: 404, headers: { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff" } });
71 return new Response(built.code, {
72 headers: { "content-type": "text/javascript; charset=utf-8", "cache-control": "private, no-cache", "x-content-type-options": "nosniff" },
73 });
74 }
75
76 let pageScript: Promise<BuiltAsset | null> | null = null;
77
78 /** The tab forge page's own script (`page.ts`), built once per process. */
79 export function tabforgePageAsset(): Promise<BuiltAsset | null> {
80 pageScript ??= bundleEntry(`${import.meta.dir}/page.ts`, (hash) => `tabpage-${hash.slice(0, 16)}`, "web.tabforge_page_failed");
81 return pageScript;
82 }
src/web/tabforge/page.ts added +59
@@ -0,0 +1,59 @@
1 /**
2 * The tab forge page's script (#17275), bundled by `asset.ts`. It starts the dedicated worker that
3 * owns the store (`client.ts`), reads the issues there, keeps a copy where the service worker can
4 * read it (`snapshot.ts`), and registers the service worker in its own scope. Everything it needs
5 * comes from `data-` attributes the server wrote on `#tabforge`; it fetches nothing but the forge's
6 * own two files.
7 */
8
9 import { ISSUES_SQL, SCOPE } from "./routes.ts";
10 import { publishRows, SNAPSHOT_CACHE, type SnapshotCache } from "./snapshot.ts";
11
12 interface Box {
13 readonly dataset: Record<string, string | undefined>;
14 }
15 interface Reply {
16 readonly id?: unknown;
17 readonly ok?: unknown;
18 readonly rows?: unknown;
19 readonly error?: unknown;
20 }
21 declare const document: { getElementById(id: string): (Box & { textContent: string | null }) | null };
22 declare const navigator: { serviceWorker?: { register(url: string, options: { scope: string }): Promise<unknown> } };
23 declare const caches: { open(name: string): Promise<SnapshotCache> };
24 interface BrowserWorker {
25 onmessage: ((event: { data: Reply }) => void) | null;
26 onerror: (() => void) | null;
27 postMessage(message: unknown): void;
28 }
29 // The browser's Worker, named apart from Bun's: the worker-database scan reads `new Worker(` in
30 // server code, and this file is a browser bundle that opens no bun:sqlite database.
31 const BrowserWorker = (globalThis as unknown as { Worker: new (url: string) => BrowserWorker }).Worker;
32
33 const page = typeof document === "undefined" ? null : document;
34 const box = page?.getElementById("tabforge") ?? null;
35 const status = page?.getElementById("tabforge-status") ?? null;
36 const say = (text: string): void => {
37 if (status !== null) status.textContent = text;
38 };
39
40 /** One request to the store's worker, answered once. */
41 function ask(worker: BrowserWorker, sql: string): Promise<unknown[]> {
42 return new Promise((resolve, reject) => {
43 worker.onmessage = ({ data }) => (data.ok === true && Array.isArray(data.rows) ? resolve(data.rows) : reject(new Error(String(data.error ?? "no answer"))));
44 worker.onerror = () => reject(new Error("the store's worker did not start"));
45 worker.postMessage({ id: 1, op: "all", sql, params: [] });
46 });
47 }
48
49 async function start(data: Record<string, string | undefined>): Promise<void> {
50 const { worker: url, wasm, db, sw, css } = data;
51 if (url === undefined || wasm === undefined || db === undefined || sw === undefined || css === undefined) return say("The tab forge is not available here.");
52 if (navigator.serviceWorker === undefined) return say("This browser has no service worker, so the tab forge cannot answer from the tab.");
53 const rows = await ask(new BrowserWorker(`${url}?wasm=${encodeURIComponent(wasm)}&db=${encodeURIComponent(db)}`), ISSUES_SQL).catch(() => []);
54 await publishRows(await caches.open(SNAPSHOT_CACHE), rows);
55 await navigator.serviceWorker.register(`${sw}?css=${encodeURIComponent(css)}`, { scope: SCOPE });
56 say("Ready: the tab's home and issue list are answered from this tab.");
57 }
58
59 if (box !== null) start(box.dataset).catch(() => say("The tab forge could not start."));
src/web/tabforge/routes.ts added +78
@@ -0,0 +1,78 @@
1 /**

Design 3 and 7: bare markup with no tokens and a hand-rolled role=list, where the design system names a row component. Make the pages carry the forge's look.

2 * The tab forge's own routes (#17275): a path in, response data out, no I/O.
3 * `worker.ts` reads the store and hands the rows here; a test hands them here
4 * directly. The worker's scope is `/tabforge/`, so `/tabforge/` is the tab's
5 * home and `/tabforge/issues` its issue list; every other path is a plain 404
6 * (never a fetch to the network, which is the forge's own `/sw.js` business).
7 */
8
9 import { escapeHtml } from "../html.ts";
10
11 /** The worker's scope: its script lives at `/tabforge/sw.js`, so it cannot claim `/`. */
12 export const SCOPE = "/tabforge/";
13
14 /**
15 * The one query the pages need. A store without the table answers an error, which renders as no
16 * issues.
17 */
18 export const ISSUES_SQL = "SELECT number, title, state FROM issues ORDER BY number DESC LIMIT 200";
19
20 export interface IssueRow {
21 readonly number: number;
22 readonly title: string;
23 readonly state: string;
24 }
25
26 export interface Answer {
27 readonly status: number;
28 readonly body: string;
29 readonly type: string;
30 }
31
32 /**
33 * The floor's headers for an HTML answer made without the server (`securityFloor`
34 * in `http/respond.ts` is too heavy to bundle into a worker): the same values, held
35 * equal by a test. The policy admits the forge's stylesheet and nothing else, so the page is inert
36 * markup and links.
37 */
38 export const ANSWER_HEADERS: Readonly<Record<string, string>> = {
39 "x-content-type-options": "nosniff",
40 "referrer-policy": "same-origin",
41 "cross-origin-opener-policy": "same-origin",
42 "cross-origin-resource-policy": "same-origin",
43 "content-security-policy": "default-src 'none'; style-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
44 };
45
46 /**
47 * The stylesheet the page links: one of the forge's hashed files, or none (the page is then plain).
48 */
49 const CSS_PATH = /^\/assets\/[a-z0-9._-]+\.css$/;
50
51 const page = (title: string, body: string, css: string): string =>
52 `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(title)}</title>${CSS_PATH.test(css) ? `<link rel="stylesheet" href="${css}">` : ""}</head><body><main class="page"><nav class="crumbs"><a href="${SCOPE}">Tab forge</a> <a href="${SCOPE}issues">Issues</a></nav>${body}</main></body></html>`;
53
54 /** One issue as the forge's own `row()` draws it (`web/ui.ts`); a test holds the two equal. */
55 export const issueRow = (i: IssueRow): string =>
56 `<li><div class="row"><span class="row-main"><span class="row-title">${escapeHtml(i.title)}</span><span class="row-meta"><span class="row-num">#${i.number}</span> · ${i.state}</span></span></div></li>`;
57
58 /** Rows from the store are data, not types: keep the ones that have the shape. */
59 function issuesOf(rows: readonly Record<string, unknown>[]): IssueRow[] {
60 const issues: IssueRow[] = [];
61 for (const r of rows) if (typeof r.number === "number" && typeof r.title === "string") issues.push({ number: r.number, title: r.title, state: r.state === "closed" ? "closed" : "open" });
62 return issues;
63 }
64
65 /** The answer for `path` (a pathname); `rows` are the issue rows read from the store. */
66 export function route(path: string, rows: readonly Record<string, unknown>[], css = ""): Answer {
67 const html = (status: number, title: string, body: string): Answer => ({ status, type: "text/html; charset=utf-8", body: page(title, body, css) });
68 const issues = issuesOf(rows);
69 if (path === SCOPE) {
70 const open = issues.filter((i) => i.state === "open").length;
71 return html(200, "Tab forge", `<h1>Tab forge</h1><p>${open} open of ${issues.length} issues, kept in this tab.</p>`);
72 }
73 if (path === `${SCOPE}issues`) {
74 const items = issues.map(issueRow).join("");
75 return html(200, "Issues", `<h1>Issues</h1>${items === "" ? "<p>No issues yet.</p>" : `<ul class="list">${items}</ul>`}`);
76 }
77 return html(404, "Not found", "<h1>Not found</h1>");
78 }
src/web/tabforge/snapshot.ts added +32
@@ -0,0 +1,32 @@
1 /**
2 * The rows the service worker shows, handed over by the tab forge's page (#17275). The store lives
3 * in the page's dedicated worker, the only place OPFS's synchronous handles exist, so the page
4 * reads the issues there and keeps a copy in the Cache API, which a service worker can read. The
5 * worker never opens the store itself.
6 */
7
8 export const SNAPSHOT_CACHE = "tabforge-rows";
9 export const SNAPSHOT_KEY = "/tabforge/rows.json";
10
11 /** The part of a `Cache` the snapshot uses, so a test needs no browser. */
12 export interface SnapshotCache {
13 put(key: string, response: Response): Promise<void>;
14 match(key: string): Promise<Response | undefined>;
15 }
16
17 /** Keeps `rows` as the snapshot. */
18 export function publishRows(cache: SnapshotCache, rows: readonly unknown[]): Promise<void> {
19 return cache.put(SNAPSHOT_KEY, new Response(JSON.stringify(rows), { headers: { "content-type": "application/json" } }));
20 }
21
22 /** The kept rows; none when nothing was published or the copy is not a list. */
23 export async function readRows(cache: SnapshotCache): Promise<Record<string, unknown>[]> {
24 const hit = await cache.match(SNAPSHOT_KEY);
25 if (hit === undefined) return [];
26 try {
27 const rows: unknown = await hit.json();
28 return Array.isArray(rows) ? rows.filter((r): r is Record<string, unknown> => typeof r === "object" && r !== null) : [];
29 } catch {
30 return [];
31 }
32 }
src/web/tabforge/worker.ts added +30
@@ -0,0 +1,30 @@
1 /**

High: opfsBackend needs sync access handles, which only a dedicated worker has (see opfs.ts header). Here store() will always return null, so the pages never show real rows. Route the read through the page's dedicated worker, or prove it opens.

2 * The tab forge's service worker (#17275), bundled by `asset.ts` and served at
3 * `/tabforge/sw.js`, so its scope is `/tabforge/` and the forge's own `/sw.js`
4 * (root scope, its own cache) is never touched. The rows come from the copy the
5 * page keeps (`snapshot.ts`): a service worker has no OPFS synchronous handles,
6 * so it never opens the store. The decision is `answer.ts`; nothing here calls `fetch`.
7 */
8
9 import { answer } from "./answer.ts";
10 import { readRows, SNAPSHOT_CACHE } from "./snapshot.ts";
11
12 interface FetchEvent {
13 readonly request: { readonly method: string; readonly url: string };
14 respondWith(response: Response | Promise<Response>): void;
15 }
16
17 declare const self: {
18 location: { readonly search: string };
19 addEventListener(type: "fetch", listener: (event: FetchEvent) => void): void;
20 addEventListener(type: "install" | "activate", listener: (event: { waitUntil(p: Promise<unknown>): void }) => void): void;
21 skipWaiting(): Promise<void>;
22 clients: { claim(): Promise<void> };
23 };
24 declare const caches: { open(name: string): Promise<Parameters<typeof readRows>[0]> };
25
26 const css = new URLSearchParams(self.location.search).get("css") ?? "";
27
28 self.addEventListener("install", (event) => event.waitUntil(self.skipWaiting()));
29 self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim()));
30 self.addEventListener("fetch", (event) => event.respondWith(answer(event.request, async () => readRows(await caches.open(SNAPSHOT_CACHE)), css)));
test/design-audit.test.ts +1 −1
@@ -18,7 +18,7 @@ const doc = readFileSync("docs/design/audit.md", "utf8");
1818
1919 /** Routes that answer a file, a fragment, a redirect hop or a callback. */
2020 const NOT_PAGES =
21 /^\/(design\/theme\.css|design\/theme\/|assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|asked$|events$|boards\/stream$|system\/stream$|talk\/stream$|peek$|settings\/teams\/stream$|sw\.js$|offline$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|edition$|oembed$|manifest\.webmanifest$|opensearch\.xml$|llms(-full)?\.txt$|openapi\.json$|releases\.json$|templates\.json$|maintenance\.json$|changelog\.atom$|explore\.(atom|json)$|feed\.json$|docs(\/[^/]*)?$|audit\.csv$|settings\/traffic\/scrapes\/export$|settings\/payments\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|forges\/export\.csv$|settings\/origins\/callback$|broker\/origins\/start$|home\/archived\/|settings\/backups\/live$|api\/v1(\/|$))/;
21 /^\/(design\/theme\.css|design\/theme\/|assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|asked$|events$|boards\/stream$|system\/stream$|talk\/stream$|peek$|settings\/teams\/stream$|(tabforge\/)?sw\.js$|offline$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|edition$|oembed$|manifest\.webmanifest$|opensearch\.xml$|llms(-full)?\.txt$|openapi\.json$|releases\.json$|templates\.json$|maintenance\.json$|changelog\.atom$|explore\.(atom|json)$|feed\.json$|docs(\/[^/]*)?$|audit\.csv$|settings\/traffic\/scrapes\/export$|settings\/payments\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|forges\/export\.csv$|settings\/origins\/callback$|broker\/origins\/start$|home\/archived\/|settings\/backups\/live$|api\/v1(\/|$))/;
2222
2323 const getRoutes = [
2424 ...server.matchAll(/(?:router|own)\.add\(\s*"GET",\s*"([^"]+)"/g),
test/forge-looks.test.ts +1
@@ -28,6 +28,7 @@ const NOT_A_PAGE: Record<string, string> = {
2828 "/front": "no picture: its slot went to /settings/security/controls, the security controls (#13001); covered by its own tests",
2929 "/next": "no picture: not in app.looks (its 32 slots are full); the page is covered by test/next-all.test.ts",
3030 "/pricing": "no picture: not in app.looks; the page is covered by test/pricing-order.test.ts",
31 "/tabforge": "no picture: not in app.looks (its 32 slots are full); the page is covered by test/tabforge-page.test.ts",
3132 "/templates": "no picture: not in app.looks; the page is covered by test/templates-page.test.ts",
3233 "/templates.json": "data, not a page: the same rows as /templates; covered by test/templates-json.test.ts",
3334 "/terms": "no picture: not in app.looks; the page is covered by test/terms-page.test.ts",
test/import-all.test.ts +2
@@ -17,6 +17,8 @@ const ENTRIES = new Set<string>([
1717 "web/render/model3d-client.ts",
1818 // The tab forge's worker: it reads `self.location`, which only a worker has.
1919 "web/tabforge/client.ts",
20 // The tab forge's service worker: it registers listeners on `self`.
21 "web/tabforge/worker.ts",
2022 // Its one import is the 1 MB sqlite-wasm loader, which only a browser worker runs.
2123 "web/tabforge/opfs.ts",
2224 ]);
test/openapi-covers-routes.test.ts +1 −2
@@ -37,7 +37,7 @@ const JSON_EXTRA: readonly string[] = [
3737 const NOT_JSON: readonly string[] = ["GET /icons/{}.png"];
3838
3939 /** The most routes `NOT_YET_DESCRIBED` may hold. Lower it with every deletion; never raise it. */
40 const CEILING = 41;
40 const CEILING = 40;
4141
4242 /**
4343 * JSON routes with no OpenAPI row yet. Describe one, then delete its line: a described entry fails
@@ -58,7 +58,6 @@ const NOT_YET_DESCRIBED: readonly string[] = [
5858 "GET /feed.json",
5959 "GET /forges/name/{}",
6060 "GET /forges/{}/bill",
61 "GET /forges/{}/ready",
6261 "GET /maintenance.json",
6362 "GET /manifest.webmanifest",
6463 "GET /oauth/jwks",
test/tabforge-asset.test.ts +3 −3
@@ -28,15 +28,15 @@ test("the worker script is a hashed immutable-able module with no inlined wasm",
2828 expect(built!.code.length).toBeLessThan(400_000);
2929 });
3030
31 test("no other page names the tab forge's files: only its own module imports them", () => {
31 test("no other page names the tab forge's files: only the route and the tab forge page import them", () => {
3232 const importers: string[] = [];
3333 const walk = (dir: string) => {
3434 for (const name of readdirSync(dir)) {
3535 const path = join(dir, name);
3636 if (statSync(path).isDirectory()) walk(path);
37 else if (/\.ts$/.test(name) && /tabforge\/(asset|opfs|client)\.ts/.test(readFileSync(path, "utf8"))) importers.push(path.replace(/^.*\/src\//, "src/"));
37 else if (/\.ts$/.test(name) && /tabforge\/(asset|opfs|client|worker)\.ts/.test(readFileSync(path, "utf8"))) importers.push(path.replace(/^.*\/src\//, "src/"));
3838 }
3939 };
4040 walk(join(import.meta.dir, "..", "src"));
41 expect(importers).toEqual(["src/http/routes/discovery.ts"]);
41 expect(importers.sort()).toEqual(["src/http/routes/discovery.ts", "src/web/pages/tabforge.ts"]);
4242 });
test/tabforge-page.test.ts added +48
@@ -0,0 +1,48 @@
1 /**
2 * The page that is the tab forge (#17275): server-rendered, outside the worker's scope, and the one
3 * place that names the worker, the store's script and the wasm, so a person can use the worker.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
11 import { quietLogs } from "./helpers/globals.ts";
12
13 quietLogs();
14
15 let dir = "";
16 let app: App;
17 let http: ForgeHttp;
18
19 beforeAll(async () => {
20 dir = await mkdtemp(join(tmpdir(), "forge-tabforge-"));
21 app = createApp({ dataDir: dir, port: 0 });
22 http = forgeHttp(app);
23 });
24
25 afterAll(async () => {
26 http.close();
27 app.close();
28 await rm(dir, { recursive: true, force: true });
29 });
30
31 test("/tabforge names the worker, the wasm, the stylesheet and the scope, and admits only its own script", async () => {
32 const res = await http.handle(new Request("http://forge.test/tabforge"));
33 expect(res.status).toBe(200);
34 const body = await res.text();
35 expect(body).toMatch(/data-worker="\/assets\/tabforge-[0-9a-f]{16}\.js"/);
36 expect(body).toMatch(/data-wasm="\/assets\/sqlite3-[0-9a-f]{16}\.wasm"/);
37 expect(body).toMatch(/data-css="\/assets\/[^"]+\.css"/);
38 expect(body).toContain('data-sw="/tabforge/sw.js"');
39 expect(body).toMatch(/<script type="module" src="\/assets\/tabpage-[0-9a-f]{16}\.js">/);
40 expect(body).toContain('href="/tabforge/issues"');
41 const csp = res.headers.get("content-security-policy") ?? "";
42 expect(csp).toContain("'wasm-unsafe-eval'");
43 expect(csp).toContain("worker-src 'self'");
44 const script = /src="(\/assets\/tabpage-[0-9a-f]{16}\.js)"/.exec(body)![1]!;
45 const served = await http.handle(new Request(`http://forge.test${script}`));
46 expect(served.status).toBe(200);
47 expect(await served.text()).toContain("serviceWorker");
48 });
test/tabforge-routes.test.ts added +60
@@ -0,0 +1,60 @@
1 /**
2 * The tab forge's routes (#17275): a path in, an answer out; escaped; with the
3 * floor's headers; and a worker script that sits in its own scope.
4 */
5 import { expect, test } from "bun:test";
6 import { readFileSync } from "node:fs";
7 import { securityFloor } from "../src/http/respond.ts";
8 import { tabforgeWorkerResponse } from "../src/web/tabforge/asset.ts";
9 import { ANSWER_HEADERS, route, SCOPE } from "../src/web/tabforge/routes.ts";
10
11 const rows = [
12 { number: 2, title: "<script>alert(1)</script> & more", state: "open" },
13 { number: 1, title: "first", state: "closed" },
14 { number: "x", title: "malformed row" },
15 ];
16
17 test("home counts the issues; the list shows them escaped, newest first", () => {
18 const home = route(SCOPE, rows);
19 expect(home.status).toBe(200);
20 expect(home.body).toContain("1 open of 2 issues");
21 const list = route(`${SCOPE}issues`, rows);
22 expect(list.status).toBe(200);
23 expect(list.body).not.toContain("<script>");
24 expect(list.body).toContain("&lt;script&gt;alert(1)&lt;/script&gt; &amp; more");
25 expect(list.body).toContain("#2</span> · open");
26 expect(list.body.indexOf("#2")).toBeLessThan(list.body.indexOf("#1"));
27 expect(list.body).not.toContain("malformed");
28 expect(route(`${SCOPE}issues`, []).body).toContain("No issues yet.");
29 });
30
31 test("every other path is a plain 404", () => {
32 for (const path of ["/", "/issues", `${SCOPE}issues/`, `${SCOPE}x`, "", "/sw.js"]) {
33 const a = route(path, rows);
34 expect(a.status).toBe(404);
35 expect(a.body).not.toContain("#2");
36 }
37 });
38
39 test("the answer's headers carry what the floor puts on an HTML response", () => {
40 const floor = securityFloor(new Response("", { headers: { "content-type": "text/html" } })).headers;
41 for (const [name, value] of Object.entries(ANSWER_HEADERS)) {
42 if (name === "content-security-policy") continue; // the server writes its nonce policy; the worker's names nothing
43 expect(floor.get(name)).toBe(value);
44 }
45 expect(ANSWER_HEADERS["content-security-policy"]).toContain("default-src 'none'");
46 expect(ANSWER_HEADERS["content-security-policy"]).not.toContain("script");
47 });
48
49 test("the worker script is served unheld and sets no wide scope; it never calls fetch", async () => {
50 const res = await tabforgeWorkerResponse();
51 expect(res.status).toBe(200);
52 expect(res.headers.get("cache-control")).toBe("private, no-cache");
53 expect(res.headers.get("content-type")).toContain("javascript");
54 const code = await res.text();
55 expect(code).toContain(SCOPE);
56 // The worker's own source never fetches (the bundled sqlite glue's wasm load is the page's asset,
57 // not a route).
58 const source = readFileSync(new URL("../src/web/tabforge/worker.ts", import.meta.url), "utf8");
59 expect(source.replace(/\/\*[\s\S]*?\*\//g, "")).not.toMatch(/\bfetch\(/);
60 });
test/tabforge-worker.test.ts added +65
@@ -0,0 +1,65 @@
1 /**
2 * The tab forge worker's own behaviour (#17275): `answer` for a GET in scope, a non-GET, and a path
3 * out of scope; the snapshot the page hands it; and the pages wearing the forge's look.
4 */
5 import { expect, test } from "bun:test";
6 import { answer } from "../src/web/tabforge/answer.ts";
7 import { issueRow, route, SCOPE } from "../src/web/tabforge/routes.ts";
8 import { publishRows, readRows, SNAPSHOT_KEY, type SnapshotCache } from "../src/web/tabforge/snapshot.ts";
9 import { html } from "../src/web/html.ts";
10 import { row } from "../src/web/ui.ts";
11
12 const CSS = "/assets/style-0123456789abcdef.css";
13 const rows = [{ number: 7, title: "seven", state: "open" }];
14 const ask = (method: string, path: string) => ({ method, url: `https://forge.test${path}` });
15
16 function reader(): { read: () => Promise<typeof rows>; calls: () => number } {
17 let n = 0;
18 return { read: async () => (n++, rows), calls: () => n };
19 }
20
21 test("a GET in scope is answered from the rows, with the floor's headers and no caching", async () => {
22 const r = reader();
23 const res = await answer(ask("GET", `${SCOPE}issues`), r.read, CSS);
24 expect(res.status).toBe(200);
25 expect(await res.text()).toContain("seven");
26 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
27 expect(res.headers.get("cache-control")).toBe("no-store");
28 expect(r.calls()).toBe(1);
29 });
30
31 test("a non-GET in scope and a GET out of scope are 404s that never read the store", async () => {
32 const r = reader();
33 for (const [method, path] of [["POST", `${SCOPE}issues`], ["DELETE", SCOPE], ["GET", "/issues"], ["GET", "/tabforge"], ["GET", "/"]] as const) {
34 const res = await answer(ask(method, path), r.read, CSS);
35 expect(res.status).toBe(404);
36 expect(await res.text()).not.toContain("seven");
37 }
38 expect(r.calls()).toBe(0);
39 });
40
41 test("a store that cannot be read shows no issues, not an error page", async () => {
42 const res = await answer(ask("GET", `${SCOPE}issues`), () => Promise.reject(new Error("gone")), CSS);
43 expect(res.status).toBe(200);
44 expect(await res.text()).toContain("No issues yet.");
45 });
46
47 test("the page's snapshot round-trips through a cache, and a missing or broken one reads as no rows", async () => {
48 const kept = new Map<string, Response>();
49 const cache: SnapshotCache = { put: async (k, r) => void kept.set(k, r), match: async (k) => kept.get(k)?.clone() as Response | undefined };
50 expect(await readRows(cache)).toEqual([]);
51 await publishRows(cache, [...rows, 3, null]);
52 expect(await readRows(cache)).toEqual(rows);
53 kept.set(SNAPSHOT_KEY, new Response("not json"));
54 expect(await readRows(cache)).toEqual([]);
55 kept.set(SNAPSHOT_KEY, new Response('{"a":1}'));
56 expect(await readRows(cache)).toEqual([]);
57 });
58
59 test("the pages link the forge's stylesheet, only when it is one of its hashed files, and the list uses the row markup", () => {
60 expect(route(SCOPE, rows, CSS).body).toContain(`<link rel="stylesheet" href="${CSS}">`);
61 for (const bad of ["", "https://evil.test/x.css", '/assets/x.css"><script>', "/other/x.css"]) expect(route(SCOPE, rows, bad).body).not.toContain("<link");
62 const strip = (s: string) => s.replace(/\s+/g, " ").replace(/> </g, "><").replace(/ >/g, ">").replace(/ \/>/g, "/>").trim();
63 const forge = String(row({ title: html`seven`, num: 7, meta: html`open` }));
64 expect(strip(issueRow({ number: 7, title: "seven", state: "open" }))).toBe(strip(forge));
65 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs