@agent-custody/receipts 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/gateway.js CHANGED
@@ -9,6 +9,7 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/
9
9
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
10
10
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
11
11
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
12
+ import { strictRefusals } from "./config.js";
12
13
  import { digestOf, dsseVerifiers, dsseVerify, loadPrivateKey, loadPublicKey } from "./crypto.js";
13
14
  import { delegationValidAt, grantChainDigests, verifyDelegation } from "./delegation.js";
14
15
  import { APPROVAL_META_KEY, DEFAULT_APPROVAL_LIFETIME_SECONDS, consumeApproval, verifyApproval, verifyApprovalStatement } from "./approval.js";
@@ -192,10 +193,19 @@ export async function createGatewayHost(cfg, options = {}) {
192
193
  throw new Error(`capture for ${tool} uses mode encrypted, which needs captureKeyEnv`);
193
194
  }
194
195
  // The rules are applied by the issuer to every statement it signs, the authorization included: the gateway hands it the call in full.
195
- const issuer = createIssuer(gatewayKey, cfg.receiptsDir, options.log ?? openLog(cfg, gatewayKey), { exporter: options.exporter ?? openExporter(cfg), capture: { rules: cfg.capture, key: captureKey } });
196
+ if (cfg.strict) {
197
+ const refused = strictRefusals(cfg);
198
+ if (refused.length)
199
+ throw new Error(`agent-custody gateway: ${refused.join("; ")}`);
200
+ }
201
+ const sink = options.log ?? openLog(cfg, gatewayKey);
202
+ if (cfg.strict && sink.kind !== "http")
203
+ throw new Error(`agent-custody gateway: strict mode needs a remote log, and ${sink.where} is a file`);
204
+ const issuer = createIssuer(gatewayKey, cfg.receiptsDir, sink, { exporter: options.exporter ?? openExporter(cfg), capture: { rules: cfg.capture, key: captureKey } });
205
+ const issuedBy = { kind: "gateway", keyid: issuer.keyid, version: GATEWAY_VERSION, ...(cfg.strict ? { strict: true } : {}) };
196
206
  const precommit = new Set(cfg.precommit);
197
207
  const operationRule = (tool) => cfg.operations?.tools.find((rule) => rule.tool === tool);
198
- const consequential = (tool) => !!operationRule(tool) || precommit.has("*") || precommit.has(tool);
208
+ const consequential = (tool) => !!cfg.strict || !!operationRule(tool) || precommit.has("*") || precommit.has(tool);
199
209
  // A fact lookup runs before the policy can decide, because the policy decides on it. It is therefore a read the
200
210
  // gateway makes on the agent's request, never a consequential call: a fact tool named in precommit is a config error.
201
211
  // "*" covers the tools the agent calls; a lookup is the gateway's own read, so only an explicit name makes it consequential.
@@ -508,7 +518,7 @@ export async function createGatewayHost(cfg, options = {}) {
508
518
  const head = {
509
519
  receiptId,
510
520
  timestamp,
511
- issuer: { kind: "gateway", keyid: issuer.keyid, version: GATEWAY_VERSION },
521
+ issuer: issuedBy,
512
522
  principal: { id: delegation.principal, keyid: principalKeyid, provenance: "attested" },
513
523
  agent: { id: delegation.agent, provenance: "attested" },
514
524
  delegation: { envelope: grantEnvelope, provenance: "attested" },
@@ -551,15 +561,15 @@ export async function createGatewayHost(cfg, options = {}) {
551
561
  cached = { ...(result ?? { isError: true, content: [{ type: "text", text: head.operation.status === "failed" ? "Operation failed and the call was not sent; use a new operation id to try again" : `Operation outcome is ${head.operation.status}; reconcile with the provider before taking further action` }] }), _meta: { ...result?._meta, [RECEIPT_META_KEY]: receipt, ...(operation.original && !existsSync(`${cfg.receiptsDir}/${operation.originalReceiptId}.json`) ? { "agent-custody/authorization": operation.original } : {}) } };
552
562
  execution = { status: "withheld", reason: `existing operation: not forwarded again; the stored outcome is ${head.operation.status}`, provenance: "observed" };
553
563
  }
554
- if (!execution && (policy.decision === "allow" || financial && forward) && consequential(tool)) {
564
+ if (!execution && (policy.decision === "allow" || (financial || cfg.strict) && forward) && consequential(tool)) {
555
565
  // A consequential call is committed to the log before it goes out, so that evidence of the side effect exists
556
566
  // before the side effect does. If the log will not take the authorization, the call is not forwarded; in
557
- // observe mode nothing is withheld, and the missing authorization is printed instead.
567
+ // observe mode nothing is withheld, and the missing authorization is printed instead, unless the mode is strict.
558
568
  try {
559
569
  authorization = await issuer.authorize({ ...head, policy: { ...policy, provenance: "observed" } }, captureCtx);
560
570
  }
561
571
  catch (e) {
562
- if (cfg.mode === "observe" && !financial)
572
+ if (cfg.mode === "observe" && !financial && !cfg.strict)
563
573
  console.error(`agent-custody gateway (observe mode): the log did not commit the authorization for ${tool}, receipt ${receiptId}; the call was forwarded without it: ${String(e instanceof Error ? e.message : e)}`);
564
574
  else
565
575
  execution = { status: "withheld", reason: `the log did not commit the authorization, so the call was not forwarded: ${String(e instanceof Error ? e.message : e)}`, provenance: "observed" };
@@ -659,7 +669,8 @@ export async function createGatewayHost(cfg, options = {}) {
659
669
  if (operation)
660
670
  head.operation = operationEvidence(operation, operation.status === "submitted" && !createdOperation ? "unknown" : operation.status);
661
671
  // The call is done, so a log outage now must not tell the agent it failed: the receipt waits in the outbox. An
662
- // operation keeps the old order, because its record holds the bundle and its retry is idempotent.
672
+ // operation keeps the old order, because its record holds the bundle and its retry is idempotent. Strict mode
673
+ // keeps no outbox: the authorization is in the log, and a receipt the log refuses leaves the call incomplete.
663
674
  let issued;
664
675
  let logPending = false;
665
676
  try {
@@ -671,7 +682,7 @@ export async function createGatewayHost(cfg, options = {}) {
671
682
  policy: { ...policy, provenance: "observed" },
672
683
  ...(authorization ? { authorization } : {}),
673
684
  execution,
674
- }, captureCtx, undefined, { deferLog: !operation });
685
+ }, captureCtx, undefined, { deferLog: !operation && !cfg.strict });
675
686
  }
676
687
  catch (e) {
677
688
  if (!(e instanceof ReceiptPending))
@@ -713,7 +724,7 @@ export async function createGatewayHost(cfg, options = {}) {
713
724
  },
714
725
  };
715
726
  }
716
- if (cfg.log && !cfg.precommit.length)
727
+ if (cfg.log && !cfg.precommit.length && !cfg.strict)
717
728
  console.error("agent-custody gateway: a remote log is set and precommit is empty: every call is forwarded before its receipt is logged. Name the consequential tools in precommit, or [\"*\"]; requirePrecommit makes this an error");
718
729
  let flushing;
719
730
  const flushOutbox = () => flushing ??= (async () => {
@@ -727,7 +738,8 @@ export async function createGatewayHost(cfg, options = {}) {
727
738
  return r;
728
739
  })().finally(() => { flushing = undefined; });
729
740
  const autoFlush = () => void flushOutbox().catch((e) => console.error(`agent-custody gateway: the outbox flush failed: ${e instanceof Error ? e.message : String(e)}`));
730
- const outboxTimer = options.autoFlush ? setInterval(autoFlush, 30_000).unref() : undefined;
741
+ // strict mode never adds to the outbox; receipts left there from before it was turned on are appended once, at start
742
+ const outboxTimer = options.autoFlush && !cfg.strict ? setInterval(autoFlush, 30_000).unref() : undefined;
731
743
  if (options.autoFlush)
732
744
  autoFlush();
733
745
  return {
@@ -792,7 +804,7 @@ export async function createGatewayHost(cfg, options = {}) {
792
804
  throw new Error("provider outcome remains pending or unknown; the reservation is retained");
793
805
  const predicate = {
794
806
  receiptId: randomUUID(), timestamp: new Date().toISOString(),
795
- issuer: { kind: "gateway", keyid: issuer.keyid, version: GATEWAY_VERSION },
807
+ issuer: issuedBy,
796
808
  principal: initial.principal, agent: initial.agent, delegation: initial.delegation,
797
809
  session: { id: null, toolUseId: null, provenance: "claimed" }, model: { id: null, provenance: "claimed" },
798
810
  tool: initial.tool, request: { args: lookup.args, argsDigest: digestOf(lookup.args), provenance: "claimed" },
package/dist/index.d.ts CHANGED
@@ -25,6 +25,10 @@ export type { KeyDocument, RemoteSignerOptions, RetiredKey, RunningSigner, Signe
25
25
  export { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoints.ts";
26
26
  export { adminRoutes, welcomeSheet } from "./log-admin.ts";
27
27
  export { fetchWitnessKeys, Witness } from "./witness.ts";
28
+ export { Anchor, ANCHOR_CHAINS, anchorCalldata, anchorLeaf, checkAnchorRecord, resolveAnchorChain } from "./anchor.ts";
29
+ export type { AnchorChain, AnchorCheck, AnchorCheckOptions, AnchorOptions, AnchorRecord, AnchorRun, AnchorTenantOutcome, AnchorTxOutcome } from "./anchor.ts";
30
+ export { evmChain } from "./anchor-evm.ts";
31
+ export type { EvmChainOptions } from "./anchor-evm.ts";
28
32
  export { checkLog, formatLogCheck } from "./log-check.ts";
29
33
  export type { LogCheck, LogCheckOptions, LogCheckResult } from "./log-check.ts";
30
34
  export type { WitnessOptions, WitnessOutcome, WitnessedCheckpoint } from "./witness.ts";
package/dist/index.js CHANGED
@@ -17,6 +17,8 @@ export { connectSigner, fetchLogKeys, localSigner, serveSigner, signerHandler }
17
17
  export { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoints.js";
18
18
  export { adminRoutes, welcomeSheet } from "./log-admin.js";
19
19
  export { fetchWitnessKeys, Witness } from "./witness.js";
20
+ export { Anchor, ANCHOR_CHAINS, anchorCalldata, anchorLeaf, checkAnchorRecord, resolveAnchorChain } from "./anchor.js";
21
+ export { evmChain } from "./anchor-evm.js";
20
22
  export { checkLog, formatLogCheck } from "./log-check.js";
21
23
  export * from "./config.js";
22
24
  export * from "./operations.js";
@@ -8,6 +8,21 @@ export interface LogCheckOptions {
8
8
  maxLagMs?: number;
9
9
  /** how old a checkpoint may be while the head has not moved; default a day, since an idle log is not a broken one */
10
10
  maxIdleMs?: number;
11
+ /** where the anchor publishes its records; with it, `anchorAddress` and `anchorRpcUrls` are required */
12
+ anchorUrl?: string;
13
+ /** the anchor's address, pinned from a source other than the anchor's host */
14
+ anchorAddress?: string;
15
+ /** JSON-RPC endpoints of the anchor's chain; with more than one, they must agree */
16
+ anchorRpcUrls?: string[];
17
+ /** the anchor's chain id; default 1, Ethereum mainnet (`resolveAnchorChain` maps a name to its id) */
18
+ anchorChainId?: number;
19
+ /**
20
+ * each anchored log's id, pinned by the verifier: tenant logs share the log's keys and the anchor's address, so only
21
+ * the id tells one log's anchored checkpoint from another's
22
+ */
23
+ anchorLogIds?: Record<string, string>;
24
+ /** how long the log may stay ahead of its newest anchor, counted from that anchor's block time; default thirteen hours */
25
+ maxAnchorLagMs?: number;
11
26
  fetch?: typeof fetch;
12
27
  now?: () => number;
13
28
  }
package/dist/log-check.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // log is down, its head does not verify, its checkpoints have fallen behind its head, or its witness has stopped
4
4
  // countersigning. Run it from cron on a machine that is not the log's, or from a scheduled workflow; the exit code
5
5
  // is the alert.
6
+ import { checkAnchorRecord } from "./anchor.js";
6
7
  import { dsseVerify, dsseVerifiers } from "./crypto.js";
7
8
  import { verifyConsistency } from "./log.js";
8
9
  import { TREEHEAD_TYPE } from "./receipt.js";
@@ -26,6 +27,55 @@ export async function checkLog(o) {
26
27
  throw new Error(`${res.status} from ${url.pathname}`);
27
28
  return res.json();
28
29
  };
30
+ const anchorChecks = async (tenant, head) => {
31
+ if (!o.anchorAddress || !o.anchorRpcUrls?.length) {
32
+ add(tenant, "anchor verifies on chain", false, "an anchor URL needs the pinned anchor address and at least one JSON-RPC endpoint");
33
+ return;
34
+ }
35
+ const logId = o.anchorLogIds && Object.hasOwn(o.anchorLogIds, tenant) ? o.anchorLogIds[tenant] : undefined;
36
+ if (logId === undefined) {
37
+ add(tenant, "anchor verifies on chain", false, `checking an anchor needs the log id of ${tenant} pinned (--anchor-log-id ${tenant}=<id>)`);
38
+ return;
39
+ }
40
+ const aBase = o.anchorUrl.endsWith("/") ? o.anchorUrl : `${o.anchorUrl}/`;
41
+ let record;
42
+ try {
43
+ record = (await get(new URL(`${tenant}/latest.json`, aBase)));
44
+ }
45
+ catch (e) {
46
+ add(tenant, "anchor verifies on chain", false, e instanceof Error ? e.message : String(e));
47
+ return;
48
+ }
49
+ const r = await checkAnchorRecord(record, { rpcUrls: o.anchorRpcUrls, address: o.anchorAddress, chainId: o.anchorChainId ?? 1, logKeys: keys, fetch: f });
50
+ if (!add(tenant, "anchor verifies on chain", r.ok, r.ok ? `size ${record.treeSize} in block ${r.blockNumber} at ${r.blockTime}${r.finalized ? ", finalized" : ", not yet finalized"}` : r.error))
51
+ return;
52
+ if (!r.ok)
53
+ return;
54
+ // the record's id is its signed checkpoint's (checked above); both it and the head must be the pinned log's
55
+ if (!add(tenant, "anchor and head name the pinned log", record.logId === logId && head.log === logId, `pinned ${logId}, anchored ${record.logId ?? "none"}, head ${head.log ?? "none"}`))
56
+ return;
57
+ add(tenant, "anchor is the newest from its address", r.newer === 0, r.newer === 0 ? undefined : `the address has sent ${r.newer} transaction(s) since this one: the record is not the current anchor`);
58
+ if (record.treeSize > head.treeSize) {
59
+ add(tenant, "head extends the anchored checkpoint", false, `the head at ${head.treeSize} is behind the anchored size ${record.treeSize}: the log was rolled back`);
60
+ }
61
+ else if (record.treeSize === head.treeSize) {
62
+ add(tenant, "head extends the anchored checkpoint", record.rootHash === head.rootHash, record.rootHash === head.rootHash ? `at the anchored size ${head.treeSize}` : `a different root at the anchored size ${head.treeSize}: history was rewritten`);
63
+ }
64
+ else {
65
+ try {
66
+ const proof = (await get(new URL(tenant === "default" ? `consistency?old=${record.treeSize}&new=${head.treeSize}` : `t/${tenant}/consistency?old=${record.treeSize}&new=${head.treeSize}`, base)));
67
+ const ok = verifyConsistency(record.treeSize, record.rootHash, head.treeSize, head.rootHash, proof.hashes);
68
+ add(tenant, "head extends the anchored checkpoint", ok, ok ? `${record.treeSize} -> ${head.treeSize}` : `the head at ${head.treeSize} does not extend the anchored ${record.treeSize}: history was rewritten`);
69
+ }
70
+ catch (e) {
71
+ add(tenant, "head extends the anchored checkpoint", false, e instanceof Error ? e.message : String(e));
72
+ }
73
+ }
74
+ // the block's time is the chain's, so a host that stopped anchoring cannot make a log look covered
75
+ const age = now() - Date.parse(r.blockTime);
76
+ const ahead = head.treeSize > record.treeSize;
77
+ add(tenant, "anchor keeps up with the log", !ahead || age <= (o.maxAnchorLagMs ?? 13 * 3_600_000), ahead ? `the head at ${head.treeSize} is ahead of an anchor ${Math.round(age / 60_000)} min old` : `the anchor covers the head; anchored ${Math.round(age / 60_000)} min ago`);
78
+ };
29
79
  let keys = [];
30
80
  try {
31
81
  keys = (await fetchLogKeys(base, f)).keys;
@@ -60,6 +110,8 @@ export async function checkLog(o) {
60
110
  }
61
111
  if (!head)
62
112
  continue;
113
+ if (o.anchorUrl)
114
+ await anchorChecks(tenant, head);
63
115
  if (!o.checkpointsUrl)
64
116
  continue;
65
117
  const cpBase = o.checkpointsUrl.endsWith("/") ? o.checkpointsUrl : `${o.checkpointsUrl}/`;
package/dist/receipt.d.ts CHANGED
@@ -63,11 +63,13 @@ export interface ReconciliationEvidence {
63
63
  export interface ReceiptPredicate {
64
64
  receiptId: string;
65
65
  timestamp: string;
66
+ /** `strict` is the gateway's own statement that it ran in strict mode: every call precommitted to a remote, hash-only log, and no outbox */
66
67
  issuer: {
67
68
  kind: IssuerKind;
68
69
  keyid: string;
69
70
  version: string;
70
71
  framework?: string;
72
+ strict?: boolean;
71
73
  };
72
74
  principal: {
73
75
  id: string;
package/dist/verify.d.ts CHANGED
@@ -22,6 +22,8 @@ export interface VerifyOptions {
22
22
  logFile?: string;
23
23
  /** If given, every tree head in the bundle must name this log, so a head from another tenant's log cannot be presented as this one's. */
24
24
  logId?: string;
25
+ /** Require a strict gateway receipt: one whose issuer says it ran in strict mode, and whose call, if forwarded, carries the authorization committed before it. */
26
+ requireStrict?: boolean;
25
27
  /**
26
28
  * The withheld values, as `agent-custody reveal` writes them or the party that holds them hands them over: a partial
27
29
  * predicate with `{ $custody: "disclosed", salt, value }` at each withheld path (`{ receiptId, request: { args: { reason: {...} } }, execution: { result: { content: {...} }, error, upstream: { rawBody } }, policy: { errors }, facts: { <name>: { value, args } } }`).
package/dist/verify.js CHANGED
@@ -186,6 +186,12 @@ export function verifyBundle(bundle, opts) {
186
186
  const p = st.predicate;
187
187
  add("issuer kind is known", p.issuer.kind === "gateway" || p.issuer.kind === "sdk", `${p.issuer.kind}${p.issuer.framework ? ` / ${p.issuer.framework}` : ""}`);
188
188
  add("issuer keyid matches signer", p.issuer.keyid === sig.keyid);
189
+ if (opts.requireStrict) {
190
+ add("strict mode in force", p.issuer.kind === "gateway" && p.issuer.strict === true, p.issuer.strict === true ? undefined : "the issuer does not say it ran in strict mode");
191
+ // under strict mode every call is precommitted; a provider read the operator ran is a lookup, not a call
192
+ const forwarded = p.execution.status === "executed" || p.execution.status === "failed" || p.execution.status === "error";
193
+ add("strict: call precommitted before forwarding", !forwarded || !!p.reconciliation || !!p.authorization, forwarded && !p.reconciliation && !p.authorization ? `the call was ${p.execution.status} with no authorization committed first` : undefined);
194
+ }
189
195
  if (p.operation) {
190
196
  add("operation observed by gateway", p.issuer.kind === "gateway" && p.operation.provenance === "observed");
191
197
  if (!p.reconciliation) {
@@ -547,7 +553,7 @@ export function formatReport(r) {
547
553
  return lines.join("\n");
548
554
  const p = r.statement.predicate;
549
555
  lines.push("");
550
- lines.push(`ISSUER: ${p.issuer.kind}${p.issuer.framework ? ` (${p.issuer.framework})` : ""}, ${ISSUER_NOTE[p.issuer.kind] ?? "unknown issuer kind"}`);
556
+ lines.push(`ISSUER: ${p.issuer.kind}${p.issuer.framework ? ` (${p.issuer.framework})` : ""}${p.issuer.strict ? ", strict mode" : ""}, ${ISSUER_NOTE[p.issuer.kind] ?? "unknown issuer kind"}`);
551
557
  lines.push("");
552
558
  lines.push("field provenance value");
553
559
  const row = (f, prov, v) => lines.push(`${f.padEnd(15)} ${prov.padEnd(11)} ${typeof v === "string" ? v : JSON.stringify(v)}`);
@@ -0,0 +1,115 @@
1
+ # Anchoring the log on a chain
2
+
3
+ The log's operator holds the key that signs the log's tree heads. A signed checkpoint therefore shows what the log said at one moment, but it cannot show that the operator never rewrote a tenant's tree later. Anyone who saved an earlier checkpoint can check that, and so can a witness on a machine the operator does not control. The anchor removes the need for either: it commits each new checkpoint to a public chain that nobody in the chain of custody controls: Ethereum mainnet by default, or another EVM chain the installation chooses. A monitor then checks the log against the chain alone.
4
+
5
+ ## What it proves, and what it does not
6
+
7
+ | claim | who can check it | holds against |
8
+ | --- | --- | --- |
9
+ | this signed checkpoint existed no later than this block's time | anyone with a JSON-RPC endpoint, the pinned anchor address, and the log's pinned id | the log's operator, the checkpoints host, the anchor's own host |
10
+ | this is the newest anchor, so no later one says something else | the same: the address's transaction count is on the chain | the anchor's own host |
11
+ | the log today extends what was anchored, so nothing before it was removed or changed | the same, plus the log's consistency proof | the log's operator |
12
+ | the receipts under the checkpoint are true | nobody, from the chain | nothing: a chain commits to existence, not truth |
13
+
14
+ What an anchor rests on depends on the chain; see [choosing the chain](#choosing-the-chain).
15
+
16
+ A rewritten tree is caught between anchors as well as at them: once a checkpoint is anchored, every later head must extend it. What the anchor does not catch is a rewrite inside the window before the first anchor that covers it. That window is at most the anchor's interval, six hours by default, plus the time to finality.
17
+
18
+ The anchor host is not trusted. A record it publishes is checked against the chain:
19
+ - the checkpoint must verify against the log's published keys;
20
+ - it must name the log the verifier pinned;
21
+ - its leaf must be under the anchored Merkle root;
22
+ - a successful transaction from the pinned address to itself must carry exactly that root;
23
+ - that transaction must be the newest the address has sent.
24
+
25
+ The last point is why every anchor transaction covers every watched log. A log that did not move goes in again at its last checkpoint, so the newest transaction always holds each log's current anchor, and a host that serves an older, genuine record is caught by the address's transaction count. The address must therefore send nothing but anchors.
26
+
27
+ Pin the address, the chain, and each log's id from a source other than the anchor's host, such as the welcome sheet, the security page, or the log id in your own receipts' tree heads. Tenant logs share the log's keys and the anchor's address, so only the id tells one tenant's checkpoint from another's. The anchor's `/.well-known/agent-custody-anchor.json` is for discovery only.
28
+
29
+ JSON-RPC endpoints are trusted to report the chain. With several `--anchor-rpc-env` endpoints from different providers, each one must agree on the transaction and its block. A block counts as finalized only when every endpoint says so.
30
+
31
+ ## How it works
32
+
33
+ Each run, for each watched log, the anchor:
34
+
35
+ 1. fetches `latest.json` from the checkpoints host and verifies it against the log's published keys;
36
+ 2. proves, with the log's `GET /consistency`, that it extends the last checkpoint this anchor committed;
37
+ 3. refuses, and writes `<dir>/<tenant>/ALARM.json` and `ALARM-<time>.json`, when it does not, when a second root appears at the same size, or when an unpublished key signed it.
38
+
39
+ When any log has moved, every watched log's checkpoint becomes a leaf of one Merkle tree: the new one for a log that moved, the last one anchored for the rest. Each leaf is the RFC 9162 leaf hash of the checkpoint's canonical envelope. The anchor sends one zero-value transaction from its address to itself, with calldata `0x` + hex(`agent-custody/anchor/1:`) + the 32-byte root. Once the transaction is in a block, each log gets `<dir>/<tenant>/<treeSize>.json` and `latest.json`: its own checkpoint, the transaction, the block, the root, and its inclusion proof. A log's record names no other log.
40
+
41
+ Nothing is sent when no checkpoint has moved, so an idle log costs nothing.
42
+
43
+ A transaction in flight holds the address's nonce, and no new one is sent until its block is finalized:
44
+ - **In a block:** the records are published at once, and the run reports `included`.
45
+ - **Moved by a reorg:** if the transaction lands in another block, the records are written again with that block.
46
+ - **Dropped by a reorg:** if it stays out of every block for 30 minutes (`resendAfterMs`), the same root is sent again.
47
+ - **Finalized:** only now do its checkpoints become the ones that later checkpoints must extend.
48
+ - **Failed:** it is reported, and the next run sends the same checkpoints again.
49
+
50
+ While a transaction is pending, the service checks it every minute, so a record is published soon after it lands.
51
+
52
+ ## Running it
53
+
54
+ ```bash
55
+ export ANCHOR_RPC_URL=https://... # a mainnet JSON-RPC endpoint; a provider URL often carries its key
56
+ export ANCHOR_KEY=0x... # the anchor's private key, for this purpose only
57
+ npm install viem # optional dependency, needed by the anchor only
58
+ agent-custody anchor --log-url https://log.example.com/ --checkpoints-url https://checkpoints.example.com/ \
59
+ --out /srv/anchors --rpc-url-env ANCHOR_RPC_URL --key-env ANCHOR_KEY --tenant acme --tenant default
60
+ ```
61
+
62
+ | flag | default | meaning |
63
+ | --- | --- | --- |
64
+ | `--rpc-url-env NAME` | | the environment variable holding the JSON-RPC URL |
65
+ | `--key-env NAME` | | the environment variable holding the private key, 0x-prefixed hex |
66
+ | `--chain` | `ethereum` | `ethereum`, `base`, `arbitrum`, `optimism`, `polygon`, or any EVM chain id; the endpoint must report the same chain |
67
+ | `--max-fee-gwei` | per chain, below | a run whose fee per gas would exceed this is skipped, not sent; required for a chain given by id alone |
68
+ | `--every` | `21600` | seconds between runs |
69
+ | `--once` | | one run; exit 1 when a log was refused |
70
+
71
+ Serve `<dir>` read-only from a host of its own, or under the checkpoints host.
72
+
73
+ **The key.** Generate it for this purpose and hold only what it needs to pay for anchors. Its address is the anchor's identity: publish it where tenants already read the log's key ids. A key that leaks lets someone else post transactions from that address. A transaction that carries a root nobody computed proves nothing, so the harm is spent funds, not a false anchor. To rotate, publish the new address beside the old one with its date and keep the old one listed, so earlier records still check.
74
+
75
+ **Cost.** One transaction uses about 23,200 gas on Ethereum: 21,000 for the transaction and the calldata floor of EIP-7623 for its 55 bytes. At 2 gwei per gas that is about 0.000046 ETH, and at the default cap of 20 gwei about 0.00046 ETH. An L2 also charges for posting the transaction's data to Ethereum, which the fee cap does not bound, though for 55 bytes it is small. The anchor sends at most one transaction per run, and only when a log grew, so the default interval means at most four a day.
76
+
77
+ ## Choosing the chain
78
+
79
+ The default is Ethereum mainnet. An installation can anchor on any other EVM chain with `--chain`; a verifier then names the same chain with `--anchor-chain`, and a record from another chain fails. The record carries its chain id, and an endpoint that reports another chain fails the check.
80
+
81
+ | `--chain` | chain id | default `--max-fee-gwei` | what an anchor there rests on |
82
+ | --- | --- | --- | --- |
83
+ | `ethereum` | 1 | 20 | Ethereum's consensus; a block is finalized after about two epochs, some 13 minutes |
84
+ | `base` | 8453 | 1 | an OP Stack rollup: one sequencer orders transactions and can delay or refuse one; a block is finalized once its batch is in a finalized Ethereum block |
85
+ | `optimism` | 10 | 1 | the same as Base |
86
+ | `arbitrum` | 42161 | 1 | an Arbitrum rollup: the same shape, with its own sequencer, finalized once its batch is in a finalized Ethereum block |
87
+ | `polygon` | 137 | 1000 | Polygon PoS: its own validator set, which checkpoints to Ethereum; finality is Polygon's, not Ethereum's |
88
+ | a chain id | that id | none: give one | whatever that chain's consensus is; say so to whoever relies on the anchor |
89
+
90
+ What a chain's sequencer or validators can do is delay an anchor or refuse it, which `log-check` shows as an anchor that does not keep up. Rewriting a block that a verifier saw finalized would mean breaking that chain's own guarantees, which differ by chain. Choose the chain the people who rely on the log already trust. A verifier checks finality through `eth_getBlockByNumber("finalized")`, and every named chain's endpoints answer it.
91
+
92
+ The fee caps are in gwei per gas of the chain's own gas token: ETH on Ethereum and the L2s, POL on Polygon.
93
+
94
+ ## Checking it
95
+
96
+ ```bash
97
+ export ETH_RPC_A=https://... ETH_RPC_B=https://...
98
+ agent-custody log-check --log-url https://log.example.com/ --tenant acme \
99
+ --anchor-url https://anchors.example.com/ --anchor-address 0x... --anchor-rpc-env ETH_RPC_A --anchor-rpc-env ETH_RPC_B \
100
+ --anchor-chain ethereum --anchor-log-id acme=acme
101
+ ```
102
+
103
+ Each log being checked needs its id pinned with `--anchor-log-id <tenant>=<log id>` (repeatable). Five checks are added per log:
104
+
105
+ - **`anchor verifies on chain`**: the record checks out against the chain as described above. The detail says whether the block is finalized yet.
106
+ - **`anchor and head name the pinned log`**: the anchored checkpoint and the log's current head both carry the pinned id, so another tenant's record cannot stand in for this log's.
107
+ - **`anchor is the newest from its address`**: the chain's count of transactions from the address shows that none came after this record's.
108
+ - **`head extends the anchored checkpoint`**: the log's head is at or beyond the anchored size, and the log's consistency proof shows that it extends the anchored root. A head below the anchored size is a rolled-back log. A head that does not extend the anchored root is a rewritten one.
109
+ - **`anchor keeps up with the log`**: a head ahead of its newest anchor fails once that anchor's block is older than `--max-anchor-lag` (default 46800 s, thirteen hours). The block's time is the chain's, so an anchor that stopped cannot be hidden by its host.
110
+
111
+ Anchors are sent only when a log grows. A log that has been quiet for longer than the lag therefore shows this failure after it grows, until the anchor's next run covers it. Keep the anchor's interval well under the lag.
112
+
113
+ An `--anchor-url` without `--anchor-address`, at least one `--anchor-rpc-env`, and a pinned log id for each log is a failure, never a skipped check.
114
+
115
+ In code, `checkAnchorRecord(record, { rpcUrls, address, chainId, logKeys })` checks one record and needs no Ethereum library. Its `newer` is the number of transactions the address has sent since the record's, so 0 means this is the current anchor. `new Anchor({ logUrl, checkpointsUrl, tenants, chain, outDir })` runs the anchor with any `AnchorChain`, and `evmChain({ rpcUrl, privateKey, chainId, maxFeeGwei })` is the EVM one. `resolveAnchorChain("base")` gives a named chain's id and default cap, and `ANCHOR_CHAINS` lists them. Example 33 runs the whole loop against an in-memory chain; the tests drive real signed transactions.
@@ -202,7 +202,8 @@ docker run --rm -v "$PWD/config:/config:ro" -v gateway-data:/data --env-file .en
202
202
  | a stdio `command` exists, and a script argument exists | error, and a warning |
203
203
  | the receipts, log, revocation, operations database, and approvals paths can be written, and the revocation file is a JSON array | error |
204
204
  | the grant the config names verifies, and is inside its window | error, and a warning near expiry |
205
- | a remote log with an empty `precommit` | warning: a log outage after a call puts its receipt in the outbox, so the side effect is in the log only after the outbox is appended |
205
+ | a remote log with an empty `precommit` | warning: a log outage after a call puts its receipt in the outbox, so the side effect is in the log only after the outbox is appended. Not reported under `strict`, which precommits every tool |
206
+ | what [strict mode](usage.md#strict-mode) would refuse: a local log, a remote log that is not `hashOnly`, one without `keys` | with `"strict": true`, **error**: the gateway does not start; without it, listed under `strict` as what turning it on would refuse |
206
207
 
207
208
  With **`--connect`** it also starts the upstreams, which is where an unreachable server or **two upstreams offering the same tool** shows up, prints the tools they offer, and compares every tool name in `precommit`, `facts`, `approvals`, `operations`, and the grant's scopes with that list. A name in `precommit`, `facts`, `approvals`, or `operations` that no upstream offers is an **error** (for `precommit` it means the tool you meant is forwarded before it is logged); a grant scope that names nothing is a warning. `--connect` starts your stdio upstreams and may create the receipts directory. It exits 1 on any error, so it can gate a deploy.
208
209
 
@@ -218,6 +219,9 @@ With **`--connect`** it also starts the upstreams, which is where an unreachable
218
219
  | `exactly one of logFile or log is required` | both, or neither | a local file, or a remote log |
219
220
  | `precommit with a remote log needs log.keys` | a remote log gating consequential calls without a pinned key | add the log's public key file to `log.keys` |
220
221
  | `requirePrecommit is set and precommit is empty` | a remote log with no consequential tools named | name them in `precommit`, or `["*"]` |
222
+ | `strict mode needs a remote log` | `"strict": true` with `logFile`, a log the operator can rewrite | set `log.url` to a log someone else runs |
223
+ | `strict mode needs log.hashOnly` | `"strict": true` with a log that would receive whole receipts | add `"hashOnly": true` to `log` |
224
+ | `strict mode needs log.keys` | `"strict": true` with the log's key not pinned | add the log's public key file to `log.keys` |
221
225
  | `fact "f" uses tool t, which precommit names as consequential` | a fact lookup must be a read | use a read tool for the fact |
222
226
  | `ENOENT … gateway.key` | the key file does not exist | `agent-custody keygen`, or let the container create it |
223
227
  | `EROFS` or a permission error on `receipts` | a writable path points into the read-only `/config` | use an absolute path under `/data` |
@@ -0,0 +1,82 @@
1
+ # Payment mandates and agent identity: AP2, Visa TAP, Mastercard Agent Pay
2
+
3
+ Design, not yet built. It tracks issues #185 and #186: fitting the grant and the receipt to the payment networks' standards, so that the networks define the authority and agent-custody keeps the evidence of what was done under it.
4
+
5
+ Sources read on 26 October 2026: AP2 v0.2 ([google-agentic-commerce/AP2](https://github.com/google-agentic-commerce/AP2), `docs/ap2/specification.md` and `agent_authorization.md`), and Visa's Trusted Agent Protocol ([visa/trusted-agent-protocol](https://github.com/visa/trusted-agent-protocol)). Mastercard Agent Pay has no public specification that we could find; what follows on it comes from secondary sources.
6
+
7
+ ## What AP2 v0.2 defines
8
+
9
+ - **Mandates are SD-JWT verifiable credentials.** A `vct` claim names the type and version: `mandate.checkout.1`, `mandate.payment.1`, and the open variants `mandate.checkout.open.1` and `mandate.payment.open.1`.
10
+ - An **open** mandate carries `constraints` and the agent's key in `cnf` (RFC 7800).
11
+ - A **closed** mandate is bound to one transaction by the agent's key-binding JWT.
12
+ - Verifiers always receive a closed mandate, sometimes with the open mandate it came from.
13
+ - **Two modes.** In human-present mode, the user signs the closed mandate directly. In human-not-present mode, the user signs an open mandate and the agent signs the closed one under its constraints.
14
+ - **Payment constraints:** recurrence, allowed payees, allowed instruments, allowed payment initiation service providers, an amount range, a budget, the checkout reference, and an execution date. An unknown constraint fails.
15
+ - **Mandate receipts.** Every verifier returns a signed Mandate Receipt JWT on acceptance *and* on rejection: `iss` (the verifier), `result` (`success` or `error`), `reference` (a hash of the mandate it received, computed like `sd_hash`), and, on an error, an `error` code (`invalid_credential`, `unresolved_constraint`, `invalid_mandate`, `mandates_not_supported`) with an optional `error_description`. In the autonomous flow, an agent may not present another open mandate until the previous one has a rejection receipt.
16
+ - **Not only payments.** `agent_authorization.md` is a general framework: new mandate types and constraint types MAY be defined, named with an rDNS prefix.
17
+ - **What AP2 leaves open: dispute evidence.** The mandates and receipts "provide a non-repudiable picture of the transaction", but *retention and retrieval are outside the scope of this specification*. That gap is exactly agent-custody's job.
18
+
19
+ ## How agent-custody maps onto it
20
+
21
+ | AP2 | agent-custody today | What changes |
22
+ |---|---|---|
23
+ | Open mandate, user-signed, with `cnf` = the agent's key and `constraints` | Grant: principal-signed DSSE, with `agentKey`, `scopes`, and a time window | Accept an open AP2 mandate as a grant. Define our own mandate type for non-payment tools, so a grant can be issued as an AP2 SD-JWT VC. |
24
+ | Closed mandate, user-signed (human present) | Payload-bound approval: principal-side keys sign the exact tool, arguments, amount and beneficiary | Accept a closed AP2 payment mandate as the approval for a payment tool. |
25
+ | Closed mandate, agent-signed under an open mandate (human not present) | A call checked against the grant and the Cedar policy | The gateway verifies the chain and evaluates every constraint before the policy runs. A failed constraint is a denial with a receipt, and an AP2 rejection receipt goes back to the agent. |
26
+ | Verifier | The gateway | The gateway becomes an AP2 verifier for the actions it gates. |
27
+ | Mandate Receipt JWT (`iss`, `result`, `reference`) | The signed receipt | Each receipt carries the mandate's `reference` and the outcome. For every mandate presented, whether accepted or rejected, the gateway also returns a standard Mandate Receipt JWT, so an AP2 party reads our answer in its own format. |
28
+ | Dispute evidence, retention out of scope | The transparency log, chain anchoring, retention, the verifiers | The mandate chain and its receipts are logged and anchored, and are retrievable by `transaction_id`. |
29
+ | One open mandate presented at a time | Single-use approvals (`usedDir`) | Track open-mandate presentations the same way, for recurrence and budget constraints. |
30
+
31
+ **The line for the deck:** AP2 defines who authorised what; agent-custody proves what was then done with it, and keeps the proof where nobody can change it.
32
+
33
+ ## Visa Trusted Agent Protocol
34
+
35
+ TAP is an identity layer between an agent and a merchant.
36
+ - The agent signs each HTTP request with RFC 9421 message signatures, bound to the merchant's domain and the operation, with a timestamp and a nonce.
37
+ - Merchants verify the key against Visa's directory.
38
+ - It doesn't move money and doesn't carry a mandate.
39
+
40
+ The fit is at the gateway's outbound side. The gateway already sits between the agent and the merchant. With the agent's TAP key held by the gateway, ideally in the TEE (#179), it signs the outbound request, and the receipt records the signature parameters. The merchant then sees a trusted agent, and the receipt shows exactly which request carried that identity.
41
+
42
+ ## Mastercard Agent Pay
43
+
44
+ Reported to work through agentic tokens: MDES tokens scoped to an agent, a merchant and a consent policy, with spending limits held by the issuer. No public specification was found. Until one exists, the plan is limited to recording the token reference and its scope in the receipt, as a fact the gateway observed.
45
+
46
+ ## Plan, in order
47
+
48
+ 1. **Record AP2 mandates in receipts.**
49
+ - Verify an SD-JWT VC mandate chain (ES256 and RFC 7800 `cnf`), with issuer keys pinned in the gateway config.
50
+ - Evaluate the payment constraints.
51
+ - Record the `vct`, the `reference`, each constraint's result, and the issuer's key id in the receipt.
52
+ - Under a capture rule, undisclosed claims stay out, and the disclosed ones are treated like arguments.
53
+ - This needs vectors, and both verifiers (`src/verify.ts` and `site/verifier/verify-web.ts`) change together.
54
+ 2. **Return Mandate Receipts, on acceptance and on rejection.** For every mandate presented with a call, the gateway returns an AP2 Mandate Receipt JWT in `_meta`, bound to the agent-custody receipt id, including when the mandate is refused. A rejection is what lets an AP2 agent retry, fall back, or present its next open mandate, so a refusal must never produce only our own denial receipt.
55
+
56
+ | Gateway outcome | `result` | `error` |
57
+ | --- | --- | --- |
58
+ | Chain and constraints verify, and the call is allowed | `success` | |
59
+ | The SD-JWT, its key binding or the chain fails, the issuer isn't trusted, or the mandate has expired | `error` | `invalid_credential` |
60
+ | An unknown constraint type, or a constraint the gateway can't evaluate | `error` | `unresolved_constraint` |
61
+ | Constraints evaluate false, or the mandate doesn't cover this tool or these arguments | `error` | `invalid_mandate` |
62
+ | The tool has no mandate configuration, or the presented `vct` isn't supported | `error` | `mandates_not_supported` |
63
+
64
+ - **Authorization, not outcome.** The JWT's `result` is the authorization decision only. Whether the tool then ran, failed, or was withheld, and how a payment later settles, are recorded in the agent-custody receipt (`execution`, `operation`, `reconciliation`), never in the mandate receipt.
65
+ - **Logged.** The mandate receipt's digest is recorded in our receipt, so the rejection evidence is logged too.
66
+ - **No leaks.** `error_description` never carries a withheld value or a policy's internal reason.
67
+ - **One mandate in flight.** An open mandate counts as in flight from its presentation until its receipt, whichever the result.
68
+ 3. **An agent-custody mandate type for tools.**
69
+ - Name: `dev.agent-custody.mandate.tool.1`.
70
+ - Constraints: allowed tools, an argument range, an amount range, payees, and a window.
71
+ - A principal can then issue an AP2-format open mandate in place of a DSSE grant, and the gateway accepts both.
72
+ 4. **The TAP signer.** RFC 9421 signatures on outbound requests to configured merchants, with the key held by the gateway, and the signature parameters recorded in the receipt.
73
+ 5. **Dispute retrieval.** Look a receipt up by AP2 `transaction_id`, and produce an evidence pack with the mandate chain, the AP2 receipts, our receipt, the inclusion proof and the anchor.
74
+
75
+ ## Open questions
76
+
77
+ - **SD-JWT implementation.** Use an existing library (the OpenWallet Foundation's `@sd-jwt/*`), or write a small verifier ourselves, the way the rest of the verifier is dependency-light? The browser verifier needs it too.
78
+ - **Delegation chains.** AP2 uses the Delegate SD-JWT draft for chains, which is not yet stable. Pin to the draft revision that AP2 v0.2's reference implementation uses, and test against its fixtures.
79
+ - **Keys.** Mandates are ES256, while our receipts are Ed25519. The gateway verifies ES256 and keeps signing with Ed25519, so no format change is needed. ML-DSA (#11) is unaffected.
80
+ - **Privacy.** A mandate's undisclosed claims must never reach a receipt in clear. Disclosed payee and instrument details follow the capture rule, and the capture canary test gets a mandate path.
81
+ - **A refusal by the gateway's own policy.** If the mandate verifies but the operator's Cedar policy, an approval rule, or strict mode refuses the call, which code applies? `invalid_mandate` would wrongly blame the mandate. Our recommendation is a namespaced code, `dev.agent-custody.policy_denied`, with a short public reason, if AP2 allows codes beyond the four it defines. Otherwise `invalid_mandate`, with the cause in `error_description`. Confirm with the AP2 maintainers.
82
+ - **Which party we are.** In AP2 terms the gateway is a verifier for the actions it gates, not a Credential Provider or a Network. Say so in the docs, so nobody reads agent-custody as a payment network component.