@agent-custody/receipts 0.9.0 → 0.11.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.
@@ -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.
@@ -127,6 +127,6 @@ node examples/10-support-recovery.ts
127
127
  bun run test test/codex-recovery.test.ts test/examples.test.ts
128
128
  ```
129
129
 
130
- The checks cover approval, stale plans, revoked support authority, duplicate-credit prevention, receipt tampering, store/evidence consistency, missing observed dependencies, and runs without agent activity.
130
+ The checks cover approval, stale plans, revoked support authority, duplicate-credit prevention, receipt tampering, store/evidence consistency, missing observed dependencies (a credit or a benefit that no memory read supports), the refresh after a partial recovery, and runs without agent activity.
131
131
 
132
132
  Codex integration references: [non-interactive mode](https://learn.chatgpt.com/docs/non-interactive-mode), [MCP configuration](https://learn.chatgpt.com/docs/extend/mcp?surface=cli).
@@ -119,6 +119,7 @@ What each part does:
119
119
  | `trustedPrincipalKeys` | the public keys whose grants this gateway accepts. Only public keys go here. |
120
120
  | `facts` | before a refund, the gateway calls `customer.lookup` itself with the customer id from the call, and the policy reads the answer as `context.facts.customer`. |
121
121
  | `precommit` | the consequential tools: the gateway commits the authorization to the log before it forwards, and withholds the call if the log will not take it. |
122
+ | `requirePrecommit` | with a remote log, the gateway does not start when `precommit` is empty. Without it, the gateway prints a warning. |
122
123
  | `revokedGrants` | the file `agent-custody revoke` appends to; the gateway re-reads it on every call. |
123
124
  | `receiptsDir`, `log` | full receipts stay on the gateway's disk. The hosted log receives only their hashes (`hashOnly`), and its public key is pinned (`keys`), which `precommit` with a remote log requires. |
124
125
 
@@ -201,7 +202,8 @@ docker run --rm -v "$PWD/config:/config:ro" -v gateway-data:/data --env-file .en
201
202
  | a stdio `command` exists, and a script argument exists | error, and a warning |
202
203
  | the receipts, log, revocation, operations database, and approvals paths can be written, and the revocation file is a JSON array | error |
203
204
  | the grant the config names verifies, and is inside its window | error, and a warning near expiry |
204
- | a remote log with an empty `precommit` | warning: a log outage after a call leaves its side effect without evidence |
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 |
205
207
 
206
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.
207
209
 
@@ -216,6 +218,10 @@ With **`--connect`** it also starts the upstreams, which is where an unreachable
216
218
  | `exactly one of upstream or upstreams is required` | both, or neither | use `upstream` for one source and `upstreams` for several |
217
219
  | `exactly one of logFile or log is required` | both, or neither | a local file, or a remote log |
218
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` |
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` |
219
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 |
220
226
  | `ENOENT … gateway.key` | the key file does not exist | `agent-custody keygen`, or let the container create it |
221
227
  | `EROFS` or a permission error on `receipts` | a writable path points into the read-only `/config` | use an absolute path under `/data` |
package/docs/console.md CHANGED
@@ -37,7 +37,7 @@ It listens on `127.0.0.1:8795` and prints the URL. Open it and sign in with the
37
37
 
38
38
  ## What a saved policy does
39
39
 
40
- The gateway reads `policy.cedar` when it starts, so **a saved policy applies after the gateway restarts**, and the console says so each time. Reloading a policy without a restart is a separate change. The save is guarded: Cedar must parse the text; and the operator must confirm a policy that has no `permit` rule (a `permit(` in a comment does not count), because every call would be denied, or a `permit` rule with **no action and no condition**, which allows every tool in a grant's scopes and which a replay cannot show. A save made from a copy that is no longer the file on disk is refused with `409`. The digest check, the history copy, and the write happen under one lock, in this process and, through a lock file in the state directory, across consoles that share it, so two administrators cannot overwrite each other. The previous version is kept under `console/policy-history/` and the change goes in the audit trail.
40
+ A running gateway re-reads `policy.cedar` when it changes, so **a saved policy applies from the gateway's next call**, with no restart, and the gateway records the change in `receipts/policy-reloads.jsonl`. The save is guarded: Cedar must parse the text; and the operator must confirm a policy that has no `permit` rule (a `permit(` in a comment does not count), because every call would be denied, or a `permit` rule with **no action and no condition**, which allows every tool in a grant's scopes and which a replay cannot show. A save made from a copy that is no longer the file on disk is refused with `409`. The digest check, the history copy, and the write happen under one lock, in this process and, through a lock file in the state directory, across consoles that share it, so two administrators cannot overwrite each other. The previous version is kept under `console/policy-history/` and the change goes in the audit trail.
41
41
 
42
42
  ## How it is protected
43
43
 
@@ -52,7 +52,6 @@ The gateway reads `policy.cedar` when it starts, so **a saved policy applies aft
52
52
 
53
53
  - It does not issue grants. A grant is signed by a principal's key, which belongs where grants are issued ([configuration.md](configuration.md#the-principals-key)).
54
54
  - It does not edit `gateway.json`: upstreams, facts, and `precommit` are changed in the file, and the gateway restarted. The Overview and Check tabs show them.
55
- - A policy change needs a gateway restart.
56
55
  - The credential variables are not checked in the console, and an upstream that needs one is not started there.
57
56
  - One token, no per-user accounts, and the audit records the address and not a person.
58
57
  - It reads the local receipts directory. With a remote log it verifies receipts against the keys but not the log's inclusion proofs.
@@ -68,7 +67,7 @@ Every route except `GET /` (the page) and `GET /healthz` needs `Authorization: B
68
67
  | `POST /api/check` `{ connect? }` | the check; `connect` starts the upstreams |
69
68
  | `GET /api/policy` | the policy text, its digest, and the earlier versions kept |
70
69
  | `POST /api/policy/validate` `{ text }` | does Cedar parse it, and which things need confirming (`issues`) |
71
- | `POST /api/policy/simulate` `{ text }` | replay up to 1,000 verified receipts against it |
70
+ | `POST /api/policy/simulate` `{ text }` | replay up to 1,000 verified receipts against it; the report counts reconciliation receipts (provider reads, no policy decision) in `reconciliations`, apart from `evaluated` |
72
71
  | `PUT /api/policy` `{ text, expectDigest, confirm? }` | save it; `400` unless `confirm` is true when the policy has an issue the validate route reported; `409` if the file changed |
73
72
  | `POST /api/grants/inspect` `{ grant }` | status, agent, scopes, window, digest |
74
73
  | `POST /api/grants/revoke` `{ grant }` | add its digest to the revocation file |
package/docs/policies.md CHANGED
@@ -215,10 +215,12 @@ For SDK receipts, use the application's public key as `--issuer-key`; no princip
215
215
 
216
216
  A gateway that dies after it forwards a `precommit` call leaves `<id>.authorization.json` and no `<id>.json`. The command verifies each such file as an authorization statement (the issuer key, the tree head, and the inclusion proof) and lists the call under `skipped`, so the report is `INCOMPLETE`. An authorization that does not verify fails the command. An authorization that sits beside its receipt is not read twice.
217
217
 
218
+ The command also checks that each `<id>.json` holds receipt `<id>`. A receipt under another file name fails the command, so a copy over the name of another receipt cannot hide that call.
219
+
218
220
  A receipt under a capture rule needs its withheld arguments and fact values to replay. Give `--capture-key-env NAME` to decrypt the values that mode `encrypted` withheld, as `verify` does. Give `--disclose <file>`, which you can repeat, for the values that mode `digest` withheld. Each file is a disclosure as `reveal` writes it, and it applies only to the receipt that its `receiptId` names. A key or a disclosure that does not match a commitment skips that receipt as malformed. The key comes from the environment, never from a flag value.
219
221
 
220
222
  The report lists every call whose `allow` or `deny` decision changes, grouped by tool and the proposed decision's policy ids or evaluation errors, with the receipt ids and both decisions. A call executed in observe mode may already have a recorded deny: replay compares that recorded decision, not whether the tool ran. Calls with the same decision stay unchanged even when different policy ids match. Cedar evaluation errors remain denials.
221
223
 
222
- Every run records a `runId`, `timestamp`, the proposed text's sha256 as `policyDigest`, and the original digests as `previousPolicyDigests`. `--out` saves the full JSON report, and `--json` prints it to stdout. Changes alone exit 0. A report that cannot replay every call says `INCOMPLETE` and exits 1: `skipped` names each receipt and why. This includes record-only receipts with no policy baseline, withheld arguments or fact values, calls whose receipt is missing, and calls stopped before Cedar could evaluate. Grant failures cannot become permits through a policy change, and neither can an approval refusal: the gateway checks the approval before Cedar runs, so the call is skipped as a non-policy gate. The approval record says so even under a private rule. Withheld results alone do not prevent replay.
224
+ Every run records a `runId`, `timestamp`, the proposed text's sha256 as `policyDigest`, and the original digests as `previousPolicyDigests`. `--out` saves the full JSON report, and `--json` prints it to stdout. Changes alone exit 0. A report that cannot replay every call says `INCOMPLETE` and exits 1: `skipped` names each receipt and why. This includes record-only receipts with no policy baseline, withheld arguments or fact values, calls whose receipt is missing, and calls stopped before Cedar could evaluate. Grant failures cannot become permits through a policy change, and neither can an approval refusal: the gateway checks the approval before Cedar runs, so the call is skipped as a non-policy gate. The approval record says so even under a private rule. Withheld results alone do not prevent replay. A reconciliation receipt is a provider read, so no policy decision exists to replay. The report counts it in `reconciliations`, not in `evaluated` or `skipped`, and it does not make the report incomplete. A reconciliation whose original receipt is missing is the exception: the call that it settles cannot be replayed, so the report skips that call and says `INCOMPLETE`. The library trusts a reconciliation receipt only after `verifyBundle` accepts it; the CLI and the console verify first.
223
225
 
224
226
  The report is an analysis of the supplied receipt directory; it does not prove that the directory contains the whole history. Keep the report beside the proposed policy and review the changed receipt ids before switching from observe mode to enforcement. [Tutorial 28](../examples/28-policy-simulation.ts) records three refunds, stops the gateway, and replays them against a lower limit.
@@ -51,7 +51,7 @@ Each row names the attacker, the move, the defence, and whether the defence is a
51
51
  | attack | defence | kind |
52
52
  | --- | --- | --- |
53
53
  | Rewrite a receipt after the fact | The receipt's envelope is signed by the gateway key, which the operator holds, so the signature alone does not stop this. What stops it is the log: the leaf hash of the original envelope is in a tree whose head the log signed, and a rewritten receipt has a different hash with no inclusion proof. | evidence, with a remote log; deployment, with a local log the operator can rewrite |
54
- | Drop a receipt | The log's tree only grows, and consistency proofs between any two heads show nothing was removed. A receipt the operator never logged never existed as evidence, which is the point of `precommit` for consequential calls: the authorization leaf goes in before the action. | evidence for logged receipts; withheld calls for pre-committed tools |
54
+ | Drop a receipt | The log's tree only grows, and consistency proofs between any two heads show nothing was removed. A receipt the operator never logged never existed as evidence, which is the point of `precommit` for consequential calls: the authorization leaf goes in before the action. [Strict mode](usage.md#strict-mode) does that for every call, with a remote hash-only log and no outbox, and its receipts say so, so a verifier can require it; a modified gateway can still claim strict mode. | evidence for logged receipts; withheld calls for pre-committed tools, and for every call under strict mode |
55
55
  | Forge a receipt for an action that never happened | Nothing in the log stops the operator logging a fabricated receipt; the log commits to existence, not truth. What limits it: the upstream's signature over the result when the upstream signs, provider attestations where the provider delivers them, and the principal's signature on the grant. A forged receipt for a signing upstream fails its `upstream` checks. | evidence, where the upstream signs; otherwise the operator's word |
56
56
  | Replace the policy and claim a different one decided | The receipt carries the sha256 of the policy text; a verifier with the policy file can check it, and a policy change is a different digest in every later receipt. | evidence |
57
57
  | Produce a second, cleaner history | With a remote log, both histories would need heads signed by the log's key at the same size with different roots; the checkpoints host and the witness make that detectable. With a local log, a copy taken earlier by someone else is the only defence. | evidence with a witnessed remote log |
@@ -76,7 +76,7 @@ Each row names the attacker, the move, the defence, and whether the defence is a
76
76
  | attack | defence | kind |
77
77
  | --- | --- | --- |
78
78
  | Read receipt contents | The hosted log runs with `--hash-only` and refuses a full leaf at append, so no receipt reaches the log process even from a misconfigured gateway or a stolen token; the tenant's `hashOnly` setting keeps the receipt from ever leaving their machine. A log an operator runs for themselves may accept full leaves. | evidence: the server refuses; deployment on the tenant's side |
79
- | Rewrite a tenant's tree | Every head is signed and published as a checkpoint on a second host; a rewrite means two signed heads at one size with different roots, or a later head that does not extend an earlier one. Anyone holding an earlier head detects it with `audit`; the monitor does it every ten minutes; the witness countersigns only heads that extend the last it signed. | evidence, given a witness or an earlier head held elsewhere |
79
+ | Rewrite a tenant's tree | Every head is signed and published as a checkpoint on a second host; a rewrite means two signed heads at one size with different roots, or a later head that does not extend an earlier one. Anyone holding an earlier head detects it with `audit`; the monitor does it every ten minutes; the witness countersigns only heads that extend the last it signed; the anchor commits each checkpoint to Ethereum, and `log-check --anchor-url` fails a head that does not extend the anchored one. | evidence, given a witness or an earlier head held elsewhere |
80
80
  | Show different histories to different verifiers | Same: checkpoints are public and the witness sees one history. Without a witness, two verifiers who compare heads detect it, and nobody else does. | evidence with a witness; otherwise detection needs comparison |
81
81
  | Mint a token for a tenant and append noise | Appends are hashes with no content; the tenant's export and usage show leaves and live tokens they did not make, and the audit trail, which the tenant's export carries, records who minted what and from where. | deployment |
82
82
  | Sign with a key not in the key document | Verifiers pin by keyid from the published document; a head signed by an unpublished key fails. Retired keys stay published so old heads keep verifying, and a rotation is announced with its date. | evidence |
@@ -90,6 +90,20 @@ Each row names the attacker, the move, the defence, and whether the defence is a
90
90
  | Refuse a true history | An alarm with no consistency failure behind it is a false alarm; the log's consistency proof settles it in public. Verifiers who require a witness signature see a gap, which is the correct outcome for a disputed period. | evidence |
91
91
  | Collude with the log operator | Two independent operators are the assumption. A witness on the log operator's machine proves nothing, and the deployment guide says so. | assumption |
92
92
 
93
+ ### By the anchor
94
+
95
+ | attack | defence | kind |
96
+ | --- | --- | --- |
97
+ | Publish a record for a checkpoint it never anchored | The record is checked against the chain: the transaction must come from the pinned address to itself, succeed, and carry exactly the root the record's inclusion proof leads to, from a checkpoint the log's keys signed. | evidence |
98
+ | Anchor a rewritten history | The anchor proves each checkpoint extends the last one it anchored, and refuses with an alarm otherwise. An anchor that skipped the proof would still leave two anchored roots that cannot both extend the earlier one, in public. | evidence |
99
+ | Serve an older, genuine record as the current one | Every anchor transaction covers every watched log, and the verifier requires the record's transaction to be the newest from the address, by the address's transaction count on the chain. | evidence |
100
+ | Serve another tenant's record for this log | Tenant logs share the log's keys and the anchor's address, so the verifier pins each log's id; the anchored checkpoint and the current head must both name it. | evidence, given the pinned id |
101
+ | Stop anchoring | A head ahead of its newest anchor fails once that anchor's block, timed by the chain, is older than `--max-anchor-lag`. Between anchors, a rewrite is caught only once a later anchor or another holder of a head disagrees. | detection |
102
+ | Count an anchor a reorg removed | The anchor holds a transaction until its block is finalized, writes its records again if a reorg moves it, and sends the same root again if a reorg drops it. A verifier reports whether the record's block is finalized. | evidence once finalized |
103
+ | Leak its key | Someone else can spend the funds and post transactions from the address. A root that no checkpoint leads to proves nothing, so a leaked key cannot make a false record check out. | evidence |
104
+ | Anchor on a chain a few parties control | The installation chooses the chain, and the record names it. On an L2 a sequencer can delay or refuse an anchor, which shows as an anchor that does not keep up. A finalized block is as hard to rewrite as that chain makes it, which differs by chain (`docs/anchoring.md` lists what each rests on). | assumption: the chain's own guarantees |
105
+ | Lie through a JSON-RPC endpoint | Give `log-check` several endpoints from different providers: they must agree on the transaction and its block, and a block counts as finalized only when every endpoint says so. | assumption: not every endpoint lies the same way |
106
+
93
107
  ### On the network
94
108
 
95
109
  | attack | defence | kind |
package/docs/tutorials.md CHANGED
@@ -42,6 +42,8 @@ Suggested reading order is the numbering. Output lands in `examples-out/`, which
42
42
  | 30 | payload-bound human approvals | [30-payload-bound-approvals.ts](../examples/30-payload-bound-approvals.ts) | two people sign the exact refund; missing approval, one signer, changed amount or beneficiary, extra arguments, and expiry are refused; the approved call executes once, its replay is refused, and every receipt verifies with separately trusted approval keys | `src/approval.ts`, `src/gateway.ts`, `src/verify.ts` |
43
43
  | 31 | enterprise sign-in and roles | [31-enterprise-sign-in.ts](../examples/31-enterprise-sign-in.ts) | an enterprise tenant signs in through its own identity provider, a stand-in OIDC IdP: the operator sets single sign-on, a member joins as readonly and is refused a policy write, an owner promotes them to reviewer, and enforcement turns password sign-in off | `src/sso.ts`, `src/portal.ts` |
44
44
  | 32 | the gateway console | [32-console.ts](../examples/32-console.ts) | a gateway that has made two receipts, and its operator's console: a token on every route, the receipts with a verdict each, a stricter policy replayed against the recorded calls before it is saved, the save recorded with the old version kept and a stale edit refused, and a grant inspected, revoked, and then refused by the gateway | `src/console.ts`, `src/console-page.ts` |
45
+ | 33 | anchoring the log on a chain | [33-chain-anchor.ts](../examples/33-chain-anchor.ts) | a log publishes a checkpoint, the anchor commits it to a stand-in chain in one transaction, and `log-check` passes against the chain; the operator swaps in a rewritten log under the same key and log id, and `log-check` fails it from the chain alone |
46
+ | 34 | strict mode | [34-strict-mode.ts](../examples/34-strict-mode.ts) | `check` lists what strict mode would refuse; a local log and a log that is not hash-only are refused at startup; behind a hash-only log with a pinned key, a read is precommitted and its receipt says `issuer.strict`; `requireStrict` accepts it and refuses an ordinary receipt; with the log down the call is not forwarded and the outbox stays empty | `src/config.ts`, `src/gateway.ts`, `src/check.ts`, `src/verify.ts` |
45
47
 
46
48
  ## How policies are defined, in one paragraph
47
49
 
@@ -53,6 +55,7 @@ A policy is a Cedar file. The gateway turns each tool call into a Cedar request:
53
55
  - [codex-recovery.md](codex-recovery.md): the opt-in live Codex support incident, operator-reviewed recovery, and its offline state example
54
56
  - [approvals.md](approvals.md): exact-action signatures, two-person thresholds, consumption, and privacy limits
55
57
  - [console.md](console.md): the admin console: run it, what each tab does, how it is protected, and its limits
58
+ - [anchoring.md](anchoring.md): the log's checkpoints on Ethereum: what an anchor proves, running it, and checking a log against the chain
56
59
  - [financial-operations.md](financial-operations.md): payment retries, budget reservations, provider contract, and operator reconciliation
57
60
  - [sdk.md](sdk.md): the interceptor and every adapter
58
61
  - [policies.md](policies.md): the Cedar mapping, evaluation rules, tested examples, gotchas
package/docs/usage.md CHANGED
@@ -123,7 +123,7 @@ At startup the gateway fetches the agent's card from `<url>/.well-known/agent-ca
123
123
  "log": { "url": "https://log.example.com/", "tokenEnv": "AGENT_CUSTODY_LOG_TOKEN" }
124
124
  ```
125
125
 
126
- Exactly one of the two. The bearer token comes from the named environment variable, never from the file, and a missing variable fails at startup. Add `"hashOnly": true` for any log run by someone else: the gateway then sends only the leaf hash, sha256 of the receipt envelope with the RFC 6962 prefix, so the log commits to the receipt without ever holding it, and the receipts with their arguments and results stay in `receiptsDir`. The verifier does not change; it hashes the envelope itself. A log that serves several tenants is reached at `<url>/t/<tenant>/`, and each of its tree heads names its log, which a verifier checks with `--log-id`. With a remote log the tree head in each receipt is signed by the log's key, and a verifier must be given that key with `--log-key`. The gateway does not take the log's answer on trust either: the tree head in every append's answer must verify against the log's keys, name the expected log, match the proof's size, and the inclusion proof must place that very leaf under the signed root, all before a pre-committed call is forwarded and before any receipt is handed out; an answer that fails any of it is a refusal. `"keys": ["keys/log.pub"]` pins the log's public keys, `"logId"` the id its heads must carry; without `keys` the log's key document at `/.well-known/agent-custody-log.json` is fetched from the log itself once, on the first append, and pinned. That catches a log that turns dishonest later, not one that is dishonest from the start, so a gateway config with `precommit` and a remote log must list `keys`. When the log rotates its key, add the new public key to `keys`; a gateway that fetched the keys needs a restart. An append that gets no answer within `timeoutMs` (default 10000) counts as unreachable and is retried like a server error, so a log that accepts connections and never answers cannot hold a call forever. If the log refuses a leaf, the receipt is not issued and the call returns an error to the agent. For an ordinary call the upstream action has already happened by then, and the error says so; a receipt that was never logged must not be handed out. For a tool named in `precommit` the order is reversed, below, and the action never happens. A fact lookup is different: it runs before the policy decides, because the policy decides on it, and only once the intercepted tool is in the grant's scope, so a fact tool must be a read. Naming a fact tool in `precommit` is refused at startup; `"*"` covers the tools the agent calls, not the gateway's own lookups. Every lookup is on the receipt with its arguments. The reference log server is `node src/cli.ts log --file log.jsonl --key keys/log.key --port 8787 --token-env AGENT_CUSTODY_LOG_TOKEN [--log-id <id>] [--tenants tenants.json]`. It serves `POST /append` with `{leaf}` or `{leafHash}` (token required when one is configured), `GET /root?size=N`, `GET /consistency?old=M&new=N`, and `GET /head`; [verification.md](verification.md) says what each proves. `--log-id` writes that id into every tree head. `--tenants` names a JSON file, `{ "acme": { "file": "acme.jsonl", "tokenEnv": "ACME_TOKEN", "logId": "acme-eu" } }`, and each tenant is its own log at `/t/acme/…` with its own token and id; the default log stays at the root paths. With `--hash-only` the server refuses `{leaf}` at append and accepts only `{leafHash}`, so a log run for other people never receives a receipt regardless of the client's configuration; the hosted deployment sets it. With `--db-env DATABASE_URL` the server keeps its logs in Postgres instead of files, and needs the `pg` package beside it: leaves as hashes in one table keyed by tenant, one writer per tenant enforced with an advisory lock so a second instance is safe, tenants and their tokens in tables of their own with tokens stored only as hashes, and rate limits per token (50 appends a second, burst 100, a 64 KB body cap; a refused append answers 429 with `retry-after`, and the gateway's sink retries a few times). Tenants are managed with `log-admin --db-env DATABASE_URL`: `tenant add <id> [--log-id <id>]`, `token add <tenant> --label <text>` (the token is printed once), `token revoke <tenant> <hash-prefix>`, `tenant disable <id>`, `tenant plan <id> <free|team|enterprise>`, and `import --file log.jsonl [--tenant default]` to bring an existing file log in as hashes. Every tenant is on a plan, `free` unless moved: free allows ten thousand appends a calendar month, team a million, enterprise has no allowance. An append past the allowance is refused with 429, the numbers, and a `retry-after` that reaches the start of next month; the gateway behind it then withholds pre-committed calls, so a tenant out of quota never acts without evidence. The tenant's own `GET /t/<name>/usage` reports the plan and quota beside the month's appends. The tenant portal, `agent-custody portal --db-env DATABASE_URL --secret-env PORTAL_SECRET --public-url <log url> [--checkpoints-url <url>] [--portal-url <url>] [--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]`, is the self-serve front of the same tables: a team registers with an email, a password (scrypt), and a tenant id and gets the tenant and its first key shown once with the welcome sheet; the dashboard shows appends against the plan, the tree size and root, the latest checkpoint, the log's URLs, keys, and the audit rows; keys are minted and revoked there, recorded as `portal:<email>`; the export command is on the page; and with the three Stripe variables the team plan is bought through Stripe Checkout, the signed webhook moving the plan (`stripe:<event>` in the audit trail) and the customer portal handling cancellation. Sessions are a signed cookie, `SameSite=Strict`, and every write needs a JSON body. Each member has a role (`owner`, `admin`, `reviewer`, `readonly`), an account can turn on TOTP MFA, and the operator can set up single sign-on through the tenant's own OIDC or SAML identity provider with `log-admin sso set`; the [hosted log reference](https://docs.agent-custody.dev/reference/hosted) lists the routes. SAML needs `@node-saml/node-saml` beside the CLI. The compose file runs it as the `portal` service at `PORTAL_HOST`. The root paths serve the tenant `default`, created on first start with `--log-id`, and `--token-env` still works for it. The key that signs tree heads can live in its own process: `agent-custody signer --key keys/log.key --port 8790 --token-env SIGNER_TOKEN` holds it and answers `POST /sign` with the shared secret and `GET /keys` to anyone; the log server then runs with `--signer-url http://signer:8790/ --signer-token-env SIGNER_TOKEN` instead of `--key`, and the process that faces the internet never holds the key. Either way the log serves its keys at `/.well-known/agent-custody-log.json`, current key first and retired keys (`--retired-key old.pub`) after it, so verifiers fetch and pin them with `verify --log-url` and `audit --log-url` rather than receiving a key file from the operator. With `--checkpoint-dir <dir>` the server publishes a signed checkpoint, every `--checkpoint-every` seconds (default 300), for each log whose tree has grown, and every `--checkpoint-heartbeat` seconds (default 21600, six hours) for a log that has not, so a quiet log's latest checkpoint is never more than six hours old and the monitor can tell quiet from stalled, as `<dir>/<tenant>/<treeSize>.json` and `latest.json`, and with a database also as rows; `GET /checkpoints?since=<size>` and `GET /t/<tenant>/checkpoints` list them. Serve the directory read-only from a second host, so the record of what the log signed does not depend on the log's API being up; a verifier who kept an earlier head audits against a later checkpoint with `audit --older <bundle> --newer <checkpoint> --log-url <url>`. With `--admin-token-env ADMIN_TOKEN` (Postgres only) the server also serves the operator's page at `/admin` and its API under `/admin/`: list and create tenants, mint a token that is shown once beside the tenant's welcome sheet, revoke tokens, disable tenants. Everything under `/admin`, the page included, needs the admin token: the browser asks for it (any user name, the token as the password) and an API client sends it as a bearer; a handful of wrong attempts from one address are throttled for a minute. Every change made there or with `log-admin` is recorded: who (the name entered at the browser prompt and the address, `bearer` for an API client, or the user and host for the command line), what (`tenant.add`, `tenant.disable`, `token.add`, `token.revoke`), which tenant, and the detail, never the token itself; the page shows it under Activity, `GET /admin/audit?tenant=&limit=` and `log-admin audit` list it, and a tenant reads their own rows at `GET /t/<name>/audit` with their token. Nothing else is stored by the page. Behind a reverse proxy, start the server with `--trust-proxy` so those per-address limits key on `X-Forwarded-For` instead of on the proxy's own address, and only there, since the header is otherwise the client's to forge. `--public-url` and `--checkpoints-url` fill the sheet in. The witness closes the last gap: `agent-custody witness --key witness.key --log-url <url> --checkpoints-url <url> --out <dir> [--tenant <name>]...` runs on a machine the log's operator does not control, fetches each watched log's latest checkpoint, verifies it against the log's published keys, proves with the log's consistency proof that it extends the last head the witness signed, and countersigns it into `<dir>/<tenant>/<size>.json` and `latest.json`; a checkpoint that does not extend, or a second history at the same size, gets `ALARM.json` instead. Its key document is `<dir>/.well-known/agent-custody-witness.json`. Serve `<dir>` from the witness's own host; verifiers add `--witness-url` (or `--witness-key`) to `audit`, and the newer head must then carry the witness's signature. Two more things an operator needs. `agent-custody log-check --log-url <url> --checkpoints-url <url> [--witness-url <url>] [--tenant <name>]... [--max-lag <seconds>]` is the outside monitor: it verifies the head against the published keys, that the latest checkpoint verifies and keeps up with the head, that the head extends the checkpoint, and, with a witness, that the witness has countersigned, keeps up, and has raised no alarm; it exits 1 on any failure, so cron or a scheduled workflow on a machine that is not the log's turns it into an alert. `GET /health` on the server is the liveness check for a load balancer. And `GET /admin/usage?month=YYYY-MM`, on the admin page and as `/admin/usage.csv`, is the metering: appends per tenant for the month, leaves in total, live tokens, the numbers any invoice rests on. A tenant needs none of that to leave with their evidence: `agent-custody log-export --log-url <url> --tenant <name> --token-env AGENT_CUSTODY_LOG_TOKEN --out <dir>` fetches, with their own token, every leaf hash (`GET /t/<name>/leaves?since=&limit=`, pages of up to ten thousand), the signed head, the published keys, the signed checkpoints, their own usage (`GET /t/<name>/usage?month=`), and the administrative actions on their tenant (`GET /t/<name>/audit`, into `audit.json`), checks that the head and every checkpoint verify against the keys and that the leaves fetched hash to their roots, and writes `log.jsonl` in the format `verify --log` and `audit --log` read, so the export verifies receipts with no server at all. It exits 1 and says what did not add up if anything does not. Both routes answer only to that tenant's token. [deploy/](../../deploy/README.md) runs the server, the signer, Postgres, and the checkpoints host as containers, and [deploy/witness/](../../deploy/witness/) the witness.
126
+ Exactly one of the two. The bearer token comes from the named environment variable, never from the file, and a missing variable fails at startup. Add `"hashOnly": true` for any log run by someone else: the gateway then sends only the leaf hash, sha256 of the receipt envelope with the RFC 6962 prefix, so the log commits to the receipt without ever holding it, and the receipts with their arguments and results stay in `receiptsDir`. The verifier does not change; it hashes the envelope itself. A log that serves several tenants is reached at `<url>/t/<tenant>/`, and each of its tree heads names its log, which a verifier checks with `--log-id`. With a remote log the tree head in each receipt is signed by the log's key, and a verifier must be given that key with `--log-key`. The gateway does not take the log's answer on trust either: the tree head in every append's answer must verify against the log's keys, name the expected log, match the proof's size, and the inclusion proof must place that very leaf under the signed root, all before a pre-committed call is forwarded and before any receipt is handed out; an answer that fails any of it is a refusal. `"keys": ["keys/log.pub"]` pins the log's public keys, `"logId"` the id its heads must carry; without `keys` the log's key document at `/.well-known/agent-custody-log.json` is fetched from the log itself once, on the first append, and pinned. That catches a log that turns dishonest later, not one that is dishonest from the start, so a gateway config with `precommit` and a remote log must list `keys`. When the log rotates its key, add the new public key to `keys`; a gateway that fetched the keys needs a restart. An append that gets no answer within `timeoutMs` (default 10000) counts as unreachable and is retried like a server error, so a log that accepts connections and never answers cannot hold a call forever. If the log does not take a receipt, the gateway keeps the signed receipt in `receipts/outbox/<receiptId>.json` and returns the real outcome of the call to the agent, with the receipt id and `_meta["agent-custody/log-pending"]: true`. The gateway appends the outbox at startup and every 30 seconds, and writes `receipts/<receiptId>.json` when the log takes the receipt. Until then no bundle exists, so no receipt that was never logged is handed out. The table [below](#when-the-log-fails) gives each case. For a tool named in `precommit` the order is reversed, below, and the action never happens. A fact lookup is different: it runs before the policy decides, because the policy decides on it, and only once the intercepted tool is in the grant's scope, so a fact tool must be a read. Naming a fact tool in `precommit` is refused at startup; `"*"` covers the tools the agent calls, not the gateway's own lookups. Every lookup is on the receipt with its arguments. The reference log server is `node src/cli.ts log --file log.jsonl --key keys/log.key --port 8787 --token-env AGENT_CUSTODY_LOG_TOKEN [--log-id <id>] [--tenants tenants.json]`. It serves `POST /append` with `{leaf}` or `{leafHash}` (token required when one is configured), `GET /root?size=N`, `GET /consistency?old=M&new=N`, and `GET /head`; [verification.md](verification.md) says what each proves. `--log-id` writes that id into every tree head. `--tenants` names a JSON file, `{ "acme": { "file": "acme.jsonl", "tokenEnv": "ACME_TOKEN", "logId": "acme-eu" } }`, and each tenant is its own log at `/t/acme/…` with its own token and id; the default log stays at the root paths. With `--hash-only` the server refuses `{leaf}` at append and accepts only `{leafHash}`, so a log run for other people never receives a receipt regardless of the client's configuration; the hosted deployment sets it. With `--db-env DATABASE_URL` the server keeps its logs in Postgres instead of files, and needs the `pg` package beside it: leaves as hashes in one table keyed by tenant, one writer per tenant enforced with an advisory lock so a second instance is safe, tenants and their tokens in tables of their own with tokens stored only as hashes, and rate limits per token (50 appends a second, burst 100, a 64 KB body cap; a refused append answers 429 with `retry-after`, and the gateway's sink retries a few times). Tenants are managed with `log-admin --db-env DATABASE_URL`: `tenant add <id> [--log-id <id>]`, `token add <tenant> --label <text>` (the token is printed once), `token revoke <tenant> <hash-prefix>`, `tenant disable <id>`, `tenant plan <id> <free|team|enterprise>`, and `import --file log.jsonl [--tenant default]` to bring an existing file log in as hashes. Every tenant is on a plan, `free` unless moved: free allows ten thousand appends a calendar month, team a million, enterprise has no allowance. An append past the allowance is refused with 429, the numbers, and a `retry-after` that reaches the start of next month; the gateway behind it then withholds pre-committed calls, so a tenant out of quota never acts without evidence. The tenant's own `GET /t/<name>/usage` reports the plan and quota beside the month's appends. The tenant portal, `agent-custody portal --db-env DATABASE_URL --secret-env PORTAL_SECRET --public-url <log url> [--checkpoints-url <url>] [--portal-url <url>] [--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]`, is the self-serve front of the same tables: a team registers with an email, a password (scrypt), and a tenant id and gets the tenant and its first key shown once with the welcome sheet; the dashboard shows appends against the plan, the tree size and root, the latest checkpoint, the log's URLs, keys, and the audit rows; keys are minted and revoked there, recorded as `portal:<email>`; the export command is on the page; and with the three Stripe variables the team plan is bought through Stripe Checkout, the signed webhook moving the plan (`stripe:<event>` in the audit trail) and the customer portal handling cancellation. Sessions are a signed cookie, `SameSite=Strict`, and every write needs a JSON body. Each member has a role (`owner`, `admin`, `reviewer`, `readonly`), an account can turn on TOTP MFA, and the operator can set up single sign-on through the tenant's own OIDC or SAML identity provider with `log-admin sso set`; the [hosted log reference](https://docs.agent-custody.dev/reference/hosted) lists the routes. SAML needs `@node-saml/node-saml` beside the CLI. The compose file runs it as the `portal` service at `PORTAL_HOST`. The root paths serve the tenant `default`, created on first start with `--log-id`, and `--token-env` still works for it. The key that signs tree heads can live in its own process: `agent-custody signer --key keys/log.key --port 8790 --token-env SIGNER_TOKEN` holds it and answers `POST /sign` with the shared secret and `GET /keys` to anyone; the log server then runs with `--signer-url http://signer:8790/ --signer-token-env SIGNER_TOKEN` instead of `--key`, and the process that faces the internet never holds the key. Either way the log serves its keys at `/.well-known/agent-custody-log.json`, current key first and retired keys (`--retired-key old.pub`) after it, so verifiers fetch and pin them with `verify --log-url` and `audit --log-url` rather than receiving a key file from the operator. With `--checkpoint-dir <dir>` the server publishes a signed checkpoint, every `--checkpoint-every` seconds (default 300), for each log whose tree has grown, and every `--checkpoint-heartbeat` seconds (default 21600, six hours) for a log that has not, so a quiet log's latest checkpoint is never more than six hours old and the monitor can tell quiet from stalled, as `<dir>/<tenant>/<treeSize>.json` and `latest.json`, and with a database also as rows; `GET /checkpoints?since=<size>` and `GET /t/<tenant>/checkpoints` list them. Serve the directory read-only from a second host, so the record of what the log signed does not depend on the log's API being up; a verifier who kept an earlier head audits against a later checkpoint with `audit --older <bundle> --newer <checkpoint> --log-url <url>`. With `--admin-token-env ADMIN_TOKEN` (Postgres only) the server also serves the operator's page at `/admin` and its API under `/admin/`: list and create tenants, mint a token that is shown once beside the tenant's welcome sheet, revoke tokens, disable tenants. Everything under `/admin`, the page included, needs the admin token: the browser asks for it (any user name, the token as the password) and an API client sends it as a bearer; a handful of wrong attempts from one address are throttled for a minute. Every change made there or with `log-admin` is recorded: who (the name entered at the browser prompt and the address, `bearer` for an API client, or the user and host for the command line), what (`tenant.add`, `tenant.disable`, `token.add`, `token.revoke`), which tenant, and the detail, never the token itself; the page shows it under Activity, `GET /admin/audit?tenant=&limit=` and `log-admin audit` list it, and a tenant reads their own rows at `GET /t/<name>/audit` with their token. Nothing else is stored by the page. Behind a reverse proxy, start the server with `--trust-proxy` so those per-address limits key on `X-Forwarded-For` instead of on the proxy's own address, and only there, since the header is otherwise the client's to forge. `--public-url` and `--checkpoints-url` fill the sheet in. The witness closes the last gap: `agent-custody witness --key witness.key --log-url <url> --checkpoints-url <url> --out <dir> [--tenant <name>]...` runs on a machine the log's operator does not control, fetches each watched log's latest checkpoint, verifies it against the log's published keys, proves with the log's consistency proof that it extends the last head the witness signed, and countersigns it into `<dir>/<tenant>/<size>.json` and `latest.json`; a checkpoint that does not extend, or a second history at the same size, gets `ALARM.json` instead. Its key document is `<dir>/.well-known/agent-custody-witness.json`. Serve `<dir>` from the witness's own host; verifiers add `--witness-url` (or `--witness-key`) to `audit`, and the newer head must then carry the witness's signature. Two more things an operator needs. `agent-custody log-check --log-url <url> --checkpoints-url <url> [--witness-url <url>] [--tenant <name>]... [--max-lag <seconds>]` is the outside monitor: it verifies the head against the published keys, that the latest checkpoint verifies and keeps up with the head, that the head extends the checkpoint, and, with a witness, that the witness has countersigned, keeps up, and has raised no alarm; it exits 1 on any failure, so cron or a scheduled workflow on a machine that is not the log's turns it into an alert. `GET /health` on the server is the liveness check for a load balancer. And `GET /admin/usage?month=YYYY-MM`, on the admin page and as `/admin/usage.csv`, is the metering: appends per tenant for the month, leaves in total, live tokens, the numbers any invoice rests on. A tenant needs none of that to leave with their evidence: `agent-custody log-export --log-url <url> --tenant <name> --token-env AGENT_CUSTODY_LOG_TOKEN --out <dir>` fetches, with their own token, every leaf hash (`GET /t/<name>/leaves?since=&limit=`, pages of up to ten thousand), the signed head, the published keys, the signed checkpoints, their own usage (`GET /t/<name>/usage?month=`), and the administrative actions on their tenant (`GET /t/<name>/audit`, into `audit.json`), checks that the head and every checkpoint verify against the keys and that the leaves fetched hash to their roots, and writes `log.jsonl` in the format `verify --log` and `audit --log` read, so the export verifies receipts with no server at all. It exits 1 and says what did not add up if anything does not. Both routes answer only to that tenant's token. [deploy/](../../deploy/README.md) runs the server, the signer, Postgres, and the checkpoints host as containers, and [deploy/witness/](../../deploy/witness/) the witness.
127
127
 
128
128
  `otel`, optional in both the gateway and SDK configs, sends every receipt to the collector you already run as one span over OTLP/HTTP, after the receipt is issued: `"otel": { "url": "http://localhost:4318", "headersEnv": { "x-api-key": "OTEL_KEY" }, "serviceName": "support-agents" }`. The span's trace id is the receipt id, its attributes carry the tool, agent, principal, execution status, policy decision, and log position, and its status is an error only when the upstream failed or errored, since a denial is the policy working. Export is best effort: a collector that is down or refuses costs a line on stderr, never a receipt. Tutorial 18 shows it against a stand-in collector.
129
129
 
@@ -135,7 +135,40 @@ Exactly one of the two. The bearer token comes from the named environment variab
135
135
 
136
136
  To test a different policy against the history already collected, run `agent-custody policy simulate --policy proposed.cedar --receipts receipts --issuer-key keys/gateway.pub --principal-key keys/principal.pub --out simulation.json`. It replays recorded arguments and fact values without calling upstreams, lists changed decisions by tool and reason with the receipt ids, and records the proposed policy digest. Missing replay inputs make the report incomplete. See [the policy simulation guide](policies.md#simulating-a-policy-against-recorded-history).
137
137
 
138
- The grant is checked on every call, not only when the session opens: a call after `expiresAt` is denied with a receipt that says so, the check is repeated just before the forward (a grant that ran out while the facts were gathered leaves the call `withheld`), and over HTTP a session whose grant has expired or been revoked is closed on its next request with `403`. `"revokedGrants": "revoked.json"` names a file of grant digests the gateway re-reads whenever it changes. The digest is sha256 over the grant's signed payload, so extra signatures or fields on the envelope do not change it, and revoking a grant also revokes every grant delegated from it. A file that cannot be read denies every call until it can be read; `agent-custody revoke --config gateway.json --grant grant.json` appends a grant's digest to it, after which every session under that grant refuses its next call and no new session opens for it, with no key rotation. `precommit` names the consequential tools, or `["*"]` for all of them. For every other tool the gateway forwards the call and then records it, so if the log is unreachable at that moment the side effect exists before its evidence does. For a tool in `precommit` the gateway first signs an authorization statement, everything the receipt will say except the outcome, and appends it to the log. Only if the log took it does the call go upstream. The receipt then embeds that authorization with its own inclusion proof, and a verifier checks that it names this call and sits in the log before the receipt does. If the log will not take it, or answers with a head or proof that does not verify, the call is not forwarded, the agent is told `Not executed`, and the receipt records `execution.status: "withheld"` with the policy's `allow` beside it. The authorization is also written on its own as `receipts/<receiptId>.authorization.json`, which is the evidence that survives if the gateway dies between forwarding and the receipt. Use it for money, for anything irreversible, and for anything a counterparty could later dispute; the cost is one extra log append per call.
138
+ The grant is checked on every call, not only when the session opens: a call after `expiresAt` is denied with a receipt that says so, the check is repeated just before the forward (a grant that ran out while the facts were gathered leaves the call `withheld`), and over HTTP a session whose grant has expired or been revoked is closed on its next request with `403`. `"revokedGrants": "revoked.json"` names a file of grant digests the gateway re-reads whenever it changes. The digest is sha256 over the grant's signed payload, so extra signatures or fields on the envelope do not change it, and revoking a grant also revokes every grant delegated from it. A file that cannot be read denies every call until it can be read; `agent-custody revoke --config gateway.json --grant grant.json` appends a grant's digest to it, after which every session under that grant refuses its next call and no new session opens for it, with no key rotation. The Cedar policy is re-read the same way: when `policyFile` changes (device, inode, mtime, ctime, or size; a file written in the last two seconds is re-read on each call until it settles), the next call is evaluated under the new policy, with no restart and no dropped session, and a call already evaluating finishes under the policy it started with, whose digest its receipt carries. A changed file that does not parse, or that cannot be read, is refused: the policy in force stays, never an allow, and the gateway prints `POLICY NOT RELOADED` on stderr. Every change and every refusal is appended to `receipts/policy-reloads.jsonl` as `{ at, file, event: "reloaded" | "refused", from, to, errors?, warnings? }`, with the digest in force and the digest of the new file (`null` when the file was removed or cannot be read), so the change between two receipts' `policyDigest`s has a time. A reloaded policy with no permit rule is applied, since it denies every call, but is printed and recorded with the warning `no permit rule: every call is denied`. Write the file by rename, as `agent-custody console` does. A file written in place can be read half-written: a prefix that parses, missing a trailing `forbid`, decides calls until the write finishes and the settled file is read. `precommit` names the consequential tools, or `["*"]` for all of them. For every other tool the gateway forwards the call and then records it, so if the log is unreachable at that moment the side effect exists before its evidence is in the log: the receipt waits in the outbox. With a remote log and an empty `precommit`, the gateway prints a warning at startup and `agent-custody check` reports it; `"requirePrecommit": true` makes it a startup error, and [strict mode](#strict-mode) precommits every tool. For a tool in `precommit` the gateway first signs an authorization statement, everything the receipt will say except the outcome, and appends it to the log. Only if the log took it does the call go upstream. The receipt then embeds that authorization with its own inclusion proof, and a verifier checks that it names this call and sits in the log before the receipt does. If the log will not take it, or answers with a head or proof that does not verify, the call is not forwarded, the agent is told `Not executed`, and the receipt records `execution.status: "withheld"` with the policy's `allow` beside it. The authorization is also written on its own as `receipts/<receiptId>.authorization.json`, which is the evidence that survives if the gateway dies between forwarding and the receipt. Use it for money, for anything irreversible, and for anything a counterparty could later dispute; the cost is one extra log append per call.
139
+
140
+ #### When the log fails
141
+
142
+ "Down" is a log that does not answer or answers 5xx. "Slow" is an append that takes longer than `log.timeoutMs` (default 10000 ms), which counts as down. "Refusing" is a 4xx answer other than 429, or an answer whose tree head or proof does not verify. "Quota" is 429, after the sink's retries. The sink makes three attempts before the gateway treats the append as failed.
143
+
144
+ | log state | ordinary tool | tool in `precommit` | financial operation |
145
+ | --- | --- | --- | --- |
146
+ | down, slow, or quota (429) | forwarded; the agent gets the real result and `log-pending`; the receipt waits in the outbox and is appended when the log answers again | not forwarded; the agent gets `Not executed` and `log-pending`; the `withheld` receipt waits in the outbox | the call returns an error and nothing is forwarded, because the authorization is not in the log; if only the receipt append fails after the forward, the call also returns an error, and `reconcile` finishes the operation |
147
+ | refusing | as above, but the outbox does not empty until the operator fixes the cause (a token, a quota, the pinned keys); the gateway prints the reason on each attempt | as above | as above |
148
+
149
+ The outbox is appended in the order of the signed statements' timestamps, oldest first. A log refusal stops the flush, so one receipt that the log refuses holds the receipts after it. `GET /health` on the HTTP gateway reports `pendingReceipts`. Only a gateway that serves (stdio, `--http`, `--a2a`) runs the flush, at start and every 30 seconds; `check`, `reconcile`, and the other commands never append the outbox. A gateway that stops waits for a flush that runs. A gateway that stops before the log takes the receipt keeps the outbox on disk and appends it on the next start. The gateway writes the outbox entry to disk, and syncs the file and its directory, before the agent gets the result.
150
+
151
+ Several gateways, or a gateway and a command, can share one `receipts/` directory. A flush takes the lock file `receipts/outbox/.lock` with an exclusive create. When another process holds the lock, the flush does nothing and reports the entries as `pending`. The gateway breaks a lock whose owner process no longer runs on this host, and a lock that nobody has touched for 15 minutes.
152
+
153
+ When the log takes a receipt, the gateway records the log's answer in the outbox entry before it writes the bundle. If the bundle write then fails (a full disk, a permission error), the gateway prints the error on stderr, and the next flush writes the bundle from the recorded answer and does not append the leaf again. A process that dies between the append and that record appends the leaf again on the next flush; the log then holds it twice, and either copy proves the receipt. A gateway that dies after the forward and before the outbox write leaves no receipt; `precommit` is the guard for the calls where that matters. Before the gateway appends an outbox entry, it checks the entry. It renames an entry to `<name>.bad`, does not append it, and prints a warning, when the file is damaged, when the entry carries this gateway's key id but the signature does not verify, or when the receipt id in the statement is not the id in the file name. An entry that another key signed (a rotated gateway key, or a restored backup) is not appended, is not called forged, and stays in the outbox; the gateway prints a warning on each flush. Restore the key that signed it, or move the entry away. Until the log takes a pending receipt, `receipts/<id>.json` does not exist, so `verify`, `explain`, `blast`, the review console, and `prune` do not see the call yet.
154
+
155
+ #### Strict mode
156
+
157
+ The outbox keeps the receipt of a call through a log outage, but the operator runs the gateway: killing it between the forward and the outbox write, or deleting the outbox entry, leaves a call with no receipt, and a local log can be rewritten outright. `"strict": true` closes that for the calls the agent makes:
158
+
159
+ ```json
160
+ {
161
+ "strict": true,
162
+ "log": { "url": "https://log.example.com/t/acme/", "tokenEnv": "AGENT_CUSTODY_LOG_TOKEN", "hashOnly": true, "keys": ["keys/log.pub"] }
163
+ }
164
+ ```
165
+
166
+ - The gateway does not start with `logFile`, with a `log` that is not `hashOnly`, or with a `log` without `keys`. Each is a startup error that names the setting, and `agent-custody check` reports it. On a config without `strict`, `check` lists what strict mode would refuse.
167
+ - Every tool is precommitted, as with `precommit: ["*"]`: the authorization is in the log before the call is forwarded, and a call whose authorization the log will not take is `withheld`. In observe mode too, where a call the policy would deny is still forwarded and is precommitted like any other.
168
+ - No receipt goes to the outbox. A receipt that the log refuses after the forward is not kept, the call returns an error to the agent, and the authorization in the log stands. A gateway killed at any point leaves either no call or an authorization with no outcome, which a verifier reports as incomplete. Receipts left in the outbox from before strict mode was turned on are appended once, at start; there is no 30-second retry.
169
+ - Every receipt and authorization carries `issuer.strict: true`, and `verify --require-strict` refuses a receipt without it, or a forwarded call without its authorization ([verification.md](verification.md)).
170
+
171
+ The cost is one extra log append per call, and a log outage stops every call. What strict mode does not cover: a fact lookup and a `reconcile` read are reads the gateway makes itself, before the policy decides or on the operator's command, and go out before any log entry; each is on the receipt that follows. The flag is the gateway's own statement, signed with its key: it binds an honest gateway's operator to a mode a verifier can hold them to, and a modified gateway can still claim it. Only a gateway the operator cannot change ([the plan](../README.md#plan)) closes that.
139
172
 
140
173
  **5. Run the gateway.** It speaks MCP on stdin/stdout and logs to stderr only.
141
174
 
@@ -347,6 +380,6 @@ The upstream can answer in kind. A result whose `_meta` carries `agent-custody/f
347
380
  - **Money is integer minor units.** Cedar has no floating point. A float in `args` that a policy touches is an evaluation error, which is a deny.
348
381
  - **The gateway key is the trust root for receipts.** Keep it out of the agent's reach. The upstream credentials in `upstream.env` are likewise never exposed to the agent.
349
382
  - **Rotate keys by adding, not replacing.** The verifier accepts a list of gateway keys and principal keys and matches by keyid, so old receipts stay verifiable.
350
- - **Evidence before the side effect, for the calls that matter.** Without `precommit`, a call is forwarded and then logged, and a log outage at that moment leaves an executed action with no receipt (the agent gets an error saying so). With `precommit`, the authorization is logged first and the call is withheld if that fails. The receipt of a withheld call shows `allow` next to `withheld`, so an auditor can tell a log outage from a denial.
383
+ - **Evidence before the side effect, for the calls that matter.** Without `precommit`, a call is forwarded and then logged, and a log outage at that moment leaves an executed action whose receipt waits in the outbox until the log takes it (the agent gets the real result, marked `log-pending`). With `precommit`, the authorization is logged first and the call is withheld if that fails. The receipt of a withheld call shows `allow` next to `withheld`, so an auditor can tell a log outage from a denial.
351
384
  - **The log is append-only by convention, not enforcement.** Copy it somewhere the operator cannot rewrite, on a schedule. The receipts' tree heads let an auditor check that the copy matches.
352
385
  - **stdout is the MCP channel.** Anything the gateway prints goes to stderr. Do not add `console.log` to gateway code paths.
@@ -24,7 +24,7 @@ node src/cli.ts verify receipts/<id>.json \
24
24
  --log log.jsonl
25
25
  ```
26
26
 
27
- `--approval-key` is needed for forwarded calls carrying human approvals (not for a refusal), `--log-key` for a remote log, and `--upstream-key` when checking a signed upstream result. `--log` is optional.
27
+ `--approval-key` is needed for forwarded calls carrying human approvals (not for a refusal), `--log-key` for a remote log, and `--upstream-key` when checking a signed upstream result. `--log` is optional. `--require-strict` refuses a receipt that a gateway in [strict mode](usage.md#strict-mode) did not issue, and a forwarded call without its precommitted authorization.
28
28
 
29
29
  Exit code 0 when every check passes, 1 otherwise. Add `--json` for machine-readable output. `--issuer-key`, `--principal-key`, and `--approval-key` can be repeated to accept rotated keys; signatures are matched by keyid. `--gateway-key` is an alias for `--issuer-key`. `--principal-key` may be omitted for SDK receipts, which carry no delegation.
30
30
 
@@ -103,12 +103,14 @@ A refused call's `execution` row carries the reason the receipt records, for exa
103
103
  | authorization log inclusion proof | the authorization statement is a leaf of that tree | an authorization that was never logged |
104
104
  | authorization logged before execution | the authorization's leaf precedes the receipt's leaf, at a tree size no larger than the receipt's | evidence written after the side effect, dressed up as before |
105
105
  | tree head signature | the tree head was signed by a trusted issuer key | forged log position |
106
+ | strict mode in force | with `--require-strict`: a gateway receipt whose issuer says `strict: true`. It is the gateway's own statement, signed with its key, so it binds the operator to a mode it can be held to; it does not prove the gateway's code | an ordinary receipt presented where strict ones are required |
107
+ | strict: call precommitted before forwarding | with `--require-strict`: a call that was executed, failed, or errored carries its authorization, which the `authorization …` checks then place in the log before the receipt. A reconciliation receipt is a provider read and needs none | a strict claim on a call that went out before any log entry |
106
108
  | tree head names the expected log | with `--log-id`: the tree head carries that log id, so a head from another tenant's log on the same server cannot be presented as this one's | a receipt logged to a different log than claimed |
107
109
  | tree head matches inclusion proof size | the proof and the tree head describe the same tree | mismatched bundle parts |
108
110
  | log inclusion proof | this exact envelope is a leaf of the tree with that root | receipt never logged, or logged then changed |
109
111
  | log file root matches tree head | recomputing the root from your copy of the log at that size gives the same value | your log copy and the issuer's history diverge: deletion, reordering, or edit |
110
112
 
111
- Approval-bearing forwarded calls add four approval checks. A refused call runs only `approval consistent with execution`, so it verifies without approval keys, with a valid approval or with the invalid approval that caused its refusal. Gateway receipts otherwise run seventeen checks, eighteen with a log file, one more (`execution result digest`) when the call was executed or failed, and five more when the tool was committed before it ran (`precommit` in the gateway config). SDK receipts run fewer, because there is no delegation to check, and the report says so on the `principal is claimed` line. A receipt issued to a sub-agent under a delegation chain runs one more, `delegation chain to the principal`.
113
+ Approval-bearing forwarded calls add four approval checks. A refused call runs only `approval consistent with execution`, so it verifies without approval keys, with a valid approval or with the invalid approval that caused its refusal. Gateway receipts otherwise run seventeen checks, eighteen with a log file, one more (`execution result digest`) when the call was executed or failed, and five more when the tool was committed before it ran (`precommit` in the gateway config). `--require-strict` adds two. SDK receipts run fewer, because there is no delegation to check, and the report says so on the `principal is claimed` line. A receipt issued to a sub-agent under a delegation chain runs one more, `delegation chain to the principal`.
112
114
 
113
115
  Financial receipts add `operation …` checks and `authorization names this operation` for the durable id (absent under a private capture rule; the provider key then links the receipts), provider key, precommitted lookup, and budget. Reconciliation receipts embed their original receipt or authorization and run its checks under `reconciliation original …`, reject nested reconciliation evidence, preserve identity at `reconciliation links the original operation`, and check the configured mapping and provider record at `reconciliation lookup matches authorization`, `reconciliation lookup args match request`, and `reconciliation provider status`. The provider's terminal state must agree with the financial outcome and its record must echo the idempotency key. `reconciliation logged after original` checks ordering. These observations do not independently prove settlement without trusting the gateway and provider; private provider results verify as committed until disclosed or decrypted. See [financial operations](financial-operations.md).
114
116
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-custody/receipts",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "mcpName": "io.github.svayatta/agent-custody",
5
5
  "description": "Chain of custody for AI agents: signed, independently verifiable receipts for tool calls. MCP gateway + Cedar policy + Merkle transparency log",
6
6
  "license": "Apache-2.0",
@@ -84,6 +84,7 @@
84
84
  "langchain": "1.5.15",
85
85
  "tsx": "^4.23.13",
86
86
  "typescript": "^7.0.2",
87
+ "viem": "2.57.4",
87
88
  "vitest": "^5.0.0",
88
89
  "xml-crypto": "^6.1.2"
89
90
  },
@@ -92,7 +93,8 @@
92
93
  "@node-saml/node-saml": ">=5.1.0",
93
94
  "@openai/agents": ">=0.1.0",
94
95
  "ai": ">=5.0.0",
95
- "pg": ">=8"
96
+ "pg": ">=8",
97
+ "viem": ">=2.30.0"
96
98
  },
97
99
  "peerDependenciesMeta": {
98
100
  "@langchain/core": {
@@ -109,6 +111,9 @@
109
111
  },
110
112
  "pg": {
111
113
  "optional": true
114
+ },
115
+ "viem": {
116
+ "optional": true
112
117
  }
113
118
  }
114
119
  }