@agent-custody/receipts 0.16.8 → 0.16.9

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/README.md CHANGED
@@ -289,6 +289,7 @@ src/policy-rego.ts Rego: compiled with opa build, evaluated in-process with the
289
289
  src/opa-server.ts an OPA server's Data API as the policy, with bundle revisions as the digest
290
290
  src/simulate.ts replay recorded policy decisions against a proposed Cedar or Rego policy, grouped changes and run digest
291
291
  src/delegation.ts signed delegation grants
292
+ src/revocation.ts the revoked-grants file the gateway and the door share: re-read when it changes, written by rename
292
293
  src/approval.ts exact-action human approvals, distinct trusted signatures, persistent single-use consumption
293
294
  src/receipt.ts receipt and authorization statement types and provenance labels
294
295
  src/issue.ts sign, log, and write a receipt, or commit an authorization first; shared by every producer
package/dist/check.js CHANGED
@@ -225,6 +225,23 @@ export function checkDoorConfig(configPath) {
225
225
  if (!ldir)
226
226
  add("error", "paths", `${cfg.logFile} cannot be written`);
227
227
  }
228
+ if (cfg.revokedGrants) {
229
+ if (!existsSync(cfg.revokedGrants))
230
+ add("ok", "revokedGrants", `no grant is revoked yet; \`agent-custody revoke --config\` creates ${cfg.revokedGrants}`);
231
+ else {
232
+ try {
233
+ const list = JSON.parse(readFileSync(cfg.revokedGrants, "utf8"));
234
+ if (!Array.isArray(list))
235
+ throw new Error("expected a JSON array of grant digests");
236
+ add("ok", "revokedGrants", `${list.length} revoked grant(s) in ${cfg.revokedGrants}`);
237
+ }
238
+ catch (e) {
239
+ add("error", "revokedGrants", `${cfg.revokedGrants}: ${e instanceof Error ? e.message : String(e)}; the door refuses to start, and a file that becomes unreadable while it runs makes every grant revoked`);
240
+ }
241
+ }
242
+ }
243
+ else if (cfg.trustedPrincipalKeys.length > 0)
244
+ add("warn", "revokedGrants", "no revokedGrants file: a grant cannot be revoked at this door before it expires");
228
245
  return out;
229
246
  }
230
247
  /** True when the file is an egress witness config: it names agents, and no upstream or origin. */
package/dist/cli.js CHANGED
@@ -86,8 +86,10 @@ const USAGE = `agent-custody <command>
86
86
  a narrower grant for a sub-agent, signed by the agent the parent names; the parent travels inside
87
87
  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
88
88
  for verify --disclose; needs the customer's capture key
89
- revoke --config <gateway.json> --grant <grant.json> revokes a grant: its digest goes into the config's revokedGrants file, every
90
- session under it or under a grant delegated from it refuses its next call, and no new session opens for them
89
+ revoke --config <gateway.json|door.json> --grant <grant.json>
90
+ revokes a grant: its digest goes into the config's revokedGrants file. At a gateway, every
91
+ session under it or under a grant delegated from it refuses its next call, and no new session opens for them;
92
+ at a door, an arrival carrying it, or a grant delegated from it, is claimed with grant "revoked"
91
93
  reconcile --config <gateway.json> --operation <uuid> operator-only provider lookup; commits a receipt before closing an unknown/pending financial operation
92
94
  console --config <gateway.json> [--port 8795] [--host 127.0.0.1] [--token-env CONSOLE_TOKEN | --token-file <path>] [--gateway-url <url>] [--state-dir <dir>]
93
95
  the admin console for a gateway: its config and tools, a config check, receipts with a verdict each, a policy editor that
@@ -329,9 +331,10 @@ async function main(argv) {
329
331
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, grant: { type: "string" } } });
330
332
  if (!values.config || !values.grant)
331
333
  throw new Error("revoke needs --config and --grant");
332
- const cfg = loadConfig(values.config);
334
+ const door = isDoorConfig(values.config);
335
+ const cfg = door ? loadDoorConfig(values.config) : loadConfig(values.config);
333
336
  if (!cfg.revokedGrants)
334
- throw new Error("revoke needs revokedGrants in the config: the file the gateway re-reads on every call");
337
+ throw new Error(`revoke needs revokedGrants in the config: the file the ${door ? "door re-reads on every arrival" : "gateway re-reads on every call"}`);
335
338
  const envelope = JSON.parse(readFileSync(values.grant, "utf8"));
336
339
  const chain = decodeDelegation(envelope);
337
340
  if (!chain)
@@ -340,7 +343,7 @@ async function main(argv) {
340
343
  const list = existsSync(cfg.revokedGrants) ? JSON.parse(readFileSync(cfg.revokedGrants, "utf8")) : [];
341
344
  if (!list.includes(digest))
342
345
  writeRevokedGrants(cfg.revokedGrants, [...list, digest]);
343
- 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`);
346
+ 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); ${door ? "a running door classifies it as revoked on its next arrival" : "a running gateway refuses it on its next call"}`);
344
347
  return 0;
345
348
  }
346
349
  case "gateway": {
package/dist/config.d.ts CHANGED
@@ -415,6 +415,7 @@ export declare const DoorConfigSchema: z.ZodObject<{
415
415
  }, z.core.$strip>>>;
416
416
  unmatchedRoute: z.ZodDefault<z.ZodString>;
417
417
  trustedPrincipalKeys: z.ZodDefault<z.ZodArray<z.ZodString>>;
418
+ revokedGrants: z.ZodOptional<z.ZodString>;
418
419
  policyFile: z.ZodString;
419
420
  mode: z.ZodOptional<z.ZodEnum<{
420
421
  enforce: "enforce";
package/dist/config.js CHANGED
@@ -255,6 +255,8 @@ export const DoorConfigSchema = z.object({
255
255
  unmatchedRoute: z.string().min(1).default("other"),
256
256
  /** principal keys whose grants the door accepts as a passport: an arrival carrying one of their grants, in scope for its route, is `verified` */
257
257
  trustedPrincipalKeys: z.array(z.string()).default([]),
258
+ /** a JSON file listing digests of revoked grant envelopes, the same file and format as the gateway's (`agent-custody revoke --config door.json` appends to it); re-read whenever it changes, checked on every arrival. A grant it lists, or one whose chain it lists, is `revoked` */
259
+ revokedGrants: z.string().min(1).optional(),
258
260
  policyFile: z.string(),
259
261
  /** "enforce" (default) refuses what the policy denies; "observe" forwards everything and records the decision with `enforced: false` */
260
262
  mode: z.enum(["enforce", "observe"]).optional(),
@@ -399,6 +401,7 @@ export function loadDoorConfig(path) {
399
401
  ...cfg,
400
402
  identity: { keyFile: r(cfg.identity.keyFile) },
401
403
  trustedPrincipalKeys: cfg.trustedPrincipalKeys.map(r),
404
+ ...(cfg.revokedGrants ? { revokedGrants: r(cfg.revokedGrants) } : {}),
402
405
  policyFile: r(cfg.policyFile),
403
406
  receiptsDir: r(cfg.receiptsDir),
404
407
  ...(cfg.logFile ? { logFile: r(cfg.logFile) } : {}),
package/dist/door.d.ts CHANGED
@@ -30,10 +30,11 @@ export interface Arrival {
30
30
  subject: string;
31
31
  /**
32
32
  * What became of the grant header: a trusted grant in scope for this route, one out of scope, one that did not verify,
33
+ * one revoked (`revoked`: it, or a grant above it in its chain, is in `revokedGrants`, or that file cannot be read),
33
34
  * one presented by another agent (`wrong-sender`: the request is signed by a signature agent the grant does not name),
34
35
  * or none.
35
36
  */
36
- grant: "verified" | "out-of-scope" | "invalid" | "wrong-sender" | "absent";
37
+ grant: "verified" | "out-of-scope" | "invalid" | "revoked" | "wrong-sender" | "absent";
37
38
  grantError?: string;
38
39
  /** What became of an RFC 9421 signature tagged `web-bot-auth`: see `SignatureCheck`. `unchecked` when the door has no `webBotAuth` config */
39
40
  signature: SignatureCheck["outcome"];
@@ -220,9 +221,10 @@ export declare function signedRequestOf(req: DoorRequest): SignedRequest;
220
221
  * arrival `verified` as its signature agent. With both, the signature binds the grant to its sender when the grant names
221
222
  * that signature agent; a grant presented under another agent's signature is `wrong-sender` and the arrival `claimed`.
222
223
  * An `x-agent-custody-agent` header or a signature that did not verify alone is `claimed`. Nothing at all is `unknown`.
223
- * Without `signature`, a `Signature-Input` header is recorded as `unchecked`.
224
+ * Without `signature`, a `Signature-Input` header is recorded as `unchecked`. `revoked`, when given, says why a grant
225
+ * that verified is revoked (from its chain's digests, leaf first), or null when it is not; a revoked grant is `claimed`.
224
226
  */
225
- export declare function classifyArrival(req: DoorRequest, trusted: PublicKeyRef[], route: string, trustProxy: boolean, at: string, signature?: SignatureCheck): Classified;
227
+ export declare function classifyArrival(req: DoorRequest, trusted: PublicKeyRef[], route: string, trustProxy: boolean, at: string, signature?: SignatureCheck, revoked?: (chainDigests: string[]) => string | null): Classified;
226
228
  export interface DoorOptions {
227
229
  /** the log to append to, in place of the one the config names; for embedding and tests */
228
230
  log?: LogSink;
package/dist/door.js CHANGED
@@ -11,12 +11,13 @@ import { closeSync, fstatSync, openSync, readFileSync } from "node:fs";
11
11
  import { createServer } from "node:http";
12
12
  import { captureKeyFrom } from "./capture.js";
13
13
  import { digestOf, loadPrivateKey, loadPublicKey, sha256Hex } from "./crypto.js";
14
- import { decodeDelegation, delegationValidAt, verifyDelegation } from "./delegation.js";
14
+ import { decodeDelegation, delegationValidAt, grantChainDigests, verifyDelegation } from "./delegation.js";
15
15
  import { parseGrantHeader, GRANT_HEADER } from "./gateway-http.js";
16
16
  import { createIssuer, ReceiptPending } from "./issue.js";
17
17
  import { createWebBotAuthVerifier, normalizeAuthority } from "./web-bot-auth.js";
18
18
  import { createPartnerEngine, PARTNER_FACT, PARTNER_TOOL } from "./door-partner.js";
19
19
  import { openLog } from "./log-sink.js";
20
+ import { createRevocationList } from "./revocation.js";
20
21
  import { openExporter } from "./otel.js";
21
22
  import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
22
23
  export const DOOR_VERSION = "0.1.0";
@@ -283,9 +284,10 @@ export function signedRequestOf(req) {
283
284
  * arrival `verified` as its signature agent. With both, the signature binds the grant to its sender when the grant names
284
285
  * that signature agent; a grant presented under another agent's signature is `wrong-sender` and the arrival `claimed`.
285
286
  * An `x-agent-custody-agent` header or a signature that did not verify alone is `claimed`. Nothing at all is `unknown`.
286
- * Without `signature`, a `Signature-Input` header is recorded as `unchecked`.
287
+ * Without `signature`, a `Signature-Input` header is recorded as `unchecked`. `revoked`, when given, says why a grant
288
+ * that verified is revoked (from its chain's digests, leaf first), or null when it is not; a revoked grant is `claimed`.
287
289
  */
288
- export function classifyArrival(req, trusted, route, trustProxy, at, signature) {
290
+ export function classifyArrival(req, trusted, route, trustProxy, at, signature, revoked) {
289
291
  const url = requestUrl(req);
290
292
  const method = (req.method ?? "GET").toUpperCase();
291
293
  const declaredRaw = req.headers[AGENT_HEADER];
@@ -313,6 +315,9 @@ export function classifyArrival(req, trusted, route, trustProxy, at, signature)
313
315
  if (!checked.ok)
314
316
  return { arrival: { class: "claimed", subject, grant: "invalid", grantError: checked.error, ...base } };
315
317
  const grant = checked.delegation;
318
+ const revocation = revoked?.(grantChainDigests(envelope));
319
+ if (revocation)
320
+ return { arrival: { class: "claimed", subject: grant.agent, grant: "revoked", grantError: revocation, ...base } };
316
321
  if (!delegationValidAt(grant, at))
317
322
  return { arrival: { class: "claimed", subject: grant.agent, grant: "invalid", grantError: "the grant is outside its validity window", ...base } };
318
323
  if (!grant.scopes.includes(route))
@@ -388,6 +393,20 @@ const json = (status, headers, body) => ({ status, headers: { "content-type": "a
388
393
  export function createDoorCore(cfg, options, framework) {
389
394
  const key = loadPrivateKey(cfg.identity.keyFile);
390
395
  const trusted = cfg.trustedPrincipalKeys.map(loadPublicKey);
396
+ const revocations = createRevocationList(cfg.revokedGrants);
397
+ revocations.reload();
398
+ const revoked = (chainDigests) => {
399
+ try {
400
+ revocations.reload();
401
+ }
402
+ catch (e) {
403
+ // fail closed: a revocation list that cannot be read revokes every grant until it can
404
+ return `the grant cannot be checked against the revocation list (${e instanceof Error ? e.message : String(e)})`;
405
+ }
406
+ if (!revocations.has(chainDigests))
407
+ return null;
408
+ return revocations.has(chainDigests.slice(0, 1)) ? "the grant has been revoked" : "a grant above it in its chain has been revoked";
409
+ };
391
410
  const captureKey = cfg.captureKeyEnv ? captureKeyFrom(process.env[cfg.captureKeyEnv] ?? (() => { throw new Error(`capture key: environment variable ${cfg.captureKeyEnv} is not set`); })()) : undefined;
392
411
  for (const [route, rule] of Object.entries(cfg.capture ?? {})) {
393
412
  for (const side of [rule.args, rule.result, rule.facts])
@@ -453,7 +472,7 @@ export function createDoorCore(cfg, options, framework) {
453
472
  const path = "path" in norm ? norm.path : url.pathname;
454
473
  const route = "path" in norm ? matchRoute(cfg.routes, cfg.unmatchedRoute, method, path) : cfg.unmatchedRoute;
455
474
  const signature = webBotAuth ? await webBotAuth.verify(signedRequestOf(req)) : undefined;
456
- const { arrival, delegation, signer } = classifyArrival(req, trusted, route, !!cfg.trustProxy, timestamp, signature);
475
+ const { arrival, delegation, signer } = classifyArrival(req, trusted, route, !!cfg.trustProxy, timestamp, signature, revoked);
457
476
  const checkedAgent = arrival.class === "verified";
458
477
  const by = checkedAgent ? "agent" : "remote";
459
478
  arrival.rate = { by, ...rates.hit(`${by}:${checkedAgent ? arrival.subject : arrival.remote}`) };
package/dist/gateway.d.ts CHANGED
@@ -6,6 +6,7 @@ import { type FlushResult } from "./issue.ts";
6
6
  import { type LogSink } from "./log-sink.ts";
7
7
  import { type ReceiptExporter } from "./otel.ts";
8
8
  import type { ReceiptBundle } from "./receipt.ts";
9
+ export { writeRevokedGrants } from "./revocation.ts";
9
10
  export declare const GATEWAY_VERSION = "0.1.0";
10
11
  export declare const RECEIPT_META_KEY = "agent-custody/receipt";
11
12
  export declare const MODEL_META_KEY = "agent-custody/model";
@@ -80,8 +81,6 @@ export interface GatewayHost {
80
81
  /** closes the upstreams; every session opened from this host is finished with */
81
82
  close(): Promise<void>;
82
83
  }
83
- /** Writes the revocation list whole, by rename, so a gateway re-reading it never sees half a file. */
84
- export declare function writeRevokedGrants(path: string, digests: string[]): void;
85
84
  export declare function createGatewayHost(cfg: GatewayConfig, options?: GatewayOptions): Promise<GatewayHost>;
86
85
  /** One gateway for the grant the config names: what `agent-custody gateway` serves over stdio. Closing it closes the host. */
87
86
  export declare function createGateway(cfg: GatewayConfig, options?: GatewayOptions): Promise<Gateway>;
package/dist/gateway.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // The MCP gateway: sits between an agent and its upstreams, MCP servers or REST APIs, enforces scope + Cedar policy,
2
2
  // and emits a signed, logged receipt for every tool call, allowed or denied.
3
3
  import { randomUUID } from "node:crypto";
4
- import { appendFileSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
4
+ import { appendFileSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, statSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
7
7
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
@@ -23,6 +23,8 @@ import { captureKeyFrom, effectiveRule } from "./capture.js";
23
23
  import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
24
24
  import { compileRego, evaluateRego, isRegoFile } from "./policy-rego.js";
25
25
  import { createOpaServerPolicy } from "./opa-server.js";
26
+ import { createRevocationList } from "./revocation.js";
27
+ export { writeRevokedGrants } from "./revocation.js";
26
28
  import { OPERATION_META_KEY, OperationStore, ownerAlive } from "./operations.js";
27
29
  export const GATEWAY_VERSION = "0.1.0";
28
30
  export const RECEIPT_META_KEY = "agent-custody/receipt";
@@ -87,12 +89,6 @@ export function upstreamEnv(extra) {
87
89
  }
88
90
  return { ...base, ...(extra ?? {}) };
89
91
  }
90
- /** Writes the revocation list whole, by rename, so a gateway re-reading it never sees half a file. */
91
- export function writeRevokedGrants(path, digests) {
92
- const tmp = `${path}.${process.pid}.tmp`;
93
- writeFileSync(tmp, JSON.stringify(digests, null, 2) + "\n");
94
- renameSync(tmp, path);
95
- }
96
92
  export async function createGatewayHost(cfg, options = {}) {
97
93
  const gatewayKey = loadPrivateKey(cfg.identity.keyFile);
98
94
  const trusted = cfg.trustedPrincipalKeys.map(loadPublicKey);
@@ -250,41 +246,10 @@ export async function createGatewayHost(cfg, options = {}) {
250
246
  if (cfg.approvals?.tools.some((rule) => rule.tool === f.tool))
251
247
  throw new Error(`fact "${f.name}" uses tool ${f.tool}, which requires approval; a fact lookup must be a read that does not require approval`);
252
248
  }
253
- // Revoked grants: digests of grant envelopes, from the file the operator edits (or `revoke` appends to), re-read
254
- // whenever the file changes. Checked when a session opens and again on every call, so revocation takes effect on
255
- // the next call of a running session, without a key rotation.
256
- const revokedSet = new Set();
257
- let revokedSeen = "";
258
- const reloadRevoked = () => {
259
- if (!cfg.revokedGrants)
260
- return;
261
- if (!existsSync(cfg.revokedGrants)) {
262
- if (revokedSeen !== "absent") {
263
- revokedSet.clear();
264
- revokedSeen = "absent";
265
- }
266
- return;
267
- }
268
- // inode as well as mtime: `revoke` replaces the file by rename, so two writes in one mtime tick are still seen
269
- const st = statSync(cfg.revokedGrants);
270
- const m = `${st.ino}:${st.mtimeMs}:${st.size}`;
271
- if (m === revokedSeen)
272
- return;
273
- const list = JSON.parse(readFileSync(cfg.revokedGrants, "utf8"));
274
- if (!Array.isArray(list))
275
- throw new Error(`${cfg.revokedGrants}: expected a JSON array of grant digests`);
276
- revokedSet.clear();
277
- for (const d of list)
278
- if (typeof d === "string")
279
- revokedSet.add(d);
280
- revokedSeen = m;
281
- };
282
- const revoke = (digest) => {
283
- reloadRevoked();
284
- revokedSet.add(digest);
285
- if (cfg.revokedGrants)
286
- writeRevokedGrants(cfg.revokedGrants, [...revokedSet]);
287
- };
249
+ // Revoked grants, re-read whenever the file changes. Checked when a session opens and again on every call, so
250
+ // revocation takes effect on the next call of a running session, without a key rotation.
251
+ const revocations = createRevocationList(cfg.revokedGrants);
252
+ const revoke = (digest) => revocations.add(digest);
288
253
  // One host, as many upstreams as the agents' jobs need. Each tool name belongs to exactly one upstream, decided at
289
254
  // startup, so a receipt's tool is unambiguous and consumed facts flow across them.
290
255
  const upstreamConfigs = cfg.upstreams ? cfg.upstreams.map((u) => ({ name: u.name, cfg: u })) : [{ name: "upstream", cfg: cfg.upstream }];
@@ -425,19 +390,19 @@ export async function createGatewayHost(cfg, options = {}) {
425
390
  const principalKeyid = grant.keyid;
426
391
  const chainDigests = grantChainDigests(grantEnvelope);
427
392
  const grantDigest = chainDigests[0];
428
- reloadRevoked();
429
- if (chainDigests.some((d) => revokedSet.has(d)))
393
+ revocations.reload();
394
+ if (revocations.has(chainDigests))
430
395
  throw new Error("delegation grant has been revoked");
431
396
  /** Why the grant is not in force at `at`, or null. Asked on every call, and again just before a forward. */
432
397
  const grantProblem = (at = new Date().toISOString()) => {
433
398
  try {
434
- reloadRevoked();
399
+ revocations.reload();
435
400
  }
436
401
  catch (e) {
437
402
  // fail closed: a revocation list that cannot be read revokes everything until it can
438
403
  return `cannot be checked against the revocation list (${e instanceof Error ? e.message : String(e)})`;
439
404
  }
440
- if (chainDigests.some((d) => revokedSet.has(d)))
405
+ if (revocations.has(chainDigests))
441
406
  return "has been revoked";
442
407
  if (!delegationValidAt(delegation, at))
443
408
  return Date.parse(at) < Date.parse(delegation.issuedAt) ? "is not yet valid" : "has expired";
@@ -780,10 +745,7 @@ export async function createGatewayHost(cfg, options = {}) {
780
745
  revoke,
781
746
  policyDigest: () => currentPolicy().digest,
782
747
  tools: () => advertised.map((t) => t.name),
783
- revoked: () => {
784
- reloadRevoked();
785
- return [...revokedSet];
786
- },
748
+ revoked: () => revocations.list(),
787
749
  async reconcile(operationId) {
788
750
  if (!operations)
789
751
  throw new Error("gateway has no financial operations configured");
@@ -0,0 +1,14 @@
1
+ /** Replaces the revocation file by rename, so a reader never sees half a list. */
2
+ export declare function writeRevokedGrants(path: string, digests: string[]): void;
3
+ export interface RevocationList {
4
+ /** re-reads the file if it changed; throws when it exists and cannot be read as a JSON array */
5
+ reload(): void;
6
+ /** true when any of `digests` is revoked, as of the last reload */
7
+ has(digests: string[]): boolean;
8
+ /** reloads, adds a digest, and writes the file back when there is one */
9
+ add(digest: string): void;
10
+ /** reloads and returns every revoked digest */
11
+ list(): string[];
12
+ }
13
+ /** The revocation list in `path`; with no path, a list held in memory only. A missing file is an empty list. */
14
+ export declare function createRevocationList(path: string | undefined): RevocationList;
@@ -0,0 +1,53 @@
1
+ // Revoked grants: digests of grant envelopes (`grantDigest` in delegation.ts), in a JSON array the operator edits or
2
+ // `agent-custody revoke` appends to. The gateway and the door read the same file the same way: re-read whenever it
3
+ // changes, so revocation takes effect on the next call or arrival without a restart or a key rotation.
4
+ import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
5
+ /** Replaces the revocation file by rename, so a reader never sees half a list. */
6
+ export function writeRevokedGrants(path, digests) {
7
+ const tmp = `${path}.${process.pid}.tmp`;
8
+ writeFileSync(tmp, JSON.stringify(digests, null, 2) + "\n");
9
+ renameSync(tmp, path);
10
+ }
11
+ /** The revocation list in `path`; with no path, a list held in memory only. A missing file is an empty list. */
12
+ export function createRevocationList(path) {
13
+ const revoked = new Set();
14
+ let seen = "";
15
+ const reload = () => {
16
+ if (!path)
17
+ return;
18
+ if (!existsSync(path)) {
19
+ if (seen !== "absent") {
20
+ revoked.clear();
21
+ seen = "absent";
22
+ }
23
+ return;
24
+ }
25
+ // inode as well as mtime: `revoke` replaces the file by rename, so two writes in one mtime tick are still seen
26
+ const st = statSync(path);
27
+ const m = `${st.ino}:${st.mtimeMs}:${st.size}`;
28
+ if (m === seen)
29
+ return;
30
+ const list = JSON.parse(readFileSync(path, "utf8"));
31
+ if (!Array.isArray(list))
32
+ throw new Error(`${path}: expected a JSON array of grant digests`);
33
+ revoked.clear();
34
+ for (const d of list)
35
+ if (typeof d === "string")
36
+ revoked.add(d);
37
+ seen = m;
38
+ };
39
+ return {
40
+ reload,
41
+ has: (digests) => digests.some((d) => revoked.has(d)),
42
+ add(digest) {
43
+ reload();
44
+ revoked.add(digest);
45
+ if (path)
46
+ writeRevokedGrants(path, [...revoked]);
47
+ },
48
+ list() {
49
+ reload();
50
+ return [...revoked];
51
+ },
52
+ };
53
+ }
@@ -12,12 +12,13 @@ Three labels run through the table:
12
12
 
13
13
  | signal | label | what it means | what it does not mean |
14
14
  | --- | --- | --- | --- |
15
- | `class: "verified"` | checked | A grant signed by a principal in `trustedPrincipalKeys`, inside its validity window, names this agent and lists this arrival's route among its scopes. Or, with no grant, a Web Bot Auth signature checked against the key its signature agent's directory publishes, and the agent is that origin. The Cedar `principal` is that agent | That the agent is well-behaved, that the principal is who they say they are beyond holding the key, or that the request body is what the principal intended. The grant has no revocation list: it stands until it expires. A grant alone is bearer-grade: `signature` says whether the sender also proved it holds the agent's key |
16
- | `class: "claimed"` | a claim | Something was asserted that the door could not accept: a grant from a key it does not trust, an expired one, one for other routes, one presented under another agent's signature, a declared agent name, or a signature that did not verify or was not checked. `grant`, `grantError`, `signature`, and `signatureError` say which | That the arrival is an agent, or that it is hostile. A misconfigured client, a grant for the wrong route, and an impostor all look the same here |
15
+ | `class: "verified"` | checked | A grant signed by a principal in `trustedPrincipalKeys`, inside its validity window, names this agent, lists this arrival's route among its scopes, and is not revoked. Or, with no grant, a Web Bot Auth signature checked against the key its signature agent's directory publishes, and the agent is that origin. The Cedar `principal` is that agent | That the agent is well-behaved, that the principal is who they say they are beyond holding the key, or that the request body is what the principal intended. It stands until it expires unless the door has `revokedGrants` and the grant is listed there. A grant alone is bearer-grade: `signature` says whether the sender also proved it holds the agent's key |
16
+ | `class: "claimed"` | a claim | Something was asserted that the door could not accept: a grant from a key it does not trust, an expired one, a revoked one, one for other routes, one presented under another agent's signature, a declared agent name, or a signature that did not verify or was not checked. `grant`, `grantError`, `signature`, and `signatureError` say which | That the arrival is an agent, or that it is hostile. A misconfigured client, a grant for the wrong route, and an impostor all look the same here |
17
17
  | `class: "unknown"` | observed | Nothing was presented | That the arrival is a person. A browser, a crawler, and a script that sends no headers are all `unknown`. There is no `human` class, and a policy that admits `unknown` on a route admits everything on that route |
18
18
  | `grant: "verified"` | checked | As `class: "verified"` | |
19
19
  | `grant: "out-of-scope"` | checked | The grant verified and is valid, but this route is not among its scopes. `subject` is the agent it names | That the agent may do anything here. The principal did not grant this route |
20
20
  | `grant: "invalid"` | checked | The grant did not verify against a trusted key, did not decode, or is outside its window. `grantError` says which | Who signed it. A grant from an untrusted principal is `invalid` even when it is genuine |
21
+ | `grant: "revoked"` | checked | The grant verified against a trusted key, and it, or a grant above it in its chain, is in the door's `revokedGrants` file; or that file could not be read, which revokes every grant until it can. `grantError` says which | That the agent misbehaved. The operator withdrew the grant, for whatever reason; the revocation file does not record why |
21
22
  | `grant: "wrong-sender"` | checked | The grant verified and is in scope, and the request is signed, verifiably, by a signature agent the grant does not name. The arrival is `claimed` | Which of the two is lying. The grant was handed on or taken; the door does not admit it as the agent it names |
22
23
  | `grant: "absent"` | observed | No grant header | |
23
24
  | `subject` | checked only when `class` is `verified` | The agent a verified grant names; else the signature agent of a verified signature; else the declared name or the agent a rejected grant named; else `unknown` | For a `claimed` arrival, anything. It is recorded so the receipt shows what was asserted; the Cedar `principal` is `Agent::"unknown"` for it |
package/docs/door.md CHANGED
@@ -14,6 +14,8 @@ agent-custody check --config door.json
14
14
  agent-custody door --config door.json --port 8780
15
15
  ```
16
16
 
17
+ To run it as a service, the gateway image has a `door` mode (`docker run ... ghcr.io/svayatta/agent-custody-gateway:<version> door`, config at `/config/door.json`, key created at `/data/keys/door.key`), and [deploy/door](../../../deploy/door/README.md#as-a-reverse-proxy-from-the-gateway-image) has a compose file in front of a stand-in site, Kubernetes manifests, a systemd unit, and the smoke test that every build of the image passes.
18
+
17
19
  ## The config file
18
20
 
19
21
  `door.json`, paths relative to the file. Loaded with `loadDoorConfig(path)`.
@@ -37,7 +39,7 @@ agent-custody door --config door.json --port 8780
37
39
 
38
40
  Every field of the config, with its type and default, is in [the door reference](../../../site/reference/door.md#config).
39
41
 
40
- `agent-custody check --config door.json` reads a door config the way the door would: unknown keys, the key, the principal keys, the policy (including a permit that names an agent without requiring a verified arrival, see below), the routes, what is precommitted, the challenge provider or its absence, the partner engine and its key, the origin's scheme, every credential variable the door reads at startup (origin headers, the log, Splunk, OTel, the capture key, the challenge secret), and the paths. It exits 1 on an error.
42
+ `agent-custody check --config door.json` reads a door config the way the door would: unknown keys, the key, the principal keys, the policy (including a permit that names an agent without requiring a verified arrival, see below), the routes, what is precommitted, the challenge provider or its absence, the partner engine and its key, the revocation file, the origin's scheme, every credential variable the door reads at startup (origin headers, the log, Splunk, OTel, the capture key, the challenge secret), and the paths. It exits 1 on an error.
41
43
 
42
44
  ## What the door knows about an arrival
43
45
 
@@ -45,9 +47,9 @@ The door records one fact for every arrival, `arrival`, observed by the door its
45
47
 
46
48
  | field | values | meaning |
47
49
  | --- | --- | --- |
48
- | `class` | `verified`, `claimed`, `unknown` | `verified`: a grant signed by a trusted principal, inside its window, naming this route among its scopes; or, with no grant, a [Web Bot Auth signature](#web-bot-auth-signatures) that checked against the key its agent's directory publishes. `claimed`: something was asserted that the door could not accept: a grant from a stranger, an expired one, one for other routes, one presented under another agent's signature, a declared agent name, or a signature that did not check or was not checked. `unknown`: nothing was presented |
50
+ | `class` | `verified`, `claimed`, `unknown` | `verified`: a grant signed by a trusted principal, inside its window, naming this route among its scopes; or, with no grant, a [Web Bot Auth signature](#web-bot-auth-signatures) that checked against the key its agent's directory publishes. `claimed`: something was asserted that the door could not accept: a grant from a stranger, an expired one, a revoked one, one for other routes, one presented under another agent's signature, a declared agent name, or a signature that did not check or was not checked. `unknown`: nothing was presented |
49
51
  | `subject` | string | the agent named in a verified grant; else the signature agent of a verified signature (its https origin); else the declared name or the agent a rejected grant named; else `unknown`. Only a verified subject reaches the Cedar `principal` |
50
- | `grant` | `verified`, `out-of-scope`, `invalid`, `wrong-sender`, `absent` | what became of the grant header, with `grantError` when it was not accepted. `wrong-sender`: the grant verified, and the request is signed by a signature agent the grant does not name |
52
+ | `grant` | `verified`, `out-of-scope`, `invalid`, `revoked`, `wrong-sender`, `absent` | what became of the grant header, with `grantError` when it was not accepted. `revoked`: the grant verified, and it or a grant above it in its chain is in `revokedGrants` (see [revoking a grant](#revoking-a-grant)). `wrong-sender`: the grant verified, and the request is signed by a signature agent the grant does not name |
51
53
  | `signature` | `verified`, `invalid`, `unavailable`, `unchecked`, `absent` | what became of an RFC 9421 signature tagged `web-bot-auth`, with `signatureError` when it was not verified. `unchecked`: a `Signature-Input` arrived and the config has no `webBotAuth`, so it is a claim. See [Web Bot Auth signatures](#web-bot-auth-signatures) |
52
54
  | `signatureAgent`, `signatureKeyid` | strings | the `Signature-Agent` origin and the keyid the signature named. Checked only when `signature` is `verified` |
53
55
  | `declared` | string | the `x-agent-custody-agent` header, when sent. A claim |
@@ -65,6 +67,8 @@ There is no `human` class. The door cannot tell a person from a program that pre
65
67
 
66
68
  **A grant alone is bearer-grade; a grant under its agent's signature is bound to its sender.** The door checks the grant's signature, window, and scope. On its own, that does not show that the sender holds the agent's key. Anyone who holds the grant's bytes is that agent until the grant expires, and every verified receipt carries the grant in `delegation`, so a person who can read one receipt can replay its grant. When the request also carries a Web Bot Auth signature that the door verified, and the grant names that signature agent (`"agent": "https://crawler.example"`), the grant is bound to its sender: a thief has the grant's bytes but not the agent's signing key, and a captured signature serves one request (its nonce) for at most `maxAgeSeconds`. A grant presented under another agent's signature is `wrong-sender`, and the arrival is `claimed`. A grant with no signature, or with one that did not verify, is still verified, bearer-grade, as before, so a route that needs the binding says so in its policy: `context.facts.arrival.grant == "verified" && context.facts.arrival.signature == "verified"` holds only for a bound grant, since a mismatch makes `grant` `wrong-sender`. For bearer grants, issue door grants with short lifetimes (minutes, not days), scope them to the routes they need, bound what a route allows per call in the policy, and treat receipt files and logs as holding live credentials until those grants expire.
67
69
 
70
+ **Revoking a grant.** <a id="revoking-a-grant"></a>With `revokedGrants` in the config, a grant can be withdrawn before it expires: the file is the gateway's, a JSON array of grant digests, and `agent-custody revoke --config door.json --grant grant.json` appends one. The door re-reads the file when it changes and checks every grant against it after the signature and before the window and the scope, so a running door classifies the next arrival that carries the grant as `claimed` with `grant: "revoked"`, and the Cedar principal is not the agent. Revoking a grant revokes every grant delegated from it (`grantError` says "a grant above it in its chain has been revoked"). A file that is there and cannot be read stops the door from starting; one that becomes unreadable while it runs makes every grant `revoked` until it can be read, so a broken list never lets a grant through. A missing file is an empty list. Without `revokedGrants`, a grant stands until it expires, and `check` warns when the door trusts principals.
71
+
68
72
  **Challenging a human.** The door builds no CAPTCHA. With `challenge` configured, a page in front of a protected route renders the provider's widget (Cloudflare Turnstile or hCaptcha) with `siteKey`, and sends the token the widget produced in the `challenge.header` header of its request. The door posts the token and the secret from `secretEnv` to the provider's `siteverify` endpoint, with a timeout, and records the answer as `challenge.outcome`. It adds the arrival's address as `remoteip` only with `trustProxy`, where that address is the client's; without it the socket's address may be a proxy's, and the provider would refuse a token the client solved. It never follows a redirect, which would resend the secret and the token elsewhere. To hCaptcha it also sends `siteKey` as `sitekey`: an hCaptcha secret belongs to the account, and without it a token solved on the account's easiest widget would pass on the hardest. A Turnstile secret belongs to one widget already. `success` alone does not pass: the token must have been issued on one of `hostnames`, and for `action` when one is set, or a token solved on another site that uses this site key, or for another widget, would count. At most `maxInFlight` checks wait on the provider at once; an arrival past that is `unavailable`. The token is stripped before the request is relayed, and neither the token nor the secret is recorded. A policy admits a person on a form route with
69
73
 
70
74
  ```cedar
@@ -390,7 +394,7 @@ To record more in clear, give the route a rule of its own, as for the gateway ([
390
394
 
391
395
  A door receipt is a v0.2 receipt with `issuer.kind: "door"` and `issuer.framework: "http"` (`"authz"` when it answered a proxy's check, [below](#behind-nginx-or-envoy-authz-mode)). The route is the tool, observed. `request.args` is the arrival as the table above describes it, claimed. `facts.arrival` is the door's observation; `facts.partner`, when present, is a partner engine's signed verdict, attested ([above](#a-partner-engines-verdict)). When the arrival was verified by a grant, `principal` and `agent` are attested and `delegation` carries the grant. When it was verified by a signature alone, `principal` is `{ id: null, provenance: "claimed" }` and `agent` is the signature agent, observed. Otherwise `principal` is `{ id: null, provenance: "claimed" }` and `agent` is the subject, claimed. `execution.result` for a relayed call is `{ status, contentType?, bodyBytes, bodyDigest }`: the origin's body is never copied into the receipt, only committed to.
392
396
 
393
- The verifier runs `door receipt carries a policy decision` in place of the gateway's two checks, and otherwise the same checks: a verified arrival's receipt passes `delegation binds principal and agent` and `executed tool within delegated scope`; an unknown arrival's passes `principal is claimed, not attested`; a receipt that carries an `authorization` passes the authorization checks, including `authorization logged before execution`. Both verifiers, the Python verifier, and `policy simulate` accept door receipts; the conformance vectors `door-unknown-executed`, `door-unknown-denied`, and `door-verified-executed` pin them.
397
+ The verifier runs `door receipt carries a policy decision` in place of the gateway's two checks, and otherwise the same checks: a verified arrival's receipt passes `delegation binds principal and agent` and `executed tool within delegated scope`; an unknown arrival's passes `principal is claimed, not attested`; a receipt that carries an `authorization` passes the authorization checks, including `authorization logged before execution`. Both verifiers, the Python verifier, and `policy simulate` accept door receipts; the conformance vectors `door-unknown-executed`, `door-unknown-denied`, and `door-verified-executed` pin them. The `door-grant-*` vectors pin each passport the door may be shown: an expired grant, one signed by a key it does not trust, a revoked grant, a delegated grant (with `delegation chain to the principal`), and a delegated grant whose parent was revoked. Each one the door refuses is a claimed arrival whose receipt verifies with no delegation; the `resigned-door-grant-*` vectors paste the refused grant into the receipt as if the door had accepted it, and fail `delegation valid at receipt time` or `delegation signature (principal key)`.
394
398
 
395
399
  ## Behind nginx or Envoy: authz mode
396
400
 
@@ -426,7 +430,6 @@ A site that already runs nginx or Envoy need not send its traffic through the do
426
430
  - Check AP2 mandates.
427
431
  - Check every Web Bot Auth signature: Ed25519 only (no RSA-PSS or ECDSA), the components listed above only, no `Content-Digest`, no response signatures on the directory, and nonces in one process's memory. A signature agent must be listed in `agents`; the door does not fetch the directory of an origin it was not told about.
428
432
  - Challenge an arrival with a passkey. Turnstile and hCaptcha are the providers; see [challenging a human](#challenging-a-human).
429
- - Revoke a grant by a revocation list; a grant stands until it expires.
430
433
  - Bind a grant to its sender without a signature. A grant presented alone is bearer-grade; under its agent's Web Bot Auth signature it is bound: see [presenting a passport](#what-the-door-knows-about-an-arrival).
431
434
  - Stream a request body: the body is read whole, up to `maxBodyBytes`, so that the policy can read it and the receipt can commit to it.
432
435
  - Relay a response larger than `maxResponseBytes`, or stream one: the body is relayed whole so that its digest can be recorded. A larger one is not held: reading stops at the limit, the client gets 502, and the receipt records that the origin answered.
@@ -20,7 +20,7 @@ jobs:
20
20
  runs-on: ubuntu-latest
21
21
  steps:
22
22
  - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
23
- - uses: svayatta/agent-custody@<commit sha of the release> # 0.16.8
23
+ - uses: svayatta/agent-custody@<commit sha of the release> # 0.16.9
24
24
  with:
25
25
  path: .custody/receipts
26
26
  issuer-key: .custody/keys/agent.pub
@@ -37,7 +37,7 @@ Pin the action to the commit of a release, as you pin every other action. A movi
37
37
  | `principal-key` | the public key files of the principals whose grants a gateway receipt carries, one path on each line; SDK and Claude Code hook receipts need none | |
38
38
  | `log-url` | the URL of the log; the action fetches the log key from it (`verify --log-url`) | |
39
39
  | `log-id` | the id that every tree head must name (`verify --log-id`) | |
40
- | `version` | the `@agent-custody/receipts` version that `npx` runs | `0.16.8` |
40
+ | `version` | the `@agent-custody/receipts` version that `npx` runs | `0.16.9` |
41
41
  | `github-token` | a token that can write pull request comments; an empty value writes the job summary only | `github.token` |
42
42
  | `comment-author` | the login of the account that `github-token` posts as; the action edits only a comment from this account | `github-actions[bot]` |
43
43
 
package/docs/tutorials.md CHANGED
@@ -49,7 +49,7 @@ Suggested reading order is the numbering. Output lands in `examples-out/`, which
49
49
  | 37 | receipts on a pull request | [37-pr-summary.ts](../examples/37-pr-summary.ts) | two receipts from a gateway verify into one Markdown table (what `verify --markdown` and the GitHub Action post); one changed byte makes the table name the failed check; a directory with no receipt fails | `src/pr-summary.ts`, `action.yml` |
50
50
  | 38 | an incident replay | [38-incident-replay.ts](../examples/38-incident-replay.ts) | the same setup as `init claude-code --enforce`, in a temporary home; a scripted Claude Code session that runs the real hook command for each event: `terraform plan` runs and gets an executed receipt, `terraform destroy -auto-approve` and `rm -rf ~` are denied before they run, with the denial text and the receipt id; a reviewer with only the public key verifies all three receipts, and a stranger's key fails | `src/sdk/claude.ts`, `src/claude-init.ts`, `templates/claude-code.cedar` |
51
51
  | 39 | exporting receipts to a pull request | [39-export.ts](../examples/39-export.ts) | an agent works under a capture rule; `export` copies the two receipts that withhold their values, byte for byte, and refuses the one that records plain values; one changed byte makes it refuse a third | `src/export.ts`, `src/cli.ts` |
52
- | 40 | the door: a receipted reverse proxy in front of your own API | [40-door.ts](../examples/40-door.ts) | a stand-in shop behind the door; an unknown arrival reads the catalogue and is refused a refund; an agent with a grant signed by the shop's principal is verified and refunds within the policy, refused above it; a forged grant is claimed; the origin saw only what was allowed; both receipts verified | `src/door.ts`, `src/config.ts` |
52
+ | 40 | the door: a receipted reverse proxy in front of your own API | [40-door.ts](../examples/40-door.ts) | a stand-in shop behind the door; an unknown arrival reads the catalogue and is refused a refund; an agent with a grant signed by the shop's principal is verified and refunds within the policy, refused above it; a forged grant is claimed, and so is the grant once the shop revokes it, with no restart; the origin saw only what was allowed; both receipts verified | `src/door.ts`, `src/config.ts` |
53
53
  | 41 | the egress witness: a receipted forward proxy for calls around the gateway | [41-egress.ts](../examples/41-egress.ts) | a locked-down agent tries a direct call to a payment provider (CONNECT api.stripe.com:443) and the witness refuses it; an allowed tunnel to a stand-in docs mirror is relayed and recorded by destination and byte counts, never its contents; a connection with no proxy credential gets 407; the refusal's receipt verifies with the witness's key | `src/egress.ts`, `src/config.ts` |
54
54
  | 42 | a first egress policy from what the agents did in observe mode | [42-egress-draft.ts](../examples/42-egress-draft.ts) | the witness observes an agent reach a docs mirror three times and a paste site once; `egress draft-policy` verifies the receipts and drafts one permit with a count and first and last time per destination, under a warning that it permits everything the agent did; the review deletes the paste site, and the enforced policy relays the mirror and refuses the paste site | `src/egress-draft.ts` |
55
55
  | 43 | an OWASP ACS Guardian whose decisions land in a transparency log | [43-acs-guardian.ts](../examples/43-acs-guardian.ts) | a log runs under a key of its own; the ACS README's sample `steps/toolCallRequest` piped through `agent-custody acs` is allowed, its receipt carries the session's `chain_hash`, and it verifies offline with only the Guardian's and the log's public keys; in one session a read outside `/reports` is denied, a result for an allowed request passes, and a result for an unknown request is denied; a consistency proof shows the log after the deny extends the log that held the first decision (ACS issue #18, directions 1 and 3) | `src/acs.ts`, `src/config.ts` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-custody/receipts",
3
- "version": "0.16.8",
3
+ "version": "0.16.9",
4
4
  "mcpName": "io.github.svayatta/agent-custody",
5
5
  "description": "Proof of what your AI agents did. Give your agents real power, without losing control of them: signed, verifiable receipts for tool calls, an MCP gateway with Cedar or Rego policy, and a Merkle transparency log.",
6
6
  "license": "Apache-2.0",