@agent-custody/receipts 0.14.0 → 0.16.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 +48 -21
- package/dist/acs.d.ts +47 -0
- package/dist/acs.js +235 -0
- package/dist/addresses.d.ts +6 -0
- package/dist/addresses.js +90 -0
- package/dist/check.d.ts +10 -0
- package/dist/check.js +179 -3
- package/dist/cli.js +147 -12
- package/dist/config.d.ts +198 -1
- package/dist/config.js +154 -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/egress-draft.d.ts +43 -0
- package/dist/egress-draft.js +153 -0
- package/dist/egress.d.ts +116 -0
- package/dist/egress.js +585 -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 +15 -0
- package/dist/index.js +10 -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 +63 -43
- 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 +116 -0
- package/dist/portal.js +147 -41
- package/dist/pr-summary.d.ts +25 -0
- package/dist/pr-summary.js +87 -0
- package/dist/receipt.d.ts +8 -2
- 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 +35 -4
- package/docs/acs.md +107 -0
- package/docs/configuration.md +3 -3
- package/docs/door-signals.md +66 -0
- package/docs/door.md +168 -0
- package/docs/egress.md +177 -0
- package/docs/github-action.md +164 -0
- package/docs/policies.md +112 -1
- package/docs/sdk.md +25 -9
- package/docs/threat-model.md +1 -1
- package/docs/tutorials.md +7 -0
- package/docs/usage.md +2 -2
- package/docs/verification.md +16 -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 +1951 -1005
package/README.md
CHANGED
|
@@ -1,16 +1,26 @@
|
|
|
1
1
|
# agent-custody
|
|
2
2
|
|
|
3
|
+
**Proof of what your AI agents did.** Give your agents real power, without losing control of them.
|
|
4
|
+
|
|
3
5
|
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
6
|
|
|
5
|
-
|
|
7
|
+
Five producers, one receipt format, one verifier.
|
|
6
8
|
|
|
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.
|
|
9
|
+
- **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.
|
|
10
|
+
- **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)).
|
|
11
|
+
- **The egress witness** covers the calls that go around the gateway. Under egress lockdown, a locked-down agent's network reaches only the gateway and the witness. The witness is a forward proxy: it identifies the agent by the proxy credential it checked, lets a Cedar or Rego policy decide per destination, relays or refuses the connection, and receipts it either way (issuer kind `egress`). It records the destination, the times, and the byte counts. It never records a payload, because there is no TLS interception. It sees nothing when lockdown is off, and it relays no protocol other than HTTP. A receipt is an observed bypass, not a record of what was done.
|
|
12
|
+
- **The ACS Guardian**, a spike, answers an agent that asks before it acts over the OWASP Agent Control Standard: it decides `steps/toolCallRequest` and `steps/toolCallResult` by a Cedar policy and receipts each decision (issuer kind `guardian`). It carries out nothing, and the agent chooses to ask and to obey, so a receipt proves the decision, not that the call ran or did not ([the ACS Guardian](docs/acs.md)).
|
|
8
13
|
- **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
14
|
|
|
10
15
|
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
16
|
|
|
12
17
|
- [Reference](https://docs.agent-custody.dev/reference/): every function, endpoint, MCP tool, and command with its request and response
|
|
13
18
|
- [Tutorials](docs/tutorials.md): runnable examples, one per aspect of the code, all executed by the test suite
|
|
19
|
+
- [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
|
|
20
|
+
- [The egress witness](docs/egress.md): a receipted forward proxy for calls that go around the gateway; lockdown, how the witness knows the agent, the Cedar request (or Rego input) per destination, the receipt, and what it cannot see: payloads, traffic when lockdown is off, and non-HTTP protocols
|
|
21
|
+
- [Writing egress policies](../../site/guide/egress-policies.md): per-agent allow lists, wildcard hosts and the `*.example.com` trap, ports, IP literals, why a provider that needs a credential stays in the gateway, `forbid`, and rolling out from observe mode with `egress draft-policy`; every example is tested
|
|
22
|
+
- [The ACS Guardian](docs/acs.md): agent-custody as an OWASP Agent Control Standard Guardian for `steps/toolCallRequest` and `steps/toolCallResult`; each decision a receipt a third party can check, the ACS sections it relies on, and what it does not implement
|
|
23
|
+
- [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
24
|
- [Financial operations](docs/financial-operations.md): durable operation ids, provider idempotency keys, atomic daily budget reservations, and reconciliation receipts for uncertain outcomes
|
|
15
25
|
- [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
26
|
- [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 +28,11 @@ Anyone holding the public keys can verify a receipt offline. The agent is not tr
|
|
|
18
28
|
- [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
29
|
- [Human approvals](docs/approvals.md): short-lived signatures over the exact action, two-person thresholds, single-use enforcement, and offline verification
|
|
20
30
|
- [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`
|
|
31
|
+
- [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
32
|
- [Verifying a receipt](docs/verification.md): what each check means and what a verified receipt does and does not prove
|
|
23
33
|
- [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
34
|
- [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
|
|
35
|
+
- [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
36
|
- [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
37
|
- [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
38
|
- [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 +67,7 @@ const bundle = JSON.parse(readFileSync("receipts/<id>.json", "utf8"));
|
|
|
56
67
|
verifyBundle(bundle, { issuerKeys: [loadPublicKey("keys/app.pub")], logFile: "log.jsonl" }).ok; // true
|
|
57
68
|
```
|
|
58
69
|
|
|
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: `
|
|
70
|
+
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
71
|
|
|
61
72
|
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
73
|
|
|
@@ -97,18 +108,18 @@ flowchart LR
|
|
|
97
108
|
|
|
98
109
|
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
110
|
|
|
100
|
-
##
|
|
111
|
+
## Five producers, one receipt
|
|
101
112
|
|
|
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 |
|
|
113
|
+
| | gateway | door | egress witness | ACS Guardian | SDK |
|
|
114
|
+
| --- | --- | --- | --- | --- | --- |
|
|
115
|
+
| where it runs | separate process between agent and tools | separate process between the world and your own site or API | forward proxy in a locked-down agent's network path | separate process the agent asks, one JSON-RPC document at a time | inside the agent's process |
|
|
116
|
+
| what it sees | MCP tool calls | every HTTP arrival, by route | each connection that does not go to the gateway: destination, times, byte counts, never the payload | the tool-call requests and results the agent chooses to send | whatever the framework's hooks expose |
|
|
117
|
+
| enforcement | yes, denied calls never reach upstream | yes, refused arrivals never reach the origin | yes, refused connections are never opened; only under lockdown, since an agent can ignore the proxy | no: it decides, and the agent honours the answer or not | only where a hook can block |
|
|
118
|
+
| provenance of its fields | `attested` and `observed` | `observed`; `attested` only when the arrival presented a grant, else `claimed` | `observed`; the agent is `observed` only through a proxy credential the witness checked, else `claimed` | the decision and the policy `observed`; the agent, the tool, and the arguments `claimed` | `claimed`, all of them |
|
|
119
|
+
| 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 connected to this destination around the gateway; not what it sent | the Guardian made this decision on this request under this policy; not that the call ran | the agent's process reported this and it has not changed since |
|
|
120
|
+
| install | one line in the host's MCP config | a reverse proxy in front of the origin | a forward proxy plus egress lockdown (`deploy/gateway/lockdown`) | `agent-custody acs --config acs.json`, or `createAcsGuardian` in code | a hook entry or a wrapped function |
|
|
110
121
|
|
|
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.
|
|
122
|
+
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)). The egress witness receipts the connections that go around the gateway ([the egress witness](docs/egress.md)). The ACS Guardian receipts the decisions it gives an agent that asks ([the ACS Guardian](docs/acs.md)).
|
|
112
123
|
|
|
113
124
|
### Supported hosts and frameworks
|
|
114
125
|
|
|
@@ -246,7 +257,8 @@ If a vendor tells you their receipts prove more than the first five rows, ask th
|
|
|
246
257
|
```
|
|
247
258
|
src/config.ts gateway and SDK config schemas, path resolution
|
|
248
259
|
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;
|
|
260
|
+
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`
|
|
261
|
+
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
262
|
src/log-check.ts the outside monitor: verifies the head, checkpoints, witness, and anchor of a running log
|
|
251
263
|
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
264
|
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 +267,27 @@ src/witness.ts the witness: countersigns the log's checkpoints from another
|
|
|
255
267
|
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
268
|
src/anchor-evm.ts the anchor's transactions on Ethereum or another EVM chain, through the optional dependency viem
|
|
257
269
|
src/completeness.ts completeness from the provider's side: the provider's own list, matched against verified receipts
|
|
270
|
+
src/pr-summary.ts `verify --markdown`: a directory of bundles verified into one Markdown table, for the GitHub Action
|
|
271
|
+
src/export.ts `export`: verified receipt bundles that keep their values private, copied byte for byte into a directory for a pull request
|
|
258
272
|
src/signer.ts the signer: the log's key in its own process, the key document verifiers fetch
|
|
259
273
|
src/checkpoints.ts signed heads published on a schedule, to files and to Postgres
|
|
260
274
|
src/log-store.ts the log server's backends: the file, and Postgres with tenants, hashed tokens, one writer per tenant, rate limits
|
|
261
275
|
src/log-sink.ts where leaves go: the local file, or a remote log over HTTP; plus the reference log server
|
|
262
276
|
src/policy.ts Cedar evaluation wrapper, fail-closed
|
|
263
|
-
src/
|
|
277
|
+
src/policy-rego.ts Rego: compiled with opa build, evaluated in-process with the OPA WebAssembly SDK, fail-closed
|
|
278
|
+
src/opa-server.ts an OPA server's Data API as the policy, with bundle revisions as the digest
|
|
279
|
+
src/simulate.ts replay recorded policy decisions against a proposed Cedar or Rego policy, grouped changes and run digest
|
|
264
280
|
src/delegation.ts signed delegation grants
|
|
265
281
|
src/approval.ts exact-action human approvals, distinct trusted signatures, persistent single-use consumption
|
|
266
282
|
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
|
|
283
|
+
src/issue.ts sign, log, and write a receipt, or commit an authorization first; shared by every producer
|
|
268
284
|
src/gateway.ts the MCP proxy: a host (key, policy, upstreams, log) and a session per grant; scope check, facts, policy, forward, receipt
|
|
269
285
|
src/operations.ts SQLite operation claims and daily budget reservations, retained across retries and process crashes
|
|
270
286
|
src/gateway-http.ts the gateway over Streamable HTTP: one process, a session per connection, each under the grant it presents
|
|
287
|
+
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
|
|
288
|
+
src/egress.ts the egress witness: a forward proxy (CONNECT and plain HTTP, no TLS interception) for calls around the gateway; agent by proxy credential, decided per destination, receipted as issuer kind egress
|
|
289
|
+
src/egress-draft.ts `egress draft-policy`: a first egress policy from verified observe-mode receipts, one permit per agent and scheme over the destinations it used, for review
|
|
290
|
+
src/acs.ts an OWASP ACS Guardian: steps/toolCallRequest and steps/toolCallResult over JSON-RPC, decided by Cedar, each decision receipted as issuer kind guardian
|
|
271
291
|
src/sdk/index.ts the interceptor: policy decision, record, wrap(tool fn)
|
|
272
292
|
src/sdk/claude.ts Claude Code command hook and Claude Agent SDK in-process hooks
|
|
273
293
|
src/sdk/openai-agents.ts, vercel-ai.ts, langchain.ts framework adapters, tested against the real packages
|
|
@@ -283,25 +303,32 @@ src/verify.ts offline verification, the human-readable report, and the audi
|
|
|
283
303
|
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
304
|
src/deny-report.ts `report`: verifies the receipts of an SDK config and lists the calls the policy would have denied
|
|
285
305
|
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
|
|
306
|
+
src/cli.ts keygen, grant, gateway, door, egress, egress draft-policy, acs, init, report, hook, serve, log, prune, verify, reveal, audit, policy simulate
|
|
287
307
|
src/retention.ts pruning the log: leaves become their hashes, bundles are removed, proofs survive
|
|
288
308
|
src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
|
|
289
309
|
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
|
|
310
|
+
scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, fixture builders for gateway, SDK, door (with a stand-in origin), and the egress witness (with a stand-in destination), 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
311
|
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
312
|
test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
|
|
293
|
-
adapter tests against the real packages, and
|
|
313
|
+
adapter tests against the real packages, and tests that run every policy in docs/policies.md and site/guide/egress-policies.md
|
|
294
314
|
docs/ tutorials, usage (gateway), codex-recovery (live demo), approvals, sdk, policies, verification
|
|
295
315
|
```
|
|
296
316
|
|
|
297
317
|
## Plan
|
|
298
318
|
|
|
299
|
-
The design is
|
|
319
|
+
The design is several 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. The egress witness receipts what goes around the gateway. The ACS Guardian, a spike, receipts the decisions it gives an agent that asks before it acts. All five 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
320
|
|
|
301
321
|
**Done**
|
|
302
322
|
|
|
323
|
+
- The egress witness decides by Rego as well as Cedar: a `policyFile` ending in `.rego` is compiled with `opa build` as the gateway compiles one, the input is the Cedar request with plain strings, and a file that does not compile is not loaded. An OPA server is not supported for egress yet ([the egress witness](docs/egress.md#the-same-policy-in-rego), tutorial 44).
|
|
324
|
+
- Drafting an egress policy: `agent-custody egress draft-policy --receipts <dir> --issuer-key <witness.pub>` verifies each egress receipt, keeps the connections the witness relayed for a verified agent, and prints one `permit` per agent and scheme over the `host:port` destinations it used, sorted, with a count and the first and last time seen for each. The output starts with a warning that it permits whatever the agents did, bad destinations included. [Writing egress policies](../../site/guide/egress-policies.md) is the guide, and its examples are tested; tutorial [42-egress-draft.ts](examples/42-egress-draft.ts).
|
|
325
|
+
- An OWASP Agent Control Standard Guardian, as a spike: `agent-custody acs` answers `steps/toolCallRequest` and `steps/toolCallResult` with the Cedar policy's allow or deny, and every decision is a receipt with the new issuer kind `guardian`, signed with the Guardian's key and logged, which ACS's HMAC baseline cannot attribute (ACS §8.6). It publishes the ACS chain head, and its receipts in a log someone else runs answer two of the three directions in ACS issue #18 (a signed checkpoint of `chain_hash`, and signed heads in an external append-only log; Guardians exchanging heads is not done). Handshake, ACS signatures, the other hooks, modify/ask/defer, and provenance are not implemented; [the list](docs/acs.md#what-it-does-not-implement). Example 43.
|
|
326
|
+
- The egress witness: `agent-custody egress` is an HTTP forward proxy for a locked-down agent's connections that do not go to the gateway. It relays CONNECT and plain HTTP with no TLS interception. It identifies the agent only by a per-agent proxy credential it checks, lets the Cedar policy decide per `host:port`, commits each connection to the log before any byte moves, never dials an internal address for a host name, and receipts each connection, relayed or refused, as issuer kind `egress`, with the destination observed and the byte counts each way. `deploy/gateway/lockdown` gives the agent default-deny egress (a Kubernetes NetworkPolicy, an internal docker network). All three verifiers know the new kind, and ten conformance vectors pin it. It cannot see payloads, traffic when lockdown is off, or non-HTTP protocols ([the egress witness](docs/egress.md), [credential custody and lockdown](../../site/guide/credential-custody.md), tutorial 41).
|
|
303
327
|
- 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
328
|
- 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).
|
|
329
|
+
- `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.
|
|
330
|
+
- 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).
|
|
331
|
+
- 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
332
|
- 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
333
|
- 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
334
|
- 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/acs.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { AcsGuardianConfig } from "./config.ts";
|
|
2
|
+
import { type LogSink } from "./log-sink.ts";
|
|
3
|
+
export declare const ACS_GUARDIAN_VERSION = "0.1.0";
|
|
4
|
+
/** the version the Guardian answers with; a request of any 0.x.y is accepted, as ACS §3 asks for the same major */
|
|
5
|
+
export declare const ACS_VERSION = "0.1.0";
|
|
6
|
+
/** the key in `policy_data` under which an answer carries its receipt */
|
|
7
|
+
export declare const ACS_RECEIPT_KEY = "agent-custody";
|
|
8
|
+
/** the fact every guardian receipt carries: which envelope arrived, and where it sits in the session's ACS chain */
|
|
9
|
+
export declare const ACS_STEP_FACT = "acsStep";
|
|
10
|
+
export declare const ACS_METHODS: readonly ["steps/toolCallRequest", "steps/toolCallResult"];
|
|
11
|
+
export type AcsMethod = (typeof ACS_METHODS)[number];
|
|
12
|
+
/** JSON-RPC 2.0 codes, and the ACS codes of §17.1 this Guardian raises */
|
|
13
|
+
export declare const ACS_ERROR: {
|
|
14
|
+
readonly parse: -32700;
|
|
15
|
+
readonly invalidRequest: -32600;
|
|
16
|
+
readonly methodNotFound: -32601;
|
|
17
|
+
readonly invalidParams: -32602;
|
|
18
|
+
readonly internal: -32603;
|
|
19
|
+
readonly sessionRefused: -32000;
|
|
20
|
+
readonly unsupportedVersion: -32001;
|
|
21
|
+
readonly replay: -32005;
|
|
22
|
+
};
|
|
23
|
+
export type AcsResponse = {
|
|
24
|
+
jsonrpc: "2.0";
|
|
25
|
+
id: string | number;
|
|
26
|
+
result: Record<string, unknown>;
|
|
27
|
+
} | {
|
|
28
|
+
jsonrpc: "2.0";
|
|
29
|
+
id: string | number | null;
|
|
30
|
+
error: {
|
|
31
|
+
code: number;
|
|
32
|
+
message: string;
|
|
33
|
+
data?: Record<string, unknown>;
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
export interface AcsGuardian {
|
|
37
|
+
keyid: string;
|
|
38
|
+
/** sha256 of the policy in force: the one the next call is evaluated under */
|
|
39
|
+
readonly policyDigest: string;
|
|
40
|
+
/** One JSON-RPC message, or a batch evaluated in order. Never throws: a failure is a JSON-RPC error. */
|
|
41
|
+
handle(message: unknown): Promise<AcsResponse | AcsResponse[]>;
|
|
42
|
+
}
|
|
43
|
+
/** ACS §8.2: sha256 over the JCS form of the entry without `entry_hash` and `previous_hash`, then the previous hash's 32 bytes. */
|
|
44
|
+
export declare function acsEntryHash(entry: Record<string, unknown>, previousHash: string | null): string;
|
|
45
|
+
export declare function createAcsGuardian(cfg: AcsGuardianConfig, options?: {
|
|
46
|
+
log?: LogSink;
|
|
47
|
+
}): AcsGuardian;
|
package/dist/acs.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
// An OWASP Agent Control Standard (ACS) v0.1 Guardian. The agent's ACS instrumentation sends `steps/toolCallRequest`
|
|
2
|
+
// and `steps/toolCallResult` as JSON-RPC 2.0; the Cedar policy decides allow or deny; every decision is a signed,
|
|
3
|
+
// logged receipt with issuer kind `guardian`, returned in the answer. The receipt is what ACS's HMAC baseline cannot
|
|
4
|
+
// give (ACS §8.6): a decision a third party can attribute to this Guardian's key alone. It is not enforcement. The agent
|
|
5
|
+
// chose to ask, reports the call itself, and is trusted to honor the answer; the gateway is the point it cannot skip.
|
|
6
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
7
|
+
import { closeSync, fstatSync, openSync, readFileSync } from "node:fs";
|
|
8
|
+
import { canonicalize, digestOf, loadPrivateKey, sha256Hex } from "./crypto.js";
|
|
9
|
+
import { createIssuer } from "./issue.js";
|
|
10
|
+
import { openLog } from "./log-sink.js";
|
|
11
|
+
import { evaluate, policyDigest, policyParseErrors, policyReasons, reasonOfRule } from "./policy.js";
|
|
12
|
+
export const ACS_GUARDIAN_VERSION = "0.1.0";
|
|
13
|
+
/** the version the Guardian answers with; a request of any 0.x.y is accepted, as ACS §3 asks for the same major */
|
|
14
|
+
export const ACS_VERSION = "0.1.0";
|
|
15
|
+
/** the key in `policy_data` under which an answer carries its receipt */
|
|
16
|
+
export const ACS_RECEIPT_KEY = "agent-custody";
|
|
17
|
+
/** the fact every guardian receipt carries: which envelope arrived, and where it sits in the session's ACS chain */
|
|
18
|
+
export const ACS_STEP_FACT = "acsStep";
|
|
19
|
+
export const ACS_METHODS = ["steps/toolCallRequest", "steps/toolCallResult"];
|
|
20
|
+
/** JSON-RPC 2.0 codes, and the ACS codes of §17.1 this Guardian raises */
|
|
21
|
+
export const ACS_ERROR = { parse: -32700, invalidRequest: -32600, methodNotFound: -32601, invalidParams: -32602, internal: -32603, sessionRefused: -32000, unsupportedVersion: -32001, replay: -32005 };
|
|
22
|
+
/** ACS §8.2: sha256 over the JCS form of the entry without `entry_hash` and `previous_hash`, then the previous hash's 32 bytes. */
|
|
23
|
+
export function acsEntryHash(entry, previousHash) {
|
|
24
|
+
const { entry_hash: _h, previous_hash: _p, ...content } = entry;
|
|
25
|
+
return createHash("sha256").update(canonicalize(content)).update(previousHash ? Buffer.from(previousHash, "hex") : Buffer.alloc(0)).digest("hex");
|
|
26
|
+
}
|
|
27
|
+
const isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
28
|
+
const EXIT = ["success", "failure", "timeout", "blocked"];
|
|
29
|
+
export function createAcsGuardian(cfg, options = {}) {
|
|
30
|
+
const key = loadPrivateKey(cfg.identity.keyFile);
|
|
31
|
+
const issuer = createIssuer(key, cfg.receiptsDir, options.log ?? openLog(cfg, key));
|
|
32
|
+
// The policy, re-read when the file changes, as the egress witness does: a changed file that does not parse is refused
|
|
33
|
+
// and the policy in force stays. The bytes and the metadata come from one open file.
|
|
34
|
+
const readPolicy = () => {
|
|
35
|
+
const fd = openSync(cfg.policyFile, "r");
|
|
36
|
+
try {
|
|
37
|
+
const st = fstatSync(fd);
|
|
38
|
+
return { text: readFileSync(fd, "utf8"), key: `${st.ino}:${st.mtimeMs}:${st.ctimeMs}:${st.size}` };
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
closeSync(fd);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
const loaded = (text, key) => ({ text, key, digest: policyDigest(text), named: policyReasons(text) });
|
|
45
|
+
const first = readPolicy();
|
|
46
|
+
const parseErrors = policyParseErrors(first.text);
|
|
47
|
+
if (parseErrors.length)
|
|
48
|
+
throw new Error(`${cfg.policyFile} does not parse: ${parseErrors.join("; ")}`);
|
|
49
|
+
let policyNow = loaded(first.text, first.key);
|
|
50
|
+
const currentPolicy = () => {
|
|
51
|
+
try {
|
|
52
|
+
const next = readPolicy();
|
|
53
|
+
if (next.key !== policyNow.key) {
|
|
54
|
+
const problems = policyParseErrors(next.text);
|
|
55
|
+
if (problems.length)
|
|
56
|
+
console.error(`agent-custody acs: POLICY NOT RELOADED: ${cfg.policyFile} ${problems.join("; ")}; policy ${policyNow.digest} stays in force`);
|
|
57
|
+
else
|
|
58
|
+
policyNow = loaded(next.text, next.key);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
catch (e) {
|
|
62
|
+
console.error(`agent-custody acs: cannot read ${cfg.policyFile}: ${e instanceof Error ? e.message : String(e)}; policy ${policyNow.digest} stays in force`);
|
|
63
|
+
}
|
|
64
|
+
return policyNow;
|
|
65
|
+
};
|
|
66
|
+
const sessions = new Map();
|
|
67
|
+
// One call at a time per session: the replay check, the chain head, and the receipt form one step, or two calls with
|
|
68
|
+
// one request_id would both pass the check and fork the chain.
|
|
69
|
+
const locks = new Map();
|
|
70
|
+
const lock = async (key) => {
|
|
71
|
+
const prev = locks.get(key) ?? Promise.resolve();
|
|
72
|
+
let release;
|
|
73
|
+
const tail = prev.then(() => new Promise((r) => (release = r)));
|
|
74
|
+
locks.set(key, tail);
|
|
75
|
+
await prev;
|
|
76
|
+
return () => {
|
|
77
|
+
release();
|
|
78
|
+
if (locks.get(key) === tail)
|
|
79
|
+
locks.delete(key);
|
|
80
|
+
};
|
|
81
|
+
};
|
|
82
|
+
const fail = (id, code, message, data) => ({ jsonrpc: "2.0", id, error: { code, message, ...(data ? { data } : {}) } });
|
|
83
|
+
async function one(msg) {
|
|
84
|
+
const rawId = isObject(msg) ? msg.id : undefined;
|
|
85
|
+
const id = typeof rawId === "string" || typeof rawId === "number" ? rawId : null;
|
|
86
|
+
if (!isObject(msg) || msg.jsonrpc !== "2.0" || typeof msg.method !== "string" || id === null)
|
|
87
|
+
return fail(id, ACS_ERROR.invalidRequest, "not an ACS request: JSON-RPC 2.0 with a method and an id");
|
|
88
|
+
const p = msg.params;
|
|
89
|
+
// ACS §13: a ping is always allowed and never an ACS error, so liveness survives anything else being wrong
|
|
90
|
+
if (msg.method === "system/ping") {
|
|
91
|
+
const echo = isObject(p) && isObject(p.payload) && typeof p.payload.echo === "string" ? p.payload.echo : undefined;
|
|
92
|
+
return { jsonrpc: "2.0", id, result: { type: "final", acs_version: ACS_VERSION, request_id: isObject(p) && typeof p.request_id === "string" ? p.request_id : "", decision: "allow", payload: { status: "ok", ...(echo === undefined ? {} : { echo }), server_timestamp: new Date().toISOString() } } };
|
|
93
|
+
}
|
|
94
|
+
if (!ACS_METHODS.includes(msg.method))
|
|
95
|
+
return fail(id, ACS_ERROR.methodNotFound, `this Guardian evaluates ${ACS_METHODS.join(" and ")} only`, { method: msg.method });
|
|
96
|
+
const method = msg.method;
|
|
97
|
+
if (!isObject(p) || typeof p.acs_version !== "string")
|
|
98
|
+
return fail(id, ACS_ERROR.invalidParams, "params need acs_version");
|
|
99
|
+
if (!/^0\.\d+\.\d+$/.test(p.acs_version))
|
|
100
|
+
return fail(id, ACS_ERROR.unsupportedVersion, `acs_version ${p.acs_version} is not supported`, { supported_versions: [ACS_VERSION] });
|
|
101
|
+
const meta = p.metadata;
|
|
102
|
+
const payload = p.payload;
|
|
103
|
+
if (typeof p.request_id !== "string" || !p.request_id || typeof p.timestamp !== "string" || !isObject(meta) || typeof meta.agent_id !== "string" || !meta.agent_id || typeof meta.session_id !== "string" || !meta.session_id || !isObject(payload)) {
|
|
104
|
+
return fail(id, ACS_ERROR.invalidParams, "params need request_id, timestamp, metadata.agent_id, metadata.session_id, and payload");
|
|
105
|
+
}
|
|
106
|
+
const tool = isObject(payload.tool) && typeof payload.tool.name === "string" && payload.tool.name ? payload.tool.name : null;
|
|
107
|
+
if (!tool)
|
|
108
|
+
return fail(id, ACS_ERROR.invalidParams, "payload.tool.name is required");
|
|
109
|
+
const requestId = p.request_id;
|
|
110
|
+
const agentId = meta.agent_id;
|
|
111
|
+
const sessionId = meta.session_id;
|
|
112
|
+
// What the agent submitted for a decision, as the policy and the receipt see it. Argument and output values are
|
|
113
|
+
// unwrapped from their `{value, provenance}` objects; the provenance is not read.
|
|
114
|
+
let args;
|
|
115
|
+
let ref;
|
|
116
|
+
if (method === "steps/toolCallRequest") {
|
|
117
|
+
const a = payload.arguments;
|
|
118
|
+
if (!isObject(a) || !Object.values(a).every((v) => isObject(v) && "value" in v))
|
|
119
|
+
return fail(id, ACS_ERROR.invalidParams, "payload.arguments must map each name to {value}");
|
|
120
|
+
args = Object.fromEntries(Object.entries(a).map(([k, v]) => [k, v.value]));
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
const outputs = payload.outputs;
|
|
124
|
+
if (typeof payload.exit_status !== "string" || !EXIT.includes(payload.exit_status) || !Array.isArray(outputs) || !outputs.every((o) => isObject(o) && "value" in o)) {
|
|
125
|
+
return fail(id, ACS_ERROR.invalidParams, `payload needs exit_status (${EXIT.join(", ")}) and outputs, each {value}`);
|
|
126
|
+
}
|
|
127
|
+
ref = typeof payload.request_id_ref === "string" ? payload.request_id_ref : undefined;
|
|
128
|
+
args = { exit_status: payload.exit_status, outputs: outputs.map((o) => o.value), ...(typeof payload.duration_ms === "number" ? { duration_ms: payload.duration_ms } : {}), ...(ref === undefined ? {} : { request_id_ref: ref }) };
|
|
129
|
+
}
|
|
130
|
+
const release = await lock(sessionId);
|
|
131
|
+
try {
|
|
132
|
+
// ACS hooks.md, toolCallResult: a reference the Guardian cannot resolve is recorded, and the policy decides what it means
|
|
133
|
+
const existing = sessions.get(sessionId);
|
|
134
|
+
if (existing && existing.agentId !== agentId)
|
|
135
|
+
return fail(id, ACS_ERROR.sessionRefused, `session ${sessionId} was opened by another agent`, { reason: "agent_mismatch" });
|
|
136
|
+
const session = existing ?? { agentId, head: null, seen: new Set(), requests: new Map() };
|
|
137
|
+
if (session.seen.has(requestId))
|
|
138
|
+
return fail(id, ACS_ERROR.replay, `request_id ${requestId} was already decided in this session`, { reason: "duplicate_request_id" });
|
|
139
|
+
const known = ref === undefined ? undefined : session.requests.get(ref);
|
|
140
|
+
// what a policy needs to tie a result to its request: the request's decision and tool, and whether a result was already let through
|
|
141
|
+
const linked = known ? { decision: known.decision, tool: known.tool, agent: agentId, consumed: known.results > 0 } : {};
|
|
142
|
+
const requestRef = ref === undefined ? undefined : { id: ref, resolved: !!known, ...linked, ...(known ? { receiptId: known.receiptId } : {}) };
|
|
143
|
+
const acs = {
|
|
144
|
+
method,
|
|
145
|
+
...(typeof payload.capability === "string" ? { capability: payload.capability } : {}),
|
|
146
|
+
...(typeof payload.operation === "string" ? { operation: payload.operation } : {}),
|
|
147
|
+
...(requestRef ? { requestRef: { resolved: requestRef.resolved, ...linked } } : {}),
|
|
148
|
+
};
|
|
149
|
+
const started = Date.now();
|
|
150
|
+
const { text: policyText, digest, named } = currentPolicy();
|
|
151
|
+
let policy;
|
|
152
|
+
try {
|
|
153
|
+
policy = evaluate(policyText, { agentId, tool, context: { args, acs } });
|
|
154
|
+
}
|
|
155
|
+
catch (e) {
|
|
156
|
+
policy = { decision: "deny", reasons: [], errors: [e instanceof Error ? e.message : String(e)], policyDigest: digest };
|
|
157
|
+
}
|
|
158
|
+
const reasoning = policy.errors.length ? policy.errors.join("; ") : policy.reasons.length ? policy.reasons.map((r) => reasonOfRule(r, named)).join("; ") : "no permit policy matched";
|
|
159
|
+
const timestamp = new Date().toISOString();
|
|
160
|
+
const requestHash = sha256Hex(canonicalize(p));
|
|
161
|
+
const entry = { entry_id: randomUUID(), step_id: requestId, step_type: method, request_hash: requestHash, timestamp };
|
|
162
|
+
const chainHash = acsEntryHash(entry, session.head);
|
|
163
|
+
const step = { method, request_id: requestId, request_hash: requestHash, entry_id: entry.entry_id, previous_hash: session.head, chain_hash: chainHash, ...(requestRef ? { request_ref: requestRef } : {}) };
|
|
164
|
+
const receiptId = randomUUID();
|
|
165
|
+
const predicate = {
|
|
166
|
+
receiptId,
|
|
167
|
+
timestamp,
|
|
168
|
+
issuer: { kind: "guardian", keyid: issuer.keyid, version: ACS_GUARDIAN_VERSION, framework: `acs ${method}` },
|
|
169
|
+
principal: { id: null, provenance: "claimed" },
|
|
170
|
+
agent: { id: agentId, provenance: "claimed" },
|
|
171
|
+
session: { id: sessionId, toolUseId: requestId, provenance: "claimed" },
|
|
172
|
+
model: { id: null, provenance: "claimed" },
|
|
173
|
+
tool: { name: tool, provenance: "claimed" },
|
|
174
|
+
request: { args, argsDigest: digestOf(args), provenance: "claimed" },
|
|
175
|
+
facts: { [ACS_STEP_FACT]: { tool: "acs.step", args: {}, value: step, resultDigest: digestOf(step), provenance: "observed" } },
|
|
176
|
+
policy: { ...policy, provenance: "observed" },
|
|
177
|
+
execution: policy.decision === "allow"
|
|
178
|
+
? { status: "withheld", reason: "allowed; a Guardian forwards nothing: the agent carries out the step and is trusted to honor the decision", provenance: "observed" }
|
|
179
|
+
: { status: "denied", reason: reasoning, provenance: "observed" },
|
|
180
|
+
};
|
|
181
|
+
let bundle;
|
|
182
|
+
try {
|
|
183
|
+
bundle = await issuer.issue(predicate);
|
|
184
|
+
}
|
|
185
|
+
catch (e) {
|
|
186
|
+
return fail(id, ACS_ERROR.internal, "the receipt could not be written, so no decision is given", { reason: "receipt_not_written", message: e instanceof Error ? e.message : String(e) });
|
|
187
|
+
}
|
|
188
|
+
session.head = chainHash;
|
|
189
|
+
session.seen.add(requestId);
|
|
190
|
+
if (method === "steps/toolCallRequest")
|
|
191
|
+
session.requests.set(requestId, { receiptId, decision: policy.decision, tool, results: 0 });
|
|
192
|
+
else if (known && policy.decision === "allow")
|
|
193
|
+
known.results += 1;
|
|
194
|
+
sessions.set(sessionId, session);
|
|
195
|
+
return {
|
|
196
|
+
jsonrpc: "2.0",
|
|
197
|
+
id,
|
|
198
|
+
result: {
|
|
199
|
+
type: "final",
|
|
200
|
+
acs_version: ACS_VERSION,
|
|
201
|
+
request_id: requestId,
|
|
202
|
+
decision: policy.decision,
|
|
203
|
+
reasoning,
|
|
204
|
+
...(policy.decision === "deny" ? { reason_codes: [policy.errors.length ? "policy_error" : "policy_denied"] } : {}),
|
|
205
|
+
policy_references: policy.reasons.map((r) => {
|
|
206
|
+
const name = named[Number(r.replace(/^policy/, ""))];
|
|
207
|
+
return { policy_id: `cedar:${policy.policyDigest}`, policy_version: policy.policyDigest, rule_id: r, ...(name ? { policy_name: name } : {}) };
|
|
208
|
+
}),
|
|
209
|
+
chain_hash: chainHash,
|
|
210
|
+
policy_data: { [ACS_RECEIPT_KEY]: { receiptId, keyid: issuer.keyid, receipt: bundle } },
|
|
211
|
+
metadata: { evaluator: "deterministic", evaluator_version: `agent-custody guardian ${ACS_GUARDIAN_VERSION}`, evaluation_duration_ms: Date.now() - started },
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
finally {
|
|
216
|
+
release();
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return {
|
|
220
|
+
keyid: issuer.keyid,
|
|
221
|
+
get policyDigest() {
|
|
222
|
+
return currentPolicy().digest;
|
|
223
|
+
},
|
|
224
|
+
async handle(message) {
|
|
225
|
+
if (!Array.isArray(message))
|
|
226
|
+
return one(message);
|
|
227
|
+
if (message.length === 0)
|
|
228
|
+
return fail(null, ACS_ERROR.invalidRequest, "an empty batch");
|
|
229
|
+
const out = [];
|
|
230
|
+
for (const m of message)
|
|
231
|
+
out.push(await one(m));
|
|
232
|
+
return out;
|
|
233
|
+
},
|
|
234
|
+
};
|
|
235
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** True when `ip` is not a public address, or is not an address at all: a caller that cannot read it must not dial it. */
|
|
2
|
+
export declare function internalAddress(ip: string): boolean;
|
|
3
|
+
/** True when `a` and `b` are the same address, written however (::1 and 0:0::1; 10.0.0.1 and ::ffff:10.0.0.1). */
|
|
4
|
+
export declare function sameAddress(a: string, b: string): boolean;
|
|
5
|
+
/** True when `host` is an IP address rather than a name. */
|
|
6
|
+
export declare function isAddressLiteral(host: string): boolean;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Addresses that are not the public internet: loopback, private, shared (CGNAT), link-local (cloud metadata), the IETF
|
|
2
|
+
// protocol block (Oracle's metadata at 192.0.0.192), benchmarking, multicast, and reserved space, in IPv4 and IPv6,
|
|
3
|
+
// IPv4-mapped and NAT64 IPv6 included: an address that embeds an IPv4 address is as internal as that address. Pure, with no Node import, so the browser verifier carries the same list.
|
|
4
|
+
const V4 = [
|
|
5
|
+
["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], ["169.254.0.0", 16], ["172.16.0.0", 12],
|
|
6
|
+
["192.0.0.0", 24], ["192.168.0.0", 16], ["198.18.0.0", 15], ["224.0.0.0", 4], ["240.0.0.0", 4],
|
|
7
|
+
];
|
|
8
|
+
const V6 = [["::", 128], ["::1", 128], ["fc00::", 7], ["fe80::", 10], ["ff00::", 8], ["64:ff9b:1::", 48]];
|
|
9
|
+
function v4(ip) {
|
|
10
|
+
const parts = ip.split(".");
|
|
11
|
+
if (parts.length !== 4)
|
|
12
|
+
return null;
|
|
13
|
+
let n = 0;
|
|
14
|
+
for (const p of parts) {
|
|
15
|
+
// no leading zeros: `010` is octal to getaddrinfo and an error to Python's ipaddress, so it is not an address here either
|
|
16
|
+
if (!/^(0|[1-9]\d{0,2})$/.test(p) || Number(p) > 255)
|
|
17
|
+
return null;
|
|
18
|
+
n = n * 256 + Number(p);
|
|
19
|
+
}
|
|
20
|
+
return n;
|
|
21
|
+
}
|
|
22
|
+
function v6(ip) {
|
|
23
|
+
let s = ip.toLowerCase();
|
|
24
|
+
// an embedded IPv4 tail (::ffff:10.0.0.1) becomes its two hex groups
|
|
25
|
+
if (s.includes(".")) {
|
|
26
|
+
const at = s.lastIndexOf(":");
|
|
27
|
+
const n = at < 0 ? null : v4(s.slice(at + 1));
|
|
28
|
+
if (n === null)
|
|
29
|
+
return null;
|
|
30
|
+
s = `${s.slice(0, at + 1)}${Math.floor(n / 65536).toString(16)}:${(n % 65536).toString(16)}`;
|
|
31
|
+
}
|
|
32
|
+
const halves = s.split("::");
|
|
33
|
+
if (halves.length > 2)
|
|
34
|
+
return null;
|
|
35
|
+
const read = (h) => (h === "" ? [] : h.split(":").map((g) => (/^[0-9a-f]{1,4}$/.test(g) ? parseInt(g, 16) : NaN)));
|
|
36
|
+
const head = read(halves[0]);
|
|
37
|
+
const rest = halves.length === 2 ? read(halves[1]) : [];
|
|
38
|
+
const fill = 8 - head.length - rest.length;
|
|
39
|
+
if (halves.length === 1 ? fill !== 0 : fill < 1)
|
|
40
|
+
return null;
|
|
41
|
+
const groups = [...head, ...Array(halves.length === 2 ? fill : 0).fill(0), ...rest];
|
|
42
|
+
return groups.every((g) => Number.isInteger(g)) ? groups : null;
|
|
43
|
+
}
|
|
44
|
+
function inV6(g, base, bits) {
|
|
45
|
+
for (let i = 0; i < 8 && bits > 0; i++, bits -= 16) {
|
|
46
|
+
const mask = bits >= 16 ? 0xffff : (0xffff << (16 - bits)) & 0xffff;
|
|
47
|
+
if ((g[i] & mask) !== (base[i] & mask))
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
/** True when `ip` is not a public address, or is not an address at all: a caller that cannot read it must not dial it. */
|
|
53
|
+
export function internalAddress(ip) {
|
|
54
|
+
const n = v4(ip);
|
|
55
|
+
if (n !== null)
|
|
56
|
+
return V4.some(([base, bits]) => Math.floor(n / 2 ** (32 - bits)) === Math.floor(v4(base) / 2 ** (32 - bits)));
|
|
57
|
+
const g = v6(ip.replace(/^\[|\]$/g, "").replace(/%.*$/, ""));
|
|
58
|
+
if (!g)
|
|
59
|
+
return true;
|
|
60
|
+
const embedded = embeddedV4(g);
|
|
61
|
+
if (embedded)
|
|
62
|
+
return internalAddress(embedded);
|
|
63
|
+
return V6.some(([base, bits]) => inV6(g, v6(base), bits));
|
|
64
|
+
}
|
|
65
|
+
/** The IPv4 address inside an IPv4-mapped (::ffff:0:0/96) or NAT64 (64:ff9b::/96) address, else null: a DNS64 answer can wrap an internal IPv4 address. */
|
|
66
|
+
function embeddedV4(g) {
|
|
67
|
+
const mapped = g.slice(0, 5).every((x) => x === 0) && g[5] === 0xffff;
|
|
68
|
+
const nat64 = g[0] === 0x64 && g[1] === 0xff9b && g.slice(2, 6).every((x) => x === 0);
|
|
69
|
+
return mapped || nat64 ? `${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}` : null;
|
|
70
|
+
}
|
|
71
|
+
/** The address in a canonical form (IPv4 dotted, or eight IPv6 groups; a mapped IPv4 address as IPv4), or null when it is not one. */
|
|
72
|
+
function canonicalAddress(ip) {
|
|
73
|
+
if (v4(ip) !== null)
|
|
74
|
+
return ip.split(".").map(Number).join(".");
|
|
75
|
+
const g = v6(ip.replace(/^\[|\]$/g, "").replace(/%.*$/, ""));
|
|
76
|
+
if (!g)
|
|
77
|
+
return null;
|
|
78
|
+
if (g.slice(0, 5).every((x) => x === 0) && g[5] === 0xffff)
|
|
79
|
+
return embeddedV4(g);
|
|
80
|
+
return g.map((x) => x.toString(16)).join(":");
|
|
81
|
+
}
|
|
82
|
+
/** True when `a` and `b` are the same address, written however (::1 and 0:0::1; 10.0.0.1 and ::ffff:10.0.0.1). */
|
|
83
|
+
export function sameAddress(a, b) {
|
|
84
|
+
const x = canonicalAddress(a);
|
|
85
|
+
return x !== null && x === canonicalAddress(b);
|
|
86
|
+
}
|
|
87
|
+
/** True when `host` is an IP address rather than a name. */
|
|
88
|
+
export function isAddressLiteral(host) {
|
|
89
|
+
return canonicalAddress(host) !== null;
|
|
90
|
+
}
|
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;
|