@agent-custody/receipts 0.13.0 → 0.15.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.
Files changed (58) hide show
  1. package/README.md +46 -28
  2. package/dist/check.d.ts +10 -0
  3. package/dist/check.js +179 -3
  4. package/dist/claude-init.d.ts +46 -0
  5. package/dist/claude-init.js +208 -0
  6. package/dist/cli.js +126 -11
  7. package/dist/config.d.ts +128 -1
  8. package/dist/config.js +92 -3
  9. package/dist/console.js +16 -7
  10. package/dist/deny-report.d.ts +30 -0
  11. package/dist/deny-report.js +106 -0
  12. package/dist/door.d.ts +203 -0
  13. package/dist/door.js +712 -0
  14. package/dist/export.d.ts +39 -0
  15. package/dist/export.js +95 -0
  16. package/dist/gateway.js +53 -21
  17. package/dist/index.d.ts +8 -0
  18. package/dist/index.js +7 -0
  19. package/dist/issue.js +5 -65
  20. package/dist/lock.d.ts +12 -0
  21. package/dist/lock.js +124 -0
  22. package/dist/log-admin.js +3 -3
  23. package/dist/log.d.ts +20 -3
  24. package/dist/log.js +117 -24
  25. package/dist/opa-server.d.ts +34 -0
  26. package/dist/opa-server.js +93 -0
  27. package/dist/policy-rego.d.ts +30 -0
  28. package/dist/policy-rego.js +114 -0
  29. package/dist/policy.d.ts +6 -0
  30. package/dist/policy.js +17 -0
  31. package/dist/pr-summary.d.ts +25 -0
  32. package/dist/pr-summary.js +87 -0
  33. package/dist/receipt.d.ts +3 -1
  34. package/dist/retention.d.ts +1 -1
  35. package/dist/retention.js +14 -4
  36. package/dist/sdk/claude.js +18 -2
  37. package/dist/sdk/index.d.ts +2 -0
  38. package/dist/sdk/index.js +11 -2
  39. package/dist/simulate.d.ts +3 -1
  40. package/dist/simulate.js +15 -7
  41. package/dist/verify.js +6 -3
  42. package/dist/witness.js +3 -3
  43. package/docs/compliance.md +117 -7
  44. package/docs/configuration.md +3 -3
  45. package/docs/door-signals.md +66 -0
  46. package/docs/door.md +168 -0
  47. package/docs/github-action.md +164 -0
  48. package/docs/policies.md +124 -1
  49. package/docs/sdk.md +99 -1
  50. package/docs/tutorials.md +5 -0
  51. package/docs/usage.md +3 -3
  52. package/docs/verification.md +9 -2
  53. package/package.json +16 -14
  54. package/templates/claude-code.cedar +373 -0
  55. package/vectors/audit.json +27 -27
  56. package/vectors/canonical.json +5 -5
  57. package/vectors/merkle.json +123 -0
  58. package/vectors/receipts.json +1258 -1005
package/README.md CHANGED
@@ -2,15 +2,18 @@
2
2
 
3
3
  Chain of custody for AI agents: a signed receipt for every tool call, checkable with public keys alone. What each check proves, and against whom, is [a table below](#what-a-receipt-proves-and-what-it-does-not).
4
4
 
5
- Two producers, one receipt format, one verifier.
5
+ Three producers, one receipt format, one verifier.
6
6
 
7
- - **The gateway** is an MCP proxy between an agent and the systems it can affect: MCP servers, REST APIs described as tools, and other agents it delegates to over A2A. For every tool call, allowed or denied, it checks a delegation grant signed by the human principal and any required human approval of the exact arguments, gathers the facts the policy needs by calling upstream itself, evaluates a Cedar policy that fails closed, forwards the call only on allow, and emits a signed receipt appended to a Merkle transparency log.
7
+ - **The gateway** is an MCP proxy between an agent and the systems it can affect: MCP servers, REST APIs described as tools, and other agents it delegates to over A2A. For every tool call, allowed or denied, it checks a delegation grant signed by the human principal and any required human approval of the exact arguments, gathers the facts the policy needs by calling upstream itself, evaluates a Cedar or Rego policy that fails closed (Rego from a file or from your own OPA server), forwards the call only on allow, and emits a signed receipt appended to a Merkle transparency log.
8
+ - **The door** is the gateway turned around: a reverse proxy in front of your own website, API, or forms. Every arrival, a browser, an API client, a crawler, or an agent, is classified by what it presented (a grant signed by a principal you trust makes it `verified`; an assertion the door cannot check is `claimed`; nothing is `unknown`), decided by a Cedar policy for its route, relayed or refused, and receipted either way with the same receipt. It is the first piece of an agent front door; it does not yet detect agents in web traffic, and says so ([the door](docs/door.md)).
8
9
  - **The SDK** is an interceptor inside the agent's own process, hooked into the framework's tool-call callbacks: Claude Code, the Claude Agent SDK, the OpenAI Agents SDK, the Vercel AI SDK, OpenClaw, DeepSeek Harness, Hermes, Google ADK, LangChain, or any function you wrap. It reaches everything the gateway cannot see and issues the same receipts, labelled as self-reported.
9
10
 
10
11
  Anyone holding the public keys can verify a receipt offline. The agent is not trusted. The layer around it is, and the receipt says exactly how far that trust extends, starting with who issued it. What the receipt file carries of a call is a choice per tool: a field can be withheld as a commitment or encrypted under your key, and the verifier recomputes the digests when it is shown the values.
11
12
 
12
13
  - [Reference](https://docs.agent-custody.dev/reference/): every function, endpoint, MCP tool, and command with its request and response
13
- - [Tutorials](docs/tutorials.md): thirty-five runnable examples, one per aspect of the code, all executed by the test suite
14
+ - [Tutorials](docs/tutorials.md): runnable examples, one per aspect of the code, all executed by the test suite
15
+ - [The door](docs/door.md): a receipted reverse proxy in front of your own site or API; what it knows about an arrival, how an arrival becomes a Cedar request, what the arrival gets back, and what it does not do yet
16
+ - [Door signals](docs/door-signals.md): every field of the arrival fact, labelled checked, observed, or a claim, with what it does and does not mean and how a policy should read it
14
17
  - [Financial operations](docs/financial-operations.md): durable operation ids, provider idempotency keys, atomic daily budget reservations, and reconciliation receipts for uncertain outcomes
15
18
  - [The gateway console](docs/console.md): an admin service for the person who runs a gateway: config, tools, receipts with a verdict each, a policy editor that replays recorded calls before it saves, grant revocation, and an audit trail
16
19
  - [Configuring the gateway](docs/configuration.md): who may use which tools and where the tools live, a worked example with two agents, the Docker image, and `agent-custody check` to validate a config before it starts
@@ -18,10 +21,11 @@ Anyone holding the public keys can verify a receipt offline. The agent is not tr
18
21
  - [Live Codex recovery demo](docs/codex-recovery.md): a real support agent, incorrect CRM memory, operator-reviewed compensation, and verified receipts; an opt-in live run with offline regression coverage
19
22
  - [Human approvals](docs/approvals.md): short-lived signatures over the exact action, two-person thresholds, single-use enforcement, and offline verification
20
23
  - [The interceptor SDK](docs/sdk.md): Claude Code hooks, the Claude Agent SDK, adapters for the OpenAI Agents SDK, Vercel AI SDK, LangChain, OpenClaw and DeepSeek Harness, a Hermes Agent plugin and Google ADK callbacks through the Python package, and wrapping tool functions in anything else
21
- - [Writing policies](docs/policies.md): how a tool call becomes a Cedar request, with tested examples, and replaying history against a proposed policy with `policy simulate`
24
+ - [Writing policies](docs/policies.md): how a tool call becomes a Cedar request or Rego input, with tested examples, a Rego file against an OPA server, and replaying history against a proposed policy with `policy simulate`
22
25
  - [Verifying a receipt](docs/verification.md): what each check means and what a verified receipt does and does not prove
23
- - [What the evidence satisfies](docs/compliance.md): the receipts, packs, and certificates mapped to SOC 2, ISO 27001, the EU AI Act, and UK GDPR, with what none of them claims
26
+ - [What the evidence satisfies](docs/compliance.md): the receipts, packs, and certificates mapped to SOC 2, ISO 27001, UK GDPR, the EU AI Act, FINRA, MAS, Colorado, DORA, the CSA AI Controls Matrix, the OWASP agentic guidance, and ISO/IEC 42001. Each regulation has a primary source, an "as of" date, and a list of what a receipt does not supply
24
27
  - [Anchoring the log on a chain](docs/anchoring.md): the log's checkpoints committed to Ethereum mainnet, or another EVM chain the installation picks, from a published address, what that proves and what it does not, running the anchor, and `log-check` against the chain
28
+ - [Receipts on a pull request](docs/github-action.md): the GitHub Action that verifies a directory of receipt bundles and posts one table on the pull request, the workflow file to copy, the `export` command that copies the receipts into the branch, and why a committed receipt publishes the call unless a capture rule withholds it
25
29
  - [Completeness](docs/completeness.md): an auditor's read-only key lists the provider's objects and matches each to a verified receipt, so an action taken outside the gateway shows up
26
30
  - [Payment mandates and agent identity](docs/mandates.md): the design for fitting grants and receipts to Google's AP2 mandates, Visa's Trusted Agent Protocol and Mastercard Agent Pay; not yet built
27
31
  - [Threat model](docs/threat-model.md): every party who could make a receipt false, the move, what stops it, and whether that is a property of the evidence or of the deployment; and what is not defended
@@ -38,7 +42,7 @@ Published on npm as [`@agent-custody/receipts`](https://www.npmjs.com/package/@a
38
42
  Record receipts from inside your own agent, no gateway needed. Generate a signing key, point a config at it, wrap the functions the agent calls:
39
43
 
40
44
  ```bash
41
- npx agent-custody keygen --dir keys --name app
45
+ npx @agent-custody/receipts keygen --dir keys --name app
42
46
  ```
43
47
 
44
48
  ```json
@@ -56,7 +60,9 @@ const bundle = JSON.parse(readFileSync("receipts/<id>.json", "utf8"));
56
60
  verifyBundle(bundle, { issuerKeys: [loadPublicKey("keys/app.pub")], logFile: "log.jsonl" }).ok; // true
57
61
  ```
58
62
 
59
- Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the Vercel AI SDK, LangChain, OpenClaw, DeepSeek Harness, Hermes and Google ADK, are in [docs/sdk.md](docs/sdk.md). To enforce rather than record, put the gateway between the agent and its tools: `npx agent-custody gateway --config gateway.json`, set up in [docs/usage.md](docs/usage.md); between an agent and the agents it delegates to over A2A, `--a2a` serves the gateway as an A2A agent itself. The gateway is listed in the [MCP Registry](https://registry.modelcontextprotocol.io/) as `io.github.svayatta/agent-custody`; its entry is [server.json](server.json), published after each npm release by running the `mcp-registry` workflow from the Actions tab (GitHub OIDC, no token).
63
+ For your own Claude Code sessions, one command does the whole setup (key, config in observe mode, starter deny policy, hooks), and `agent-custody report` lists the calls the policy would have denied: `npm install -g @agent-custody/receipts`, then `agent-custody init claude-code`, then see [docs/sdk.md](docs/sdk.md#claude-code).
64
+
65
+ Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the Vercel AI SDK, LangChain, OpenClaw, DeepSeek Harness, Hermes and Google ADK, are in [docs/sdk.md](docs/sdk.md). To enforce rather than record, put the gateway between the agent and its tools: `npx @agent-custody/receipts gateway --config gateway.json`, set up in [docs/usage.md](docs/usage.md); between an agent and the agents it delegates to over A2A, `--a2a` serves the gateway as an A2A agent itself. The gateway is listed in the [MCP Registry](https://registry.modelcontextprotocol.io/) as `io.github.svayatta/agent-custody`; its entry is [server.json](server.json), published after each npm release by running the `mcp-registry` workflow from the Actions tab (GitHub OIDC, no token).
60
66
 
61
67
  ## How it fits together
62
68
 
@@ -95,18 +101,18 @@ flowchart LR
95
101
 
96
102
  Three parties hold keys. The **principal** signs a grant saying which agent may use which tools until when. The **issuer**, gateway or SDK, signs every receipt and every tree head. The **verifier** holds only public keys and needs no access to the issuer, the agent, or the upstream system.
97
103
 
98
- ## Two producers, one receipt
104
+ ## Three producers, one receipt
99
105
 
100
- | | gateway | SDK |
101
- | --- | --- | --- |
102
- | where it runs | separate process between agent and tools | inside the agent's process |
103
- | what it sees | MCP tool calls | whatever the framework's hooks expose |
104
- | enforcement | yes, denied calls never reach upstream | only where a hook can block |
105
- | provenance of its fields | `attested` and `observed` | `claimed`, all of them |
106
- | what a verifier learns | the agent could not skip or forge this | the agent's process reported this and it has not changed since |
107
- | install | one line in the host's MCP config | a hook entry or a wrapped function |
106
+ | | gateway | door | SDK |
107
+ | --- | --- | --- | --- |
108
+ | where it runs | separate process between agent and tools | separate process between the world and your own site or API | inside the agent's process |
109
+ | what it sees | MCP tool calls | every HTTP arrival, by route | whatever the framework's hooks expose |
110
+ | enforcement | yes, denied calls never reach upstream | yes, refused arrivals never reach the origin | only where a hook can block |
111
+ | provenance of its fields | `attested` and `observed` | `observed`; `attested` only when the arrival presented a grant, else `claimed` | `claimed`, all of them |
112
+ | what a verifier learns | the agent could not skip or forge this | the arrival could not skip or forge this; who it was is proven only with a grant | the agent's process reported this and it has not changed since |
113
+ | install | one line in the host's MCP config | a reverse proxy in front of the origin | a hook entry or a wrapped function |
108
114
 
109
- Every receipt names its issuer, and the verifier prints what that issuer kind is worth before anything else. A dashboard full of `sdk` rows is the reason to route the consequential calls through the gateway.
115
+ Every receipt names its issuer, and the verifier prints what that issuer kind is worth before anything else. A dashboard full of `sdk` rows is the reason to route the consequential calls through the gateway. The door is the gateway turned around ([the door](docs/door.md)).
110
116
 
111
117
  ### Supported hosts and frameworks
112
118
 
@@ -114,7 +120,7 @@ Every receipt names its issuer, and the verifier prints what that issuer kind is
114
120
  | --- | --- | --- | --- | --- |
115
121
  | any MCP host: Claude Desktop, Claude Code, Cursor, custom | gateway | yes | | a real MCP client and upstream over stdio |
116
122
  | Codex CLI (headless) | gateway | yes | | a manual `codex exec` run and offline MCP recovery checks; [guide](docs/codex-recovery.md) |
117
- | Claude Code | SDK | `hook` command, PreToolUse deny | PostToolUse | the documented hook contract, via stdin |
123
+ | Claude Code | SDK | `hook` command, PreToolUse deny; `init claude-code` sets it up | PostToolUse | the documented hook contract, via stdin; `init` and `report` against a temporary home |
118
124
  | Claude Agent SDK | SDK | `claudeAgentHooks` | same | the same handler |
119
125
  | OpenAI Agents SDK (JS) | SDK | `wrapTools` | `observeRunner` | a real `Runner` with a scripted model |
120
126
  | Vercel AI SDK | SDK | `wrapTools` | | a real `generateText` loop over the SDK's mock model |
@@ -193,7 +199,7 @@ Every field carries a provenance label. This is the design decision that matters
193
199
  bun install # from the repository root, once for the workspace
194
200
  cd packages/receipts
195
201
  node scripts/demo.ts # gateway: keys, grant, policy, four tool calls, verification, a tampering attempt; then the SDK wrapping the same tool
196
- node examples/01-keys-and-signing.ts # first of thirty-five step-by-step examples, see docs/tutorials.md
202
+ node examples/01-keys-and-signing.ts # first of the step-by-step examples, see docs/tutorials.md
197
203
  bun run test # this package; `bun run test` at the root runs every package
198
204
  ```
199
205
 
@@ -244,7 +250,8 @@ If a vendor tells you their receipts prove more than the first five rows, ask th
244
250
  ```
245
251
  src/config.ts gateway and SDK config schemas, path resolution
246
252
  src/crypto.ts canonical JSON, sha256, Ed25519 keys, DSSE sign/verify
247
- src/log.ts Merkle log: append, root, inclusion and consistency proofs, verify, JSONL persistence
253
+ src/log.ts Merkle log: append, root, inclusion and consistency proofs, verify, JSONL persistence; a lock file makes an append safe when several processes share one log file, and a partial last line from a killed writer is moved to `<file>.torn`
254
+ src/lock.ts the one lock file design (owner token, liveness check, rename to break a stale lock) that the local log, prune, and the gateway outbox share
248
255
  src/log-check.ts the outside monitor: verifies the head, checkpoints, witness, and anchor of a running log
249
256
  src/portal.ts the tenant portal: register, first key, usage against plan, keys, Stripe billing, export, member roles, TOTP MFA, single sign-on, on the log's Postgres
250
257
  src/sso.ts enterprise sign-in for the portal: OIDC (code and PKCE, id_token checked against the IdP's key set) and SAML 2.0 (signed assertions only, through @node-saml/node-saml)
@@ -253,19 +260,24 @@ src/witness.ts the witness: countersigns the log's checkpoints from another
253
260
  src/anchor.ts the anchor: commits a Merkle root over new checkpoints to a chain, or refuses with an alarm; checks a record against JSON-RPC
254
261
  src/anchor-evm.ts the anchor's transactions on Ethereum or another EVM chain, through the optional dependency viem
255
262
  src/completeness.ts completeness from the provider's side: the provider's own list, matched against verified receipts
263
+ src/pr-summary.ts `verify --markdown`: a directory of bundles verified into one Markdown table, for the GitHub Action
264
+ src/export.ts `export`: verified receipt bundles that keep their values private, copied byte for byte into a directory for a pull request
256
265
  src/signer.ts the signer: the log's key in its own process, the key document verifiers fetch
257
266
  src/checkpoints.ts signed heads published on a schedule, to files and to Postgres
258
267
  src/log-store.ts the log server's backends: the file, and Postgres with tenants, hashed tokens, one writer per tenant, rate limits
259
268
  src/log-sink.ts where leaves go: the local file, or a remote log over HTTP; plus the reference log server
260
269
  src/policy.ts Cedar evaluation wrapper, fail-closed
261
- src/simulate.ts replay recorded policy decisions against a proposed Cedar policy, grouped changes and run digest
270
+ src/policy-rego.ts Rego: compiled with opa build, evaluated in-process with the OPA WebAssembly SDK, fail-closed
271
+ src/opa-server.ts an OPA server's Data API as the policy, with bundle revisions as the digest
272
+ src/simulate.ts replay recorded policy decisions against a proposed Cedar or Rego policy, grouped changes and run digest
262
273
  src/delegation.ts signed delegation grants
263
274
  src/approval.ts exact-action human approvals, distinct trusted signatures, persistent single-use consumption
264
275
  src/receipt.ts receipt and authorization statement types and provenance labels
265
- src/issue.ts sign, log, and write a receipt, or commit an authorization first; shared by both producers
276
+ src/issue.ts sign, log, and write a receipt, or commit an authorization first; shared by every producer
266
277
  src/gateway.ts the MCP proxy: a host (key, policy, upstreams, log) and a session per grant; scope check, facts, policy, forward, receipt
267
278
  src/operations.ts SQLite operation claims and daily budget reservations, retained across retries and process crashes
268
279
  src/gateway-http.ts the gateway over Streamable HTTP: one process, a session per connection, each under the grant it presents
280
+ src/door.ts the door: a reverse proxy in front of your own HTTP surface; every arrival classified, decided per route, relayed or refused, receipted as issuer kind door
269
281
  src/sdk/index.ts the interceptor: policy decision, record, wrap(tool fn)
270
282
  src/sdk/claude.ts Claude Code command hook and Claude Agent SDK in-process hooks
271
283
  src/sdk/openai-agents.ts, vercel-ai.ts, langchain.ts framework adapters, tested against the real packages
@@ -278,12 +290,15 @@ src/upstream.ts attested execution: an upstream signs its result for the rece
278
290
  src/capture.ts private evidence: per-tool capture rules applied by the issuer to the whole statement, withheld values as salted commitments or encrypted under the customer's key, restore and reveal
279
291
  vectors/ conformance vectors: receipts, keys, logs, proofs, and expected verdicts; `bun run vectors` regenerates them
280
292
  src/verify.ts offline verification, the human-readable report, and the audit that a later log extends an earlier one
281
- src/cli.ts keygen, grant, gateway, hook, serve, log, prune, verify, reveal, audit, policy simulate
293
+ src/claude-init.ts `init claude-code`: the agent key, the observe-mode config, the starter policy, and the three hooks merged into the settings file with absolute paths
294
+ src/deny-report.ts `report`: verifies the receipts of an SDK config and lists the calls the policy would have denied
295
+ templates/ the starter Cedar policy that `init claude-code` copies (shipped in the package)
296
+ src/cli.ts keygen, grant, gateway, door, init, report, hook, serve, log, prune, verify, reveal, audit, policy simulate
282
297
  src/retention.ts pruning the log: leaves become their hashes, bundles are removed, proofs survive
283
298
  src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
284
299
  tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
285
- scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, fixture builders for gateway and SDK, the replay builder (`replay.ts`: example 27 and state example 07 as a folder of receipts and public keys anyone can verify with the published packages), demo
286
- examples/ thirty-five runnable tutorials, plus examples/languages/: Python, Go, Java, and Rust clients of the sidecar, run by the test suite, one per aspect; each is run by the test suite
300
+ scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, fixture builders for gateway, SDK, and door (with a stand-in origin), the replay builder (`replay.ts`: example 27 and state example 07 as a folder of receipts and public keys anyone can verify with the published packages), demo
301
+ examples/ runnable tutorials, plus examples/languages/: Python, Go, Java, and Rust clients of the sidecar, run by the test suite, one per aspect; each is run by the test suite
287
302
  test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
288
303
  adapter tests against the real packages, and a test that runs every policy in docs/policies.md
289
304
  docs/ tutorials, usage (gateway), codex-recovery (live demo), approvals, sdk, policies, verification
@@ -291,10 +306,15 @@ docs/ tutorials, usage (gateway), codex-recovery (live demo), appro
291
306
 
292
307
  ## Plan
293
308
 
294
- The design is two producers feeding one verifier. The SDK is the top of the funnel: cheap to install, wide reach, honest about being self-reported. The gateway is what a security or compliance owner mandates for consequential actions. Both exist; the work is widening each.
309
+ The design is three producers feeding one verifier. The SDK is the top of the funnel: cheap to install, wide reach, honest about being self-reported. The gateway is what a security or compliance owner mandates for consequential actions. The door turns the gateway around, in front of the business's own surface. All three exist; the work is widening each, and the door's next steps are detection signals with published error rates and standards-based passports (RFC 9421, AP2).
295
310
 
296
311
  **Done**
297
312
 
313
+ - An incident replay: `node examples/38-incident-replay.ts` plays a Claude Code session against the starter deny set in enforce mode. `terraform destroy` and `rm -rf ~` are denied before they run, and the denial receipts verify offline with the public key only. The site page [An incident replay](../../site/guide/incident-replay.md) shows the output and the limit: a credential in the agent's environment goes around the hook (tutorial 38).
314
+ - One command for Claude Code (issue #204): `agent-custody init claude-code` makes the agent key, writes `sdk.json` in observe mode with no log, writes a starter deny policy, and merges the three hooks into `.claude/settings.local.json` or `~/.claude/settings.json` with absolute paths, safe to run two times. `agent-custody report` verifies the receipts and prints the calls the policy would have denied, with the reason, the rule, and the receipt id; removing the `mode` line enforces. The default local log takes a lock for each append, so hooks that run at the same time keep one log; `--log-url` needs `--log-key`; a second run keeps the pinned log key and warns about log flags it does not apply; `init` warns when git does not ignore the project settings file ([sdk.md](docs/sdk.md#claude-code), tutorial 36).
315
+ - `agent-custody export`: copies the receipt bundles of a session into a directory for a pull request, byte for byte. It verifies each receipt against the issuer key, refuses one that carries plain arguments, results, or facts (unless `--allow-clear`), reads only `<id>.json` at the top level (never `salts/`, `outbox/`, or `*.authorization.json`), and keeps only the receipts issued at or after `--since`; [guide](docs/github-action.md), tutorial 39.
316
+ - A GitHub Action (`action.yml` at the repository root) that runs `verify --markdown` on a directory of receipt bundles, posts one table as a pull request comment that it edits on each push, writes the same table to the job summary, and fails when a receipt does not verify or none exists; [guide](docs/github-action.md). [Issue #205](https://github.com/svayatta/agent-custody/issues/205).
317
+ - The door, step one of the agent front door: `agent-custody door` is a reverse proxy in front of a business's own site or API. Every arrival is classified by what it presented (`verified` by a grant from a trusted principal in scope for its route, `claimed`, or `unknown`), decided by the Cedar policy for its route with the door's own arrival fact in context (the Cedar principal is a verified agent or `unknown`, never a declared name), committed to the log before any request that can change something is relayed, relayed to the origin or refused with 403, and receipted either way as issuer kind `door`; both verifiers, the Python verifier, and `policy simulate` accept the receipts, and five conformance vectors pin them. A Turnstile or hCaptcha token is verified with the provider and recorded as the `challenge` signal, so a policy can admit a person on a route that refuses `unknown`. It does not yet detect agents in web traffic or check HTTP message signatures ([the door](docs/door.md), [door signals](docs/door-signals.md), tutorial 40).
298
318
  - Strict mode: `"strict": true` refuses a local log, a log that is not hash-only, and a log without pinned keys; precommits every tool, in observe mode too; and turns the outbox off. No call the agent makes is forwarded before its authorization is in a log the operator does not run, every receipt says `issuer.strict`, and `verify --require-strict` requires it ([usage](docs/usage.md#strict-mode), tutorial 34). [Issue #177](https://github.com/svayatta/agent-custody/issues/177).
299
319
  - Policy reload: the gateway re-reads `policy.cedar` whenever it changes and applies it from the next call, with no restart and no dropped session; a policy that does not parse is refused and the one in force stays, and every change or refusal is recorded in `receipts/policy-reloads.jsonl` ([usage](docs/usage.md)).
300
320
  - Live Codex support recovery demo: model-selected MCP calls, incorrect CRM memory, a reviewed recovery plan, simulated credit compensation, and verified evidence; [guide](docs/codex-recovery.md), with offline regression coverage.
@@ -353,5 +373,3 @@ The first three close the gap between a log the operator cannot rewrite and a re
353
373
  5. Post-quantum signatures: ML-DSA beside Ed25519 in the same DSSE envelope, hybrid by default when a PQ key is present, in every signed artefact and in the browser verifier. [Issue #11](https://github.com/svayatta/agent-custody/issues/11).
354
374
  6. Receiver attestation for agent-to-agent calls: the delegate signs its answer for the receipt, as a signing upstream does today.
355
375
  7. SD-JWT redaction, then ZK proofs of policy compliance. Not before.
356
-
357
- A Python SDK follows the same shape once the TypeScript adapters have settled.
package/dist/check.d.ts CHANGED
@@ -15,5 +15,15 @@ export interface CheckOptions {
15
15
  /** cancels --connect while it is starting the upstreams; whatever was started is closed */
16
16
  signal?: AbortSignal;
17
17
  }
18
+ /** True when the file is a door config rather than a gateway config: it names an origin, which no gateway config has. */
19
+ export declare function isDoorConfig(configPath: string): boolean;
20
+ /**
21
+ * The agents named by permits that do not also require a verified arrival. At the door the principal is the agent of a
22
+ * verified grant, or `unknown`, so such a permit admits only a verified agent; the warning is for the reader who
23
+ * expects it to admit a declared name, as the same text would at the gateway.
24
+ */
25
+ export declare function permitsNamingAgentWithoutVerifiedArrival(policyText: string): string[];
26
+ /** `agent-custody check` on a door config: what the door would fail on at startup, and what it would silently do less than the config seems to promise. */
27
+ export declare function checkDoorConfig(configPath: string): CheckFinding[];
18
28
  export declare function checkConfig(configPath: string, options?: CheckOptions): Promise<CheckFinding[]>;
19
29
  export declare function formatFindings(findings: CheckFinding[]): string;
package/dist/check.js CHANGED
@@ -6,10 +6,12 @@ import * as cedar from "@cedar-policy/cedar-wasm/nodejs";
6
6
  import { accessSync, constants, existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
7
7
  import { tmpdir } from "node:os";
8
8
  import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
9
- import { GatewayConfigSchema, loadConfig, strictRefusals } from "./config.js";
9
+ import { DoorConfigSchema, GatewayConfigSchema, loadConfig, loadDoorConfig, strictRefusals } from "./config.js";
10
10
  import { generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
11
11
  import { delegationValidAt, verifyDelegation } from "./delegation.js";
12
12
  import { hasPermitRule } from "./policy.js";
13
+ import { compileRego, isRegoFile } from "./policy-rego.js";
14
+ import { createOpaServerPolicy } from "./opa-server.js";
13
15
  import { createGatewayHost } from "./gateway.js";
14
16
  const distance = (a, b) => {
15
17
  const row = Array.from({ length: b.length + 1 }, (_, i) => i);
@@ -46,6 +48,158 @@ function onPath(command) {
46
48
  return existsSync(command);
47
49
  return (process.env.PATH ?? "").split(delimiter).some((d) => d && existsSync(join(d, command)));
48
50
  }
51
+ /** True when the file is a door config rather than a gateway config: it names an origin, which no gateway config has. */
52
+ export function isDoorConfig(configPath) {
53
+ try {
54
+ const raw = JSON.parse(readFileSync(configPath, "utf8"));
55
+ return !!raw && typeof raw === "object" && !Array.isArray(raw) && "origin" in raw && !("upstream" in raw) && !("upstreams" in raw);
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }
61
+ /**
62
+ * The agents named by permits that do not also require a verified arrival. At the door the principal is the agent of a
63
+ * verified grant, or `unknown`, so such a permit admits only a verified agent; the warning is for the reader who
64
+ * expects it to admit a declared name, as the same text would at the gateway.
65
+ */
66
+ export function permitsNamingAgentWithoutVerifiedArrival(policyText) {
67
+ const parts = cedar.policySetTextToParts(policyText);
68
+ if (parts.type !== "success")
69
+ return [];
70
+ const out = [];
71
+ for (const policy of parts.policies) {
72
+ const j = cedar.policyToJson(policy);
73
+ if (j.type !== "success" || j.json.effect !== "permit")
74
+ continue;
75
+ const principal = j.json.principal;
76
+ if (principal.op === "All" || !principal.entity)
77
+ continue;
78
+ const conditions = JSON.stringify(j.json.conditions ?? []);
79
+ if (conditions.includes('"class"') && conditions.includes('"verified"'))
80
+ continue;
81
+ out.push(`${principal.entity.type}::"${principal.entity.id}"`);
82
+ }
83
+ return out;
84
+ }
85
+ /** `agent-custody check` on a door config: what the door would fail on at startup, and what it would silently do less than the config seems to promise. */
86
+ export function checkDoorConfig(configPath) {
87
+ const out = [];
88
+ const add = (level, check, message) => out.push({ level, check, message });
89
+ let raw;
90
+ try {
91
+ raw = JSON.parse(readFileSync(configPath, "utf8"));
92
+ }
93
+ catch (e) {
94
+ add("error", "config", `${configPath} is not readable JSON: ${e instanceof Error ? e.message : String(e)}`);
95
+ return out;
96
+ }
97
+ const known = Object.keys(DoorConfigSchema.shape);
98
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
99
+ for (const key of Object.keys(raw)) {
100
+ if (known.includes(key))
101
+ continue;
102
+ const near = known.find((k) => distance(k.toLowerCase(), key.toLowerCase()) <= 2);
103
+ add("error", "config", `unknown key "${key}" is ignored by the door${near ? `; did you mean "${near}"?` : ""} A mistyped key leaves the setting it was meant for at its default`);
104
+ }
105
+ }
106
+ const parsed = DoorConfigSchema.safeParse(raw);
107
+ if (!parsed.success) {
108
+ for (const issue of parsed.error.issues)
109
+ add("error", "config", `${issue.path.join(".") || "(root)"}: ${issue.message}`);
110
+ return out;
111
+ }
112
+ add("ok", "config", "the config parses");
113
+ const cfg = loadDoorConfig(configPath);
114
+ if (!existsSync(cfg.identity.keyFile))
115
+ add("warn", "key", `${cfg.identity.keyFile} does not exist yet; \`agent-custody keygen\` creates it`);
116
+ else {
117
+ try {
118
+ loadPrivateKey(cfg.identity.keyFile);
119
+ add("ok", "key", `the door key at ${cfg.identity.keyFile} loads`);
120
+ if (process.platform !== "win32" && (statSync(cfg.identity.keyFile).mode & 0o077) !== 0)
121
+ add("warn", "key", `${cfg.identity.keyFile} is readable by other users; make it mode 0600`);
122
+ }
123
+ catch (e) {
124
+ add("error", "key", `${cfg.identity.keyFile}: ${e instanceof Error ? e.message : String(e)}`);
125
+ }
126
+ }
127
+ let principals = 0;
128
+ for (const f of cfg.trustedPrincipalKeys) {
129
+ try {
130
+ loadPublicKey(f);
131
+ principals++;
132
+ }
133
+ catch (e) {
134
+ add("error", "principal keys", `${f}: ${e instanceof Error ? e.message : String(e)}`);
135
+ }
136
+ }
137
+ if (cfg.trustedPrincipalKeys.length === 0)
138
+ add("warn", "principal keys", "no trusted principal keys: no arrival can be verified, every one is claimed or unknown");
139
+ else if (principals === cfg.trustedPrincipalKeys.length)
140
+ add("ok", "principal keys", `${principals} trusted principal key${principals === 1 ? "" : "s"} load`);
141
+ if (!existsSync(cfg.policyFile))
142
+ add("error", "policy", `${cfg.policyFile} does not exist`);
143
+ else {
144
+ const text = readFileSync(cfg.policyFile, "utf8");
145
+ const r = cedar.checkParsePolicySet({ staticPolicies: text });
146
+ if (r.type !== "success")
147
+ for (const e of r.errors)
148
+ add("error", "policy", `${cfg.policyFile}: ${e.message}`);
149
+ else if (!hasPermitRule(text))
150
+ add("warn", "policy", `${cfg.policyFile} has no permit rule, so every arrival is refused`);
151
+ else {
152
+ add("ok", "policy", "the policy parses");
153
+ for (const name of permitsNamingAgentWithoutVerifiedArrival(text))
154
+ add("warn", "policy", `a permit names ${name} without requiring context.facts.arrival.class == "verified": the principal is that agent only for a verified grant, so this permit admits nothing else; if it was copied from a gateway policy, add the arrival condition`);
155
+ }
156
+ }
157
+ if (cfg.mode === "observe")
158
+ add("warn", "mode", "observe mode relays every arrival and records what the policy would have decided; nothing is refused by policy");
159
+ add("ok", "precommit", cfg.precommit.includes("*") ? "every arrival is committed to the log before it is relayed" : `every POST, PUT, PATCH, and DELETE${cfg.precommit.length ? `, and every arrival at ${cfg.precommit.join(", ")},` : ""} is committed to the log before it is relayed`);
160
+ if (cfg.routes.length === 0)
161
+ add("warn", "routes", `no routes: every arrival is the action "${cfg.unmatchedRoute}"`);
162
+ else
163
+ add("ok", "routes", `${cfg.routes.length} route(s); unmatched arrivals are "${cfg.unmatchedRoute}"`);
164
+ const origin = new URL(cfg.origin.url);
165
+ if (origin.protocol !== "https:" && !["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname))
166
+ add("warn", "origin", `${cfg.origin.url} is plain HTTP to a remote host; the relayed traffic is not encrypted on that leg`);
167
+ else
168
+ add("ok", "origin", `relays to ${cfg.origin.url}`);
169
+ for (const [, variable] of Object.entries(cfg.origin.headerEnv ?? {}))
170
+ if (!process.env[variable])
171
+ add("error", "credentials", `origin header variable ${variable} is not set in this environment`);
172
+ if (cfg.log?.tokenEnv && !process.env[cfg.log.tokenEnv])
173
+ add("error", "credentials", `log token variable ${cfg.log.tokenEnv} is not set in this environment`);
174
+ if (cfg.splunk?.tokenEnv && !process.env[cfg.splunk.tokenEnv])
175
+ add("error", "credentials", `splunk token variable ${cfg.splunk.tokenEnv} is not set in this environment`);
176
+ for (const v of Object.values(cfg.otel?.headersEnv ?? {}))
177
+ if (!process.env[v])
178
+ add("error", "credentials", `otel header variable ${v} is not set in this environment`);
179
+ for (const f of cfg.log?.keys ?? [])
180
+ if (!existsSync(f))
181
+ add("error", "log keys", `${f} does not exist`);
182
+ if (cfg.captureKeyEnv && !process.env[cfg.captureKeyEnv])
183
+ add("error", "credentials", `capture key variable ${cfg.captureKeyEnv} is not set in this environment`);
184
+ if (cfg.challenge) {
185
+ if (!process.env[cfg.challenge.secretEnv])
186
+ add("error", "credentials", `challenge secret variable ${cfg.challenge.secretEnv} is not set in this environment`);
187
+ add("ok", "challenge", `${cfg.challenge.provider} tokens in the ${cfg.challenge.header} header are verified with the provider; the outcome is context.facts.arrival.challenge.outcome, and class is unchanged by it`);
188
+ }
189
+ else
190
+ add("ok", "challenge", "no challenge: an unknown arrival has no way to become anything else on this door");
191
+ const dir = writableAncestor(cfg.receiptsDir);
192
+ if (!dir)
193
+ add("error", "paths", `${cfg.receiptsDir} cannot be created: no writable directory above it`);
194
+ else
195
+ add("ok", "paths", `receipts go to ${cfg.receiptsDir}`);
196
+ if (cfg.logFile) {
197
+ const ldir = writableAncestor(cfg.logFile);
198
+ if (!ldir)
199
+ add("error", "paths", `${cfg.logFile} cannot be written`);
200
+ }
201
+ return out;
202
+ }
49
203
  export async function checkConfig(configPath, options = {}) {
50
204
  const out = [];
51
205
  const add = (level, check, message) => out.push({ level, check, message });
@@ -101,10 +255,30 @@ export async function checkConfig(configPath, options = {}) {
101
255
  }
102
256
  if (principals.length === cfg.trustedPrincipalKeys.length)
103
257
  add("ok", "principal keys", `${principals.length} trusted principal key${principals.length === 1 ? "" : "s"} load`);
104
- // the policy
105
- if (!existsSync(cfg.policyFile)) {
258
+ // the policy: an OPA server answers for its package, a Rego file compiles, a Cedar file parses
259
+ if (cfg.opa) {
260
+ let bundles = {};
261
+ try {
262
+ await createOpaServerPolicy(cfg.opa, (p) => { if (p.bundles)
263
+ bundles = p.bundles; }).probe();
264
+ add("ok", "policy", `the OPA server at ${cfg.opa.url} answers for data.${(cfg.opa.decision ?? "agentcustody").replaceAll("/", ".")}`);
265
+ if (!Object.keys(bundles).length)
266
+ add("warn", "policy", "the OPA server reports no bundle revision, so receipts cannot name the policy that decided; serve the policy from a bundle with a revision");
267
+ }
268
+ catch (e) {
269
+ add("error", "policy", e instanceof Error ? e.message : String(e));
270
+ }
271
+ }
272
+ else if (!cfg.policyFile || !existsSync(cfg.policyFile)) {
106
273
  add("error", "policy", `${cfg.policyFile} does not exist`);
107
274
  }
275
+ else if (isRegoFile(cfg.policyFile)) {
276
+ const errors = compileRego(readFileSync(cfg.policyFile, "utf8")).errors;
277
+ for (const e of errors)
278
+ add("error", "policy", `${cfg.policyFile}: ${e}`);
279
+ if (!errors.length)
280
+ add("ok", "policy", "the Rego policy compiles");
281
+ }
108
282
  else {
109
283
  const text = readFileSync(cfg.policyFile, "utf8");
110
284
  const r = cedar.checkParsePolicySet({ staticPolicies: text });
@@ -139,6 +313,8 @@ export async function checkConfig(configPath, options = {}) {
139
313
  envNames.push(["otel", v]);
140
314
  if (cfg.captureKeyEnv)
141
315
  envNames.push(["capture", cfg.captureKeyEnv]);
316
+ if (cfg.opa?.tokenEnv)
317
+ envNames.push(["opa", cfg.opa.tokenEnv]);
142
318
  const skipEnvironment = options.environment === "skip";
143
319
  const missing = skipEnvironment ? [] : envNames.filter(([, v]) => !process.env[v]);
144
320
  for (const [who, v] of missing)
@@ -0,0 +1,46 @@
1
+ export declare const HOOK_EVENTS: readonly ["PreToolUse", "PostToolUse", "PostToolUseFailure"];
2
+ export declare const HOOK_MATCHER = "Bash|Write|Edit|MultiEdit|NotebookEdit|mcp__.*";
3
+ export interface ClaudeInitOptions {
4
+ /** The absolute path of the CLI script that runs now. The hook runs this script. */
5
+ cliPath: string;
6
+ /** The Node binary that the hook runs. Default: the binary that runs now. */
7
+ nodePath?: string;
8
+ /** Default: `~/.config/agent-custody` */
9
+ dir?: string;
10
+ /** Write the hooks to `~/.claude/settings.json`. Default: `.claude/settings.local.json` in `cwd`. */
11
+ user?: boolean;
12
+ /** Leave out `"mode": "observe"`, so the policy blocks a denied call. */
13
+ enforce?: boolean;
14
+ logUrl?: string;
15
+ logId?: string;
16
+ /** The NAME of the environment variable that holds the log token. Never the token. */
17
+ logTokenEnv?: string;
18
+ /** The log's public key file. A log URL needs it. The command copies it into the directory when it writes a new config. */
19
+ logKey?: string;
20
+ home?: string;
21
+ cwd?: string;
22
+ /** One line of progress. Default: stdout. */
23
+ print?: (line: string) => void;
24
+ }
25
+ export interface ClaudeInitResult {
26
+ dir: string;
27
+ configFile: string;
28
+ settingsFile: string;
29
+ hookCommand: string;
30
+ }
31
+ /** A shell word for a path: bare when it is plain, in single quotes otherwise. */
32
+ export declare function shellQuote(s: string): string;
33
+ type Json = Record<string, unknown>;
34
+ /** Parses a settings file. Throws, and so changes nothing, when the text is not a JSON object with usable `hooks`. */
35
+ export declare function parseSettings(text: string, file: string): Json;
36
+ export type HookChange = "added" | "updated" | "kept";
37
+ /**
38
+ * Registers the hook command for the three events and keeps every other key and hook. A hook of ours is a command
39
+ * that ends with `hook --config <this config>`. It is updated in place when its command differs, and never added twice.
40
+ */
41
+ export declare function mergeHooks(settings: Json, command: string, configFile: string): {
42
+ settings: Json;
43
+ changes: Record<string, HookChange>;
44
+ };
45
+ export declare function initClaudeCode(o: ClaudeInitOptions): ClaudeInitResult;
46
+ export {};