@agent-custody/receipts 0.14.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.
- package/README.md +33 -20
- package/dist/check.d.ts +10 -0
- package/dist/check.js +179 -3
- package/dist/cli.js +82 -11
- package/dist/config.d.ts +128 -1
- package/dist/config.js +92 -3
- package/dist/console.js +16 -7
- package/dist/deny-report.js +1 -1
- package/dist/door.d.ts +203 -0
- package/dist/door.js +712 -0
- package/dist/export.d.ts +39 -0
- package/dist/export.js +95 -0
- package/dist/gateway.js +53 -21
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/issue.js +5 -65
- package/dist/lock.d.ts +12 -0
- package/dist/lock.js +124 -0
- package/dist/log.d.ts +11 -5
- package/dist/log.js +55 -42
- package/dist/opa-server.d.ts +34 -0
- package/dist/opa-server.js +93 -0
- package/dist/policy-rego.d.ts +30 -0
- package/dist/policy-rego.js +114 -0
- package/dist/pr-summary.d.ts +25 -0
- package/dist/pr-summary.js +87 -0
- package/dist/receipt.d.ts +3 -1
- package/dist/retention.d.ts +1 -1
- package/dist/retention.js +14 -4
- package/dist/sdk/index.js +10 -3
- package/dist/simulate.d.ts +3 -1
- package/dist/simulate.js +15 -7
- package/dist/verify.js +6 -3
- package/docs/configuration.md +3 -3
- package/docs/door-signals.md +66 -0
- package/docs/door.md +168 -0
- package/docs/github-action.md +164 -0
- package/docs/policies.md +112 -1
- package/docs/sdk.md +25 -9
- package/docs/tutorials.md +3 -0
- package/docs/usage.md +2 -2
- package/docs/verification.md +9 -2
- package/package.json +14 -13
- package/templates/claude-code.cedar +287 -10
- package/vectors/audit.json +27 -27
- package/vectors/canonical.json +5 -5
- package/vectors/merkle.json +123 -0
- 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
|
-
|
|
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
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
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
|
|
@@ -56,7 +60,7 @@ 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
|
-
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: `
|
|
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).
|
|
60
64
|
|
|
61
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).
|
|
62
66
|
|
|
@@ -97,18 +101,18 @@ flowchart LR
|
|
|
97
101
|
|
|
98
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.
|
|
99
103
|
|
|
100
|
-
##
|
|
104
|
+
## Three producers, one receipt
|
|
101
105
|
|
|
102
|
-
| | gateway | SDK |
|
|
103
|
-
| --- | --- | --- |
|
|
104
|
-
| where it runs | separate process between agent and tools | inside the agent's process |
|
|
105
|
-
| what it sees | MCP tool calls | whatever the framework's hooks expose |
|
|
106
|
-
| enforcement | yes, denied calls never reach upstream | only where a hook can block |
|
|
107
|
-
| provenance of its fields | `attested` and `observed` | `claimed`, all of them |
|
|
108
|
-
| what a verifier learns | the agent could not skip or forge this | the agent's process reported this and it has not changed since |
|
|
109
|
-
| 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 |
|
|
110
114
|
|
|
111
|
-
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)).
|
|
112
116
|
|
|
113
117
|
### Supported hosts and frameworks
|
|
114
118
|
|
|
@@ -246,7 +250,8 @@ If a vendor tells you their receipts prove more than the first five rows, ask th
|
|
|
246
250
|
```
|
|
247
251
|
src/config.ts gateway and SDK config schemas, path resolution
|
|
248
252
|
src/crypto.ts canonical JSON, sha256, Ed25519 keys, DSSE sign/verify
|
|
249
|
-
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
|
|
250
255
|
src/log-check.ts the outside monitor: verifies the head, checkpoints, witness, and anchor of a running log
|
|
251
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
|
|
252
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)
|
|
@@ -255,19 +260,24 @@ src/witness.ts the witness: countersigns the log's checkpoints from another
|
|
|
255
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
|
|
256
261
|
src/anchor-evm.ts the anchor's transactions on Ethereum or another EVM chain, through the optional dependency viem
|
|
257
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
|
|
258
265
|
src/signer.ts the signer: the log's key in its own process, the key document verifiers fetch
|
|
259
266
|
src/checkpoints.ts signed heads published on a schedule, to files and to Postgres
|
|
260
267
|
src/log-store.ts the log server's backends: the file, and Postgres with tenants, hashed tokens, one writer per tenant, rate limits
|
|
261
268
|
src/log-sink.ts where leaves go: the local file, or a remote log over HTTP; plus the reference log server
|
|
262
269
|
src/policy.ts Cedar evaluation wrapper, fail-closed
|
|
263
|
-
src/
|
|
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
|
|
264
273
|
src/delegation.ts signed delegation grants
|
|
265
274
|
src/approval.ts exact-action human approvals, distinct trusted signatures, persistent single-use consumption
|
|
266
275
|
src/receipt.ts receipt and authorization statement types and provenance labels
|
|
267
|
-
src/issue.ts sign, log, and write a receipt, or commit an authorization first; shared by
|
|
276
|
+
src/issue.ts sign, log, and write a receipt, or commit an authorization first; shared by every producer
|
|
268
277
|
src/gateway.ts the MCP proxy: a host (key, policy, upstreams, log) and a session per grant; scope check, facts, policy, forward, receipt
|
|
269
278
|
src/operations.ts SQLite operation claims and daily budget reservations, retained across retries and process crashes
|
|
270
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
|
|
271
281
|
src/sdk/index.ts the interceptor: policy decision, record, wrap(tool fn)
|
|
272
282
|
src/sdk/claude.ts Claude Code command hook and Claude Agent SDK in-process hooks
|
|
273
283
|
src/sdk/openai-agents.ts, vercel-ai.ts, langchain.ts framework adapters, tested against the real packages
|
|
@@ -283,11 +293,11 @@ src/verify.ts offline verification, the human-readable report, and the audi
|
|
|
283
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
|
|
284
294
|
src/deny-report.ts `report`: verifies the receipts of an SDK config and lists the calls the policy would have denied
|
|
285
295
|
templates/ the starter Cedar policy that `init claude-code` copies (shipped in the package)
|
|
286
|
-
src/cli.ts keygen, grant, gateway, init, report, hook, serve, log, prune, verify, reveal, audit, policy simulate
|
|
296
|
+
src/cli.ts keygen, grant, gateway, door, init, report, hook, serve, log, prune, verify, reveal, audit, policy simulate
|
|
287
297
|
src/retention.ts pruning the log: leaves become their hashes, bundles are removed, proofs survive
|
|
288
298
|
src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
|
|
289
299
|
tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
|
|
290
|
-
scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, fixture builders for gateway and
|
|
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
|
|
291
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
|
|
292
302
|
test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
|
|
293
303
|
adapter tests against the real packages, and a test that runs every policy in docs/policies.md
|
|
@@ -296,12 +306,15 @@ docs/ tutorials, usage (gateway), codex-recovery (live demo), appro
|
|
|
296
306
|
|
|
297
307
|
## Plan
|
|
298
308
|
|
|
299
|
-
The design is
|
|
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).
|
|
300
310
|
|
|
301
311
|
**Done**
|
|
302
312
|
|
|
303
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).
|
|
304
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).
|
|
305
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).
|
|
306
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)).
|
|
307
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.
|
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 (
|
|
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)
|
package/dist/cli.js
CHANGED
|
@@ -5,7 +5,7 @@ import { saltsFileFor } from "./retention.js";
|
|
|
5
5
|
import { parseArgs } from "node:util";
|
|
6
6
|
import { closeSync, constants as fsConstants, existsSync, fchmodSync, openSync, readFileSync, readdirSync, writeFileSync, writeSync } from "node:fs";
|
|
7
7
|
import { dirname, join, resolve } from "node:path";
|
|
8
|
-
import { loadConfig, loadSdkConfig } from "./config.js";
|
|
8
|
+
import { loadConfig, loadDoorConfig, loadSdkConfig } from "./config.js";
|
|
9
9
|
import { dsseVerify, generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
|
|
10
10
|
import { createDelegation, decodeDelegation, delegateFrom, grantDigest } from "./delegation.js";
|
|
11
11
|
import { createGateway, createGatewayHost, serveStdio, writeRevokedGrants } from "./gateway.js";
|
|
@@ -19,6 +19,7 @@ import { Anchor, ANCHOR_CHAINS, resolveAnchorChain } from "./anchor.js";
|
|
|
19
19
|
import { checkCompleteness, formatCompleteness, stripeSource } from "./completeness.js";
|
|
20
20
|
import { evmChain } from "./anchor-evm.js";
|
|
21
21
|
import { serveHttp } from "./gateway-http.js";
|
|
22
|
+
import { createDoorHost, serveDoor } from "./door.js";
|
|
22
23
|
import { serveA2a } from "./a2a.js";
|
|
23
24
|
import { PortalStore, sendFollowUps, servePortal } from "./portal.js";
|
|
24
25
|
import { exportLog, formatExport } from "./log-export.js";
|
|
@@ -26,7 +27,7 @@ import { CheckpointPublisher, fileResolver } from "./log-sink.js";
|
|
|
26
27
|
import { createRequire } from "node:module";
|
|
27
28
|
import { pruneLog } from "./retention.js";
|
|
28
29
|
import { serveSidecar } from "./sidecar.js";
|
|
29
|
-
import { checkConfig, formatFindings } from "./check.js";
|
|
30
|
+
import { checkConfig, checkDoorConfig, formatFindings, isDoorConfig } from "./check.js";
|
|
30
31
|
import { serveConsole } from "./console.js";
|
|
31
32
|
import { TREEHEAD_TYPE } from "./receipt.js";
|
|
32
33
|
import { MerkleLog } from "./log.js";
|
|
@@ -36,7 +37,10 @@ import { denyReport, formatDenyReport } from "./deny-report.js";
|
|
|
36
37
|
import { fileURLToPath } from "node:url";
|
|
37
38
|
import { handleHookEvent } from "./sdk/claude.js";
|
|
38
39
|
import { auditExtends, formatReport, verifyBundle } from "./verify.js";
|
|
40
|
+
import { CLEAR_WARNING, exportReceipts, formatReceiptExport as formatExportLines } from "./export.js";
|
|
41
|
+
import { formatSummaryMarkdown, receiptFiles, summarizeReceipts } from "./pr-summary.js";
|
|
39
42
|
import { formatSimulation, simulatePolicy, verifyOrphanAuthorization } from "./simulate.js";
|
|
43
|
+
import { isRegoFile } from "./policy-rego.js";
|
|
40
44
|
/**
|
|
41
45
|
* Resolves on SIGINT or SIGTERM: a container runtime and systemd stop a service with SIGTERM, which PID 1 ignores unless
|
|
42
46
|
* it is handled. The handlers are installed once, before a service starts, so a signal that arrives while it starts up
|
|
@@ -50,7 +54,7 @@ function untilStopped() {
|
|
|
50
54
|
});
|
|
51
55
|
return stopped;
|
|
52
56
|
}
|
|
53
|
-
const SERVICES = new Set(["serve", "witness", "signer", "portal", "log", "console"]);
|
|
57
|
+
const SERVICES = new Set(["serve", "witness", "signer", "portal", "log", "console", "door"]);
|
|
54
58
|
/** a command that waits for untilStopped(); a stdio gateway runs until its input closes and keeps the default signal behaviour */
|
|
55
59
|
const runsUntilStopped = (cmd, args) => !!cmd && (SERVICES.has(cmd) || (cmd === "gateway" && (args.includes("--http") || args.includes("--a2a"))));
|
|
56
60
|
/** A secret kept in a file that only this process can read, such as a container secret mounted at /run/secrets. The file's path is not a secret; its contents are. */
|
|
@@ -90,6 +94,10 @@ const USAGE = `agent-custody <command>
|
|
|
90
94
|
gateway --config <gateway.json> [--http [--port 8790] [--host 127.0.0.1] [--idle-minutes 30]]
|
|
91
95
|
stdio: one gateway for the grant the config names. --http: one shared gateway, MCP over
|
|
92
96
|
Streamable HTTP at /mcp, each connection presenting its own grant as Authorization: Bearer
|
|
97
|
+
door --config <door.json> [--port 8780] [--host 127.0.0.1]
|
|
98
|
+
a reverse proxy in front of your own site or API: every arrival classified (verified by a
|
|
99
|
+
trusted grant, claimed, or unknown), decided by the Cedar policy for its route, relayed to the
|
|
100
|
+
origin or refused with 403, and receipted either way; GET /.well-known/agent-custody-door
|
|
93
101
|
init claude-code [--dir <dir>] [--user] [--enforce] [--log-url <url> [--log-id <id>] [--log-token-env NAME] [--log-key <pub>]]
|
|
94
102
|
one command for your own Claude Code sessions: an agent key, sdk.json in observe mode, a starter deny
|
|
95
103
|
policy, and the three hooks in .claude/settings.local.json (--user: ~/.claude/settings.json). Safe to run twice
|
|
@@ -101,7 +109,11 @@ const USAGE = `agent-custody <command>
|
|
|
101
109
|
retention on the receipt log: replaces older leaves with their hashes, so proofs still verify and the content is gone
|
|
102
110
|
log --file <log.jsonl> --key <log.key> [--port 8787] [--host 127.0.0.1] [--token-env <NAME>] reference log server
|
|
103
111
|
verify <bundle.json> --issuer-key <pub> [--principal-key <pub>] [--approval-key <pub>] [--log-key <pub> | --log-url <url>] [--log-id <id>] [--require-strict] [--upstream-key <pub>] [--stripe-secret-env NAME] [--github-secret-env NAME] [--log <log.jsonl>] [--disclose <file>] [--capture-key-env NAME] [--json]
|
|
104
|
-
|
|
112
|
+
verify --markdown <dir|bundle.json>... --issuer-key <pub> one Markdown table for a directory of bundles; exit 1 when one does not verify or none exists
|
|
113
|
+
export --receipts <dir> --out <dir> --issuer-key <pub>... [--principal-key <pub>]... [--approval-key <pub>]... [--since <ISO time>] [--allow-clear]
|
|
114
|
+
copies the verified receipt bundles that keep their values private into a directory for a pull request, byte for byte.
|
|
115
|
+
Reads only <id>.json at the top level; never salts/, outbox/, or *.authorization.json. Exits 1 when it refuses a receipt, and when it copies none
|
|
116
|
+
policy simulate --policy <proposed.cedar|.rego> --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--approval-key <pub>]... [--log-key <pub>]... [--json] [--out <file>]
|
|
105
117
|
completeness --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--log-key <pub>]... [--log <log.jsonl>] [--log-id <id>]
|
|
106
118
|
--provider stripe --object refunds|payouts|transfers --key-env NAME --tool <name>... --since <ISO> --until <ISO>
|
|
107
119
|
[--id-path id] [--amount-field amount] [--currency-field currency] [--beneficiary <arg>=<field>]... [--json]
|
|
@@ -281,7 +293,7 @@ async function main(argv) {
|
|
|
281
293
|
const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, connect: { type: "boolean", default: false }, json: { type: "boolean", default: false } } });
|
|
282
294
|
if (!values.config)
|
|
283
295
|
throw new Error("check needs --config");
|
|
284
|
-
const findings = await checkConfig(values.config, { connect: values.connect });
|
|
296
|
+
const findings = isDoorConfig(values.config) ? checkDoorConfig(values.config) : await checkConfig(values.config, { connect: values.connect });
|
|
285
297
|
console.log(values.json ? JSON.stringify(findings, null, 2) : formatFindings(findings));
|
|
286
298
|
return findings.some((f) => f.level === "error") ? 1 : 0;
|
|
287
299
|
}
|
|
@@ -339,6 +351,19 @@ async function main(argv) {
|
|
|
339
351
|
await gw.close();
|
|
340
352
|
return 0;
|
|
341
353
|
}
|
|
354
|
+
case "door": {
|
|
355
|
+
const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, port: { type: "string", default: "8780" }, host: { type: "string", default: "127.0.0.1" } } });
|
|
356
|
+
if (!values.config)
|
|
357
|
+
throw new Error("door needs --config");
|
|
358
|
+
const cfg = loadDoorConfig(values.config);
|
|
359
|
+
const host = await createDoorHost(cfg, { autoFlush: true });
|
|
360
|
+
const running = await serveDoor(host, { port: Number(values.port), host: values.host });
|
|
361
|
+
console.error(`agent-custody door: ${running.url} keyid=${host.keyid} in front of ${cfg.origin.url}; ${cfg.routes.length} route(s), unmatched arrivals are "${cfg.unmatchedRoute}"`);
|
|
362
|
+
await untilStopped();
|
|
363
|
+
await running.close();
|
|
364
|
+
await host.close();
|
|
365
|
+
return 0;
|
|
366
|
+
}
|
|
342
367
|
case "init": {
|
|
343
368
|
const [target, ...args] = rest;
|
|
344
369
|
if (target !== "claude-code")
|
|
@@ -770,18 +795,20 @@ async function main(argv) {
|
|
|
770
795
|
disclose: { type: "string" },
|
|
771
796
|
"capture-key-env": { type: "string" },
|
|
772
797
|
json: { type: "boolean", default: false },
|
|
798
|
+
markdown: { type: "boolean", default: false },
|
|
773
799
|
},
|
|
774
800
|
});
|
|
775
801
|
const file = positionals[0];
|
|
776
802
|
const issuerKeyFiles = [...(values["issuer-key"] ?? []), ...(values["gateway-key"] ?? [])];
|
|
777
803
|
if (!file || issuerKeyFiles.length === 0)
|
|
778
804
|
throw new Error("verify needs <bundle> --issuer-key (alias --gateway-key)");
|
|
779
|
-
|
|
805
|
+
if (values.markdown && (values.json || values.disclose))
|
|
806
|
+
throw new Error("verify --markdown does not combine with --json or --disclose");
|
|
780
807
|
const captureKey = values["capture-key-env"] ? captureKeyFrom(secretFrom(values["capture-key-env"])) : undefined;
|
|
781
808
|
const disclosed = values.disclose ? JSON.parse(readFileSync(values.disclose, "utf8")) : undefined;
|
|
782
809
|
const fetchedLogKeys = values["log-url"] ? (await fetchLogKeys(values["log-url"])).keys : [];
|
|
783
810
|
const logKeys = [...(values["log-key"] ?? []).map(loadPublicKey), ...fetchedLogKeys];
|
|
784
|
-
const
|
|
811
|
+
const verifyOptions = {
|
|
785
812
|
issuerKeys: issuerKeyFiles.map(loadPublicKey),
|
|
786
813
|
principalKeys: (values["principal-key"] ?? []).map(loadPublicKey),
|
|
787
814
|
...(values["approval-key"] ? { approvalKeys: values["approval-key"].map(loadPublicKey) } : {}),
|
|
@@ -793,10 +820,54 @@ async function main(argv) {
|
|
|
793
820
|
...(values.log ? { logFile: values.log } : {}),
|
|
794
821
|
...(captureKey ? { captureKey } : {}),
|
|
795
822
|
...(disclosed ? { disclosed } : {}),
|
|
796
|
-
}
|
|
823
|
+
};
|
|
824
|
+
if (values.markdown) {
|
|
825
|
+
const summary = summarizeReceipts(positionals.flatMap(receiptFiles), verifyOptions);
|
|
826
|
+
console.log(formatSummaryMarkdown(summary));
|
|
827
|
+
return summary.ok ? 0 : 1;
|
|
828
|
+
}
|
|
829
|
+
const result = verifyBundle(JSON.parse(readFileSync(file, "utf8")), verifyOptions);
|
|
797
830
|
console.log(values.json ? JSON.stringify(result, null, 2) : formatReport(result));
|
|
798
831
|
return result.ok ? 0 : 1;
|
|
799
832
|
}
|
|
833
|
+
case "export": {
|
|
834
|
+
const { values } = parseArgs({
|
|
835
|
+
args: rest,
|
|
836
|
+
options: {
|
|
837
|
+
receipts: { type: "string" },
|
|
838
|
+
out: { type: "string" },
|
|
839
|
+
"issuer-key": { type: "string", multiple: true },
|
|
840
|
+
"principal-key": { type: "string", multiple: true },
|
|
841
|
+
"approval-key": { type: "string", multiple: true },
|
|
842
|
+
since: { type: "string" },
|
|
843
|
+
"allow-clear": { type: "boolean", default: false },
|
|
844
|
+
},
|
|
845
|
+
});
|
|
846
|
+
if (!values.receipts || !values.out || !values["issuer-key"]?.length)
|
|
847
|
+
throw new Error("export needs --receipts <dir>, --out <dir> and --issuer-key <pub>");
|
|
848
|
+
// Date.parse reads "1" as the year 2001, so the text must start with a date
|
|
849
|
+
const since = values.since === undefined ? undefined : /^\d{4}-\d{2}-\d{2}/.test(values.since) ? Date.parse(values.since) : NaN;
|
|
850
|
+
if (since !== undefined && !Number.isFinite(since))
|
|
851
|
+
throw new Error(`--since must be an ISO time; got "${values.since}"`);
|
|
852
|
+
const result = exportReceipts({
|
|
853
|
+
receiptsDir: values.receipts,
|
|
854
|
+
outDir: values.out,
|
|
855
|
+
verify: {
|
|
856
|
+
issuerKeys: values["issuer-key"].map(loadPublicKey),
|
|
857
|
+
principalKeys: (values["principal-key"] ?? []).map(loadPublicKey),
|
|
858
|
+
...(values["approval-key"] ? { approvalKeys: values["approval-key"].map(loadPublicKey) } : {}),
|
|
859
|
+
},
|
|
860
|
+
...(since !== undefined ? { since } : {}),
|
|
861
|
+
allowClear: values["allow-clear"],
|
|
862
|
+
});
|
|
863
|
+
for (const line of formatExportLines(result))
|
|
864
|
+
console.log(line);
|
|
865
|
+
if (result.lines.some((l) => l.outcome === "copied" && l.clear.length))
|
|
866
|
+
console.error(CLEAR_WARNING);
|
|
867
|
+
if (result.problem)
|
|
868
|
+
console.error(`agent-custody export: ${result.problem}`);
|
|
869
|
+
return result.refused > 0 || result.copied === 0 ? 1 : 0;
|
|
870
|
+
}
|
|
800
871
|
case "completeness": {
|
|
801
872
|
const { values } = parseArgs({
|
|
802
873
|
args: rest,
|
|
@@ -864,7 +935,7 @@ async function main(argv) {
|
|
|
864
935
|
case "policy": {
|
|
865
936
|
const [subcommand, ...args] = rest;
|
|
866
937
|
if (subcommand !== "simulate")
|
|
867
|
-
throw new Error("policy needs the simulate subcommand: policy simulate --policy <proposed.cedar> --receipts <dir> --issuer-key <pub>");
|
|
938
|
+
throw new Error("policy needs the simulate subcommand: policy simulate --policy <proposed.cedar|.rego> --receipts <dir> --issuer-key <pub>");
|
|
868
939
|
const { values } = parseArgs({
|
|
869
940
|
args,
|
|
870
941
|
options: {
|
|
@@ -881,7 +952,7 @@ async function main(argv) {
|
|
|
881
952
|
},
|
|
882
953
|
});
|
|
883
954
|
if (!values.policy || !values.receipts || !values["issuer-key"]?.length)
|
|
884
|
-
throw new Error("policy simulate needs --policy <proposed.cedar> --receipts <dir> --issuer-key <pub>");
|
|
955
|
+
throw new Error("policy simulate needs --policy <proposed.cedar|.rego> --receipts <dir> --issuer-key <pub>");
|
|
885
956
|
const policy = readFileSync(values.policy, "utf8");
|
|
886
957
|
const keys = {
|
|
887
958
|
issuerKeys: values["issuer-key"].map(loadPublicKey),
|
|
@@ -945,7 +1016,7 @@ async function main(argv) {
|
|
|
945
1016
|
}
|
|
946
1017
|
}
|
|
947
1018
|
}
|
|
948
|
-
const report = simulatePolicy(policy, verified(), { unreplayable, ...(captureKey ? { captureKey } : {}), disclosures });
|
|
1019
|
+
const report = simulatePolicy(policy, verified(), { unreplayable, ...(captureKey ? { captureKey } : {}), disclosures, language: isRegoFile(values.policy) ? "rego" : "cedar" });
|
|
949
1020
|
const json = JSON.stringify(report, null, 2);
|
|
950
1021
|
if (values.out) {
|
|
951
1022
|
// Reports name calls and decisions: keep them owner-only, including when replacing an existing file.
|