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

A public repository's page says in one visible line how to report a problem or offer a change, and a test files one as an anonymous agent #12344

Merged opened this

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

Merged

scout/forge:scout/12321-a-public-repository-s-page-says-in-one-v → main 7 commits fork 5 threads · 5 unresolved

  • Merged. scout/12321-a-public-repository-s-page-says-in-one-v was merged into main as 6da1e48.

Review

Sign in to review this change.
19 files changed +488 −28
AGENTS.md +2
@@ -37,3 +37,5 @@ State shared between modules through process memory, not the database, is named
3737
3838 ## Awake ceiling and the boot
3939 `FORGE_CHILD_AWAKE_MAX` counts forges in use. Hosted children the boot opens (so their apps come back) are exempt from `awakeCount` until a credentialed request reaches them or they sleep (`bootOpened` in `src/spawn/host.ts`). The exempt set holds only body ids of existing finished children and is emptied when the parent closes, so it is bounded by the number of children. Cell children are always counted; they are not opened by the boot.
40
41 `src/core/reports.ts`: `closedSet`, the ids of repositories whose owner closed reports from outside (#12321), read once per database and kept by `setReportsClosed`, the only writer, so every repository page's head link costs no statement; at most one id per closed repository, gone on restart (the rows are `report_closed`). `src/core/contribute_token.ts`: `openSet`, the ids of repositories that allow outside agents, read once per database and kept by `setContributeOpen`, the only writer, at most one id per allowing repository, gone on restart; a raw SQL write to `contribute_open` bypasses it. The terminal door for reports is `r` on the outside agents screen (`setOutsideReports`, admins).
docs/features/report-form.md +4
@@ -6,3 +6,7 @@ Anyone may tell a public repository something is wrong at `/<owner>/<name>/repor
66 - **The sent link.** Sending redirects to `/<owner>/<name>/report?sent=<id>`. It shows "Not read yet" until a person decides, then either the issue it became or that it was closed without one. It never shows the report's text or any reply.
77 - **The limit.** One source may send `report.per_source` reports a minute (default 5); the next gets 429 with `Retry-After`. Set it on the limits page or the `limits` tool; it is read on every report, so a change applies at once. Per-repository and per-forge caps stay in `src/actions/reports.ts`.
88 - **Terminal.** None for outsiders: the terminal needs an account. Signed-in people report from a repository's `:` palette (`src/tui/screens/report.ts`) and read waiting reports on the reports page.
9
10 ## Finding it, and closing it (#12321)
11
12 A public repository's front page carries one line, "Something wrong? Report a problem, no account needed", and its head names `rel="help"` links to the form and to `POST /api/v1/repos/<owner>/<name>/reports` (and, on the front page where outside agents are allowed, to `/api/v1/contribute`). A repository admin closes the door in settings ("Close reports"): the page then says "Reports from outside are closed here.", the links go, the form says so, and the API answers 403 `reports_closed`. The rate limits are unchanged. `test/muse-report-journey.test.ts` walks it as an anonymous client.
src/actions/contribute_token.ts +4 −2
@@ -61,13 +61,15 @@ export interface ContributeTokenRefusal {
6161 * and its owner said yes.
6262 */
6363 export function takesOutside(app: App, repo: Repo): boolean {
64 // The one-row read first: most repositories have not opened the door, and
65 // the rest of the questions cost queries.
6466 return (
6567 repo.visibility === "public" &&
6668 repo.sealedFor === null &&
6769 repo.archivedAt === null &&
70 contributeOpen(app.db, repo.id) &&
6871 !isMirror(app, repo) &&
69 !isContributionFork(app.db, repo.id) &&
70 contributeOpen(app.db, repo.id)
72 !isContributionFork(app.db, repo.id)
7173 );
7274 }
7375
src/actions/reports.ts +18 −2
@@ -30,6 +30,8 @@ import {
3030 WAITING_MAX,
3131 cleanReport,
3232 countWaiting,
33 reportsClosed,
34 setReportsClosed,
3335 decideReport,
3436 filerWords,
3537 getReport,
@@ -43,7 +45,7 @@ import {
4345 type ReportInput,
4446 } from "../core/reports.ts";
4547 import { createLabel, getLabel, type Issue } from "../core/issues.ts";
46 import { canRead, canWrite, type Repo } from "../core/repos.ts";
48 import { canAdmin, canRead, canWrite, type Repo } from "../core/repos.ts";
4749 import { getUserById, type User } from "../core/users.ts";
4850 import { defect } from "../kernel/error.ts";
4951 import { err, ok, type Result } from "../kernel/result.ts";
@@ -80,7 +82,7 @@ function limitsOf(app: App): Limits {
8082 }
8183
8284 export type FileRefusal =
83 | { readonly error: "not_found" | ReportError | "queue_full" }
85 | { readonly error: "not_found" | ReportError | "queue_full" | "closed" }
8486 | { readonly error: "rate_limited"; readonly retryAfter: number };
8587
8688 /**
@@ -97,6 +99,7 @@ export function fileReport(
9799 filer?: User,
98100 ): Result<Report, FileRefusal> {
99101 if (!canRead(app.db, repo, undefined)) return err({ error: "not_found" });
102 if (reportsClosed(app.db, repo.id)) return err({ error: "closed" });
100103 const clean = cleanReport(input);
101104 if (!clean.ok) return err({ error: clean.error });
102105 const { forge, repo: perRepo, source: perSource } = limitsOf(app);
@@ -342,3 +345,16 @@ export function dismissReport(
342345 });
343346 return ok(true);
344347 }
348
349 /** A repository admin's yes or no to reports from outside; the rate limits are not touched. */
350 export function setOutsideReports(

Both doors: closing/opening reports exists only on the web settings page. Add a src/tui/ screen (or palette entry on the repository settings screen) calling setOutsideReports, gated by canAdmin exactly like the page, and wire its entry where AGENTS.md says.

351 app: App,
352 actor: User | undefined,
353 repo: Repo,
354 open: boolean,
355 ): Result<{ open: boolean }, "not_found"> {
356 if (!canAdmin(app.db, repo, actor)) return err("not_found");
357 setReportsClosed(app.db, repo.id, !open);
358 app.bus.append({ kind: "report.door", repoId: repo.id, actorId: actor!.id, payload: { open } });
359 return ok({ open });
360 }
src/core/contribute_token.ts +17 −2
@@ -204,12 +204,27 @@ export function pullNumberIn(path: string, repo: { owner: string; name: string }
204204 /** A source (an address) is kept only as a hash: enough to count, never to read. */
205205 const sourceKey = (source: string): string => sha256(`contribute-source:${source}`).slice(0, 24);
206206
207 export const contributeOpen = (db: Database, repoId: string): boolean =>
208 db.query("SELECT 1 FROM contribute_open WHERE repo_id = ?1").get(repoId) !== null;
207 /**
208 * The repositories that said yes, held per database after the first read (every
209 * public page asks); `setContributeOpen` is the only writer.
210 */
211 const openSets = new WeakMap<Database, Set<string>>();

This is shared process memory like closedSet; AGENTS.md names closedSet but not openSets. Name it there with its bound, and note that raw SQL writes bypass it.

212 function openSet(db: Database): Set<string> {
213 let set = openSets.get(db);
214 if (set === undefined) {
215 set = new Set((db.query("SELECT repo_id AS id FROM contribute_open").all() as { id: string }[]).map((r) => r.id));
216 openSets.set(db, set);
217 }
218 return set;
219 }
220
221 export const contributeOpen = (db: Database, repoId: string): boolean => openSet(db).has(repoId);
209222
210223 export function setContributeOpen(db: Database, repoId: string, on: boolean): void {
211224 if (on) db.query("INSERT OR IGNORE INTO contribute_open (repo_id) VALUES (?1)").run(repoId);
212225 else db.query("DELETE FROM contribute_open WHERE repo_id = ?1").run(repoId);
226 if (on) openSet(db).add(repoId);
227 else openSet(db).delete(repoId);
213228 }
214229
215230 export function mintsSince(db: Database, since: number, source: string): number {
src/core/migration-pins/20261114090000-reports-closed.pin added +1
@@ -0,0 +1,1 @@
1 75b59696046c994f1bb02afb897eae5bbe1eaa7088286c082b9218cbb2d1a61c
src/core/migrations/20261114090000-reports-closed.ts added +7
@@ -0,0 +1,7 @@
1 // A repository's owner may close the door for reports from outside (#12321): a row here is the
2 // "no". No row, the default, is open. Deleting a repository deletes its row. New table only.
3 export default `
4 CREATE TABLE report_closed (
5 repo_id TEXT PRIMARY KEY REFERENCES repo(id) ON DELETE CASCADE
6 );
7 `;
src/core/reports.ts +27
@@ -193,6 +193,33 @@ export function outsideTitle(
193193 return ok(`${OUTSIDE_TITLE}${words}`);
194194 }
195195
196 /**
197 * Which repositories have closed the door, held per database after the first
198 * read (every repository page asks): `setReportsClosed` is the only writer, so
199 * it keeps the set. At most one id per closed repository, gone on restart.
200 */
201 const closedSets = new WeakMap<Database, Set<string>>();
202 function closedSet(db: Database): Set<string> {
203 let set = closedSets.get(db);
204 if (set === undefined) {
205 set = new Set(
206 (db.query("SELECT repo_id AS id FROM report_closed").all() as { id: string }[]).map((r) => r.id),
207 );
208 closedSets.set(db, set);
209 }
210 return set;
211 }
212
213 /** Whether the repository's owner has closed the door for reports from outside. */
214 export const reportsClosed = (db: Database, repoId: string): boolean => closedSet(db).has(repoId);
215
216 export function setReportsClosed(db: Database, repoId: string, closed: boolean): void {
217 if (closed) db.query("INSERT OR IGNORE INTO report_closed (repo_id) VALUES (?1)").run(repoId);
218 else db.query("DELETE FROM report_closed WHERE repo_id = ?1").run(repoId);
219 if (closed) closedSet(db).add(repoId);
220 else closedSet(db).delete(repoId);
221 }
222
196223 export function countWaiting(db: Database, repoId: string): number {
197224 return (
198225 db
src/http/api/reports.ts +2
@@ -69,6 +69,8 @@ export function reportRoutes(router: Router<Handler>): void {
6969 if (!filed.ok) {
7070 const refusal = filed.error;
7171 if (refusal.error === "not_found") return notFound();
72 if (refusal.error === "closed")
73 return apiError("reports_closed", 403, "the people who keep this repository have closed reports from outside");
7274 if (refusal.error === "rate_limited")
7375 return tryAgain("rate_limited", 429, "too many reports; wait and send again", refusal.retryAfter);
7476 if (refusal.error === "queue_full")
src/http/mcp.ts +3 −1
@@ -388,7 +388,9 @@ function reportAnswer(ctx: Ctx, id: unknown, args: Args): unknown {
388388 return text(
389389 e.error === "not_found"
390390 ? "not_found: no such public repository (owner/name)"
391 : e.error === "rate_limited"
391 : e.error === "closed"
392 ? "reports_closed: the people who keep this repository have closed reports from outside"
393 : e.error === "rate_limited"
392394 ? `rate_limited: try again in ${e.retryAfter} seconds`
393395 : `${e.error}: plain text, a title of 1-${TITLE_MAX} characters, a body of at most ${BODY_MAX}, agent a name of letters, digits, . _ -`,
394396 true,
src/http/server.ts +2 −1
@@ -512,7 +512,7 @@ import { pageParamRefused } from "./cursor_lists.ts";
512512 import { inNamespace } from "../core/proposal_token.ts";
513513 import { inContribNamespace } from "../core/contribute_token.ts";
514514 import { takesOutside } from "../actions/contribute_token.ts";
515 import { contributeOpenSet, contributeTokenRevoke, proposalTokenMint, proposalTokenRevoke } from "../web/pages/proposal-tokens.ts";
515 import { reportsOpenSet, contributeOpenSet, contributeTokenRevoke, proposalTokenMint, proposalTokenRevoke } from "../web/pages/proposal-tokens.ts";
516516 import { adminGate } from "./admin_gate.ts";
517517 import { movedResponse } from "./moved.ts";
518518 import { originGate } from "./origin_gate.ts";
@@ -1626,6 +1626,7 @@ export function buildRouter(): Router<Handler> {
16261626 proposalTokenRevoke,
16271627 );
16281628 router.add("POST", "/:owner/:name/settings/contribute-tokens/open", contributeOpenSet);
1629 router.add("POST", "/:owner/:name/settings/reports/open", reportsOpenSet);
16291630 router.add("POST", "/:owner/:name/settings/contribute-tokens/:id/delete", contributeTokenRevoke);
16301631 router.add("GET", "/:owner/:name/settings/app", appSettingsPage);
16311632 router.add("GET", "/:owner/:name/settings/app/traffic", appSourcesPage);
src/tui/screens/outsideagents.ts +23 −5
@@ -3,12 +3,15 @@
33 * (`web/pages/proposal-tokens.ts`) from the same actions
44 * (`actions/contribute_token.ts`), gated the same way: a repository's admins.
55 * `a` allows outside agents or stops allowing them; `x` revokes the token under
6 * the cursor, after a confirm. Each write is an event on the bus, so an open
6 * the cursor, after a confirm; `r` opens or closes reports from outside on the
7 * repository's page (`setOutsideReports`, the page's own action and gate). Each write is an event on the bus, so an open
78 * settings page redraws, and this screen follows a write made there.
89 */
910
11 import { setOutsideReports } from "../../actions/reports.ts";
1012 import { revokeOutsideToken, setOutsideContributions, takesOutside } from "../../actions/contribute_token.ts";
1113 import { contributeOpen, listContribute, type ContributeTokenInfo } from "../../core/contribute_token.ts";
14 import { reportsClosed } from "../../core/reports.ts";
1215 import { canAdmin, type Repo } from "../../core/repos.ts";
1316 import type { Ctx, Screen } from "../app/app.ts";
1417 import { binding } from "../app/keys.ts";
@@ -35,9 +38,9 @@ export function outsideAgentsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
3538 const where = `${repo.ownerName}/${repo.name}`;
3639 const screen: Screen = {
3740 title: `${where} — Outside agents`,
38 keys: [binding(["j", "k"], "move cursor"), binding(["a"], "allow or stop allowing"), binding(["x"], "revoke token")],
41 keys: [binding(["j", "k"], "move cursor"), binding(["a"], "allow or stop allowing"), binding(["x"], "revoke token"), binding(["r"], "open or close reports")],
3942 async load(signal) {
40 live(f, signal, { repoId: repo.id, where: (e) => e.kind.startsWith("contribute.") }, () => ctx.invalidate());
43 live(f, signal, { repoId: repo.id, where: (e) => e.kind.startsWith("contribute.") || e.kind === "report.door" }, () => ctx.invalidate());
4144 },
4245 render(area, s) {
4346 const c = ctx.theme.c;
@@ -51,7 +54,8 @@ export function outsideAgentsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
5154 : takesOutside(f.app, repo)
5255 ? "Outside agents may ask for a day's token. a stops allowing them; x revokes."
5356 : "Allowed, but not offered now: only a public, original, unarchived repository takes them.";
54 s.text(head!.x, head!.y, truncate(said, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
57 const reports = reportsClosed(f.db, repo.id) ? " Reports: closed (r opens)." : " Reports: open (r closes).";
58 s.text(head!.x, head!.y, truncate(said + (may ? reports : ""), head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
5559 const rows: ListRow[] = outsideRows(f, repo).map((t) => ({
5660 title: t.agent,
5761 note: `${t.origin === "" ? "no origin given" : t.origin} · claimed, not verified`,
@@ -62,11 +66,25 @@ export function outsideAgentsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
6266 key(e) {
6367 const all = outsideRows(f, repo);
6468 if (state.key(e, all.length)) return true;
65 if (e.ctrl || e.alt || (e.key !== "a" && e.key !== "x")) return false;
69 if (e.ctrl || e.alt || (e.key !== "a" && e.key !== "x" && e.key !== "r")) return false;
6670 if (!mayManageOutside(f, repo)) {
6771 ctx.toast("An admin of this repository manages outside agents.", "danger");
6872 return true;
6973 }
74 if (e.key === "r") {
75 const on = reportsClosed(f.db, repo.id);
76 const set = setOutsideReports(f.app, f.user, repo, on);
77 ctx.toast(
78 !set.ok
79 ? "An admin of this repository manages outside agents."
80 : on
81 ? "Reports from outside are open."
82 : "Reports from outside are closed.",
83 set.ok ? undefined : "danger",
84 );
85 ctx.invalidate();
86 return true;
87 }
7088 if (e.key === "a") {
7189 const on = !contributeOpen(f.db, repo.id);
7290 const set = setOutsideContributions(f.app, f.user, repo, on);
src/web/pages/issues.ts +18 −10
@@ -13,6 +13,7 @@ import {
1313 } from "../../actions/issues.ts";
1414 import type { Issue } from "../../core/issues.ts";
1515 import { canRead, getRepo, listReposWritableTo, type Repo } from "../../core/repos.ts";
16 import { reportsClosed } from "../../core/reports.ts";
1617 import { privateRepoForSealed } from "../../actions/repos.ts";
1718 import { sealedWords, sealRefusedWords } from "../../actions/seal_issue_words.ts";
1819 import { BODY_TOO_LONG, TITLE_TOO_LONG } from "../../actions/thread_limits_words.ts";
@@ -172,16 +173,23 @@ function accountOrReport(ctx: Ctx, repo: Repo, sealed: boolean): Response {
172173 "The report without an account is not sealed: do not use it for a vulnerability.",
173174 action: signIn("primary"),
174175 })
175 : empty({
176 icon: "issue",
177 title: "Opening an issue needs an account",
178 note: "Something wrong? You can report it without one; a person who keeps this repository reads it.",
179 action: html`${btn("Report a problem", {
180 href: `${repoBase(repo)}/report`,
181 variant: "primary",
182 })}
183 ${signIn("ghost")}`,
184 });
176 : reportsClosed(ctx.app.db, repo.id)
177 ? empty({
178 icon: "issue",
179 title: "Opening an issue needs an account",
180 note: "Reports from outside are closed here.",
181 action: signIn("primary"),
182 })
183 : empty({
184 icon: "issue",
185 title: "Opening an issue needs an account",
186 note: "Something wrong? You can report it without one; a person who keeps this repository reads it.",
187 action: html`${btn("Report a problem", {
188 href: `${repoBase(repo)}/report`,
189 variant: "primary",
190 })}
191 ${signIn("ghost")}`,
192 });
185193 return page({
186194 ctx,
187195 title: `New issue · ${repo.ownerName}/${repo.name}`,
src/web/pages/proposal-tokens.ts +18 −1
@@ -7,6 +7,8 @@
77
88 import { listProposals, mintProposal, revokeProposal } from "../../actions/proposal_tokens.ts";
99 import { revokeOutsideToken, setOutsideContributions, takesOutside } from "../../actions/contribute_token.ts";
10 import { setOutsideReports } from "../../actions/reports.ts";
11 import { reportsClosed } from "../../core/reports.ts";
1012 import { contributeOpen, listContribute } from "../../core/contribute_token.ts";
1113 import { canAdmin, canWrite, type Repo } from "../../core/repos.ts";
1214 import { isAccountItself, type Ctx } from "../../http/context.ts";
@@ -26,12 +28,13 @@ function contributeTokensSection(ctx: Ctx, repo: Repo): Html | null {
2628 const base = repoBase(repo);
2729 const open = contributeOpen(ctx.app.db, repo.id);
2830 const tokens = open ? listContribute(ctx.app.db, repo.id, new Date()) : [];
31 const reportsOpen = !reportsClosed(ctx.app.db, repo.id);
2932 return html`<section class="settings-block mb" id="contribute-tokens">
3033 <form method="post" action="${base}/settings/contribute-tokens/open">
3134 <input type="hidden" name="on" value="${open ? "0" : "1"}" />
3235 <p class="muted"><strong>Outside agents</strong> with their own sandbox may ask for a token that lasts a day, push <code>contrib/&lt;name&gt;/…</code> branches here and open pulls, with no account. Names and origins are claimed, not verified.${open && !takesOutside(ctx.app, repo)
3336 ? " Not offered now: only a public, original, unarchived repository takes them."
34 : ""} ${btn(open ? "Stop allowing" : "Allow", { variant: open ? "secondary" : "primary", size: "sm" })}</p>
37 : ""} ${btn(open ? "Stop allowing" : "Allow", { variant: open ? "secondary" : "primary", size: "sm" })} ${btn(reportsOpen ? "Close reports" : "Open reports", { variant: "secondary", size: "sm", name: "door", value: reportsOpen ? "0" : "1", formaction: `${base}/settings/reports/open` })}</p>
3538 </form>
3639 ${tokens.length === 0
3740 ? null
@@ -149,6 +152,20 @@ export async function contributeOpenSet(ctx: Ctx): Promise<Response> {
149152 });
150153 }
151154
155 // POST /:owner/:name/settings/reports/open
156 export async function reportsOpenSet(ctx: Ctx): Promise<Response> {

New mutation route with no test: cover non-admin refused, cross-origin refused, admin toggles and the flash message. Today the test calls setOutsideReports directly and never the route.

157 const repo = loadRepo(ctx);
158 if (!repo) return repoNotFound(ctx);
159 const form = await readForm(ctx, "rw");
160 if (form instanceof Response) return form;
161 const on = field(form, "door") === "1";
162 const set = setOutsideReports(ctx.app, ctx.auth.user, repo, on);
163 if (!set.ok) return forbiddenPage(ctx, NOT_YOURS_TO_DO);
164 return flashTo(ctx, `${repoBase(repo)}/settings`, {
165 message: on ? "Reports from outside are open." : "Reports from outside are closed.",
166 });
167 }
168
152169 // POST /:owner/:name/settings/contribute-tokens/:id/delete
153170 export async function contributeTokenRevoke(ctx: Ctx): Promise<Response> {
154171 const repo = loadRepo(ctx);
src/web/pages/repo.ts +20 −2
@@ -24,6 +24,8 @@ import { GUEST_REFUSALS, HELP_BUILD, HELP_BUILD_NEXT, isContributionFork, isGues
2424 import { lacks, NOT_A_MEMBER } from "../../core/roles.ts";
2525 import { storageLimitMessage } from "../../core/storage.ts";
2626 import { canRead, canWrite, listForks, type Repo } from "../../core/repos.ts";
27 import { reportsClosed } from "../../core/reports.ts";
28 import { takesOutside } from "../../actions/contribute_token.ts";
2729 import { FORKS_PER_DAY, forkRepo, repositoryLimitMessage } from "../../actions/repos.ts";
2830 import {
2931 type RankedFork,
@@ -1373,6 +1375,22 @@ function movedLine(ctx: Ctx, repo: Repo): Html | null {
13731375 return html`<p class="muted small moved-from">Moved from ${move.from} on ${time(move.at, { date: true })}</p>`;
13741376 }
13751377
1378 /**
1379 * The one visible line on a public repository's front page that says how
1380 * someone with no account reports a problem or offers a change, or that the
1381 * owner has closed reports (#12321). Nothing for a repository not public.
1382 */
outdated

reportLine's doc comment was inserted inside archivedLine's doc block, which is now orphaned above reportLine's comment. Move reportLine above the archivedLine comment.

1383 function reportLine(ctx: Ctx, repo: Repo): Html | null {
1384 if (repo.visibility !== "public") return null;
1385 if (reportsClosed(ctx.app.db, repo.id))
1386 return html`<p class="muted small mt" id="report-line">Reports from outside are closed here.</p>`;
1387 return html`<p class="muted small mt" id="report-line">
1388 Something wrong? <a href="${repoBase(repo)}/report">Report a problem</a>, no account needed${takesOutside(ctx.app, repo)
1389 ? html`; outside agents may also <a href="/api/v1/contribute">offer a change</a>`
1390 : null}.
1391 </p>`;
1392 }
1393
13761394 /**
13771395 * "Archived on <date>" with, for an admin, the Restore button. A repository put
13781396 * away still clones, pushes and links as before; this only says so.
@@ -1407,7 +1425,7 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
14071425
14081426 if (refs.branches.length === 0) {
14091427 const emptyRendering = performance.now();
1410 const body = html`${scopeHeader(ctx, scope, "code")}${archivedLine(ctx, repo)}${movedLine(ctx, repo)}${noApp}
1428 const body = html`${scopeHeader(ctx, scope, "code")}${archivedLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp}
14111429 <div class="mt">
14121430 ${empty({
14131431 icon: "repo",
@@ -1491,7 +1509,7 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
14911509 const rendering = performance.now();
14921510 const body = html`${scopeHeader(ctx, scope, "code", {
14931511 branchCount: refs.branches.length,
1494 })}${credit}${behind}${originAhead}${behind === null && originAhead === null ? standingLine : null}${archivedLine(ctx, repo)}${movedLine(ctx, repo)}${noApp}
1512 })}${credit}${behind}${originAhead}${behind === null && originAhead === null ? standingLine : null}${archivedLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp}
14951513 ${offerUpstream(repo, parent, offer)}
14961514 ${latest === null
14971515 ? ""
src/web/pages/reports.ts +22
@@ -25,6 +25,7 @@ import {
2525 filerWords,
2626 outsideWords,
2727 reportStanding,
28 reportsClosed,
2829 type FiledBy,
2930 type Report,
3031 } from "../../core/reports.ts";
@@ -151,9 +152,29 @@ export function reportPage(ctx: Ctx): Response {
151152 const repo = timePhase(request, "repo", () => loadRepo(ctx));
152153 const open = repo !== undefined && timePhase(request, "access", () => canRead(ctx.app.db, repo, undefined));
153154 if (!repo || !open) return timePhase(request, "render", () => notFoundPage(ctx));
155 if (reportsClosed(ctx.app.db, repo.id) && ctx.url.searchParams.get("sent") === null)
156 return timePhase(request, "render", () => closedPage(ctx, repo));
154157 return timePhase(request, "render", () => reportBody(ctx, repo));
155158 }
156159
160 /** The door the owner has shut: said plainly, with no form. */
161 function closedPage(ctx: Ctx, repo: Repo, status = 200): Response {
162 return page(
163 {
164 ctx,
165 title: `Reports closed · ${repo.ownerName}/${repo.name}`,
166 crumbs: crumbsFor(repo),
167 body: html`${repoHeader(ctx, repo, "issues", { compact: true, ownTitle: true })}
168 <h1 class="mt">Reports are closed</h1>
169 <p class="mt">
170 The people who keep ${repo.ownerName}/${repo.name} are not taking
171 reports from outside right now.
172 </p>`,
173 },
174 status,
175 );
176 }
177
157178 function reportBody(ctx: Ctx, repo: Repo): Response {
158179 const sentId = ctx.url.searchParams.get("sent");
159180 if (sentId !== null && sentId !== "") {
@@ -228,6 +249,7 @@ export async function reportSubmit(ctx: Ctx): Promise<Response> {
228249 });
229250 const refusal = filed.error;
230251 if (refusal.error === "not_found") return notFoundPage(ctx);
252 if (refusal.error === "closed") return closedPage(ctx, repo, 403);
231253 if (refusal.error === "rate_limited") {
232254 const response = reportForm(
233255 ctx,
src/web/standards.ts +21 −2
@@ -31,9 +31,10 @@ import { UPSTREAM_REPO } from "../core/upstream.ts";
3131 import { CRAWL_DELAY_S, DEEP_SEGMENTS } from "../http/crawl.ts";
3232 import { markPng, type MarkShape } from "../design/mark.ts";
3333 import { metaThemeColor } from "../design/themes.ts";
34 import { BODY_MAX, TITLE_MAX } from "../core/reports.ts";
34 import { BODY_MAX, TITLE_MAX, reportsClosed } from "../core/reports.ts";
3535 import { dayOf } from "../release/days.ts";
3636 import { readLandings } from "../release/landings.ts";
37 import { takesOutside } from "../actions/contribute_token.ts";
3738 import { REPORT_LINK_TITLE } from "../actions/report_words.ts";
3839 import { sshTellCommand } from "../ssh/command.ts";
3940 import { llmsRepos, sitemapRepos, type LlmsListing } from "../core/listings.ts";
@@ -571,12 +572,30 @@ export function pageLinks(ctx: Ctx): PageLink[] {
571572 ctx.url.pathname.startsWith(`/${owner}/${name}`)
572573 ) {
573574 const repo = getRepo(ctx.app.db, owner, name.replace(/\.git$/, ""));
574 if (repo !== undefined && canRead(ctx.app.db, repo, undefined))
575 if (
576 repo !== undefined &&
577 canRead(ctx.app.db, repo, undefined) &&
578 !reportsClosed(ctx.app.db, repo.id)
579 ) {
575580 links.push({
576581 rel: "help",
577582 href: `/${repo.ownerName}/${repo.name}/report`,
578583 title: REPORT_LINK_TITLE,
579584 });
585 // The same door for an agent: the endpoint that takes the JSON.
586 links.push({
587 rel: "help",
588 href: `/api/v1/repos/${repo.ownerName}/${repo.name}/reports`,
589 title: "Report a problem as JSON: POST {title, body?, page?}",
590 });
591 // The door for a change, only where the owner has said yes to it.
592 if (ctx.url.pathname === `/${repo.ownerName}/${repo.name}` && takesOutside(ctx.app, repo))
593 links.push({
594 rel: "help",
595 href: "/api/v1/contribute",
596 title: "Offer a change: ask for a day's token, push contrib/<name>/..., open a pull",
597 });
598 }
580599 }
581600 return links;
582601 }
test/muse-report-journey.test.ts added +147
@@ -0,0 +1,147 @@
1 /**

Box 2 says follow only what the page names: the test hard-codes /alice/game/report and the API path after only asserting they appear. Fetch the hrefs parsed from the page. Also the 'untrusted' check and the XFF header: confirm limiter keys on socket address.

2 * The Muse test, end to end (#12321): an anonymous client reads a public
3 * repository's page, follows only what the page names, and files a report that
4 * a person accepts as an issue marked as from outside. A repository whose owner
5 * closed reports says so and offers no link. The rate limit is not touched.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { setOutsideReports } from "../src/actions/reports.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 describe("an anonymous client finds the report door from the page alone", () => {
20 quietLogs();
21 let dataDir: string;
22 let app: App;
23 let servers: Servers;
24 let base: string;
25 let ownerToken = "";
26 let alice: any;
27 let shut: any;
28
29 beforeAll(async () => {
30 dataDir = await mkdtemp(join(tmpdir(), "forge-muse-journey-"));
31 app = createApp({ dataDir, port: 0 });
32 servers = await serve(app);
33 base = servers.url;
34 const a = await createUser(app.db, {
35 origin: "seed",
36 trusted: true,
37 username: "alice",
38 email: "[email protected]",
39 password: "a-good-passphrase",
40 adminIfFirst: true,
41 });
42 if (!a.ok) throw new Error(a.error);
43 alice = a.value;
44 ownerToken = createToken(app.db, alice.id, "t", "rw").token;
45 for (const name of ["game", "quiet"]) {
46 const made = await createRepo(app, alice, { name, visibility: "public" });
47 if (!made.ok) throw new Error(String(made.error));
48 if (name === "quiet") shut = made.value;
49 }
50 });
51 afterAll(async () => {
52 servers.stop();
53 app.close();
54 await rm(dataDir, { recursive: true, force: true });
55 });
56
57 test("the page says it in a line and its head names both endpoints; following them files a report", async () => {
58 const page = await fetch(`${base}/alice/game`);
59 expect(page.status).toBe(200);
60 const html = await page.text();
61 // One visible line, with the link.
62 expect(html).toContain('id="report-line"');
63 expect(html).toContain('<a href="/alice/game/report">Report a problem</a>');
64 // The head names the form and the JSON endpoint.
65 const helps = [...html.matchAll(/<link\b[^>]*>/g)]
66 .map((m) => m[0])
67 .filter((l) => l.includes('rel="help"'));
68 const targets = helps.map((l) => /href="([^"]+)"/.exec(l)![1]!);
69 expect(targets).toContain("/alice/game/report");
70 expect(targets).toContain("/api/v1/repos/alice/game/reports");
71
72 // Follow what the page named, not a path known in advance.
73 const formHref = targets.find((t) => t.endsWith("/report"))!;
74 const apiHref = targets.find((t) => t.startsWith("/api/") && t.endsWith("/reports"))!;
75 expect(html).toContain(`<a href="${formHref}">Report a problem</a>`);
76 const form = await fetch(`${base}${formHref}`);
77 expect(form.status).toBe(200);
78 const filed = await fetch(`${base}${apiHref}`, {
79 method: "POST",
80 headers: { "content-type": "application/json", "x-forwarded-for": "192.0.2.50" },
81 body: JSON.stringify({ title: "The board does not load", body: "Blank after login" }),
82 });
83 expect(filed.status).toBe(202);
84 const receipt = (await filed.json()) as any;
85 expect(receipt.state).toBe("pending");
86
87 // It waits as untrusted until a person accepts it into an issue marked from outside.
88 const auth = { authorization: `Bearer ${ownerToken}` };
89 const listed = (await (
90 await fetch(`${base}/api/v1/repos/alice/game/reports`, { headers: auth })
91 ).json()) as any;
92 const mine = listed.items.find((r: any) => r.id === receipt.id);
93 expect(mine.untrusted).toBe(true);
94 const accepted = await fetch(
95 `${base}/api/v1/repos/alice/game/reports/${receipt.id}/accept`,
96 { method: "POST", headers: auth },
97 );
98 expect(accepted.status).toBe(201);
99 const issue = (await accepted.json()) as any;
100 expect(issue.title).toBe("From outside: The board does not load");
101 expect(issue.labels.map((l: any) => l.name)).toEqual(["outside"]);
102 });
103
104 test("the journey does not loosen the rate limit", async () => {
105 let last = 0;
106 for (let i = 0; i < 40 && last !== 429; i++) {
107 const res = await fetch(`${base}/api/v1/repos/alice/game/reports`, {
108 method: "POST",
109 headers: { "content-type": "application/json", "x-forwarded-for": "192.0.2.77" },
110 body: JSON.stringify({ title: `again ${i}` }),
111 });
112 last = res.status;
113 }
114 expect(last).toBe(429);
115 });
116
117 test("a repository with reports closed says so, shows no link, and takes nothing", async () => {
118 expect(setOutsideReports(app, alice, shut, false).ok).toBe(true);
119 const page = await fetch(`${base}/alice/quiet`);
120 const html = await page.text();
121 expect(html).toContain("Reports from outside are closed here.");
122 expect(html).not.toContain("/alice/quiet/report");
123 expect(page.headers.get("link") ?? "").not.toContain("rel=\"help\"");
124 const form = await fetch(`${base}/alice/quiet/report`);
125 expect(await form.text()).toContain("Reports are closed");
126 const api = await fetch(`${base}/api/v1/repos/alice/quiet/reports`, {
127 method: "POST",
128 headers: { "content-type": "application/json", "x-forwarded-for": "192.0.2.90" },
129 body: JSON.stringify({ title: "hello" }),
130 });
131 expect(api.status).toBe(403);
132 expect(((await api.json()) as any).error).toBe("reports_closed");
133 // Only an admin may reopen it.
134 const carol = await createUser(app.db, {
135 origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase",
136 });
137 if (!carol.ok) throw new Error(carol.error);
138 expect(setOutsideReports(app, carol.value, shut, true).ok).toBe(false);
139 expect(setOutsideReports(app, alice, shut, true).ok).toBe(true);
140 const again = await fetch(`${base}/api/v1/repos/alice/quiet/reports`, {
141 method: "POST",
142 headers: { "content-type": "application/json", "x-forwarded-for": "192.0.2.91" },
143 body: JSON.stringify({ title: "hello" }),
144 });
145 expect(again.status).toBe(202);
146 });
147 });
test/reports-door-route.test.ts added +132
@@ -0,0 +1,132 @@
1 /**
2 * The reports door's route (#12321): `POST /:owner/:name/settings/reports/open`
3 * is an admin's, same-origin, and flips the line on the page and on
4 * /issues/new; and the terminal's `r` does the same through the same action.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { reportsClosed } from "../src/core/reports.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { createForgeApp } from "../src/tui/forge.ts";
17 import { outsideAgentsScreen } from "../src/tui/screens/outsideagents.ts";
18 import { headlessTerminal } from "../src/tui/term/terminal.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { settleApp } from "./helpers/tui.ts";
21
22 describe("closing and opening reports from outside", () => {
23 quietLogs();
24 let dir: string;
25 let app: App;
26 let servers: Servers;
27 let repo: any;
28 let alice: any;
29 let bob: any;
30 let aliceCookie = "";
31 let bobCookie = "";
32
33 beforeAll(async () => {
34 dir = await mkdtemp(join(tmpdir(), "forge-reports-door-"));
35 app = createApp({ dataDir: dir, port: 0 });
36 servers = await serve(app);
37 const make = async (username: string, first = false) => {
38 const u = await createUser(app.db, {
39 origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase",
40 ...(first ? { adminIfFirst: true } : {}),
41 });
42 if (!u.ok) throw new Error(u.error);
43 return u.value;
44 };
45 alice = await make("alice", true);
46 bob = await make("bob");
47 aliceCookie = `forge_session=${createSession(app.db, alice.id).token}`;
48 bobCookie = `forge_session=${createSession(app.db, bob.id).token}`;
49 const made = await createRepo(app, alice, { name: "game", visibility: "public" });
50 if (!made.ok) throw new Error(String(made.error));
51 repo = made.value;
52 });
53 afterAll(async () => {
54 servers.stop();
55 app.close();
56 await rm(dir, { recursive: true, force: true });
57 });
58
59 const post = (cookie: string, door: "0" | "1", headers: Record<string, string> = {}) =>
60 fetch(`${servers.url}/alice/game/settings/reports/open`, {
61 method: "POST",
62 redirect: "manual",
63 headers: { cookie, "content-type": "application/x-www-form-urlencoded", ...headers },
64 body: `door=${door}`,
65 });
66 const page = async () => await (await fetch(`${servers.url}/alice/game`)).text();
67 const newIssue = async () => await (await fetch(`${servers.url}/alice/game/issues/new`)).text();
68
69 test("a non-admin is refused and the door stays as it was", async () => {
70 const res = await post(bobCookie, "0");
71 expect(res.status).toBe(403);
72 expect(reportsClosed(app.db, repo.id)).toBe(false);
73 });
74
75 test("a cross-origin post is refused even from the admin", async () => {
76 const res = await post(aliceCookie, "0", { origin: "https://evil.example" });
77 expect(res.status).toBe(403);
78 expect(reportsClosed(app.db, repo.id)).toBe(false);
79 });
80
81 test("the admin closes it: the line says so, and /issues/new drops the Report button", async () => {
82 expect(await page()).toContain('<a href="/alice/game/report">Report a problem</a>');
83 expect(await newIssue()).toContain('href="/alice/game/report"');
84 const res = await post(aliceCookie, "0", { origin: servers.url });
85 expect(res.status).toBe(303);
86 expect(reportsClosed(app.db, repo.id)).toBe(true);
87 expect(await page()).toContain("Reports from outside are closed here.");
88 const issue = await newIssue();
89 expect(issue).not.toContain("/alice/game/report");
90 expect(issue).toContain("Reports from outside are closed here.");
91 });
92
93 test("the admin opens it again and the link returns", async () => {
94 const res = await post(aliceCookie, "1");
95 expect(res.status).toBe(303);
96 expect(reportsClosed(app.db, repo.id)).toBe(false);
97 expect(await page()).toContain('<a href="/alice/game/report">Report a problem</a>');
98 });
99
100 test("in the terminal, r closes and opens it for an admin and does nothing for anyone else", async () => {
101 const key = (k: string) => ({ type: "key" as const, key: k, ctrl: false, alt: false, shift: false });
102 const open = (user: any) => {
103 const { app: tui, session } = createForgeApp(
104 app,
105 { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
106 { terminal: headlessTerminal(120, 40), exitHooks: false },
107 );
108 tui.start();
109 tui.ctx.push(outsideAgentsScreen(session, tui.ctx, repo));
110 return tui;
111 };
112 const stranger = open(bob);
113 await settleApp(stranger);
114 stranger.dispatch(key("r"));
115 await settleApp(stranger);
116 expect(reportsClosed(app.db, repo.id)).toBe(false);
117 stranger.stop?.();
118
119 const tui = open(alice);
120 await settleApp(tui);
121 expect(tui.screen.toText()).toContain("Reports: open");
122 tui.dispatch(key("r"));
123 await settleApp(tui);
124 expect(reportsClosed(app.db, repo.id)).toBe(true);
125 expect(await page()).toContain("Reports from outside are closed here.");
126 expect(tui.screen.toText()).toContain("Reports: closed");
127 tui.dispatch(key("r"));
128 await settleApp(tui);
129 expect(reportsClosed(app.db, repo.id)).toBe(false);
130 tui.stop?.();
131 });
132 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs