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
@@ -0,0 +1,513 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { z } from "zod";
3
+ import { AuditLog, LoosenAcknowledgedSchema, MAX_BODY_BYTES, POLICY_FILE_EDIT, POLICY_RULE_ADD, POLICY_RULE_DELETE, POLICY_RULE_ORDER, POLICY_RULE_SET, POLICY_SETTING_PATHS, POLICY_SETTING_RULE, PolicyWriteError, parsePolicySetting, parseRuleInput, policyDigest, previewPolicyFile, previewRulesOp, readRegistry, ruleToYaml, writePolicyFile, writePolicyRules, writePolicySetting } from "hmcp-core";
4
+ import { buildSuggestion, gatewayStatus } from "hmcp-gateway";
5
+ import { badRequest, conflict, notFound, route, unprocessable } from "../http.js";
6
+ import { chooseTenant, loadServer } from "../model/server.js";
7
+ import { toolSurfaceFor } from "../model/tools.js";
8
+ /* ------------------------------------------------------------------ helpers */
9
+ function serverById(options, id) {
10
+ const entry = readRegistry(options.registryPath).servers.find((s) => s.id === id);
11
+ if (!entry)
12
+ throw notFound(`no registered server with id "${id}"`);
13
+ try {
14
+ return loadServer(entry);
15
+ }
16
+ catch (err) {
17
+ throw unprocessable(`server "${id}" could not be loaded: ${err.message}`);
18
+ }
19
+ }
20
+ /** The same tenant rule as every other scoped route in `api.ts`. */
21
+ function scopedRequest(options, id, query) {
22
+ const server = serverById(options, id);
23
+ const choice = chooseTenant(server, query.get("tenant"));
24
+ if (!choice.ok)
25
+ throw unprocessable(choice.why);
26
+ return { server, tenant: choice.tenant, explicit: choice.explicit };
27
+ }
28
+ function auditFor(server, actor) {
29
+ return new AuditLog({ config: server.policy.audit, actor, component: "hmcp-web", cwd: server.cwd });
30
+ }
31
+ function parseBody(schema, body) {
32
+ const result = schema.safeParse(body ?? {});
33
+ if (!result.success) {
34
+ const detail = result.error.issues.map((i) => `${i.path.join(".") || "(body)"}: ${i.message}`).join("; ");
35
+ throw badRequest(`invalid request: ${detail}`);
36
+ }
37
+ return result.data;
38
+ }
39
+ /** The file a write goes to, or the reason there is none. Inline and `policy_writes: false` both stop here. */
40
+ function writableFile(server) {
41
+ if (server.policyFile === null || !server.policyWritable.ok) {
42
+ throw unprocessable(server.policyWritable.why ?? "this gateway's policy cannot be written from here");
43
+ }
44
+ return server.policyFile;
45
+ }
46
+ /**
47
+ * What a live gateway serves, for grading a change tool by tool. Empty when
48
+ * nothing live has reported, which makes core fall back to judging the rules
49
+ * by their shape -- conservatively -- rather than calling an edit harmless
50
+ * because it was compared against no tools at all.
51
+ */
52
+ function liveTools(server, tenant) {
53
+ const surface = toolSurfaceFor(server, tenant);
54
+ return surface.live ? surface.entries.map((t) => ({ name: t.name, effect: t.effect })) : [];
55
+ }
56
+ /** Core's refusals as HTTP. `needs` tells the UI an acknowledgement would lift it. */
57
+ function settle(result) {
58
+ const r = result;
59
+ if (r.kind === "stale")
60
+ throw conflict(r.why);
61
+ if (r.kind === "refused")
62
+ throw unprocessable(r.why, r.needs ? { needs: r.needs } : undefined);
63
+ if (r.ok === false)
64
+ throw r.missing ? notFound(r.why) : unprocessable(r.why);
65
+ return result;
66
+ }
67
+ /**
68
+ * Appends the record for a write that already happened.
69
+ *
70
+ * Not rolled back when the record fails, for the reason `api.ts` gives at the
71
+ * tool-rule route: the file is on disk and may already be adopted, and undoing
72
+ * it would be a second, unaudited write. The failure is reported instead.
73
+ *
74
+ * `decision` says which way the edit moved what policy lets through -- `allow`
75
+ * for a loosening, `deny` otherwise -- so the Activity page's decision filter
76
+ * finds every widening.
77
+ */
78
+ function record(server, actor, tenant, entry) {
79
+ try {
80
+ auditFor(server, actor).appendStrict({
81
+ tool: "(policy)",
82
+ effect: null,
83
+ decision: entry.loosens ? "allow" : "deny",
84
+ tenant: tenant || null,
85
+ rule_id: entry.ruleId,
86
+ reason: entry.reason,
87
+ outcome: "completed",
88
+ args_redacted: { ...entry.args, scope: "all tenants", origin: "console" }
89
+ });
90
+ return null;
91
+ }
92
+ catch (err) {
93
+ return `the change was written but the audit record failed: ${err.message}`;
94
+ }
95
+ }
96
+ /**
97
+ * A line diff in unified hunks, for the file editor's preview. Plain LCS over
98
+ * whatever differs between the common head and tail; a change too large for
99
+ * that is shown as everything removed and everything added, which is still
100
+ * correct, only less helpful.
101
+ *
102
+ * The gateway.yaml editor has its own flat op/line diff (`lineDiff` in
103
+ * model/gateway-config.ts); the two UIs read different shapes, so both stay.
104
+ */
105
+ export function lineDiff(before, after, context = 3) {
106
+ const a = before.split("\n");
107
+ const b = after.split("\n");
108
+ let head = 0;
109
+ while (head < a.length && head < b.length && a[head] === b[head])
110
+ head++;
111
+ let tail = 0;
112
+ while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail])
113
+ tail++;
114
+ const am = a.slice(head, a.length - tail);
115
+ const bm = b.slice(head, b.length - tail);
116
+ const ops = a.slice(0, head).map((line) => ({ op: " ", line }));
117
+ if (am.length * bm.length <= 4_000_000) {
118
+ const n = am.length;
119
+ const m = bm.length;
120
+ const lcs = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
121
+ for (let i = n - 1; i >= 0; i--) {
122
+ for (let j = m - 1; j >= 0; j--) {
123
+ lcs[i][j] = am[i] === bm[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
124
+ }
125
+ }
126
+ let i = 0;
127
+ let j = 0;
128
+ while (i < n || j < m) {
129
+ if (i < n && j < m && am[i] === bm[j]) {
130
+ ops.push({ op: " ", line: am[i] });
131
+ i++;
132
+ j++;
133
+ }
134
+ else if (j < m && (i === n || lcs[i][j + 1] >= lcs[i + 1][j])) {
135
+ ops.push({ op: "+", line: bm[j++] });
136
+ }
137
+ else {
138
+ ops.push({ op: "-", line: am[i++] });
139
+ }
140
+ }
141
+ }
142
+ else {
143
+ ops.push(...am.map((line) => ({ op: "-", line })), ...bm.map((line) => ({ op: "+", line })));
144
+ }
145
+ ops.push(...a.slice(a.length - tail).map((line) => ({ op: " ", line })));
146
+ // Line numbers (1-based) each op starts at, in the old and the new text.
147
+ const oldAt = [];
148
+ const newAt = [];
149
+ let oldLine = 1;
150
+ let newLine = 1;
151
+ for (const o of ops) {
152
+ oldAt.push(oldLine);
153
+ newAt.push(newLine);
154
+ if (o.op !== "+")
155
+ oldLine++;
156
+ if (o.op !== "-")
157
+ newLine++;
158
+ }
159
+ // Changes closer than two contexts apart share a hunk.
160
+ const changed = ops.flatMap((o, i) => (o.op === " " ? [] : [i]));
161
+ const hunks = [];
162
+ let k = 0;
163
+ while (k < changed.length) {
164
+ let end = k;
165
+ while (end + 1 < changed.length && changed[end + 1] - changed[end] <= context * 2)
166
+ end++;
167
+ const from = Math.max(0, changed[k] - context);
168
+ const to = Math.min(ops.length - 1, changed[end] + context);
169
+ hunks.push({
170
+ oldStart: oldAt[from],
171
+ newStart: newAt[from],
172
+ lines: ops.slice(from, to + 1).map((o) => `${o.op}${o.line}`)
173
+ });
174
+ k = end + 1;
175
+ }
176
+ return hunks;
177
+ }
178
+ /* ------------------------------------------------------------------- bodies */
179
+ const Digest = z.string().min(1).max(200);
180
+ const Ack = LoosenAcknowledgedSchema.optional();
181
+ const RuleId = z.string().min(1).max(200);
182
+ const Order = z.array(RuleId).max(2000);
183
+ const SettingBody = z
184
+ .object({ path: z.string().min(1).max(100), value: z.unknown(), expectedDigest: Digest, acknowledged: Ack })
185
+ .strict();
186
+ const SetRuleBody = z.object({ rule: z.unknown(), expectedDigest: Digest, acknowledged: Ack }).strict();
187
+ const AddRuleBody = z
188
+ .object({ rule: z.unknown(), index: z.number().int().min(0).optional(), expectedDigest: Digest, acknowledged: Ack })
189
+ .strict();
190
+ const OrderBody = z.object({ order: Order, expectedDigest: Digest, acknowledged: Ack }).strict();
191
+ const PreviewRulesBody = z.discriminatedUnion("op", [
192
+ z.object({ op: z.literal("set"), ruleId: RuleId, rule: z.unknown() }).strict(),
193
+ z.object({ op: z.literal("add"), rule: z.unknown(), index: z.number().int().min(0).optional() }).strict(),
194
+ z.object({ op: z.literal("delete"), ruleId: RuleId }).strict(),
195
+ z.object({ op: z.literal("order"), order: Order }).strict()
196
+ ]);
197
+ const FileText = z.string().max(MAX_BODY_BYTES);
198
+ const FilePreviewBody = z.object({ text: FileText }).strict();
199
+ const FileBody = z.object({ text: FileText, expectedDigest: Digest, acknowledged: Ack }).strict();
200
+ /** A rule from the browser, validated by the policy's own schema. Refusals are 422. */
201
+ function ruleFrom(input, existing) {
202
+ try {
203
+ return parseRuleInput(input, existing);
204
+ }
205
+ catch (err) {
206
+ if (err instanceof PolicyWriteError)
207
+ throw unprocessable(err.message);
208
+ throw err;
209
+ }
210
+ }
211
+ /* ------------------------------------------------------------------- routes */
212
+ export function policyRoutes(options) {
213
+ /** Shared by the four rule writes: preview, write, audit, answer. */
214
+ const writeRules = (ctx, op, expectedDigest, acknowledged, auditId) => {
215
+ const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
216
+ const policyPath = writableFile(server);
217
+ const result = settle(writePolicyRules({
218
+ policyPath,
219
+ op,
220
+ expectedDigest,
221
+ tools: liveTools(server, tenant),
222
+ writesAllowed: true,
223
+ overridesAllowed: server.policyOverrides,
224
+ acknowledged
225
+ }));
226
+ const ruleId = op.kind === "order" ? null : op.kind === "add" ? op.rule.id : op.ruleId;
227
+ const rule = op.kind === "set" || op.kind === "add" ? result.rules.find((r) => r.id === ruleId) ?? null : null;
228
+ const what = op.kind === "order"
229
+ ? `rules reordered to ${op.order.join(", ")}`
230
+ : op.kind === "delete"
231
+ ? `rule "${ruleId}" removed`
232
+ : op.kind === "add"
233
+ ? `rule "${ruleId}" added at position ${result.rules.findIndex((r) => r.id === ruleId)}`
234
+ : `rule "${ruleId}" rewritten`;
235
+ const warning = record(server, ctx.actor, tenant, {
236
+ ruleId: auditId,
237
+ loosens: result.loosens,
238
+ reason: `${what} in ${policyPath} via the console by ${ctx.actor}` +
239
+ (result.loosens ? `; acknowledged as loosening: ${result.loosenReasons.join("; ")}` : ""),
240
+ args: {
241
+ op: op.kind,
242
+ rule_id: ruleId,
243
+ rule,
244
+ /* The rule as it was: the only way the log can restore a change. */
245
+ previous: result.previous,
246
+ order: op.kind === "order" ? op.order : null,
247
+ changes: result.changes,
248
+ loosens: result.loosens,
249
+ acknowledged: acknowledged ?? null,
250
+ policy_digest_before: result.previousDigest,
251
+ policy_digest_after: result.digest
252
+ }
253
+ });
254
+ return {
255
+ op: op.kind,
256
+ ruleId,
257
+ rule,
258
+ yaml: rule ? ruleToYaml(rule) : null,
259
+ previous: result.previous,
260
+ rules: result.rules,
261
+ changes: result.changes,
262
+ loosens: result.loosens,
263
+ loosenReasons: result.loosenReasons,
264
+ digest: result.digest,
265
+ previousDigest: result.previousDigest,
266
+ policyPath,
267
+ warning,
268
+ tenant,
269
+ explicitTenant: explicit
270
+ };
271
+ };
272
+ return [
273
+ /**
274
+ * One policy setting. The path must be in core's allow-list and the value
275
+ * must pass that path's own schema; a loosening needs
276
+ * `acknowledged.loosens` and is refused outright under
277
+ * `policy_overrides: false`.
278
+ */
279
+ route("PUT", "/api/v1/servers/:id/policy/setting", (ctx) => {
280
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
281
+ const body = parseBody(SettingBody, ctx.body);
282
+ try {
283
+ parsePolicySetting(body.path, body.value);
284
+ }
285
+ catch (err) {
286
+ throw badRequest(err.message, { paths: POLICY_SETTING_PATHS });
287
+ }
288
+ const policyPath = writableFile(server);
289
+ const result = settle(writePolicySetting({
290
+ policyPath,
291
+ path: body.path,
292
+ value: body.value,
293
+ expectedDigest: body.expectedDigest,
294
+ writesAllowed: true,
295
+ overridesAllowed: server.policyOverrides,
296
+ acknowledged: body.acknowledged
297
+ }));
298
+ const warning = record(server, ctx.actor, tenant, {
299
+ ruleId: POLICY_SETTING_RULE,
300
+ loosens: result.loosens,
301
+ reason: `${result.path} changed from ${JSON.stringify(result.before)} to ${JSON.stringify(result.after)} ` +
302
+ `in ${policyPath} via the console by ${ctx.actor}` +
303
+ (result.loosens ? " (acknowledged as loosening)" : ""),
304
+ args: {
305
+ path: result.path,
306
+ before: result.before,
307
+ after: result.after,
308
+ loosens: result.loosens,
309
+ acknowledged: body.acknowledged ?? null,
310
+ policy_digest_before: result.previousDigest,
311
+ policy_digest_after: result.digest
312
+ }
313
+ });
314
+ return {
315
+ path: result.path,
316
+ before: result.before,
317
+ after: result.after,
318
+ loosens: result.loosens,
319
+ digest: result.digest,
320
+ previousDigest: result.previousDigest,
321
+ policyPath,
322
+ warning
323
+ };
324
+ }),
325
+ /** What a rule edit would do to every live tool. Writes nothing. */
326
+ route("POST", "/api/v1/servers/:id/policy/rules/preview", (ctx) => {
327
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
328
+ const body = parseBody(PreviewRulesBody, ctx.body);
329
+ const policy = server.policy;
330
+ let op;
331
+ switch (body.op) {
332
+ case "set":
333
+ op = { kind: "set", ruleId: body.ruleId, rule: ruleFrom(body.rule, policy.rules.find((r) => r.id === body.ruleId)) };
334
+ break;
335
+ case "add":
336
+ op = { kind: "add", rule: ruleFrom(body.rule), index: body.index };
337
+ break;
338
+ case "delete":
339
+ op = { kind: "delete", ruleId: body.ruleId };
340
+ break;
341
+ case "order":
342
+ op = { kind: "order", order: body.order };
343
+ break;
344
+ }
345
+ const preview = settle(previewRulesOp(policy, op, liveTools(server, tenant)));
346
+ const rule = op.kind === "set" || op.kind === "add" ? op.rule : null;
347
+ return {
348
+ op: op.kind,
349
+ rule,
350
+ yaml: rule ? ruleToYaml(rule) : null,
351
+ previous: preview.previous,
352
+ rules: preview.rules,
353
+ changes: preview.changes,
354
+ loosens: preview.loosens,
355
+ loosenReasons: preview.loosenReasons,
356
+ expectedDigest: policyDigest(policy),
357
+ writable: server.policyWritable,
358
+ overridesAllowed: server.policyOverrides
359
+ };
360
+ }),
361
+ route("PUT", "/api/v1/servers/:id/policy/rules/:ruleId", (ctx) => {
362
+ const body = parseBody(SetRuleBody, ctx.body);
363
+ const ruleId = ctx.params["ruleId"];
364
+ const { server } = scopedRequest(options, ctx.params["id"], ctx.query);
365
+ const rule = ruleFrom(body.rule, server.policy.rules.find((r) => r.id === ruleId));
366
+ return writeRules(ctx, { kind: "set", ruleId, rule }, body.expectedDigest, body.acknowledged, POLICY_RULE_SET);
367
+ }),
368
+ route("POST", "/api/v1/servers/:id/policy/rules", (ctx) => {
369
+ const body = parseBody(AddRuleBody, ctx.body);
370
+ const rule = ruleFrom(body.rule);
371
+ return writeRules(ctx, { kind: "add", rule, index: body.index }, body.expectedDigest, body.acknowledged, POLICY_RULE_ADD);
372
+ }),
373
+ /** `?expectedDigest=…`, and `&acknowledged=loosens` when the preview said it loosens. */
374
+ route("DELETE", "/api/v1/servers/:id/policy/rules/:ruleId", (ctx) => {
375
+ const expectedDigest = ctx.query.get("expectedDigest") ?? "";
376
+ if (!expectedDigest)
377
+ throw badRequest("expectedDigest is required");
378
+ const acknowledged = ctx.query.get("acknowledged") === "loosens" ? { loosens: true } : undefined;
379
+ return writeRules(ctx, { kind: "delete", ruleId: ctx.params["ruleId"] }, expectedDigest, acknowledged, POLICY_RULE_DELETE);
380
+ }),
381
+ route("POST", "/api/v1/servers/:id/policy/rules/order", (ctx) => {
382
+ const body = parseBody(OrderBody, ctx.body);
383
+ return writeRules(ctx, { kind: "order", order: body.order }, body.expectedDigest, body.acknowledged, POLICY_RULE_ORDER);
384
+ }),
385
+ /** The policy file as text, with the digest an edit must be given back. */
386
+ route("GET", "/api/v1/servers/:id/policy/file", (ctx) => {
387
+ const { server } = scopedRequest(options, ctx.params["id"], ctx.query);
388
+ let text = null;
389
+ let readError = null;
390
+ if (server.policyFile !== null) {
391
+ try {
392
+ text = readFileSync(server.policyFile, "utf8");
393
+ }
394
+ catch (err) {
395
+ readError = err.message;
396
+ }
397
+ }
398
+ return {
399
+ path: server.policyFile,
400
+ text,
401
+ readError,
402
+ digest: policyDigest(server.policy),
403
+ writable: server.policyWritable,
404
+ overridesAllowed: server.policyOverrides
405
+ };
406
+ }),
407
+ /**
408
+ * What replacing the file with `text` would do. Invalid YAML and an
409
+ * invalid policy come back as `valid: false` with the reason, not as an
410
+ * error, because the editor shows them beside the text.
411
+ */
412
+ route("POST", "/api/v1/servers/:id/policy/file/preview", (ctx) => {
413
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
414
+ const body = parseBody(FilePreviewBody, ctx.body);
415
+ let current = "";
416
+ if (server.policyFile !== null) {
417
+ try {
418
+ current = readFileSync(server.policyFile, "utf8");
419
+ }
420
+ catch {
421
+ current = "";
422
+ }
423
+ }
424
+ const preview = previewPolicyFile(server.policy, body.text, liveTools(server, tenant));
425
+ return {
426
+ valid: preview.valid,
427
+ error: preview.error,
428
+ diff: lineDiff(current, body.text),
429
+ changes: preview.changes,
430
+ loosens: preview.loosens,
431
+ loosenReasons: preview.loosenReasons,
432
+ expectedDigest: policyDigest(server.policy),
433
+ writable: server.policyWritable,
434
+ overridesAllowed: server.policyOverrides
435
+ };
436
+ }),
437
+ route("PUT", "/api/v1/servers/:id/policy/file", (ctx) => {
438
+ const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
439
+ const body = parseBody(FileBody, ctx.body);
440
+ const policyPath = writableFile(server);
441
+ let current = "";
442
+ try {
443
+ current = readFileSync(policyPath, "utf8");
444
+ }
445
+ catch {
446
+ current = "";
447
+ }
448
+ const result = settle(writePolicyFile({
449
+ policyPath,
450
+ text: body.text,
451
+ expectedDigest: body.expectedDigest,
452
+ tools: liveTools(server, tenant),
453
+ writesAllowed: true,
454
+ overridesAllowed: server.policyOverrides,
455
+ acknowledged: body.acknowledged
456
+ }));
457
+ const diff = lineDiff(current, body.text);
458
+ const warning = record(server, ctx.actor, tenant, {
459
+ ruleId: POLICY_FILE_EDIT,
460
+ loosens: result.loosens,
461
+ reason: `${policyPath} edited as text via the console by ${ctx.actor}` +
462
+ (result.loosens ? `; acknowledged as loosening: ${result.loosenReasons.join("; ")}` : ""),
463
+ args: {
464
+ /* The changed lines, capped: enough to see and to undo an ordinary edit. */
465
+ diff: diff.flatMap((h) => h.lines.filter((l) => !l.startsWith(" "))).slice(0, 200),
466
+ changes: result.changes,
467
+ loosens: result.loosens,
468
+ acknowledged: body.acknowledged ?? null,
469
+ policy_digest_before: result.previousDigest,
470
+ policy_digest_after: result.digest
471
+ }
472
+ });
473
+ return {
474
+ digest: result.digest,
475
+ previousDigest: result.previousDigest,
476
+ diff,
477
+ changes: result.changes,
478
+ loosens: result.loosens,
479
+ loosenReasons: result.loosenReasons,
480
+ policyPath,
481
+ warning
482
+ };
483
+ }),
484
+ /**
485
+ * What watch-only mode saw, and the bounded rules that would fit it --
486
+ * `hmcp-gateway suggest`. It only proposes: applying a suggestion goes
487
+ * through the rule writers above, with their preview and acknowledgement.
488
+ */
489
+ route("GET", "/api/v1/servers/:id/suggestions", (ctx) => {
490
+ const server = serverById(options, ctx.params["id"]);
491
+ const since = ctx.query.get("since") || undefined;
492
+ if (since !== undefined && Number.isNaN(Date.parse(since))) {
493
+ throw badRequest("since must be an ISO date or timestamp");
494
+ }
495
+ try {
496
+ return buildSuggestion(server.policyPath, since);
497
+ }
498
+ catch (err) {
499
+ throw unprocessable(`could not read what this gateway observed: ${err.message}`);
500
+ }
501
+ }),
502
+ /** `hmcp-gateway status`: is it running, on which policy, and what it has done lately. */
503
+ route("GET", "/api/v1/servers/:id/status", (ctx) => {
504
+ const server = serverById(options, ctx.params["id"]);
505
+ try {
506
+ return gatewayStatus(server.policyPath);
507
+ }
508
+ catch (err) {
509
+ throw unprocessable(`could not read this gateway's status: ${err.message}`);
510
+ }
511
+ })
512
+ ];
513
+ }
@@ -0,0 +1,12 @@
1
+ import type { ApiOptions } from "../api.js";
2
+ import { type Route } from "../http.js";
3
+ import { type LoadedServer } from "../model/server.js";
4
+ import { type ApplyState, type CommitResult } from "../model/gateway-config.js";
5
+ /** What a write just did to what is running. See `applyStateFor`. */
6
+ export declare function applyStateAfter(options: ApiOptions, id: string, result: CommitResult): ApplyState;
7
+ /** Takes the ready-made rules written for a removed server out of policy.yaml, and says what happened. */
8
+ export declare function removeServerRules(server: LoadedServer, name: string): {
9
+ removed: string[];
10
+ note: string | null;
11
+ };
12
+ export declare function runtimeRoutes(options: ApiOptions): Route[];