@agent-custody/receipts 0.15.0 → 0.16.1

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 CHANGED
@@ -1,11 +1,15 @@
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
- Three producers, one receipt format, one verifier.
7
+ Five producers, one receipt format, one verifier.
6
8
 
7
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.
8
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)).
9
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.
10
14
 
11
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.
@@ -13,6 +17,9 @@ Anyone holding the public keys can verify a receipt offline. The agent is not tr
13
17
  - [Reference](https://docs.agent-custody.dev/reference/): every function, endpoint, MCP tool, and command with its request and response
14
18
  - [Tutorials](docs/tutorials.md): runnable examples, one per aspect of the code, all executed by the test suite
15
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
16
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
17
24
  - [Financial operations](docs/financial-operations.md): durable operation ids, provider idempotency keys, atomic daily budget reservations, and reconciliation receipts for uncertain outcomes
18
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
@@ -101,18 +108,18 @@ flowchart LR
101
108
 
102
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.
103
110
 
104
- ## Three producers, one receipt
111
+ ## Five producers, one receipt
105
112
 
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 |
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 |
114
121
 
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)).
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)).
116
123
 
117
124
  ### Supported hosts and frameworks
118
125
 
@@ -278,6 +285,9 @@ src/gateway.ts the MCP proxy: a host (key, policy, upstreams, log) and a ses
278
285
  src/operations.ts SQLite operation claims and daily budget reservations, retained across retries and process crashes
279
286
  src/gateway-http.ts the gateway over Streamable HTTP: one process, a session per connection, each under the grant it presents
280
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
281
291
  src/sdk/index.ts the interceptor: policy decision, record, wrap(tool fn)
282
292
  src/sdk/claude.ts Claude Code command hook and Claude Agent SDK in-process hooks
283
293
  src/sdk/openai-agents.ts, vercel-ai.ts, langchain.ts framework adapters, tested against the real packages
@@ -293,23 +303,27 @@ src/verify.ts offline verification, the human-readable report, and the audi
293
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
294
304
  src/deny-report.ts `report`: verifies the receipts of an SDK config and lists the calls the policy would have denied
295
305
  templates/ the starter Cedar policy that `init claude-code` copies (shipped in the package)
296
- src/cli.ts keygen, grant, gateway, door, init, report, hook, serve, log, prune, verify, reveal, audit, policy simulate
306
+ src/cli.ts keygen, grant, gateway, door, egress, egress draft-policy, acs, init, report, hook, serve, log, prune, verify, reveal, audit, policy simulate
297
307
  src/retention.ts pruning the log: leaves become their hashes, bundles are removed, proofs survive
298
308
  src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
299
309
  tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
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
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
301
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
302
312
  test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
303
- adapter tests against the real packages, and a test that runs every policy in docs/policies.md
313
+ adapter tests against the real packages, and tests that run every policy in docs/policies.md and site/guide/egress-policies.md
304
314
  docs/ tutorials, usage (gateway), codex-recovery (live demo), approvals, sdk, policies, verification
305
315
  ```
306
316
 
307
317
  ## Plan
308
318
 
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).
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).
310
320
 
311
321
  **Done**
312
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).
313
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).
314
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).
315
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.
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/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, loadDoorConfig, loadSdkConfig } from "./config.js";
8
+ import { loadAcsGuardianConfig, loadConfig, loadDoorConfig, loadEgressConfig, 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";
@@ -20,6 +20,9 @@ import { checkCompleteness, formatCompleteness, stripeSource } from "./completen
20
20
  import { evmChain } from "./anchor-evm.js";
21
21
  import { serveHttp } from "./gateway-http.js";
22
22
  import { createDoorHost, serveDoor } from "./door.js";
23
+ import { createEgressHost, serveEgress } from "./egress.js";
24
+ import { draftEgressPolicy } from "./egress-draft.js";
25
+ import { createAcsGuardian } from "./acs.js";
23
26
  import { serveA2a } from "./a2a.js";
24
27
  import { PortalStore, sendFollowUps, servePortal } from "./portal.js";
25
28
  import { exportLog, formatExport } from "./log-export.js";
@@ -54,9 +57,9 @@ function untilStopped() {
54
57
  });
55
58
  return stopped;
56
59
  }
57
- const SERVICES = new Set(["serve", "witness", "signer", "portal", "log", "console", "door"]);
60
+ const SERVICES = new Set(["serve", "witness", "signer", "portal", "log", "console", "door", "egress"]);
58
61
  /** a command that waits for untilStopped(); a stdio gateway runs until its input closes and keeps the default signal behaviour */
59
- const runsUntilStopped = (cmd, args) => !!cmd && (SERVICES.has(cmd) || (cmd === "gateway" && (args.includes("--http") || args.includes("--a2a"))));
62
+ const runsUntilStopped = (cmd, args) => !!cmd && ((SERVICES.has(cmd) && !(cmd === "egress" && args[0] === "draft-policy")) || (cmd === "gateway" && (args.includes("--http") || args.includes("--a2a"))));
60
63
  /** 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. */
61
64
  function tokenFromFile(path) {
62
65
  const v = readFileSync(path, "utf8").trim();
@@ -98,6 +101,17 @@ const USAGE = `agent-custody <command>
98
101
  a reverse proxy in front of your own site or API: every arrival classified (verified by a
99
102
  trusted grant, claimed, or unknown), decided by the Cedar policy for its route, relayed to the
100
103
  origin or refused with 403, and receipted either way; GET /.well-known/agent-custody-door
104
+ egress --config <egress.json> [--port 8791] [--host 127.0.0.1]
105
+ the egress witness: a forward proxy (CONNECT and plain HTTP, no TLS interception) for a
106
+ locked-down agent's calls that do not go to the gateway. Each agent proves itself with its own
107
+ Proxy-Authorization; the Cedar policy decides per host:port; every connection is receipted
108
+ egress draft-policy --receipts <dir> --issuer-key <witness.pub>... [--log-key <pub>]... [--log <log.jsonl>]
109
+ a first egress policy from observe-mode receipts: one permit per verified agent and scheme over the
110
+ host:port destinations the witness relayed for it, each with its count and first and last time. It permits
111
+ whatever the agents did, bad destinations included: review it. Receipts that do not verify are skipped
112
+ acs --config <acs.json> an OWASP Agent Control Standard Guardian, one document at a time: reads a JSON-RPC
113
+ steps/toolCallRequest or steps/toolCallResult (or a batch) on stdin, answers allow or
114
+ deny by the Cedar policy on stdout, and writes a signed receipt for each decision
101
115
  init claude-code [--dir <dir>] [--user] [--enforce] [--log-url <url> [--log-id <id>] [--log-token-env NAME] [--log-key <pub>]]
102
116
  one command for your own Claude Code sessions: an agent key, sdk.json in observe mode, a starter deny
103
117
  policy, and the three hooks in .claude/settings.local.json (--user: ~/.claude/settings.json). Safe to run twice
@@ -364,6 +378,56 @@ async function main(argv) {
364
378
  await host.close();
365
379
  return 0;
366
380
  }
381
+ case "egress": {
382
+ if (rest[0] === "draft-policy") {
383
+ const { values } = parseArgs({ args: rest.slice(1), options: { receipts: { type: "string" }, "issuer-key": { type: "string", multiple: true }, "log-key": { type: "string", multiple: true }, log: { type: "string" } } });
384
+ if (!values.receipts || !values["issuer-key"]?.length)
385
+ throw new Error("egress draft-policy needs --receipts <dir> --issuer-key <witness.pub>");
386
+ const draft = draftEgressPolicy(values.receipts, { issuerKeys: values["issuer-key"].map(loadPublicKey), logKeys: (values["log-key"] ?? []).map(loadPublicKey), ...(values.log ? { logFile: values.log } : {}) });
387
+ for (const s of draft.skipped)
388
+ if (s.kind === "unverified")
389
+ console.error(`skipped ${s.file}: does not verify: ${s.reason}`);
390
+ process.stdout.write(draft.policy);
391
+ if (!draft.agents.length) {
392
+ console.error(`egress draft-policy: no relayed connection from a verified agent among ${draft.read} receipt(s) in ${values.receipts}`);
393
+ return 1;
394
+ }
395
+ return 0;
396
+ }
397
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, port: { type: "string", default: "8791" }, host: { type: "string", default: "127.0.0.1" } } });
398
+ if (!values.config)
399
+ throw new Error("egress needs --config");
400
+ const cfg = loadEgressConfig(values.config);
401
+ const host = await createEgressHost(cfg, { autoFlush: true });
402
+ const running = await serveEgress(host, { port: Number(values.port), host: values.host });
403
+ console.error(`agent-custody egress: ${running.url} keyid=${host.keyid}; ${cfg.agents.length} agent(s), mode ${cfg.mode ?? "enforce"}; GET /.well-known/agent-custody-egress`);
404
+ await untilStopped();
405
+ // the relayed connections first, so that each is receipted as witness-stopped before the listener goes
406
+ await host.close();
407
+ await running.close();
408
+ return 0;
409
+ }
410
+ case "acs": {
411
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" } } });
412
+ if (!values.config)
413
+ throw new Error("acs needs --config");
414
+ const guardian = createAcsGuardian(loadAcsGuardianConfig(values.config));
415
+ const chunks = [];
416
+ for await (const c of process.stdin)
417
+ chunks.push(c);
418
+ let message;
419
+ try {
420
+ message = JSON.parse(Buffer.concat(chunks).toString("utf8"));
421
+ }
422
+ catch (e) {
423
+ console.log(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: `parse error: ${e instanceof Error ? e.message : String(e)}` } }, null, 2));
424
+ return 1;
425
+ }
426
+ const answer = await guardian.handle(message);
427
+ console.log(JSON.stringify(answer, null, 2));
428
+ // a deny is a decision, so 0; an error (no decision, including a receipt that could not be written) is 1
429
+ return (Array.isArray(answer) ? answer : [answer]).some((a) => "error" in a) ? 1 : 0;
430
+ }
367
431
  case "init": {
368
432
  const [target, ...args] = rest;
369
433
  if (target !== "claude-code")