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

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

Closed opened this in answer to
Closed without merging

mason/forge:mason/665-see-what-outside-agents-tried-a-compact → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +780 −20
CLAUDE.md +3 −1
@@ -128,7 +128,9 @@ src/
128128 http/ router, request context (Ctx/auth), respond (json/error shapes,
129129 scope floors, pagination, `securityFloor` — the headers every
130130 response leaves with), api (every /api/v1 route), server
131 (auth resolution, git smart HTTP, web routes, hook socket), sse
131 (auth resolution, git smart HTTP, web routes, hook socket), sse,
132 access-log (one redacted line per request under
133 `<data>/access`, 14 days, read by admins only)
132134 design/ shared design tokens: themes (palettes both surfaces render)
133135 origins/ other forges as one Provider interface: discover (version-endpoint
134136 probe), providers/{github,forgejo} (+ http: paging, ETags, rate
README.md +16
@@ -356,6 +356,22 @@ holds, where it goes, and the one command that restores it.
356356 grew up in switched off: what a host owes it, the moves in order, and what is
357357 given up.
358358
359 ## Access log
360
361 The forge writes one line per request that is not a static asset or the
362 health probe — time, host, method, path, status, milliseconds, user agent
363 (200 characters at most), signed in or not, and the client address as a
364 hash salted per UTC day with the data directory's key. A query string, a
365 token, a cookie and the address itself are never written. One file per day
366 under `<data>/access/`, 8 MiB at most each, 14 days kept; nothing serves the
367 directory, and snapshots leave it out.
368
369 When an outside agent fails on a public door, **Settings → Access log**
370 (admins) shows what it tried: the last day's non-browser requests to
371 issues, `/api/`, `/mcp`, `/.well-known/`, `/llms.txt`, sign-in and sign-up,
372 filtered by user agent and path. The `access` MCP tool answers the same for
373 an admin's write-scoped token.
374
359375 ## Cloud accounts
360376
361377 **Settings → Cloud accounts** (admins) holds provider keys — Cloudflare,
docs/MCP.md +1
@@ -43,6 +43,7 @@ for a tunnel and a forge that sleeps.
4343 | `front_page` | `{ pinned?, hidden?, dryRun? }`: the front page as a stranger sees it, ranked, with numbers; a site admin sets what is pinned (first public one featured) and hidden | yes |
4444 | `map` | an app's plan: ready now, waiting on what, the critical path, where the crew is (`app`) | |
4545 | `usage` | `{ repo, days? }`: what the crew's runs spent — tokens, cost, wall time — by subscription, agent, issue, and each account's 5-hour and weekly standing; a writer's | |
46 | `access` | `{ since?, ua?, path? }`: what outside agents tried — the non-browser requests to issues, `/api/`, `/mcp`, `/.well-known/`, `/llms.txt`, sign-in and sign-up, newest first (500 at most; `since` is `30m`/`6h`/`2d` up to 14 days, or an ISO time; default 24h); a forge admin's, and only with an `rw` token | |
4647 | `link` | `{ app, issue, blockedBy }`: the issue waits for another; loops and cross-repository are refused | yes |
4748 | `unlink` | `{ app, issue, blockedBy }`: the issue stops waiting for it | yes |
4849 | `plan` | `{ app, issues }`: open up to 12 linked issues, all or none (see below) | yes |
scripts/gate.ts +1
@@ -125,6 +125,7 @@ export const GATE: readonly string[] = [
125125 "test/looks.test.ts",
126126 "test/map.test.ts",
127127 "test/mcp.test.ts",
128 "test/access-log.test.ts",
128129 "test/notify.test.ts",
129130 "test/onboarding.test.ts",
130131 "test/origins-oauth.test.ts",
src/http/access-log.ts added +307
@@ -0,0 +1,307 @@
1 /**
2 * What reached the forge: one compact line per request that is not a static
3 * asset, so when an outside agent fails on a public app or repository its
4 * owner can see what it tried. Nothing upstream keeps this — the edge logs
5 * no requests and pod logs go with each rollout — so it lives in the data
6 * directory, beside the index, and survives a release.
7 *
8 * A line is redacted as it is made, never later: the path without its query
9 * string, a forge token anywhere in path or user agent reduced to its
10 * prefix, no header but the user agent, no cookie, and the client address
11 * only as a hash salted per day with the data directory's key — the same
12 * address is the same hash within a UTC day and unlinkable across days.
13 *
14 * One file per UTC day (`<data>/access/YYYY-MM-DD.log`, JSON lines), each
15 * capped at `DAY_CAP` bytes, files older than `KEEP_DAYS` removed as a new
16 * day begins. Nothing serves the directory; it is read only through
17 * `readAccess`, which the admin settings page and the `access` MCP tool call.
18 */
19
20 import { createHmac } from "node:crypto";
21 import {
22 appendFile,
23 mkdir,
24 readdir,
25 readFile,
26 rm,
27 stat,
28 } from "node:fs/promises";
29 import { join } from "node:path";
30 import type { App } from "../app.ts";
31 import { loadKey } from "../kernel/secret.ts";
32
33 export interface AccessLine {
34 /** ISO time the request arrived. */
35 readonly at: string;
36 readonly host: string;
37 readonly method: string;
38 /** The path alone: a query string never reaches the log. */
39 readonly path: string;
40 readonly status: number;
41 /** Milliseconds until the response's head was ready. */
42 readonly ms: number;
43 /** At most `UA_MAX` characters. */
44 readonly ua: string;
45 readonly signedIn: boolean;
46 /** The client address, hashed with a salt that changes every UTC day. */
47 readonly client: string;
48 }
49
50 export const KEEP_DAYS = 14;
51 /** Bytes one day's file may grow to; past it, that day's lines are dropped. */
52 export const DAY_CAP = 8 * 1024 * 1024;
53 export const UA_MAX = 200;
54 const PATH_MAX = 300;
55 const HOST_MAX = 100;
56 /** The most lines one read returns, newest first. */
57 export const READ_MAX = 500;
58
59 const DAY_MS = 86_400_000;
60 const FILE = /^(\d{4}-\d{2}-\d{2})\.log$/;
61 const STATIC =
62 /^\/assets\/|\.(css|js|mjs|map|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf|otf)$/i;
63 const TOKEN = /forge_[A-Za-z0-9_-]+/g;
64 const CONTROL = /[\u0000-\u001f\u007f]/g;
65
66 /** Static assets and the health probe are not worth a line each. */
67 export const isLogged = (path: string): boolean =>
68 path !== "/healthz" && !STATIC.test(path);
69
70 /**
71 * A browser says Mozilla and is not a crawler or an agent wearing one. An
72 * outside agent is anything else: curl, an SDK, an MCP client, a bot.
73 */
74 export const isBrowser = (ua: string): boolean =>
75 /^Mozilla\//.test(ua) &&
76 !/bot|crawl|spider|headless|claude|anthropic|gpt|openai|perplexity/i.test(ua);
77
78 /** The doors an outside agent knocks on. */
79 export const isPublicPath = (path: string): boolean =>
80 /\/issues(\/|$)/.test(path) ||
81 path === "/mcp" ||
82 path.startsWith("/api/") ||
83 path.startsWith("/.well-known/") ||
84 path === "/llms.txt" ||
85 path === "/signin" ||
86 path === "/signup";
87
88 const dayOf = (at: Date): string => at.toISOString().slice(0, 10);
89
90 /** A string as it may sit in a line: no control bytes, no token, bounded. */
91 function clean(text: string, max: number): string {
92 return text.replace(CONTROL, "").replace(TOKEN, "forge_…").slice(0, max);
93 }
94
95 /** The path, with the parts that act as a credential taken out. */
96 function cleanPath(pathname: string): string {
97 // `/go/:code` is a short-lived sign-in hand-off; the code is the secret.
98 const path = pathname.startsWith("/go/") ? "/go/…" : pathname;
99 return clean(path, PATH_MAX);
100 }
101
102 export function clientHash(key: Uint8Array, day: string, address: string): string {
103 return createHmac("sha256", key)
104 .update(`access\n${day}\n${address}`)
105 .digest("hex")
106 .slice(0, 16);
107 }
108
109 export interface Seen {
110 readonly request: Request;
111 readonly url: URL;
112 readonly status: number;
113 readonly ms: number;
114 readonly signedIn: boolean;
115 readonly address: string;
116 readonly at: Date;
117 }
118
119 /** The one line a request becomes. Pure, so redaction is testable alone. */
120 export function lineFor(key: Uint8Array, seen: Seen): AccessLine {
121 const host = (seen.request.headers.get("host") ?? seen.url.host)
122 .toLowerCase()
123 .replace(/[^a-z0-9.:\-\[\]]/g, "")
124 .slice(0, HOST_MAX);
125 return {
126 at: seen.at.toISOString(),
127 host,
128 method: seen.request.method.replace(/[^A-Z]/g, "").slice(0, 10),
129 path: cleanPath(seen.url.pathname),
130 status: seen.status,
131 ms: Math.max(0, Math.round(seen.ms)),
132 ua: clean(seen.request.headers.get("user-agent") ?? "", UA_MAX),
133 signedIn: seen.signedIn,
134 client: clientHash(key, dayOf(seen.at), seen.address),
135 };
136 }
137
138 /**
139 * The writer for one data directory. Lines are batched for a moment and
140 * appended off the request's path, in order; a read waits for what is
141 * pending, so a person never misses the request they just made.
142 */
143 export class AccessLog {
144 readonly dir: string;
145 private pending: AccessLine[] = [];
146 private timer: ReturnType<typeof setTimeout> | undefined;
147 private chain: Promise<void> = Promise.resolve();
148 private day = "";
149 private bytes = 0;
150
151 constructor(dir: string) {
152 this.dir = dir;
153 }
154
155 record(line: AccessLine): void {
156 this.pending.push(line);
157 if (this.timer !== undefined) return;
158 this.timer = setTimeout(() => void this.flush(), 50);
159 this.timer.unref?.();
160 }
161
162 flush(): Promise<void> {
163 if (this.timer !== undefined) clearTimeout(this.timer);
164 this.timer = undefined;
165 const lines = this.pending;
166 this.pending = [];
167 this.chain = this.chain
168 .then(() => this.write(lines))
169 .catch(() => undefined);
170 return this.chain;
171 }
172
173 private async write(lines: readonly AccessLine[]): Promise<void> {
174 for (const line of lines) {
175 const day = line.at.slice(0, 10);
176 if (day !== this.day) await this.turn(day);
177 const text = JSON.stringify(line) + "\n";
178 const size = Buffer.byteLength(text);
179 if (this.bytes + size > DAY_CAP) continue;
180 await appendFile(join(this.dir, `${day}.log`), text, { mode: 0o600 });
181 this.bytes += size;
182 }
183 }
184
185 /** A new day: learn its file's size, and let the oldest days go. */
186 private async turn(day: string): Promise<void> {
187 await mkdir(this.dir, { recursive: true, mode: 0o700 });
188 this.day = day;
189 this.bytes = await stat(join(this.dir, `${day}.log`)).then(
190 (s) => s.size,
191 () => 0,
192 );
193 await prune(this.dir, new Date(`${day}T00:00:00Z`));
194 }
195 }
196
197 /** Remove every day's file older than `KEEP_DAYS` before `today`. */
198 export async function prune(dir: string, today: Date): Promise<void> {
199 const oldest = dayOf(new Date(today.getTime() - (KEEP_DAYS - 1) * DAY_MS));
200 const names = await readdir(dir).catch(() => [] as string[]);
201 for (const name of names) {
202 const day = FILE.exec(name)?.[1];
203 if (day !== undefined && day < oldest)
204 await rm(join(dir, name), { force: true });
205 }
206 }
207
208 const logs = new WeakMap<App, AccessLog>();
209
210 export function accessLogOf(app: App): AccessLog {
211 let log = logs.get(app);
212 if (log === undefined) {
213 log = new AccessLog(join(app.config.dataDir, "access"));
214 logs.set(app, log);
215 }
216 return log;
217 }
218
219 /** Record one answered request, if it is worth a line. */
220 export function noteRequest(
221 app: App,
222 seen: Omit<Seen, "at"> & { at?: Date },
223 ): void {
224 if (!isLogged(seen.url.pathname)) return;
225 const key = loadKey(app.config.dataDir);
226 accessLogOf(app).record(lineFor(key, { ...seen, at: seen.at ?? new Date() }));
227 }
228
229 export interface AccessQuery {
230 readonly since: Date;
231 /** A case-insensitive piece of the user agent. */
232 readonly ua?: string;
233 /** A prefix of the path. */
234 readonly path?: string;
235 }
236
237 /**
238 * The non-browser requests to public paths since a moment, newest first,
239 * at most `READ_MAX`. The window never reaches past what is kept.
240 */
241 export async function readAccess(
242 app: App,
243 query: AccessQuery,
244 now = new Date(),
245 ): Promise<AccessLine[]> {
246 const log = accessLogOf(app);
247 await log.flush();
248 const floor = Math.max(query.since.getTime(), now.getTime() - KEEP_DAYS * DAY_MS);
249 const since = new Date(floor).toISOString();
250 const ua = query.ua?.toLowerCase();
251 const names = (await readdir(log.dir).catch(() => [] as string[]))
252 .filter((name) => {
253 const day = FILE.exec(name)?.[1];
254 return day !== undefined && day >= since.slice(0, 10);
255 })
256 .sort()
257 .reverse();
258 const out: AccessLine[] = [];
259 for (const name of names) {
260 const text = await readFile(join(log.dir, name), "utf8").catch(() => "");
261 const lines = text.split("\n");
262 for (let i = lines.length - 1; i >= 0 && out.length < READ_MAX; i--) {
263 const line = parseLine(lines[i] ?? "");
264 if (line === undefined || line.at < since) continue;
265 if (isBrowser(line.ua) || !isPublicPath(line.path)) continue;
266 if (ua !== undefined && !line.ua.toLowerCase().includes(ua)) continue;
267 if (query.path !== undefined && !line.path.startsWith(query.path)) continue;
268 out.push(line);
269 }
270 if (out.length >= READ_MAX) break;
271 }
272 return out;
273 }
274
275 function parseLine(text: string): AccessLine | undefined {
276 if (text === "") return undefined;
277 try {
278 const v = JSON.parse(text) as Partial<AccessLine>;
279 return typeof v.at === "string" &&
280 typeof v.path === "string" &&
281 typeof v.ua === "string"
282 ? (v as AccessLine)
283 : undefined;
284 } catch {
285 return undefined;
286 }
287 }
288
289 /**
290 * `since` as a person or a tool says it: a duration back from now (`30m`,
291 * `6h`, `2d`) or an ISO time. Undefined when it is neither, or reaches
292 * further than the log is kept.
293 */
294 export function parseSince(text: string, now = new Date()): Date | undefined {
295 const t = text.trim();
296 const rel = /^(\d{1,4})([mhd])$/.exec(t);
297 if (rel !== null) {
298 const unit = rel[2] === "m" ? 60_000 : rel[2] === "h" ? 3_600_000 : DAY_MS;
299 const ms = Number(rel[1]) * unit;
300 return ms <= KEEP_DAYS * DAY_MS ? new Date(now.getTime() - ms) : undefined;
301 }
302 if (!/^\d{4}-\d{2}-\d{2}(T[\d:.]+Z?)?$/.test(t)) return undefined;
303 const at = new Date(t);
304 return Number.isNaN(at.getTime()) || now.getTime() - at.getTime() > KEEP_DAYS * DAY_MS
305 ? undefined
306 : at;
307 }
src/http/mcp.ts +38
@@ -75,6 +75,7 @@ import {
7575 } from "../core/asked.ts";
7676 import { frontInput, frontJson, setFront } from "../actions/front.ts";
7777 import { resourceMetadataUrl } from "./oauth.ts";
78 import { parseSince, readAccess } from "./access-log.ts";
7879 import { body, boundedBody, json } from "./respond.ts";
7980 import type { Router } from "./router.ts";
8081 import { manifestFor } from "../actions/here.ts";
@@ -799,6 +800,43 @@ const TOOLS: readonly Tool[] = [
799800 : bad("forbidden", "spend is for those who can write this app");
800801 },
801802 },
803 {
804 name: "access",
805 description:
806 "What outside agents tried on this forge: the non-browser requests to its public doors (issues, /api/, /mcp, /.well-known/, /llms.txt, sign-in, sign-up), newest first, at most 500 — time, host, method, path (never a query string), status, milliseconds, user agent, signed in or not, and a daily hash of the client. `since` is a duration back (30m, 6h, 2d; at most 14d) or an ISO time, default 24h; `ua` matches part of the user agent, `path` the start of the path. For the forge's admins, with a token that may write.",
807 inputSchema: {
808 type: "object",
809 properties: {
810 since: { type: "string" },
811 ua: { type: "string", maxLength: 100 },
812 path: { type: "string", maxLength: 100 },
813 },
814 },
815 writes: false,
816 async run(ctx, user, args) {
817 // Who knocked is the operator's to read, and only with a token
818 // trusted to act: an `ro` token handed to a dashboard never sees it.
819 if (!user.isAdmin || !scopeAllows(ctx.auth.scope ?? "ro", "rw"))
820 return bad("forbidden", "the access log is for the forge's admins, with a write-scoped token");
821 const raw = args["since"];
822 const since =
823 raw === undefined
824 ? parseSince("24h")
825 : typeof raw === "string"
826 ? parseSince(raw)
827 : undefined;
828 if (since === undefined)
829 return bad("invalid_since", "since is 30m, 6h, 2d (at most 14d) or an ISO time");
830 const ua = str(args["ua"]).slice(0, 100);
831 const path = str(args["path"]).slice(0, 100);
832 const requests = await readAccess(ctx.app, {
833 since,
834 ...(ua !== "" ? { ua } : {}),
835 ...(path !== "" ? { path } : {}),
836 });
837 return good({ since: since.toISOString(), requests });
838 },
839 },
802840 {
803841 name: "link",
804842 description:
src/http/server.ts +44 −19
@@ -61,6 +61,7 @@ import {
6161 backupsPage,
6262 backupsTest,
6363 } from "../web/pages/backups.ts";
64 import { accessPage } from "../web/pages/access.ts";
6465 import {
6566 cloudAdd,
6667 cloudAudit,
@@ -300,6 +301,7 @@ import { feedRoutes } from "./feed.ts";
300301 import { mcpRoutes } from "./mcp.ts";
301302 import { oauthRoutes } from "./oauth.ts";
302303 import { clientAddress, notePeer } from "./peer.ts";
304 import { noteRequest } from "./access-log.ts";
303305 import {
304306 reportAcceptSubmit,
305307 reportDismissSubmit,
@@ -343,6 +345,9 @@ import { getVerifiedDomain } from "../core/domains.ts";
343345
344346 const NO_AUTH: Auth = { user: undefined, scope: undefined, via: "none" };
345347
348 /** The requests that arrived signed in, for the access log's one bit. */
349 const signedIn = new WeakSet<Request>();
350
346351 async function resolveAuth(app: App, request: Request): Promise<Auth> {
347352 // The platform edge, when there is one, has already signed this person
348353 // in; its word outranks a cookie of ours.
@@ -563,6 +568,7 @@ export function buildRouter(): Router<Handler> {
563568 router.add("POST", "/settings/cloud/audit", cloudAudit);
564569 router.add("POST", "/settings/cloud/remove", cloudRemove);
565570 router.add("GET", "/settings/backups", backupsPage);
571 router.add("GET", "/settings/access", accessPage);
566572 router.add("POST", "/settings/backups/now", backupsNow);
567573 router.add("POST", "/settings/backups/destination", backupsDestination);
568574 router.add("POST", "/settings/backups/test", backupsTest);
@@ -1408,25 +1414,21 @@ export async function serve(app: App): Promise<Servers> {
14081414 // proxy; its own live surfaces are SSE (`sse.ts`) and stay so.
14091415 websocket: appWebSocket,
14101416 async fetch(request, server) {
1411 // An app's hostname is answered before any route: `hello.<domain>` is
1412 // the app, whatever its path, and the forge's own routes never apply.
1413 const runtime = appsRuntime(app);
1414 if (runtime !== undefined) {
1415 const target = resolveAppHost(app, runtime.options.domain, request);
1416 // A preview's headers are the app's business: what `proxyApp`
1417 // carries back leaves exactly as the app wrote it, which is why the
1418 // floor below sits after this return and not around it.
1419 if (target !== undefined && target !== "unknown")
1420 return proxyApp(runtime, request, target, server);
1421 if (target === "unknown")
1422 return securityFloor(new Response("not found", { status: 404 }));
1423 }
1424 notePeer(request, server.requestIP(request)?.address);
1425 // Everything the forge answers for itself leaves through this one
1426 // door, so a responder added next year cannot forget the floor.
1427 return securityFloor(
1428 await answer(app, router, apiRouter, limiter, request),
1429 );
1417 const started = performance.now();
1418 const address = server.requestIP(request)?.address;
1419 notePeer(request, address);
1420 const response = await answerAny(request, server);
1421 // A websocket upgrade answers nothing; the upgrade is not a page.
1422 if (response !== undefined)
1423 noteRequest(app, {
1424 request,
1425 url: new URL(request.url),
1426 status: response.status,
1427 ms: performance.now() - started,
1428 signedIn: signedIn.has(request),
1429 address: clientAddress(request),
1430 });
1431 return response;
14301432 },
14311433 error(error) {
14321434 const refused = refusedByDatabase(error);
@@ -1450,6 +1452,28 @@ export async function serve(app: App): Promise<Servers> {
14501452 },
14511453 });
14521454
1455 async function answerAny(
1456 request: Request,
1457 server: Parameters<typeof proxyApp>[3],
1458 ): Promise<Response | undefined> {
1459 // An app's hostname is answered before any route: `hello.<domain>` is
1460 // the app, whatever its path, and the forge's own routes never apply.
1461 const runtime = appsRuntime(app);
1462 if (runtime !== undefined) {
1463 const target = resolveAppHost(app, runtime.options.domain, request);
1464 // A preview's headers are the app's business: what `proxyApp`
1465 // carries back leaves exactly as the app wrote it, which is why the
1466 // floor below sits after this return and not around it.
1467 if (target !== undefined && target !== "unknown")
1468 return proxyApp(runtime, request, target, server);
1469 if (target === "unknown")
1470 return securityFloor(new Response("not found", { status: 404 }));
1471 }
1472 // Everything the forge answers for itself leaves through this one
1473 // door, so a responder added next year cannot forget the floor.
1474 return securityFloor(await answer(app, router, apiRouter, limiter, request));
1475 }
1476
14531477 const port = web.port ?? 0;
14541478 return {
14551479 url: `http://localhost:${port}`,
@@ -1532,6 +1556,7 @@ async function answerGet(
15321556 return noRoute(request.method, url.pathname);
15331557 }
15341558 const auth = await resolveAuth(app, request);
1559 if (auth.user !== undefined) signedIn.add(request);
15351560
15361561 // The two things standing between one runaway agent and everybody
15371562 // else's latency, applied before a handler runs and after auth is
src/web/pages/access.ts added +87
@@ -0,0 +1,87 @@
1 /**
2 * The access log, for an admin: what outside agents tried on the forge's
3 * public doors over the last day (or the window asked for) — the
4 * non-browser requests to issues, the API, MCP, the well-known documents,
5 * llms.txt, sign-in and sign-up. Read-only; the filters are a GET form, so
6 * a view is a link one admin can hand another.
7 */
8
9 import { parseSince, readAccess, type AccessLine } from "../../http/access-log.ts";
10 import type { Ctx } from "../../http/context.ts";
11 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
12 import { html, type Html } from "../html.ts";
13 import { page } from "../layout.ts";
14 import { badge, btn, card, empty, field, listCard, row, time } from "../ui.ts";
15 import { accountSections } from "./origins.ts";
16
17 const FILTER_MAX = 100;
18
19 function lineRow(line: AccessLine): Html {
20 const tone =
21 line.status >= 500 ? "danger" : line.status >= 400 ? "attn" : "success";
22 return row({
23 lead: badge(String(line.status), { tone }),
24 title: html`<code>${line.method} ${line.path}</code>`,
25 meta: html`${line.ua === "" ? "no user agent" : line.ua} ·
26 ${time(line.at)} · ${line.host} · ${line.ms} ms ·
27 ${line.signedIn ? "signed in" : "anonymous"} · client
28 <code>${line.client}</code>`,
29 });
30 }
31
32 export async function accessPage(ctx: Ctx): Promise<Response> {
33 if (!ctx.auth.user) return signInFirst(ctx);
34 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
35 const q = ctx.url.searchParams;
36 const sinceText = (q.get("since") ?? "").trim() || "24h";
37 const since = parseSince(sinceText);
38 const ua = (q.get("ua") ?? "").trim().slice(0, FILTER_MAX);
39 const path = (q.get("path") ?? "").trim().slice(0, FILTER_MAX);
40 const lines =
41 since === undefined
42 ? []
43 : await readAccess(ctx.app, {
44 since,
45 ...(ua !== "" ? { ua } : {}),
46 ...(path !== "" ? { path } : {}),
47 });
48 const filters = card(
49 html`<form method="get" action="/settings/access" class="access-filters">
50 ${field({
51 name: "since",
52 label: "Since",
53 value: sinceText,
54 hint: "30m, 6h, 2d (up to 14d), or an ISO time",
55 ...(since === undefined ? { error: "Not a time the log covers" } : {}),
56 })}
57 ${field({ name: "ua", label: "User agent contains", value: ua })}
58 ${field({ name: "path", label: "Path starts with", value: path })}
59 ${btn("Show", { type: "submit" })}
60 </form>`,
61 );
62 const list =
63 lines.length === 0
64 ? empty({
65 icon: "activity",
66 title: "No outside requests",
67 note: "Nothing but browsers reached the public paths in this window.",
68 })
69 : listCard(lines.map(lineRow));
70 const body = html`<p>
71 Non-browser requests to the forge's public doors, newest first, at most
72 500. Kept 14 days under the data directory and never served; a query
73 string, token or cookie is never written, and a client is a hash that
74 changes every day.
75 </p>
76 ${filters} ${list}`;
77 return page({
78 ctx,
79 title: "Access log",
80 body: html`<div class="page-head"><h1>Access log</h1></div>
81 ${settingsLayout(
82 accountSections("access", { admin: true }),
83 body,
84 "Account settings",
85 )}`,
86 });
87 }
src/web/pages/origins.ts +7
@@ -71,6 +71,7 @@ export type AccountSection =
7171 | "accounts"
7272 | "subscriptions"
7373 | "backups"
74 | "access"
7475 | "secrets"
7576 | "cloud";
7677
@@ -123,6 +124,12 @@ export function accountSections(
123124 icon: "download" as const,
124125 current: current === "backups",
125126 },
127 {
128 label: "Access log",
129 href: "/settings/access",
130 icon: "activity" as const,
131 current: current === "access",
132 },
126133 ]
127134 : []),
128135 {
test/access-log.test.ts added +275
@@ -0,0 +1,275 @@
1 /**
2 * The access log: one redacted line per request that is not a static
3 * asset, kept 14 days and capped, read only by the forge's admins — on a
4 * settings page and over MCP with a write-scoped token. The redaction is
5 * proven against the raw files, not the reader: a token, a cookie, a query
6 * string or a client address must never reach the disk at all.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
10 import { mkdirSync } from "node:fs";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { createSession } from "../src/core/sessions.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createUser } from "../src/core/users.ts";
17 import {
18 AccessLog,
19 DAY_CAP,
20 accessLogOf,
21 clientHash,
22 isBrowser,
23 parseSince,
24 type AccessLine,
25 } from "../src/http/access-log.ts";
26 import { serve, type Servers } from "../src/http/server.ts";
27
28 const line = (at: string, path = "/api/v1/user"): AccessLine => ({
29 at,
30 host: "forge.test",
31 method: "GET",
32 path,
33 status: 200,
34 ms: 1,
35 ua: "curl/8",
36 signedIn: false,
37 client: "x",
38 });
39
40 describe("the access log", () => {
41 let dataDir: string;
42 let app: App;
43 let servers: Servers;
44 let base: string;
45 let rw: string;
46 let ro: string;
47 let bobRw: string;
48 let aliceCookie: string;
49 let bobCookie: string;
50 let nextId = 1;
51
52 const raw = async (): Promise<string> => {
53 await accessLogOf(app).flush();
54 const dir = join(dataDir, "access");
55 const names = await readdir(dir);
56 const texts = await Promise.all(names.map((n) => readFile(join(dir, n), "utf8")));
57 return texts.join("");
58 };
59 const lines = async (): Promise<AccessLine[]> =>
60 (await raw())
61 .split("\n")
62 .filter((l) => l !== "")
63 .map((l) => JSON.parse(l) as AccessLine);
64
65 const access = async (token: string, args: unknown = {}) => {
66 const res = await fetch(`${base}/mcp`, {
67 method: "POST",
68 headers: {
69 "content-type": "application/json",
70 authorization: `Bearer ${token}`,
71 },
72 body: JSON.stringify({
73 jsonrpc: "2.0",
74 id: nextId++,
75 method: "tools/call",
76 params: { name: "access", arguments: args },
77 }),
78 });
79 const body = (await res.json()) as any;
80 const text: string = body.result.content[0].text;
81 return body.result.isError === true
82 ? { error: text }
83 : { value: JSON.parse(text) as { requests: AccessLine[] } };
84 };
85
86 beforeAll(async () => {
87 dataDir = await mkdtemp(join(tmpdir(), "forge-access-"));
88 app = createApp({ dataDir, port: 0 });
89 servers = await serve(app);
90 base = servers.url;
91 const a = await createUser(app.db, {
92 username: "alice",
93 email: "[email protected]",
94 password: "a-good-passphrase",
95 adminIfFirst: true,
96 });
97 if (!a.ok) throw new Error(a.error);
98 const b = await createUser(app.db, {
99 username: "bob",
100 email: "[email protected]",
101 password: "a-good-passphrase",
102 });
103 if (!b.ok) throw new Error(b.error);
104 rw = createToken(app.db, a.value.id, "rw", "rw").token;
105 ro = createToken(app.db, a.value.id, "ro", "ro").token;
106 bobRw = createToken(app.db, b.value.id, "rw", "rw").token;
107 aliceCookie = `forge_session=${createSession(app.db, a.value.id).token}`;
108 bobCookie = `forge_session=${createSession(app.db, b.value.id).token}`;
109 // Two argon2 hashes: slow on a busy machine, and not what is under test.
110 }, 30_000);
111
112 afterAll(async () => {
113 servers.stop();
114 app.close();
115 await rm(dataDir, { recursive: true, force: true });
116 });
117
118 test("tokens, cookies, query strings and addresses never reach the disk", async () => {
119 await fetch(`${base}/api/v1/user?access_token=${rw}&q=secret-query`, {
120 headers: {
121 authorization: `Bearer ${rw}`,
122 cookie: aliceCookie,
123 "x-forwarded-for": "203.0.113.9",
124 "user-agent": `agent/1 (${ro}) ${"x".repeat(400)}`,
125 },
126 });
127 await fetch(`${base}/${ro}/issues`, { headers: { "user-agent": "curl/8" } });
128 await fetch(`${base}/go/ABCD1234`, { headers: { "user-agent": "curl/8" } });
129 const text = await raw();
130 expect(text).not.toContain(rw);
131 expect(text).not.toContain(ro);
132 expect(text).not.toContain(aliceCookie.slice("forge_session=".length));
133 expect(text).not.toContain("secret-query");
134 expect(text).not.toContain("access_token");
135 expect(text).not.toContain("?");
136 expect(text).not.toContain("203.0.113.9");
137 expect(text).not.toContain("ABCD1234");
138
139 const user = (await lines()).find((l) => l.path === "/api/v1/user");
140 expect(user).toBeDefined();
141 expect(user!.method).toBe("GET");
142 expect(user!.status).toBe(200);
143 expect(user!.signedIn).toBe(true);
144 expect(user!.ua.length).toBe(200);
145 expect(user!.ua.startsWith("agent/1 (forge_…)")).toBe(true);
146 expect(user!.client).toMatch(/^[0-9a-f]{16}$/);
147 expect(user!.host).toContain("localhost");
148 });
149
150 test("static assets and the health probe are not logged", async () => {
151 await fetch(`${base}/assets/nothing-here.css`);
152 await fetch(`${base}/healthz`);
153 await fetch(`${base}/favicon.ico`);
154 const paths = (await lines()).map((l) => l.path);
155 expect(paths.some((p) => p.startsWith("/assets/"))).toBe(false);
156 expect(paths).not.toContain("/healthz");
157 expect(paths).not.toContain("/favicon.ico");
158 });
159
160 test("a client is one hash within a day and another the next", () => {
161 const key = new Uint8Array(32).fill(7);
162 const today = clientHash(key, "2026-10-05", "203.0.113.9");
163 expect(clientHash(key, "2026-10-05", "203.0.113.9")).toBe(today);
164 expect(clientHash(key, "2026-10-06", "203.0.113.9")).not.toBe(today);
165 expect(clientHash(key, "2026-10-05", "203.0.113.10")).not.toBe(today);
166 });
167
168 test("files older than 14 days go as a new day begins", async () => {
169 const dir = join(dataDir, "rotation");
170 mkdirSync(dir, { recursive: true });
171 for (const day of ["2026-09-01", "2026-09-21", "2026-09-22", "2026-10-04"])
172 await writeFile(join(dir, `${day}.log`), JSON.stringify(line(`${day}T12:00:00.000Z`)) + "\n");
173 const log = new AccessLog(dir);
174 log.record(line("2026-10-05T08:00:00.000Z"));
175 await log.flush();
176 expect((await readdir(dir)).sort()).toEqual([
177 "2026-09-22.log",
178 "2026-10-04.log",
179 "2026-10-05.log",
180 ]);
181 });
182
183 test("a day's file stops growing at its cap", async () => {
184 const dir = join(dataDir, "capped");
185 mkdirSync(dir, { recursive: true });
186 const file = join(dir, "2026-10-05.log");
187 await writeFile(file, "x".repeat(DAY_CAP - 10));
188 const log = new AccessLog(dir);
189 log.record(line("2026-10-05T08:00:00.000Z"));
190 await log.flush();
191 expect((await stat(file)).size).toBe(DAY_CAP - 10);
192 log.record(line("2026-10-06T00:00:01.000Z"));
193 await log.flush();
194 expect((await stat(join(dir, "2026-10-06.log"))).size).toBeGreaterThan(0);
195 });
196
197 test("browsers are told apart from agents", () => {
198 expect(isBrowser("Mozilla/5.0 (X11; Linux x86_64) Firefox/131.0")).toBe(true);
199 expect(isBrowser("Mozilla/5.0 (compatible; ClaudeBot/1.0)")).toBe(false);
200 expect(isBrowser("curl/8.5.0")).toBe(false);
201 expect(isBrowser("")).toBe(false);
202 });
203
204 test("since reads as a duration or a time, never past what is kept", () => {
205 const now = new Date("2026-10-05T12:00:00Z");
206 expect(parseSince("6h", now)?.toISOString()).toBe("2026-10-05T06:00:00.000Z");
207 expect(parseSince("2026-10-01", now)?.toISOString()).toBe("2026-10-01T00:00:00.000Z");
208 expect(parseSince("15d", now)).toBeUndefined();
209 expect(parseSince("2026-09-01", now)).toBeUndefined();
210 expect(parseSince("yesterday", now)).toBeUndefined();
211 });
212
213 test("MCP `access` answers an admin's write token with outside requests only", async () => {
214 await fetch(`${base}/llms.txt`, { headers: { "user-agent": "outside-agent/2" } });
215 await fetch(`${base}/api/v1/repos/nobody/nothing/issues`, {
216 headers: { "user-agent": "outside-agent/2" },
217 });
218 await fetch(`${base}/api/v1/user`, {
219 headers: { "user-agent": "Mozilla/5.0 (X11; Linux x86_64) Firefox/131.0" },
220 });
221 await fetch(`${base}/explore`, { headers: { "user-agent": "outside-agent/2" } });
222
223 const got = await access(rw, { ua: "outside-agent" });
224 if (!("value" in got)) throw new Error(got.error);
225 const paths = got.value.requests.map((r) => r.path);
226 expect(paths).toContain("/llms.txt");
227 expect(paths).toContain("/api/v1/repos/nobody/nothing/issues");
228 expect(paths).not.toContain("/explore");
229 expect(got.value.requests.every((r) => r.ua === "outside-agent/2")).toBe(true);
230 // Newest first.
231 expect(paths[0]).toBe("/api/v1/repos/nobody/nothing/issues");
232
233 const browsers = await access(rw, { ua: "Firefox" });
234 if (!("value" in browsers)) throw new Error(browsers.error);
235 expect(browsers.value.requests).toEqual([]);
236
237 const byPath = await access(rw, { path: "/llms" });
238 if (!("value" in byPath)) throw new Error(byPath.error);
239 expect(byPath.value.requests.every((r) => r.path === "/llms.txt")).toBe(true);
240
241 expect(await access(rw, { since: "40d" })).toEqual({
242 error: expect.stringContaining("invalid_since"),
243 });
244 });
245
246 test("MCP `access` refuses a read token and a non-admin", async () => {
247 expect(await access(ro)).toEqual({ error: expect.stringContaining("forbidden") });
248 expect(await access(bobRw)).toEqual({ error: expect.stringContaining("forbidden") });
249 });
250
251 test("the settings page shows an admin what came in, escaped", async () => {
252 await fetch(`${base}/api/v1/user`, {
253 headers: { "user-agent": "<script>alert(1)</script>" },
254 });
255 const res = await fetch(`${base}/settings/access?since=1h`, {
256 headers: { cookie: aliceCookie },
257 });
258 expect(res.status).toBe(200);
259 const page = await res.text();
260 expect(page).toContain("/llms.txt");
261 expect(page).toContain("outside-agent/2");
262 expect(page).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
263 expect(page).not.toContain("<script>alert(1)</script>");
264 expect(res.headers.get("content-security-policy")).toBeTruthy();
265 });
266
267 test("the settings page is a 404 for anyone but an admin", async () => {
268 const res = await fetch(`${base}/settings/access`, {
269 headers: { cookie: bobCookie },
270 });
271 expect(res.status).toBe(404);
272 const anon = await fetch(`${base}/settings/access`, { redirect: "manual" });
273 expect(anon.status).toBe(303);
274 });
275 });
test/mcp.test.ts +1
@@ -174,6 +174,7 @@ describe("the forge over MCP", () => {
174174 "front_page",
175175 "map",
176176 "usage",
177 "access",
177178 "link",
178179 "unlink",
179180 "plan",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs