@agent-custody/receipts 0.6.19 → 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";
@@ -40,6 +42,10 @@ const USAGE = `agent-custody <command>
40
42
  --agent-key names the agent's own key in the grant, so the agent may delegate
41
43
  delegate --key <agent.key> --parent <grant.json> --agent <sub-agent> --scopes <a,b> [--ttl-hours N] [--agent-key <sub.pub>] --out <file>
42
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
43
49
  gateway --config <gateway.json> [--http [--port 8790] [--host 127.0.0.1] [--idle-minutes 30]]
44
50
  stdio: one gateway for the grant the config names. --http: one shared gateway, MCP over
45
51
  Streamable HTTP at /mcp, each connection presenting its own grant as Authorization: Bearer
@@ -176,6 +182,24 @@ async function main(argv) {
176
182
  console.log(`delegated to ${chain.agent}: scopes [${chain.scopes.join(", ")}] until ${chain.expiresAt}, under ${decodeDelegation(parent).agent}'s grant from ${chain.principal}`);
177
183
  return 0;
178
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
+ }
179
203
  case "gateway": {
180
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" } } });
181
205
  if (!values.config)
@@ -501,6 +525,8 @@ async function main(argv) {
501
525
  "stripe-secret-env": { type: "string" },
502
526
  "github-secret-env": { type: "string" },
503
527
  log: { type: "string" },
528
+ disclose: { type: "string" },
529
+ "capture-key-env": { type: "string" },
504
530
  json: { type: "boolean", default: false },
505
531
  },
506
532
  });
@@ -509,6 +535,8 @@ async function main(argv) {
509
535
  if (!file || issuerKeyFiles.length === 0)
510
536
  throw new Error("verify needs <bundle> --issuer-key (alias --gateway-key)");
511
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;
512
540
  const fetchedLogKeys = values["log-url"] ? (await fetchLogKeys(values["log-url"])).keys : [];
513
541
  const logKeys = [...(values["log-key"] ?? []).map(loadPublicKey), ...fetchedLogKeys];
514
542
  const result = verifyBundle(bundle, {
@@ -519,10 +547,76 @@ async function main(argv) {
519
547
  ...(values["upstream-key"] ? { upstreamKeys: values["upstream-key"].map(loadPublicKey) } : {}),
520
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"]) } : {}) } } : {}),
521
549
  ...(values.log ? { logFile: values.log } : {}),
550
+ ...(captureKey ? { captureKey } : {}),
551
+ ...(disclosed ? { disclosed } : {}),
522
552
  });
523
553
  console.log(values.json ? JSON.stringify(result, null, 2) : formatReport(result));
524
554
  return result.ok ? 0 : 1;
525
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
+ }
526
620
  case "audit": {
527
621
  const { values } = parseArgs({
528
622
  args: rest,
package/dist/config.d.ts CHANGED
@@ -202,6 +202,34 @@ export declare const GatewayConfigSchema: z.ZodObject<{
202
202
  optional: z.ZodDefault<z.ZodBoolean>;
203
203
  }, z.core.$strip>>>;
204
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>;
205
233
  mode: z.ZodOptional<z.ZodEnum<{
206
234
  enforce: "enforce";
207
235
  observe: "observe";
@@ -213,6 +241,8 @@ export declare const GatewayConfigSchema: z.ZodObject<{
213
241
  tokenEnv: z.ZodOptional<z.ZodString>;
214
242
  hashOnly: z.ZodOptional<z.ZodBoolean>;
215
243
  timeoutMs: z.ZodOptional<z.ZodNumber>;
244
+ keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
245
+ logId: z.ZodOptional<z.ZodString>;
216
246
  }, z.core.$strip>>;
217
247
  otel: z.ZodOptional<z.ZodObject<{
218
248
  url: z.ZodString;
@@ -250,6 +280,8 @@ export declare const SdkConfigSchema: z.ZodObject<{
250
280
  tokenEnv: z.ZodOptional<z.ZodString>;
251
281
  hashOnly: z.ZodOptional<z.ZodBoolean>;
252
282
  timeoutMs: z.ZodOptional<z.ZodNumber>;
283
+ keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
284
+ logId: z.ZodOptional<z.ZodString>;
253
285
  }, z.core.$strip>>;
254
286
  otel: z.ZodOptional<z.ZodObject<{
255
287
  url: z.ZodString;
@@ -265,6 +297,33 @@ export declare const SdkConfigSchema: z.ZodObject<{
265
297
  host: z.ZodOptional<z.ZodString>;
266
298
  }, z.core.$strip>>;
267
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>;
268
327
  }, z.core.$strip>;
269
328
  export type SdkConfig = z.infer<typeof SdkConfigSchema>;
270
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),
@@ -76,6 +80,12 @@ export const GatewayConfigSchema = z.object({
76
80
  * authorization to the log and refuses the call if the log will not take it. Evidence then precedes the side effect.
77
81
  */
78
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(),
79
89
  /**
80
90
  * "enforce" (the default when absent) denies what the policy denies. "observe" forwards every call the grant allows and records the
81
91
  * decision the policy would have made, with `enforced: false` on the receipt: the way to run a new policy against
@@ -88,7 +98,10 @@ export const GatewayConfigSchema = z.object({
88
98
  log: LogSchema.optional(),
89
99
  otel: OtelSchema.optional(),
90
100
  splunk: SplunkSchema.optional(),
91
- }).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" });
92
105
  /** Loads a config file and resolves every path relative to the file's directory. */
93
106
  export function loadConfig(path) {
94
107
  const cfg = GatewayConfigSchema.parse(JSON.parse(readFileSync(path, "utf8")));
@@ -102,6 +115,8 @@ export function loadConfig(path) {
102
115
  policyFile: r(cfg.policyFile),
103
116
  receiptsDir: r(cfg.receiptsDir),
104
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) } : {}),
105
120
  };
106
121
  }
107
122
  export const SdkConfigSchema = z.object({
@@ -120,6 +135,9 @@ export const SdkConfigSchema = z.object({
120
135
  splunk: SplunkSchema.optional(),
121
136
  /** free-text label of the host framework, e.g. "claude-code", "openai-agents" */
122
137
  framework: z.string().optional(),
138
+ /** private evidence, as for the gateway */
139
+ capture: CaptureSchema.optional(),
140
+ captureKeyEnv: z.string().min(1).optional(),
123
141
  }).refine(hasOneLog, oneLog);
124
142
  export function loadSdkConfig(path) {
125
143
  const cfg = SdkConfigSchema.parse(JSON.parse(readFileSync(path, "utf8")));
@@ -131,5 +149,6 @@ export function loadSdkConfig(path) {
131
149
  ...(cfg.policyFile ? { policyFile: r(cfg.policyFile) } : {}),
132
150
  receiptsDir: r(cfg.receiptsDir),
133
151
  ...(cfg.logFile ? { logFile: r(cfg.logFile) } : {}),
152
+ ...(cfg.log?.keys ? { log: { ...cfg.log, keys: cfg.log.keys.map(r) } } : {}),
134
153
  };
135
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>;