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

See what outside agents tried: a compact, redacted request log the owner can read #1009

Closed opened this in answer to
Closed without merging

scout/forge:scout/665-see-what-outside-agents-tried-a-compact → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
9 files changed +612 −0
README.md +11
@@ -386,6 +386,17 @@ not as a crew run; AWS audits look at us-east-1 only; over-provisioned
386386 droplets and forgotten DNS records need metrics or resolution and are not
387387 attempted; Backblaze audits find nothing yet. No dependency was added.
388388
389 ## Access log
390
391 The forge writes one tab-separated line per request that is not a static
392 asset to `<data>/access/YYYY-MM-DD.log`: time, host, method, path (no query),
393 status, milliseconds, user agent (200 chars), `in`/`out` (a credential was
394 presented), and a salted daily hash of the client address. Never a token,
395 cookie, query string or raw address. 14 days kept, 4 MB a day, never served.
396 A forge admin reads non-browser requests to the public doors at
397 **Settings → Access** or with the MCP tool `access {since, ua?, path?}`
398 (write-scoped token).
399
389400 ## Develop
390401
391402 ```sh
scripts/gate.ts +1
@@ -66,6 +66,7 @@ export const GATE: readonly string[] = [
6666 "test/decide.test.ts",
6767 "test/ledger.test.ts",
6868 "test/capacity.test.ts",
69 "test/access-log.test.ts",
6970 "test/checks.test.ts",
7071 "test/dependencies.test.ts",
7172 "test/map-closing.test.ts",
src/http/mcp.ts +44
@@ -18,6 +18,7 @@
1818 */
1919
2020 import { mayView, mayViewId, sealedScope } from "../core/sealed.ts";
21 import { parseSince, readAccess } from "../kernel/access_log.ts";
2122 import { changeCapacity, listCapacity } from "../actions/capacity.ts";
2223 import { relationOf, takeUpdates } from "../actions/forks.ts";
2324 import { watchMilestone } from "../actions/watches.ts";
@@ -641,6 +642,49 @@ const TOOLS: readonly Tool[] = [
641642 );
642643 },
643644 },
645 {
646 name: "access",
647 description:
648 "What outside agents tried, for a forge admin: the last day's (or `since`'s) non-browser requests to public doors (/issues, /api/, /mcp, /.well-known/, /llms.txt, sign-in, sign-up), newest first — time, host, method, path without its query, status, milliseconds, user agent, signed in or out, and a salted daily hash of the client address. Tokens, cookies and query strings are never kept. Needs a write-scoped token. The same as Settings → Access.",
649 inputSchema: {
650 type: "object",
651 properties: {
652 since: {
653 type: "string",
654 maxLength: 40,
655 description: 'An ISO time or an age: "90m", "24h", "7d". A day ago by default; the log keeps 14 days.',
656 },
657 ua: { type: "string", maxLength: 100, description: "Only user agents containing this text." },
658 path: { type: "string", maxLength: 100, description: "Only paths containing this text." },
659 },
660 },
661 writes: true,
662 run(ctx, user, args) {
663 if (!user.isAdmin)
664 return bad("forbidden", "only an admin of this forge reads its access log");
665 const since = parseSince(str(args["since"]));
666 if (since === undefined)
667 return bad("bad_since", 'since is an ISO time or an age like "24h"');
668 const entries = readAccess(ctx.app.config.dataDir, {
669 since,
670 ...(str(args["ua"]) === "" ? {} : { ua: str(args["ua"]).slice(0, 100) }),
671 ...(str(args["path"]) === "" ? {} : { path: str(args["path"]).slice(0, 100) }),
672 });
673 return good(
674 entries.map((e) => ({
675 at: new Date(e.at).toISOString(),
676 host: e.host,
677 method: e.method,
678 path: e.path,
679 status: e.status,
680 ms: e.ms,
681 ua: e.ua,
682 signedIn: e.signedIn,
683 client: e.client,
684 })),
685 );
686 },
687 },
644688 {
645689 name: "outsiders",
646690 description:
src/http/server.ts +39
@@ -6,6 +6,14 @@
66 */
77
88 import { unsealReleased } from "../actions/sealed.ts";
9 import {
10 clientHash,
11 isLogged,
12 recordAccess,
13 redactAgent,
14 redactPath,
15 } from "../kernel/access_log.ts";
16 import { accessPage } from "../web/pages/access.ts";
917 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
1018 import {
1119 closeStreamsOf,
@@ -644,6 +652,7 @@ export function buildRouter(): Router<Handler> {
644652 router.add("POST", "/settings/cloud/audit", cloudAudit);
645653 router.add("POST", "/settings/cloud/remove", cloudRemove);
646654 router.add("GET", "/settings/capacity", capacityPage);
655 router.add("GET", "/settings/access", accessPage);
647656 router.add("POST", "/settings/capacity", capacitySet);
648657 router.add("GET", "/settings/backups", backupsPage);
649658 router.add("POST", "/settings/backups/now", backupsNow);
@@ -1637,6 +1646,7 @@ export async function serve(app: App): Promise<Servers> {
16371646 return securityFloor(new Response("not found", { status: 404 }));
16381647 }
16391648 notePeer(request, server.requestIP(request)?.address, trust);
1649 const began = performance.now();
16401650 // A body refused part-way, or one left unread with no declared length,
16411651 // ends its connection once answered (`http/limits.ts`).
16421652 armClose(request, () => server.timeout(request, 1));
@@ -1646,6 +1656,7 @@ export async function serve(app: App): Promise<Servers> {
16461656 await answer(app, router, apiRouter, limiter, request),
16471657 );
16481658 await settleBody(request);
1659 noteAccess(app, request, response, performance.now() - began);
16491660 if (!mustClose(request)) return response;
16501661 // Said, so no client or proxy reuses it; then done, so none can.
16511662 server.timeout(request, 1);
@@ -1699,6 +1710,34 @@ export async function serve(app: App): Promise<Servers> {
16991710 * dropped from whatever GET would have returned, after the one render that
17001711 * produced it.
17011712 */
1713 /** One line in the access log (`kernel/access_log.ts`); no asset, no secret. */
1714 function noteAccess(
1715 app: App,
1716 request: Request,
1717 response: Response,
1718 ms: number,
1719 ): void {
1720 const url = new URL(request.url);
1721 if (!isLogged(url.pathname)) return;
1722 const at = Date.now();
1723 const dataDir = app.config.dataDir;
1724 const headers = request.headers;
1725 recordAccess(dataDir, {
1726 at,
1727 host: (headers.get("host") ?? url.host).toLowerCase(),
1728 method: request.method,
1729 path: redactPath(url.pathname),
1730 status: response.status,
1731 ms,
1732 ua: redactAgent(headers.get("user-agent") ?? ""),
1733 // A credential was presented, not proven; the log must cost no lookup.
1734 signedIn:
1735 headers.has("authorization") ||
1736 cookieValue(request, "forge_session") !== undefined,
1737 client: clientHash(dataDir, at, clientAddress(request)),
1738 });
1739 }
1740
17021741 async function answer(
17031742 app: App,
17041743 router: Router<Handler>,
src/kernel/access_log.ts added +223
@@ -0,0 +1,223 @@
1 /**
2 * What outside agents tried: one compact line per request that is not a
3 * static asset, kept under the data directory so it survives a rollout.
4 *
5 * A line is tab-separated: time, host, method, path, status, milliseconds,
6 * user agent, `in`/`out`, and a salted daily hash of the client address.
7 * Never the raw address, a query string, a cookie, or a token: the path is
8 * cut at `?`, a segment that looks like a secret is replaced, and the user
9 * agent is scrubbed of anything token-shaped. One file per UTC day, 14 days
10 * kept, each day capped in size, so the whole is bounded. Nothing serves
11 * these files; only a forge admin reads them, through `readAccess`.
12 */
13
14 import { createHmac } from "node:crypto";
15 import {
16 appendFileSync,
17 existsSync,
18 mkdirSync,
19 readdirSync,
20 readFileSync,
21 statSync,
22 unlinkSync,
23 } from "node:fs";
24 import { join } from "node:path";
25 import { loadKey } from "./secret.ts";
26
27 export const KEEP_DAYS = 14;
28 /** The most one day's file may hold; past it lines are dropped, not the file grown. */
29 export const DAY_CAP_BYTES = 4 * 1024 * 1024;
30 const UA_MAX = 200;
31 const PATH_MAX = 300;
32
33 export interface AccessEntry {
34 readonly at: number;
35 readonly host: string;
36 readonly method: string;
37 readonly path: string;
38 readonly status: number;
39 readonly ms: number;
40 readonly ua: string;
41 readonly signedIn: boolean;
42 readonly client: string;
43 }
44
45 const dayOf = (at: number): string => new Date(at).toISOString().slice(0, 10);
46 const dirOf = (dataDir: string): string => join(dataDir, "access");
47
48 /** Not a static asset: those are the browser's, and say nothing of an agent. */
49 export function isLogged(path: string): boolean {
50 return !(
51 path.startsWith("/assets/") ||
52 path.startsWith("/icons/") ||
53 path === "/sw.js" ||
54 path === "/favicon.ico" ||
55 path === "/healthz" ||
56 path === "/manifest.webmanifest"
57 );
58 }
59
60 // eslint-disable-next-line no-control-regex
61 const CONTROL = /[\u0000-\u001f\u007f]/g;
62 // Token-shaped: a prefixed key, a bearer value, or a long opaque run.
63 const SECRETISH =
64 /\b(?:bearer|basic)\s+\S+|\b[a-z]{2,6}_[A-Za-z0-9]{16,}\b|\b[A-Za-z0-9_-]{32,}\b/gi;
65
66 const clean = (s: string): string => s.replace(CONTROL, " ");
67
68 /** The path alone: no query, no fragment, no secret-looking segment. */
69 export function redactPath(raw: string): string {
70 const path = clean(raw.split(/[?#]/)[0] ?? "")
71 .split("/")
72 .map((seg) => (/^[A-Za-z0-9_-]{24,}$/.test(seg) ? ":redacted" : seg))
73 .join("/");
74 return path.slice(0, PATH_MAX);
75 }
76
77 export function redactAgent(raw: string): string {
78 return clean(raw).replace(SECRETISH, "[redacted]").slice(0, UA_MAX);
79 }
80
81 /** The client address, hashed with a salt that changes each UTC day. */
82 export function clientHash(dataDir: string, at: number, address: string): string {
83 const salt = createHmac("sha256", loadKey(dataDir)).update(`access:${dayOf(at)}`);
84 return createHmac("sha256", salt.digest())
85 .update(address)
86 .digest("hex")
87 .slice(0, 12);
88 }
89
90 export function formatLine(e: AccessEntry): string {
91 return [
92 new Date(e.at).toISOString(),
93 clean(e.host).slice(0, 100),
94 clean(e.method).slice(0, 12),
95 e.path,
96 String(e.status),
97 String(Math.round(e.ms)),
98 e.ua,
99 e.signedIn ? "in" : "out",
100 e.client,
101 ].join("\t");
102 }
103
104 export function parseLine(line: string): AccessEntry | undefined {
105 const f = line.split("\t");
106 if (f.length !== 9) return undefined;
107 const at = Date.parse(f[0]!);
108 if (Number.isNaN(at)) return undefined;
109 return {
110 at,
111 host: f[1]!,
112 method: f[2]!,
113 path: f[3]!,
114 status: Number(f[4]),
115 ms: Number(f[5]),
116 ua: f[6]!,
117 signedIn: f[7] === "in",
118 client: f[8]!,
119 };
120 }
121
122 const sizes = new Map<string, number>();
123 let swept = "";
124
125 /** Append one request; never throws — a log must not fail a request. */
126 export function recordAccess(dataDir: string, e: AccessEntry): void {
127 try {
128 const dir = dirOf(dataDir);
129 mkdirSync(dir, { recursive: true });
130 const file = join(dir, `${dayOf(e.at)}.log`);
131 const line = `${formatLine(e)}\n`;
132 let size = sizes.get(file);
133 if (size === undefined) size = existsSync(file) ? statSync(file).size : 0;
134 if (size + line.length <= DAY_CAP_BYTES) {
135 appendFileSync(file, line, { mode: 0o600 });
136 size += line.length;
137 }
138 sizes.set(file, size);
139 if (swept !== `${dir}|${dayOf(e.at)}`) {
140 swept = `${dir}|${dayOf(e.at)}`;
141 sweepAccess(dataDir, e.at);
142 }
143 } catch {
144 // dropped: the request is the point
145 }
146 }
147
148 /** Remove day files older than the window. */
149 export function sweepAccess(dataDir: string, now: number): void {
150 const dir = dirOf(dataDir);
151 if (!existsSync(dir)) return;
152 const oldest = dayOf(now - (KEEP_DAYS - 1) * 86_400_000);
153 for (const name of readdirSync(dir)) {
154 if (/^\d{4}-\d{2}-\d{2}\.log$/.test(name) && name.slice(0, 10) < oldest) {
155 unlinkSync(join(dir, name));
156 sizes.delete(join(dir, name));
157 }
158 }
159 }
160
161 /** A browser says Mozilla; an agent, a script or nothing does not. */
162 export const isBrowser = (ua: string): boolean => ua.includes("Mozilla/");
163
164 /** The doors an outside agent knocks on. */
165 export function isPublicDoor(path: string): boolean {
166 return (
167 path === "/mcp" ||
168 path === "/llms.txt" ||
169 path === "/signin" ||
170 path === "/signup" ||
171 path.startsWith("/api/") ||
172 path.startsWith("/.well-known/") ||
173 path.split("/").includes("issues")
174 );
175 }
176
177 export interface AccessQuery {
178 /** Epoch ms; entries from then on. */
179 readonly since: number;
180 readonly ua?: string;
181 readonly path?: string;
182 readonly limit?: number;
183 }
184
185 /** Newest first: non-browser requests to public doors since `since`. */
186 export function readAccess(dataDir: string, q: AccessQuery, now = Date.now()): AccessEntry[] {
187 const dir = dirOf(dataDir);
188 if (!existsSync(dir)) return [];
189 const from = dayOf(Math.max(q.since, now - KEEP_DAYS * 86_400_000));
190 const files = readdirSync(dir)
191 .filter((n) => /^\d{4}-\d{2}-\d{2}\.log$/.test(n) && n.slice(0, 10) >= from)
192 .sort()
193 .reverse();
194 const ua = q.ua?.toLowerCase();
195 const out: AccessEntry[] = [];
196 const limit = q.limit ?? 200;
197 for (const name of files) {
198 const lines = readFileSync(join(dir, name), "utf8").split("\n").reverse();
199 for (const line of lines) {
200 const e = parseLine(line);
201 if (e === undefined || e.at < q.since) continue;
202 if (isBrowser(e.ua) || !isPublicDoor(e.path)) continue;
203 if (ua !== undefined && !e.ua.toLowerCase().includes(ua)) continue;
204 if (q.path !== undefined && !e.path.includes(q.path)) continue;
205 out.push(e);
206 if (out.length >= limit) return out;
207 }
208 }
209 return out;
210 }
211
212 /** `since` as an ISO time or an age ("90m", "24h", "7d"); a day ago when absent. */
213 export function parseSince(raw: string, now = Date.now()): number | undefined {
214 const text = raw.trim();
215 if (text === "") return now - 86_400_000;
216 const age = /^(\d{1,4})([mhd])$/.exec(text);
217 if (age) {
218 const unit = { m: 60_000, h: 3_600_000, d: 86_400_000 }[age[2] as "m" | "h" | "d"];
219 return now - Number(age[1]) * unit;
220 }
221 const at = Date.parse(text);
222 return Number.isNaN(at) ? undefined : at;
223 }
src/web/pages/access.ts added +82
@@ -0,0 +1,82 @@
1 /**
2 * Access, for a forge admin: what outside agents tried in the last day (or
3 * since a time you give) — non-browser requests to the public doors, newest
4 * first, as `kernel/access_log.ts` keeps them. Read-only; nothing here
5 * changes anything, and the log itself is never served.
6 */
7
8 import type { Ctx } from "../../http/context.ts";
9 import { parseSince, readAccess } from "../../kernel/access_log.ts";
10 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
11 import { html } from "../html.ts";
12 import { page } from "../layout.ts";
13 import { card, icon, row, time } from "../ui.ts";
14 import { accountSections } from "./origins.ts";
15
16 // GET /settings/access?since=24h&ua=&path=
17 export function accessPage(ctx: Ctx): Response {
18 if (!ctx.auth.user) return signInFirst(ctx);
19 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
20 const q = ctx.url.searchParams;
21 const sinceText = (q.get("since") ?? "").slice(0, 40);
22 const ua = (q.get("ua") ?? "").trim().slice(0, 100);
23 const path = (q.get("path") ?? "").trim().slice(0, 100);
24 const since = parseSince(sinceText);
25 const entries =
26 since === undefined
27 ? []
28 : readAccess(ctx.app.config.dataDir, {
29 since,
30 ...(ua === "" ? {} : { ua }),
31 ...(path === "" ? {} : { path }),
32 });
33 const rows = entries.map((e) =>
34 row({
35 lead: icon("eye"),
36 title: html`<span class="mono">${e.method} ${e.path}</span>
37 <span class="muted small">→ ${String(e.status)} · ${String(e.ms)} ms</span>`,
38 meta: html`${time(new Date(e.at).toISOString())} · ${e.host} ·
39 <span class="mono">${e.ua === "" ? "no user agent" : e.ua}</span> ·
40 ${e.signedIn ? "signed in" : "not signed in"} ·
41 <span class="mono" title="Salted daily hash; never the address">${e.client}</span>`,
42 }),
43 );
44 const body = html`${card(
45 html`<div class="card-body">
46 <p class="muted small">
47 Non-browser requests to public paths (/issues, /api/, /mcp,
48 /.well-known/, /llms.txt, sign-in, sign-up). Query strings, cookies
49 and tokens are never kept; addresses are a salted hash that changes
50 each day. Kept 14 days.
51 </p>
52 <form class="row-actions" method="get" action="/settings/access">
53 <input class="input mono" name="since" value="${sinceText}"
54 placeholder="since: 24h, 7d or a time" aria-label="Since" />
55 <input class="input mono" name="ua" value="${ua}"
56 placeholder="user agent contains" aria-label="User agent contains" />
57 <input class="input mono" name="path" value="${path}"
58 placeholder="path contains" aria-label="Path contains" />
59 <button class="btn btn-sm btn-primary" type="submit">Show</button>
60 </form>
61 ${since === undefined
62 ? html`<p class="error-note">Since is a time or an age like 24h.</p>`
63 : null}
64 </div>
65 <ul class="list" id="access-rows">
66 ${rows.length === 0
67 ? html`<li class="muted small card-body">Nothing in that window.</li>`
68 : rows}
69 </ul>`,
70 {
71 head: html`${icon("eye")}
72 <h2>Access</h2>`,
73 pad: false,
74 },
75 )}`;
76 return page({
77 ctx,
78 title: "Access",
79 body: html`<div class="page-head"><h1>Access</h1></div>
80 ${settingsLayout(accountSections("access", { admin: true }), body, "Account settings")}`,
81 });
82 }
src/web/pages/origins.ts +7
@@ -73,6 +73,7 @@ export type AccountSection =
7373 | "backups"
7474 | "secrets"
7575 | "capacity"
76 | "access"
7677 | "cloud";
7778
7879 /**
@@ -124,6 +125,12 @@ export function accountSections(
124125 icon: "activity" as const,
125126 current: current === "capacity",
126127 },
128 {
129 label: "Access",
130 href: "/settings/access",
131 icon: "eye" as const,
132 current: current === "access",
133 },
127134 {
128135 label: "Backups",
129136 href: "/settings/backups",
test/access-log.test.ts added +204
@@ -0,0 +1,204 @@
1 /**
2 * The access log (#665): what outside agents tried, kept compactly. A line
3 * never carries a token, a cookie, a query string or a raw address; files
4 * rotate at 14 days and are capped; only a forge admin with a write-scoped
5 * token reads it, over MCP or on the settings page.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { existsSync, readdirSync, readFileSync } from "node:fs";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
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 {
18 DAY_CAP_BYTES,
19 clientHash,
20 readAccess,
21 recordAccess,
22 redactAgent,
23 redactPath,
24 sweepAccess,
25 type AccessEntry,
26 } from "../src/kernel/access_log.ts";
27
28 const DAY = 86_400_000;
29 const entry = (over: Partial<AccessEntry> = {}): AccessEntry => ({
30 at: Date.now(),
31 host: "forge.test",
32 method: "GET",
33 path: "/api/v1/repos",
34 status: 200,
35 ms: 3,
36 ua: "curl/8",
37 signedIn: false,
38 client: "abc",
39 ...over,
40 });
41
42 describe("access log: files", () => {
43 let dir: string;
44 beforeAll(async () => {
45 dir = await mkdtemp(join(tmpdir(), "forge-access-"));
46 });
47 afterAll(() => rm(dir, { recursive: true, force: true }));
48
49 test("redaction: no query, no long secret segment, no token in the agent", () => {
50 expect(redactPath("/api/v1/x?token=frg_secretsecretsecretsecret")).toBe("/api/v1/x");
51 expect(redactPath("/a/abcdefghijklmnopqrstuvwxyz0123/b")).toBe("/a/:redacted/b");
52 expect(redactAgent("bot Bearer abc123 frg_abcdefghijklmnopqrstuv")).not.toMatch(
53 /abc123|abcdefghij/,
54 );
55 expect(redactAgent("x".repeat(500)).length).toBeLessThanOrEqual(200);
56 expect(redactPath("/a\tb\nc")).not.toMatch(/[\t\n]/);
57 });
58
59 test("the address is hashed with a salt that changes each day", () => {
60 const now = Date.now();
61 const a = clientHash(dir, now, "203.0.113.9");
62 expect(a).not.toContain("203.0.113.9");
63 expect(clientHash(dir, now, "203.0.113.9")).toBe(a);
64 expect(clientHash(dir, now + DAY, "203.0.113.9")).not.toBe(a);
65 });
66
67 test("files older than 14 days go; a day's file is capped", () => {
68 const now = Date.now();
69 recordAccess(dir, entry({ at: now - 20 * DAY }));
70 recordAccess(dir, entry({ at: now - 2 * DAY }));
71 sweepAccess(dir, now);
72 const names = readdirSync(join(dir, "access"));
73 expect(names.some((n) => n === `${new Date(now - 20 * DAY).toISOString().slice(0, 10)}.log`)).toBe(false);
74 expect(names.length).toBe(1);
75
76 const capped = join(dir, "capped");
77 const big = "p".repeat(190);
78 for (let i = 0; i < Math.ceil(DAY_CAP_BYTES / 200) + 500; i++)
79 recordAccess(capped, entry({ at: now, ua: big }));
80 const today = `${new Date(now).toISOString().slice(0, 10)}.log`;
81 const size = readFileSync(join(capped, "access", today)).length;
82 expect(size).toBeLessThanOrEqual(DAY_CAP_BYTES);
83 expect(size).toBeGreaterThan(DAY_CAP_BYTES - 1000);
84 });
85 });
86
87 describe("access log: through the forge", () => {
88 let dataDir: string;
89 let app: App;
90 let servers: Servers;
91 let adminRw: string;
92 let adminRo: string;
93 let memberRw: string;
94 let cookie: string;
95
96 const mcp = async (token: string, args: Record<string, unknown>) => {
97 const res = await fetch(`${servers.url}/mcp`, {
98 method: "POST",
99 headers: {
100 authorization: `Bearer ${token}`,
101 "content-type": "application/json",
102 accept: "application/json, text/event-stream",
103 },
104 body: JSON.stringify({
105 jsonrpc: "2.0",
106 id: 1,
107 method: "tools/call",
108 params: { name: "access", arguments: args },
109 }),
110 });
111 const body = (await res.json()) as {
112 result: { isError?: boolean; content: { text: string }[] };
113 };
114 return { error: body.result.isError === true, text: body.result.content[0]!.text };
115 };
116
117 beforeAll(async () => {
118 dataDir = await mkdtemp(join(tmpdir(), "forge-access-app-"));
119 app = createApp({ dataDir, port: 0 });
120 servers = await serve(app);
121 const mk = async (username: string, adminIfFirst: boolean) => {
122 const u = await createUser(app.db, {
123 trusted: true,
124 username,
125 email: `${username}@forge.local`,
126 password: "a-good-passphrase",
127 adminIfFirst,
128 });
129 if (!u.ok) throw new Error(u.error);
130 return u.value;
131 };
132 const alice = await mk("alice", true);
133 const bob = await mk("bob", false);
134 adminRw = createToken(app.db, alice.id, "t", "rw").token;
135 adminRo = createToken(app.db, alice.id, "t", "ro").token;
136 memberRw = createToken(app.db, bob.id, "t", "rw").token;
137 const res = await fetch(`${servers.url}/signin`, {
138 method: "POST",
139 redirect: "manual",
140 headers: {
141 "content-type": "application/x-www-form-urlencoded",
142 origin: servers.url,
143 },
144 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
145 });
146 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
147 });
148
149 afterAll(async () => {
150 servers.stop();
151 app.close();
152 await rm(dataDir, { recursive: true, force: true });
153 });
154
155 test("an outside agent's failed call is seen, with nothing secret in the file", async () => {
156 const secret = "frg_SUPERSECRETTOKENVALUE0123456789";
157 const res = await fetch(`${servers.url}/api/v1/nothing/here?token=${secret}&x=1`, {
158 headers: {
159 "user-agent": "python-requests/2.31",
160 authorization: `Bearer ${secret}`,
161 cookie: "forge_session=SESSIONCOOKIEVALUE",
162 },
163 });
164 expect(res.status).toBeGreaterThanOrEqual(400);
165 await fetch(`${servers.url}/api/v1/repos`, {
166 headers: { "user-agent": "Mozilla/5.0 Firefox" },
167 });
168 await fetch(`${servers.url}/assets/forge.css`, { headers: { "user-agent": "curl/8" } });
169
170 const raw = readdirSync(join(dataDir, "access"))
171 .map((n) => readFileSync(join(dataDir, "access", n), "utf8"))
172 .join("");
173 expect(raw).toContain("/api/v1/nothing/here");
174 expect(raw).not.toMatch(/SUPERSECRET|SESSIONCOOKIE|token=|x=1|127\.0\.0\.1/);
175 expect(raw).not.toContain("/assets/");
176
177 const seen = await mcp(adminRw, { ua: "python" });
178 expect(seen.error).toBe(false);
179 const rows = JSON.parse(seen.text) as { path: string; ua: string; signedIn: boolean }[];
180 expect(rows.length).toBe(1);
181 expect(rows[0]).toMatchObject({ path: "/api/v1/nothing/here", ua: "python-requests/2.31", signedIn: true });
182 expect(existsSync(join(dataDir, "access"))).toBe(true);
183 // the browser's call is not an outside agent's
184 expect(readAccess(dataDir, { since: 0 }).some((e) => e.ua.includes("Mozilla"))).toBe(false);
185 });
186
187 test("only a forge admin with a write-scoped token reads it", async () => {
188 expect((await mcp(adminRo, {})).error).toBe(true);
189 const member = await mcp(memberRw, {});
190 expect(member.error).toBe(true);
191 expect(member.text).toContain("forbidden");
192 expect((await mcp(adminRw, { since: "nonsense" })).error).toBe(true);
193 });
194
195 test("the settings page shows it to an admin and is not there for anyone else", async () => {
196 const page = await fetch(`${servers.url}/settings/access?ua=python`, { headers: { cookie } });
197 expect(page.status).toBe(200);
198 const text = await page.text();
199 expect(text).toContain("python-requests/2.31");
200 expect(text).toContain("/api/v1/nothing/here");
201 const anon = await fetch(`${servers.url}/settings/access`);
202 expect(await anon.text()).not.toContain("python-requests");
203 });
204 });
test/mcp.test.ts +1
@@ -167,6 +167,7 @@ describe("the forge over MCP", () => {
167167 "stop",
168168 "health",
169169 "audit",
170 "access",
170171 "outsiders",
171172 "probe",
172173 "following",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs