@agent-custody/receipts 0.16.8 → 0.16.10

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/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;
@@ -238,6 +240,8 @@ export interface DoorHost {
238
240
  handle(req: IncomingMessage, res: ServerResponse): Promise<void>;
239
241
  flushOutbox(): Promise<FlushResult>;
240
242
  pendingReceipts(): number;
243
+ /** the form protector script, when the door has a challenge to protect forms with */
244
+ formScript?(): string | null;
241
245
  close(): Promise<void>;
242
246
  }
243
247
  /** The body as the door read it: whole, or how many bytes had arrived when it passed the limit. */
@@ -327,6 +331,10 @@ export interface RunningDoor {
327
331
  url: string;
328
332
  close(): Promise<void>;
329
333
  }
330
- /** Serves a door host over plain HTTP. Bind to loopback or put TLS in front. `GET /.well-known/agent-custody-door` answers the key id and the policy digest. */
334
+ /**
335
+ * Serves a door host over plain HTTP. Bind to loopback or put TLS in front. `GET /.well-known/agent-custody-door` answers
336
+ * the key id and the policy digest; with a challenge configured, `GET /.well-known/agent-custody-door/form.js` is the
337
+ * form protector script.
338
+ */
331
339
  export declare function serveDoor(host: DoorHost, opts: DoorServerOptions): Promise<RunningDoor>;
332
340
  export {};
package/dist/door.js CHANGED
@@ -10,13 +10,16 @@ import { randomUUID } from "node:crypto";
10
10
  import { closeSync, fstatSync, openSync, readFileSync } from "node:fs";
11
11
  import { createServer } from "node:http";
12
12
  import { captureKeyFrom } from "./capture.js";
13
- import { digestOf, loadPrivateKey, loadPublicKey, sha256Hex } from "./crypto.js";
14
- import { decodeDelegation, delegationValidAt, verifyDelegation } from "./delegation.js";
13
+ import { digestOf, loadPrivateKey, loadPublicKey, publicKeyFromPem, sha256Hex } from "./crypto.js";
14
+ import { DID_KEY_PREFIX, publicKeyFromDidKey } from "./did-key.js";
15
+ import { decodeDelegation, delegationValidAt, grantChainDigests, verifyDelegation } from "./delegation.js";
15
16
  import { parseGrantHeader, GRANT_HEADER } from "./gateway-http.js";
16
17
  import { createIssuer, ReceiptPending } from "./issue.js";
17
18
  import { createWebBotAuthVerifier, normalizeAuthority } from "./web-bot-auth.js";
18
19
  import { createPartnerEngine, PARTNER_FACT, PARTNER_TOOL } from "./door-partner.js";
19
20
  import { openLog } from "./log-sink.js";
21
+ import { FORM_SCRIPT_PATH, formScript } from "./door-form.js";
22
+ import { createRevocationList } from "./revocation.js";
20
23
  import { openExporter } from "./otel.js";
21
24
  import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
22
25
  export const DOOR_VERSION = "0.1.0";
@@ -283,9 +286,10 @@ export function signedRequestOf(req) {
283
286
  * arrival `verified` as its signature agent. With both, the signature binds the grant to its sender when the grant names
284
287
  * that signature agent; a grant presented under another agent's signature is `wrong-sender` and the arrival `claimed`.
285
288
  * 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`.
289
+ * Without `signature`, a `Signature-Input` header is recorded as `unchecked`. `revoked`, when given, says why a grant
290
+ * that verified is revoked (from its chain's digests, leaf first), or null when it is not; a revoked grant is `claimed`.
287
291
  */
288
- export function classifyArrival(req, trusted, route, trustProxy, at, signature) {
292
+ export function classifyArrival(req, trusted, route, trustProxy, at, signature, revoked) {
289
293
  const url = requestUrl(req);
290
294
  const method = (req.method ?? "GET").toUpperCase();
291
295
  const declaredRaw = req.headers[AGENT_HEADER];
@@ -313,6 +317,20 @@ export function classifyArrival(req, trusted, route, trustProxy, at, signature)
313
317
  if (!checked.ok)
314
318
  return { arrival: { class: "claimed", subject, grant: "invalid", grantError: checked.error, ...base } };
315
319
  const grant = checked.delegation;
320
+ const revocation = revoked?.(grantChainDigests(envelope));
321
+ if (revocation)
322
+ return { arrival: { class: "claimed", subject: grant.agent, grant: "revoked", grantError: revocation, ...base } };
323
+ // An agent named by a did:key is its key: the identifier must decode to an Ed25519 key, and the grant's agentKey, if
324
+ // it names one, must be that key, or the grant says two things about who the agent is. Every link of a chain, since a
325
+ // parent's agentKey is what verified the link below it.
326
+ for (const [i, link] of checked.chain.entries()) {
327
+ if (!link.agent.startsWith(DID_KEY_PREFIX))
328
+ continue;
329
+ const named = didKeyAgent(link.agent, link.agentKey);
330
+ const where = i === checked.chain.length - 1 ? "" : `link ${i} (${link.agent}): `;
331
+ if (named)
332
+ return { arrival: { class: "claimed", subject: grant.agent, grant: "invalid", grantError: where + named, ...base } };
333
+ }
316
334
  if (!delegationValidAt(grant, at))
317
335
  return { arrival: { class: "claimed", subject: grant.agent, grant: "invalid", grantError: "the grant is outside its validity window", ...base } };
318
336
  if (!grant.scopes.includes(route))
@@ -322,6 +340,26 @@ export function classifyArrival(req, trusted, route, trustProxy, at, signature)
322
340
  return { arrival: { class: "claimed", subject: grant.agent, grant: "wrong-sender", grantError: `the grant names agent "${grant.agent}", and the request is signed by ${signer.agent}`, ...base } };
323
341
  return { arrival: { class: "verified", subject: grant.agent, grant: "verified", ...base }, delegation: { envelope, grant, principalKeyid: checked.keyid }, ...(signer ? { signer } : {}) };
324
342
  }
343
+ /** Why a did:key agent does not check out, or null when it decodes and agrees with the grant's agentKey. */
344
+ function didKeyAgent(did, agentKey) {
345
+ let named;
346
+ try {
347
+ named = publicKeyFromDidKey(did);
348
+ }
349
+ catch (e) {
350
+ return `the grant's did:key agent does not decode: ${e instanceof Error ? e.message : String(e)}`;
351
+ }
352
+ if (agentKey === undefined)
353
+ return null;
354
+ try {
355
+ if (publicKeyFromPem(agentKey).keyid === named.keyid)
356
+ return null;
357
+ }
358
+ catch {
359
+ return "the grant's agentKey is not a public key";
360
+ }
361
+ return "the grant's agentKey is not the key its did:key agent names";
362
+ }
325
363
  /** methods that must not change anything at the origin; every other method is relayed only after its receipt is committed to the log */
326
364
  const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
327
365
  /** The body, or how many bytes had arrived when it passed the limit; the rest is drained and dropped. */
@@ -388,6 +426,20 @@ const json = (status, headers, body) => ({ status, headers: { "content-type": "a
388
426
  export function createDoorCore(cfg, options, framework) {
389
427
  const key = loadPrivateKey(cfg.identity.keyFile);
390
428
  const trusted = cfg.trustedPrincipalKeys.map(loadPublicKey);
429
+ const revocations = createRevocationList(cfg.revokedGrants);
430
+ revocations.reload();
431
+ const revoked = (chainDigests) => {
432
+ try {
433
+ revocations.reload();
434
+ }
435
+ catch (e) {
436
+ // fail closed: a revocation list that cannot be read revokes every grant until it can
437
+ return `the grant cannot be checked against the revocation list (${e instanceof Error ? e.message : String(e)})`;
438
+ }
439
+ if (!revocations.has(chainDigests))
440
+ return null;
441
+ return revocations.has(chainDigests.slice(0, 1)) ? "the grant has been revoked" : "a grant above it in its chain has been revoked";
442
+ };
391
443
  const captureKey = cfg.captureKeyEnv ? captureKeyFrom(process.env[cfg.captureKeyEnv] ?? (() => { throw new Error(`capture key: environment variable ${cfg.captureKeyEnv} is not set`); })()) : undefined;
392
444
  for (const [route, rule] of Object.entries(cfg.capture ?? {})) {
393
445
  for (const side of [rule.args, rule.result, rule.facts])
@@ -453,7 +505,7 @@ export function createDoorCore(cfg, options, framework) {
453
505
  const path = "path" in norm ? norm.path : url.pathname;
454
506
  const route = "path" in norm ? matchRoute(cfg.routes, cfg.unmatchedRoute, method, path) : cfg.unmatchedRoute;
455
507
  const signature = webBotAuth ? await webBotAuth.verify(signedRequestOf(req)) : undefined;
456
- const { arrival, delegation, signer } = classifyArrival(req, trusted, route, !!cfg.trustProxy, timestamp, signature);
508
+ const { arrival, delegation, signer } = classifyArrival(req, trusted, route, !!cfg.trustProxy, timestamp, signature, revoked);
457
509
  const checkedAgent = arrival.class === "verified";
458
510
  const by = checkedAgent ? "agent" : "remote";
459
511
  arrival.rate = { by, ...rates.hit(`${by}:${checkedAgent ? arrival.subject : arrival.remote}`) };
@@ -791,6 +843,7 @@ export async function createDoorHost(cfg, options = {}) {
791
843
  handle,
792
844
  flushOutbox: core.flushOutbox,
793
845
  pendingReceipts: core.pendingReceipts,
846
+ formScript: () => (cfg.challenge ? formScript(cfg.challenge) : null),
794
847
  async close() {
795
848
  core.close();
796
849
  },
@@ -835,12 +888,17 @@ function createAuthzHost(cfg, options) {
835
888
  handle,
836
889
  flushOutbox: core.flushOutbox,
837
890
  pendingReceipts: core.pendingReceipts,
891
+ formScript: () => (cfg.challenge ? formScript(cfg.challenge) : null),
838
892
  async close() {
839
893
  core.close();
840
894
  },
841
895
  };
842
896
  }
843
- /** Serves a door host over plain HTTP. Bind to loopback or put TLS in front. `GET /.well-known/agent-custody-door` answers the key id and the policy digest. */
897
+ /**
898
+ * Serves a door host over plain HTTP. Bind to loopback or put TLS in front. `GET /.well-known/agent-custody-door` answers
899
+ * the key id and the policy digest; with a challenge configured, `GET /.well-known/agent-custody-door/form.js` is the
900
+ * form protector script.
901
+ */
844
902
  export async function serveDoor(host, opts) {
845
903
  const bind = opts.host ?? "127.0.0.1";
846
904
  const log = opts.log ?? ((m) => console.error(m));
@@ -850,6 +908,17 @@ export async function serveDoor(host, opts) {
850
908
  res.end(JSON.stringify({ keyid: host.keyid, policyDigest: host.policyDigest(), version: DOOR_VERSION, pendingReceipts: host.pendingReceipts() }));
851
909
  return;
852
910
  }
911
+ if (req.method === "GET" && (req.url ?? "").split("?")[0] === FORM_SCRIPT_PATH) {
912
+ const script = host.formScript?.() ?? null;
913
+ if (!script) {
914
+ res.writeHead(404, { "content-type": "application/json", "cache-control": "no-store" });
915
+ res.end(JSON.stringify({ error: "this door has no challenge configured, so it has no form protector" }));
916
+ return;
917
+ }
918
+ res.writeHead(200, { "content-type": "text/javascript; charset=utf-8", "cache-control": "public, max-age=300", "x-content-type-options": "nosniff" });
919
+ res.end(script);
920
+ return;
921
+ }
853
922
  host.handle(req, res).catch((e) => {
854
923
  log(`agent-custody door: ${e instanceof Error ? e.message : String(e)}`);
855
924
  if (!res.headersSent) {
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");
package/dist/index.d.ts CHANGED
@@ -20,6 +20,7 @@ export { formatPerathosReport, PERATHOS_RECEIPT_V1, perathosHead, perathosReceip
20
20
  export type { PerathosCheck, PerathosOptions, PerathosReport } from "./perathos.ts";
21
21
  export { loadAcsGuardianConfig } from "./config.ts";
22
22
  export type { AcsGuardianConfig } from "./config.ts";
23
+ export { FORM_SCRIPT_PATH, formScript } from "./door-form.ts";
23
24
  export type { Arrival, ArrivalChallenge, ArrivalClass, ArrivalRate, ChallengeCheck, Classified, DoorHost, DoorOptions, DoorRequest, DoorServerOptions, RateTracker, RateTrackerLimits, RunningDoor } from "./door.ts";
24
25
  export type { SignatureCheck, SignedRequest, WebBotAuthOptions, WebBotAuthVerifier } from "./web-bot-auth.ts";
25
26
  export * from "./capture.ts";
@@ -41,8 +42,8 @@ export { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoi
41
42
  export { adminRoutes, welcomeSheet } from "./log-admin.ts";
42
43
  export { fetchWitnessKeys, Witness } from "./witness.ts";
43
44
  export { Anchor, ANCHOR_CHAINS, anchorCalldata, anchorLeaf, checkAnchorRecord, resolveAnchorChain } from "./anchor.ts";
44
- export { checkCompleteness, formatCompleteness, stripeSource } from "./completeness.ts";
45
- export type { CompletenessOptions, CompletenessReport, ProviderObject, ProviderSource, StripeObject, StripeSourceOptions } from "./completeness.ts";
45
+ export { checkCompleteness, formatCompleteness, githubSource, stripeSource } from "./completeness.ts";
46
+ export type { CompletenessOptions, CompletenessReport, GitHubObject, GitHubSourceOptions, ProviderObject, ProviderSource, StripeObject, StripeSourceOptions } from "./completeness.ts";
46
47
  export type { AnchorChain, AnchorCheck, AnchorCheckOptions, AnchorOptions, AnchorRecord, AnchorRun, AnchorTenantOutcome, AnchorTxOutcome } from "./anchor.ts";
47
48
  export { evmChain } from "./anchor-evm.ts";
48
49
  export type { EvmChainOptions } from "./anchor-evm.ts";
@@ -61,6 +62,7 @@ export * from "./config.ts";
61
62
  export * from "./operations.ts";
62
63
  export * from "./crypto.ts";
63
64
  export * from "./delegation.ts";
65
+ export { base58btcDecode, base58btcEncode, DID_KEY_PREFIX, didKeyOf, publicKeyFromDidKey } from "./did-key.ts";
64
66
  export * from "./approval.ts";
65
67
  export * from "./gateway.ts";
66
68
  export * from "./issue.ts";
package/dist/index.js CHANGED
@@ -14,6 +14,7 @@ export { DRAFT_WARNING, draftEgressPolicy } from "./egress-draft.js";
14
14
  export { ACS_ERROR, ACS_GUARDIAN_VERSION, ACS_METHODS, ACS_RECEIPT_KEY, ACS_STEP_FACT, ACS_VERSION, acsEntryHash, createAcsGuardian } from "./acs.js";
15
15
  export { formatPerathosReport, PERATHOS_RECEIPT_V1, perathosHead, perathosReceiptHash, verifyPerathosLog } from "./perathos.js";
16
16
  export { loadAcsGuardianConfig } from "./config.js";
17
+ export { FORM_SCRIPT_PATH, formScript } from "./door-form.js";
17
18
  export * from "./capture.js";
18
19
  export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.js";
19
20
  export { deliverMail, founderNote, PortalStore, portalHandler, readSession, readSessionVia, sendFollowUps, servePortal, signSession, SsoRefusedError, stripeRequest, verifyStripeSignature } from "./portal.js";
@@ -26,13 +27,14 @@ export { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoi
26
27
  export { adminRoutes, welcomeSheet } from "./log-admin.js";
27
28
  export { fetchWitnessKeys, Witness } from "./witness.js";
28
29
  export { Anchor, ANCHOR_CHAINS, anchorCalldata, anchorLeaf, checkAnchorRecord, resolveAnchorChain } from "./anchor.js";
29
- export { checkCompleteness, formatCompleteness, stripeSource } from "./completeness.js";
30
+ export { checkCompleteness, formatCompleteness, githubSource, stripeSource } from "./completeness.js";
30
31
  export { evmChain } from "./anchor-evm.js";
31
32
  export { checkLog, formatLogCheck } from "./log-check.js";
32
33
  export * from "./config.js";
33
34
  export * from "./operations.js";
34
35
  export * from "./crypto.js";
35
36
  export * from "./delegation.js";
37
+ export { base58btcDecode, base58btcEncode, DID_KEY_PREFIX, didKeyOf, publicKeyFromDidKey } from "./did-key.js";
36
38
  export * from "./approval.js";
37
39
  export * from "./gateway.js";
38
40
  export * from "./issue.js";
@@ -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
+ }
@@ -1,6 +1,6 @@
1
1
  # Completeness
2
2
 
3
- A verified receipt proves what went through the gateway. Nothing on the gateway's side can see an action that never went through it: whoever holds the Stripe key can issue a refund straight through Stripe's API. The provider's own record is the only place that action shows. `agent-custody completeness` lets an auditor check it, with a read-only key of their own.
3
+ A verified receipt proves what went through the gateway. Nothing on the gateway's side can see an action that never went through it: whoever holds the Stripe key can issue a refund straight through Stripe's API. The provider's own record is the only place that action shows. `agent-custody completeness` lets an auditor check it, with a read-only key of their own. It supports two providers: Stripe and GitHub.
4
4
 
5
5
  ## What it reports
6
6
 
@@ -8,7 +8,7 @@ For a window and a set of tools, it lists the provider's objects and matches eac
8
8
 
9
9
  | section | meaning | what to do |
10
10
  | --- | --- | --- |
11
- | provider actions with no receipt | an object the provider created in the window that no verified receipt names | the finding this command exists for: an action taken outside the gateway, or by a gateway whose receipts you were not given |
11
+ | provider actions with no receipt | an object the provider created in the window that no verified receipt names, or a second object with an id that a receipt already accounts for | the finding this command exists for: an action taken outside the gateway, or by a gateway whose receipts you were not given |
12
12
  | receipts the provider does not have | an executed receipt in the window whose object the provider has no record of | a receipt for something that did not happen at the provider, or an object in another account or mode |
13
13
  | mismatches | a matched pair whose amount, currency (ignoring case), or a beneficiary field differs | the receipt and the provider disagree about what happened |
14
14
  | one provider object, several receipts | more than one verified receipt names the same provider object; each is still compared with it | one action recorded twice, or receipts that contradict each other |
@@ -37,23 +37,54 @@ agent-custody completeness --receipts ./receipts --issuer-key gateway.pub --prin
37
37
  | --- | --- | --- |
38
38
  | `--receipts <dir>` | | the auditor's copy of the receipts directory, authorization files included |
39
39
  | `--issuer-key`, `--principal-key`, `--approval-key`, `--log-key`, `--log`, `--log-id` | | how each receipt is verified, as for `verify` |
40
- | `--provider stripe` | | the provider; Stripe is the only one so far |
41
- | `--object` | `refunds` | `refunds`, `payouts`, or `transfers` |
42
- | `--key-env NAME` | | the environment variable holding the read-only key; never a flag value |
40
+ | `--provider` | | `stripe` or `github` |
41
+ | `--object` | `refunds` for Stripe, `pushes` for GitHub | Stripe: `refunds`, `payouts`, or `transfers`. GitHub: `pushes`, `merges`, or `releases` |
42
+ | `--repo <owner>/<name>` | | GitHub only: the repository to list |
43
+ | `--key-env NAME` | | the environment variable holding the read-only key or token; never a flag value |
43
44
  | `--tool <name>` | | each tool whose executed calls create provider objects; repeatable |
44
45
  | `--since`, `--until` | | the window, ISO times; `--until` is exclusive |
45
- | `--id-path` | `id` | where the provider's object id sits in the JSON of the result's first text item; Stripe's own response uses `id` |
46
+ | `--id-path` | `id` | where the provider's object id sits in the JSON of the result's first text item, a string or an integer; Stripe's own response uses `id` |
46
47
  | `--amount-field`, `--currency-field` | `amount`, `currency` | the call arguments compared with the provider's amount and currency |
47
48
  | `--beneficiary <arg>=<field>` | | a call argument that must equal a provider field, such as `charge=charge` or `customer_id=metadata.customer_id`; repeatable |
48
49
  | `--json` | | the full report as JSON |
49
50
 
50
51
  Use a restricted Stripe key with read-only access to the objects you check. The command only lists objects: it never creates, retries, or reconciles anything. The operator's `reconcile` command is a different thing: it settles one financial operation through the gateway and writes a receipt.
51
52
 
53
+ ## GitHub
54
+
55
+ ```bash
56
+ export GITHUB_AUDIT_TOKEN=github_pat_... # a fine-grained token with read-only access to Contents, held by the auditor
57
+ agent-custody completeness --receipts ./receipts --issuer-key gateway.pub --principal-key principal.pub \
58
+ --log log.jsonl --provider github --repo acme/shop --object merges --key-env GITHUB_AUDIT_TOKEN \
59
+ --tool github.merge_pull_request --id-path sha --since 2026-10-01T00:00:00Z --until 2026-11-01T00:00:00Z
60
+ ```
61
+
62
+ Each run checks one repository and one object kind. Run the command one time for each kind that the agents can do.
63
+
64
+ | `--object` | what GitHub lists | the id that the receipt must carry | `--id-path` for GitHub's own response |
65
+ | --- | --- | --- | --- |
66
+ | `pushes` | each push, each force push, and each branch creation, from the repository's activity list | the commit that the branch moved to (`after`) | `object.sha` for a created or updated ref, `commit.sha` for a written file |
67
+ | `merges` | each merged pull request, merge queue included, from the same activity list | the commit that the branch moved to: the merge commit | `sha` |
68
+ | `releases` | each release, by its publication time, or by its creation time while it is a draft | the release's numeric id | `id` |
69
+
70
+ GitHub objects have no amount and no currency, so those comparisons do not run. `--beneficiary` compares a call argument with a field of the listed object, for example `--beneficiary tag_name=tag_name` for releases.
71
+
72
+ Limits that apply to GitHub only:
73
+
74
+ - **Deleted branches are not supported.** GitHub answers a branch deletion with an empty body, so a receipt carries no identifier that the activity list also has.
75
+ - **A branch creation is a push.** GitHub lists a push that creates a branch only as a branch creation, so `pushes` includes each branch creation. A branch that someone creates in the GitHub web interface is listed too.
76
+ - **A commit identifies a push.** The id is the commit, not the branch. A receipt accounts for one listed action with its id. When the same commit goes to a second branch, or a force push moves a branch back to it, the report lists that action as a provider action with no receipt. This is correct for an action outside the gateway. When an agent moves two branches to the same commit through the gateway, two receipts name one id: the report lists them under "one provider object, several receipts", and you compare them by hand.
77
+ - **GitHub records some pushes twice.** Entries with the same branch, the same two commits, and the same time are read as one push.
78
+ - **Releases are slow on a large repository.** GitHub gives no time order for releases, so each run reads every page of them.
79
+ - **A push of several commits has one id.** The id is the last commit, which is the commit that the tool's result must carry.
80
+ - **Draft releases.** GitHub shows a draft release only to a token with write access. A read-only token lists published releases.
81
+ - **Tags are not listed.** The activity list covers branches.
82
+
52
83
  ## Limits
53
84
 
54
85
  - **The receipts you were given.** The check proves completeness against those receipts. A second gateway, or a second receipts directory, that issued receipts you were not handed shows up as provider actions with no receipt, which is the correct finding.
55
86
  - **One provider account and mode per run.** Test-mode and live-mode objects are separate lists.
56
87
  - **The id must be readable.** A capture rule that withholds the result content also withholds the object id inside it, and such receipts are reported as unmatchable, never as matched or missing. A rule that keeps `content` in clear (`result: { mode: "digest", clear: ["content"] }`) leaves the id readable. Likewise, keep the amount, currency, and beneficiary arguments in clear, or those comparisons are reported as unmatchable. Reading values from disclosures is still to come.
57
- - **Stripe first.** Other providers, and on-chain transfers from an agent's wallet, are `ProviderSource` implementations still to come.
88
+ - **Stripe and GitHub.** Other providers, and on-chain transfers from an agent's wallet, are `ProviderSource` implementations still to come.
58
89
 
59
- In code, `checkCompleteness({ receiptsDir, verify, source, tools, sinceMs, untilMs })` returns the report, `stripeSource({ secretKey, object })` lists Stripe objects, and `formatCompleteness(report)` prints it. Example 35 runs the whole check against a stand-in for Stripe's list API.
90
+ In code, `checkCompleteness({ receiptsDir, verify, source, tools, sinceMs, untilMs })` returns the report, `stripeSource({ secretKey, object })` lists Stripe objects, `githubSource({ token, repo, object })` lists GitHub objects, and `formatCompleteness(report)` prints it. Example 35 runs the whole check against a stand-in for Stripe's list API, and example 53 runs it against a stand-in for GitHub's activity list.
@@ -178,6 +178,17 @@ RESULT: VERIFIED
178
178
 
179
179
  The refund was in the log before your handler ran. The output is cut to the lines that matter; the full report lists every check. Your receipt ids differ; take them from the `x-agent-custody-receipt` headers. The output above is from the Express app, run from this repository at the commit that added the in-process door, with the headers cut to the door's; a Next.js route's receipt says `door / fetch-route`.
180
180
 
181
+ ## A form protected by the challenge
182
+
183
+ With `challenge` in the config, a page protects a form with one line, `<script src="/.well-known/agent-custody-door/form.js" defer></script>` ([protecting a form with one line](door.md#protecting-a-form-with-one-line)). In Express the middleware answers that path itself, before it decides anything. In Next.js, add a route at `app/.well-known/agent-custody-door/form.js/route.ts`:
184
+
185
+ ```ts
186
+ import { guard } from "@/lib/door";
187
+ export const GET = () => new Response(guard.formScript(), { headers: { "content-type": "text/javascript; charset=utf-8" } });
188
+ ```
189
+
190
+ The form's own route is wrapped as any other: `export const POST = guard.route(handler)`.
191
+
181
192
  ## What your code receives
182
193
 
183
194
  An allowed request reaches your code with:
@@ -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
- | `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 |
20
+ | `grant: "invalid"` | checked | The grant did not verify against a trusted key, did not decode, or is outside its window; or it, or a grant above it in its chain, names its agent by a did:key that does not decode to an Ed25519 key, or that is not the key in its `agentKey`. `grantError` says which | Who signed it. A grant from an untrusted principal is `invalid` even when it is genuine. A did:key grant that is not `invalid` is `verified` without any proof that the sender holds the key: it is bearer-grade like any grant, and no request signature binds it, since a Web Bot Auth signature names an https origin, never a did:key |
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 |