@agent-custody/receipts 0.8.0 → 0.10.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.
package/dist/cli.js CHANGED
@@ -23,12 +23,37 @@ import { CheckpointPublisher, fileResolver } from "./log-sink.js";
23
23
  import { createRequire } from "node:module";
24
24
  import { pruneLog } from "./retention.js";
25
25
  import { serveSidecar } from "./sidecar.js";
26
+ import { checkConfig, formatFindings } from "./check.js";
27
+ import { serveConsole } from "./console.js";
26
28
  import { TREEHEAD_TYPE } from "./receipt.js";
27
29
  import { MerkleLog } from "./log.js";
28
30
  import { createSdkIssuer } from "./sdk/index.js";
29
31
  import { handleHookEvent } from "./sdk/claude.js";
30
32
  import { auditExtends, formatReport, verifyBundle } from "./verify.js";
31
33
  import { formatSimulation, simulatePolicy, verifyOrphanAuthorization } from "./simulate.js";
34
+ /**
35
+ * Resolves on SIGINT or SIGTERM: a container runtime and systemd stop a service with SIGTERM, which PID 1 ignores unless
36
+ * it is handled. The handlers are installed once, before a service starts, so a signal that arrives while it starts up
37
+ * is kept and the service closes as soon as it is running.
38
+ */
39
+ let stopped;
40
+ function untilStopped() {
41
+ stopped ??= new Promise((resolve) => {
42
+ process.once("SIGINT", resolve);
43
+ process.once("SIGTERM", resolve);
44
+ });
45
+ return stopped;
46
+ }
47
+ const SERVICES = new Set(["serve", "witness", "signer", "portal", "log", "console"]);
48
+ /** a command that waits for untilStopped(); a stdio gateway runs until its input closes and keeps the default signal behaviour */
49
+ const runsUntilStopped = (cmd, args) => !!cmd && (SERVICES.has(cmd) || (cmd === "gateway" && (args.includes("--http") || args.includes("--a2a"))));
50
+ /** A secret kept in a file that only this process can read, such as a container secret mounted at /run/secrets. The file's path is not a secret; its contents are. */
51
+ function tokenFromFile(path) {
52
+ const v = readFileSync(path, "utf8").trim();
53
+ if (!v)
54
+ throw new Error(`${path} is empty`);
55
+ return v;
56
+ }
32
57
  /** A shared secret from an environment variable; never from the command line, where it would land in shell history. */
33
58
  function secretFrom(envName) {
34
59
  const v = process.env[envName];
@@ -48,6 +73,14 @@ const USAGE = `agent-custody <command>
48
73
  revoke --config <gateway.json> --grant <grant.json> revokes a grant: its digest goes into the config's revokedGrants file, every
49
74
  session under it or under a grant delegated from it refuses its next call, and no new session opens for them
50
75
  reconcile --config <gateway.json> --operation <uuid> operator-only provider lookup; commits a receipt before closing an unknown/pending financial operation
76
+ console --config <gateway.json> [--port 8795] [--host 127.0.0.1] [--token-env CONSOLE_TOKEN | --token-file <path>] [--gateway-url <url>] [--state-dir <dir>]
77
+ the admin console for a gateway: its config and tools, a config check, receipts with a verdict each, a policy editor that
78
+ validates and replays recorded calls before it saves, grant inspection and revocation, and an audit trail of its own changes.
79
+ A separate service from the gateway, behind a token read from the environment; it holds no principal key and never signs
80
+ check --config <gateway.json> [--connect] [--json]
81
+ what the gateway would fail on at startup, found before it starts: the config and its unknown keys, the keys,
82
+ the Cedar policy, the grant, credential variables, stdio commands, and writable paths. --connect also starts the
83
+ upstreams (tool-name collisions, unreachable servers) and checks every tool name the config and grant mention. Exits 1 on an error
51
84
  gateway --config <gateway.json> [--http [--port 8790] [--host 127.0.0.1] [--idle-minutes 30]]
52
85
  stdio: one gateway for the grant the config names. --http: one shared gateway, MCP over
53
86
  Streamable HTTP at /mcp, each connection presenting its own grant as Authorization: Bearer
@@ -87,6 +120,10 @@ const USAGE = `agent-custody <command>
87
120
  log-admin --db-env NAME tenant add <id> [--log-id <id>] | tenant list | tenant disable <id> | tenant plan <id> <free|team|enterprise>
88
121
  log-admin --db-env NAME token add <tenant> --label <text> | token list <tenant> | token revoke <tenant> <hash-prefix>
89
122
  log-admin --db-env NAME audit [--tenant <id>] who did what to tenants and tokens, newest first
123
+ log-admin --db-env NAME sso set <tenant> --domains a.com,b.com [--default-role readonly] [--enforce]
124
+ (--oidc-issuer <url> --oidc-client-id <id> --oidc-secret-env NAME | --saml-entry-point <url> --saml-cert <pem file> [--saml-idp-issuer <id>])
125
+ log-admin --db-env NAME sso show <tenant> | sso remove <tenant> enterprise sign-in through the tenant's own identity provider
126
+ log-admin --db-env NAME user mfa-reset <email> turns MFA off for a portal account that lost its authenticator
90
127
  portal --db-env NAME --secret-env NAME --public-url <log url> [--checkpoints-url <url>] [--portal-url <url>] [--port 8792] [--host 127.0.0.1]
91
128
  [--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]
92
129
  the tenant portal: register, first key, usage against plan, keys, billing, export
@@ -132,6 +169,8 @@ function loadTenants(path) {
132
169
  }
133
170
  async function main(argv) {
134
171
  const [cmd, ...rest] = argv;
172
+ if (runsUntilStopped(cmd, rest))
173
+ void untilStopped();
135
174
  switch (cmd) {
136
175
  case "reconcile": {
137
176
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, operation: { type: "string" } } });
@@ -203,6 +242,24 @@ async function main(argv) {
203
242
  console.log(`delegated to ${chain.agent}: scopes [${chain.scopes.join(", ")}] until ${chain.expiresAt}, under ${decodeDelegation(parent).agent}'s grant from ${chain.principal}`);
204
243
  return 0;
205
244
  }
245
+ case "console": {
246
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, port: { type: "string", default: "8795" }, host: { type: "string", default: "127.0.0.1" }, "token-env": { type: "string", default: "CONSOLE_TOKEN" }, "token-file": { type: "string" }, "gateway-url": { type: "string" }, "state-dir": { type: "string" } } });
247
+ if (!values.config)
248
+ throw new Error("console needs --config");
249
+ const running = await serveConsole({ configFile: values.config, token: values["token-file"] ? tokenFromFile(values["token-file"]) : secretFrom(values["token-env"]), port: Number(values.port), host: values.host, ...(values["gateway-url"] ? { gatewayUrl: values["gateway-url"] } : {}), ...(values["state-dir"] ? { stateDir: values["state-dir"] } : {}) });
250
+ console.error(`agent-custody console: ${running.url} config=${values.config}${values.host === "0.0.0.0" || (values.host !== "127.0.0.1" && values.host !== "localhost") ? " (reachable beyond this host: put TLS in front and limit who can reach it)" : ""}`);
251
+ await untilStopped();
252
+ await running.close();
253
+ return 0;
254
+ }
255
+ case "check": {
256
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, connect: { type: "boolean", default: false }, json: { type: "boolean", default: false } } });
257
+ if (!values.config)
258
+ throw new Error("check needs --config");
259
+ const findings = await checkConfig(values.config, { connect: values.connect });
260
+ console.log(values.json ? JSON.stringify(findings, null, 2) : formatFindings(findings));
261
+ return findings.some((f) => f.level === "error") ? 1 : 0;
262
+ }
206
263
  case "revoke": {
207
264
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, grant: { type: "string" } } });
208
265
  if (!values.config || !values.grant)
@@ -233,25 +290,25 @@ async function main(argv) {
233
290
  if (candidates.length !== 1)
234
291
  throw new Error("gateway --a2a needs exactly one { a2a: ... } upstream in the config");
235
292
  const a2a = candidates[0].a2a;
236
- const host = await createGatewayHost(cfg);
293
+ const host = await createGatewayHost(cfg, { autoFlush: true });
237
294
  const grant = cfg.grantFile ? JSON.parse(readFileSync(cfg.grantFile, "utf8")) : undefined;
238
295
  const running = await serveA2a(host, a2a, { port: Number(values.port), host: values.host, ...(grant ? { grant } : {}) });
239
296
  console.error(`agent-custody gateway (a2a): ${running.url} keyid=${host.keyid} fronting ${a2a.url} as ${a2a.prefix}.send; card at ${running.url}/.well-known/agent-card.json`);
240
- await new Promise((resolve) => process.once("SIGINT", resolve));
297
+ await untilStopped();
241
298
  await running.close();
242
299
  await host.close();
243
300
  return 0;
244
301
  }
245
302
  if (values.http) {
246
- const host = await createGatewayHost(loadConfig(values.config));
303
+ const host = await createGatewayHost(loadConfig(values.config), { autoFlush: true });
247
304
  const running = await serveHttp(host, { port: Number(values.port), host: values.host, idleMs: Number(values["idle-minutes"]) * 60_000 });
248
305
  console.error(`agent-custody gateway: ${running.url} keyid=${host.keyid} one session per grant; GET /health`);
249
- await new Promise((resolve) => process.once("SIGINT", resolve));
306
+ await untilStopped();
250
307
  await running.close();
251
308
  await host.close();
252
309
  return 0;
253
310
  }
254
- const gw = await createGateway(loadConfig(values.config));
311
+ const gw = await createGateway(loadConfig(values.config), { autoFlush: true });
255
312
  console.error(`agent-custody gateway: agent=${gw.agentId} principal=${gw.delegation.principal} scopes=[${gw.delegation.scopes.join(", ")}]`);
256
313
  await serveStdio(gw);
257
314
  await gw.close();
@@ -274,7 +331,7 @@ async function main(argv) {
274
331
  const issuer = createSdkIssuer(loadSdkConfig(values.config));
275
332
  const running = await serveSidecar(issuer, { port: Number(values.port), host: values.host });
276
333
  console.error(`agent-custody serve: ${running.url} agent=${issuer.agentId} keyid=${issuer.keyid} log=${issuer.log.kind}:${issuer.log.where}`);
277
- await new Promise((resolve) => process.once("SIGINT", resolve));
334
+ await untilStopped();
278
335
  await running.close();
279
336
  return 0;
280
337
  }
@@ -313,7 +370,7 @@ async function main(argv) {
313
370
  }
314
371
  console.error(`agent-custody witness: keyid=${w.keyid} watching ${values["log-url"]} via ${values["checkpoints-url"]} every ${values.every}s, writing to ${values.out}`);
315
372
  w.start(everyMs);
316
- await new Promise((resolve) => process.once("SIGINT", resolve));
373
+ await untilStopped();
317
374
  w.stop();
318
375
  return 0;
319
376
  }
@@ -327,7 +384,7 @@ async function main(argv) {
327
384
  const kp = loadPrivateKey(values.key);
328
385
  const running = await serveSigner(kp, { port: Number(values.port), host: values.host, ...(token ? { token } : {}), retired: (values["retired-key"] ?? []).map(retiredKey) });
329
386
  console.error(`agent-custody signer: ${running.url} keyid=${kp.keyid} ${token ? "token required" : "open: bind this to a private network"}${values["retired-key"]?.length ? ` retired=${values["retired-key"].length}` : ""}`);
330
- await new Promise((resolve) => process.once("SIGINT", resolve));
387
+ await untilStopped();
331
388
  await running.close();
332
389
  return 0;
333
390
  }
@@ -395,12 +452,12 @@ async function main(argv) {
395
452
  }
396
453
  const running = await servePortal({ tenancy, client, secret, publicUrl: values["public-url"], ...(values["checkpoints-url"] ? { checkpointsUrl: values["checkpoints-url"] } : {}), ...(values["portal-url"] ? { portalUrl: values["portal-url"] } : {}), ...(keyid ? { keyid } : {}), ...(stripe ? { stripe } : {}), ...(mail ? { mail } : {}), ...(oauth ? { oauth } : {}), trustProxy: values["trust-proxy"] }, { port: Number(values.port), host: values.host });
397
454
  console.error(`agent-custody portal: ${running.url} log=${values["public-url"]} billing=${stripe ? "stripe" : "off"}${values["trust-proxy"] ? " trust-proxy" : ""}`);
398
- await new Promise((resolve) => process.once("SIGINT", resolve));
455
+ await untilStopped();
399
456
  await running.close();
400
457
  return 0;
401
458
  }
402
459
  case "log-admin": {
403
- const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { "db-env": { type: "string" }, "log-id": { type: "string" }, label: { type: "string" }, file: { type: "string" }, tenant: { type: "string", default: "default" } } });
460
+ const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { "db-env": { type: "string" }, "log-id": { type: "string" }, label: { type: "string" }, file: { type: "string" }, tenant: { type: "string", default: "default" }, domains: { type: "string" }, "default-role": { type: "string", default: "readonly" }, enforce: { type: "boolean", default: false }, "oidc-issuer": { type: "string" }, "oidc-client-id": { type: "string" }, "oidc-secret-env": { type: "string" }, "saml-entry-point": { type: "string" }, "saml-cert": { type: "string" }, "saml-idp-issuer": { type: "string" } } });
404
461
  if (!values["db-env"])
405
462
  throw new Error("log-admin needs --db-env NAME");
406
463
  const tenancy = new PostgresTenancy(openPostgres(values["db-env"]));
@@ -436,6 +493,55 @@ async function main(argv) {
436
493
  else if (what === "token" && verb === "revoke" && args[0] && args[1]) {
437
494
  console.log(`revoked ${await tenancy.revokeToken(args[0], args[1], actor)} token(s)`);
438
495
  }
496
+ else if (what === "sso" && verb === "set" && args[0]) {
497
+ if (!(await tenancy.tenant(args[0])))
498
+ throw new Error(`unknown tenant ${args[0]}; add it first`);
499
+ if (!values.domains)
500
+ throw new Error("sso set needs --domains");
501
+ let config;
502
+ if (values["oidc-issuer"]) {
503
+ if (!values["oidc-client-id"] || !values["oidc-secret-env"])
504
+ throw new Error("OIDC needs --oidc-issuer, --oidc-client-id, and --oidc-secret-env");
505
+ const clientSecret = process.env[values["oidc-secret-env"]];
506
+ if (!clientSecret)
507
+ throw new Error(`environment variable ${values["oidc-secret-env"]} is not set`);
508
+ config = { issuer: values["oidc-issuer"], clientId: values["oidc-client-id"], clientSecret };
509
+ }
510
+ else if (values["saml-entry-point"] && values["saml-cert"]) {
511
+ config = { entryPoint: values["saml-entry-point"], idpCert: readFileSync(values["saml-cert"], "utf8"), ...(values["saml-idp-issuer"] ? { idpIssuer: values["saml-idp-issuer"] } : {}) };
512
+ }
513
+ else {
514
+ throw new Error("sso set needs the OIDC flags or --saml-entry-point with --saml-cert");
515
+ }
516
+ const domains = values.domains.split(",");
517
+ const protocol = "issuer" in config ? "oidc" : "saml";
518
+ await new PortalStore(openPostgres(values["db-env"])).setSso({ tenant: args[0], protocol, config, domains, defaultRole: values["default-role"], enforced: values.enforce });
519
+ await tenancy.record(actor, "sso.set", args[0], { protocol, ...("issuer" in config ? { issuer: config.issuer } : { entryPoint: config.entryPoint }), domains, defaultRole: values["default-role"], enforced: values.enforce });
520
+ console.log(`single sign-on set for ${args[0]}: ${domains.join(", ")}${values.enforce ? " (enforced)" : ""}`);
521
+ }
522
+ else if (what === "sso" && verb === "show" && args[0]) {
523
+ const s = await new PortalStore(openPostgres(values["db-env"])).ssoOf(args[0]);
524
+ if (!s)
525
+ throw new Error(`no single sign-on for ${args[0]}`);
526
+ const c = s.config;
527
+ console.log([`protocol ${s.protocol}`, ...(c.issuer ? [`issuer ${c.issuer}`, `client id ${c.clientId}`, "client secret set"] : [`entry point ${c.entryPoint}`, `idp issuer ${c.idpIssuer ?? "(not pinned)"}`, "idp cert set"]), `domains ${s.domains.join(", ")}`, `default role ${s.defaultRole}`, `enforced ${s.enforced}`].join("\n"));
528
+ }
529
+ else if (what === "sso" && verb === "remove" && args[0]) {
530
+ const removed = await new PortalStore(openPostgres(values["db-env"])).removeSso(args[0]);
531
+ if (removed)
532
+ await tenancy.record(actor, "sso.remove", args[0], {});
533
+ console.log(`${removed ? "removed" : "there was no"} single sign-on for ${args[0]}`);
534
+ }
535
+ else if (what === "user" && verb === "mfa-reset" && args[0]) {
536
+ const portal = new PortalStore(openPostgres(values["db-env"]));
537
+ const email = args[0].trim().toLowerCase();
538
+ const member = await portal.userByEmail(email);
539
+ if (!member)
540
+ throw new Error(`no portal account with the address ${args[0]}`);
541
+ await portal.resetMfa(email);
542
+ await tenancy.record(actor, "user.mfa-reset", await portal.tenantOf(member.id), { email });
543
+ console.log(`MFA reset for ${args[0]}`);
544
+ }
439
545
  else if (what === "audit") {
440
546
  for (const e of await tenancy.audit({ ...(values.tenant !== "default" ? { tenant: values.tenant } : {}), limit: 100 }))
441
547
  console.log(`${e.at} ${e.actor.padEnd(40)} ${e.action.padEnd(14)} ${(e.tenantId ?? "").padEnd(20)} ${Object.entries(e.detail).map(([k, v]) => `${k}=${v}`).join(" ")}`);
@@ -526,7 +632,7 @@ async function main(argv) {
526
632
  const publisher = checkpoints ? new CheckpointPublisher(resolver, signer, checkpoints, everyMs, undefined, heartbeatMs) : null;
527
633
  publisher?.start();
528
634
  console.error(`agent-custody log: ${running.url} keyid=${signer.keyid} ${values["signer-url"] ? `signer=${values["signer-url"]} ` : ""}${where}${checkpoints ? ` checkpoints every ${values["checkpoint-every"]}s${values["checkpoint-dir"] ? ` to ${values["checkpoint-dir"]}` : ""}` : ""}${admin ? " admin page at /admin" : ""}`);
529
- await new Promise((resolve) => process.once("SIGINT", resolve));
635
+ await untilStopped();
530
636
  publisher?.stop();
531
637
  await running.close();
532
638
  return 0;
@@ -651,6 +757,8 @@ async function main(argv) {
651
757
  const failures = result.checks.filter((check) => !check.ok).map((check) => `${check.name}${check.detail ? ` (${check.detail})` : ""}`);
652
758
  throw new Error(`receipt verification failed: ${failures.join("; ")}`);
653
759
  }
760
+ if (`${result.statement.predicate.receiptId}.json` !== name)
761
+ throw new Error("the file name does not match the receipt id");
654
762
  yield result.statement.predicate;
655
763
  }
656
764
  catch (error) {
package/dist/config.d.ts CHANGED
@@ -249,6 +249,7 @@ export declare const GatewayConfigSchema: z.ZodObject<{
249
249
  optional: z.ZodDefault<z.ZodBoolean>;
250
250
  }, z.core.$strip>>>;
251
251
  precommit: z.ZodDefault<z.ZodArray<z.ZodString>>;
252
+ requirePrecommit: z.ZodOptional<z.ZodBoolean>;
252
253
  approvals: z.ZodOptional<z.ZodObject<{
253
254
  trustedKeys: z.ZodArray<z.ZodString>;
254
255
  usedDir: z.ZodString;
package/dist/config.js CHANGED
@@ -143,6 +143,8 @@ export const GatewayConfigSchema = z.object({
143
143
  * authorization to the log and refuses the call if the log will not take it. Evidence then precedes the side effect.
144
144
  */
145
145
  precommit: z.array(z.string().min(1)).default([]),
146
+ /** with a remote log, refuse to start when precommit is empty; without it the gateway only warns */
147
+ requirePrecommit: z.boolean().optional(),
146
148
  /** Tools that require a signed, unexpired, single-use approval, in every mode; "*" covers all agent calls. */
147
149
  approvals: ApprovalsSchema.optional(),
148
150
  /** Durable idempotency, daily budget reservations, and provider reconciliation for financial operations. */
@@ -169,6 +171,7 @@ export const GatewayConfigSchema = z.object({
169
171
  // a key fetched from the log itself proves nothing about a log that is dishonest from the start, so a remote log that
170
172
  // gates consequential calls must have its keys pinned in the config (issue #99)
171
173
  .refine((c) => !c.log || (!c.precommit.length && !c.operations) || !!c.log.keys?.length, { message: "precommit with a remote log needs log.keys: the log's public key files, pinned, to check its answer before a consequential call is forwarded" })
174
+ .refine((c) => !c.requirePrecommit || !c.log || c.precommit.length > 0, { message: "requirePrecommit is set and precommit is empty: name the consequential tools in precommit, or [\"*\"]" })
172
175
  .refine((c) => !c.operations || !c.facts.some((fact) => c.operations.tools.some((tool) => tool.tool === fact.tool)), { message: "a fact lookup cannot invoke a financial operation tool" });
173
176
  /** Loads a config file and resolves every path relative to the file's directory. */
174
177
  export function loadConfig(path) {
@@ -0,0 +1,4 @@
1
+ declare const SCRIPT: string;
2
+ export declare const CONSOLE_CSP: string;
3
+ export declare const CONSOLE_HTML: string;
4
+ export { SCRIPT as CONSOLE_SCRIPT };
@@ -0,0 +1,342 @@
1
+ // The console's one page. The data it shows is written into the document with textContent only, never as markup, and the
2
+ // content-security-policy allows exactly this script and this style by hash, so a value that reaches the page cannot run.
3
+ import { createHash } from "node:crypto";
4
+ const STYLE = String.raw `
5
+ :root { --bg: #fafaf9; --panel: #ffffff; --ink: #1c1917; --muted: #78716c; --line: #e7e5e4; --accent: #b45309; --accent-ink: #ffffff; --ok: #15803d; --warn: #b45309; --bad: #b91c1c; --code: #f5f5f4; color-scheme: light dark; }
6
+ @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --bg: #1c1917; --panel: #292524; --ink: #fafaf9; --muted: #a8a29e; --line: #44403c; --accent: #f59e0b; --accent-ink: #1c1917; --ok: #4ade80; --warn: #fbbf24; --bad: #f87171; --code: #1c1917; } }
7
+ :root[data-theme="dark"] { --bg: #1c1917; --panel: #292524; --ink: #fafaf9; --muted: #a8a29e; --line: #44403c; --accent: #f59e0b; --accent-ink: #1c1917; --ok: #4ade80; --warn: #fbbf24; --bad: #f87171; --code: #1c1917; }
8
+ * { box-sizing: border-box; }
9
+ body { margin: 0; background: var(--bg); color: var(--ink); font: 14px/1.5 Inter, system-ui, -apple-system, "Segoe UI", sans-serif; }
10
+ header { display: flex; align-items: center; gap: 16px; padding: 12px 24px; border-bottom: 1px solid var(--line); background: var(--panel); flex-wrap: wrap; }
11
+ header h1 { font-size: 15px; margin: 0; font-weight: 650; }
12
+ nav { display: flex; gap: 4px; flex-wrap: wrap; flex: 1; }
13
+ nav button { background: none; border: 0; padding: 6px 12px; border-radius: 6px; color: var(--muted); cursor: pointer; font: inherit; }
14
+ nav button[aria-current="page"] { background: var(--code); color: var(--ink); font-weight: 600; }
15
+ main { max-width: 1100px; margin: 0 auto; padding: 24px 16px 64px; }
16
+ h2 { font-size: 18px; margin: 0 0 12px; }
17
+ h3 { font-size: 14px; margin: 0 0 8px; }
18
+ .card { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 16px; margin-bottom: 16px; }
19
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 16px; }
20
+ .grid .card { margin: 0; }
21
+ table { width: 100%; border-collapse: collapse; }
22
+ th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; overflow-wrap: anywhere; }
23
+ th { color: var(--muted); font-weight: 600; font-size: 12px; white-space: nowrap; overflow-wrap: normal; }
24
+ table.kv th { width: 9em; white-space: nowrap; overflow-wrap: normal; }
25
+ tr.click { cursor: pointer; } tr.click:hover { background: var(--code); }
26
+ code, pre, textarea { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; }
27
+ pre { background: var(--code); padding: 10px; border-radius: 6px; overflow: auto; max-height: 420px; margin: 8px 0 0; }
28
+ textarea { width: 100%; min-height: 280px; background: var(--code); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: 10px; resize: vertical; }
29
+ input[type=password], input[type=text], select { background: var(--code); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: 6px 10px; font: inherit; }
30
+ button.primary { background: var(--accent); color: var(--accent-ink); border: 0; border-radius: 6px; padding: 7px 14px; font: inherit; font-weight: 600; cursor: pointer; }
31
+ button.secondary { background: var(--panel); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: 7px 14px; font: inherit; cursor: pointer; }
32
+ button.danger { background: var(--bad); color: #fff; border: 0; border-radius: 6px; padding: 7px 14px; font: inherit; font-weight: 600; cursor: pointer; }
33
+ button:disabled { opacity: .5; cursor: default; }
34
+ .row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin: 8px 0; }
35
+ .muted { color: var(--muted); }
36
+ .ok { color: var(--ok); } .warn { color: var(--warn); } .error, .bad { color: var(--bad); }
37
+ .pill { display: inline-block; padding: 0 8px; border-radius: 999px; border: 1px solid var(--line); font-size: 12px; }
38
+ .banner { border: 1px solid var(--line); border-left: 4px solid var(--accent); background: var(--panel); border-radius: 6px; padding: 10px 14px; margin-bottom: 16px; }
39
+ .banner.bad { border-left-color: var(--bad); }
40
+ .finding { display: grid; grid-template-columns: 56px 130px 1fr; gap: 8px; padding: 4px 0; border-bottom: 1px solid var(--line); }
41
+ #login { max-width: 420px; margin: 96px auto; }
42
+ [hidden] { display: none !important; }
43
+ .mt { margin-top: 16px; }
44
+ textarea.short { min-height: 140px; }
45
+ @media (max-width: 600px) { .finding { grid-template-columns: 56px 1fr; } .finding .check { display: none; } }
46
+ `;
47
+ const SCRIPT = String.raw `
48
+ (function () {
49
+ 'use strict';
50
+ var KEY = 'agent-custody-console-token';
51
+ var THEME = 'agent-custody-theme';
52
+ try { var t = localStorage.getItem(THEME); if (t) document.documentElement.setAttribute('data-theme', t); } catch (e) {}
53
+ var token = '';
54
+ try { token = sessionStorage.getItem(KEY) || ''; } catch (e) {}
55
+ var view = document.getElementById('view');
56
+ var tabs = ['Overview', 'Check', 'Policy', 'Grants', 'Receipts', 'Audit'];
57
+ var current = 'Overview';
58
+ var policyDigest = '';
59
+
60
+ function h(tag, attrs) {
61
+ var e = document.createElement(tag);
62
+ if (attrs) Object.keys(attrs).forEach(function (k) {
63
+ var v = attrs[k];
64
+ if (k === 'class') e.className = v;
65
+ else if (k === 'text') e.textContent = v;
66
+ else if (k.slice(0, 2) === 'on') e.addEventListener(k.slice(2), v);
67
+ else if (v === true) e.setAttribute(k, '');
68
+ else if (v !== false && v != null) e.setAttribute(k, v);
69
+ });
70
+ for (var i = 2; i < arguments.length; i++) {
71
+ var c = arguments[i];
72
+ if (c == null || c === false) continue;
73
+ e.appendChild(typeof c === 'string' || typeof c === 'number' ? document.createTextNode(String(c)) : c);
74
+ }
75
+ return e;
76
+ }
77
+ function clear(e) { while (e.firstChild) e.removeChild(e.firstChild); return e; }
78
+ function say(text, bad) {
79
+ var m = document.getElementById('msg');
80
+ clear(m);
81
+ if (text) m.appendChild(h('div', { class: 'banner' + (bad ? ' bad' : ''), role: bad ? 'alert' : 'status', text: text }));
82
+ }
83
+ function api(method, path, body) {
84
+ return fetch(path, { method: method, headers: { 'authorization': 'Bearer ' + token, 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) })
85
+ .then(function (r) {
86
+ return r.json().then(function (data) {
87
+ if (r.status === 401 || r.status === 429) { signOut(); throw new Error(data.error || 'sign in again'); }
88
+ if (!r.ok) throw new Error(data.error || ('request failed: ' + r.status));
89
+ return data;
90
+ });
91
+ });
92
+ }
93
+ function fail(e) { say(e.message || String(e), true); }
94
+ function signOut() {
95
+ token = '';
96
+ try { sessionStorage.removeItem(KEY); } catch (e) {}
97
+ document.getElementById('app').hidden = true;
98
+ document.getElementById('login').hidden = false;
99
+ }
100
+ function kv(rows) {
101
+ var t = h('table', { class: 'kv' });
102
+ rows.forEach(function (r) { t.appendChild(h('tr', null, h('th', { text: r[0] }), h('td', null, r[1] == null ? '-' : r[1]))); });
103
+ return t;
104
+ }
105
+ function mark(level) { return h('span', { class: level, text: level === 'ok' ? 'ok' : level === 'warn' ? 'warn' : 'ERROR' }); }
106
+ function findings(list) {
107
+ var box = h('div');
108
+ list.forEach(function (f) { box.appendChild(h('div', { class: 'finding' }, mark(f.level), h('span', { class: 'muted check', text: f.check }), h('span', { text: f.message }))); });
109
+ return box;
110
+ }
111
+ function short(s) { return s ? String(s).slice(0, 12) + '…' : '-'; }
112
+
113
+ var renderers = {
114
+ Overview: function () {
115
+ return api('GET', '/api/overview').then(function (o) {
116
+ var g = o.gateway;
117
+ var gw = g == null ? h('span', { class: 'muted', text: 'not configured (start the console with --gateway-url)' })
118
+ : g.reachable ? h('span', { class: 'ok', text: 'running, ' + g.sessions + ' open session' + (g.sessions === 1 ? '' : 's') }) : h('span', { class: 'bad', text: 'not reachable' + (g.error ? ': ' + g.error : '') });
119
+ var up = h('table', null, h('tr', null, h('th', { text: 'name' }), h('th', { text: 'kind' }), h('th', { text: 'target' }), h('th', { text: 'tools' })));
120
+ o.upstreams.forEach(function (u) { up.appendChild(h('tr', null, h('td', { text: u.name }), h('td', { text: u.kind }), h('td', { text: u.target }), h('td', { text: u.tools ? u.tools.join(', ') : 'offered by the server; use Check and connect' }))); });
121
+ var errs = o.findings.filter(function (f) { return f.level === 'error'; }).length;
122
+ var warns = o.findings.filter(function (f) { return f.level === 'warn'; }).length;
123
+ return h('div', null,
124
+ h('h2', { text: 'Overview' }),
125
+ h('div', { class: 'grid' },
126
+ h('div', { class: 'card' }, h('h3', { text: 'Gateway' }), kv([['status', gw], ['key id', o.gatewayKeyid ? short(o.gatewayKeyid) : 'not created yet'], ['mode', o.mode], ['config', o.configFile]])),
127
+ h('div', { class: 'card' }, h('h3', { text: 'Evidence' }), kv([['receipts', String(o.receiptCount)], ['last receipt', o.lastReceiptAt], ['log', o.log.kind === 'remote' ? 'remote ' + o.log.url + (o.log.hashOnly ? ' (hashes only)' : '') : 'local ' + o.log.file], ['precommit', o.precommit.length ? o.precommit.join(', ') : 'none']])),
128
+ h('div', { class: 'card' }, h('h3', { text: 'Who is trusted' }), kv([['principal keys', String(o.principals.length)], ['key ids', o.principals.map(short).join(', ') || 'none'], ['revoked grants', String(o.revokedCount)]])),
129
+ h('div', { class: 'card' }, h('h3', { text: 'Config check' }), h('p', null, h('span', { class: errs ? 'bad' : 'ok', text: errs + ' error' + (errs === 1 ? '' : 's') }), ', ', h('span', { class: warns ? 'warn' : 'muted', text: warns + ' warning' + (warns === 1 ? '' : 's') })), h('button', { class: 'secondary', onclick: function () { show('Check'); } }, 'See the findings'))),
130
+ o.keyProblems.length ? h('div', { class: 'banner bad' }, o.keyProblems.join('. ')) : null,
131
+ h('div', { class: 'card mt' }, h('h3', { text: 'Upstreams' }), up),
132
+ o.facts.length ? h('div', { class: 'card' }, h('h3', { text: 'Fact lookups the gateway makes itself' }), kv(o.facts.map(function (f) { return [f.name, f.tool + ' for ' + f.forTools.join(', ')]; }))) : null);
133
+ });
134
+ },
135
+
136
+ Check: function () {
137
+ var out = h('div');
138
+ function run(connect) {
139
+ say(connect ? 'Starting the upstreams to list their tools…' : '');
140
+ clear(out);
141
+ return api('POST', '/api/check', { connect: connect }).then(function (r) { say(''); out.appendChild(h('div', { class: 'card' }, findings(r.findings))); }).catch(fail);
142
+ }
143
+ var box = h('div', null, h('h2', { text: 'Config check' }),
144
+ h('p', { class: 'muted', text: 'What the gateway would fail on at startup, found before it starts. Connecting starts your stdio upstreams and lists the tools every upstream offers.' }),
145
+ h('div', { class: 'row' }, h('button', { class: 'primary', onclick: function () { run(false); } }, 'Run check'), h('button', { class: 'secondary', onclick: function () { run(true); } }, 'Run check and connect to the upstreams')), out);
146
+ run(false);
147
+ return Promise.resolve(box);
148
+ },
149
+
150
+ Policy: function () {
151
+ return api('GET', '/api/policy').then(function (p) {
152
+ policyDigest = p.digest;
153
+ var area = h('textarea', { 'aria-label': 'Cedar policy', spellcheck: 'false' });
154
+ area.value = p.text;
155
+ var out = h('div');
156
+ function validate() {
157
+ return api('POST', '/api/policy/validate', { text: area.value }).then(function (r) {
158
+ clear(out);
159
+ if (r.ok) {
160
+ out.appendChild(h('p', { class: 'ok', text: 'The policy parses.' }));
161
+ r.issues.forEach(function (m) { out.appendChild(h('p', { class: 'warn', text: m })); });
162
+ } else r.errors.forEach(function (m) { out.appendChild(h('p', { class: 'bad', text: m })); });
163
+ return r;
164
+ });
165
+ }
166
+ function simulate() {
167
+ return validate().then(function (v) {
168
+ if (!v.ok) return;
169
+ say('Replaying recorded calls against this policy…');
170
+ return api('POST', '/api/policy/simulate', { text: area.value }).then(function (s) {
171
+ say('');
172
+ var r = s.report;
173
+ out.appendChild(h('div', { class: 'card' }, h('h3', { text: 'Replay of recorded calls' }),
174
+ h('p', { class: 'muted', text: 'A replay re-decides calls that already happened. A limit that no recorded call reached, and an argument value that was never sent, are not covered, so a change that widens what is allowed can show no change here.' }),
175
+ h('p', { text: s.replayed + ' verified receipts replayed (' + s.unverified + ' skipped because they did not verify). ' + r.evaluated + ' evaluated, ' + r.unchanged + ' unchanged, ' + r.reconciliations + ' reconciliations (provider reads with no policy decision), ' + r.changeCount + ' would change.' + (r.complete ? '' : ' The replay is incomplete: ' + r.skipped.length + ' calls could not be replayed.') }),
176
+ r.changes.length ? (function () {
177
+ var t = h('table', null, h('tr', null, h('th', { text: 'receipt' }), h('th', { text: 'tool' }), h('th', { text: 'was' }), h('th', { text: 'would be' })));
178
+ r.changes.forEach(function (c) { t.appendChild(h('tr', null, h('td', { text: short(c.receiptId) }), h('td', { text: c.tool }), h('td', { text: c.from }), h('td', { class: c.to === 'deny' ? 'bad' : 'warn', text: c.to }))); });
179
+ return t;
180
+ })() : h('p', { class: 'muted', text: 'No recorded decision would change.' })));
181
+ });
182
+ });
183
+ }
184
+ function save() {
185
+ return validate().then(function (v) {
186
+ if (!v.ok) return;
187
+ var ask = 'Save this policy?\n\nA running gateway applies it from its next call.';
188
+ if (v.issues.length) ask = 'Confirm before saving:\n\n' + v.issues.join('\n\n') + '\n\nSave this policy anyway?';
189
+ if (!window.confirm(ask)) return;
190
+ return api('PUT', '/api/policy', { text: area.value, expectDigest: policyDigest, confirm: v.issues.length > 0 }).then(function (r) {
191
+ policyDigest = r.digest;
192
+ say('Saved (' + short(r.digest) + '). ' + r.note);
193
+ });
194
+ });
195
+ }
196
+ return h('div', null, h('h2', { text: 'Policy' }),
197
+ h('div', { class: 'banner' }, 'A running gateway applies a saved change from its next call; every save is recorded in the audit trail, and the previous version is kept.'),
198
+ h('p', { class: 'muted' }, p.path + ' · ' + short(p.digest)),
199
+ area, h('div', { class: 'row' },
200
+ h('button', { class: 'secondary', onclick: function () { validate().catch(fail); } }, 'Validate'),
201
+ h('button', { class: 'secondary', onclick: function () { simulate().catch(fail); } }, 'Replay recorded calls'),
202
+ h('button', { class: 'primary', onclick: function () { save().catch(fail); } }, 'Save')),
203
+ out,
204
+ p.history.length ? h('div', { class: 'card' }, h('h3', { text: 'Earlier versions kept' }), h('p', { class: 'muted', text: p.history.join(', ') })) : null);
205
+ });
206
+ },
207
+
208
+ Grants: function () {
209
+ var area = h('textarea', { 'aria-label': 'Grant', placeholder: 'Paste a grant (the JSON of a grant file)', spellcheck: 'false', class: 'short' });
210
+ var out = h('div');
211
+ var last = null;
212
+ function inspect() {
213
+ return api('POST', '/api/grants/inspect', { grant: area.value }).then(function (g) {
214
+ last = g;
215
+ clear(out);
216
+ out.appendChild(h('div', { class: 'card' }, h('h3', { text: 'Grant' }), kv([
217
+ ['status', h('span', { class: g.status === 'valid' ? 'ok' : 'bad', text: g.status })],
218
+ ['agent', g.agent], ['principal', g.principal], ['scopes', g.scopes.join(', ')], ['issued', g.issuedAt], ['expires', g.expiresAt],
219
+ ['delegated from another grant', g.delegated ? 'yes' : 'no'], ['can delegate', g.canDelegate ? 'yes' : 'no'], ['digest', g.digest], ['why not valid', g.error]]),
220
+ h('div', { class: 'row' }, g.revoked ? h('span', { class: 'pill', text: 'already revoked' }) : h('button', { class: 'danger', onclick: function () { revoke().catch(fail); } }, 'Revoke this grant'))));
221
+ });
222
+ }
223
+ function revoke() {
224
+ if (!last || !window.confirm('Revoke the grant for ' + last.agent + '?\n\nIt, and every grant delegated from it, is refused on its next call. This cannot be undone here.')) return Promise.resolve();
225
+ return api('POST', '/api/grants/revoke', { grant: area.value }).then(function (r) { say('Revoked the grant for ' + r.agent + '. ' + r.note); return inspect().then(list); });
226
+ }
227
+ var revoked = h('div');
228
+ function list() {
229
+ return api('GET', '/api/revocations').then(function (r) {
230
+ clear(revoked);
231
+ revoked.appendChild(h('div', { class: 'card' }, h('h3', { text: 'Revoked grants (' + r.digests.length + ')' }), r.digests.length ? h('table', null, r.digests.map(function (d) { return h('tr', null, h('td', null, h('code', { text: d }))); })) : h('p', { class: 'muted', text: 'None.' })));
232
+ });
233
+ }
234
+ list().catch(fail);
235
+ return Promise.resolve(h('div', null, h('h2', { text: 'Grants' }),
236
+ h('p', { class: 'muted', text: 'The gateway does not store grants: each agent presents its own. Paste one to see whether the gateway would accept it, and to revoke it. The console never holds a principal key and cannot issue a grant.' }),
237
+ area, h('div', { class: 'row' }, h('button', { class: 'primary', onclick: function () { inspect().catch(fail); } }, 'Inspect')), out, revoked));
238
+ },
239
+
240
+ Receipts: function () {
241
+ return api('GET', '/api/receipts?limit=100').then(function (r) {
242
+ var detail = h('div');
243
+ var filter = h('select', { 'aria-label': 'Filter by status' }, h('option', { value: '' }, 'all'), h('option', { value: 'executed' }, 'executed'), h('option', { value: 'denied' }, 'denied'), h('option', { value: 'withheld' }, 'withheld'), h('option', { value: 'failed' }, 'failed'));
244
+ var body = h('table');
245
+ function draw() {
246
+ clear(body);
247
+ body.appendChild(h('tr', null, h('th', { text: 'time' }), h('th', { text: 'agent' }), h('th', { text: 'tool' }), h('th', { text: 'decision' }), h('th', { text: 'outcome' }), h('th', { text: 'verifies' })));
248
+ r.receipts.filter(function (x) { return !filter.value || x.status === filter.value; }).forEach(function (x) {
249
+ body.appendChild(h('tr', { class: 'click', onclick: function () { open(x.id); } },
250
+ h('td', { text: x.timestamp || '-' }), h('td', { text: x.agent || '-' }), h('td', { text: x.tool || '-' }),
251
+ h('td', { class: x.decision === 'deny' ? 'bad' : '', text: x.decision ? x.decision + (x.enforced ? '' : ' (not enforced)') : '-' }),
252
+ h('td', { text: x.status ? x.status + (x.reason ? ': ' + x.reason : '') : '-' }),
253
+ h('td', { class: x.verified ? 'ok' : 'bad', text: x.verified ? 'yes' : 'NO: ' + (x.failing || []).join(', ') })));
254
+ });
255
+ }
256
+ function open(id) {
257
+ api('GET', '/api/receipts/' + encodeURIComponent(id)).then(function (d) {
258
+ clear(detail);
259
+ detail.appendChild(h('div', { class: 'card' }, h('h3', { text: 'Receipt ' + id }), h('pre', { text: JSON.stringify(d.statement, null, 2) })));
260
+ detail.scrollIntoView();
261
+ }).catch(fail);
262
+ }
263
+ filter.addEventListener('change', draw);
264
+ draw();
265
+ return h('div', null, h('h2', { text: 'Receipts' }),
266
+ h('p', { class: 'muted', text: r.total + ' receipts on disk, the newest ' + r.receipts.length + ' shown. Each is verified against the gateway key, the trusted principals, and the local log.' }),
267
+ r.problems.length ? h('div', { class: 'banner bad' }, r.problems.join('. ')) : null,
268
+ h('div', { class: 'row' }, h('label', null, 'Outcome ', filter)), h('div', { class: 'card' }, body), detail);
269
+ });
270
+ },
271
+
272
+ Audit: function () {
273
+ return api('GET', '/api/audit').then(function (a) {
274
+ var t = h('table', null, h('tr', null, h('th', { text: 'when' }), h('th', { text: 'by' }), h('th', { text: 'action' }), h('th', { text: 'detail' })));
275
+ a.entries.forEach(function (e) {
276
+ var rest = {}; Object.keys(e).forEach(function (k) { if (k !== 'at' && k !== 'by' && k !== 'action') rest[k] = e[k]; });
277
+ t.appendChild(h('tr', null, h('td', { text: e.at }), h('td', { text: e.by }), h('td', { text: e.action }), h('td', null, h('code', { text: JSON.stringify(rest) }))));
278
+ });
279
+ return h('div', null, h('h2', { text: 'Audit trail' }), h('p', { class: 'muted', text: 'Every change made here: who, when, and what.' }), h('div', { class: 'card' }, a.entries.length ? t : h('p', { class: 'muted', text: 'No changes yet.' })));
280
+ });
281
+ }
282
+ };
283
+
284
+ function show(name) {
285
+ current = name;
286
+ say('');
287
+ Array.prototype.forEach.call(document.querySelectorAll('nav button'), function (b) { if (b.textContent === name) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current'); });
288
+ clear(view).appendChild(h('p', { class: 'muted', text: 'Loading…' }));
289
+ renderers[name]().then(function (el) { clear(view).appendChild(el); }).catch(function (e) { clear(view); fail(e); });
290
+ }
291
+
292
+ var nav = document.getElementById('nav');
293
+ tabs.forEach(function (n) { nav.appendChild(h('button', { type: 'button', onclick: function () { show(n); } }, n)); });
294
+ document.getElementById('signout').addEventListener('click', signOut);
295
+ document.getElementById('theme').addEventListener('click', function () {
296
+ var dark = document.documentElement.getAttribute('data-theme') === 'dark' || (!document.documentElement.getAttribute('data-theme') && window.matchMedia('(prefers-color-scheme: dark)').matches);
297
+ var next = dark ? 'light' : 'dark';
298
+ document.documentElement.setAttribute('data-theme', next);
299
+ try { localStorage.setItem(THEME, next); } catch (e) {}
300
+ });
301
+ document.getElementById('login-form').addEventListener('submit', function (ev) {
302
+ ev.preventDefault();
303
+ token = document.getElementById('token').value.trim();
304
+ document.getElementById('token').value = '';
305
+ api('GET', '/api/audit').then(function () {
306
+ try { sessionStorage.setItem(KEY, token); } catch (e) {}
307
+ document.getElementById('login').hidden = true;
308
+ document.getElementById('app').hidden = false;
309
+ show(current);
310
+ }).catch(function (e) { clear(document.getElementById('login-msg')).appendChild(h('p', { class: 'bad', role: 'alert', text: e.message })); });
311
+ });
312
+ if (token) {
313
+ api('GET', '/api/audit').then(function () { document.getElementById('login').hidden = true; document.getElementById('app').hidden = false; show(current); }).catch(function () { signOut(); });
314
+ }
315
+ })();
316
+ `;
317
+ const sha = (s) => `'sha256-${createHash("sha256").update(s).digest("base64")}'`;
318
+ export const CONSOLE_CSP = `default-src 'none'; style-src ${sha(STYLE)}; script-src ${sha(SCRIPT)}; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`;
319
+ export const CONSOLE_HTML = `<!doctype html>
320
+ <html lang="en">
321
+ <head>
322
+ <meta charset="utf-8">
323
+ <meta name="viewport" content="width=device-width, initial-scale=1">
324
+ <title>agent-custody console</title>
325
+ <style>${STYLE}</style>
326
+ </head>
327
+ <body>
328
+ <section id="login" class="card">
329
+ <h2>agent-custody console</h2>
330
+ <p class="muted">Sign in with the console's token. It is kept for this browser tab only.</p>
331
+ <form id="login-form"><div class="row"><label for="token">Token</label><input id="token" type="password" autocomplete="off" required><button class="primary" type="submit">Sign in</button></div></form>
332
+ <div id="login-msg"></div>
333
+ </section>
334
+ <div id="app" hidden>
335
+ <header><h1>agent-custody console</h1><nav id="nav" aria-label="Sections"></nav><button id="theme" type="button" class="secondary">Theme</button><button id="signout" type="button" class="secondary">Sign out</button></header>
336
+ <main><div id="msg"></div><div id="view"></div></main>
337
+ </div>
338
+ <script>${SCRIPT}</script>
339
+ </body>
340
+ </html>
341
+ `;
342
+ export { SCRIPT as CONSOLE_SCRIPT };