@agent-custody/receipts 0.7.0 → 0.9.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 (51) hide show
  1. package/README.md +29 -13
  2. package/dist/approval.d.ts +74 -0
  3. package/dist/approval.js +196 -0
  4. package/dist/capture.js +49 -1
  5. package/dist/check.d.ts +19 -0
  6. package/dist/check.js +288 -0
  7. package/dist/cli.js +238 -11
  8. package/dist/config.d.ts +85 -0
  9. package/dist/config.js +72 -2
  10. package/dist/console-page.d.ts +4 -0
  11. package/dist/console-page.js +342 -0
  12. package/dist/console.d.ts +20 -0
  13. package/dist/console.js +521 -0
  14. package/dist/gateway.d.ts +9 -0
  15. package/dist/gateway.js +335 -45
  16. package/dist/index.d.ts +9 -2
  17. package/dist/index.js +7 -1
  18. package/dist/issue.d.ts +8 -3
  19. package/dist/issue.js +13 -4
  20. package/dist/log-store.d.ts +3 -2
  21. package/dist/log-store.js +2 -0
  22. package/dist/operations.d.ts +101 -0
  23. package/dist/operations.js +239 -0
  24. package/dist/otel.js +12 -5
  25. package/dist/policy.d.ts +2 -0
  26. package/dist/policy.js +10 -0
  27. package/dist/portal.d.ts +78 -4
  28. package/dist/portal.js +516 -26
  29. package/dist/receipt.d.ts +36 -1
  30. package/dist/rest.js +14 -1
  31. package/dist/simulate.d.ts +58 -0
  32. package/dist/simulate.js +204 -0
  33. package/dist/splunk.js +11 -4
  34. package/dist/sso.d.ts +47 -0
  35. package/dist/sso.js +161 -0
  36. package/dist/verify.d.ts +2 -0
  37. package/dist/verify.js +241 -7
  38. package/docs/approvals.md +107 -0
  39. package/docs/codex-recovery.md +132 -0
  40. package/docs/configuration.md +224 -0
  41. package/docs/console.md +79 -0
  42. package/docs/financial-operations.md +99 -0
  43. package/docs/policies.md +23 -0
  44. package/docs/threat-model.md +13 -0
  45. package/docs/tutorials.md +9 -0
  46. package/docs/usage.md +49 -4
  47. package/docs/verification.md +26 -8
  48. package/package.json +8 -2
  49. package/vectors/audit.json +27 -27
  50. package/vectors/canonical.json +5 -5
  51. package/vectors/receipts.json +2866 -464
package/dist/cli.js CHANGED
@@ -3,8 +3,8 @@ import { hostname, userInfo } from "node:os";
3
3
  import { captureKeyFrom, getAt, pathText, restorePaths, setAt } from "./capture.js";
4
4
  import { saltsFileFor } from "./retention.js";
5
5
  import { parseArgs } from "node:util";
6
- import { closeSync, constants as fsConstants, existsSync, fchmodSync, openSync, readFileSync, writeFileSync, writeSync } from "node:fs";
7
- import { dirname, resolve } from "node:path";
6
+ import { closeSync, constants as fsConstants, existsSync, fchmodSync, openSync, readFileSync, readdirSync, writeFileSync, writeSync } from "node:fs";
7
+ import { dirname, join, resolve } from "node:path";
8
8
  import { loadConfig, loadSdkConfig } from "./config.js";
9
9
  import { dsseVerify, generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
10
10
  import { createDelegation, decodeDelegation, delegateFrom, grantDigest } from "./delegation.js";
@@ -23,11 +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";
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
+ }
31
57
  /** A shared secret from an environment variable; never from the command line, where it would land in shell history. */
32
58
  function secretFrom(envName) {
33
59
  const v = process.env[envName];
@@ -46,6 +72,15 @@ const USAGE = `agent-custody <command>
46
72
  for verify --disclose; needs the customer's capture key
47
73
  revoke --config <gateway.json> --grant <grant.json> revokes a grant: its digest goes into the config's revokedGrants file, every
48
74
  session under it or under a grant delegated from it refuses its next call, and no new session opens for them
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
49
84
  gateway --config <gateway.json> [--http [--port 8790] [--host 127.0.0.1] [--idle-minutes 30]]
50
85
  stdio: one gateway for the grant the config names. --http: one shared gateway, MCP over
51
86
  Streamable HTTP at /mcp, each connection presenting its own grant as Authorization: Bearer
@@ -54,7 +89,10 @@ const USAGE = `agent-custody <command>
54
89
  prune --log <log.jsonl> --before <ISO instant> [--receipts <dir>]
55
90
  retention on the receipt log: replaces older leaves with their hashes, so proofs still verify and the content is gone
56
91
  log --file <log.jsonl> --key <log.key> [--port 8787] [--host 127.0.0.1] [--token-env <NAME>] reference log server
57
- verify <bundle.json> --issuer-key <pub> [--principal-key <pub>] [--log-key <pub> | --log-url <url>] [--log-id <id>] [--upstream-key <pub>] [--stripe-secret-env NAME] [--github-secret-env NAME] [--log <log.jsonl>] [--json]
92
+ verify <bundle.json> --issuer-key <pub> [--principal-key <pub>] [--approval-key <pub>] [--log-key <pub> | --log-url <url>] [--log-id <id>] [--upstream-key <pub>] [--stripe-secret-env NAME] [--github-secret-env NAME] [--log <log.jsonl>] [--disclose <file>] [--capture-key-env NAME] [--json]
93
+ policy simulate --policy <proposed.cedar> --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--approval-key <pub>]... [--log-key <pub>]... [--json] [--out <file>]
94
+ replay verified local receipts against a proposed policy using their recorded inputs;
95
+ --out saves the full JSON report. Exits 1 when any call could not be evaluated.
58
96
  log ... --db-env NAME the same server over Postgres: tenants and tokens from the database, one writer per tenant,
59
97
  root paths serve the tenant "default" (created with --log-id). Needs the pg package.
60
98
  log ... (--key <log.key> [--retired-key <pub>]... | --signer-url <url> [--signer-token-env NAME]) [--checkpoint-dir <dir>] [--checkpoint-every <seconds>] [--checkpoint-heartbeat <seconds>]
@@ -82,6 +120,10 @@ const USAGE = `agent-custody <command>
82
120
  log-admin --db-env NAME tenant add <id> [--log-id <id>] | tenant list | tenant disable <id> | tenant plan <id> <free|team|enterprise>
83
121
  log-admin --db-env NAME token add <tenant> --label <text> | token list <tenant> | token revoke <tenant> <hash-prefix>
84
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
85
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]
86
128
  [--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]
87
129
  the tenant portal: register, first key, usage against plan, keys, billing, export
@@ -127,7 +169,25 @@ function loadTenants(path) {
127
169
  }
128
170
  async function main(argv) {
129
171
  const [cmd, ...rest] = argv;
172
+ if (runsUntilStopped(cmd, rest))
173
+ void untilStopped();
130
174
  switch (cmd) {
175
+ case "reconcile": {
176
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, operation: { type: "string" } } });
177
+ if (!values.config || !values.operation)
178
+ throw new Error("reconcile needs --config and --operation");
179
+ const cfg = loadConfig(values.config);
180
+ const host = await createGatewayHost(cfg);
181
+ try {
182
+ const bundle = await host.reconcile(values.operation);
183
+ const p = JSON.parse(Buffer.from(bundle.envelope.payload, "base64").toString("utf8")).predicate;
184
+ console.log(JSON.stringify({ operation: values.operation, status: p.operation.status, receipt: join(cfg.receiptsDir, `${p.receiptId}.json`) }));
185
+ return 0;
186
+ }
187
+ finally {
188
+ await host.close();
189
+ }
190
+ }
131
191
  case "keygen": {
132
192
  const { values } = parseArgs({ args: rest, options: { dir: { type: "string" }, name: { type: "string" } } });
133
193
  if (!values.dir || !values.name)
@@ -182,6 +242,24 @@ async function main(argv) {
182
242
  console.log(`delegated to ${chain.agent}: scopes [${chain.scopes.join(", ")}] until ${chain.expiresAt}, under ${decodeDelegation(parent).agent}'s grant from ${chain.principal}`);
183
243
  return 0;
184
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
+ }
185
263
  case "revoke": {
186
264
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, grant: { type: "string" } } });
187
265
  if (!values.config || !values.grant)
@@ -216,7 +294,7 @@ async function main(argv) {
216
294
  const grant = cfg.grantFile ? JSON.parse(readFileSync(cfg.grantFile, "utf8")) : undefined;
217
295
  const running = await serveA2a(host, a2a, { port: Number(values.port), host: values.host, ...(grant ? { grant } : {}) });
218
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`);
219
- await new Promise((resolve) => process.once("SIGINT", resolve));
297
+ await untilStopped();
220
298
  await running.close();
221
299
  await host.close();
222
300
  return 0;
@@ -225,7 +303,7 @@ async function main(argv) {
225
303
  const host = await createGatewayHost(loadConfig(values.config));
226
304
  const running = await serveHttp(host, { port: Number(values.port), host: values.host, idleMs: Number(values["idle-minutes"]) * 60_000 });
227
305
  console.error(`agent-custody gateway: ${running.url} keyid=${host.keyid} one session per grant; GET /health`);
228
- await new Promise((resolve) => process.once("SIGINT", resolve));
306
+ await untilStopped();
229
307
  await running.close();
230
308
  await host.close();
231
309
  return 0;
@@ -253,7 +331,7 @@ async function main(argv) {
253
331
  const issuer = createSdkIssuer(loadSdkConfig(values.config));
254
332
  const running = await serveSidecar(issuer, { port: Number(values.port), host: values.host });
255
333
  console.error(`agent-custody serve: ${running.url} agent=${issuer.agentId} keyid=${issuer.keyid} log=${issuer.log.kind}:${issuer.log.where}`);
256
- await new Promise((resolve) => process.once("SIGINT", resolve));
334
+ await untilStopped();
257
335
  await running.close();
258
336
  return 0;
259
337
  }
@@ -292,7 +370,7 @@ async function main(argv) {
292
370
  }
293
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}`);
294
372
  w.start(everyMs);
295
- await new Promise((resolve) => process.once("SIGINT", resolve));
373
+ await untilStopped();
296
374
  w.stop();
297
375
  return 0;
298
376
  }
@@ -306,7 +384,7 @@ async function main(argv) {
306
384
  const kp = loadPrivateKey(values.key);
307
385
  const running = await serveSigner(kp, { port: Number(values.port), host: values.host, ...(token ? { token } : {}), retired: (values["retired-key"] ?? []).map(retiredKey) });
308
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}` : ""}`);
309
- await new Promise((resolve) => process.once("SIGINT", resolve));
387
+ await untilStopped();
310
388
  await running.close();
311
389
  return 0;
312
390
  }
@@ -374,12 +452,12 @@ async function main(argv) {
374
452
  }
375
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 });
376
454
  console.error(`agent-custody portal: ${running.url} log=${values["public-url"]} billing=${stripe ? "stripe" : "off"}${values["trust-proxy"] ? " trust-proxy" : ""}`);
377
- await new Promise((resolve) => process.once("SIGINT", resolve));
455
+ await untilStopped();
378
456
  await running.close();
379
457
  return 0;
380
458
  }
381
459
  case "log-admin": {
382
- 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" } } });
383
461
  if (!values["db-env"])
384
462
  throw new Error("log-admin needs --db-env NAME");
385
463
  const tenancy = new PostgresTenancy(openPostgres(values["db-env"]));
@@ -415,6 +493,55 @@ async function main(argv) {
415
493
  else if (what === "token" && verb === "revoke" && args[0] && args[1]) {
416
494
  console.log(`revoked ${await tenancy.revokeToken(args[0], args[1], actor)} token(s)`);
417
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
+ }
418
545
  else if (what === "audit") {
419
546
  for (const e of await tenancy.audit({ ...(values.tenant !== "default" ? { tenant: values.tenant } : {}), limit: 100 }))
420
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(" ")}`);
@@ -505,7 +632,7 @@ async function main(argv) {
505
632
  const publisher = checkpoints ? new CheckpointPublisher(resolver, signer, checkpoints, everyMs, undefined, heartbeatMs) : null;
506
633
  publisher?.start();
507
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" : ""}`);
508
- await new Promise((resolve) => process.once("SIGINT", resolve));
635
+ await untilStopped();
509
636
  publisher?.stop();
510
637
  await running.close();
511
638
  return 0;
@@ -518,6 +645,7 @@ async function main(argv) {
518
645
  "issuer-key": { type: "string", multiple: true },
519
646
  "gateway-key": { type: "string", multiple: true },
520
647
  "principal-key": { type: "string", multiple: true },
648
+ "approval-key": { type: "string", multiple: true },
521
649
  "log-key": { type: "string", multiple: true },
522
650
  "log-url": { type: "string" },
523
651
  "log-id": { type: "string" },
@@ -542,6 +670,7 @@ async function main(argv) {
542
670
  const result = verifyBundle(bundle, {
543
671
  issuerKeys: issuerKeyFiles.map(loadPublicKey),
544
672
  principalKeys: (values["principal-key"] ?? []).map(loadPublicKey),
673
+ ...(values["approval-key"] ? { approvalKeys: values["approval-key"].map(loadPublicKey) } : {}),
545
674
  ...(logKeys.length ? { logKeys } : {}),
546
675
  ...(values["log-id"] ? { logId: values["log-id"] } : {}),
547
676
  ...(values["upstream-key"] ? { upstreamKeys: values["upstream-key"].map(loadPublicKey) } : {}),
@@ -553,6 +682,104 @@ async function main(argv) {
553
682
  console.log(values.json ? JSON.stringify(result, null, 2) : formatReport(result));
554
683
  return result.ok ? 0 : 1;
555
684
  }
685
+ case "policy": {
686
+ const [subcommand, ...args] = rest;
687
+ if (subcommand !== "simulate")
688
+ throw new Error("policy needs the simulate subcommand: policy simulate --policy <proposed.cedar> --receipts <dir> --issuer-key <pub>");
689
+ const { values } = parseArgs({
690
+ args,
691
+ options: {
692
+ policy: { type: "string" },
693
+ receipts: { type: "string" },
694
+ "issuer-key": { type: "string", multiple: true },
695
+ "principal-key": { type: "string", multiple: true },
696
+ "approval-key": { type: "string", multiple: true },
697
+ "log-key": { type: "string", multiple: true },
698
+ "capture-key-env": { type: "string" },
699
+ disclose: { type: "string", multiple: true },
700
+ json: { type: "boolean", default: false },
701
+ out: { type: "string" },
702
+ },
703
+ });
704
+ if (!values.policy || !values.receipts || !values["issuer-key"]?.length)
705
+ throw new Error("policy simulate needs --policy <proposed.cedar> --receipts <dir> --issuer-key <pub>");
706
+ const policy = readFileSync(values.policy, "utf8");
707
+ const keys = {
708
+ issuerKeys: values["issuer-key"].map(loadPublicKey),
709
+ principalKeys: (values["principal-key"] ?? []).map(loadPublicKey),
710
+ approvalKeys: (values["approval-key"] ?? []).map(loadPublicKey),
711
+ logKeys: (values["log-key"] ?? []).map(loadPublicKey),
712
+ };
713
+ const names = readdirSync(values.receipts, { withFileTypes: true })
714
+ .filter((entry) => (entry.isFile() || entry.isSymbolicLink()) && entry.name.endsWith(".json"))
715
+ .map((entry) => entry.name);
716
+ const AUTHORIZATION = ".authorization.json";
717
+ const files = names.filter((name) => !name.endsWith(AUTHORIZATION)).sort();
718
+ const have = new Set(files);
719
+ const fail = (file, error) => { throw new Error(`policy simulate: ${file}: ${error instanceof Error ? error.message : String(error)}`); };
720
+ // A gateway that dies after it forwards a precommit call leaves <id>.authorization.json and no <id>.json. That
721
+ // call went upstream, so it counts as skipped and the report is incomplete.
722
+ const unreplayable = names.filter((name) => name.endsWith(AUTHORIZATION) && !have.has(`${name.slice(0, -AUTHORIZATION.length)}.json`)).sort().map((name) => {
723
+ const file = join(values.receipts, name);
724
+ try {
725
+ const p = verifyOrphanAuthorization(JSON.parse(readFileSync(file, "utf8")), keys.issuerKeys, keys.logKeys);
726
+ if (`${p.receiptId}${AUTHORIZATION}` !== name)
727
+ throw new Error("the file name does not match the receipt id in the authorization");
728
+ return { receiptId: p.receiptId, tool: p.tool.name, reason: "only the authorization survives; the receipt is missing, so the outcome and the call cannot be replayed" };
729
+ }
730
+ catch (error) {
731
+ return fail(file, error);
732
+ }
733
+ });
734
+ if (!files.length && !unreplayable.length)
735
+ throw new Error(`policy simulate: no receipt bundles found in ${values.receipts}`);
736
+ const captureKey = values["capture-key-env"] ? captureKeyFrom(secretFrom(values["capture-key-env"])) : undefined;
737
+ const disclosures = new Map();
738
+ for (const file of values.disclose ?? []) {
739
+ try {
740
+ const disclosure = JSON.parse(readFileSync(file, "utf8"));
741
+ if (typeof disclosure?.receiptId !== "string")
742
+ throw new Error("the disclosure names no receiptId");
743
+ disclosures.set(disclosure.receiptId, disclosure);
744
+ }
745
+ catch (error) {
746
+ fail(file, error);
747
+ }
748
+ }
749
+ // One bundle at a time: the replay needs the predicate of the receipt it is on, not the results of the others.
750
+ function* verified() {
751
+ for (const name of files) {
752
+ const file = join(values.receipts, name);
753
+ try {
754
+ const bundle = JSON.parse(readFileSync(file, "utf8"));
755
+ const result = verifyBundle(bundle, keys);
756
+ if (!result.ok || !result.statement) {
757
+ const failures = result.checks.filter((check) => !check.ok).map((check) => `${check.name}${check.detail ? ` (${check.detail})` : ""}`);
758
+ throw new Error(`receipt verification failed: ${failures.join("; ")}`);
759
+ }
760
+ yield result.statement.predicate;
761
+ }
762
+ catch (error) {
763
+ fail(file, error);
764
+ }
765
+ }
766
+ }
767
+ const report = simulatePolicy(policy, verified(), { unreplayable, ...(captureKey ? { captureKey } : {}), disclosures });
768
+ const json = JSON.stringify(report, null, 2);
769
+ if (values.out) {
770
+ // Reports name calls and decisions: keep them owner-only, including when replacing an existing file.
771
+ const fd = openSync(values.out, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC | fsConstants.O_NOFOLLOW, 0o600);
772
+ try {
773
+ fchmodSync(fd, 0o600);
774
+ writeSync(fd, json);
775
+ }
776
+ finally {
777
+ closeSync(fd);
778
+ }
779
+ }
780
+ console.log(values.json ? json : formatSimulation(report));
781
+ return report.complete ? 0 : 1;
782
+ }
556
783
  case "reveal": {
557
784
  // The values a receipt withheld, under the customer's key, as a disclosure file: hand it to a reviewer with the
558
785
  // receipt, and `verify --disclose` recomputes every digest from it.
package/dist/config.d.ts CHANGED
@@ -16,6 +16,7 @@ declare const RestToolSchema: z.ZodObject<{
16
16
  json: "json";
17
17
  none: "none";
18
18
  }>>;
19
+ idempotencyHeader: z.ZodOptional<z.ZodString>;
19
20
  inputSchema: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
20
21
  }, z.core.$strip>;
21
22
  export type RestToolConfig = z.infer<typeof RestToolSchema>;
@@ -41,6 +42,7 @@ declare const RestUpstreamSchema: z.ZodObject<{
41
42
  json: "json";
42
43
  none: "none";
43
44
  }>>;
45
+ idempotencyHeader: z.ZodOptional<z.ZodString>;
44
46
  inputSchema: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
45
47
  }, z.core.$strip>>;
46
48
  }, z.core.$strip>;
@@ -83,6 +85,7 @@ declare const UpstreamSchema: z.ZodUnion<readonly [z.ZodObject<{
83
85
  json: "json";
84
86
  none: "none";
85
87
  }>>;
88
+ idempotencyHeader: z.ZodOptional<z.ZodString>;
86
89
  inputSchema: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
87
90
  }, z.core.$strip>>;
88
91
  }, z.core.$strip>;
@@ -103,6 +106,48 @@ declare const FactSchema: z.ZodObject<{
103
106
  forTools: z.ZodArray<z.ZodString>;
104
107
  optional: z.ZodDefault<z.ZodBoolean>;
105
108
  }, z.core.$strip>;
109
+ declare const OperationToolSchema: z.ZodObject<{
110
+ tool: z.ZodString;
111
+ budget: z.ZodString;
112
+ amountField: z.ZodDefault<z.ZodString>;
113
+ currencyField: z.ZodDefault<z.ZodString>;
114
+ idempotencyHeader: z.ZodDefault<z.ZodString>;
115
+ reconcile: z.ZodObject<{
116
+ tool: z.ZodString;
117
+ args: z.ZodRecord<z.ZodString, z.ZodString>;
118
+ statusPath: z.ZodString;
119
+ identityPath: z.ZodDefault<z.ZodString>;
120
+ confirmed: z.ZodArray<z.ZodString>;
121
+ failed: z.ZodArray<z.ZodString>;
122
+ pending: z.ZodDefault<z.ZodArray<z.ZodString>>;
123
+ }, z.core.$strip>;
124
+ }, z.core.$strip>;
125
+ declare const OperationsSchema: z.ZodObject<{
126
+ database: z.ZodString;
127
+ budgets: z.ZodArray<z.ZodObject<{
128
+ id: z.ZodString;
129
+ currency: z.ZodString;
130
+ limit: z.ZodNumber;
131
+ }, z.core.$strip>>;
132
+ tools: z.ZodArray<z.ZodObject<{
133
+ tool: z.ZodString;
134
+ budget: z.ZodString;
135
+ amountField: z.ZodDefault<z.ZodString>;
136
+ currencyField: z.ZodDefault<z.ZodString>;
137
+ idempotencyHeader: z.ZodDefault<z.ZodString>;
138
+ reconcile: z.ZodObject<{
139
+ tool: z.ZodString;
140
+ args: z.ZodRecord<z.ZodString, z.ZodString>;
141
+ statusPath: z.ZodString;
142
+ identityPath: z.ZodDefault<z.ZodString>;
143
+ confirmed: z.ZodArray<z.ZodString>;
144
+ failed: z.ZodArray<z.ZodString>;
145
+ pending: z.ZodDefault<z.ZodArray<z.ZodString>>;
146
+ }, z.core.$strip>;
147
+ }, z.core.$strip>>;
148
+ }, z.core.$strip>;
149
+ export type OperationsConfig = z.infer<typeof OperationsSchema>;
150
+ export type OperationToolConfig = z.infer<typeof OperationToolSchema>;
106
151
  export declare const GatewayConfigSchema: z.ZodObject<{
107
152
  identity: z.ZodObject<{
108
153
  keyFile: z.ZodString;
@@ -136,6 +181,7 @@ export declare const GatewayConfigSchema: z.ZodObject<{
136
181
  json: "json";
137
182
  none: "none";
138
183
  }>>;
184
+ idempotencyHeader: z.ZodOptional<z.ZodString>;
139
185
  inputSchema: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
140
186
  }, z.core.$strip>>;
141
187
  }, z.core.$strip>;
@@ -177,6 +223,7 @@ export declare const GatewayConfigSchema: z.ZodObject<{
177
223
  json: "json";
178
224
  none: "none";
179
225
  }>>;
226
+ idempotencyHeader: z.ZodOptional<z.ZodString>;
180
227
  inputSchema: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
181
228
  }, z.core.$strip>>;
182
229
  }, z.core.$strip>;
@@ -202,6 +249,44 @@ export declare const GatewayConfigSchema: z.ZodObject<{
202
249
  optional: z.ZodDefault<z.ZodBoolean>;
203
250
  }, z.core.$strip>>>;
204
251
  precommit: z.ZodDefault<z.ZodArray<z.ZodString>>;
252
+ approvals: z.ZodOptional<z.ZodObject<{
253
+ trustedKeys: z.ZodArray<z.ZodString>;
254
+ usedDir: z.ZodString;
255
+ maxLifetimeSeconds: z.ZodOptional<z.ZodNumber>;
256
+ tools: z.ZodArray<z.ZodObject<{
257
+ tool: z.ZodString;
258
+ minApprovers: z.ZodDefault<z.ZodUnion<readonly [z.ZodLiteral<1>, z.ZodLiteral<2>]>>;
259
+ fields: z.ZodOptional<z.ZodObject<{
260
+ amount: z.ZodOptional<z.ZodString>;
261
+ currency: z.ZodOptional<z.ZodString>;
262
+ beneficiary: z.ZodOptional<z.ZodString>;
263
+ }, z.core.$strip>>;
264
+ }, z.core.$strip>>;
265
+ }, z.core.$strip>>;
266
+ operations: z.ZodOptional<z.ZodObject<{
267
+ database: z.ZodString;
268
+ budgets: z.ZodArray<z.ZodObject<{
269
+ id: z.ZodString;
270
+ currency: z.ZodString;
271
+ limit: z.ZodNumber;
272
+ }, z.core.$strip>>;
273
+ tools: z.ZodArray<z.ZodObject<{
274
+ tool: z.ZodString;
275
+ budget: z.ZodString;
276
+ amountField: z.ZodDefault<z.ZodString>;
277
+ currencyField: z.ZodDefault<z.ZodString>;
278
+ idempotencyHeader: z.ZodDefault<z.ZodString>;
279
+ reconcile: z.ZodObject<{
280
+ tool: z.ZodString;
281
+ args: z.ZodRecord<z.ZodString, z.ZodString>;
282
+ statusPath: z.ZodString;
283
+ identityPath: z.ZodDefault<z.ZodString>;
284
+ confirmed: z.ZodArray<z.ZodString>;
285
+ failed: z.ZodArray<z.ZodString>;
286
+ pending: z.ZodDefault<z.ZodArray<z.ZodString>>;
287
+ }, z.core.$strip>;
288
+ }, z.core.$strip>>;
289
+ }, z.core.$strip>>;
205
290
  revokedGrants: z.ZodOptional<z.ZodString>;
206
291
  capture: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
207
292
  args: z.ZodOptional<z.ZodObject<{
package/dist/config.js CHANGED
@@ -22,6 +22,8 @@ const RestToolSchema = z.object({
22
22
  query: z.array(z.string().min(1)).optional(),
23
23
  /** "none" sends no body even on POST */
24
24
  body: z.enum(["json", "none"]).default("json"),
25
+ /** The gateway supplies its durable operation key in this header; callers cannot choose or override it. */
26
+ idempotencyHeader: z.string().regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/).optional(),
25
27
  /** the JSON Schema the agent sees; default accepts any object */
26
28
  inputSchema: z.record(z.string(), z.unknown()).default({ type: "object" }),
27
29
  });
@@ -64,6 +66,67 @@ const FactSchema = z.object({
64
66
  /** when true and a "$args.<key>" the template needs is absent from the call, the lookup is skipped and the fact is simply not present */
65
67
  optional: z.boolean().default(false),
66
68
  });
69
+ /** Signed human approvals are independent of Cedar: an approving artifact binds the whole call and is used once. */
70
+ const ApprovalsSchema = z.object({
71
+ trustedKeys: z.array(z.string().min(1)).min(1),
72
+ usedDir: z.string().min(1),
73
+ /** The longest lifetime (expiresAt minus issuedAt) that the gateway accepts. The signer chooses the expiry, and this caps it. Default: 3600. */
74
+ maxLifetimeSeconds: z.number().int().positive().optional(),
75
+ tools: z.array(z.object({
76
+ tool: z.string().min(1),
77
+ minApprovers: z.union([z.literal(1), z.literal(2)]).default(1),
78
+ /** Argument names carrying these values; omitted names default to amount, currency, and beneficiary. */
79
+ fields: z.object({ amount: z.string().min(1).optional(), currency: z.string().min(1).optional(), beneficiary: z.string().min(1).optional() }).optional(),
80
+ })).min(1).refine((tools) => new Set(tools.map((t) => t.tool)).size === tools.length, { message: "approval tool names must be unique" }),
81
+ });
82
+ /** Amounts and limits are integer minor units; one budget is shared by every principal and agent on this database. */
83
+ const OperationBudgetSchema = z.object({ id: z.string().min(1).max(128), currency: z.string().regex(/^[A-Z]{3}$/), limit: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER) });
84
+ const OperationReconcileSchema = z.object({
85
+ tool: z.string().min(1),
86
+ /** Only the gateway-derived idempotency key may be substituted. The agent's operation id never reaches a receipt, and reconciliation never takes new caller arguments. */
87
+ args: z.record(z.string(), z.string()).refine((args) => Object.values(args).every((v) => !v.startsWith("$") || v === "$operation.idempotencyKey"), { message: "reconciliation templates only support $operation.idempotencyKey" }),
88
+ statusPath: z.string().min(1).max(512).refine((path) => path.split(".").every((part) => part.length > 0), { message: "reconciliation statusPath must have nonempty dot-separated parts" }),
89
+ /** The provider record must echo this operation's idempotency key before it may close the reservation. */
90
+ identityPath: z.string().min(1).max(512).refine((path) => path.split(".").every((part) => part.length > 0), { message: "reconciliation identityPath must have nonempty dot-separated parts" }).default("idempotencyKey"),
91
+ confirmed: z.array(z.string().min(1).max(128)).min(1),
92
+ failed: z.array(z.string().min(1).max(128)).min(1),
93
+ pending: z.array(z.string().min(1)).default([]),
94
+ }).refine((r) => {
95
+ const statuses = [...r.confirmed, ...r.failed, ...(r.pending ?? [])];
96
+ return new Set(statuses).size === statuses.length;
97
+ }, { message: "reconciliation statuses must be distinct" });
98
+ const OperationToolSchema = z.object({
99
+ tool: z.string().min(1),
100
+ budget: z.string().min(1),
101
+ amountField: z.string().min(1).default("amount"),
102
+ currencyField: z.string().min(1).default("currency"),
103
+ idempotencyHeader: z.string().regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/).default("Idempotency-Key"),
104
+ reconcile: OperationReconcileSchema,
105
+ });
106
+ const OperationsSchema = z.object({
107
+ database: z.string().min(1),
108
+ budgets: z.array(OperationBudgetSchema).min(1),
109
+ tools: z.array(OperationToolSchema).min(1),
110
+ }).superRefine((operations, ctx) => {
111
+ const budgets = new Set();
112
+ for (const [i, budget] of operations.budgets.entries()) {
113
+ if (budgets.has(budget.id))
114
+ ctx.addIssue({ code: "custom", path: ["budgets", i, "id"], message: "duplicate operation budget" });
115
+ budgets.add(budget.id);
116
+ }
117
+ const tools = new Set();
118
+ for (const [i, tool] of operations.tools.entries()) {
119
+ if (tools.has(tool.tool))
120
+ ctx.addIssue({ code: "custom", path: ["tools", i, "tool"], message: "duplicate financial operation tool" });
121
+ tools.add(tool.tool);
122
+ if (!budgets.has(tool.budget))
123
+ ctx.addIssue({ code: "custom", path: ["tools", i, "budget"], message: "unknown operation budget" });
124
+ }
125
+ for (const [i, tool] of operations.tools.entries()) {
126
+ if (tools.has(tool.reconcile.tool))
127
+ ctx.addIssue({ code: "custom", path: ["tools", i, "reconcile", "tool"], message: "a reconciliation read cannot be a financial operation tool" });
128
+ }
129
+ });
67
130
  export const GatewayConfigSchema = z.object({
68
131
  identity: z.object({ keyFile: z.string() }),
69
132
  /** the upstream: an MCP server to spawn over stdio, an MCP URL to reach over Streamable HTTP with an optional bearer token from the environment, or a REST API described as tools */
@@ -80,6 +143,10 @@ export const GatewayConfigSchema = z.object({
80
143
  * authorization to the log and refuses the call if the log will not take it. Evidence then precedes the side effect.
81
144
  */
82
145
  precommit: z.array(z.string().min(1)).default([]),
146
+ /** Tools that require a signed, unexpired, single-use approval, in every mode; "*" covers all agent calls. */
147
+ approvals: ApprovalsSchema.optional(),
148
+ /** Durable idempotency, daily budget reservations, and provider reconciliation for financial operations. */
149
+ operations: OperationsSchema.optional(),
83
150
  /** a JSON file listing digests of revoked grant envelopes (`agent-custody revoke` appends to it); re-read whenever it changes, checked on every call */
84
151
  revokedGrants: z.string().min(1).optional(),
85
152
  /** private evidence: what the receipt file carries of each tool's arguments, result, and facts */
@@ -87,7 +154,7 @@ export const GatewayConfigSchema = z.object({
87
154
  /** the environment variable holding the 32-byte key (hex or base64) that encrypts withheld fields in mode encrypted; read at startup, never in the file */
88
155
  captureKeyEnv: z.string().min(1).optional(),
89
156
  /**
90
- * "enforce" (the default when absent) denies what the policy denies. "observe" forwards every call the grant allows and records the
157
+ * "enforce" (the default when absent) denies what the policy denies. "observe" forwards every call the grant and required human approval allow and records the
91
158
  * decision the policy would have made, with `enforced: false` on the receipt: the way to run a new policy against
92
159
  * real traffic before turning it on. A log that refuses a consequential call's authorization does not withhold the
93
160
  * call in observe mode; it is printed.
@@ -101,7 +168,8 @@ export const GatewayConfigSchema = z.object({
101
168
  }).refine(hasOneLog, oneLog).refine((c) => (c.upstream ? 1 : 0) + (c.upstreams ? 1 : 0) === 1, { message: "exactly one of upstream or upstreams is required" })
102
169
  // a key fetched from the log itself proves nothing about a log that is dishonest from the start, so a remote log that
103
170
  // gates consequential calls must have its keys pinned in the config (issue #99)
104
- .refine((c) => !c.log || !c.precommit.length || !!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" });
171
+ .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" })
172
+ .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" });
105
173
  /** Loads a config file and resolves every path relative to the file's directory. */
106
174
  export function loadConfig(path) {
107
175
  const cfg = GatewayConfigSchema.parse(JSON.parse(readFileSync(path, "utf8")));
@@ -117,6 +185,8 @@ export function loadConfig(path) {
117
185
  ...(cfg.logFile ? { logFile: r(cfg.logFile) } : {}),
118
186
  ...(cfg.log?.keys ? { log: { ...cfg.log, keys: cfg.log.keys.map(r) } } : {}),
119
187
  ...(cfg.revokedGrants ? { revokedGrants: r(cfg.revokedGrants) } : {}),
188
+ ...(cfg.approvals ? { approvals: { ...cfg.approvals, trustedKeys: cfg.approvals.trustedKeys.map(r), usedDir: r(cfg.approvals.usedDir) } } : {}),
189
+ ...(cfg.operations ? { operations: { ...cfg.operations, database: r(cfg.operations.database) } } : {}),
120
190
  };
121
191
  }
122
192
  export const SdkConfigSchema = z.object({
@@ -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 };