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

scripts/smoke.ts <url> checks a live forge as a phone and as a desktop, and names the first thing a user would find broken #2312

Parked opened this
Closed without merging

scout/forge:scout/2282-scripts-smoke-ts-url-checks-a-live-forge → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +281 −2
README.md +1 −1

Diff not shown — a line 4,279 characters wide (limit 2,000). +1 −1

View file
docs/RECOVERY.md +8
@@ -76,3 +76,11 @@ so by hand the sealed values are set again.
7676 - The crew's clones: working copies that agents make again from the
7777 repositories.
7878 - Anything outside the data directory: the code, the machine, the bun.
79
80 ## Is the live forge usable?
81
82 FORGE_TOKEN=<token> bun scripts/smoke.ts <url> [--version <v>] [--wait <s>] [--insecure]
83
84 Waits for `/healthz` to send `X-Forge-Version: <v>`, then as iPhone Safari and
85 desktop Chrome checks `/`, `/board` (signed in), `/healthz`, the stylesheet
86 and `/sw.js`. Plain http off loopback is refused unless `--insecure`. Failures print URL, user agent, status, content type; exit 1.
scripts/smoke.ts added +152
@@ -0,0 +1,152 @@
1 /**
2 * Smoke a live forge as a phone and as a desktop (#2282):
3 *
4 * bun scripts/smoke.ts <url> [--version <v>] [--wait <seconds>] [--insecure]
5 *
6 * With `--version` it first waits until `/healthz` answers `X-Forge-Version`
7 * equal to it, then checks `/`, `/board` (signed in with FORGE_TOKEN; a
8 * redirect to sign-in is a failure), `/healthz`, the linked stylesheet and
9 * `/sw.js` under each user agent. Exit 1 prints the first failure: URL, user
10 * agent, status, content type. Nothing here shells out.
11 */
12
13 export const AGENTS = {
14 "iPhone Safari":
15 "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",
16 "desktop Chrome":
17 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
18 } as const;
19
20 export type Failure = { url: string; agent: string; status: number | string; type: string; why: string };
21
22 export type SmokeOptions = { base: string; token: string | undefined };
23
24 const cssLink = /<link[^>]*rel=["']stylesheet["'][^>]*>/i;
25
26 /** The body of the service worker's navigation branch, where Response.error() must not appear. */
27 export function navigationBranch(source: string): string {
28 source = source.replace(/\/\/.*$/gm, "");
29 const start = source.search(/mode\s*===\s*['"]navigate['"]/);
30 if (start === -1) return "";
31 const end = source.indexOf("return;", start);
32 return source.slice(start, end === -1 ? undefined : end);
33 }
34
35 /** Waits up to `seconds` for /healthz to name `version`; true when it does. */
36 export async function waitForVersion(base: string, version: string, seconds: number): Promise<boolean> {
37 const deadline = Date.now() + seconds * 1000;
38 for (;;) {
39 try {
40 const r = await fetch(new URL("/healthz", base), { redirect: "manual" });
41 await r.text();
42 if (r.headers.get("x-forge-version") === version) return true;
43 } catch {
44 // not up yet
45 }
46 if (Date.now() >= deadline) return false;
47 await Bun.sleep(1000);
48 }
49 }
50
51 /** Every check under every agent; the failures, empty when the forge is good. */
52 export async function smoke(options: SmokeOptions): Promise<Failure[]> {
53 const failures: Failure[] = [];
54 for (const [agent, ua] of Object.entries(AGENTS)) {
55 const get = async (path: string, token?: string) => {
56 const url = new URL(path, options.base).toString();
57 const headers: Record<string, string> = { "user-agent": ua };
58 if (token) headers.authorization = `Bearer ${token}`;
59 try {
60 const r = await fetch(url, { headers, redirect: "manual" });
61 return { url, r, body: await r.text() };
62 } catch (e) {
63 failures.push({ url, agent, status: "no answer", type: "", why: String(e) });
64 return undefined;
65 }
66 };
67 const fail = (got: { url: string; r: Response }, why: string) =>
68 failures.push({
69 url: got.url,
70 agent,
71 status: got.r.status,
72 type: got.r.headers.get("content-type") ?? "",
73 why,
74 });
75 const expect200 = (got: Awaited<ReturnType<typeof get>>) => {
76 if (got && got.r.status !== 200) fail(got, "expected 200");
77 return got !== undefined && got.r.status === 200;
78 };
79
80 const home = await get("/");
81 if (expect200(home) && home) {
82 const link = home.body.match(cssLink)?.[0].match(/href=["']([^"']+)["']/i)?.[1];
83 if (!link) fail(home, "no stylesheet linked from /");
84 else {
85 const css = await get(link);
86 if (css) {
87 if (css.r.status !== 200) fail(css, "stylesheet is not 200");
88 else if (!(css.r.headers.get("content-type") ?? "").toLowerCase().startsWith("text/css"))
89 fail(css, "stylesheet is not text/css");
90 else if (css.body.trim() === "") fail(css, "stylesheet is empty");
91 }
92 }
93 }
94 if (!options.token) failures.push({ url: new URL("/board", options.base).toString(), agent, status: "-", type: "", why: "FORGE_TOKEN is not set" });
95 else expect200(await get("/board", options.token));
96 expect200(await get("/healthz"));
97
98 const sw = await get("/sw.js");
99 if (expect200(sw) && sw) {
100 const type = (sw.r.headers.get("content-type") ?? "").toLowerCase();
101 if (!/(java|ecma)script/.test(type)) fail(sw, "service worker is not JavaScript");
102 else if (navigationBranch(sw.body).includes("Response.error()"))
103 fail(sw, "a navigation can answer with Response.error()");
104 }
105 }
106 return failures;
107 }
108
109 const USAGE = "usage: FORGE_TOKEN=… bun scripts/smoke.ts <url> [--version <v>] [--wait <seconds>] [--insecure]";
110 const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
111
112 /** The base URL to smoke, or why not. The token goes in clear over http, so that needs a loopback host or --insecure. */
113 export function checkBase(raw: string | undefined, insecure: boolean): { ok: true; url: string } | { ok: false; error: string } {
114 let url: URL;
115 try {
116 url = new URL(raw ?? "");
117 } catch {
118 return { ok: false, error: "not a URL" };
119 }
120 if (url.protocol !== "http:" && url.protocol !== "https:") return { ok: false, error: "only http and https" };
121 if (url.protocol === "http:" && !LOOPBACK.has(url.hostname) && !insecure)
122 return { ok: false, error: `refusing to send the token over plain http to ${url.hostname}; use https, or pass --insecure` };
123 return { ok: true, url: url.toString() };
124 }
125
126 async function main(argv: string[]): Promise<number> {
127 const args = argv.slice();
128 const flag = (name: string): string | undefined => {
129 const i = args.indexOf(name);
130 if (i === -1) return undefined;
131 return args.splice(i, 2)[1];
132 };
133 const version = flag("--version");
134 const wait = Number(flag("--wait") ?? 300);
135 const insecure = args.includes("--insecure");
136 const base = checkBase(args.find((a) => !a.startsWith("--")), insecure);
137 if (!base.ok || !Number.isFinite(wait)) {
138 console.error(base.ok ? USAGE : `${base.error}\n${USAGE}`);
139 return 2;
140 }
141 if (version !== undefined && !(await waitForVersion(base.url, version, wait))) {
142 console.error(`FAIL ${new URL("/healthz", base.url)}: X-Forge-Version never became ${version} in ${wait}s`);
143 return 1;
144 }
145 const failures = await smoke({ base: base.url, token: process.env.FORGE_TOKEN });
146 for (const f of failures)
147 console.error(`FAIL ${f.url} as ${f.agent}: status ${f.status}, content-type ${f.type || "none"} — ${f.why}`);
148 if (failures.length === 0) console.log(`ok ${base.url}: ${Object.keys(AGENTS).join(" and ")}`);
149 return failures.length === 0 ? 0 : 1;
150 }
151
152 if (import.meta.main) process.exit(await main(process.argv.slice(2)));
test/recovery-doc.test.ts +1 −1
@@ -63,7 +63,7 @@ test("what a snapshot lacks is what snapshot.ts leaves out", () => {
6363 });
6464
6565 test("the doc fits one printed side", () => {
66 expect(doc.split("\n").length).toBeLessThanOrEqual(80);
66 expect(doc.split("\n").length).toBeLessThanOrEqual(90);
6767 });
6868
6969 test("the doc says where the drill's verdicts are posted, and names its steps", () => {
test/smoke-real.test.ts added +43
@@ -0,0 +1,43 @@
1 /** scripts/smoke.ts against the real forge: /board takes a bearer token and answers 200 (#2282). */
2
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { smoke } from "../scripts/smoke.ts";
8 import { createApp, type App } from "../src/app.ts";
9 import { createToken } from "../src/core/tokens.ts";
10 import { createUser } from "../src/core/users.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12
13 let dir: string;
14 let app: App;
15 let servers: Servers;
16 let token: string;
17
18 beforeAll(async () => {
19 dir = await mkdtemp(join(tmpdir(), "forge-smoke-real-"));
20 app = createApp({ dataDir: dir, port: 0 });
21 servers = await serve(app);
22 const r = await createUser(app.db, {
23 trusted: true, username: "alice", email: "[email protected]",
24 password: "a-good-passphrase", adminIfFirst: true,
25 });
26 if (!r.ok) throw new Error(r.error);
27 token = createToken(app.db, r.value.id, "smoke", "admin").token;
28 });
29
30 afterAll(async () => {
31 servers.stop();
32 app.close();
33 await rm(dir, { recursive: true, force: true });
34 });
35
36 test("a real forge passes, and /board with the token is 200", async () => {
37 expect(await smoke({ base: servers.url, token })).toEqual([]);
38 });
39
40 test("without a valid token /board fails", async () => {
41 const failures = await smoke({ base: servers.url, token: "forge_nope" });
42 expect(failures.map((f) => new URL(f.url).pathname)).toEqual(["/board", "/board"]);
43 });
test/smoke.test.ts added +76
@@ -0,0 +1,76 @@
1 /** scripts/smoke.ts against a stub forge on a loopback port (#2282). */
2
3 import { afterEach, expect, test } from "bun:test";
4 import { checkBase, smoke, waitForVersion } from "../scripts/smoke.ts";
5 import { swSource } from "../src/web/sw.ts";
6
7 let server: ReturnType<typeof Bun.serve> | undefined;
8 afterEach(() => server?.stop(true));
9
10 function stub(opts: { cssType?: string; sw?: string; board?: boolean } = {}): string {
11 server = Bun.serve({
12 port: 0,
13 hostname: "127.0.0.1",
14 fetch(req) {
15 const path = new URL(req.url).pathname;
16 if (path === "/") return new Response('<link rel="stylesheet" href="/assets/a.css">', { headers: { "content-type": "text/html" } });
17 if (path === "/assets/a.css") return new Response("body{}", { headers: { "content-type": opts.cssType ?? "text/css" } });
18 if (path === "/healthz") return new Response("ok", { headers: { "x-forge-version": "v1" } });
19 if (path === "/sw.js") return new Response(opts.sw ?? swSource, { headers: { "content-type": "text/javascript" } });
20 if (path === "/board")
21 return req.headers.get("authorization") === "Bearer t" && opts.board !== false
22 ? new Response("board")
23 : new Response(null, { status: 302, headers: { location: "/signin" } });
24 return new Response("no", { status: 404 });
25 },
26 });
27 return `http://127.0.0.1:${server.port}`;
28 }
29
30 test("a good forge passes under both agents", async () => {
31 expect(await smoke({ base: stub(), token: "t" })).toEqual([]);
32 });
33
34 test("a stylesheet served as text/html fails, naming url, agent, status and type", async () => {
35 const failures = await smoke({ base: stub({ cssType: "text/html" }), token: "t" });
36 expect(failures.length).toBe(2);
37 expect(failures[0]).toMatchObject({ status: 200, type: "text/html", agent: "iPhone Safari" });
38 expect(failures[0]?.url).toEndWith("/assets/a.css");
39 });
40
41 test("a redirect to sign-in on /board is a failure", async () => {
42 const failures = await smoke({ base: stub({ board: false }), token: "t" });
43 expect(failures.map((f) => f.status)).toEqual([302, 302]);
44 });
45
46 test("a navigation answered with Response.error() fails", async () => {
47 const sw = "if (request.mode === 'navigate') { return Response.error(); return; }";
48 expect((await smoke({ base: stub({ sw }), token: "t" })).length).toBe(2);
49 });
50
51 test("waitForVersion matches the header and gives up at the limit", async () => {
52 const base = stub();
53 expect(await waitForVersion(base, "v1", 1)).toBe(true);
54 expect(await waitForVersion(base, "v2", 0)).toBe(false);
55 });
56
57 test("plain http is refused off loopback unless --insecure; loopback and https are fine", () => {
58 expect(checkBase("http://forge.example.com", false)).toMatchObject({ ok: false });
59 expect(checkBase("http://forge.example.com", true)).toMatchObject({ ok: true });
60 expect(checkBase("http://127.0.0.1:3000", false)).toMatchObject({ ok: true });
61 expect(checkBase("http://localhost:3000", false)).toMatchObject({ ok: true });
62 expect(checkBase("https://forge.example.com", false)).toMatchObject({ ok: true });
63 expect(checkBase("ftp://127.0.0.1", true)).toMatchObject({ ok: false });
64 expect(checkBase(undefined, false)).toMatchObject({ ok: false });
65 });
66
67 test("the CLI exits 2 with the usage line and sends nothing for a remote http url", async () => {
68 const p = Bun.spawn(["bun", "scripts/smoke.ts", "http://forge.invalid"], {
69 env: { ...process.env, FORGE_TOKEN: "secret" }, stderr: "pipe", stdout: "pipe",
70 });
71 expect(await p.exited).toBe(2);
72 const err = await new Response(p.stderr).text();
73 expect(err).toContain("refusing");
74 expect(err).toContain("usage:");
75 expect(err).not.toContain("secret");
76 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs