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

An outsider who files a report or offers a pull gets a status link they can open without an account #15783

Merged opened this

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

Merged

scout/forge:scout/15768-an-outsider-who-files-a-report-or-offers → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/15768-an-outsider-who-files-a-report-or-offers was merged into main as e28e113.

Review

Sign in to review this change.
20 files changed +437 −3
docs/features/report-status.md +8
@@ -28,4 +28,12 @@ then `curl -s` the `statusUrl`.
2828
2929 Not limited yet: the status route has no rate limit of its own; that is tracked in #14500.
3030
31 ## The 90-day status link (#15768)
32
33 The answer to a report or an offer (`…/offers`, the MCP `offer` tool) also carries `statusPage` and `statusJson`: `/status/<token>` and `/api/v1/status/<token>`.
34
35 - **Shows:** `kind`, `state` (received, read, planned, landed or declined), its words, and the dates it arrived, last changed and expires. Never the title, the words, a name or an id.
36 - **States:** a report is received until a person decides; accepting makes it planned, closing that issue makes it landed (done) or declined (dropped); dismissing declines it. An offer is received, then read once a reviewer reviews, then landed or declined. So a report is never `read` (a person's decision is its first change) and an offer is never `planned`; each shows only the states its own steps can reach.
37 - **The token:** 192 random bits, read-only, good 90 days; a wrong, malformed or expired one is a 404 (`src/core/outsider_status.ts`, `src/http/offer_routes.ts`). The status routes answer 429 past 60 reads a minute per client, and links past their day are deleted hourly. Pinned by `test/outsider-status.test.ts`.
38
3139 Pinned by `test/report-status.test.ts`.
src/actions/offer.ts +4 −1
@@ -28,6 +28,7 @@ import type { App } from "../app.ts";
2828 import { commitIdentity } from "../core/commit_identity.ts";
2929 import { isContributionFork } from "../core/contribute.ts";
3030 import { issueReceipt } from "../core/offer_receipt.ts";
31 import { issueStatusToken } from "../core/outsider_status.ts";
3132 import { type Pull } from "../core/pulls.ts";
3233 import { plainText } from "../core/reports.ts";
3334 import { RateLimiter } from "../core/ratelimit.ts";
@@ -117,6 +118,8 @@ export interface Offered {
117118 readonly pull: Pull;
118119 /** The random id the sender reads the offer's state by. */
119120 readonly receipt: string;
121 /** The token of the plain status page and JSON (`core/outsider_status.ts`). */
122 readonly statusToken: string;
120123 }
121124
122125 interface Limits {
@@ -298,5 +301,5 @@ export async function fileOffer(
298301 await runGit(["update-ref", "-d", `refs/heads/${branch}`], { cwd: dir });
299302 return err({ error: "unavailable" });
300303 }
301 return ok({ number: opened.value.number, pull: opened.value, receipt: issueReceipt(app.db, opened.value.id) });
304 return ok({ number: opened.value.number, pull: opened.value, receipt: issueReceipt(app.db, opened.value.id), statusToken: issueStatusToken(app.db, "offer", opened.value.id) });
302305 }
src/contract/openapi/routes/getApiV1StatusToken.ts added +13
@@ -0,0 +1,13 @@
1 import { type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: "/api/v1/status/{token}",
6 summary: "Read the state of a report or offered patch by the status link its filing returned",
7 detail:
8 "Read the state and dates of one report or offered patch by the random 90-day token its filing returned, without an account; shows only that state, nothing the outsider wrote, and a wrong, malformed or expired token is one 404",
9 auth: false,
10 role: "anonymous",
11 refusals: { not_found: "404: no live status link has this token" },
12 refuses: [404],
13 };
src/contract/openapi/routes/index.ts +1
@@ -221,6 +221,7 @@ export { route as getApiV1Returns } from "./getApiV1Returns.ts";
221221 export { route as getApiV1RunnerJobsIdGitInfoRefs } from "./getApiV1RunnerJobsIdGitInfoRefs.ts";
222222 export { route as getApiV1Search } from "./getApiV1Search.ts";
223223 export { route as getApiV1SecretsScope } from "./getApiV1SecretsScope.ts";
224 export { route as getApiV1StatusToken } from "./getApiV1StatusToken.ts";
224225 export { route as getApiV1TelemetryFlow } from "./getApiV1TelemetryFlow.ts";
225226 export { route as getApiV1TelemetryHeapCensus } from "./getApiV1TelemetryHeapCensus.ts";
226227 export { route as getApiV1TelemetryHistory } from "./getApiV1TelemetryHistory.ts";
src/contract/tags.ts +1
@@ -102,6 +102,7 @@ const ALIAS: Readonly<Record<string, string>> = {
102102 drop: "apps",
103103 security: "reports",
104104 deepsec: "reports",
105 status: "reports",
105106 };
106107
107108 /** One line on each tag the document lists. */
src/core/migration-pins/20261123090000-outsider-status.pin added +1
@@ -0,0 +1,1 @@
1 a04acdc4b2dc852243197bb944b09664a22e631555b6dd87d3a3c88464e1913c
src/core/migrations/20261123090000-outsider-status.ts added +12
@@ -0,0 +1,12 @@
1 // An outsider's report or offer is given an unguessable status token (#15768) that shows what
2 // became of it, with no account, for 90 days. `ref_id` is the report's or the pull issue's id.
3 export default `
4 CREATE TABLE outsider_status (
5 token TEXT PRIMARY KEY,
6 kind TEXT NOT NULL CHECK (kind IN ('report','offer')),
7 ref_id TEXT NOT NULL,
8 created_at TEXT NOT NULL,
9 expires_at TEXT NOT NULL
10 );
11 CREATE INDEX outsider_status_expiry ON outsider_status (expires_at);
12 `;
src/core/outsider_status.ts added +128
@@ -0,0 +1,128 @@
1 /**
2 * What became of an outsider's report or offer (#15768): an unguessable, read-only token, good for
3 * 90 days, that names one report or one offer's pull and shows its state with dates, and
4 * nothing private: no title, no words, no names, no ids but the token itself.
5 *
6 * States, in the order a thing can reach them: received, read, planned, landed, declined.
7 * A report is received until a person decides; accepting it makes it planned (an open issue),
8 * and closing that issue makes it landed (done) or declined (dropped); dismissing declines it.
9 * An offer is received until a reviewer leaves a review (read), then landed or declined.
10 * So a report is never "read" (a person's decision is its first state change) and an offer is
11 * never "planned" (no step marks one taken up before it lands); `docs/features/report-status.md`
12 * says so.
13 */
14 import type { Database } from "bun:sqlite";
15 import { getIssueById } from "./issues.ts";
16 import { getPull } from "./pulls.ts";
17 import { listReviews } from "./reviews.ts";
18
19 export type OutsiderState = "received" | "read" | "planned" | "landed" | "declined";
20 export type OutsiderKind = "report" | "offer";
21
22 export const STATUS_TTL_MS = 90 * 24 * 60 * 60 * 1000;
23
24 export const OUTSIDER_STATE_WORDS: Readonly<Record<OutsiderState, string>> = {
25 received: "A person who maintains this repository has not read it yet.",
26 read: "A person who maintains this repository has read it.",
27 planned: "A person took it up and it is planned.",
28 landed: "It was done and is part of the repository.",
29 declined: "A person decided not to act on it.",
30 };
31
32 export interface OutsiderStatus {
33 readonly kind: OutsiderKind;
34 readonly state: OutsiderState;
35 readonly words: string;
36 /** When it arrived. */
37 readonly received: string;
38 /** When its state last changed, or null while it is only received. */
39 readonly updated: string | null;
40 /** After this the token answers 404. */
41 readonly expires: string;
42 }
43
44 /** 192 random bits, hex: never derived from a number, a clock or the thing's own id. */
45 const newToken = (): string => {
46 return Buffer.from(crypto.getRandomValues(new Uint8Array(24))).toString("hex");
47 };
48
49 /** Keep a status token for a report id or an offer's pull issue id; returns the token. */
50 export function issueStatusToken(db: Database, kind: OutsiderKind, refId: string, now = Date.now()): string {
outdated

Rows are never deleted after expiry; prune them in the existing maintenance sweep.

51 const token = newToken();
52 db.query("INSERT INTO outsider_status (token, kind, ref_id, created_at, expires_at) VALUES (?1, ?2, ?3, ?4, ?5)").run(
53 token,
54 kind,
55 refId,
56 new Date(now).toISOString(),
57 new Date(now + STATUS_TTL_MS).toISOString(),
58 );
59 return token;
60 }
61
62 /** Drop the links past their day; a dead token already answers 404, so this only frees rows. */
63 export function pruneOutsiderStatus(db: Database, now = Date.now()): number {
64 return db.query("DELETE FROM outsider_status WHERE expires_at <= ?1").run(new Date(now).toISOString()).changes;
65 }
66
67 interface ReportRow {
68 state: "pending" | "accepted" | "dismissed";
69 decided_at: string | null;
70 issue_state: string | null;
71 close_reason: string | null;
72 closed_at: string | null;
73 }
74
75 function ofReport(db: Database, id: string): { state: OutsiderState; updated: string | null } | undefined {
76 const row = db
77 .query<ReportRow, [string]>(
78 `SELECT report.state, report.decided_at, issue.state AS issue_state, issue.close_reason, issue.closed_at
79 FROM report LEFT JOIN issue ON issue.repo_id = report.repo_id AND issue.number = report.issue_number
80 WHERE report.id = ?1`,
81 )
82 .get(id);
83 if (row === null) return undefined;
84 if (row.state === "pending") return { state: "received", updated: null };
85 if (row.state === "dismissed") return { state: "declined", updated: row.decided_at };
86 if (row.issue_state !== "closed") return { state: "planned", updated: row.decided_at };
87 if (row.close_reason === "dropped") return { state: "declined", updated: row.closed_at };
88 if (row.close_reason === null || row.close_reason === "done") return { state: "landed", updated: row.closed_at };
89 return { state: "planned", updated: row.decided_at };
90 }
91
92 function ofOffer(db: Database, issueId: string): { state: OutsiderState; updated: string | null } {
93 const issue = getIssueById(db, issueId);
94 const pull = issue === undefined ? undefined : getPull(db, issue.repoId, issue.number);
95 if (pull === undefined) return { state: "declined", updated: issue?.closedAt ?? null };
96 if (pull.mergedAt !== null) return { state: "landed", updated: pull.mergedAt };
97 if (pull.state === "closed") return { state: "declined", updated: issue?.closedAt ?? null };
98 const reviews = listReviews(db, pull.id);
99 if (reviews.length === 0) return { state: "received", updated: null };
100 return { state: "read", updated: reviews.reduce((a, r) => (r.createdAt > a ? r.createdAt : a), "") || null };
101 }
102
103 /** The status a token shows now; undefined for a wrong, malformed or expired token. */
104 export function readOutsiderStatus(db: Database, token: string, now = Date.now()): OutsiderStatus | undefined {
105 if (!/^[0-9a-f]{48}$/.test(token)) return undefined;
106 const row = db
107 .query<{ kind: OutsiderKind; ref_id: string; created_at: string; expires_at: string }, [string]>(
108 "SELECT kind, ref_id, created_at, expires_at FROM outsider_status WHERE token = ?1",
109 )
110 .get(token);
111 if (row === null || Date.parse(row.expires_at) <= now) return undefined;
112 const got = row.kind === "report" ? ofReport(db, row.ref_id) : ofOffer(db, row.ref_id);
113 if (got === undefined) return undefined;
114 return {
115 kind: row.kind,
116 state: got.state,
117 words: OUTSIDER_STATE_WORDS[got.state],
118 received: row.created_at,
119 updated: got.updated,
120 expires: row.expires_at,
121 };
122 }
123
124 /** Where a filer reads it: the page, and the same answer as JSON. */
125 export const statusLinks = (origin: string, token: string): { page: string; json: string } => ({
126 page: `${origin}/status/${token}`,
127 json: `${origin}/api/v1/status/${token}`,
128 });
src/engine/duties.ts +3
@@ -20,6 +20,7 @@ import { settleDue } from "../actions/estimates_settle.ts";
2020 import { returnSnoozed } from "../actions/gate_snooze.ts";
2121 import { sweepStarts } from "../actions/start_sweep.ts";
2222 import { runDelivery } from "../core/webhooks.ts";
23 import { pruneOutsiderStatus } from "../core/outsider_status.ts";
2324 import { pruneSessions } from "../core/sessions.ts";
2425 import { pruneTokens } from "../core/tokens.ts";
2526 import { getRepoById } from "../core/repos.ts";
@@ -59,6 +60,8 @@ export function startDuties(app: App, options: { onWorker: boolean }): () => voi
5960 during("delivery", delivery, undefined, app);
6061 // Estimates of "done" come due as time passes (#11955).
6162 timers.push(setInterval(() => during("estimates-due", () => void settleDue(app.db), undefined, app), 300_000));
63 // Outsider status links past their 90 days are freed on a slow tick (#15768).
64 timers.push(setInterval(() => during("outsider-status-prune", () => void pruneOutsiderStatus(app.db), undefined, app), 3_600_000));
6265 // An issue snoozed behind the Later gate comes back on its day (#13113).
6366 timers.push(setInterval(() => during("gate-snooze", () => void returnSnoozed(app), undefined, app), 60_000));
6467 during("gate-snooze", () => void returnSnoozed(app), undefined, app);
src/http/api.ts +2
@@ -359,6 +359,7 @@ import { deepsecRoutes } from "./api/deepsec.ts";
359359 import { appNoteRoutes } from "./api/app_notes.ts";
360360 import { reportRoutes } from "./api/reports.ts";
361361 import { offerHandler, offerStatusHandler } from "./offer_routes.ts";
362 import { outsiderStatusJson } from "./offer_routes.ts";
362363 import { startRoutes } from "./api/start.ts";
363364 import { rollbackRoutes } from "./api/rollback.ts";
364365 import { takeBackRoutes } from "./api/take_back.ts";
@@ -2220,6 +2221,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
22202221 reportRoutes(router);
22212222 router.add("POST", "/api/v1/repos/:owner/:name/offers", offerHandler);
22222223 router.add("GET", "/api/v1/offers/:receipt", offerStatusHandler);
2224 router.add("GET", "/api/v1/status/:token", outsiderStatusJson);
22232225 startRoutes(router);
22242226 appNoteRoutes(router);
22252227 rollbackRoutes(router);
src/http/marks/api-v1-status.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/api/v1/status",
3 "mark": "open"
4 }
src/http/mcp/offer.ts +2
@@ -70,6 +70,8 @@ export async function offerAnswer(ctx: Ctx, id: unknown, args: Args): Promise<un
7070 state: "open",
7171 receipt: filed.value.receipt,
7272 status: `${ctx.url.origin}/api/v1/offers/${filed.value.receipt}`,
73 statusPage: `${ctx.url.origin}/status/${filed.value.statusToken}`,
74 statusJson: `${ctx.url.origin}/api/v1/status/${filed.value.statusToken}`,
7375 url: `${ctx.url.origin}/${repo.ownerName}/${repo.name}/pulls/${filed.value.number}`,
7476 message: OFFER_RECEIVED,
7577 }),
src/http/offer_routes.ts +61 −1
@@ -12,11 +12,16 @@ import {
1212 OFFER_WORDS,
1313 type OfferRefusal,
1414 } from "../actions/offer.ts";
15 import { readOutsiderStatus, statusLinks, type OutsiderStatus } from "../core/outsider_status.ts";
1516 import { readReceipt } from "../core/offer_receipt.ts";
1617 import { canRead, getRepo } from "../core/repos.ts";
18 import { notFoundPage } from "../web/chrome.ts";
19 import { escapeHtml } from "../web/html.ts";
20 import { RateLimiter } from "../core/ratelimit.ts";
21 import type { App } from "../app.ts";
1722 import type { Handler } from "./context.ts";
1823 import { clientBucket } from "./peer.ts";
19 import { apiError, boundedBody, json, notFound, str as bodyStr, tryAgain } from "./respond.ts";
24 import { apiError, boundedBody, json, notFound, securityFloor, str as bodyStr, tryAgain } from "./respond.ts";
2025 import { PATCH_TEXT } from "./parseable_request.ts";
2126
2227 /** A full queue drains as people read offers; no clock says when, so a minute. */
@@ -47,12 +52,15 @@ export const offerHandler: Handler = async (ctx) => {
4752 const why: OfferRefusal = refusal.error;
4853 return json({ error: why, message: `${OFFER_WORDS[why]}; ${OFFER_HINT}` }, 422);
4954 }
55 const links = statusLinks(ctx.url.origin, filed.value.statusToken);
5056 return json(
5157 {
5258 number: filed.value.number,
outdated

Calls statusLinks twice with the same token; compute once. Also move the local escape helper to the repo's shared escaper.

5359 state: "open",
5460 receipt: filed.value.receipt,
5561 status: `${ctx.url.origin}/api/v1/offers/${filed.value.receipt}`,
62 statusPage: links.page,
63 statusJson: links.json,
5664 url: `${ctx.url.origin}/${repo.ownerName}/${repo.name}/pulls/${filed.value.number}`,
5765 message: OFFER_RECEIVED,
5866 },
@@ -68,3 +76,55 @@ export const offerStatusHandler: Handler = (ctx) => {
6876 const found = readReceipt(ctx.app.db, ctx.params.receipt!);
6977 return found === undefined ? notFound() : json(found, 200, { "cache-control": "no-store" });
7078 };
79
80 /**
81 * The status link an outsider is handed (#15768): `GET /status/:token` as a plain page,
82 * `GET /api/v1/status/:token` as JSON; a wrong, malformed or expired token is one 404. The page has
83 * no script, no style, every word escaped.
84 */
85 const escape = escapeHtml;
86
87 const day = (iso: string): string => iso.slice(0, 10);
88
89 function pageOf(s: OutsiderStatus): string {
90 const what = s.kind === "report" ? "report" : "offered change";
91 const rows = [`<li>Received: ${escape(day(s.received))}</li>`];
92 if (s.updated !== null) rows.push(`<li>${escape(s.state[0]!.toUpperCase() + s.state.slice(1))}: ${escape(day(s.updated))}</li>`);
93 return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>Your ${what}: ${escape(s.state)}</title></head><body><main><h1>Your ${what}: ${escape(s.state)}</h1><p>${escape(s.words)}</p><ul>${rows.join("")}</ul><p>This link works until ${escape(day(s.expires))}. It shows only this state: nothing you wrote.</p></main></body></html>`;
94 }
95
96 /**
97 * Reads are counted per client, 60 a minute, for both routes together: a 192-bit token cannot be
98 * guessed, so this only keeps a loop from hammering the table. A refused read counts nothing.
99 */
100 const limiters = new WeakMap<App, RateLimiter>();
101 const STATUS_PER_MINUTE = 60;
102
103 function found(ctx: Parameters<Handler>[0]): OutsiderStatus | undefined | "slow" {
104 let limiter = limiters.get(ctx.app);
105 if (limiter === undefined) {
106 limiter = new RateLimiter({ perMinute: STATUS_PER_MINUTE, adminPerMinute: STATUS_PER_MINUTE, enabled: true });
107 limiters.set(ctx.app, limiter);
108 }
109 if (!limiter.take(clientBucket(ctx.request), "ro").allowed) return "slow";
110 return readOutsiderStatus(ctx.app.db, ctx.params.token ?? "");
111 }
112
113 const slow = (): Response => tryAgain("rate_limited", 429, "too many status reads; wait a minute", 60);
114
115 export const outsiderStatusPage: Handler = (ctx) => {
116 const status = found(ctx);
117 if (status === "slow") return slow();
118 if (status === undefined) return notFoundPage(ctx);
119 return securityFloor(
120 new Response(pageOf(status), {
121 headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "referrer-policy": "no-referrer" },
122 }),
123 );
124 };
125
126 export const outsiderStatusJson: Handler = (ctx) => {
127 const status = found(ctx);
128 if (status === "slow") return slow();
129 return status === undefined ? notFound() : json(status, 200, { "cache-control": "no-store" });
130 };
src/http/report_filer.ts +11
@@ -8,6 +8,7 @@
88 * files anonymously, or as a claim.
99 */
1010 import { REPORT_NEXT_STEP, REPORT_RECEIVED } from "../actions/report_words.ts";
11 import { issueStatusToken, statusLinks } from "../core/outsider_status.ts";
1112 import type { Report } from "../core/reports.ts";
1213 import type { Repo } from "../core/repos.ts";
1314 import type { User } from "../core/users.ts";
@@ -40,6 +41,12 @@ export interface Receipt {
4041 readonly url: string;
4142 /** Public, no account: GET answers open / being worked / fixed / declined. */
4243 readonly statusUrl: string;
44 /**
45 * A plain page and its JSON, good 90 days, showing the state with dates
46 * (`core/outsider_status.ts`).
47 */
48 readonly statusPage: string;
49 readonly statusJson: string;
4350 readonly message: string;
4451 readonly next: string;
4552 }
@@ -59,6 +66,7 @@ export const statusUrlOf = (origin: string, repo: Repo, reportId: string): strin
5966 `${origin}/api/v1/repos/${encodeURIComponent(repo.ownerName)}/${encodeURIComponent(repo.name)}/reports/${reportId}/status`;
6067
6168 export function receiptOf(ctx: Ctx, repo: Repo, report: Report): Receipt {
69 const links = statusLinks(publicOrigin(ctx), issueStatusToken(ctx.app.db, "report", report.id));
6270 return {
6371 id: report.id,
6472 state: report.state,
@@ -67,6 +75,8 @@ export function receiptOf(ctx: Ctx, repo: Repo, report: Report): Receipt {
6775 number: null,
6876 url: `${publicOrigin(ctx)}/${encodeURIComponent(repo.ownerName)}/${encodeURIComponent(repo.name)}/report?sent=${report.id}`,
6977 statusUrl: statusUrlOf(publicOrigin(ctx), repo, report.id),
78 statusPage: links.page,
79 statusJson: links.json,
7080 message: REPORT_RECEIVED,
7181 next: REPORT_NEXT_STEP,
7282 };
@@ -79,6 +89,7 @@ export function receiptText(r: Receipt): string {
7989 `issue: ${r.issue === null ? "none yet" : `#${r.issue}`}`,
8090 `url: ${r.url}`,
8191 `status: ${r.statusUrl}`,
92 `page: ${r.statusPage}`,
8293 `state: ${r.state}`,
8394 r.message,
8495 r.next,
src/http/server.ts +2
@@ -5,6 +5,7 @@
55 * verdict. Auth is resolved once per request and handed to handlers as data.
66 */
77
8 import { outsiderStatusPage } from "./offer_routes.ts";
89 import { standingFragment } from "../web/pages/fork-standing.ts";
910 import { InvalidJson } from "./json_body.ts";
1011 import { answeringFor, ControlInput, controlRefusal, dirtyUrl, parseableRequest } from "./parseable_request.ts";
@@ -1116,6 +1117,7 @@ export function buildRouter(): Router<Handler> {
11161117 router.add("GET", "/templates/:owner/:name", templatePage);
11171118 router.add("GET", "/security", publicSecurityPage);
11181119 router.add("GET", "/status", statusPage);
1120 router.add("GET", "/status/:token", outsiderStatusPage);
11191121 router.add("GET", "/docs", docsFolder);
11201122 router.add("GET", "/docs/:file", docsFile);
11211123 router.add("GET", "/docs/features/:file", docsFeature);
test/job-slices.test.ts +1
@@ -289,6 +289,7 @@ const UNTIMED: Record<string, string> = {
289289 "origin-broker-sweep": "a one-shot timer a minute after a brokered sign-in, and once on boot: one DELETE of its spent and expired rows; the fixture brokers none",
290290 "child-db-deadline": "a one-shot timer in spawn/child_db.ts that ends a read of a child's database past its deadline: it ends a reader process; the fixture has no children",
291291 "estimates-due": "settles due 'done' estimates every five minutes from one indexed query on open estimates; the fixture records none",
292 "outsider-status-prune": "frees outsider status links past 90 days, one indexed delete an hour (core/outsider_status.ts); the fixture has no links",
292293 snapshot: "copies the database file to disk (VACUUM INTO): I/O off the loop, nightly",
293294 "snapshot-mirror": "uploads a snapshot to the mirror: network, nightly",
294295 drill: "restores a snapshot into a scratch forge: nightly, I/O",
test/no-polling.test.ts +1
@@ -331,6 +331,7 @@ const NOT_WALKED: Record<string, string> = {
331331 "/runs/:id": "the seed creates no run",
332332 "/signin/access/:token": "needs a one-time access link an admin minted",
333333 "/tell/share/:id": "needs a receipt for a share sent by the signed-in person, which the seed has none of",
334 "/status/:token": "needs a status token an outsider was handed on filing, which the seed has none of",
334335 "/settings/features/:slug": "needs a feature slug",
335336 "/:owner/:name/pulls/:number/review/:step": "needs a pull carrying review steps, which the seed has none of",
336337 "/settings/origins/:id/archived": ORIGIN,
test/outsider-status.test.ts added +179
@@ -0,0 +1,179 @@
1 /**
2 * An outsider's report or offer is given a status link: a page and JSON, 90 days, no account
3 * (#15768).
4 */
5 import { afterAll, beforeAll, describe, 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 { editFiles } from "../src/actions/contents.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { acceptReport, dismissReport } from "../src/actions/reports.ts";
13 import { setIssueState } from "../src/core/issues.ts";
14 import { pruneOutsiderStatus, STATUS_TTL_MS } from "../src/core/outsider_status.ts";
15 import { getRepo } from "../src/core/repos.ts";
16 import { submitReview } from "../src/core/reviews.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import { LOOPBACK_PROXIES } from "./helpers/loopback-proxy.ts";
20
21 const PATCH = `diff --git a/hello.txt b/hello.txt
22 --- a/hello.txt
23 +++ b/hello.txt
24 @@ -1,2 +1,2 @@
25 hello
26 -world
27 +there
28 `;
29 const SECRET = "my-private-title-<b>x</b>";
30
31 describe("outsider status link", () => {
32 let dataDir: string;
33 let app: App;
34 let servers: Servers;
35 let alice: User;
36 let n = 1;
37 const post = async (path: string, body: object) => {
38 const res = await fetch(`${servers.url}${path}`, {
39 method: "POST",
40 headers: { "content-type": "application/json", "x-forwarded-for": `10.4.0.${n++}` },
41 body: JSON.stringify(body),
42 });
43 return (await res.json()) as any;
44 };
45 const report = () => post("/api/v1/repos/alice/game/reports", { title: SECRET, body: "words" });
46 const offer = () => post("/api/v1/repos/alice/game/offers", { title: SECRET, patch: PATCH });
47 const read = async (url: string) => {
48 const res = await fetch(url);
49 return { status: res.status, res, body: res.status === 200 ? ((await res.json()) as any) : undefined };
50 };
51 const tokenOf = (link: string) => link.split("/").pop()!;
52 const issueOf = (number: number): string =>
53 app.db.query<{ id: string }, [number]>("SELECT id FROM issue WHERE number = ?1").get(number)!.id;
54 const repo = () => getRepo(app.db, "alice", "game")!;
55
56 beforeAll(async () => {
57 dataDir = await mkdtemp(join(tmpdir(), "forge-outsider-status-"));
58 app = createApp({ dataDir, port: 0, trustedProxies: LOOPBACK_PROXIES });
59 servers = await serve(app);
60 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
61 if (!a.ok) throw new Error(a.error);
62 alice = a.value;
63 const made = await createRepo(app, alice, { name: "game", visibility: "public" });
64 if (!made.ok) throw new Error(String(made.error));
65 const seeded = await editFiles(app, alice, repo(), { files: [{ path: "hello.txt", content: "hello\nworld\n" }], message: "first" });
66 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
67 }, 30_000);
68
69 afterAll(async () => {
70 servers.stop();
71 app.close();
72 await rm(dataDir, { recursive: true, force: true });
73 });
74
75 test("a report's answer links a page and JSON; received shows no private detail", async () => {
76 const r = await report();
77 expect(r.statusPage).toBe(`${servers.url}/status/${tokenOf(r.statusPage)}`);
78 expect(r.statusJson).toBe(`${servers.url}/api/v1/status/${tokenOf(r.statusPage)}`);
79 expect(tokenOf(r.statusPage)).toMatch(/^[0-9a-f]{48}$/);
80 const got = await read(r.statusJson);
81 expect(got.res.headers.get("cache-control")).toBe("no-store");
82 expect(got.body.state).toBe("received");
83 expect(got.body.kind).toBe("report");
84 expect(got.body.updated).toBeNull();
85 const expires = Date.parse(got.body.expires) - Date.parse(got.body.received);
86 expect(expires).toBe(STATUS_TTL_MS);
87 expect(JSON.stringify(got.body)).not.toContain("private");
88 expect(Object.keys(got.body).sort()).toEqual(["expires", "kind", "received", "state", "updated", "words"]);
89 const page = await fetch(r.statusPage);
90 expect(page.status).toBe(200);
91 expect(page.headers.get("x-content-type-options")).toBe("nosniff");
92 const html = await page.text();
93 expect(html).toContain("received");
94 expect(html).not.toContain("private");
95 expect(html).not.toContain(r.id);
96 });
97
98 test("a report reads planned, landed and declined as people act", async () => {
99 const planned = await report();
100 const accepted = await acceptReport(app, alice, repo(), planned.id);
101 if (!accepted.ok) throw new Error(JSON.stringify(accepted.error));
102 const body = (await read(planned.statusJson)).body;
103 expect(body.state).toBe("planned");
104 expect(body.updated).not.toBeNull();
105 setIssueState(app.db, accepted.value.id, "closed");
106 expect((await read(planned.statusJson)).body.state).toBe("landed");
107
108 const dropped = await report();
109 const second = await acceptReport(app, alice, repo(), dropped.id);
110 if (!second.ok) throw new Error(JSON.stringify(second.error));
111 setIssueState(app.db, second.value.id, "closed", "dropped");
112 expect((await read(dropped.statusJson)).body.state).toBe("declined");
113
114 const dismissed = await report();
115 const d = dismissReport(app, alice, repo(), dismissed.id);
116 if (!d.ok) throw new Error(JSON.stringify(d.error));
117 const out = await read(dismissed.statusJson);
118 expect(out.body.state).toBe("declined");
119 expect(out.body.updated).not.toBeNull();
120 });
121
122 test("an offer reads received, read, landed and declined", async () => {
123 const a = await offer();
124 expect(tokenOf(a.statusPage)).toMatch(/^[0-9a-f]{48}$/);
125 expect((await read(a.statusJson)).body.state).toBe("received");
126 expect((await read(a.statusJson)).body.kind).toBe("offer");
127 const pull = app.db.query<{ head_oid: string }, [string]>("SELECT head_oid FROM pull WHERE issue_id = ?1").get(issueOf(a.number))!;
128 submitReview(app.db, { issueId: issueOf(a.number), authorId: alice.id, state: "commented", commitOid: pull.head_oid });
129 const seen = (await read(a.statusJson)).body;
130 expect(seen.state).toBe("read");
131 expect(seen.updated).not.toBeNull();
132
133 const landed = await offer();
134 app.db.query("UPDATE pull SET merged_at = ?2 WHERE issue_id = ?1").run(issueOf(landed.number), new Date().toISOString());
135 setIssueState(app.db, issueOf(landed.number), "closed");
136 expect((await read(landed.statusJson)).body.state).toBe("landed");
137
138 const declined = await offer();
139 setIssueState(app.db, issueOf(declined.number), "closed", "dropped");
140 expect((await read(declined.statusJson)).body.state).toBe("declined");
141 expect((await fetch(declined.statusPage)).status).toBe(200);
142 });
143
144 test("a wrong, malformed or other token is 404, on the page and in JSON", async () => {
145 const r = await report();
146 const wrong = "0".repeat(48);
147 for (const t of [wrong, "short", "../etc", tokenOf(r.statusPage).toUpperCase(), r.id]) {
148 expect((await fetch(`${servers.url}/status/${t}`)).status).toBe(404);
149 expect((await fetch(`${servers.url}/api/v1/status/${t}`)).status).toBe(404);
150 }
151 });
152
153 test("the token expires after 90 days", async () => {
154 const r = await report();
155 const token = tokenOf(r.statusJson);
156 app.db.query("UPDATE outsider_status SET expires_at = ?2 WHERE token = ?1").run(token, new Date(Date.now() - 1000).toISOString());
157 expect((await fetch(r.statusPage)).status).toBe(404);
158 expect((await fetch(r.statusJson)).status).toBe(404);
159 });
160
161
162 test("expired links are pruned and live ones kept", async () => {
163 const dead = tokenOf((await report()).statusPage);
164 const live = tokenOf((await report()).statusPage);
165 app.db.query("UPDATE outsider_status SET expires_at = ?2 WHERE token = ?1").run(dead, new Date(Date.now() - 1000).toISOString());
166 expect(pruneOutsiderStatus(app.db)).toBeGreaterThanOrEqual(1);
167 const has = (t: string) => app.db.query("SELECT 1 FROM outsider_status WHERE token = ?1").get(t) !== null;
168 expect(has(dead)).toBe(false);
169 expect(has(live)).toBe(true);
170 });
171
172 test("a client reading status past its minute's allowance is told to wait", async () => {
173 const url = `${servers.url}/api/v1/status/${"0".repeat(48)}`;
174 const get = () => fetch(url, { headers: { "x-forwarded-for": "10.9.9.9" } });
175 let last = 0;
176 for (let i = 0; i < 61; i++) last = (await get()).status;
177 expect(last).toBe(429);
178 });
179 });
test/pages-budget.test.ts +1 −1
@@ -65,7 +65,7 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = {
6565 };
6666
6767 /** Patterns with no fixture today: lower this as fixtures are added, never raise it silently. */
68 const MAX_UNFIXTURED = 153; // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856)
68 const MAX_UNFIXTURED = 155; // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856)
6969
7070 /** Streams and live fragments: no page. */
7171 const NOT_PAGES = new Set([
test/security-floor-routes.test.ts +2
@@ -76,6 +76,8 @@ const UNSEEDED: Record<string, string> = {
7676 "/claim/start/:token": "needs a one-time start claim token, which the seed does not mint (test/start.test.ts covers it)",
7777 "/signin/access/:token": "needs a one-time access link an admin minted",
7878 "/tell/share/:id": "needs a receipt for a share sent by the signed-in person, which the seed has none of",
79 "/status/:token": "needs a status token an outsider was handed on filing, which the seed has none of",
80 "/api/v1/status/:token": "needs a status token an outsider was handed on filing, which the seed has none of",
7981 "/talk/:id": TALK,
8082 "/talk/:id/download": TALK,
8183 "/docs/:file": "a file name of the documentation folder; the seed supplies no :file",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs