hmcp-web 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/LICENSE +77 -0
  2. package/README.md +49 -2
  3. package/THIRD-PARTY-NOTICES.md +110 -0
  4. package/bin/hmcp-web.js +20 -0
  5. package/dist/api.d.ts +22 -0
  6. package/dist/api.js +1458 -0
  7. package/dist/cli.d.ts +2 -0
  8. package/dist/cli.js +40 -0
  9. package/dist/contracts/onboarding.d.ts +233 -0
  10. package/dist/contracts/onboarding.js +1 -0
  11. package/dist/http.d.ts +72 -0
  12. package/dist/http.js +319 -0
  13. package/dist/index.d.ts +7 -0
  14. package/dist/index.js +7 -0
  15. package/dist/model/app-servers.d.ts +85 -0
  16. package/dist/model/app-servers.js +109 -0
  17. package/dist/model/console-settings.d.ts +37 -0
  18. package/dist/model/console-settings.js +74 -0
  19. package/dist/model/doctor.d.ts +68 -0
  20. package/dist/model/doctor.js +254 -0
  21. package/dist/model/fs-browse.d.ts +9 -0
  22. package/dist/model/fs-browse.js +184 -0
  23. package/dist/model/gateway-config.d.ts +287 -0
  24. package/dist/model/gateway-config.js +760 -0
  25. package/dist/model/import-record.d.ts +80 -0
  26. package/dist/model/import-record.js +179 -0
  27. package/dist/model/metrics.d.ts +65 -0
  28. package/dist/model/metrics.js +213 -0
  29. package/dist/model/oauth-flows.d.ts +60 -0
  30. package/dist/model/oauth-flows.js +79 -0
  31. package/dist/model/pipeline.d.ts +58 -0
  32. package/dist/model/pipeline.js +84 -0
  33. package/dist/model/probe.d.ts +155 -0
  34. package/dist/model/probe.js +385 -0
  35. package/dist/model/process.d.ts +100 -0
  36. package/dist/model/process.js +278 -0
  37. package/dist/model/protection.d.ts +378 -0
  38. package/dist/model/protection.js +470 -0
  39. package/dist/model/registry-cache.d.ts +59 -0
  40. package/dist/model/registry-cache.js +238 -0
  41. package/dist/model/scan.d.ts +48 -0
  42. package/dist/model/scan.js +59 -0
  43. package/dist/model/server.d.ts +127 -0
  44. package/dist/model/server.js +243 -0
  45. package/dist/model/tools.d.ts +61 -0
  46. package/dist/model/tools.js +72 -0
  47. package/dist/routes/catalog.d.ts +8 -0
  48. package/dist/routes/catalog.js +47 -0
  49. package/dist/routes/connect-import.d.ts +9 -0
  50. package/dist/routes/connect-import.js +594 -0
  51. package/dist/routes/connect.d.ts +50 -0
  52. package/dist/routes/connect.js +691 -0
  53. package/dist/routes/github.d.ts +97 -0
  54. package/dist/routes/github.js +587 -0
  55. package/dist/routes/guard.d.ts +3 -0
  56. package/dist/routes/guard.js +166 -0
  57. package/dist/routes/oauth.d.ts +55 -0
  58. package/dist/routes/oauth.js +406 -0
  59. package/dist/routes/policy.d.ts +34 -0
  60. package/dist/routes/policy.js +513 -0
  61. package/dist/routes/runtime.d.ts +12 -0
  62. package/dist/routes/runtime.js +921 -0
  63. package/dist/routes/servers-add.d.ts +32 -0
  64. package/dist/routes/servers-add.js +1091 -0
  65. package/dist/routes/system.d.ts +4 -0
  66. package/dist/routes/system.js +13 -0
  67. package/dist/start.d.ts +56 -0
  68. package/dist/start.js +164 -0
  69. package/dist-ui/assets/Activity-CZ78RyRO.js +1 -0
  70. package/dist-ui/assets/Approvals-DPIlNZsv.js +1 -0
  71. package/dist-ui/assets/AttachApp-DjSeWCbS.js +5 -0
  72. package/dist-ui/assets/Connections-qcA96lXh.js +2 -0
  73. package/dist-ui/assets/Gallery-DB_OO7Vw.js +17 -0
  74. package/dist-ui/assets/PreApprovals-C4cKajcK.js +1 -0
  75. package/dist-ui/assets/Protection-B8h-5YAb.js +1 -0
  76. package/dist-ui/assets/Safety-BQqHyYdo.js +1 -0
  77. package/dist-ui/assets/Settings-Cx50zZSt.js +1 -0
  78. package/dist-ui/assets/StartPage-CdX-v7ej.js +1 -0
  79. package/dist-ui/assets/Suggestions-CRo5UOTT.js +1 -0
  80. package/dist-ui/assets/Tools-xo39lPKB.js +4 -0
  81. package/dist-ui/assets/index-DttDjRpu.js +16 -0
  82. package/dist-ui/assets/index-QeJyD5z2.css +2 -0
  83. package/dist-ui/assets/kit-DRVm92_t.js +4 -0
  84. package/dist-ui/brand/logo-256.png +0 -0
  85. package/dist-ui/brand/logo-512.png +0 -0
  86. package/dist-ui/brand/logo.svg +6 -0
  87. package/dist-ui/brand/mark.svg +5 -0
  88. package/dist-ui/fonts/OFL.txt +99 -0
  89. package/dist-ui/fonts/README.md +21 -0
  90. package/dist-ui/fonts/jetbrainsmono-latin.woff2 +0 -0
  91. package/dist-ui/fonts/manrope-latin.woff2 +0 -0
  92. package/dist-ui/index.html +51 -0
  93. package/package.json +69 -6
  94. package/bin/notice.js +0 -7
package/dist/api.js ADDED
@@ -0,0 +1,1458 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { AuditLog, applyExposureChange, TOOL_RULE_CLEAR, TOOL_RULE_REFUSED, TOOL_RULE_SET, TOOL_RULE_UPDATE, boundsOf, globMatch, clearToolRule, decide, parseToolRuleDraft, policyDigest, previewClearToolRule, previewToolRule, ruleToYaml, UNCLASSIFIED_POSTURE_RULE, UNCLASSIFIED_RULE, writeToolRule, writeUnclassifiedPosture, approvalViolations, MAX_GRANT_TTL_SECONDS, REMEMBER_DEFAULT_TTL_SECONDS, REMEMBER_DEFAULT_USES, RememberError, rememberOnApprove, NO_TENANT, grantBoundGaps, grantCoversTool, grantMatches, hasLooseListItems, isOlderRemembered, parseExposureChange, parseGrantDraft, queryAuditLog, readRegistry, runtimeStateIsLive, verifyAuditLog, writeRegistry } from "hmcp-core";
4
+ import { badRequest, conflict, notFound, route, unprocessable } from "./http.js";
5
+ import { buildProtection, effectiveReach, recentActivity, toolProtection } from "./model/protection.js";
6
+ import { chooseTenant, knownTenants, loadServer, scopeFor, scopedFor, storeFor } from "./model/server.js";
7
+ import { surfaceWritable, toolSurfaceFor } from "./model/tools.js";
8
+ import { buildMetrics, isWindow } from "./model/metrics.js";
9
+ import { buildScan } from "./model/scan.js";
10
+ import { toSarif } from "hmcp-scanner";
11
+ import { z } from "zod";
12
+ import { ENFORCEMENT_PIPELINE } from "./model/pipeline.js";
13
+ import { processes } from "./model/process.js";
14
+ import { runtimeRoutes } from "./routes/runtime.js";
15
+ import { policyRoutes } from "./routes/policy.js";
16
+ import { connectRoutes } from "./routes/connect.js";
17
+ import { connectImportRoutes } from "./routes/connect-import.js";
18
+ import { doctorPathDirs } from "./model/doctor.js";
19
+ import { serversAddRoutes } from "./routes/servers-add.js";
20
+ import { catalogRoutes } from "./routes/catalog.js";
21
+ import { oauthRoutes } from "./routes/oauth.js";
22
+ import { systemRoutes } from "./routes/system.js";
23
+ import { githubRoutes } from "./routes/github.js";
24
+ import { guardRoutes } from "./routes/guard.js";
25
+ import { GUARD_COMPONENT } from "hmcp-gateway";
26
+ /* ------------------------------------------------------------------ helpers */
27
+ function registry(options) {
28
+ return readRegistry(options.registryPath);
29
+ }
30
+ function entryById(options, id) {
31
+ const found = registry(options).servers.find((s) => s.id === id);
32
+ if (!found)
33
+ throw notFound(`no registered server with id "${id}"`);
34
+ return found;
35
+ }
36
+ function serverById(options, id) {
37
+ try {
38
+ return loadServer(entryById(options, id));
39
+ }
40
+ catch (err) {
41
+ if (err.status)
42
+ throw err;
43
+ throw unprocessable(`server "${id}" could not be loaded: ${err.message}`);
44
+ }
45
+ }
46
+ /**
47
+ * The components of the other registered toolboxes that write to the same
48
+ * audit log as this one. Every toolbox writes to `~/.hmcp/audit.jsonl`
49
+ * unless told otherwise, so without this one toolbox's Home counted and
50
+ * listed its neighbours' calls as its own (UT5 round 4). The console's own
51
+ * records (`hmcp-web`) stay: they are written to the log of the toolbox
52
+ * they changed.
53
+ */
54
+ function otherComponentsSharingLog(options, server) {
55
+ const out = new Set();
56
+ for (const entry of registry(options).servers) {
57
+ if (entry.id === server.entry.id)
58
+ continue;
59
+ let other;
60
+ try {
61
+ other = loadServer(entry);
62
+ }
63
+ catch {
64
+ continue;
65
+ }
66
+ if (other.auditPath === server.auditPath && other.component !== server.component)
67
+ out.add(other.component);
68
+ }
69
+ return [...out];
70
+ }
71
+ /**
72
+ * One server, and the tenant whose rows this request is about.
73
+ *
74
+ * Every scoped route goes through this rather than resolving a tenant of its
75
+ * own, so no route can be written that forgets to and quietly falls back to the
76
+ * empty tenant. `chooseTenant` refuses where the console cannot legitimately
77
+ * know the answer, and the refusal surfaces as a 422 explaining how to name one.
78
+ */
79
+ function scopedRequest(options, id, query) {
80
+ const server = serverById(options, id);
81
+ const choice = chooseTenant(server, query.get("tenant"));
82
+ if (!choice.ok)
83
+ throw unprocessable(choice.why);
84
+ return { server, tenant: choice.tenant, explicit: choice.explicit };
85
+ }
86
+ /** An audit log scoped to one server's own configuration. */
87
+ function auditFor(server, actor) {
88
+ return new AuditLog({
89
+ config: server.policy.audit,
90
+ actor,
91
+ component: "hmcp-web",
92
+ cwd: server.cwd
93
+ });
94
+ }
95
+ /**
96
+ * The tool a rule is about, checked against what a *live* gateway says it is
97
+ * serving.
98
+ *
99
+ * The same check the exposure route makes, and for the same reason: a rule
100
+ * naming a tool nobody serves reads as a decision and governs nothing. It
101
+ * matters twice over here, because the rule is also written into a file and
102
+ * reviewed in git by someone with no way to tell.
103
+ */
104
+ function toolRuleTarget(server, tenant, body, actor) {
105
+ const raw = (body ?? {});
106
+ const surface = toolSurfaceFor(server, tenant);
107
+ // From the last list the toolbox published, so a rule can be set while no AI app is running it.
108
+ const writable = surfaceWritable(surface, { allowStale: true });
109
+ if (!writable.ok)
110
+ throw unprocessable(`cannot set a rule on "${server.entry.id}": ${writable.why}`);
111
+ /*
112
+ * Anything this route does not understand is a 422, not a dropped key.
113
+ *
114
+ * The draft is built field by field, so an unknown key could never reach the
115
+ * policy file — but it would be accepted with a 200, and a client that sent
116
+ * something and got a success would reasonably believe it took. "Not
117
+ * written" and "refused" are the same outcome on disk and opposite outcomes
118
+ * for whoever asked. `id` and `match` are refused by name: a client does not
119
+ * get to choose the rule id it is writing.
120
+ */
121
+ const allowed = new Set([
122
+ "tool",
123
+ "effect",
124
+ "decision",
125
+ "args",
126
+ "on_violation",
127
+ "unknown_args",
128
+ "reason",
129
+ "acknowledged",
130
+ "expectedDigest"
131
+ ]);
132
+ const unknown = Object.keys(raw).filter((k) => !allowed.has(k));
133
+ if (unknown.length > 0) {
134
+ throw unprocessable(`a tool rule carries a tool, an effect, a decision, argument bounds and an optional reason — ` +
135
+ `this request also carried ${unknown.join(", ")}. The rule's id and match are not the caller's ` +
136
+ `to choose, and everything else about the policy stays an edit you review in git.`);
137
+ }
138
+ const name = typeof raw["tool"] === "string" ? raw["tool"] : "";
139
+ const entry = surface.entries.find((t) => t.name === name);
140
+ if (!entry) {
141
+ throw notFound(`no tool "${name}" in what "${server.entry.id}" is currently serving. ` +
142
+ `Its upstreams advertise: ${surface.entries.map((t) => t.name).join(", ") || "nothing"}.`);
143
+ }
144
+ let draft;
145
+ try {
146
+ draft = parseToolRuleDraft({
147
+ tool: name,
148
+ effect: raw["effect"],
149
+ decision: raw["decision"],
150
+ ...(raw["args"] !== undefined ? { args: raw["args"] } : {}),
151
+ ...(raw["on_violation"] !== undefined ? { on_violation: raw["on_violation"] } : {}),
152
+ ...(raw["unknown_args"] !== undefined ? { unknown_args: raw["unknown_args"] } : {}),
153
+ ...(typeof raw["reason"] === "string" && raw["reason"] ? { reason: raw["reason"] } : {}),
154
+ ...(raw["acknowledged"] !== undefined ? { acknowledged: raw["acknowledged"] } : {}),
155
+ actor
156
+ });
157
+ }
158
+ catch (err) {
159
+ throw unprocessable(err.message);
160
+ }
161
+ return { draft, entry, liveTools: surface.entries.map((t) => t.name) };
162
+ }
163
+ function toolRulePreviewDto(server, preview) {
164
+ return {
165
+ rule: preview.rule,
166
+ /*
167
+ * Rendered by the same function the file write serialises through, so the
168
+ * YAML someone approves and the YAML that lands cannot differ about a
169
+ * carried bound.
170
+ */
171
+ yaml: ruleToYaml(preview.rule),
172
+ verdict: {
173
+ kind: preview.verdict.kind,
174
+ ruleId: preview.verdict.ruleId,
175
+ reason: preview.verdict.reason
176
+ },
177
+ current: {
178
+ kind: preview.current.kind,
179
+ ruleId: preview.current.ruleId,
180
+ reason: preview.current.reason
181
+ },
182
+ /*
183
+ * Sent beside the verdict, never folded into it. The verdict is computed
184
+ * with `argsUnknown`, which skips bounds entirely — it describes the
185
+ * tool's posture, not any real call. A page that printed only the verdict
186
+ * would tell someone their bounded tool "runs" when half its calls are
187
+ * held.
188
+ */
189
+ bounds: preview.bounds,
190
+ currentBounds: preview.currentBounds,
191
+ replaces: preview.replaces,
192
+ governedBy: preview.governedBy,
193
+ governedByConsole: preview.governedByConsole,
194
+ carriedFrom: preview.carriedFrom,
195
+ dropsBounds: preview.dropsBounds,
196
+ strandedRule: preview.strandedRule,
197
+ nameContradiction: preview.nameContradiction,
198
+ overridden: preview.overridden,
199
+ overriddenReason: preview.overriddenReason,
200
+ loosens: preview.loosens,
201
+ expectedDigest: policyDigest(server.policy),
202
+ policyPath: server.policyFile,
203
+ writable: server.policyWritable,
204
+ overridesAllowed: server.policyOverrides,
205
+ reloads: server.gateway.config.policy_reload,
206
+ approvalsReachable: server.policy.approvals.mode !== "deny",
207
+ onUnclassified: server.policy.defaults.on_unclassified
208
+ };
209
+ }
210
+ /**
211
+ * Classifying from the approval queue: the same writer, with the decision
212
+ * pinned to `approve`.
213
+ *
214
+ * It refuses anything that is not the case it exists for -- a call held
215
+ * because nothing classified the tool -- so the queue cannot become a second,
216
+ * quieter route into the policy file.
217
+ */
218
+ function classifyFromApproval(server, tenant, row, effect, actor) {
219
+ if (row.rule_id !== UNCLASSIFIED_RULE) {
220
+ throw new Error(`this call was held by rule "${row.rule_id}", not for want of a classification, so classifying ` +
221
+ `the tool would not change what happens to the next one`);
222
+ }
223
+ if (server.policyFile === null || !server.policyWritable.ok) {
224
+ throw new Error(server.policyWritable.why ?? "this gateway's policy cannot be written from here");
225
+ }
226
+ const surface = toolSurfaceFor(server, tenant);
227
+ const writable = surfaceWritable(surface);
228
+ if (!writable.ok)
229
+ throw new Error(writable.why);
230
+ const entry = surface.entries.find((t) => t.name === row.tool);
231
+ if (!entry)
232
+ throw new Error(`"${row.tool}" is not in what this gateway is currently serving`);
233
+ if (entry.effect !== null) {
234
+ throw new Error(`"${row.tool}" is already classified as ${entry.effect}`);
235
+ }
236
+ const draft = parseToolRuleDraft({
237
+ tool: row.tool,
238
+ effect,
239
+ // Fixed. See the call site.
240
+ decision: "approve",
241
+ reason: `classified while approving a held call`,
242
+ actor
243
+ });
244
+ const result = writeToolRule({
245
+ policyPath: server.policyFile,
246
+ draft,
247
+ expectedDigest: policyDigest(server.policy),
248
+ knownToLiveSurface: true,
249
+ liveTools: surface.entries.map((t) => t.name),
250
+ writesAllowed: true
251
+ });
252
+ if (result.kind !== "written")
253
+ throw new Error(result.why);
254
+ auditFor(server, actor).append({
255
+ tool: draft.tool,
256
+ effect: draft.effect,
257
+ decision: "approve",
258
+ tenant: tenant || null,
259
+ rule_id: TOOL_RULE_SET,
260
+ reason: `${draft.tool} classified as ${draft.effect} by ${actor} while approving a held call; ` +
261
+ `rule "${result.rule.id}" written to ${server.policyFile}. Calls still wait for a person.`,
262
+ outcome: "completed",
263
+ args_redacted: {
264
+ tool: draft.tool,
265
+ effect: draft.effect,
266
+ decision: "approve",
267
+ rule_id: result.rule.id,
268
+ origin: "approval-queue",
269
+ policy_digest_before: result.previousDigest,
270
+ policy_digest_after: result.digest
271
+ }
272
+ });
273
+ return { ruleId: result.rule.id };
274
+ }
275
+ /**
276
+ * Whose waiting requests a toolbox's queue shows: its own, and those the
277
+ * Claude Code guard parked in the same approvals database for the same tenant.
278
+ *
279
+ * The guard keeps its own scope (`guard:claude-code`), so its approvals can
280
+ * never release a call to one of the toolbox's tools or the other way round:
281
+ * the binding is checked within a scope. But a person has one place to look,
282
+ * and a Claude Code edit waiting for them must be in it. A store several
283
+ * toolboxes share shows the guard's requests in each, which is the same
284
+ * request, decided once, wherever it is decided.
285
+ */
286
+ function approvalScopes(server, tenant) {
287
+ const own = scopedFor(server, tenant);
288
+ if (server.component === GUARD_COMPONENT)
289
+ return [own];
290
+ return [own, storeFor(server).scoped({ component: GUARD_COMPONENT, tenant })];
291
+ }
292
+ /** The scope that holds this request: the toolbox's own when it is there or nowhere, else the guard's. */
293
+ function approvalScopeOf(server, tenant, id) {
294
+ const [own, ...rest] = approvalScopes(server, tenant);
295
+ if (own.get(id))
296
+ return own;
297
+ return rest.find((s) => s.get(id) !== undefined) ?? own;
298
+ }
299
+ /** Arguments reach the console already redacted; this only decodes them. */
300
+ function parseArgs(row) {
301
+ try {
302
+ return { args: JSON.parse(row.args_redacted), argsError: null };
303
+ }
304
+ catch {
305
+ return { args: row.args_redacted, argsError: "stored arguments are not valid JSON" };
306
+ }
307
+ }
308
+ function approvalDto(row) {
309
+ const { args, argsError } = parseArgs(row);
310
+ return {
311
+ id: row.id,
312
+ createdAt: row.created_at,
313
+ expiresAt: row.expires_at,
314
+ tool: row.tool,
315
+ effect: row.effect,
316
+ reason: row.reason,
317
+ actor: row.actor,
318
+ session: row.session,
319
+ state: row.state,
320
+ decidedAt: row.decided_at,
321
+ decidedBy: row.decided_by,
322
+ decisionNote: row.decision_note,
323
+ bindingHash: row.binding_hash,
324
+ /*
325
+ * Which bounds the call failed. `args` below is redacted and truncated, so
326
+ * for a call held by an argument bound this can be the only place the
327
+ * value being decided on appears — and a reviewer approving a binding over
328
+ * a value they were never shown is the worst version of this feature.
329
+ */
330
+ violations: approvalViolations(row),
331
+ ruleId: row.rule_id,
332
+ policyDigest: row.policy_digest,
333
+ args,
334
+ argsError,
335
+ /*
336
+ * Whether "approve and remember" can be offered at all, by the same rules
337
+ * `rememberDraft` refuses by: nothing unclassified, nothing destructive,
338
+ * nothing whose held arguments were not recorded, no pattern-like name.
339
+ * Answered here so the queue hides the option instead of offering one
340
+ * that is refused.
341
+ */
342
+ rememberAllowed:
343
+ // Not for a Claude Code call: see the decide route.
344
+ row.component !== GUARD_COMPONENT &&
345
+ row.effect !== null &&
346
+ row.effect !== "destructive" &&
347
+ row.held_args !== null &&
348
+ !/[*?{},]/.test(row.tool)
349
+ };
350
+ }
351
+ /** `remember` on a decision: how long and how many calls. Bounds beyond the shape are core's. */
352
+ const RememberSchema = z
353
+ .object({
354
+ ttlSeconds: z.number().int().positive(),
355
+ maxUses: z.number().int().positive().nullable()
356
+ })
357
+ .strict();
358
+ function grantDto(row) {
359
+ let constraints = {};
360
+ try {
361
+ constraints = JSON.parse(row.constraints);
362
+ }
363
+ catch {
364
+ constraints = {};
365
+ }
366
+ return {
367
+ id: row.id,
368
+ createdAt: row.created_at,
369
+ expiresAt: row.expires_at,
370
+ toolMatch: row.tool_match,
371
+ effect: row.effect,
372
+ constraints,
373
+ maxUses: row.max_uses,
374
+ uses: row.uses,
375
+ reason: row.reason,
376
+ createdBy: row.created_by,
377
+ state: row.state,
378
+ revokedAt: row.revoked_at,
379
+ revokedBy: row.revoked_by,
380
+ // Made by "don't ask again" in an older build: it releases only what it names now.
381
+ // Or one that bounded each field of a list's items on its own: it releases nothing now (R4-1).
382
+ olderVersion: isOlderRemembered(row) || hasLooseListItems(row)
383
+ };
384
+ }
385
+ function csv(query, key) {
386
+ const raw = query.get(key);
387
+ if (!raw)
388
+ return undefined;
389
+ return raw
390
+ .split(",")
391
+ .map((s) => s.trim())
392
+ .filter(Boolean);
393
+ }
394
+ function intParam(query, key) {
395
+ const raw = query.get(key);
396
+ if (raw === null)
397
+ return undefined;
398
+ const value = Number(raw);
399
+ if (!Number.isFinite(value))
400
+ throw badRequest(`${key} must be a number`);
401
+ return value;
402
+ }
403
+ /* ------------------------------------------------------------------- routes */
404
+ export function buildRoutes(options) {
405
+ return [
406
+ ...runtimeRoutes(options),
407
+ ...policyRoutes(options),
408
+ // Absolute folders of node, uv, docker... so an app with a minimal PATH finds them.
409
+ ...connectRoutes(options, { pathDirs: doctorPathDirs }),
410
+ ...connectImportRoutes(options),
411
+ ...serversAddRoutes(options),
412
+ ...catalogRoutes(options),
413
+ ...oauthRoutes(options),
414
+ ...systemRoutes(options),
415
+ ...githubRoutes(options),
416
+ ...guardRoutes(options),
417
+ route("GET", "/api/v1/health", () => ({ ok: true, pipelineSteps: ENFORCEMENT_PIPELINE.length })),
418
+ /**
419
+ * The redaction legend. The UI explains markers rather than printing them,
420
+ * and the patterns live in core, so they are served rather than duplicated.
421
+ */
422
+ route("GET", "/api/v1/meta/redaction", () => ({
423
+ markers: [
424
+ { marker: "[redacted:key]", meaning: "the argument's name looked like a secret" },
425
+ { marker: "[redacted:<pattern>]", meaning: "the value matched a known credential shape" },
426
+ { marker: "[redacted:circular]", meaning: "the value referred back to itself" },
427
+ { marker: "[redacted:max-depth]", meaning: "nested deeper than the redactor follows" },
428
+ { marker: "…[truncated N chars]", meaning: "a long string was cut short" },
429
+ { marker: "[truncated N items]", meaning: "a long array was cut short" }
430
+ ],
431
+ note: "Names are redacted by name, not by content, so a value may be harmless and still hidden. " +
432
+ "An argument called `session` is redacted for this reason. The original values were never " +
433
+ "written to disk, so nothing here can be un-redacted.",
434
+ grantTtlMaxSeconds: MAX_GRANT_TTL_SECONDS,
435
+ /** What "approve and remember" offers unless the reviewer changes it. */
436
+ rememberDefaults: { ttlSeconds: REMEMBER_DEFAULT_TTL_SECONDS, maxUses: REMEMBER_DEFAULT_USES },
437
+ /*
438
+ * The audit vocabulary, served for the same reason the markers are: these
439
+ * are core's enums, and the filter UI had its own copy of both lists. A
440
+ * value added to `DecisionKind` would have been unfilterable until
441
+ * someone noticed the dropdown was short.
442
+ */
443
+ decisions: [
444
+ { value: "allow", label: "allowed" },
445
+ { value: "approve", label: "approved" },
446
+ { value: "deny", label: "denied" }
447
+ ],
448
+ outcomes: [
449
+ { value: "completed", label: "completed" },
450
+ { value: "denied", label: "denied" },
451
+ { value: "pending-approval", label: "held for approval" },
452
+ { value: "error", label: "error" },
453
+ { value: "relayed", label: "let through to Claude Code" }
454
+ ]
455
+ })),
456
+ /* servers */
457
+ route("GET", "/api/v1/servers", () => registry(options).servers.map((entry) => {
458
+ try {
459
+ const server = loadServer(entry);
460
+ /*
461
+ * The inventory is process-wide, so the tool count needs no tenant.
462
+ * Reach does: it subtracts whatever that tenant switched off. Where
463
+ * the console cannot know which tenant to speak for, it says so with
464
+ * a null rather than quietly reporting the empty tenant's answer as
465
+ * the gateway's.
466
+ */
467
+ const choice = chooseTenant(server, null);
468
+ const surface = toolSurfaceFor(server, choice.ok ? choice.tenant : NO_TENANT);
469
+ const announced = storeFor(server).runtimeState(server.component);
470
+ return {
471
+ id: entry.id,
472
+ kind: entry.kind,
473
+ label: entry.label,
474
+ ok: true,
475
+ component: server.component,
476
+ upstreams: server.gateway.config.upstreams.map((u) => u.name),
477
+ /*
478
+ * Null, not zero, when nothing has been published. A gateway that
479
+ * has not reported is not a gateway serving no tools, and the two
480
+ * used to be the same number here.
481
+ */
482
+ toolCount: surface.live ? surface.entries.length : null,
483
+ surfaceLive: surface.live,
484
+ surfaceStale: surface.stale,
485
+ posture: server.policy.defaults.mode,
486
+ // Whether that posture is applied or only recorded. The console
487
+ // draws a page-level banner from this: a gateway that is only
488
+ // observing must not look like one that is guarding.
489
+ enforcement: server.policy.enforcement,
490
+ reach: choice.ok ? effectiveReach(server, choice.tenant, surface) : null,
491
+ tenantScope: choice.ok ? choice.tenant : null,
492
+ tenantRequired: !choice.ok,
493
+ tenantHint: choice.ok ? null : choice.why,
494
+ running: announced !== undefined && runtimeStateIsLive(announced),
495
+ auditPath: server.auditPath,
496
+ storePath: server.storePath,
497
+ tenantError: server.tenantError
498
+ };
499
+ }
500
+ catch (err) {
501
+ // A broken entry is listed with its error. Failing the whole list
502
+ // would hide every working server behind one bad path.
503
+ return { id: entry.id, kind: entry.kind, label: entry.label, ok: false, error: err.message };
504
+ }
505
+ })),
506
+ route("POST", "/api/v1/servers", (ctx) => {
507
+ const body = (ctx.body ?? {});
508
+ const reg = registry(options);
509
+ const id = typeof body["id"] === "string" && body["id"] ? body["id"] : `srv_${randomBytes(3).toString("hex")}`;
510
+ if (reg.servers.some((s) => s.id === id))
511
+ throw conflict(`a server with id "${id}" is already registered`);
512
+ const entry = { ...body, id, added_at: new Date().toISOString() };
513
+ // Probe before persisting, so the registry cannot hold an entry that
514
+ // never loads. A gateway probe stops at the config: registering a server
515
+ // must not spawn its upstream child processes.
516
+ let loaded;
517
+ try {
518
+ loaded = loadServer(entry);
519
+ }
520
+ catch (err) {
521
+ throw unprocessable(`that server could not be loaded: ${err.message}`);
522
+ }
523
+ writeRegistry({ ...reg, servers: [...reg.servers, entry] }, options.registryPath);
524
+ return { id, component: loaded.component };
525
+ }),
526
+ route("DELETE", "/api/v1/servers/:id", async (ctx) => {
527
+ const reg = registry(options);
528
+ const id = ctx.params["id"];
529
+ if (!reg.servers.some((s) => s.id === id))
530
+ throw notFound(`no registered server with id "${id}"`);
531
+ // A gateway this console started would otherwise keep running with no
532
+ // entry left to stop it from. One an AI app runs is not ours to stop.
533
+ if (processes.isActive(id))
534
+ await processes.stop(id);
535
+ // Only the registry entry is removed; the referenced files are never touched.
536
+ writeRegistry({ ...reg, servers: reg.servers.filter((s) => s.id !== id) }, options.registryPath);
537
+ return { removed: id };
538
+ }),
539
+ /* tools and protection */
540
+ /**
541
+ * Which tenants this gateway has any trace of.
542
+ *
543
+ * Served so the console can offer a choice instead of a blank box, and so
544
+ * nothing in the UI has to carry a tenant list of its own. Historical, not
545
+ * authoritative: a tenant that has never made a call or had a row written
546
+ * will not be here, which is why naming one directly stays possible.
547
+ */
548
+ route("GET", "/api/v1/servers/:id/tenants", (ctx) => {
549
+ const server = serverById(options, ctx.params["id"]);
550
+ const config = server.policy.tenant;
551
+ const assumed = chooseTenant(server, null);
552
+ return {
553
+ tenants: knownTenants(server),
554
+ configured: config !== null && config !== undefined,
555
+ sourceKind: config?.source.kind ?? null,
556
+ required: config?.required ?? false,
557
+ /** Null when the request has to name one. */
558
+ assumed: assumed.ok ? assumed.tenant : null,
559
+ whyNotAssumed: assumed.ok ? null : assumed.why
560
+ };
561
+ }),
562
+ route("GET", "/api/v1/servers/:id/protection", (ctx) => {
563
+ const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
564
+ return buildProtection(server, tenant, explicit);
565
+ }),
566
+ route("GET", "/api/v1/servers/:id/tools", (ctx) => {
567
+ const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
568
+ return buildProtection(server, tenant, explicit).tools;
569
+ }),
570
+ route("GET", "/api/v1/servers/:id/tools/:tool", (ctx) => {
571
+ const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
572
+ const name = ctx.params["tool"];
573
+ const tool = buildProtection(server, tenant, explicit).tools.find((t) => t.name === name);
574
+ if (!tool)
575
+ throw notFound(`no tool "${name}" on server "${server.entry.id}"`);
576
+ const entry = toolSurfaceFor(server, tenant).entries.find((t) => t.name === name);
577
+ return { ...tool, inputSchema: entry?.inputSchema ?? null, activity: recentActivity(server, name, 10, otherComponentsSharingLog(options, server)) };
578
+ }),
579
+ /**
580
+ * The exposure switch: take one tool off the model's menu, or hand it back
581
+ * to policy.
582
+ *
583
+ * This is the one mutation the console makes to what a server exposes, and
584
+ * it is deliberately one-directional in effect. Switching a tool off
585
+ * refuses it before anything else is weighed and hides it from
586
+ * `tools/list`. Switching it back on only *deletes* that row: the tool
587
+ * returns to whatever `policy.yaml` already said, which may still be deny
588
+ * or approve. Nothing stored here can release a call `decide()` refuses, so
589
+ * the console still cannot widen a policy — which is why it may do this at
590
+ * all without writing to `policy.yaml`.
591
+ */
592
+ route("PUT", "/api/v1/servers/:id/tools/:tool/exposure", (ctx) => {
593
+ const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
594
+ const name = ctx.params["tool"];
595
+ /*
596
+ * The tool name is checked against what a *live* gateway says it is
597
+ * serving, which is the whole reason this route can exist at all now.
598
+ * A name taken from a stale list would write a row that reads as
599
+ * protection and guards nothing -- the gateway's own admin API refuses
600
+ * for exactly this reason before it writes.
601
+ */
602
+ const surface = toolSurfaceFor(server, tenant);
603
+ const writable = surfaceWritable(surface);
604
+ if (!writable.ok)
605
+ throw unprocessable(`cannot change exposure for "${server.entry.id}": ${writable.why}`);
606
+ const entry = surface.entries.find((t) => t.name === name);
607
+ if (!entry) {
608
+ throw notFound(`no tool "${name}" in what "${server.entry.id}" is currently serving. ` +
609
+ `Its upstreams advertise: ${surface.entries.map((t) => t.name).join(", ") || "nothing"}.`);
610
+ }
611
+ const body = (ctx.body ?? {});
612
+ let change;
613
+ try {
614
+ change = parseExposureChange({ tool: name, disabled: body["disabled"], reason: body["reason"] ?? "" });
615
+ }
616
+ catch (err) {
617
+ throw unprocessable(`invalid exposure change: ${err.message}`);
618
+ }
619
+ const scoped = scopedFor(server, tenant);
620
+ /*
621
+ * The disable-keeps / enable-rolls-back asymmetry lives in core, because
622
+ * the gateway's admin API and its CLI flip the same bit and three
623
+ * hand-copied versions of that rule is how two of them end up wrong.
624
+ */
625
+ const { changed, warning } = applyExposureChange({
626
+ scoped,
627
+ audit: auditFor(server, ctx.actor),
628
+ change,
629
+ actor: ctx.actor,
630
+ effect: entry.effect ?? undefined,
631
+ channel: `the console, for tenant ${tenant === "" ? "(none)" : tenant}`
632
+ });
633
+ // Re-read, so the row returned reflects the write that just happened
634
+ // rather than the surface as it was before it.
635
+ const updated = toolSurfaceFor(server, tenant).entries.find((t) => t.name === name) ?? entry;
636
+ const tool = toolProtection(server, updated, scoped.listGrants({ activeOnly: true }));
637
+ return { tool, changed, warning, tenant, explicitTenant: explicit };
638
+ }),
639
+ /* per-tool rules
640
+ *
641
+ * The console's one policy writer, and the thing that ended its "can only
642
+ * narrow" posture.
643
+ *
644
+ * The exposure switch is allowed to live in the approvals database because
645
+ * it can only subtract. Setting a tool's rule is not: it can turn a refused
646
+ * tool into one that runs. So it writes `policy.yaml` instead — the file
647
+ * people review in git — which keeps the Policy page, `hmcp policy` and a
648
+ * diff describing everything in force, and the gateway adopts it within
649
+ * about a second.
650
+ *
651
+ * The boundary is in `policy-write.ts` and is checked per write: one rule
652
+ * per tool, named literally, every other rule identical in value and in
653
+ * position, nothing outside `rules` touched, no regex and no `coerce`, and
654
+ * a confirmation for each of the three ways a change can widen something.
655
+ *
656
+ * The general writers -- any setting, any rule, the file as text -- are in
657
+ * `routes/policy.ts`, under `/policy/setting`, `/policy/rules` and
658
+ * `/policy/file`, with a loosening acknowledgement of their own. `PUT
659
+ * /policy` itself still does not exist, and two tests assert the 404.
660
+ */
661
+ route("POST", "/api/v1/servers/:id/policy/tool-rule/preview", (ctx) => {
662
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
663
+ const { draft, entry, liveTools } = toolRuleTarget(server, tenant, ctx.body, ctx.actor);
664
+ const preview = previewToolRule({
665
+ policy: server.policy,
666
+ draft,
667
+ disabled: entry.disabled !== null,
668
+ liveTools
669
+ });
670
+ return toolRulePreviewDto(server, preview);
671
+ }),
672
+ /** What reverting to policy would leave behind, before anything is removed. */
673
+ route("GET", "/api/v1/servers/:id/policy/tool-rule/:tool/preview-clear", (ctx) => {
674
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
675
+ const name = ctx.params["tool"];
676
+ const entry = toolSurfaceFor(server, tenant).entries.find((t) => t.name === name);
677
+ const preview = previewClearToolRule({
678
+ policy: server.policy,
679
+ tool: name,
680
+ disabled: entry?.disabled != null
681
+ });
682
+ if (!preview)
683
+ throw notFound(`no console-written rule for "${name}"`);
684
+ return {
685
+ removed: preview.removed,
686
+ yaml: ruleToYaml(preview.removed),
687
+ verdict: { kind: preview.verdict.kind, ruleId: preview.verdict.ruleId, reason: preview.verdict.reason },
688
+ current: { kind: preview.current.kind, ruleId: preview.current.ruleId },
689
+ /* What will bound the tool once ours is gone — the rule that governed
690
+ it before, bounds and all. */
691
+ bounds: boundsOf(preview.policy.rules.find((r) => globMatch(r.match, name))),
692
+ becomesUnclassified: preview.becomesUnclassified,
693
+ expectedDigest: policyDigest(server.policy)
694
+ };
695
+ }),
696
+ route("POST", "/api/v1/servers/:id/policy/tool-rule", (ctx) => {
697
+ const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
698
+ const { draft, entry, liveTools } = toolRuleTarget(server, tenant, ctx.body, ctx.actor);
699
+ if (server.policyFile === null || !server.policyWritable.ok) {
700
+ throw unprocessable(server.policyWritable.why ?? "this gateway's policy cannot be written from here");
701
+ }
702
+ const body = (ctx.body ?? {});
703
+ const expectedDigest = typeof body["expectedDigest"] === "string" ? body["expectedDigest"] : "";
704
+ if (!expectedDigest) {
705
+ throw badRequest("expectedDigest is required: it is the digest of the policy the preview was computed from, " +
706
+ "and without it a file edited in the meantime would be overwritten");
707
+ }
708
+ const preview = previewToolRule({ policy: server.policy, draft, liveTools });
709
+ const result = writeToolRule({
710
+ policyPath: server.policyFile,
711
+ draft,
712
+ expectedDigest,
713
+ knownToLiveSurface: true,
714
+ liveTools,
715
+ writesAllowed: true,
716
+ overridesAllowed: server.policyOverrides
717
+ });
718
+ if (result.kind === "stale")
719
+ throw conflict(result.why);
720
+ if (result.kind === "refused") {
721
+ /*
722
+ * A refused widening is exactly the record a security log should carry.
723
+ * Written before the 422 so the attempt is in the chain, with what the
724
+ * operator was shown — the predecessor of this route exported a
725
+ * refusal id and emitted it nowhere.
726
+ */
727
+ try {
728
+ auditFor(server, ctx.actor).append({
729
+ tool: draft.tool,
730
+ effect: draft.effect,
731
+ decision: "deny",
732
+ tenant: tenant || null,
733
+ rule_id: TOOL_RULE_REFUSED,
734
+ reason: `${ctx.actor} tried to set a rule for ${draft.tool} and it was refused: ${result.why}`,
735
+ outcome: "denied",
736
+ args_redacted: {
737
+ tool: draft.tool,
738
+ effect: draft.effect,
739
+ decision: draft.decision,
740
+ needs: result.needs ?? null,
741
+ origin: "console"
742
+ }
743
+ });
744
+ }
745
+ catch {
746
+ /* the refusal below is the outcome; an unwritable log must not change it */
747
+ }
748
+ throw unprocessable(result.why);
749
+ }
750
+ /*
751
+ * Audited after the write and deliberately not rolled back when the
752
+ * record fails.
753
+ *
754
+ * The grants route rolls back for the opposite reason: a grant releasing
755
+ * calls with nobody recorded as granting it is the thing the log exists
756
+ * to prevent. Here the file is already on disk and the gateway may have
757
+ * reloaded it, so undoing would be a second write — removing a rule,
758
+ * which is itself unaudited. A rule visible in the file and in `git diff`
759
+ * with no log line is a smaller problem than a writer that deletes rules
760
+ * on an I/O error. The failure is reported.
761
+ */
762
+ let warning = null;
763
+ try {
764
+ auditFor(server, ctx.actor).appendStrict({
765
+ tool: draft.tool,
766
+ effect: draft.effect,
767
+ /* What policy now says, not what was asked for — so the Audit page's
768
+ decision filter means something for every op. */
769
+ decision: preview.verdict.kind,
770
+ tenant: tenant || null,
771
+ rule_id: result.action === "update" ? TOOL_RULE_UPDATE : TOOL_RULE_SET,
772
+ reason: `${draft.tool} set to ${draft.effect}/${draft.decision} via the console by ${ctx.actor}` +
773
+ (draft.reason ? `: ${draft.reason}` : "") +
774
+ `; rule "${result.rule.id}" written to ${server.policyFile}` +
775
+ (preview.carriedFrom ? `, carrying the bounds from "${preview.carriedFrom}"` : "") +
776
+ (preview.overriddenReason
777
+ ? `, overriding "${preview.overriddenReason.ruleId}" ("${preview.overriddenReason.reason}")`
778
+ : ""),
779
+ outcome: "completed",
780
+ args_redacted: {
781
+ op: result.action,
782
+ tool: draft.tool,
783
+ effect: draft.effect,
784
+ decision: draft.decision,
785
+ rule_id: result.rule.id,
786
+ args: result.rule.args ?? null,
787
+ on_violation: result.rule.on_violation,
788
+ unknown_args: result.rule.unknown_args,
789
+ bounds_carried_from: preview.carriedFrom,
790
+ /* The rule as it was: the only way the log can restore a change. */
791
+ previous: result.previous,
792
+ overrode: preview.overriddenReason,
793
+ acknowledged: draft.acknowledged ?? null,
794
+ stranded: preview.strandedRule,
795
+ loosens: preview.loosens,
796
+ /*
797
+ * A per-tool rule is process-wide: it applies to every tenant of
798
+ * this gateway, unlike the exposure switch beside it. Recorded so
799
+ * the log does not imply otherwise.
800
+ */
801
+ scope: "all tenants",
802
+ origin: "console",
803
+ policy_digest_before: result.previousDigest,
804
+ policy_digest_after: result.digest
805
+ }
806
+ });
807
+ }
808
+ catch (err) {
809
+ warning =
810
+ `${draft.tool} was set but the audit record failed: ${err.message}. ` +
811
+ `The rule is in ${server.policyFile}.`;
812
+ }
813
+ /*
814
+ * Re-read from disk, so what comes back is what a reader of the file
815
+ * would see — including that the gateway has probably not reloaded yet,
816
+ * which is why the tool's verdict here may still describe the old policy
817
+ * for a moment.
818
+ */
819
+ const reloaded = loadServer(server.entry);
820
+ const after = toolSurfaceFor(reloaded, tenant).entries.find((t) => t.name === draft.tool);
821
+ const tool = after
822
+ ? toolProtection(reloaded, after, scopedFor(reloaded, tenant).listGrants({ activeOnly: true }))
823
+ : null;
824
+ return {
825
+ rule: result.rule,
826
+ action: result.action,
827
+ digest: result.digest,
828
+ previousDigest: result.previousDigest,
829
+ policyPath: server.policyFile,
830
+ yaml: ruleToYaml(result.rule),
831
+ carriedFrom: preview.carriedFrom,
832
+ strandedRule: preview.strandedRule,
833
+ tool,
834
+ warning,
835
+ tenant,
836
+ explicitTenant: explicit
837
+ };
838
+ }),
839
+ /** Revert to policy: remove the console's rule and nothing else. */
840
+ route("DELETE", "/api/v1/servers/:id/policy/tool-rule/:tool", (ctx) => {
841
+ const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
842
+ const name = ctx.params["tool"];
843
+ if (server.policyFile === null || !server.policyWritable.ok) {
844
+ throw unprocessable(server.policyWritable.why ?? "this gateway's policy cannot be written from here");
845
+ }
846
+ const expectedDigest = ctx.query.get("expectedDigest") ?? "";
847
+ if (!expectedDigest)
848
+ throw badRequest("expectedDigest is required");
849
+ const liveTools = toolSurfaceFor(server, tenant).entries.map((t) => t.name);
850
+ const before = previewClearToolRule({ policy: server.policy, tool: name });
851
+ const result = clearToolRule({
852
+ policyPath: server.policyFile,
853
+ tool: name,
854
+ expectedDigest,
855
+ liveTools,
856
+ writesAllowed: true
857
+ });
858
+ if (result.kind === "stale")
859
+ throw conflict(result.why);
860
+ if (result.kind === "refused")
861
+ throw unprocessable(result.why);
862
+ let warning = null;
863
+ try {
864
+ auditFor(server, ctx.actor).appendStrict({
865
+ tool: name,
866
+ effect: result.previous?.effect ?? null,
867
+ decision: before?.verdict.kind ?? "deny",
868
+ tenant: tenant || null,
869
+ rule_id: TOOL_RULE_CLEAR,
870
+ reason: `${name} handed back to policy by ${ctx.actor}; rule "${result.previous?.id}" removed from ` +
871
+ `${server.policyFile}. It is now ${before?.verdict.kind ?? "decided by policy"} under ` +
872
+ `"${before?.verdict.ruleId}".`,
873
+ outcome: "completed",
874
+ args_redacted: {
875
+ op: "cleared",
876
+ tool: name,
877
+ /* The removed rule in full: the log is the only place it survives. */
878
+ previous: result.previous,
879
+ becomes_unclassified: before?.becomesUnclassified ?? false,
880
+ scope: "all tenants",
881
+ origin: "console",
882
+ policy_digest_before: result.previousDigest,
883
+ policy_digest_after: result.digest
884
+ }
885
+ });
886
+ }
887
+ catch (err) {
888
+ warning =
889
+ `the rule was removed but the audit record failed: ${err.message}. ` +
890
+ `It was: ${JSON.stringify(result.previous)}`;
891
+ }
892
+ const reloaded = loadServer(server.entry);
893
+ const after = toolSurfaceFor(reloaded, tenant).entries.find((t) => t.name === name);
894
+ const tool = after
895
+ ? toolProtection(reloaded, after, scopedFor(reloaded, tenant).listGrants({ activeOnly: true }))
896
+ : null;
897
+ return {
898
+ removed: result.previous,
899
+ digest: result.digest,
900
+ becomesUnclassified: before?.becomesUnclassified ?? false,
901
+ tool,
902
+ warning,
903
+ tenant,
904
+ explicitTenant: explicit
905
+ };
906
+ }),
907
+ /**
908
+ * The other half of the answer to "an unclassified tool is a wall": leave
909
+ * the tool unclassified and change what that means, from refused outright
910
+ * to held for a human.
911
+ *
912
+ * A posture change rather than a permission grant -- nothing runs unasked
913
+ * under either value -- which is why it is a toggle between the schema's
914
+ * two existing values and not a form.
915
+ */
916
+ route("PUT", "/api/v1/servers/:id/policy/unclassified", (ctx) => {
917
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
918
+ const body = (ctx.body ?? {});
919
+ const value = body["value"];
920
+ if (value !== "deny" && value !== "approve") {
921
+ throw badRequest('value must be "deny" or "approve"');
922
+ }
923
+ if (server.policyFile === null || !server.policyWritable.ok) {
924
+ throw unprocessable(server.policyWritable.why ?? "this gateway's policy cannot be written from here");
925
+ }
926
+ const expectedDigest = typeof body["expectedDigest"] === "string" ? body["expectedDigest"] : "";
927
+ if (!expectedDigest)
928
+ throw badRequest("expectedDigest is required");
929
+ const result = writeUnclassifiedPosture({
930
+ policyPath: server.policyFile,
931
+ value,
932
+ expectedDigest,
933
+ actor: ctx.actor,
934
+ writesAllowed: true
935
+ });
936
+ if (result.kind === "stale")
937
+ throw conflict(result.why);
938
+ if (result.kind === "refused")
939
+ throw unprocessable(result.why);
940
+ let warning = null;
941
+ try {
942
+ auditFor(server, ctx.actor).appendStrict({
943
+ tool: "(policy)",
944
+ effect: null,
945
+ decision: value === "approve" ? "approve" : "deny",
946
+ tenant: tenant || null,
947
+ rule_id: UNCLASSIFIED_POSTURE_RULE,
948
+ reason: `defaults.on_unclassified set to ${value} via the console by ${ctx.actor}; ` +
949
+ (value === "approve"
950
+ ? "a tool nothing classifies is now held for a human rather than refused outright"
951
+ : "a tool nothing classifies is now refused outright rather than held for a human"),
952
+ outcome: "completed",
953
+ args_redacted: {
954
+ on_unclassified: value,
955
+ policy_digest_before: result.previousDigest,
956
+ policy_digest_after: result.digest
957
+ }
958
+ });
959
+ }
960
+ catch (err) {
961
+ warning = `the change was written but the audit record failed: ${err.message}`;
962
+ }
963
+ return { value, digest: result.digest, previousDigest: result.previousDigest, warning };
964
+ }),
965
+ /* approvals */
966
+ route("GET", "/api/v1/servers/:id/approvals/pending", (ctx) => {
967
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
968
+ const limit = intParam(ctx.query, "limit") ?? 50;
969
+ return approvalScopes(server, tenant)
970
+ .flatMap((s) => s.listPending(limit))
971
+ .sort((a, b) => a.created_at - b.created_at)
972
+ .slice(0, limit)
973
+ .map(approvalDto);
974
+ }),
975
+ route("GET", "/api/v1/servers/:id/approvals", (ctx) => {
976
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
977
+ const limit = intParam(ctx.query, "limit") ?? 50;
978
+ return approvalScopes(server, tenant)
979
+ .flatMap((s) => s.list(limit))
980
+ .sort((a, b) => b.created_at - a.created_at)
981
+ .slice(0, limit)
982
+ .map(approvalDto);
983
+ }),
984
+ route("POST", "/api/v1/servers/:id/approvals/:aprId/decide", (ctx) => {
985
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
986
+ const body = (ctx.body ?? {});
987
+ if (body.state !== "granted" && body.state !== "denied") {
988
+ throw badRequest('state must be "granted" or "denied"');
989
+ }
990
+ const note = typeof body.note === "string" ? body.note : "";
991
+ // The toolbox's own request, or one the Claude Code guard parked in the same database.
992
+ const holder = approvalScopeOf(server, tenant, ctx.params["aprId"]);
993
+ /*
994
+ * "Approve, and allow calls like this for a while": the grant is built
995
+ * from this call by core's `rememberOnApprove`, the same code `hmcp
996
+ * approve --remember` runs, and created *before* the decision, so a
997
+ * grant that cannot be written leaves the call undecided rather than
998
+ * released with the question unanswered.
999
+ */
1000
+ let remembered = null;
1001
+ if (body.remember !== undefined && body.remember !== null) {
1002
+ if (body.state !== "granted")
1003
+ throw badRequest("remember goes with approving a call, not refusing one");
1004
+ /*
1005
+ * Refused for a Claude Code call. A grant written here would be bounded
1006
+ * by this toolbox's policy and recorded in its name, while the guard
1007
+ * that spends it may be checking calls against another policy file.
1008
+ * A standing permission for a Claude Code tool is a rule naming
1009
+ * `claude-code__<tool>`, written on purpose.
1010
+ */
1011
+ if (holder.scope.component === GUARD_COMPONENT) {
1012
+ throw unprocessable(`"Approve and remember" is not offered for Claude Code's own tools. Approve this call on its own, or add a ` +
1013
+ `rule for this tool (claude-code__…) to the toolbox's policy. Nothing was approved.`);
1014
+ }
1015
+ const parsed = RememberSchema.safeParse(body.remember);
1016
+ if (!parsed.success) {
1017
+ throw badRequest(`remember must be {ttlSeconds, maxUses}: ${parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`);
1018
+ }
1019
+ const scoped = holder;
1020
+ const row = scoped.get(ctx.params["aprId"]);
1021
+ if (!row)
1022
+ throw notFound(`no approval request with id ${ctx.params["aprId"]}`);
1023
+ if (row.state !== "pending")
1024
+ throw conflict(`approval ${row.id} is already ${row.state} and cannot be decided again`);
1025
+ try {
1026
+ remembered = rememberOnApprove({
1027
+ scoped,
1028
+ audit: auditFor(server, ctx.actor),
1029
+ row,
1030
+ policy: server.policy,
1031
+ ttlSeconds: parsed.data.ttlSeconds,
1032
+ maxUses: parsed.data.maxUses,
1033
+ actor: ctx.actor,
1034
+ via: "the console"
1035
+ });
1036
+ }
1037
+ catch (err) {
1038
+ if (err instanceof RememberError)
1039
+ throw unprocessable(`${err.message} Nothing was approved.`);
1040
+ throw err;
1041
+ }
1042
+ }
1043
+ /*
1044
+ * "Approve, and stop asking me about this tool."
1045
+ *
1046
+ * Only offered for a call held because nothing classified the tool --
1047
+ * under `on_unclassified: approve`, where the queue is the only place
1048
+ * the gap shows up -- and it may only ever write `decision: approve`.
1049
+ *
1050
+ * The reviewer approved *one call*. Turning that into a standing
1051
+ * permission from a checkbox beside a queue row is exactly the widening
1052
+ * this whole boundary exists to prevent, so the effect is theirs to pick
1053
+ * and the decision is fixed: the tool stops being unclassified and keeps
1054
+ * asking. Making it run unasked is the full form on the Functions page,
1055
+ * with its preview and its confirmation.
1056
+ */
1057
+ const classifyEffect = typeof body.classify?.["effect"] === "string"
1058
+ ? body.classify["effect"]
1059
+ : null;
1060
+ const result = holder.decideChecked(ctx.params["aprId"], body.state, ctx.actor, note);
1061
+ if (!result.ok && remembered) {
1062
+ // Lost a race after the grant was made: withdraw it, and say so in the log.
1063
+ holder.revokeGrant(remembered.id, "system");
1064
+ auditFor(server, ctx.actor).append({
1065
+ tool: remembered.tool_match,
1066
+ decision: "deny",
1067
+ rule_id: "standing_grant.revoke",
1068
+ reason: `standing grant ${remembered.id} withdrawn: the approval it remembered could not be decided (${result.error})`,
1069
+ outcome: "completed",
1070
+ grant_id: remembered.id
1071
+ });
1072
+ }
1073
+ if (!result.ok) {
1074
+ throw result.error.includes("no approval request") ? notFound(result.error) : conflict(result.error);
1075
+ }
1076
+ // The CLI leaves no audit trace when a human approves; the console should
1077
+ // not inherit that gap. A decision is itself a security event.
1078
+ const { args } = parseArgs(result.row);
1079
+ auditFor(server, ctx.actor).append({
1080
+ tool: result.row.tool,
1081
+ effect: result.row.effect ?? null,
1082
+ decision: body.state === "granted" ? "approve" : "deny",
1083
+ rule_id: "approval.decide",
1084
+ reason: `${body.state === "granted" ? "approved" : "denied"} by ${ctx.actor} in the console${note ? `: ${note}` : ""}`,
1085
+ outcome: "completed",
1086
+ approval_id: result.row.id,
1087
+ args_redacted: (args ?? null)
1088
+ });
1089
+ /*
1090
+ * After the decision, never before, and its failure never undoes it.
1091
+ *
1092
+ * The call in flight was already released; a file write that fails must
1093
+ * not turn an approval the reviewer gave into a refusal, and it must not
1094
+ * leave them to answer the same question twice. So the outcome of the
1095
+ * classification is reported beside the decision rather than replacing
1096
+ * it.
1097
+ */
1098
+ let classified = null;
1099
+ let classifyWarning = null;
1100
+ if (classifyEffect && body.state === "granted") {
1101
+ try {
1102
+ classified = classifyFromApproval(server, tenant, result.row, classifyEffect, ctx.actor);
1103
+ }
1104
+ catch (err) {
1105
+ classifyWarning = `the call was approved, but ${result.row.tool} was not classified: ${err.message}`;
1106
+ }
1107
+ }
1108
+ return {
1109
+ ...approvalDto(result.row),
1110
+ classified,
1111
+ classifyWarning,
1112
+ remembered: remembered ? grantDto(holder.getGrant(remembered.id) ?? remembered) : null
1113
+ };
1114
+ }),
1115
+ /* standing grants */
1116
+ route("GET", "/api/v1/servers/:id/grants", (ctx) => {
1117
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
1118
+ const activeOnly = ctx.query.get("state") === "active";
1119
+ return scopedFor(server, tenant)
1120
+ .listGrants({ activeOnly, limit: intParam(ctx.query, "limit") ?? 100 })
1121
+ .map(grantDto);
1122
+ }),
1123
+ route("POST", "/api/v1/servers/:id/grants", (ctx) => {
1124
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
1125
+ const body = (ctx.body ?? {});
1126
+ // Accept a TTL and derive the deadline, which is what a form can express.
1127
+ const ttl = Number(body["ttl_seconds"]);
1128
+ const expires = Number.isFinite(ttl) ? Date.now() + ttl * 1000 : Number(body["expires_at"]);
1129
+ let draft;
1130
+ try {
1131
+ draft = parseGrantDraft({
1132
+ tool_match: body["tool_match"],
1133
+ effect: body["effect"] ?? null,
1134
+ constraints: body["constraints"] ?? {},
1135
+ expires_at: expires,
1136
+ max_uses: body["max_uses"] ?? null,
1137
+ reason: body["reason"],
1138
+ created_by: ctx.actor
1139
+ });
1140
+ }
1141
+ catch (err) {
1142
+ throw unprocessable(err.message);
1143
+ }
1144
+ const scoped = scopedFor(server, tenant);
1145
+ const grant = scoped.createGrant(draft);
1146
+ // The requirement is that no pre-approval exists unaudited, so this uses
1147
+ // appendStrict (which throws) rather than append (which only warns), and
1148
+ // the grant is withdrawn if the record cannot be written.
1149
+ try {
1150
+ auditFor(server, ctx.actor).appendStrict({
1151
+ tool: grant.tool_match,
1152
+ effect: grant.effect ?? null,
1153
+ decision: "approve",
1154
+ rule_id: "standing_grant.create",
1155
+ reason: `standing grant ${grant.id} created by ${ctx.actor}: ${grant.reason} ` +
1156
+ `(matches ${grant.tool_match}, ${grant.max_uses === null ? "unlimited uses" : `${grant.max_uses} use(s)`}, ` +
1157
+ `expires ${new Date(grant.expires_at).toISOString()})`,
1158
+ outcome: "completed",
1159
+ grant_id: grant.id,
1160
+ args_redacted: {
1161
+ tool_match: grant.tool_match,
1162
+ effect: grant.effect,
1163
+ constraints: draft.constraints ?? {},
1164
+ max_uses: grant.max_uses,
1165
+ expires_at: grant.expires_at
1166
+ }
1167
+ });
1168
+ }
1169
+ catch (err) {
1170
+ scoped.revokeGrant(grant.id, "system");
1171
+ throw new Error(`the grant was withdrawn because it could not be audited: ${err.message}`);
1172
+ }
1173
+ return grantDto(scoped.getGrant(grant.id));
1174
+ }),
1175
+ route("DELETE", "/api/v1/servers/:id/grants/:grantId", (ctx) => {
1176
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
1177
+ const scoped = scopedFor(server, tenant);
1178
+ const id = ctx.params["grantId"];
1179
+ const existing = scoped.getGrant(id);
1180
+ if (!existing)
1181
+ throw notFound(`no standing grant with id "${id}"`);
1182
+ const revoked = scoped.revokeGrant(id, ctx.actor);
1183
+ if (!revoked)
1184
+ throw conflict(`standing grant ${id} is already ${existing.state}`);
1185
+ // Revocation tightens, so unlike creation it is kept even if the audit
1186
+ // append fails; the failure is reported instead of undoing the fix.
1187
+ let warning = null;
1188
+ try {
1189
+ auditFor(server, ctx.actor).appendStrict({
1190
+ tool: revoked.tool_match,
1191
+ decision: "deny",
1192
+ rule_id: "standing_grant.revoke",
1193
+ reason: `standing grant ${revoked.id} revoked by ${ctx.actor} after ${revoked.uses} use(s)`,
1194
+ outcome: "completed",
1195
+ grant_id: revoked.id
1196
+ });
1197
+ }
1198
+ catch (err) {
1199
+ warning = `the grant was revoked but the audit record failed: ${err.message}`;
1200
+ }
1201
+ return { ...grantDto(revoked), warning };
1202
+ }),
1203
+ /**
1204
+ * Dry run: what would this grant release, right now?
1205
+ *
1206
+ * Writes nothing and claims no uses. This is what makes the settings page
1207
+ * honest — you see the blast radius before you create the grant.
1208
+ */
1209
+ route("POST", "/api/v1/servers/:id/grants/preview", (ctx) => {
1210
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
1211
+ const body = (ctx.body ?? {});
1212
+ /*
1213
+ * The point of a preview is to show the blast radius before a grant is
1214
+ * created, so an empty list has to mean "covers nothing" and nothing
1215
+ * else. Reading an unpublished surface would have it quietly claim that
1216
+ * about a grant covering every tool the gateway serves.
1217
+ */
1218
+ const surface = toolSurfaceFor(server, tenant);
1219
+ const writable = surfaceWritable(surface);
1220
+ const ttl = Number(body["ttl_seconds"]);
1221
+ const expires = Number.isFinite(ttl) ? Date.now() + ttl * 1000 : Date.now() + 3600_000;
1222
+ let draft;
1223
+ try {
1224
+ draft = parseGrantDraft({
1225
+ tool_match: body["tool_match"],
1226
+ effect: body["effect"] ?? null,
1227
+ constraints: body["constraints"] ?? {},
1228
+ expires_at: expires,
1229
+ max_uses: body["max_uses"] ?? null,
1230
+ reason: typeof body["reason"] === "string" && body["reason"] ? body["reason"] : "preview",
1231
+ created_by: ctx.actor
1232
+ });
1233
+ }
1234
+ catch (err) {
1235
+ throw unprocessable(err.message);
1236
+ }
1237
+ const candidate = {
1238
+ id: "sg_preview",
1239
+ ...scopeFor(server, tenant),
1240
+ created_at: Date.now(),
1241
+ expires_at: draft.expires_at,
1242
+ tool_match: draft.tool_match,
1243
+ effect: draft.effect ?? null,
1244
+ constraints: JSON.stringify(draft.constraints ?? {}),
1245
+ max_uses: draft.max_uses ?? null,
1246
+ uses: 0,
1247
+ reason: draft.reason,
1248
+ created_by: draft.created_by,
1249
+ state: "active",
1250
+ revoked_at: null,
1251
+ revoked_by: null,
1252
+ closed: draft.closed ? 1 : 0
1253
+ };
1254
+ return {
1255
+ expiresAt: draft.expires_at,
1256
+ surfaceKnown: writable.ok,
1257
+ surfaceUnknownWhy: writable.ok ? null : writable.why,
1258
+ tools: surface.entries.map((entry) => {
1259
+ /*
1260
+ * Tool and effect only: there is no call here, and weighing the
1261
+ * grant's own bounds against an invented empty one reports every
1262
+ * value bound as broken.
1263
+ */
1264
+ const match = grantCoversTool(candidate, entry.name, entry.effect);
1265
+ /*
1266
+ * Matching the tool is not the whole answer. A grant releases a call
1267
+ * held by a rule's bound only when the grant bounds that argument
1268
+ * too, so the rule that governs this tool decides how much of it
1269
+ * this grant actually reaches. `heldBounds` is what it does not:
1270
+ * each one is an argument whose calls will still stop and still ask
1271
+ * a person. Empty for a tool the grant does not cover at all, where
1272
+ * it would only be noise.
1273
+ */
1274
+ const rule = server.policy.rules.find((r) => globMatch(r.match, entry.name));
1275
+ return {
1276
+ name: entry.name,
1277
+ effect: entry.effect,
1278
+ covers: match.matches,
1279
+ why: match.reason,
1280
+ heldBounds: match.matches ? grantBoundGaps(draft.constraints ?? {}, rule?.args) : [],
1281
+ /*
1282
+ * A call can also be held over an argument no bound names at all,
1283
+ * which a preview cannot enumerate in advance -- only say to
1284
+ * expect.
1285
+ */
1286
+ unknownArgsHeld: match.matches && rule !== undefined && rule.unknown_args === "approve"
1287
+ };
1288
+ })
1289
+ };
1290
+ }),
1291
+ /* overview */
1292
+ /**
1293
+ * Aggregates for the overview, with the bound they were read under.
1294
+ *
1295
+ * `tenant=*` reads every tenant, which is the only honest way to answer
1296
+ * "what is this gateway doing" on a deployment serving several. Anything
1297
+ * else goes through `scopedRequest`, so a `jwt-verified` gateway is still
1298
+ * refused rather than guessed at.
1299
+ */
1300
+ route("GET", "/api/v1/servers/:id/metrics", (ctx) => {
1301
+ const requested = ctx.query.get("window") ?? "24h";
1302
+ if (!isWindow(requested))
1303
+ throw badRequest(`window must be one of 1h, 24h, 7d, 30d, all`);
1304
+ const window = requested;
1305
+ if (ctx.query.get("tenant") === "*") {
1306
+ const whole = serverById(options, ctx.params["id"]);
1307
+ return buildMetrics(whole, null, window, otherComponentsSharingLog(options, whole));
1308
+ }
1309
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
1310
+ return buildMetrics(server, tenant, window, otherComponentsSharingLog(options, server));
1311
+ }),
1312
+ /**
1313
+ * The scanner rules over what this gateway published.
1314
+ *
1315
+ * The same rules `hmcp-gateway scan` runs, over the same kind of target, so
1316
+ * the console cannot report a different answer than the CLI for one
1317
+ * gateway. It reads the upstream's own description rather than the rewritten
1318
+ * one, because the rewrite is what injection detection already did and
1319
+ * scanning its output would report nothing on the surfaces that needed it.
1320
+ */
1321
+ route("GET", "/api/v1/servers/:id/scan", (ctx) => {
1322
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
1323
+ const format = ctx.query.get("format");
1324
+ if (format !== null && format !== "json" && format !== "sarif")
1325
+ throw badRequest('format must be "json" or "sarif"');
1326
+ const report = buildScan(server, tenant);
1327
+ /*
1328
+ * The document `hmcp-gateway scan --sarif` writes, from the same
1329
+ * function, so a CI upload and a download from here agree.
1330
+ */
1331
+ if (format === "sarif")
1332
+ return JSON.parse(toSarif(report, "upstream MCP servers"));
1333
+ return report;
1334
+ }),
1335
+ /**
1336
+ * The policy on disk, beside the digest the running process is enforcing.
1337
+ *
1338
+ * `protection.runtime.policyApplied` already says whether the two agree,
1339
+ * which is enough to raise an alarm and not enough to act on: a reviewer
1340
+ * who is told the running gateway is enforcing something else immediately
1341
+ * needs to know *what*. The text is the file the console already reads to
1342
+ * build every other page, and policy is reviewed in git, so this discloses
1343
+ * nothing new.
1344
+ *
1345
+ * There is no `PUT` here: a test asserts the 404. Editing the file as
1346
+ * text is `PUT /policy/file` (routes/policy.ts), digest-locked and graded
1347
+ * for loosening like every other policy write.
1348
+ */
1349
+ route("GET", "/api/v1/servers/:id/policy", (ctx) => {
1350
+ const { server } = scopedRequest(options, ctx.params["id"], ctx.query);
1351
+ const announced = storeFor(server).runtimeState(server.component);
1352
+ let text = null;
1353
+ let readError = null;
1354
+ try {
1355
+ text = readFileSync(server.policyPath, "utf8");
1356
+ }
1357
+ catch (err) {
1358
+ readError = err.message;
1359
+ }
1360
+ return {
1361
+ path: server.policyPath,
1362
+ text,
1363
+ readError,
1364
+ policy: server.policy,
1365
+ runningDigest: announced?.policy_digest ?? null,
1366
+ runningPolicyPath: announced?.policy_path ?? null
1367
+ };
1368
+ }),
1369
+ /* audit */
1370
+ route("GET", "/api/v1/servers/:id/audit", (ctx) => {
1371
+ const server = serverById(options, ctx.params["id"]);
1372
+ // A log shared with other toolboxes: their calls are left out unless a component is asked for by name.
1373
+ const others = csv(ctx.query, "component") ? [] : otherComponentsSharingLog(options, server);
1374
+ const page = queryAuditLog(server.auditPath, {
1375
+ limit: intParam(ctx.query, "limit") ?? 50,
1376
+ ...(others.length > 0 ? { excludeComponent: others } : {}),
1377
+ ...(intParam(ctx.query, "cursor") !== undefined ? { beforeSeq: intParam(ctx.query, "cursor") } : {}),
1378
+ ...(csv(ctx.query, "decision") ? { decision: csv(ctx.query, "decision") } : {}),
1379
+ ...(csv(ctx.query, "outcome") ? { outcome: csv(ctx.query, "outcome") } : {}),
1380
+ ...(csv(ctx.query, "component") ? { component: csv(ctx.query, "component") } : {}),
1381
+ // One log holds every tenant's records, so this is how a reviewer
1382
+ // reads one customer's history out of it. `?tenant=` with an empty
1383
+ // value selects the records that carry no tenant.
1384
+ ...(ctx.query.has("tenant") ? { tenant: csv(ctx.query, "tenant") ?? [""] } : {}),
1385
+ // Recording which agent made a call is only half the requirement;
1386
+ // without this it would be written down and unaskable.
1387
+ ...(csv(ctx.query, "actor") ? { actor: csv(ctx.query, "actor") } : {}),
1388
+ ...(ctx.query.get("tool") ? { tool: ctx.query.get("tool") } : {}),
1389
+ ...(ctx.query.get("since") ? { since: ctx.query.get("since") } : {}),
1390
+ // `until` has existed in AuditQuery all along with no way to ask for
1391
+ // it, which left the log readable forwards from a point but not
1392
+ // bounded at both ends -- the shape every "what happened during the
1393
+ // incident" question has.
1394
+ ...(ctx.query.get("until") ? { until: ctx.query.get("until") } : {}),
1395
+ ...(ctx.query.get("noteworthy") ? { noteworthy: true } : {})
1396
+ });
1397
+ return { ...page, auditPath: server.auditPath };
1398
+ }),
1399
+ route("GET", "/api/v1/servers/:id/audit/verify", (ctx) => {
1400
+ const server = serverById(options, ctx.params["id"]);
1401
+ /*
1402
+ * `hmcp audit verify --expect-head`: a head recorded earlier, somewhere
1403
+ * the log's owner does not control. The chain alone cannot see its own
1404
+ * end being cut off; this is the check that can.
1405
+ */
1406
+ const expectHead = ctx.query.get("expectHead")?.trim() || undefined;
1407
+ if (expectHead !== undefined && !/^[0-9a-f]{16,128}$/i.test(expectHead)) {
1408
+ throw badRequest("expectHead must be a hash as the log records it");
1409
+ }
1410
+ return verifyAuditLog(server.auditPath, expectHead ? { expectHead } : {});
1411
+ }),
1412
+ /**
1413
+ * Combined view across servers.
1414
+ *
1415
+ * Deduped by audit path, because two servers legitimately share one log by
1416
+ * default. Where a path is shared, records are attributed by `component`
1417
+ * and the ambiguity is reported rather than guessed at.
1418
+ */
1419
+ route("GET", "/api/v1/audit", (ctx) => {
1420
+ const wanted = csv(ctx.query, "servers");
1421
+ const entries = registry(options).servers.filter((s) => !wanted || wanted.includes(s.id));
1422
+ const limit = intParam(ctx.query, "limit") ?? 50;
1423
+ const byPath = new Map();
1424
+ const broken = [];
1425
+ for (const entry of entries) {
1426
+ try {
1427
+ const server = loadServer(entry);
1428
+ const list = byPath.get(server.auditPath) ?? [];
1429
+ list.push(server);
1430
+ byPath.set(server.auditPath, list);
1431
+ }
1432
+ catch (err) {
1433
+ broken.push({ id: entry.id, error: err.message });
1434
+ }
1435
+ }
1436
+ const records = [];
1437
+ for (const [path, servers] of byPath) {
1438
+ const page = queryAuditLog(path, { limit, ...(ctx.query.get("noteworthy") ? { noteworthy: true } : {}) });
1439
+ for (const record of page.records) {
1440
+ const byComponent = servers.find((s) => s.component === record.component);
1441
+ const attribution = byComponent ? "component" : servers.length === 1 ? "path" : "ambiguous";
1442
+ records.push({
1443
+ ...record,
1444
+ serverId: byComponent?.entry.id ?? (servers.length === 1 ? servers[0].entry.id : null),
1445
+ attribution
1446
+ });
1447
+ }
1448
+ }
1449
+ records.sort((a, b) => (a.ts === b.ts ? b.seq - a.seq : a.ts < b.ts ? 1 : -1));
1450
+ // Surfaced so the UI can say why some records are attributed by
1451
+ // component rather than simply by which server was asked for.
1452
+ const sharedPaths = [...byPath.entries()]
1453
+ .filter(([, servers]) => servers.length > 1)
1454
+ .map(([path, servers]) => ({ path, servers: servers.map((s) => s.entry.id) }));
1455
+ return { records: records.slice(0, limit), sharedPaths, broken };
1456
+ })
1457
+ ];
1458
+ }