Public: anyone can read this; the crew can change it.
The owner reads what outside agents tried: a compact, redacted request log, landed from pull #1383 on today's main #1528
scout/forge:scout/1458-the-owner-reads-what-outside-agents-trie → main 2 commits fork 1 thread · 1 unresolved
10 files
changed +786
−12
docs/APPS.md +13
| @@ -1096,3 +1096,16 @@ refused), `placement` (`"metal"` or `"cloud"`, optional) and `volumes` | ||
| 1096 | 1096 | sync cadence in seconds, 10–86400). `src/apps/service.ts` validates it; the |
| 1097 | 1097 | manifest carries it as `service`, `null` for a web app. Running it, exposing |
| 1098 | 1098 | the ports and syncing volumes are not built yet (issue #391). |
| 1099 | ||
| 1100 | ## The access log | |
| 1101 | ||
| 1102 | The forge keeps one compact JSON line per request that is not a static asset | |
| 1103 | (or `/healthz`) under `<data>/access/access-YYYY-MM-DD.log`: time, host, | |
| 1104 | method, path without its query string (secret-looking segments blanked), | |
| 1105 | status, duration, user agent (200 characters), whether a credential came with | |
| 1106 | it, and a hash of the client address keyed with the data directory's secret | |
| 1107 | and the day. Lines are queued in memory and appended in one write a second (or per 200 lines), so a request pays for no disk write. No token, cookie or query string is ever written. Files go after | |
| 1108 | 14 days, a day's file stops at 4 MB and the directory at 32 MB, oldest first. | |
| 1109 | Nothing serves the files. A forge admin reads the last day's non-browser | |
| 1110 | requests to public paths at Settings → Access, or with the `access` MCP tool | |
| 1111 | (`since`, `ua`, `path`; write-scope token). |
scripts/gate.ts +1
| @@ -83,6 +83,7 @@ export const GATE: readonly string[] = [ | ||
| 83 | 83 | "test/decide.test.ts", |
| 84 | 84 | "test/ledger.test.ts", |
| 85 | 85 | "test/capacity.test.ts", |
| 86 | "test/access-log.test.ts", | |
| 86 | 87 | "test/guard-new-accounts.test.ts", |
| 87 | 88 | "test/checks.test.ts", |
| 88 | 89 | "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 +297
| @@ -0,0 +1,297 @@ | ||
| 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 time to headers (a streamed body is not counted), 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 | /** Lines waiting for the next flush, by the day's file they belong to. */ | |
| 171 | const pending = new Map<string, string[]>(); | |
| 172 | let timer: ReturnType<typeof setTimeout> | undefined; | |
| 173 | const FLUSH_MS = 1000; | |
| 174 | const FLUSH_LINES = 200; | |
| 175 | ||
| 176 | /** Write what waits, one append per day's file. Never throws. */ | |
| 177 | export function flushAccess(dataDir: string, at: Date = new Date()): void { | |
| 178 | clearTimeout(timer); | |
| 179 | timer = undefined; | |
| 180 | const batches = [...pending]; | |
| 181 | pending.clear(); | |
| 182 | for (const [file, lines] of batches) { | |
| 183 | try { | |
| 184 | const dir = accessDir(dataDir); | |
| 185 | mkdirSync(dir, { recursive: true, mode: 0o700 }); | |
| 186 | const day = dayOf(at); | |
| 187 | if (pruned !== `${dir}:${day}`) { | |
| 188 | pruned = `${dir}:${day}`; | |
| 189 | prune(dataDir, at); | |
| 190 | } | |
| 191 | let size = 0; | |
| 192 | try { | |
| 193 | size = statSync(file).size; | |
| 194 | } catch { | |
| 195 | // no file yet | |
| 196 | } | |
| 197 | if (size >= DAY_BYTES) continue; | |
| 198 | appendFileSync(file, lines.join(""), { mode: 0o600 }); | |
| 199 | } catch { | |
| 200 | // the log is a convenience; the request is the work | |
| 201 | } | |
| 202 | } | |
| 203 | } | |
| 204 | ||
| 205 | /** | |
| 206 | * Keep a request: a line in memory now, on disk within a second or 200 lines, | |
| 207 | * so a request pays for a string and not for a write. Never throws. | |
| 208 | */ | |
| 209 | export function recordAccess( | |
| 210 | dataDir: string, | |
| 211 | seen: Seen, | |
| 212 | at: Date = new Date(), | |
| 213 | ): void { | |
| 214 | try { | |
| 215 | const line = lineFor(dataDir, seen, at); | |
| 216 | if (line === undefined) return; | |
| 217 | const file = fileOf(accessDir(dataDir), dayOf(at)); | |
| 218 | const queued = pending.get(file) ?? []; | |
| 219 | queued.push(`${JSON.stringify(line)}\n`); | |
| 220 | pending.set(file, queued); | |
| 221 | let count = 0; | |
| 222 | for (const q of pending.values()) count += q.length; | |
| 223 | if (count >= FLUSH_LINES) flushAccess(dataDir, at); | |
| 224 | else if (timer === undefined) { | |
| 225 | timer = setTimeout(() => flushAccess(dataDir, new Date()), FLUSH_MS); | |
| 226 | timer.unref(); | |
| 227 | } | |
| 228 | } catch { | |
| 229 | // the log is a convenience; the request is the work | |
| 230 | } | |
| 231 | } | |
| 232 | ||
| 233 | export interface AccessQuery { | |
| 234 | /** ISO time to read from; the last day when absent or unreadable. */ | |
| 235 | readonly since?: string; | |
| 236 | /** Case-insensitive part of the user agent. */ | |
| 237 | readonly ua?: string; | |
| 238 | /** Start of the path. */ | |
| 239 | readonly path?: string; | |
| 240 | } | |
| 241 | ||
| 242 | /** A browser says so in its user agent; an agent, a script or a probe does not. */ | |
| 243 | export const isBrowser = (ua: string): boolean => ua.includes("Mozilla/"); | |
| 244 | ||
| 245 | const isPublic = (path: string): boolean => | |
| 246 | PUBLIC_PREFIXES.some((p) => path.startsWith(p)); | |
| 247 | ||
| 248 | /** | |
| 249 | * The last day's (or `since`'s) non-browser requests to public paths, newest | |
| 250 | * first, at most 500. | |
| 251 | */ | |
| 252 | export function readAccess( | |
| 253 | dataDir: string, | |
| 254 | query: AccessQuery, | |
| 255 | now: Date = new Date(), | |
| 256 | ): AccessLine[] { | |
| 257 | flushAccess(dataDir, now); | |
| 258 | const floor = now.getTime() - KEEP_DAYS * DAY_MS; | |
| 259 | const parsed = query.since === undefined ? NaN : Date.parse(query.since); | |
| 260 | const from = Math.max( | |
| 261 | Number.isNaN(parsed) ? now.getTime() - DAY_MS : parsed, | |
| 262 | floor, | |
| 263 | ); | |
| 264 | const ua = query.ua?.toLowerCase(); | |
| 265 | const dir = accessDir(dataDir); | |
| 266 | let files: string[]; | |
| 267 | try { | |
| 268 | files = readdirSync(dir) | |
| 269 | .filter((f) => /^access-\d{4}-\d{2}-\d{2}\.log$/.test(f)) | |
| 270 | .filter((f) => f.slice(7, 17) >= dayOf(new Date(from))) | |
| 271 | .sort() | |
| 272 | .reverse(); | |
| 273 | } catch { | |
| 274 | return []; | |
| 275 | } | |
| 276 | const out: AccessLine[] = []; | |
| 277 | for (const f of files) { | |
| 278 | const lines = readFileSync(join(dir, f), "utf8").split("\n").reverse(); | |
| 279 | for (const raw of lines) { | |
| 280 | if (raw === "") continue; | |
| 281 | let line: AccessLine; | |
| 282 | try { | |
| 283 | line = JSON.parse(raw) as AccessLine; | |
| 284 | } catch { | |
| 285 | continue; | |
| 286 | } | |
| 287 | if (Date.parse(line.t) < from) continue; | |
| 288 | if (isBrowser(line.ua) || !isPublic(line.path)) continue; | |
| 289 | if (ua !== undefined && !line.ua.toLowerCase().includes(ua)) continue; | |
| 290 | if (query.path !== undefined && !line.path.startsWith(query.path)) | |
| 291 | continue; | |
| 292 | out.push(line); | |
| 293 | if (out.length >= READ_MAX) return out; | |
| 294 | } | |
| 295 | } | |
| 296 | return out; | |
| 297 | } |
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"; |
| @@ -1677,6 +1678,34 @@ const TOOLS: readonly Tool[] = [ | ||
| 1677 | 1678 | }); |
| 1678 | 1679 | }, |
| 1679 | 1680 | }, |
| 1681 | { | |
| 1682 | name: "access", | |
| 1683 | description: | |
| 1684 | "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.", | |
| 1685 | inputSchema: { | |
| 1686 | type: "object", | |
| 1687 | properties: { | |
| 1688 | since: { type: "string", maxLength: 40 }, | |
| 1689 | ua: { type: "string", maxLength: 100 }, | |
| 1690 | path: { type: "string", maxLength: 200 }, | |
| 1691 | }, | |
| 1692 | }, | |
| 1693 | writes: true, | |
| 1694 | run(ctx, user, args) { | |
| 1695 | const text = (k: string): string | undefined => | |
| 1696 | typeof args[k] === "string" && args[k] !== "" ? (args[k] as string) : undefined; | |
| 1697 | const since = text("since"); | |
| 1698 | const ua = text("ua"); | |
| 1699 | const path = text("path"); | |
| 1700 | const listed = listAccess(ctx.app, user, { | |
| 1701 | ...(since === undefined ? {} : { since: since.slice(0, 40) }), | |
| 1702 | ...(ua === undefined ? {} : { ua: ua.slice(0, 100) }), | |
| 1703 | ...(path === undefined ? {} : { path: path.slice(0, 200) }), | |
| 1704 | }); | |
| 1705 | if (!listed.ok) return bad("not_found", "no such tool here"); | |
| 1706 | return good({ requests: listed.value }); | |
| 1707 | }, | |
| 1708 | }, | |
| 1680 | 1709 | { |
| 1681 | 1710 | name: "capacity", |
| 1682 | 1711 | description: |
src/http/server.ts +36 −12
| @@ -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, |
| @@ -368,6 +369,7 @@ import { apiRoutes } from "./api.ts"; | ||
| 368 | 369 | import { feedRoutes } from "./feed.ts"; |
| 369 | 370 | import { mcpRoutes } from "./mcp.ts"; |
| 370 | 371 | import { oauthRoutes } from "./oauth.ts"; |
| 372 | import { recordAccess } from "./access_log.ts"; | |
| 371 | 373 | import { carryPeer, clientAddress, notePeer, type ProxyTrust } from "./peer.ts"; |
| 372 | 374 | import { parseCidrs } from "../kernel/cidr.ts"; |
| 373 | 375 | import { |
| @@ -408,6 +410,7 @@ import { getUserById } from "../core/users.ts"; | ||
| 408 | 410 | import { appsRuntime } from "../apps/runtime.ts"; |
| 409 | 411 | import { |
| 410 | 412 | appWebSocket, |
| 413 | type AppSocket, | |
| 411 | 414 | proxyApp, |
| 412 | 415 | resolveAppHost, |
| 413 | 416 | } from "../apps/proxy.ts"; |
| @@ -661,6 +664,7 @@ export function buildRouter(): Router<Handler> { | ||
| 661 | 664 | router.add("POST", "/settings/cloud/write", cloudWrite); |
| 662 | 665 | router.add("POST", "/settings/cloud/audit", cloudAudit); |
| 663 | 666 | router.add("POST", "/settings/cloud/remove", cloudRemove); |
| 667 | router.add("GET", "/settings/access", accessPage); | |
| 664 | 668 | router.add("GET", "/settings/capacity", capacityPage); |
| 665 | 669 | router.add("POST", "/settings/capacity", capacitySet); |
| 666 | 670 | router.add("GET", "/settings/backups", backupsPage); |
| @@ -1669,17 +1673,23 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1669 | 1673 | : { header: app.config.clientIpHeader }), |
| 1670 | 1674 | }; |
| 1671 | 1675 | |
| 1672 | const web = Bun.serve({ | |
| 1673 | port: app.config.port ?? 3000, | |
| 1674 | idleTimeout: 120, | |
| 1675 | // The largest thing anyone may send — a git push. Every reader below it | |
| 1676 | // keeps its own, smaller cap (\`http/limits.ts\`); the runtime enforces | |
| 1677 | // this one only on a declared length. | |
| 1678 | maxRequestBodySize: REQUEST_MAX, | |
| 1679 | // The only sockets the forge holds are an app's, carried through the | |
| 1680 | // proxy; its own live surfaces are SSE (`sse.ts`) and stay so. | |
| 1681 | websocket: appWebSocket, | |
| 1682 | async fetch(request, server) { | |
| 1676 | // What the forge itself answered, for the owner's access log. Called only | |
| 1677 | // after `notePeer`, so the caller is known; an app's own traffic (the | |
| 1678 | // `proxyApp` branch) is the app's and never comes through here. `ms` is the | |
| 1679 | // time to headers: a streamed body is still being sent. | |
| 1680 | const logged = (request: Request, response: Response, started: number) => | |
| 1681 | recordAccess(app.config.dataDir, { | |
| 1682 | request, | |
| 1683 | status: response.status, | |
| 1684 | ms: performance.now() - started, | |
| 1685 | client: clientAddress(request), | |
| 1686 | }); | |
| 1687 | ||
| 1688 | const handle = async ( | |
| 1689 | request: Request, | |
| 1690 | server: Bun.Server<AppSocket>, | |
| 1691 | ): Promise<Response | undefined> => { | |
| 1692 | const started = performance.now(); | |
| 1683 | 1693 | // An app's hostname is answered before any route: `hello.<domain>` is |
| 1684 | 1694 | // the app, whatever its path, and the forge's own routes never apply. |
| 1685 | 1695 | const runtime = appsRuntime(app); |
| @@ -1710,6 +1720,7 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1710 | 1720 | notePeer(request, server.requestIP(request)?.address, trust); |
| 1711 | 1721 | armClose(request, () => server.timeout(request, 1)); |
| 1712 | 1722 | const response = securityFloor(await http.handle(request)); |
| 1723 | logged(request, response, started); | |
| 1713 | 1724 | await settleBody(request); |
| 1714 | 1725 | if (!mustClose(request)) return response; |
| 1715 | 1726 | server.timeout(request, 1); |
| @@ -1725,12 +1736,25 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1725 | 1736 | const response = securityFloor( |
| 1726 | 1737 | await answer(app, router, apiRouter, limiter, request), |
| 1727 | 1738 | ); |
| 1739 | logged(request, response, started); | |
| 1728 | 1740 | await settleBody(request); |
| 1729 | 1741 | if (!mustClose(request)) return response; |
| 1730 | 1742 | // Said, so no client or proxy reuses it; then done, so none can. |
| 1731 | 1743 | server.timeout(request, 1); |
| 1732 | 1744 | return withHeader(response, "connection", "close"); |
| 1733 | }, | |
| 1745 | }; | |
| 1746 | ||
| 1747 | const web = Bun.serve({ | |
| 1748 | port: app.config.port ?? 3000, | |
| 1749 | idleTimeout: 120, | |
| 1750 | // The largest thing anyone may send — a git push. Every reader below it | |
| 1751 | // keeps its own, smaller cap (\`http/limits.ts\`); the runtime enforces | |
| 1752 | // this one only on a declared length. | |
| 1753 | maxRequestBodySize: REQUEST_MAX, | |
| 1754 | // The only sockets the forge holds are an app's, carried through the | |
| 1755 | // proxy; its own live surfaces are SSE (`sse.ts`) and stay so. | |
| 1756 | websocket: appWebSocket, | |
| 1757 | fetch: handle, | |
| 1734 | 1758 | error(error) { |
| 1735 | 1759 | const refused = refusedByDatabase(error); |
| 1736 | 1760 | if (refused !== undefined) { |
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 +294
| @@ -0,0 +1,294 @@ | ||
| 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 | clientHash, | |
| 19 | flushAccess, | |
| 20 | keptPath, | |
| 21 | prune, | |
| 22 | readAccess, | |
| 23 | recordAccess, | |
| 24 | TOTAL_BYTES, | |
| 25 | } from "../src/http/access_log.ts"; | |
| 26 | import { AppsRuntime } from "../src/apps/runtime.ts"; | |
| 27 | import { newApp } from "../src/actions/apps.ts"; | |
| 28 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 29 | ||
| 30 | const logText = (dir: string): string => { | |
| 31 | flushAccess(dir); | |
| 32 | return readdirSync(accessDir(dir)) | |
| 33 | .map((f) => readFileSync(join(accessDir(dir), f), "utf8")) | |
| 34 | .join(""); | |
| 35 | }; | |
| 36 | ||
| 37 | describe("the access log", () => { | |
| 38 | let dataDir: string; | |
| 39 | let app: App; | |
| 40 | let servers: Servers; | |
| 41 | let adminRw: string; | |
| 42 | let adminRo: string; | |
| 43 | let bobRw: string; | |
| 44 | ||
| 45 | const mcp = async (token: string, args: Record<string, unknown>) => { | |
| 46 | const res = await fetch(`${servers.url}/mcp`, { | |
| 47 | method: "POST", | |
| 48 | headers: { | |
| 49 | authorization: `Bearer ${token}`, | |
| 50 | "content-type": "application/json", | |
| 51 | accept: "application/json, text/event-stream", | |
| 52 | }, | |
| 53 | body: JSON.stringify({ | |
| 54 | jsonrpc: "2.0", | |
| 55 | id: 1, | |
| 56 | method: "tools/call", | |
| 57 | params: { name: "access", arguments: args }, | |
| 58 | }), | |
| 59 | }); | |
| 60 | const body = (await res.json()) as { | |
| 61 | result: { isError?: boolean; content: { text: string }[] }; | |
| 62 | }; | |
| 63 | return { | |
| 64 | error: body.result.isError === true, | |
| 65 | text: body.result.content[0]!.text, | |
| 66 | }; | |
| 67 | }; | |
| 68 | ||
| 69 | beforeAll(async () => { | |
| 70 | dataDir = await mkdtemp(join(tmpdir(), "forge-access-")); | |
| 71 | app = createApp({ dataDir, port: 0 }); | |
| 72 | servers = await serve(app); | |
| 73 | const a = await createUser(app.db, { | |
| 74 | trusted: true, | |
| 75 | username: "alice", | |
| 76 | email: "[email protected]", | |
| 77 | password: "a-good-passphrase", | |
| 78 | adminIfFirst: true, | |
| 79 | }); | |
| 80 | const b = await createUser(app.db, { | |
| 81 | trusted: true, | |
| 82 | username: "bob", | |
| 83 | email: "[email protected]", | |
| 84 | password: "a-good-passphrase", | |
| 85 | }); | |
| 86 | if (!a.ok || !b.ok) throw new Error("users"); | |
| 87 | adminRw = createToken(app.db, a.value.id, "t", "rw").token; | |
| 88 | adminRo = createToken(app.db, a.value.id, "t", "ro").token; | |
| 89 | bobRw = createToken(app.db, b.value.id, "t", "rw").token; | |
| 90 | }); | |
| 91 | ||
| 92 | afterAll(async () => { | |
| 93 | servers.stop(); | |
| 94 | app.close(); | |
| 95 | await rm(dataDir, { recursive: true, force: true }); | |
| 96 | }); | |
| 97 | ||
| 98 | test("a replayed agent request is kept, redacted, and read back", async () => { | |
| 99 | const secret = "forge_SECRETTOKENVALUE0123456789abcdef"; | |
| 100 | await fetch(`${servers.url}/api/v1/nothing-here?token=${secret}&q=hunter2`, { | |
| 101 | headers: { | |
| 102 | "user-agent": "ExampleAgent/1.0 (+https://example.test)", | |
| 103 | authorization: `Bearer ${secret}`, | |
| 104 | cookie: "forge_session=COOKIEVALUE123; other=zzz", | |
| 105 | }, | |
| 106 | }); | |
| 107 | await fetch(`${servers.url}/mcp`, { | |
| 108 | method: "POST", | |
| 109 | headers: { "user-agent": "ExampleAgent/1.0" }, | |
| 110 | body: "{}", | |
| 111 | }); | |
| 112 | // A browser and a static asset are not what this reads. | |
| 113 | await fetch(`${servers.url}/issues`, { | |
| 114 | headers: { "user-agent": "Mozilla/5.0 (X11) Firefox/130" }, | |
| 115 | }); | |
| 116 | await fetch(`${servers.url}/assets/missing.css`); | |
| 117 | ||
| 118 | const raw = logText(dataDir); | |
| 119 | for (const leak of [secret, "SECRETTOKENVALUE", "hunter2", "COOKIEVALUE", "zzz", "q=", "127.0.0.1"]) | |
| 120 | expect(raw).not.toContain(leak); | |
| 121 | expect(raw).not.toContain("assets"); | |
| 122 | const lines = raw.trim().split("\n").map((l) => JSON.parse(l)); | |
| 123 | const hit = lines.find((l) => l.path === "/api/v1/nothing-here"); | |
| 124 | expect(hit).toMatchObject({ | |
| 125 | method: "GET", | |
| 126 | status: 404, | |
| 127 | auth: true, | |
| 128 | ua: "ExampleAgent/1.0 (+https://example.test)", | |
| 129 | }); | |
| 130 | expect(hit.who).toMatch(/^[0-9a-f]{16}$/); | |
| 131 | expect(typeof hit.ms).toBe("number"); | |
| 132 | ||
| 133 | const read = await mcp(adminRw, { ua: "exampleagent" }); | |
| 134 | expect(read.error).toBe(false); | |
| 135 | const rows = JSON.parse(read.text).requests as { path: string; ua: string }[]; | |
| 136 | expect(rows.map((r) => r.path)).toContain("/api/v1/nothing-here"); | |
| 137 | expect(rows.every((r) => !r.ua.includes("Mozilla"))).toBe(true); | |
| 138 | const narrow = JSON.parse((await mcp(adminRw, { path: "/mcp" })).text).requests; | |
| 139 | expect(narrow.every((r: { path: string }) => r.path.startsWith("/mcp"))).toBe(true); | |
| 140 | expect(narrow.length).toBeGreaterThan(0); | |
| 141 | }); | |
| 142 | ||
| 143 | test("a path never carries a secret-looking segment or a long line", () => { | |
| 144 | expect(keptPath("/claim/abcdefghijklmnopqrstuvwxyz0123")).toBe("/claim/:redacted"); | |
| 145 | expect(keptPath("/x/forge_abc")).toBe("/x/:redacted"); | |
| 146 | expect(keptPath("/issues/12")).toBe("/issues/12"); | |
| 147 | expect(keptPath("/a\n/b" + "c".repeat(500)).length).toBeLessThanOrEqual(200); | |
| 148 | expect(keptPath("/a\nb")).not.toContain("\n"); | |
| 149 | }); | |
| 150 | ||
| 151 | test("only an admin with write scope reads it, on the page and by MCP", async () => { | |
| 152 | expect((await mcp(adminRo, {})).error).toBe(true); | |
| 153 | expect((await mcp(adminRo, {})).text).toContain("forbidden"); | |
| 154 | const bob = await mcp(bobRw, {}); | |
| 155 | expect(bob.error).toBe(true); | |
| 156 | expect(bob.text).toContain("not_found"); | |
| 157 | const anon = await fetch(`${servers.url}/settings/access`, { redirect: "manual" }); | |
| 158 | expect(anon.status).not.toBe(200); | |
| 159 | }); | |
| 160 | ||
| 161 | test("the settings page lists what was tried, escaped", async () => { | |
| 162 | const res = await fetch(`${servers.url}/signin`, { | |
| 163 | method: "POST", | |
| 164 | redirect: "manual", | |
| 165 | headers: { | |
| 166 | "content-type": "application/x-www-form-urlencoded", | |
| 167 | origin: servers.url, | |
| 168 | }, | |
| 169 | body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }), | |
| 170 | }); | |
| 171 | const cookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? ""; | |
| 172 | await fetch(`${servers.url}/api/v1/x`, { | |
| 173 | headers: { "user-agent": "<script>alert(1)</script>-bot" }, | |
| 174 | }); | |
| 175 | const page = await fetch(`${servers.url}/settings/access`, { headers: { cookie } }); | |
| 176 | expect(page.status).toBe(200); | |
| 177 | const html = await page.text(); | |
| 178 | expect(html).toContain("Outside requests"); | |
| 179 | expect(html).toContain("/api/v1/nothing-here"); | |
| 180 | expect(html).not.toContain("<script>alert(1)</script>-bot"); | |
| 181 | expect(html).toContain("<script>"); | |
| 182 | }); | |
| 183 | }); | |
| 184 | ||
| 185 | describe("the access log's keeping", () => { | |
| 186 | test("files older than 14 days go, and the directory stays under its cap", async () => { | |
| 187 | const dir = await mkdtemp(join(tmpdir(), "forge-access-rot-")); | |
| 188 | try { | |
| 189 | const keep = accessDir(dir); | |
| 190 | mkdirSync(keep, { recursive: true }); | |
| 191 | writeFileSync(join(keep, "access-2026-09-01.log"), "old\n"); | |
| 192 | writeFileSync(join(keep, "access-2026-09-30.log"), "recent\n"); | |
| 193 | const now = new Date("2026-10-13T12:00:00Z"); | |
| 194 | prune(dir, now); | |
| 195 | expect(readdirSync(keep)).toEqual(["access-2026-09-30.log"]); | |
| 196 | // Over the cap: the oldest goes first, today's file always stays. | |
| 197 | const big = "x".repeat(TOTAL_BYTES / 2 + 1); | |
| 198 | writeFileSync(join(keep, "access-2026-10-10.log"), big); | |
| 199 | writeFileSync(join(keep, "access-2026-10-11.log"), big); | |
| 200 | writeFileSync(join(keep, "access-2026-10-13.log"), "today\n"); | |
| 201 | prune(dir, now); | |
| 202 | expect(readdirSync(keep).sort()).toEqual([ | |
| 203 | "access-2026-10-11.log", | |
| 204 | "access-2026-10-13.log", | |
| 205 | ]); | |
| 206 | } finally { | |
| 207 | await rm(dir, { recursive: true, force: true }); | |
| 208 | } | |
| 209 | }); | |
| 210 | ||
| 211 | test("recording prunes on a new day, and the hash changes with the day", async () => { | |
| 212 | const dir = await mkdtemp(join(tmpdir(), "forge-access-day-")); | |
| 213 | try { | |
| 214 | const seen = (path: string) => ({ | |
| 215 | request: new Request(`http://forge.test${path}?k=v`, { | |
| 216 | headers: { "user-agent": "bot" }, | |
| 217 | }), | |
| 218 | status: 200, | |
| 219 | ms: 3.4, | |
| 220 | client: "203.0.113.9", | |
| 221 | }); | |
| 222 | mkdirSync(accessDir(dir), { recursive: true }); | |
| 223 | writeFileSync(join(accessDir(dir), "access-2026-09-01.log"), "old\n"); | |
| 224 | recordAccess(dir, seen("/llms.txt"), new Date("2026-10-13T01:00:00Z")); | |
| 225 | recordAccess(dir, seen("/llms.txt"), new Date("2026-10-14T01:00:00Z")); | |
| 226 | // Batched: a request has only queued its line. | |
| 227 | expect(readdirSync(accessDir(dir))).toEqual(["access-2026-09-01.log"]); | |
| 228 | flushAccess(dir, new Date("2026-10-14T01:00:00Z")); | |
| 229 | expect(readdirSync(accessDir(dir)).sort()).toEqual([ | |
| 230 | "access-2026-10-13.log", | |
| 231 | "access-2026-10-14.log", | |
| 232 | ]); | |
| 233 | const [a, b] = readdirSync(accessDir(dir)) | |
| 234 | .sort() | |
| 235 | .map((f) => JSON.parse(readFileSync(join(accessDir(dir), f), "utf8"))); | |
| 236 | expect(a.who).not.toBe(b.who); | |
| 237 | expect(logText(dir)).not.toContain("203.0.113.9"); | |
| 238 | const rows = readAccess(dir, { since: "2026-10-13T00:00:00Z" }, new Date("2026-10-14T02:00:00Z")); | |
| 239 | expect(rows.map((r) => r.path)).toEqual(["/llms.txt", "/llms.txt"]); | |
| 240 | } finally { | |
| 241 | await rm(dir, { recursive: true, force: true }); | |
| 242 | } | |
| 243 | }); | |
| 244 | }); | |
| 245 | ||
| 246 | describe("the access log and app hostnames", () => { | |
| 247 | test("an app's own traffic, and a name nobody holds, are not the forge's access", async () => { | |
| 248 | const dataDir = await mkdtemp(join(tmpdir(), "forge-access-apps-")); | |
| 249 | const app = createApp({ dataDir, port: 0, host: "forge.test" }); | |
| 250 | const servers = await serve(app); | |
| 251 | const runtime = new AppsRuntime(app, { | |
| 252 | domain: "apps.test", | |
| 253 | scheme: "http", | |
| 254 | publicPort: servers.port, | |
| 255 | forgeUrl: servers.url, | |
| 256 | concurrency: 1, | |
| 257 | }); | |
| 258 | try { | |
| 259 | await runtime.start(); | |
| 260 | const u = await createUser(app.db, { | |
| 261 | trusted: true, | |
| 262 | username: "alice", | |
| 263 | email: "[email protected]", | |
| 264 | password: "a-good-passphrase", | |
| 265 | adminIfFirst: true, | |
| 266 | }); | |
| 267 | if (!u.ok) throw new Error(u.error); | |
| 268 | const made = await newApp(app, u.value, { | |
| 269 | name: "notes", | |
| 270 | description: "", | |
| 271 | visibility: "public", | |
| 272 | }); | |
| 273 | if (!made.ok) throw new Error(String(made.error)); | |
| 274 | const ask = (host: string, path: string) => | |
| 275 | fetch(`${servers.url}${path}`, { | |
| 276 | headers: { host, "user-agent": "VisitorBot/1.0" }, | |
| 277 | }); | |
| 278 | await ask("notes.apps.test", "/api/visitor-of-the-app"); | |
| 279 | await ask("nosuch.apps.test", "/api/nobody-home"); | |
| 280 | await ask("forge.test", "/api/the-forge-itself"); | |
| 281 | const lines = logText(dataDir) | |
| 282 | .trim() | |
| 283 | .split("\n") | |
| 284 | .map((l) => JSON.parse(l)); | |
| 285 | expect(lines.map((l) => l.path)).toEqual(["/api/the-forge-itself"]); | |
| 286 | expect(lines[0].who).not.toBe(clientHash(dataDir, "unknown", new Date())); | |
| 287 | } finally { | |
| 288 | await runtime.stop(); | |
| 289 | servers.stop(); | |
| 290 | app.close(); | |
| 291 | await rm(dataDir, { recursive: true, force: true }); | |
| 292 | } | |
| 293 | }); | |
| 294 | }); |
test/mcp.test.ts +1
| @@ -194,6 +194,7 @@ describe("the forge over MCP", () => { | ||
| 194 | 194 | "attach_look", |
| 195 | 195 | "hold", |
| 196 | 196 | "plan", |
| 197 | "access", | |
| 197 | 198 | "capacity", |
| 198 | 199 | "report", |
| 199 | 200 | ]); |
new above
offline
For requests to app hostnames,
handlereturns fromproxyAppbeforenotePeer, so this is"unknown": every app visitor becomes one hash, and the app's own traffic is logged as forge access. Record only the forge's own answers (afternotePeer), and add a test with an app host.