@agent-custody/receipts 0.6.18 → 0.7.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
@@ -1,12 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import { hostname, userInfo } from "node:os";
3
+ import { captureKeyFrom, getAt, pathText, restorePaths, setAt } from "./capture.js";
4
+ import { saltsFileFor } from "./retention.js";
3
5
  import { parseArgs } from "node:util";
4
- import { readFileSync, writeFileSync } from "node:fs";
6
+ import { closeSync, constants as fsConstants, existsSync, fchmodSync, openSync, readFileSync, writeFileSync, writeSync } from "node:fs";
5
7
  import { dirname, resolve } from "node:path";
6
8
  import { loadConfig, loadSdkConfig } from "./config.js";
7
- import { generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
8
- import { createDelegation, decodeDelegation, delegateFrom } from "./delegation.js";
9
- import { createGateway, createGatewayHost, serveStdio } from "./gateway.js";
9
+ import { dsseVerify, generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
10
+ import { createDelegation, decodeDelegation, delegateFrom, grantDigest } from "./delegation.js";
11
+ import { createGateway, createGatewayHost, serveStdio, writeRevokedGrants } from "./gateway.js";
10
12
  import { postgresResolver, serveLog } from "./log-sink.js";
11
13
  import { importLogFile, PostgresTenancy } from "./log-store.js";
12
14
  import { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoints.js";
@@ -14,6 +16,7 @@ import { connectSigner, fetchLogKeys, localSigner, serveSigner } from "./signer.
14
16
  import { fetchWitnessKeys, Witness } from "./witness.js";
15
17
  import { checkLog, formatLogCheck } from "./log-check.js";
16
18
  import { serveHttp } from "./gateway-http.js";
19
+ import { serveA2a } from "./a2a.js";
17
20
  import { PortalStore, sendFollowUps, servePortal } from "./portal.js";
18
21
  import { exportLog, formatExport } from "./log-export.js";
19
22
  import { CheckpointPublisher, fileResolver } from "./log-sink.js";
@@ -39,6 +42,10 @@ const USAGE = `agent-custody <command>
39
42
  --agent-key names the agent's own key in the grant, so the agent may delegate
40
43
  delegate --key <agent.key> --parent <grant.json> --agent <sub-agent> --scopes <a,b> [--ttl-hours N] [--agent-key <sub.pub>] --out <file>
41
44
  a narrower grant for a sub-agent, signed by the agent the parent names; the parent travels inside
45
+ reveal <bundle> --capture-key-env NAME --issuer-key <pub> [--out <file>] [--include-salts] the values a receipt withheld (capture mode encrypted), as a disclosure file
46
+ for verify --disclose; needs the customer's capture key
47
+ revoke --config <gateway.json> --grant <grant.json> revokes a grant: its digest goes into the config's revokedGrants file, every
48
+ session under it or under a grant delegated from it refuses its next call, and no new session opens for them
42
49
  gateway --config <gateway.json> [--http [--port 8790] [--host 127.0.0.1] [--idle-minutes 30]]
43
50
  stdio: one gateway for the grant the config names. --http: one shared gateway, MCP over
44
51
  Streamable HTTP at /mcp, each connection presenting its own grant as Authorization: Bearer
@@ -175,10 +182,45 @@ async function main(argv) {
175
182
  console.log(`delegated to ${chain.agent}: scopes [${chain.scopes.join(", ")}] until ${chain.expiresAt}, under ${decodeDelegation(parent).agent}'s grant from ${chain.principal}`);
176
183
  return 0;
177
184
  }
185
+ case "revoke": {
186
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, grant: { type: "string" } } });
187
+ if (!values.config || !values.grant)
188
+ throw new Error("revoke needs --config and --grant");
189
+ const cfg = loadConfig(values.config);
190
+ if (!cfg.revokedGrants)
191
+ throw new Error("revoke needs revokedGrants in the config: the file the gateway re-reads on every call");
192
+ const envelope = JSON.parse(readFileSync(values.grant, "utf8"));
193
+ const chain = decodeDelegation(envelope);
194
+ if (!chain)
195
+ throw new Error(`${values.grant} is not a delegation grant`);
196
+ const digest = grantDigest(envelope);
197
+ const list = existsSync(cfg.revokedGrants) ? JSON.parse(readFileSync(cfg.revokedGrants, "utf8")) : [];
198
+ if (!list.includes(digest))
199
+ writeRevokedGrants(cfg.revokedGrants, [...list, digest]);
200
+ console.log(`revoked ${chain.agent}'s grant from ${chain.principal} (${digest.slice(0, 12)}…): ${cfg.revokedGrants} now lists ${list.includes(digest) ? list.length : list.length + 1} grant(s); a running gateway refuses it on its next call`);
201
+ return 0;
202
+ }
178
203
  case "gateway": {
179
- const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, http: { type: "boolean", default: false }, port: { type: "string", default: "8790" }, host: { type: "string", default: "127.0.0.1" }, "idle-minutes": { type: "string", default: "30" } } });
204
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, http: { type: "boolean", default: false }, a2a: { type: "boolean", default: false }, port: { type: "string", default: "8790" }, host: { type: "string", default: "127.0.0.1" }, "idle-minutes": { type: "string", default: "30" } } });
180
205
  if (!values.config)
181
206
  throw new Error("gateway needs --config");
207
+ if (values.a2a) {
208
+ // The gateway as an A2A agent: the config's one A2A upstream is what it fronts; the grant file is the default
209
+ // session, and a request may present its own grant in the same header the HTTP gateway takes.
210
+ const cfg = loadConfig(values.config);
211
+ const candidates = (cfg.upstreams ?? (cfg.upstream ? [cfg.upstream] : [])).filter((u) => "a2a" in u);
212
+ if (candidates.length !== 1)
213
+ throw new Error("gateway --a2a needs exactly one { a2a: ... } upstream in the config");
214
+ const a2a = candidates[0].a2a;
215
+ const host = await createGatewayHost(cfg);
216
+ const grant = cfg.grantFile ? JSON.parse(readFileSync(cfg.grantFile, "utf8")) : undefined;
217
+ const running = await serveA2a(host, a2a, { port: Number(values.port), host: values.host, ...(grant ? { grant } : {}) });
218
+ 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));
220
+ await running.close();
221
+ await host.close();
222
+ return 0;
223
+ }
182
224
  if (values.http) {
183
225
  const host = await createGatewayHost(loadConfig(values.config));
184
226
  const running = await serveHttp(host, { port: Number(values.port), host: values.host, idleMs: Number(values["idle-minutes"]) * 60_000 });
@@ -483,6 +525,8 @@ async function main(argv) {
483
525
  "stripe-secret-env": { type: "string" },
484
526
  "github-secret-env": { type: "string" },
485
527
  log: { type: "string" },
528
+ disclose: { type: "string" },
529
+ "capture-key-env": { type: "string" },
486
530
  json: { type: "boolean", default: false },
487
531
  },
488
532
  });
@@ -491,6 +535,8 @@ async function main(argv) {
491
535
  if (!file || issuerKeyFiles.length === 0)
492
536
  throw new Error("verify needs <bundle> --issuer-key (alias --gateway-key)");
493
537
  const bundle = JSON.parse(readFileSync(file, "utf8"));
538
+ const captureKey = values["capture-key-env"] ? captureKeyFrom(secretFrom(values["capture-key-env"])) : undefined;
539
+ const disclosed = values.disclose ? JSON.parse(readFileSync(values.disclose, "utf8")) : undefined;
494
540
  const fetchedLogKeys = values["log-url"] ? (await fetchLogKeys(values["log-url"])).keys : [];
495
541
  const logKeys = [...(values["log-key"] ?? []).map(loadPublicKey), ...fetchedLogKeys];
496
542
  const result = verifyBundle(bundle, {
@@ -501,10 +547,76 @@ async function main(argv) {
501
547
  ...(values["upstream-key"] ? { upstreamKeys: values["upstream-key"].map(loadPublicKey) } : {}),
502
548
  ...(values["stripe-secret-env"] || values["github-secret-env"] ? { providerSecrets: { ...(values["stripe-secret-env"] ? { stripe: secretFrom(values["stripe-secret-env"]) } : {}), ...(values["github-secret-env"] ? { github: secretFrom(values["github-secret-env"]) } : {}) } } : {}),
503
549
  ...(values.log ? { logFile: values.log } : {}),
550
+ ...(captureKey ? { captureKey } : {}),
551
+ ...(disclosed ? { disclosed } : {}),
504
552
  });
505
553
  console.log(values.json ? JSON.stringify(result, null, 2) : formatReport(result));
506
554
  return result.ok ? 0 : 1;
507
555
  }
556
+ case "reveal": {
557
+ // The values a receipt withheld, under the customer's key, as a disclosure file: hand it to a reviewer with the
558
+ // receipt, and `verify --disclose` recomputes every digest from it.
559
+ const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { "capture-key-env": { type: "string" }, "issuer-key": { type: "string", multiple: true }, out: { type: "string" }, "include-salts": { type: "boolean" } } });
560
+ const file = positionals[0];
561
+ if (!file || !values["capture-key-env"] || !values["issuer-key"]?.length)
562
+ throw new Error("reveal needs <bundle> --capture-key-env NAME --issuer-key <pub> [--out disclosure.json] [--include-salts]");
563
+ const key = captureKeyFrom(secretFrom(values["capture-key-env"]));
564
+ const bundle = JSON.parse(readFileSync(file, "utf8"));
565
+ // only the issuer's own statement is decrypted: a bundle someone assembled around another receipt's ciphertexts is refused before any value comes back
566
+ const signed = dsseVerify(bundle.envelope, values["issuer-key"].map((f) => loadPublicKey(f)));
567
+ if (!signed.ok)
568
+ throw new Error(`reveal: the bundle is not signed by the issuer key given (${signed.error}); nothing is revealed`);
569
+ const p = signed.payload.predicate;
570
+ // Every withheld path the key reveals goes into the disclosure at its own path, value and salt. A path withheld
571
+ // as a digest only carries no value to reveal, and its salt is not written unless asked for (--include-salts):
572
+ // a salt beside no value would hand a reviewer the means to confirm guesses, and a file that carries one does
573
+ // not verify until the holder fills in the value.
574
+ const back = restorePaths(p, p.capture, undefined, key);
575
+ for (const x of back.problems)
576
+ throw new Error(x.error);
577
+ // the id comes from the bundle: it is checked before it becomes part of a path
578
+ const saltsFile = saltsFileFor(dirname(file), p.receiptId);
579
+ const kept = values["include-salts"] && existsSync(saltsFile) ? JSON.parse(readFileSync(saltsFile, "utf8")).salts ?? {} : {};
580
+ let disclosure = { receiptId: p.receiptId };
581
+ let saltsWritten = 0;
582
+ for (const path of p.capture?.withheld ?? []) {
583
+ const k = JSON.stringify(path);
584
+ if (back.restored.has(k))
585
+ disclosure = setAt(disclosure, path, { $custody: "disclosed", salt: back.salts.get(k), value: back.values.get(k) });
586
+ else if (kept[k]) {
587
+ disclosure = setAt(disclosure, path, { $custody: "disclosed", salt: kept[k] });
588
+ saltsWritten++;
589
+ }
590
+ }
591
+ // a value withheld without its value cannot be revealed by anyone but its holder; one encrypted under another key is a different matter, said separately
592
+ const foreign = back.missing.filter((w) => getAt(p, w)?.$custody === "encrypted");
593
+ const notRevealed = back.missing.filter((w) => !foreign.includes(w)).map(pathText);
594
+ const foreignNote = foreign.length ? ` Encrypted under key ${String(getAt(p, foreign[0]).keyid).slice(0, 12)}…, not the one given: ${foreign.map(pathText).join(", ")}.` : "";
595
+ if (foreign.length && back.restored.size === 0)
596
+ throw new Error(`reveal: nothing revealed; the values are encrypted under key ${String(getAt(p, foreign[0]).keyid).slice(0, 12)}…, not the one given`);
597
+ const text = JSON.stringify(disclosure, null, 2);
598
+ const how = saltsWritten ? `; their salts are written in the file for the holder to add \"value\" beside, and the file does not verify until then: do not hand it over unfinished` : values["include-salts"] ? ` (no salts file at ${saltsFile})` : `; --include-salts writes their salts from ${saltsFile} for the holder to complete`;
599
+ const note = (notRevealed.length ? ` Not revealed, withheld without a value: ${notRevealed.join(", ")}; only the party that holds them can disclose them${how}.` : "") + foreignNote;
600
+ if (values.out) {
601
+ // decrypted values and salts: the owner's alone, whatever the umask, whatever mode a file already there had,
602
+ // and never through a symlink someone left at that name
603
+ const fd = openSync(values.out, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC | fsConstants.O_NOFOLLOW, 0o600);
604
+ try {
605
+ fchmodSync(fd, 0o600);
606
+ writeSync(fd, text);
607
+ }
608
+ finally {
609
+ closeSync(fd);
610
+ }
611
+ console.log(`disclosure for receipt ${p.receiptId} written to ${values.out}; verify it with --disclose ${values.out}.${note}`);
612
+ }
613
+ else {
614
+ console.log(text);
615
+ if (note)
616
+ console.error(note.trim());
617
+ }
618
+ return 0;
619
+ }
508
620
  case "audit": {
509
621
  const { values } = parseArgs({
510
622
  args: rest,
package/dist/config.d.ts CHANGED
@@ -45,6 +45,15 @@ declare const RestUpstreamSchema: z.ZodObject<{
45
45
  }, z.core.$strip>>;
46
46
  }, z.core.$strip>;
47
47
  export type RestUpstreamConfig = z.infer<typeof RestUpstreamSchema>;
48
+ /** Another agent, reached over the A2A protocol, as an upstream. Its agent card is fetched at startup; the gateway offers `<prefix>.send`, which delegates a task to it, and `<prefix>.card`, a read of the card for use as a fact. */
49
+ declare const A2aUpstreamSchema: z.ZodObject<{
50
+ url: z.ZodString;
51
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
52
+ headerEnv: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
53
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
54
+ prefix: z.ZodDefault<z.ZodString>;
55
+ }, z.core.$strip>;
56
+ export type A2aUpstreamConfig = z.infer<typeof A2aUpstreamSchema>;
48
57
  declare const UpstreamSchema: z.ZodUnion<readonly [z.ZodObject<{
49
58
  command: z.ZodString;
50
59
  args: z.ZodDefault<z.ZodArray<z.ZodString>>;
@@ -77,6 +86,14 @@ declare const UpstreamSchema: z.ZodUnion<readonly [z.ZodObject<{
77
86
  inputSchema: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
78
87
  }, z.core.$strip>>;
79
88
  }, z.core.$strip>;
89
+ }, z.core.$strip>, z.ZodObject<{
90
+ a2a: z.ZodObject<{
91
+ url: z.ZodString;
92
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
93
+ headerEnv: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
94
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
95
+ prefix: z.ZodDefault<z.ZodString>;
96
+ }, z.core.$strip>;
80
97
  }, z.core.$strip>]>;
81
98
  export type UpstreamConfig = z.infer<typeof UpstreamSchema>;
82
99
  declare const FactSchema: z.ZodObject<{
@@ -122,6 +139,14 @@ export declare const GatewayConfigSchema: z.ZodObject<{
122
139
  inputSchema: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
123
140
  }, z.core.$strip>>;
124
141
  }, z.core.$strip>;
142
+ }, z.core.$strip>, z.ZodObject<{
143
+ a2a: z.ZodObject<{
144
+ url: z.ZodString;
145
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
146
+ headerEnv: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
147
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
148
+ prefix: z.ZodDefault<z.ZodString>;
149
+ }, z.core.$strip>;
125
150
  }, z.core.$strip>]>>;
126
151
  upstreams: z.ZodOptional<z.ZodArray<z.ZodIntersection<z.ZodUnion<readonly [z.ZodObject<{
127
152
  command: z.ZodString;
@@ -155,6 +180,14 @@ export declare const GatewayConfigSchema: z.ZodObject<{
155
180
  inputSchema: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
156
181
  }, z.core.$strip>>;
157
182
  }, z.core.$strip>;
183
+ }, z.core.$strip>, z.ZodObject<{
184
+ a2a: z.ZodObject<{
185
+ url: z.ZodString;
186
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
187
+ headerEnv: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
188
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
189
+ prefix: z.ZodDefault<z.ZodString>;
190
+ }, z.core.$strip>;
158
191
  }, z.core.$strip>]>, z.ZodObject<{
159
192
  name: z.ZodString;
160
193
  }, z.core.$strip>>>>;
@@ -169,6 +202,34 @@ export declare const GatewayConfigSchema: z.ZodObject<{
169
202
  optional: z.ZodDefault<z.ZodBoolean>;
170
203
  }, z.core.$strip>>>;
171
204
  precommit: z.ZodDefault<z.ZodArray<z.ZodString>>;
205
+ revokedGrants: z.ZodOptional<z.ZodString>;
206
+ capture: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
207
+ args: z.ZodOptional<z.ZodObject<{
208
+ mode: z.ZodEnum<{
209
+ clear: "clear";
210
+ digest: "digest";
211
+ encrypted: "encrypted";
212
+ }>;
213
+ clear: z.ZodOptional<z.ZodArray<z.ZodString>>;
214
+ }, z.core.$strip>>;
215
+ result: z.ZodOptional<z.ZodObject<{
216
+ mode: z.ZodEnum<{
217
+ clear: "clear";
218
+ digest: "digest";
219
+ encrypted: "encrypted";
220
+ }>;
221
+ clear: z.ZodOptional<z.ZodArray<z.ZodString>>;
222
+ }, z.core.$strip>>;
223
+ facts: z.ZodOptional<z.ZodObject<{
224
+ mode: z.ZodEnum<{
225
+ clear: "clear";
226
+ digest: "digest";
227
+ encrypted: "encrypted";
228
+ }>;
229
+ clear: z.ZodOptional<z.ZodArray<z.ZodString>>;
230
+ }, z.core.$strip>>;
231
+ }, z.core.$strip>>>;
232
+ captureKeyEnv: z.ZodOptional<z.ZodString>;
172
233
  mode: z.ZodOptional<z.ZodEnum<{
173
234
  enforce: "enforce";
174
235
  observe: "observe";
@@ -180,6 +241,8 @@ export declare const GatewayConfigSchema: z.ZodObject<{
180
241
  tokenEnv: z.ZodOptional<z.ZodString>;
181
242
  hashOnly: z.ZodOptional<z.ZodBoolean>;
182
243
  timeoutMs: z.ZodOptional<z.ZodNumber>;
244
+ keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
245
+ logId: z.ZodOptional<z.ZodString>;
183
246
  }, z.core.$strip>>;
184
247
  otel: z.ZodOptional<z.ZodObject<{
185
248
  url: z.ZodString;
@@ -217,6 +280,8 @@ export declare const SdkConfigSchema: z.ZodObject<{
217
280
  tokenEnv: z.ZodOptional<z.ZodString>;
218
281
  hashOnly: z.ZodOptional<z.ZodBoolean>;
219
282
  timeoutMs: z.ZodOptional<z.ZodNumber>;
283
+ keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
284
+ logId: z.ZodOptional<z.ZodString>;
220
285
  }, z.core.$strip>>;
221
286
  otel: z.ZodOptional<z.ZodObject<{
222
287
  url: z.ZodString;
@@ -232,6 +297,33 @@ export declare const SdkConfigSchema: z.ZodObject<{
232
297
  host: z.ZodOptional<z.ZodString>;
233
298
  }, z.core.$strip>>;
234
299
  framework: z.ZodOptional<z.ZodString>;
300
+ capture: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
301
+ args: z.ZodOptional<z.ZodObject<{
302
+ mode: z.ZodEnum<{
303
+ clear: "clear";
304
+ digest: "digest";
305
+ encrypted: "encrypted";
306
+ }>;
307
+ clear: z.ZodOptional<z.ZodArray<z.ZodString>>;
308
+ }, z.core.$strip>>;
309
+ result: z.ZodOptional<z.ZodObject<{
310
+ mode: z.ZodEnum<{
311
+ clear: "clear";
312
+ digest: "digest";
313
+ encrypted: "encrypted";
314
+ }>;
315
+ clear: z.ZodOptional<z.ZodArray<z.ZodString>>;
316
+ }, z.core.$strip>>;
317
+ facts: z.ZodOptional<z.ZodObject<{
318
+ mode: z.ZodEnum<{
319
+ clear: "clear";
320
+ digest: "digest";
321
+ encrypted: "encrypted";
322
+ }>;
323
+ clear: z.ZodOptional<z.ZodArray<z.ZodString>>;
324
+ }, z.core.$strip>>;
325
+ }, z.core.$strip>>>;
326
+ captureKeyEnv: z.ZodOptional<z.ZodString>;
235
327
  }, z.core.$strip>;
236
328
  export type SdkConfig = z.infer<typeof SdkConfigSchema>;
237
329
  export declare function loadSdkConfig(path: string): SdkConfig;
package/dist/config.js CHANGED
@@ -2,12 +2,16 @@ import { z } from "zod";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { dirname, resolve } from "node:path";
4
4
  /** Where receipts are logged: a local file, or a log reached over HTTP whose bearer token comes from an environment variable. */
5
- const LogSchema = z.object({ url: z.string().url(), tokenEnv: z.string().min(1).optional(), /** send leaf hashes only; the log never holds the receipt. Use it for any log run by someone else */ hashOnly: z.boolean().optional(), /** milliseconds one append may take before the log counts as unreachable; default 10000 */ timeoutMs: z.number().int().positive().optional() });
5
+ const LogSchema = z.object({ url: z.string().url(), tokenEnv: z.string().min(1).optional(), /** send leaf hashes only; the log never holds the receipt. Use it for any log run by someone else */ hashOnly: z.boolean().optional(), /** milliseconds one append may take before the log counts as unreachable; default 10000 */ timeoutMs: z.number().int().positive().optional(), /** the log's public key files; every append's answer is checked against them before a call is forwarded. Without them the log's key document is fetched from the log itself on first use and pinned, which catches a log that turns dishonest later but not one dishonest from the start; required with precommit. */ keys: z.array(z.string().min(1)).optional(), /** the id the log must write into every tree head; an answer for another log is refused */ logId: z.string().min(1).optional() });
6
6
  const oneLog = { message: "exactly one of logFile or log is required" };
7
7
  /** Optional OpenTelemetry export: every receipt also becomes a span at this OTLP/HTTP collector, after it is issued. Never on the evidence path. */
8
8
  const OtelSchema = z.object({ url: z.string().url(), headersEnv: z.record(z.string(), z.string().min(1)).optional(), serviceName: z.string().min(1).optional() });
9
9
  const SplunkSchema = z.object({ url: z.string().url(), tokenEnv: z.string().min(1), index: z.string().min(1).optional(), source: z.string().min(1).optional(), sourcetype: z.string().min(1).optional(), host: z.string().min(1).optional() });
10
10
  const hasOneLog = (c) => (c.logFile ? 1 : 0) + (c.log ? 1 : 0) === 1;
11
+ /** What a receipt carries of one side of a call: everything, commitments only, or commitments with the value encrypted under the customer's key; `clear` names the top-level fields kept in clear either way. */
12
+ const CaptureSideSchema = z.object({ mode: z.enum(["clear", "digest", "encrypted"]), clear: z.array(z.string().min(1)).optional() });
13
+ /** Per tool (or "*"): how the arguments, the result, and the facts are captured. Digests and signatures are always over the whole call. */
14
+ const CaptureSchema = z.record(z.string().min(1), z.object({ args: CaptureSideSchema.optional(), result: CaptureSideSchema.optional(), facts: CaptureSideSchema.optional() }));
11
15
  /** One REST endpoint offered to the agent as a tool. `{name}` segments in the path come from the call's arguments; the rest go to the query on GET and DELETE, or to a JSON body otherwise. */
12
16
  const RestToolSchema = z.object({
13
17
  name: z.string().min(1),
@@ -30,10 +34,23 @@ const RestUpstreamSchema = z.object({
30
34
  timeoutMs: z.number().int().positive().default(30_000),
31
35
  tools: z.array(RestToolSchema).min(1),
32
36
  });
37
+ /** Another agent, reached over the A2A protocol, as an upstream. Its agent card is fetched at startup; the gateway offers `<prefix>.send`, which delegates a task to it, and `<prefix>.card`, a read of the card for use as a fact. */
38
+ const A2aUpstreamSchema = z.object({
39
+ /** the agent's base URL (its card is at /.well-known/agent-card.json) or the card's URL itself */
40
+ url: z.string().url(),
41
+ headers: z.record(z.string(), z.string()).optional(),
42
+ /** header name to environment variable, as for a REST upstream */
43
+ headerEnv: z.record(z.string(), z.string().min(1)).optional(),
44
+ /** how long one delegated task may take, streamed or not; default two minutes */
45
+ timeoutMs: z.number().int().positive().default(120_000),
46
+ /** the tool names are `<prefix>.send` and `<prefix>.card`; default "a2a". Give each A2A upstream its own prefix. */
47
+ prefix: z.string().min(1).regex(/^[A-Za-z0-9_-]+$/).default("a2a"),
48
+ });
33
49
  const UpstreamSchema = z.union([
34
50
  z.object({ command: z.string(), args: z.array(z.string()).default([]), env: z.record(z.string(), z.string()).optional() }),
35
51
  z.object({ url: z.string().url(), tokenEnv: z.string().min(1).optional() }),
36
52
  z.object({ rest: RestUpstreamSchema }),
53
+ z.object({ a2a: A2aUpstreamSchema }),
37
54
  ]);
38
55
  const FactSchema = z.object({
39
56
  /** key under context.facts */
@@ -63,6 +80,12 @@ export const GatewayConfigSchema = z.object({
63
80
  * authorization to the log and refuses the call if the log will not take it. Evidence then precedes the side effect.
64
81
  */
65
82
  precommit: z.array(z.string().min(1)).default([]),
83
+ /** 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
+ revokedGrants: z.string().min(1).optional(),
85
+ /** private evidence: what the receipt file carries of each tool's arguments, result, and facts */
86
+ capture: CaptureSchema.optional(),
87
+ /** 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
+ captureKeyEnv: z.string().min(1).optional(),
66
89
  /**
67
90
  * "enforce" (the default when absent) denies what the policy denies. "observe" forwards every call the grant allows and records the
68
91
  * decision the policy would have made, with `enforced: false` on the receipt: the way to run a new policy against
@@ -75,7 +98,10 @@ export const GatewayConfigSchema = z.object({
75
98
  log: LogSchema.optional(),
76
99
  otel: OtelSchema.optional(),
77
100
  splunk: SplunkSchema.optional(),
78
- }).refine(hasOneLog, oneLog).refine((c) => (c.upstream ? 1 : 0) + (c.upstreams ? 1 : 0) === 1, { message: "exactly one of upstream or upstreams is required" });
101
+ }).refine(hasOneLog, oneLog).refine((c) => (c.upstream ? 1 : 0) + (c.upstreams ? 1 : 0) === 1, { message: "exactly one of upstream or upstreams is required" })
102
+ // a key fetched from the log itself proves nothing about a log that is dishonest from the start, so a remote log that
103
+ // 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" });
79
105
  /** Loads a config file and resolves every path relative to the file's directory. */
80
106
  export function loadConfig(path) {
81
107
  const cfg = GatewayConfigSchema.parse(JSON.parse(readFileSync(path, "utf8")));
@@ -89,6 +115,8 @@ export function loadConfig(path) {
89
115
  policyFile: r(cfg.policyFile),
90
116
  receiptsDir: r(cfg.receiptsDir),
91
117
  ...(cfg.logFile ? { logFile: r(cfg.logFile) } : {}),
118
+ ...(cfg.log?.keys ? { log: { ...cfg.log, keys: cfg.log.keys.map(r) } } : {}),
119
+ ...(cfg.revokedGrants ? { revokedGrants: r(cfg.revokedGrants) } : {}),
92
120
  };
93
121
  }
94
122
  export const SdkConfigSchema = z.object({
@@ -107,6 +135,9 @@ export const SdkConfigSchema = z.object({
107
135
  splunk: SplunkSchema.optional(),
108
136
  /** free-text label of the host framework, e.g. "claude-code", "openai-agents" */
109
137
  framework: z.string().optional(),
138
+ /** private evidence, as for the gateway */
139
+ capture: CaptureSchema.optional(),
140
+ captureKeyEnv: z.string().min(1).optional(),
110
141
  }).refine(hasOneLog, oneLog);
111
142
  export function loadSdkConfig(path) {
112
143
  const cfg = SdkConfigSchema.parse(JSON.parse(readFileSync(path, "utf8")));
@@ -118,5 +149,6 @@ export function loadSdkConfig(path) {
118
149
  ...(cfg.policyFile ? { policyFile: r(cfg.policyFile) } : {}),
119
150
  receiptsDir: r(cfg.receiptsDir),
120
151
  ...(cfg.logFile ? { logFile: r(cfg.logFile) } : {}),
152
+ ...(cfg.log?.keys ? { log: { ...cfg.log, keys: cfg.log.keys.map(r) } } : {}),
121
153
  };
122
154
  }
package/dist/crypto.d.ts CHANGED
@@ -2,8 +2,8 @@ import type { KeyObject } from "node:crypto";
2
2
  /** Deterministic JSON: sorted keys, no whitespace, undefined dropped. Not full RFC 8785, but stable across runs. */
3
3
  export declare function canonicalize(value: unknown): string;
4
4
  export declare function sha256Hex(data: string | Uint8Array): string;
5
- /** sha256 over the canonical JSON of a value. */
6
- export declare function digestOf(value: unknown): string;
5
+ /** sha256 over the canonical JSON of a value; with a salt (hex), over salt || canonical, so a digest over withheld values confirms no guess (issue #126). */
6
+ export declare function digestOf(value: unknown, salt?: string): string;
7
7
  export interface PublicKeyRef {
8
8
  publicKey: KeyObject;
9
9
  keyid: string;
package/dist/crypto.js CHANGED
@@ -10,7 +10,9 @@ function sortKeys(v) {
10
10
  if (Array.isArray(v))
11
11
  return v.map(sortKeys);
12
12
  if (v && typeof v === "object") {
13
- const out = {};
13
+ // A null-prototype object: an own property named __proto__ (which JSON.parse produces) stays a property here,
14
+ // where on a plain object the assignment would set the prototype and the key would vanish from the digest.
15
+ const out = Object.create(null);
14
16
  for (const k of Object.keys(v).sort()) {
15
17
  const x = v[k];
16
18
  if (x !== undefined)
@@ -23,9 +25,10 @@ function sortKeys(v) {
23
25
  export function sha256Hex(data) {
24
26
  return createHash("sha256").update(data).digest("hex");
25
27
  }
26
- /** sha256 over the canonical JSON of a value. */
27
- export function digestOf(value) {
28
- return sha256Hex(canonicalize(value));
28
+ /** sha256 over the canonical JSON of a value; with a salt (hex), over salt || canonical, so a digest over withheld values confirms no guess (issue #126). */
29
+ export function digestOf(value, salt) {
30
+ const canonical = Buffer.from(canonicalize(value), "utf8");
31
+ return sha256Hex(salt ? Buffer.concat([Buffer.from(salt, "hex"), canonical]) : canonical);
29
32
  }
30
33
  /** keyid = sha256 of the SPKI DER encoding of the public key. */
31
34
  export function keyidOf(publicKey) {
@@ -54,6 +54,13 @@ export type DelegationVerifyResult = {
54
54
  /** Verifies a grant, walking its chain to a grant signed by one of the trusted principal keys. */
55
55
  export declare function verifyDelegation(env: Envelope, trustedPrincipals: PublicKeyRef[], depth?: number): DelegationVerifyResult;
56
56
  /** True when `at` (ISO) lies inside the grant's validity window. */
57
+ /**
58
+ * What names a grant for revocation: sha256 over the payload its signature covers. Extra signatures or envelope fields
59
+ * leave it unchanged, so an agent cannot get a revoked grant past the list by repacking the envelope.
60
+ */
61
+ export declare function grantDigest(env: Envelope): string;
62
+ /** The digest of every link from this grant up to the principal's own, leaf first: revoking any link revokes the grants below it. */
63
+ export declare function grantChainDigests(env: Envelope): string[];
57
64
  export declare function delegationValidAt(d: Delegation, at: string): boolean;
58
65
  /** "principal → agent → sub-agent", for reports. */
59
66
  export declare function describeChain(chain: Delegation[]): string;
@@ -6,7 +6,7 @@
6
6
  // parent's, and the principal is the same throughout. The receipt then names the sub-agent as the agent and the
7
7
  // principal as the principal, exactly as with a direct grant, and the whole chain travels inside the receipt.
8
8
  import { z } from "zod";
9
- import { dsseSign, dsseVerify, publicKeyFromPem } from "./crypto.js";
9
+ import { dsseSign, dsseVerify, publicKeyFromPem, sha256Hex } from "./crypto.js";
10
10
  export const DELEGATION_TYPE = "application/vnd.agent-custody.delegation+json";
11
11
  /** the longest chain a verifier walks: the principal's grant and up to three delegations below it */
12
12
  export const MAX_DELEGATION_DEPTH = 4;
@@ -115,6 +115,20 @@ export function verifyDelegation(env, trustedPrincipals, depth = 1) {
115
115
  return { ok: true, delegation: d, keyid: up.keyid, chain: [...up.chain, d] };
116
116
  }
117
117
  /** True when `at` (ISO) lies inside the grant's validity window. */
118
+ /**
119
+ * What names a grant for revocation: sha256 over the payload its signature covers. Extra signatures or envelope fields
120
+ * leave it unchanged, so an agent cannot get a revoked grant past the list by repacking the envelope.
121
+ */
122
+ export function grantDigest(env) {
123
+ return sha256Hex(Buffer.from(env.payload, "base64"));
124
+ }
125
+ /** The digest of every link from this grant up to the principal's own, leaf first: revoking any link revokes the grants below it. */
126
+ export function grantChainDigests(env) {
127
+ const out = [];
128
+ for (let e = env; e && out.length <= MAX_DELEGATION_DEPTH; e = decodeDelegation(e)?.parent)
129
+ out.push(grantDigest(e));
130
+ return out;
131
+ }
118
132
  export function delegationValidAt(d, at) {
119
133
  const t = Date.parse(at);
120
134
  return t >= Date.parse(d.issuedAt) && t <= Date.parse(d.expiresAt);
@@ -96,6 +96,12 @@ export async function serveHttp(host, opts) {
96
96
  const sid = req.headers["mcp-session-id"];
97
97
  const existing = typeof sid === "string" ? sessions.get(sid) : undefined;
98
98
  if (existing) {
99
+ // the grant is checked again on every request of a session; an expired or revoked one ends the session here
100
+ const problem = existing.gateway.grantProblem();
101
+ if (problem) {
102
+ await closeSession(sid, `grant ${problem}`);
103
+ return rpcError(res, 403, `the grant for this session ${problem}; initialize again with a current grant`);
104
+ }
99
105
  existing.lastSeen = Date.now();
100
106
  const body = req.method === "POST" ? await readBody(req) : undefined;
101
107
  await existing.transport.handleRequest(req, res, body);
@@ -118,9 +124,15 @@ export async function serveHttp(host, opts) {
118
124
  const server = createServer((req, res) => void handler(req, res));
119
125
  const reaper = setInterval(() => {
120
126
  const cutoff = Date.now() - idleMs;
121
- for (const [id, s] of sessions)
127
+ for (const [id, s] of sessions) {
122
128
  if (s.lastSeen < cutoff)
123
129
  void closeSession(id, "idle");
130
+ else {
131
+ const problem = s.gateway.grantProblem();
132
+ if (problem)
133
+ void closeSession(id, `grant ${problem}`);
134
+ }
135
+ }
124
136
  }, Math.min(idleMs, 60_000));
125
137
  reaper.unref?.();
126
138
  await new Promise((resolve) => server.listen(opts.port, bind, resolve));
package/dist/gateway.d.ts CHANGED
@@ -22,6 +22,10 @@ export interface CallParams {
22
22
  export interface Gateway {
23
23
  agentId: string;
24
24
  delegation: Delegation;
25
+ /** sha256 over the grant's signed payload (`grantDigest` in delegation.ts): what `revoke` names */
26
+ grantDigest: string;
27
+ /** null while the grant is in force at `at` (default now); otherwise why it is not: "has expired", "is not yet valid", "has been revoked" */
28
+ grantProblem(at?: string): string | null;
25
29
  listTools(): Promise<Tool[]>;
26
30
  handleCall(params: CallParams): Promise<CallToolResult>;
27
31
  close(): Promise<void>;
@@ -46,9 +50,15 @@ export interface GatewayHost {
46
50
  keyid: string;
47
51
  /** a session for this grant: the grant is verified against the trusted principal keys and its validity window first */
48
52
  open(grantEnvelope: Envelope): Gateway;
53
+ /** revokes a grant by its digest: every session under it refuses its next call, and no new session opens for it. Written to the config's revokedGrants file when there is one. */
54
+ revoke(grantDigest: string): void;
55
+ /** the digests revoked so far */
56
+ revoked(): string[];
49
57
  /** closes the upstreams; every session opened from this host is finished with */
50
58
  close(): Promise<void>;
51
59
  }
60
+ /** Writes the revocation list whole, by rename, so a gateway re-reading it never sees half a file. */
61
+ export declare function writeRevokedGrants(path: string, digests: string[]): void;
52
62
  export declare function createGatewayHost(cfg: GatewayConfig, options?: GatewayOptions): Promise<GatewayHost>;
53
63
  /** One gateway for the grant the config names: what `agent-custody gateway` serves over stdio. Closing it closes the host. */
54
64
  export declare function createGateway(cfg: GatewayConfig, options?: GatewayOptions): Promise<Gateway>;