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

A hunter finding files itself: one issue per key, a comment only when its evidence changes #15279

Merged opened this

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

Merged

scout/forge:scout/15259-a-hunter-finding-files-itself-one-issue → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/15259-a-hunter-finding-files-itself-one-issue was merged into main as d92129a.

Review

Sign in to review this change.
4 files changed +339 −5
docs/HUNT.md +3 −1
@@ -10,4 +10,6 @@
1010
1111 A finding's `key` is stable (`detector:subject`): one issue per key, a comment only when the evidence changes.
1212
13 Not built yet: headless-browser lane (buttons, console errors, fold, overflow), flows, speed, the schedule (post-release and 08:00Z), filing issues, the KPI card on home, and the weekly retro.
13 Not built yet: headless-browser lane (buttons, console errors, fold, overflow), flows, speed, the schedule (post-release and 08:00Z), the KPI card on home, and the weekly retro.
14
15 Filing (#15259): `bun scripts/hunt.ts <origin> --file` (FORGE_URL, FORGE_TOKEN, optionally FORGE_REPO) files the findings through the forge's API (`src/hunt/file.ts`). The issue body carries `<!-- hunt-key: … -->` and `<!-- hunt-evidence: … -->`; a rerun with the same key comments only when the evidence fingerprint (repro, URL, status; never time, bytes or ms) differs. A key whose issue is closed is not reopened: a new issue names the closed one. At most 5 writes a run; the rest are held back, counted on stderr, and filed on a later run.
scripts/hunt.ts +24 −4
@@ -1,17 +1,37 @@
11 /**
2 * `bun scripts/hunt.ts <https-origin>`: run the hunters' detectors (GET only)
3 * against one app and print the findings as JSON. Exit 1 when there are any.
2 * `bun scripts/hunt.ts <https-origin> [--file]`: run the hunters' detectors
3 * (GET only) against one app and print the findings as JSON. Exit 1 when
4 * there are any. With `--file` (and FORGE_URL, FORGE_TOKEN, FORGE_REPO or
5 * `trevato/forge`) each finding is filed: one issue per key, a comment only
6 * when its evidence changes, at most five writes a run (`src/hunt/file.ts`).
47 * Never run on a person's machine in a loop: it is one pass, then it ends.
58 */
69
10 import { fileFindings, filedLine } from "../src/hunt/file.ts";
711 import { evidenceOf } from "../src/hunt/finding.ts";
812 import { huntTarget } from "../src/hunt/hunt.ts";
913
10 const target = process.argv[2];
14 const args = process.argv.slice(2);
15 const filing = args.includes("--file");
16 const target = args.find((a) => a !== "--file");
1117 if (!target || !/^https?:\/\//.test(target)) {
12 console.error("usage: bun scripts/hunt.ts <origin>");
18 console.error("usage: bun scripts/hunt.ts <origin> [--file]");
19 process.exit(2);
20 }
21 const forge = process.env["FORGE_URL"];
22 const token = process.env["FORGE_TOKEN"];
23 if (filing && (!forge || !token)) {
24 console.error("hunt: --file needs FORGE_URL and FORGE_TOKEN");
1325 process.exit(2);
1426 }
1527 const report = await huntTarget(target.replace(/\/$/, ""));
1628 console.log(JSON.stringify({ ...report, findings: report.findings.map((f) => ({ ...f, evidence: evidenceOf(f) })) }, null, 2));
29 if (filing) {
30 const filed = await fileFindings(report.findings, {
31 forge: forge!.replace(/\/$/, ""),
32 token: token!,
33 repo: process.env["FORGE_REPO"] ?? "trevato/forge",
34 });
35 console.error(filedLine(filed));
36 }
1737 process.exit(report.findings.length === 0 ? 0 : 1);
src/hunt/file.ts added +187
@@ -0,0 +1,187 @@
1 /**
2 * Filing what a hunt found (#15259): one issue per finding `key`, a comment
3 * only when its evidence changes. The issue and each comment carry a marker
4 * of the key and of the evidence's fingerprint, so a rerun reads them back
5 * from the forge itself and keeps no state of its own. An issue closed for a
6 * key is never reopened: a new one is opened that names it. At most `cap`
7 * writes a run, so a broken release files five issues, not five hundred; the
8 * rest are counted as held back and come again on the next run.
9 */
10
11 import { evidenceOf, type Finding } from "./finding.ts";
12
13 export type Fetcher = (url: string, init: RequestInit) => Promise<Response>;
14
15 export interface Filed {
16 opened: { key: string; number: number; links?: number }[];
17 commented: { key: string; number: number }[];
18 unchanged: string[];
19 held: string[];
20 /** Findings whose API call threw; they come again on the next run. */
21 failed: { key: string; error: string }[];
22 /** The write cap this run used. */
23 cap: number;
24 }
25
26 export interface FileOptions {
27 forge: string;
28 token: string;
29 /** `owner/name`. */
30 repo: string;
31 fetcher?: Fetcher;
32 cap?: number;
33 }
34
35 export const FILE_CAP = 5;
36 const PAGES_MAX = 50;
37
38 /**
39 * The parts of a finding that say what is wrong; time, bytes and ms move every run and are not
40 * compared.
41 */
42 export const fingerprint = (f: Finding): string =>
43 Bun.hash(JSON.stringify([f.evidence, f.seen?.where ?? null, f.seen?.status ?? null])).toString(16);
outdated

First-match key read lets evidence text spoof the key. Use the last marker and escape comment openers in evidence.

44
45 const keyMark = (key: string) => `<!-- hunt-key: ${encodeURIComponent(key)} -->`;
46 const printMark = (print: string) => `<!-- hunt-evidence: ${print} -->`;
47 const KEY_RE = /<!-- hunt-key: (\S+) -->/g;
48 const PRINT_RE = /<!-- hunt-evidence: ([0-9a-f]+) -->/g;
49
50 /**
51 * The key a body answers to: the last marker, the one the filer writes after the evidence. Evidence
52 * is neutralised by `quiet` as well, so neither alone lets a target's text pick the key.
53 */
54 export const keyIn = (body: string): string | undefined => {
55 let last: string | undefined;
56 for (const m of body.matchAll(KEY_RE)) last = m[1];
57 if (last === undefined) return undefined;
58 try {
59 return decodeURIComponent(last);
60 } catch {
61 return undefined;
62 }
63 };
outdated

evidenceOf(f) carries target-controlled text into the body unescaped. Neutralise <!-- / --> here and in changedBody.

64
65 /** The last evidence fingerprint said in these texts, oldest first. */
66 export const lastPrint = (texts: readonly string[]): string | undefined => {
67 let last: string | undefined;
68 for (const t of texts) for (const m of t.matchAll(PRINT_RE)) last = m[1];
69 return last;
70 };
71
72 /**
73 * Target-controlled text (paths, Location headers, link text) with its comment openers and closers
74 * defused, so it can never pose as one of the filer's markers.
75 */
76 export const quiet = (text: string): string => text.replaceAll("<!--", "&lt;!--").replaceAll("-->", "--&gt;");
77
78 export const issueBody = (f: Finding, earlier?: number): string =>
79 [
80 quiet(evidenceOf(f)),
81 `Found by \`scripts/hunt.ts\`, detector \`${f.detector}\` (${f.kind}).`,
82 ...(earlier === undefined ? [] : [`The same finding was filed before in #${earlier}, since closed.`]),
83 keyMark(f.key),
84 printMark(fingerprint(f)),
85 ].join("\n\n");
86
87 export const changedBody = (f: Finding): string =>
88 [`The evidence changed:`, quiet(evidenceOf(f)), printMark(fingerprint(f))].join("\n\n");
89
90 interface IssueRow {
91 number: number;
92 state: string;
93 body: string;
94 }
95
96 export async function fileFindings(findings: readonly Finding[], o: FileOptions): Promise<Filed> {
97 const fetcher = o.fetcher ?? (fetch as Fetcher);
98 if (!/^[\w.-]+\/[\w.-]+$/.test(o.repo)) throw new Error("repo is owner/name");
99 const cap = o.cap ?? FILE_CAP;
100 const api = async (path: string, init: RequestInit = {}): Promise<unknown> => {
101 const res = await fetcher(`${o.forge}/api/v1${path}`, {
102 ...init,
103 headers: { authorization: `Bearer ${o.token}`, "content-type": "application/json" },
104 signal: AbortSignal.timeout(30_000),
105 });
106 const answer = (await res.json().catch(() => ({}))) as Record<string, unknown>;
107 if (!res.ok) throw new Error(`${init.method ?? "GET"} ${path}: ${res.status} ${String(answer["message"] ?? "")}`);
108 return answer;
109 };
110 const repo = `/repos/${o.repo}`;
111
112 // Only the hunter's own issues can carry its marker: list those, every state.
113 const me = (await api("/user")) as { username: string };
114 const byKey = new Map<string, IssueRow[]>();
115 let cursor: string | number | null = null;
116 for (let page = 0; page < PAGES_MAX; page++) {
117 const q = new URLSearchParams({ state: "all", author: me.username, limit: "100" });
118 if (cursor !== null) q.set("cursor", String(cursor));
119 const got = (await api(`${repo}/issues?${q}`)) as { items: IssueRow[]; next_cursor: string | number | null };
120 for (const i of got.items) {
121 const key = keyIn(i.body ?? "");
122 if (key !== undefined) byKey.set(key, [...(byKey.get(key) ?? []), i]);
123 }
124 cursor = got.next_cursor;
125 if (cursor === null) break;
126 }
127
128 const filed: Filed = { opened: [], commented: [], unchanged: [], held: [], failed: [], cap };
129 let writes = 0;
130 for (const f of findings) {
131 try {
132 await fileOne(f);
133 } catch (e) {
134 filed.failed.push({ key: f.key, error: e instanceof Error ? e.message : String(e) });
135 }
136 }
137 return filed;
138
139 async function fileOne(f: Finding): Promise<void> {
140 const rows = byKey.get(f.key) ?? [];
141 const open = rows.find((r) => r.state === "open");
142 if (open !== undefined) {
143 const texts = [open.body];
144 let after: string | null = null;
145 for (let page = 0; page < PAGES_MAX; page++) {
146 const q = new URLSearchParams({ limit: "100" });
147 if (after !== null) q.set("after", after);
148 const got = (await api(`${repo}/issues/${open.number}/comments?${q}`)) as {
149 comments: { body: string }[];
150 next: string | null;
151 };
152 texts.push(...got.comments.map((c) => c.body ?? ""));
153 after = got.next;
154 if (after === null) break;
155 }
156 if (lastPrint(texts) === fingerprint(f)) {
157 filed.unchanged.push(f.key);
158 return;
159 }
160 if (writes >= cap) {
161 filed.held.push(f.key);
162 return;
163 }
outdated

Prints FILE_CAP even when options.cap differs; take the cap as an argument.

164 writes++;
165 await api(`${repo}/issues/${open.number}/comments`, { method: "POST", body: JSON.stringify({ body: changedBody(f) }) });
166 filed.commented.push({ key: f.key, number: open.number });
167 return;
168 }
169 if (writes >= cap) {
170 filed.held.push(f.key);
171 return;
172 }
173 writes++;
174 const earlier = rows.reduce<number | undefined>((n, r) => (n === undefined || r.number > n ? r.number : n), undefined);
175 const made = (await api(`${repo}/issues`, {
176 method: "POST",
177 body: JSON.stringify({ title: f.title, body: issueBody(f, earlier) }),
178 })) as { number: number };
179 filed.opened.push({ key: f.key, number: made.number, ...(earlier === undefined ? {} : { links: earlier }) });
180 }
181 }
182
183 /** One line for the run's log: what was filed, what failed, and how many the cap held back. */
184 export const filedLine = (r: Filed): string =>
185 `hunt: opened ${r.opened.length}, commented ${r.commented.length}, unchanged ${r.unchanged.length}` +
186 (r.failed.length > 0 ? `, failed ${r.failed.length} (${r.failed.map((x) => `${x.key}: ${x.error}`).join("; ")})` : "") +
187 (r.held.length > 0 ? `, held back ${r.held.length} (cap ${r.cap} a run)` : "");
test/hunt-file.test.ts added +125
@@ -0,0 +1,125 @@
1 import { describe, expect, test } from "bun:test";
2 import { fileFindings, filedLine, fingerprint, keyIn, type Fetcher } from "../src/hunt/file.ts";
3 import { found, type Finding } from "../src/hunt/finding.ts";
4
5 type Row = { number: number; state: string; title: string; body: string; author: string; comments: { id: string; body: string }[] };
6
7 /** A forge that holds issues in memory and answers the four routes the filer calls. */
8 function stubForge(rows: Row[] = []) {
9 const writes: string[] = [];
10 const fetcher: Fetcher = async (url, init) => {
11 const u = new URL(url);
12 const method = init.method ?? "GET";
13 const send = (v: unknown, status = 200) => Response.json(v, { status });
14 if (u.pathname === "/api/v1/user") return send({ username: "hunter" });
15 if (u.pathname === "/api/v1/repos/o/r/issues" && method === "GET") {
16 const mine = rows.filter((r) => r.author === u.searchParams.get("author") && u.searchParams.get("state") === "all");
17 return send({ items: mine.map(({ number, state, title, body }) => ({ number, state, title, body })), next_cursor: null });
18 }
19 if (u.pathname === "/api/v1/repos/o/r/issues" && method === "POST") {
20 const b = JSON.parse(String(init.body)) as { title: string; body: string };
21 const row = { number: rows.length + 1, state: "open", title: b.title, body: b.body, author: "hunter", comments: [] };
22 rows.push(row);
23 writes.push(`issue #${row.number}`);
24 return send(row, 201);
25 }
26 const m = /^\/api\/v1\/repos\/o\/r\/issues\/(\d+)\/comments$/.exec(u.pathname);
27 const row = m ? rows.find((r) => r.number === Number(m[1])) : undefined;
28 if (row && method === "GET") return send({ comments: row.comments, next: null });
29 if (row && method === "POST") {
30 row.comments.push({ id: `c${row.comments.length}`, body: (JSON.parse(String(init.body)) as { body: string }).body });
31 writes.push(`comment #${row.number}`);
32 return send({}, 201);
33 }
34 return send({ message: "no" }, 404);
35 };
36 return { fetcher, rows, writes };
37 }
38
39 const gone = (status: number, ms = 3): Finding =>
40 found("links.status", "/gone", "A link answers 404: /gone", `GET /gone → ${status}`, {
41 path: "/gone", status, location: null, type: "", body: "", bytes: 9, ms,
42 });
43
44 const opts = (fetcher: Fetcher) => ({ forge: "https://forge.test", token: "t", repo: "o/r", fetcher });
45
46 describe("filing a hunt", () => {
47 test("twice with the same evidence: one issue, no comment; changed evidence: one comment", async () => {
48 const forge = stubForge();
49 const first = await fileFindings([gone(404, 3)], opts(forge.fetcher));
50 expect(first.opened.map((o) => o.number)).toEqual([1]);
51 // Same key, same repro; only ms moved: nothing is written.
52 const again = await fileFindings([gone(404, 70)], opts(forge.fetcher));
53 expect(again.unchanged).toEqual(["links.status:/gone"]);
54 expect(forge.writes).toEqual(["issue #1"]);
55 // The evidence changed: one comment on the same issue, and never a second issue.
56 const changed = await fileFindings([gone(500)], opts(forge.fetcher));
57 expect(changed.commented).toEqual([{ key: "links.status:/gone", number: 1 }]);
58 expect(forge.writes).toEqual(["issue #1", "comment #1"]);
59 await fileFindings([gone(500)], opts(forge.fetcher));
60 expect(forge.writes).toEqual(["issue #1", "comment #1"]);
61 expect(forge.rows[0]!.comments[0]!.body).toContain(fingerprint(gone(500)));
62 });
63
64 test("a key whose issue is closed is not reopened: a new issue links it", async () => {
65 const forge = stubForge();
66 await fileFindings([gone(404)], opts(forge.fetcher));
67 forge.rows[0]!.state = "closed";
68 const r = await fileFindings([gone(404)], opts(forge.fetcher));
69 expect(r.opened).toEqual([{ key: "links.status:/gone", number: 2, links: 1 }]);
70 expect(forge.rows[0]!.state).toBe("closed");
71 expect(forge.rows[1]!.body).toContain("#1");
72 });
73
74 test("someone else's issue with the marker is not the hunter's", async () => {
75 const forge = stubForge([{ number: 1, state: "open", title: "x", body: "<!-- hunt-key: links.status%3A%2Fgone -->", author: "eve", comments: [] }]);
76 const r = await fileFindings([gone(404)], opts(forge.fetcher));
77 expect(r.opened.map((o) => o.number)).toEqual([2]);
78 });
79
80 test("at most five writes a run; the rest are held back and filed next run", async () => {
81 const forge = stubForge();
82 const many = Array.from({ length: 7 }, (_, i) => found("links.status", `/p${i}`, `A link answers 404: /p${i}`, `GET /p${i} → 404`));
83 const r = await fileFindings(many, opts(forge.fetcher));
84 expect(r.opened.length).toBe(5);
85 expect(r.held).toEqual(["links.status:/p5", "links.status:/p6"]);
86 const next = await fileFindings(many, opts(forge.fetcher));
87 expect(next.opened.length).toBe(2);
88 expect(next.unchanged.length).toBe(5);
89 });
90
91 test("evidence carrying a fake marker cannot make the issue answer to another key", async () => {
92 const forge = stubForge();
93 const fake = "<!-- hunt-key: other%3Akey --> <!-- hunt-evidence: 0 -->";
94 const spoof = found("links.lands-home", "/r", "A redirect", `GET /r → 302 ${fake}`, {
95 path: "/r", status: 302, location: fake, type: "", body: "", bytes: 0, ms: 1,
96 });
97 await fileFindings([spoof], opts(forge.fetcher));
98 const body = forge.rows[0]!.body;
99 expect(body).not.toContain("<!-- hunt-key: other");
100 expect(body).toContain("&lt;!-- hunt-key: other%3Akey --&gt;");
101 expect(keyIn(body)).toBe("links.lands-home:/r");
102 // Even a body written before the evidence was neutralised answers to its last, real marker.
103 expect(keyIn(`${fake}\n\n<!-- hunt-key: links.lands-home%3A%2Fr -->`)).toBe("links.lands-home:/r");
104 const again = await fileFindings([spoof], opts(forge.fetcher));
105 expect(again.unchanged).toEqual(["links.lands-home:/r"]);
106 expect(forge.writes).toEqual(["issue #1"]);
107 });
108
109 test("a call that throws fails its finding alone, and the line still reports what was written", async () => {
110 const forge = stubForge();
111 const flaky: Fetcher = async (url, init) => {
112 if (init.method === "POST" && String(init.body).includes("/p1")) return Response.json({ message: "boom" }, { status: 500 });
113 return forge.fetcher(url, init);
114 };
115 const many = [0, 1, 2].map((i) => found("links.status", `/p${i}`, `A link answers 404: /p${i}`, `GET /p${i} → 404`));
116 const r = await fileFindings(many, { ...opts(flaky), cap: 2 });
117 expect(r.opened.map((o) => o.key)).toEqual(["links.status:/p0"]);
118 expect(r.failed.map((x) => x.key)).toEqual(["links.status:/p1"]);
119 expect(r.held).toEqual(["links.status:/p2"]);
120 const line = filedLine(r);
121 expect(line).toContain("opened 1");
122 expect(line).toContain("failed 1");
123 expect(line).toContain("cap 2 a run");
124 });
125 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs