Public: anyone can read this; the crew can change it.
See what outside agents tried: a compact, redacted request log the owner can read #1383
scout/forge:scout/1061-see-what-outside-agents-tried-a-compact → main 2 commits fork
10 files
changed +689
−11
docs/APPS.md +13
| @@ -1086,3 +1086,16 @@ refused), `placement` (`"metal"` or `"cloud"`, optional) and `volumes` | ||
| 1086 | 1086 | sync cadence in seconds, 10–86400). `src/apps/service.ts` validates it; the |
| 1087 | 1087 | manifest carries it as `service`, `null` for a web app. Running it, exposing |
| 1088 | 1088 | the ports and syncing volumes are not built yet (issue #391). |
| 1089 | ||
| 1090 | ## The access log | |
| 1091 | ||
| 1092 | The forge keeps one compact JSON line per request that is not a static asset | |
| 1093 | (or `/healthz`) under `<data>/access/access-YYYY-MM-DD.log`: time, host, | |
| 1094 | method, path without its query string (secret-looking segments blanked), | |
| 1095 | status, duration, user agent (200 characters), whether a credential came with | |
| 1096 | it, and a hash of the client address keyed with the data directory's secret | |
| 1097 | and the day. No token, cookie or query string is ever written. Files go after | |
| 1098 | 14 days, a day's file stops at 4 MB and the directory at 32 MB, oldest first. | |
| 1099 | Nothing serves the files. A forge admin reads the last day's non-browser | |
| 1100 | requests to public paths at Settings → Access, or with the `access` MCP tool | |
| 1101 | (`since`, `ua`, `path`; write-scope token). |
scripts/gate.ts +1
| @@ -68,6 +68,7 @@ export const GATE: readonly string[] = [ | ||
| 68 | 68 | "test/decide.test.ts", |
| 69 | 69 | "test/ledger.test.ts", |
| 70 | 70 | "test/capacity.test.ts", |
| 71 | "test/access-log.test.ts", | |
| 71 | 72 | "test/guard-new-accounts.test.ts", |
| 72 | 73 | "test/checks.test.ts", |
| 73 | 74 | "test/dependencies.test.ts", |
src/actions/access_log.ts added +22
| @@ -0,0 +1,22 @@ | ||
| 1 | /** | |
| 2 | * The access log, read by the forge's owner (`http/access_log.ts`): a forge | |
| 3 | * admin only, never an agent, and everyone else is told `not_found`. | |
| 4 | */ | |
| 5 | ||
| 6 | import type { App } from "../app.ts"; | |
| 7 | import { | |
| 8 | readAccess, | |
| 9 | type AccessLine, | |
| 10 | type AccessQuery, | |
| 11 | } from "../http/access_log.ts"; | |
| 12 | import type { User } from "../core/users.ts"; | |
| 13 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 14 | ||
| 15 | export function listAccess( | |
| 16 | app: App, | |
| 17 | actor: User | undefined, | |
| 18 | query: AccessQuery, | |
| 19 | ): Result<AccessLine[], "not_found"> { | |
| 20 | if (actor?.isAdmin !== true || actor.kind === "agent") return err("not_found"); | |
| 21 | return ok(readAccess(app.config.dataDir, query)); | |
| 22 | } |
src/http/access_log.ts added +263
| @@ -0,0 +1,263 @@ | ||
| 1 | /** | |
| 2 | * What outside callers tried: one compact line per request that is not a | |
| 3 | * static asset, kept under `<data>/access/` as one file a day. | |
| 4 | * | |
| 5 | * A line is JSON, built only from parts that are safe to keep: the time, the | |
| 6 | * host, the method, the path without its query string (and with any | |
| 7 | * secret-looking segment blanked), the status, the duration, the first 200 | |
| 8 | * characters of the user agent, whether the caller presented a credential | |
| 9 | * (never which), and a hash of the client address keyed with the data | |
| 10 | * directory's secret and the day — so one caller is one hash for a day and | |
| 11 | * no hash can be walked back to an address or followed across days. Headers | |
| 12 | * other than the user agent, cookies, bodies and queries are never read. | |
| 13 | * | |
| 14 | * Files older than 14 days go, and the directory is capped in total, oldest | |
| 15 | * first; one day's file stops growing at its own cap. Nothing here is served | |
| 16 | * by any route; the owner reads it through `readAccess` (a settings page and | |
| 17 | * the `access` MCP tool). | |
| 18 | */ | |
| 19 | ||
| 20 | import { | |
| 21 | appendFileSync, | |
| 22 | mkdirSync, | |
| 23 | readdirSync, | |
| 24 | readFileSync, | |
| 25 | statSync, | |
| 26 | unlinkSync, | |
| 27 | } from "node:fs"; | |
| 28 | import { createHmac } from "node:crypto"; | |
| 29 | import { join } from "node:path"; | |
| 30 | import { loadKey } from "../kernel/secret.ts"; | |
| 31 | ||
| 32 | export const KEEP_DAYS = 14; | |
| 33 | export const DAY_BYTES = 4 * 1024 * 1024; | |
| 34 | export const TOTAL_BYTES = 32 * 1024 * 1024; | |
| 35 | const UA_MAX = 200; | |
| 36 | const PATH_MAX = 200; | |
| 37 | const HOST_MAX = 100; | |
| 38 | const READ_MAX = 500; | |
| 39 | const DAY_MS = 86_400_000; | |
| 40 | ||
| 41 | /** Paths a caller can reach without signing in, for the owner's view. */ | |
| 42 | export const PUBLIC_PREFIXES = [ | |
| 43 | "/issues", | |
| 44 | "/api/", | |
| 45 | "/mcp", | |
| 46 | "/.well-known/", | |
| 47 | "/llms.txt", | |
| 48 | "/signin", | |
| 49 | "/signup", | |
| 50 | ] as const; | |
| 51 | ||
| 52 | export interface AccessLine { | |
| 53 | /** ISO time the request finished. */ | |
| 54 | readonly t: string; | |
| 55 | readonly host: string; | |
| 56 | readonly method: string; | |
| 57 | readonly path: string; | |
| 58 | readonly status: number; | |
| 59 | readonly ms: number; | |
| 60 | readonly ua: string; | |
| 61 | /** Whether a session cookie or bearer token came with it. */ | |
| 62 | readonly auth: boolean; | |
| 63 | /** Keyed daily hash of the client address. */ | |
| 64 | readonly who: string; | |
| 65 | } | |
| 66 | ||
| 67 | const STATIC = /\.(?:css|js|map|png|jpe?g|gif|svg|ico|webp|avif|woff2?|ttf)$/i; | |
| 68 | ||
| 69 | /** A request the log leaves out: assets, and the platform's own health probe. */ | |
| 70 | export function isQuiet(path: string): boolean { | |
| 71 | return ( | |
| 72 | path.startsWith("/assets/") || path === "/healthz" || STATIC.test(path) | |
| 73 | ); | |
| 74 | } | |
| 75 | ||
| 76 | /** Control characters and DEL removed, then cut: nothing here breaks a line. */ | |
| 77 | const clean = (text: string, max: number): string => | |
| 78 | // eslint-disable-next-line no-control-regex | |
| 79 | text.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, max); | |
| 80 | ||
| 81 | /** | |
| 82 | * A path as it may be kept: no query, and a segment that could be a secret | |
| 83 | * (a long run of token characters, or a forge token's own prefix) blanked. | |
| 84 | */ | |
| 85 | export function keptPath(pathname: string): string { | |
| 86 | const segments = pathname.split("/").map((s) => { | |
| 87 | let seg = s; | |
| 88 | try { | |
| 89 | seg = decodeURIComponent(s); | |
| 90 | } catch { | |
| 91 | // keep the raw text; it is judged the same way | |
| 92 | } | |
| 93 | return /^[A-Za-z0-9_~.+=-]{24,}$/.test(seg) || /^(?:frg|forge|fgt)_/i.test(seg) | |
| 94 | ? ":redacted" | |
| 95 | : s; | |
| 96 | }); | |
| 97 | return clean(segments.join("/"), PATH_MAX); | |
| 98 | } | |
| 99 | ||
| 100 | const dayOf = (at: Date): string => at.toISOString().slice(0, 10); | |
| 101 | const fileOf = (dir: string, day: string): string => | |
| 102 | join(dir, `access-${day}.log`); | |
| 103 | export const accessDir = (dataDir: string): string => join(dataDir, "access"); | |
| 104 | ||
| 105 | /** The client, as one hash for one day. */ | |
| 106 | export function clientHash(dataDir: string, address: string, at: Date): string { | |
| 107 | return createHmac("sha256", loadKey(dataDir)) | |
| 108 | .update(`access:${dayOf(at)}:${address}`) | |
| 109 | .digest("hex") | |
| 110 | .slice(0, 16); | |
| 111 | } | |
| 112 | ||
| 113 | export interface Seen { | |
| 114 | readonly request: Request; | |
| 115 | readonly status: number; | |
| 116 | readonly ms: number; | |
| 117 | readonly client: string; | |
| 118 | } | |
| 119 | ||
| 120 | /** The line for a request, or undefined when it is not logged. */ | |
| 121 | export function lineFor( | |
| 122 | dataDir: string, | |
| 123 | seen: Seen, | |
| 124 | at: Date, | |
| 125 | ): AccessLine | undefined { | |
| 126 | let url: URL; | |
| 127 | try { | |
| 128 | url = new URL(seen.request.url); | |
| 129 | } catch { | |
| 130 | return undefined; | |
| 131 | } | |
| 132 | if (isQuiet(url.pathname)) return undefined; | |
| 133 | const h = seen.request.headers; | |
| 134 | return { | |
| 135 | t: at.toISOString(), | |
| 136 | host: clean((h.get("host") ?? url.host).toLowerCase(), HOST_MAX), | |
| 137 | method: clean(seen.request.method, 16), | |
| 138 | path: keptPath(url.pathname), | |
| 139 | status: seen.status, | |
| 140 | ms: Math.round(seen.ms), | |
| 141 | ua: clean(h.get("user-agent") ?? "", UA_MAX), | |
| 142 | auth: /(?:^|;\s*)forge_session=/.test(h.get("cookie") ?? "") || | |
| 143 | (h.get("authorization") ?? "") !== "", | |
| 144 | who: clientHash(dataDir, seen.client, at), | |
| 145 | }; | |
| 146 | } | |
| 147 | ||
| 148 | let pruned = ""; | |
| 149 | ||
| 150 | /** Drop files past their days, then the oldest until the directory fits. */ | |
| 151 | export function prune(dataDir: string, at: Date): void { | |
| 152 | const dir = accessDir(dataDir); | |
| 153 | const oldest = dayOf(new Date(at.getTime() - (KEEP_DAYS - 1) * DAY_MS)); | |
| 154 | const files = readdirSync(dir) | |
| 155 | .filter((f) => /^access-\d{4}-\d{2}-\d{2}\.log$/.test(f)) | |
| 156 | .sort(); | |
| 157 | const kept: string[] = []; | |
| 158 | for (const f of files) { | |
| 159 | if (f.slice(7, 17) < oldest) unlinkSync(join(dir, f)); | |
| 160 | else kept.push(f); | |
| 161 | } | |
| 162 | let total = kept.reduce((n, f) => n + statSync(join(dir, f)).size, 0); | |
| 163 | for (const f of kept) { | |
| 164 | if (total <= TOTAL_BYTES || f === kept[kept.length - 1]) break; | |
| 165 | total -= statSync(join(dir, f)).size; | |
| 166 | unlinkSync(join(dir, f)); | |
| 167 | } | |
| 168 | } | |
| 169 | ||
| 170 | /** Keep a request. Never throws: a full disk must not fail a request. */ | |
| 171 | export function recordAccess( | |
| 172 | dataDir: string, | |
| 173 | seen: Seen, | |
| 174 | at: Date = new Date(), | |
| 175 | ): void { | |
| 176 | try { | |
| 177 | const line = lineFor(dataDir, seen, at); | |
| 178 | if (line === undefined) return; | |
| 179 | const dir = accessDir(dataDir); | |
| 180 | mkdirSync(dir, { recursive: true, mode: 0o700 }); | |
| 181 | const day = dayOf(at); | |
| 182 | if (pruned !== `${dir}:${day}`) { | |
| 183 | pruned = `${dir}:${day}`; | |
| 184 | prune(dataDir, at); | |
| 185 | } | |
| 186 | const file = fileOf(dir, day); | |
| 187 | let size = 0; | |
| 188 | try { | |
| 189 | size = statSync(file).size; | |
| 190 | } catch { | |
| 191 | // no file yet | |
| 192 | } | |
| 193 | if (size >= DAY_BYTES) return; | |
| 194 | appendFileSync(file, `${JSON.stringify(line)}\n`, { mode: 0o600 }); | |
| 195 | } catch { | |
| 196 | // the log is a convenience; the request is the work | |
| 197 | } | |
| 198 | } | |
| 199 | ||
| 200 | export interface AccessQuery { | |
| 201 | /** ISO time to read from; the last day when absent or unreadable. */ | |
| 202 | readonly since?: string; | |
| 203 | /** Case-insensitive part of the user agent. */ | |
| 204 | readonly ua?: string; | |
| 205 | /** Start of the path. */ | |
| 206 | readonly path?: string; | |
| 207 | } | |
| 208 | ||
| 209 | /** A browser says so in its user agent; an agent, a script or a probe does not. */ | |
| 210 | export const isBrowser = (ua: string): boolean => ua.includes("Mozilla/"); | |
| 211 | ||
| 212 | const isPublic = (path: string): boolean => | |
| 213 | PUBLIC_PREFIXES.some((p) => path.startsWith(p)); | |
| 214 | ||
| 215 | /** | |
| 216 | * The last day's (or `since`'s) non-browser requests to public paths, newest | |
| 217 | * first, at most 500. | |
| 218 | */ | |
| 219 | export function readAccess( | |
| 220 | dataDir: string, | |
| 221 | query: AccessQuery, | |
| 222 | now: Date = new Date(), | |
| 223 | ): AccessLine[] { | |
| 224 | const floor = now.getTime() - KEEP_DAYS * DAY_MS; | |
| 225 | const parsed = query.since === undefined ? NaN : Date.parse(query.since); | |
| 226 | const from = Math.max( | |
| 227 | Number.isNaN(parsed) ? now.getTime() - DAY_MS : parsed, | |
| 228 | floor, | |
| 229 | ); | |
| 230 | const ua = query.ua?.toLowerCase(); | |
| 231 | const dir = accessDir(dataDir); | |
| 232 | let files: string[]; | |
| 233 | try { | |
| 234 | files = readdirSync(dir) | |
| 235 | .filter((f) => /^access-\d{4}-\d{2}-\d{2}\.log$/.test(f)) | |
| 236 | .filter((f) => f.slice(7, 17) >= dayOf(new Date(from))) | |
| 237 | .sort() | |
| 238 | .reverse(); | |
| 239 | } catch { | |
| 240 | return []; | |
| 241 | } | |
| 242 | const out: AccessLine[] = []; | |
| 243 | for (const f of files) { | |
| 244 | const lines = readFileSync(join(dir, f), "utf8").split("\n").reverse(); | |
| 245 | for (const raw of lines) { | |
| 246 | if (raw === "") continue; | |
| 247 | let line: AccessLine; | |
| 248 | try { | |
| 249 | line = JSON.parse(raw) as AccessLine; | |
| 250 | } catch { | |
| 251 | continue; | |
| 252 | } | |
| 253 | if (Date.parse(line.t) < from) continue; | |
| 254 | if (isBrowser(line.ua) || !isPublic(line.path)) continue; | |
| 255 | if (ua !== undefined && !line.ua.toLowerCase().includes(ua)) continue; | |
| 256 | if (query.path !== undefined && !line.path.startsWith(query.path)) | |
| 257 | continue; | |
| 258 | out.push(line); | |
| 259 | if (out.length >= READ_MAX) return out; | |
| 260 | } | |
| 261 | } | |
| 262 | return out; | |
| 263 | } |
src/http/mcp.ts +29
| @@ -18,6 +18,7 @@ | ||
| 18 | 18 | */ |
| 19 | 19 | |
| 20 | 20 | import { mayView, mayViewId, sealedScope } from "../core/sealed.ts"; |
| 21 | import { listAccess } from "../actions/access_log.ts"; | |
| 21 | 22 | import { changeCapacity, listCapacity } from "../actions/capacity.ts"; |
| 22 | 23 | import { relationOf, takeUpdates } from "../actions/forks.ts"; |
| 23 | 24 | import { watchMilestone } from "../actions/watches.ts"; |
| @@ -1596,6 +1597,34 @@ const TOOLS: readonly Tool[] = [ | ||
| 1596 | 1597 | }); |
| 1597 | 1598 | }, |
| 1598 | 1599 | }, |
| 1600 | { | |
| 1601 | name: "access", | |
| 1602 | description: | |
| 1603 | "What outside agents tried: the forge's own request log, redacted, for a forge admin. Non-browser requests to public paths (/issues, /api/, /mcp, /.well-known/, /llms.txt, sign-in, sign-up), newest first, at most 500: time, host, method, path without query, status, duration in ms, user agent, whether a credential came with it, and a daily hash of the caller (never an address). `since` is an ISO time (the last day when absent; at most 14 days back), `ua` a part of the user agent, `path` the start of the path. Needs a write-scope token. The same as Settings → Access.", | |
| 1604 | inputSchema: { | |
| 1605 | type: "object", | |
| 1606 | properties: { | |
| 1607 | since: { type: "string", maxLength: 40 }, | |
| 1608 | ua: { type: "string", maxLength: 100 }, | |
| 1609 | path: { type: "string", maxLength: 200 }, | |
| 1610 | }, | |
| 1611 | }, | |
| 1612 | writes: true, | |
| 1613 | run(ctx, user, args) { | |
| 1614 | const text = (k: string): string | undefined => | |
| 1615 | typeof args[k] === "string" && args[k] !== "" ? (args[k] as string) : undefined; | |
| 1616 | const since = text("since"); | |
| 1617 | const ua = text("ua"); | |
| 1618 | const path = text("path"); | |
| 1619 | const listed = listAccess(ctx.app, user, { | |
| 1620 | ...(since === undefined ? {} : { since: since.slice(0, 40) }), | |
| 1621 | ...(ua === undefined ? {} : { ua: ua.slice(0, 100) }), | |
| 1622 | ...(path === undefined ? {} : { path: path.slice(0, 200) }), | |
| 1623 | }); | |
| 1624 | if (!listed.ok) return bad("not_found", "no such tool here"); | |
| 1625 | return good({ requests: listed.value }); | |
| 1626 | }, | |
| 1627 | }, | |
| 1599 | 1628 | { |
| 1600 | 1629 | name: "capacity", |
| 1601 | 1630 | description: |
src/http/server.ts +32 −11
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | 8 | import { unsealReleased } from "../actions/sealed.ts"; |
| 9 | import { accessPage } from "../web/pages/access.ts"; | |
| 9 | 10 | import { capacityPage, capacitySet } from "../web/pages/capacity.ts"; |
| 10 | 11 | import { |
| 11 | 12 | closeStreamsOf, |
| @@ -355,6 +356,7 @@ import { apiRoutes } from "./api.ts"; | ||
| 355 | 356 | import { feedRoutes } from "./feed.ts"; |
| 356 | 357 | import { mcpRoutes } from "./mcp.ts"; |
| 357 | 358 | import { oauthRoutes } from "./oauth.ts"; |
| 359 | import { recordAccess } from "./access_log.ts"; | |
| 358 | 360 | import { carryPeer, clientAddress, notePeer, type ProxyTrust } from "./peer.ts"; |
| 359 | 361 | import { parseCidrs } from "../kernel/cidr.ts"; |
| 360 | 362 | import { |
| @@ -395,6 +397,7 @@ import { getUserById } from "../core/users.ts"; | ||
| 395 | 397 | import { appsRuntime } from "../apps/runtime.ts"; |
| 396 | 398 | import { |
| 397 | 399 | appWebSocket, |
| 400 | type AppSocket, | |
| 398 | 401 | proxyApp, |
| 399 | 402 | resolveAppHost, |
| 400 | 403 | } from "../apps/proxy.ts"; |
| @@ -646,6 +649,7 @@ export function buildRouter(): Router<Handler> { | ||
| 646 | 649 | router.add("POST", "/settings/cloud/write", cloudWrite); |
| 647 | 650 | router.add("POST", "/settings/cloud/audit", cloudAudit); |
| 648 | 651 | router.add("POST", "/settings/cloud/remove", cloudRemove); |
| 652 | router.add("GET", "/settings/access", accessPage); | |
| 649 | 653 | router.add("GET", "/settings/capacity", capacityPage); |
| 650 | 654 | router.add("POST", "/settings/capacity", capacitySet); |
| 651 | 655 | router.add("GET", "/settings/backups", backupsPage); |
| @@ -1643,17 +1647,10 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1643 | 1647 | : { header: app.config.clientIpHeader }), |
| 1644 | 1648 | }; |
| 1645 | 1649 | |
| 1646 | const web = Bun.serve({ | |
| 1647 | port: app.config.port ?? 3000, | |
| 1648 | idleTimeout: 120, | |
| 1649 | // The largest thing anyone may send — a git push. Every reader below it | |
| 1650 | // keeps its own, smaller cap (\`http/limits.ts\`); the runtime enforces | |
| 1651 | // this one only on a declared length. | |
| 1652 | maxRequestBodySize: REQUEST_MAX, | |
| 1653 | // The only sockets the forge holds are an app's, carried through the | |
| 1654 | // proxy; its own live surfaces are SSE (`sse.ts`) and stay so. | |
| 1655 | websocket: appWebSocket, | |
| 1656 | async fetch(request, server) { | |
| 1650 | const handle = async ( | |
| 1651 | request: Request, | |
| 1652 | server: Bun.Server<AppSocket>, | |
| 1653 | ): Promise<Response | undefined> => { | |
| 1657 | 1654 | // An app's hostname is answered before any route: `hello.<domain>` is |
| 1658 | 1655 | // the app, whatever its path, and the forge's own routes never apply. |
| 1659 | 1656 | const runtime = appsRuntime(app); |
| @@ -1704,6 +1701,30 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1704 | 1701 | // Said, so no client or proxy reuses it; then done, so none can. |
| 1705 | 1702 | server.timeout(request, 1); |
| 1706 | 1703 | return withHeader(response, "connection", "close"); |
| 1704 | }; | |
| 1705 | ||
| 1706 | const web = Bun.serve({ | |
| 1707 | port: app.config.port ?? 3000, | |
| 1708 | idleTimeout: 120, | |
| 1709 | // The largest thing anyone may send — a git push. Every reader below it | |
| 1710 | // keeps its own, smaller cap (\`http/limits.ts\`); the runtime enforces | |
| 1711 | // this one only on a declared length. | |
| 1712 | maxRequestBodySize: REQUEST_MAX, | |
| 1713 | // The only sockets the forge holds are an app's, carried through the | |
| 1714 | // proxy; its own live surfaces are SSE (`sse.ts`) and stay so. | |
| 1715 | websocket: appWebSocket, | |
| 1716 | async fetch(request, server) { | |
| 1717 | const started = performance.now(); | |
| 1718 | const response = await handle(request, server); | |
| 1719 | // An upgraded socket has no response to log. | |
| 1720 | if (response !== undefined) | |
| 1721 | recordAccess(app.config.dataDir, { | |
| 1722 | request, | |
| 1723 | status: response.status, | |
| 1724 | ms: performance.now() - started, | |
| 1725 | client: clientAddress(request), | |
| 1726 | }); | |
| 1727 | return response; | |
| 1707 | 1728 | }, |
| 1708 | 1729 | error(error) { |
| 1709 | 1730 | const refused = refusedByDatabase(error); |
src/web/pages/access.ts added +86
| @@ -0,0 +1,86 @@ | ||
| 1 | /** | |
| 2 | * What outside agents tried, for a forge admin: the last day's non-browser | |
| 3 | * requests to public paths (`http/access_log.ts`), filterable by user agent | |
| 4 | * and path. The log holds no token, cookie or query string, and a hash — | |
| 5 | * never an address — stands for the caller. | |
| 6 | */ | |
| 7 | ||
| 8 | import { listAccess } from "../../actions/access_log.ts"; | |
| 9 | import type { Ctx } from "../../http/context.ts"; | |
| 10 | import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts"; | |
| 11 | import { html } from "../html.ts"; | |
| 12 | import { page } from "../layout.ts"; | |
| 13 | import { btn, card, icon, row } from "../ui.ts"; | |
| 14 | import { accountSections } from "./origins.ts"; | |
| 15 | ||
| 16 | // GET /settings/access | |
| 17 | export function accessPage(ctx: Ctx): Response { | |
| 18 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 19 | const ua = ctx.url.searchParams.get("ua")?.slice(0, 100) ?? ""; | |
| 20 | const path = ctx.url.searchParams.get("path")?.slice(0, 200) ?? ""; | |
| 21 | const listed = listAccess(ctx.app, ctx.auth.user, { | |
| 22 | ...(ua === "" ? {} : { ua }), | |
| 23 | ...(path === "" ? {} : { path }), | |
| 24 | }); | |
| 25 | if (!listed.ok) return notFoundPage(ctx); | |
| 26 | const rows = listed.value.map((l) => | |
| 27 | row({ | |
| 28 | lead: icon("activity"), | |
| 29 | title: html`<span class="mono">${l.method} ${l.path}</span> | |
| 30 | <span class="mono">${String(l.status)}</span>`, | |
| 31 | meta: html`${l.t} · ${l.host} · ${String(l.ms)} ms · | |
| 32 | ${l.auth ? "signed in" : "anonymous"} · | |
| 33 | <span class="mono">${l.who}</span> · | |
| 34 | ${l.ua === "" ? "no user agent" : l.ua}`, | |
| 35 | }), | |
| 36 | ); | |
| 37 | const body = html`${card( | |
| 38 | html`<div class="card-body"> | |
| 39 | <p class="muted small"> | |
| 40 | The last day's requests from anything that is not a browser, to | |
| 41 | public paths (issues, the API, MCP, discovery files, sign-in and | |
| 42 | sign-up). Tokens, cookies and query strings are never kept; the | |
| 43 | hash stands for one caller for one day. | |
| 44 | </p> | |
| 45 | <form class="row-actions" method="get" action="/settings/access"> | |
| 46 | <input | |
| 47 | class="input" | |
| 48 | name="ua" | |
| 49 | value="${ua}" | |
| 50 | placeholder="User agent contains" | |
| 51 | aria-label="User agent contains" | |
| 52 | /> | |
| 53 | <input | |
| 54 | class="input mono" | |
| 55 | name="path" | |
| 56 | value="${path}" | |
| 57 | placeholder="/api/" | |
| 58 | aria-label="Path starts with" | |
| 59 | /> | |
| 60 | ${btn("Filter", { size: "sm", variant: "primary" })} | |
| 61 | </form> | |
| 62 | </div> | |
| 63 | ${rows.length === 0 | |
| 64 | ? html`<div class="card-body"> | |
| 65 | <p class="muted small" id="access-none">Nothing in the last day.</p> | |
| 66 | </div>` | |
| 67 | : html`<ul class="list" id="access-list"> | |
| 68 | ${rows} | |
| 69 | </ul>`}`, | |
| 70 | { | |
| 71 | head: html`${icon("activity")} | |
| 72 | <h2>Outside requests</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( | |
| 81 | accountSections("access", { admin: true }), | |
| 82 | body, | |
| 83 | "Account settings", | |
| 84 | )}`, | |
| 85 | }); | |
| 86 | } |
src/web/pages/origins.ts +7
| @@ -80,6 +80,7 @@ export type AccountSection = | ||
| 80 | 80 | | "backups" |
| 81 | 81 | | "secrets" |
| 82 | 82 | | "capacity" |
| 83 | | "access" | |
| 83 | 84 | | "cloud"; |
| 84 | 85 | |
| 85 | 86 | /** |
| @@ -131,6 +132,12 @@ export function accountSections( | ||
| 131 | 132 | icon: "activity" as const, |
| 132 | 133 | current: current === "capacity", |
| 133 | 134 | }, |
| 135 | { | |
| 136 | label: "Access", | |
| 137 | href: "/settings/access", | |
| 138 | icon: "activity" as const, | |
| 139 | current: current === "access", | |
| 140 | }, | |
| 134 | 141 | { |
| 135 | 142 | label: "Backups", |
| 136 | 143 | href: "/settings/backups", |
test/access-log.test.ts added +235
| @@ -0,0 +1,235 @@ | ||
| 1 | /** | |
| 2 | * What outside agents tried (#1061): one compact line per request that is | |
| 3 | * not a static asset, with no token, cookie, query string or address in it, | |
| 4 | * kept 14 days and size-capped, and readable only by a forge admin through | |
| 5 | * Settings → Access and the `access` MCP tool (write scope). | |
| 6 | */ | |
| 7 | ||
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdirSync, readdirSync, readFileSync, writeFileSync } 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 { | |
| 17 | accessDir, | |
| 18 | keptPath, | |
| 19 | prune, | |
| 20 | readAccess, | |
| 21 | recordAccess, | |
| 22 | TOTAL_BYTES, | |
| 23 | } from "../src/http/access_log.ts"; | |
| 24 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 25 | ||
| 26 | const logText = (dir: string): string => | |
| 27 | readdirSync(accessDir(dir)) | |
| 28 | .map((f) => readFileSync(join(accessDir(dir), f), "utf8")) | |
| 29 | .join(""); | |
| 30 | ||
| 31 | describe("the access log", () => { | |
| 32 | let dataDir: string; | |
| 33 | let app: App; | |
| 34 | let servers: Servers; | |
| 35 | let adminRw: string; | |
| 36 | let adminRo: string; | |
| 37 | let bobRw: string; | |
| 38 | ||
| 39 | const mcp = async (token: string, args: Record<string, unknown>) => { | |
| 40 | const res = await fetch(`${servers.url}/mcp`, { | |
| 41 | method: "POST", | |
| 42 | headers: { | |
| 43 | authorization: `Bearer ${token}`, | |
| 44 | "content-type": "application/json", | |
| 45 | accept: "application/json, text/event-stream", | |
| 46 | }, | |
| 47 | body: JSON.stringify({ | |
| 48 | jsonrpc: "2.0", | |
| 49 | id: 1, | |
| 50 | method: "tools/call", | |
| 51 | params: { name: "access", arguments: args }, | |
| 52 | }), | |
| 53 | }); | |
| 54 | const body = (await res.json()) as { | |
| 55 | result: { isError?: boolean; content: { text: string }[] }; | |
| 56 | }; | |
| 57 | return { | |
| 58 | error: body.result.isError === true, | |
| 59 | text: body.result.content[0]!.text, | |
| 60 | }; | |
| 61 | }; | |
| 62 | ||
| 63 | beforeAll(async () => { | |
| 64 | dataDir = await mkdtemp(join(tmpdir(), "forge-access-")); | |
| 65 | app = createApp({ dataDir, port: 0 }); | |
| 66 | servers = await serve(app); | |
| 67 | const a = await createUser(app.db, { | |
| 68 | trusted: true, | |
| 69 | username: "alice", | |
| 70 | email: "[email protected]", | |
| 71 | password: "a-good-passphrase", | |
| 72 | adminIfFirst: true, | |
| 73 | }); | |
| 74 | const b = await createUser(app.db, { | |
| 75 | trusted: true, | |
| 76 | username: "bob", | |
| 77 | email: "[email protected]", | |
| 78 | password: "a-good-passphrase", | |
| 79 | }); | |
| 80 | if (!a.ok || !b.ok) throw new Error("users"); | |
| 81 | adminRw = createToken(app.db, a.value.id, "t", "rw").token; | |
| 82 | adminRo = createToken(app.db, a.value.id, "t", "ro").token; | |
| 83 | bobRw = createToken(app.db, b.value.id, "t", "rw").token; | |
| 84 | }); | |
| 85 | ||
| 86 | afterAll(async () => { | |
| 87 | servers.stop(); | |
| 88 | app.close(); | |
| 89 | await rm(dataDir, { recursive: true, force: true }); | |
| 90 | }); | |
| 91 | ||
| 92 | test("a replayed agent request is kept, redacted, and read back", async () => { | |
| 93 | const secret = "forge_SECRETTOKENVALUE0123456789abcdef"; | |
| 94 | await fetch(`${servers.url}/api/v1/nothing-here?token=${secret}&q=hunter2`, { | |
| 95 | headers: { | |
| 96 | "user-agent": "ExampleAgent/1.0 (+https://example.test)", | |
| 97 | authorization: `Bearer ${secret}`, | |
| 98 | cookie: "forge_session=COOKIEVALUE123; other=zzz", | |
| 99 | }, | |
| 100 | }); | |
| 101 | await fetch(`${servers.url}/mcp`, { | |
| 102 | method: "POST", | |
| 103 | headers: { "user-agent": "ExampleAgent/1.0" }, | |
| 104 | body: "{}", | |
| 105 | }); | |
| 106 | // A browser and a static asset are not what this reads. | |
| 107 | await fetch(`${servers.url}/issues`, { | |
| 108 | headers: { "user-agent": "Mozilla/5.0 (X11) Firefox/130" }, | |
| 109 | }); | |
| 110 | await fetch(`${servers.url}/assets/missing.css`); | |
| 111 | ||
| 112 | const raw = logText(dataDir); | |
| 113 | for (const leak of [secret, "SECRETTOKENVALUE", "hunter2", "COOKIEVALUE", "zzz", "q=", "127.0.0.1"]) | |
| 114 | expect(raw).not.toContain(leak); | |
| 115 | expect(raw).not.toContain("assets"); | |
| 116 | const lines = raw.trim().split("\n").map((l) => JSON.parse(l)); | |
| 117 | const hit = lines.find((l) => l.path === "/api/v1/nothing-here"); | |
| 118 | expect(hit).toMatchObject({ | |
| 119 | method: "GET", | |
| 120 | status: 404, | |
| 121 | auth: true, | |
| 122 | ua: "ExampleAgent/1.0 (+https://example.test)", | |
| 123 | }); | |
| 124 | expect(hit.who).toMatch(/^[0-9a-f]{16}$/); | |
| 125 | expect(typeof hit.ms).toBe("number"); | |
| 126 | ||
| 127 | const read = await mcp(adminRw, { ua: "exampleagent" }); | |
| 128 | expect(read.error).toBe(false); | |
| 129 | const rows = JSON.parse(read.text).requests as { path: string; ua: string }[]; | |
| 130 | expect(rows.map((r) => r.path)).toContain("/api/v1/nothing-here"); | |
| 131 | expect(rows.every((r) => !r.ua.includes("Mozilla"))).toBe(true); | |
| 132 | const narrow = JSON.parse((await mcp(adminRw, { path: "/mcp" })).text).requests; | |
| 133 | expect(narrow.every((r: { path: string }) => r.path.startsWith("/mcp"))).toBe(true); | |
| 134 | expect(narrow.length).toBeGreaterThan(0); | |
| 135 | }); | |
| 136 | ||
| 137 | test("a path never carries a secret-looking segment or a long line", () => { | |
| 138 | expect(keptPath("/claim/abcdefghijklmnopqrstuvwxyz0123")).toBe("/claim/:redacted"); | |
| 139 | expect(keptPath("/x/forge_abc")).toBe("/x/:redacted"); | |
| 140 | expect(keptPath("/issues/12")).toBe("/issues/12"); | |
| 141 | expect(keptPath("/a\n/b" + "c".repeat(500)).length).toBeLessThanOrEqual(200); | |
| 142 | expect(keptPath("/a\nb")).not.toContain("\n"); | |
| 143 | }); | |
| 144 | ||
| 145 | test("only an admin with write scope reads it, on the page and by MCP", async () => { | |
| 146 | expect((await mcp(adminRo, {})).error).toBe(true); | |
| 147 | expect((await mcp(adminRo, {})).text).toContain("forbidden"); | |
| 148 | const bob = await mcp(bobRw, {}); | |
| 149 | expect(bob.error).toBe(true); | |
| 150 | expect(bob.text).toContain("not_found"); | |
| 151 | const anon = await fetch(`${servers.url}/settings/access`, { redirect: "manual" }); | |
| 152 | expect(anon.status).not.toBe(200); | |
| 153 | }); | |
| 154 | ||
| 155 | test("the settings page lists what was tried, escaped", async () => { | |
| 156 | const res = await fetch(`${servers.url}/signin`, { | |
| 157 | method: "POST", | |
| 158 | redirect: "manual", | |
| 159 | headers: { | |
| 160 | "content-type": "application/x-www-form-urlencoded", | |
| 161 | origin: servers.url, | |
| 162 | }, | |
| 163 | body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }), | |
| 164 | }); | |
| 165 | const cookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? ""; | |
| 166 | await fetch(`${servers.url}/api/v1/x`, { | |
| 167 | headers: { "user-agent": "<script>alert(1)</script>-bot" }, | |
| 168 | }); | |
| 169 | const page = await fetch(`${servers.url}/settings/access`, { headers: { cookie } }); | |
| 170 | expect(page.status).toBe(200); | |
| 171 | const html = await page.text(); | |
| 172 | expect(html).toContain("Outside requests"); | |
| 173 | expect(html).toContain("/api/v1/nothing-here"); | |
| 174 | expect(html).not.toContain("<script>alert(1)</script>-bot"); | |
| 175 | expect(html).toContain("<script>"); | |
| 176 | }); | |
| 177 | }); | |
| 178 | ||
| 179 | describe("the access log's keeping", () => { | |
| 180 | test("files older than 14 days go, and the directory stays under its cap", async () => { | |
| 181 | const dir = await mkdtemp(join(tmpdir(), "forge-access-rot-")); | |
| 182 | try { | |
| 183 | const keep = accessDir(dir); | |
| 184 | mkdirSync(keep, { recursive: true }); | |
| 185 | writeFileSync(join(keep, "access-2026-09-01.log"), "old\n"); | |
| 186 | writeFileSync(join(keep, "access-2026-09-30.log"), "recent\n"); | |
| 187 | const now = new Date("2026-10-13T12:00:00Z"); | |
| 188 | prune(dir, now); | |
| 189 | expect(readdirSync(keep)).toEqual(["access-2026-09-30.log"]); | |
| 190 | // Over the cap: the oldest goes first, today's file always stays. | |
| 191 | const big = "x".repeat(TOTAL_BYTES / 2 + 1); | |
| 192 | writeFileSync(join(keep, "access-2026-10-10.log"), big); | |
| 193 | writeFileSync(join(keep, "access-2026-10-11.log"), big); | |
| 194 | writeFileSync(join(keep, "access-2026-10-13.log"), "today\n"); | |
| 195 | prune(dir, now); | |
| 196 | expect(readdirSync(keep).sort()).toEqual([ | |
| 197 | "access-2026-10-11.log", | |
| 198 | "access-2026-10-13.log", | |
| 199 | ]); | |
| 200 | } finally { | |
| 201 | await rm(dir, { recursive: true, force: true }); | |
| 202 | } | |
| 203 | }); | |
| 204 | ||
| 205 | test("recording prunes on a new day, and the hash changes with the day", async () => { | |
| 206 | const dir = await mkdtemp(join(tmpdir(), "forge-access-day-")); | |
| 207 | try { | |
| 208 | const seen = (path: string) => ({ | |
| 209 | request: new Request(`http://forge.test${path}?k=v`, { | |
| 210 | headers: { "user-agent": "bot" }, | |
| 211 | }), | |
| 212 | status: 200, | |
| 213 | ms: 3.4, | |
| 214 | client: "203.0.113.9", | |
| 215 | }); | |
| 216 | mkdirSync(accessDir(dir), { recursive: true }); | |
| 217 | writeFileSync(join(accessDir(dir), "access-2026-09-01.log"), "old\n"); | |
| 218 | recordAccess(dir, seen("/llms.txt"), new Date("2026-10-13T01:00:00Z")); | |
| 219 | recordAccess(dir, seen("/llms.txt"), new Date("2026-10-14T01:00:00Z")); | |
| 220 | expect(readdirSync(accessDir(dir)).sort()).toEqual([ | |
| 221 | "access-2026-10-13.log", | |
| 222 | "access-2026-10-14.log", | |
| 223 | ]); | |
| 224 | const [a, b] = readdirSync(accessDir(dir)) | |
| 225 | .sort() | |
| 226 | .map((f) => JSON.parse(readFileSync(join(accessDir(dir), f), "utf8"))); | |
| 227 | expect(a.who).not.toBe(b.who); | |
| 228 | expect(logText(dir)).not.toContain("203.0.113.9"); | |
| 229 | const rows = readAccess(dir, { since: "2026-10-13T00:00:00Z" }, new Date("2026-10-14T02:00:00Z")); | |
| 230 | expect(rows.map((r) => r.path)).toEqual(["/llms.txt", "/llms.txt"]); | |
| 231 | } finally { | |
| 232 | await rm(dir, { recursive: true, force: true }); | |
| 233 | } | |
| 234 | }); | |
| 235 | }); |
test/mcp.test.ts +1
| @@ -193,6 +193,7 @@ describe("the forge over MCP", () => { | ||
| 193 | 193 | "unlink", |
| 194 | 194 | "hold", |
| 195 | 195 | "plan", |
| 196 | "access", | |
| 196 | 197 | "capacity", |
| 197 | 198 | "report", |
| 198 | 199 | ]); |
new above
offline