@agent-custody/receipts 0.16.6 → 0.16.7

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
@@ -7,7 +7,7 @@ Chain of custody for AI agents: a signed receipt for every tool call, checkable
7
7
  Five producers, one receipt format, one verifier.
8
8
 
9
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)).
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, or a Web Bot Auth signature checked against the signer's key directory, 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. A Node site can run the same loop in its own process: `app.use(door("door.json"))` in Express, or a wrapper around a Next.js route handler ([the door in your Node app](docs/door-middleware.md)). A site in Go, Rails, Django, or Spring asks a door in authz mode from a middleware ([the door in Go, Rails, Django, and Spring](docs/door-languages.md)). A partner detection engine (Cloudflare Bot Management, HUMAN, DataDome, behind an adapter that holds a key) can sign its verdict for each arrival, and the policy reads it and the receipt carries it, attested. It is the first piece of an agent front door; it does not yet detect agents in web traffic itself, and says so ([the door](docs/door.md)).
11
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
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)).
13
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.
@@ -17,11 +17,13 @@ Anyone holding the public keys can verify a receipt offline. The agent is not tr
17
17
  - [Reference](https://docs.agent-custody.dev/reference/): every function, endpoint, MCP tool, and command with its request and response
18
18
  - [Tutorials](docs/tutorials.md): runnable examples, one per aspect of the code, all executed by the test suite
19
19
  - [Put the door in front of a site](docs/door-quickstart.md): a fifteen-minute quick start for a site owner, from keys to verified receipts.
20
- - [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 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, behind stock nginx or Envoy as their authz check (receipts of the decision, not the result), and what it does not do yet
21
21
  - [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
22
22
  - [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
23
23
  - [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
24
- - [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
24
+ - [The door in your Node app](docs/door-middleware.md): the same decision loop in-process, as Express middleware or a Next.js route-handler wrapper; quick starts for both, what the app receives, and what the receipt records of its answer and what it does not
25
+ - [The door in Go, Rails, Django, and Spring](docs/door-languages.md): standard-library middleware for `net/http`, Rack, Django and WSGI, and the JDK `HttpServer`, with a Spring filter snippet, each a client of the door's authz check that fails closed when the door does not answer
26
+ - [Door signals](docs/door-signals.md): every field of the arrival fact and of a partner engine's signed verdict, labelled checked, observed, or a claim, with what it does and does not mean and how a policy should read it
25
27
  - [Financial operations](docs/financial-operations.md): durable operation ids, provider idempotency keys, atomic daily budget reservations, and reconciliation receipts for uncertain outcomes
26
28
  - [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
27
29
  - [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
@@ -115,12 +117,12 @@ Three parties hold keys. The **principal** signs a grant saying which agent may
115
117
 
116
118
  | | gateway | door | egress witness | ACS Guardian | SDK |
117
119
  | --- | --- | --- | --- | --- | --- |
118
- | 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 |
120
+ | where it runs | separate process between agent and tools | separate process between the world and your own site or API, or in-process in a Node site | 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 |
119
121
  | 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 |
120
122
  | 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 |
121
123
  | 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 |
122
124
  | 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 |
123
- | 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 |
125
+ | install | one line in the host's MCP config | a reverse proxy in front of the origin, or `app.use(door(...))` in Express and `guard.route(handler)` in Next.js | 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 |
124
126
 
125
127
  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)).
126
128
 
@@ -145,6 +147,9 @@ Every receipt names its issuer, and the verifier prints what that issuer kind is
145
147
  | any MCP host in any language: Claude Agent SDK Python, OpenAI Agents Python | gateway | yes | | the gateway is an MCP server; [usage.md](docs/usage.md#python-hosts) |
146
148
  | any REST API, as tools the agent reaches through the gateway | gateway, `rest` upstream | yes | | a stand-in HTTP API; [usage.md](docs/usage.md#setup-step-by-step) |
147
149
  | any agent reached over A2A (Google ADK `RemoteA2aAgent`, or any A2A client) | gateway, `a2a` upstream and `gateway --a2a` | yes | | stand-in A2A agents in both wire formats; ADK's own `to_a2a` and `RemoteA2aAgent` in the Python suite; [usage.md](docs/usage.md#the-gateway-as-an-a2a-agent) |
150
+ | a site any agent arrives at, built on Express or Connect | door, in-process | `app.use(door("door.json"))` | | Express 5.2.1 with `express.json()`, `express.urlencoded()`, and a raw stream read after the door; [guide](docs/door-middleware.md) |
151
+ | a site any agent arrives at, built on Go `net/http`, Rails (Rack), Django (or WSGI), or Spring | door, authz mode, asked by a middleware | `Door(url, timeout)(handler)`, `AgentCustody::Door`, `DoorMiddleware` / `DoorWSGI`, `CustodyDoor` with a filter | | each example against a live door: Go through `ServeHTTP`, Rack with a Rack env, WSGI under `wsgiref`, Django with a stand-in request and `HttpResponse`, the JDK `HttpServer` filter; the Spring filter is a doc snippet, not compiled; [guide](docs/door-languages.md) |
152
+ | a site any agent arrives at, built on Next.js (App Router) | door, in-process | `guard.route(handler)` on each route handler | | fetch `Request` and `Response` objects in the tests; by hand, a fresh `create-next-app` (Next.js 16.4.6) under `next dev` and `next start`; [guide](docs/door-middleware.md) |
148
153
 
149
154
  The framework packages, `pg`, and `@node-saml/node-saml` (for SAML sign-in to the portal) are optional peer dependencies. Each adapter imports only from its own package.
150
155
 
@@ -288,7 +293,10 @@ src/issue.ts sign, log, and write a receipt, or commit an authorization fi
288
293
  src/gateway.ts the MCP proxy: a host (key, policy, upstreams, log) and a session per grant; scope check, facts, policy, forward, receipt
289
294
  src/operations.ts SQLite operation claims and daily budget reservations, retained across retries and process crashes
290
295
  src/gateway-http.ts the gateway over Streamable HTTP: one process, a session per connection, each under the grant it presents
291
- 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
296
+ src/door.ts the door: a reverse proxy in front of your own HTTP surface, or the authz check behind nginx and Envoy; every arrival classified, decided per route, relayed or refused, receipted as issuer kind door; its decision loop is shared with door-app.ts
297
+ src/door-app.ts the door in-process (`@agent-custody/receipts/door`): Express or Connect middleware and a fetch route-handler wrapper (Next.js), over the same decision loop
298
+ src/web-bot-auth.ts the door's Web Bot Auth check: RFC 9421 signature base, RFC 8941 dictionaries, Ed25519, the signer's key directory fetched and cached, nonces
299
+ src/door-partner.ts the door's partner engine slot: asks a detection engine about an arrival, accepts only a verdict signed for that receipt and route (the upstream attestation format), and `signVerdict` for engines
292
300
  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
293
301
  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
294
302
  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
@@ -311,8 +319,8 @@ src/cli.ts keygen, grant, gateway, door, egress, egress draft-policy, ac
311
319
  src/retention.ts pruning the log: leaves become their hashes, bundles are removed, proofs survive
312
320
  src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
313
321
  tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
314
- 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, the site's numbers (`bench.ts`), and the per-step hot-path benchmark (`hot-path-bench.ts`, `bun run bench`)
315
- 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
322
+ scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, a fake partner detection engine for the door (`fake-partner.ts`, signs its verdicts), 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, the site's numbers (`bench.ts`), and the per-step hot-path benchmark (`hot-path-bench.ts`, `bun run bench`)
323
+ examples/ runnable tutorials, plus examples/languages/: Python, Go, Java, and Rust clients of the sidecar, and in door/ the Go, Rack, Django and WSGI, and JDK middleware clients of the door's authz check, run by the test suite, one per aspect; each is run by the test suite
316
324
  test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
317
325
  adapter tests against the real packages, and tests that run every policy in docs/policies.md and site/guide/egress-policies.md
318
326
  docs/ tutorials, usage (gateway), codex-recovery (live demo), approvals, sdk, policies, verification, performance
@@ -320,10 +328,14 @@ docs/ tutorials, usage (gateway), codex-recovery (live demo), appro
320
328
 
321
329
  ## Plan
322
330
 
323
- 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).
331
+ 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 AP2 mandates as a passport.
324
332
 
325
333
  **Done**
326
334
 
335
+ - The door for sites that are not Node (svayatta/pm#4): standard-library middleware for Go `net/http`, Rack (Rails), Django and WSGI, and the JDK `HttpServer`, in `examples/languages/door/`, each a client of the door's authz check. It forwards the method, path, query, and headers, runs the app only on the door's 200 with the receipt id and class in the request and the grant removed, returns any refusal as the door gave it, and answers 503 when the door cannot be reached or does not answer in time. A Spring `OncePerRequestFilter` around the same Java client is a doc snippet, not compiled by the tests ([the door in Go, Rails, Django, and Spring](docs/door-languages.md)).
336
+ - The door's partner engine slot (svayatta/pm#13): with `partner` in the door config, the door asks a detection engine (Cloudflare Bot Management, HUMAN, DataDome, behind an adapter that holds an Ed25519 key) about each arrival on the listed routes, naming the receipt it is writing. The engine signs its verdict for that receipt and route in the upstream attestation format; only a verdict whose signature verifies under the configured key reaches the policy, as `context.facts.partner`, and lands in the receipt as an attested fact, checked again by all three verifiers with `--upstream-key`. A verdict for another arrival is refused, and an engine that is down, slow, or signs wrongly never becomes an allow: the arrival is refused with 503 (`onFailure: "deny"`, the default) or the policy decides without the fact (`"absent"`) ([the door](docs/door.md#a-partner-engines-verdict), tutorial 52).
337
+ - The door in-process: `@agent-custody/receipts/door` runs the door's decision loop inside a Node site, the proxy's own code path split out of it. Express takes `app.use(door("door.json"))`; a Next.js App Router route takes `export const POST = guard.route(handler)`. An allowed request reaches the app with the receipt id and the class in its headers, the grant removed, and the body the policy read handed on to the app's own parsers; a refused one never reaches it; a request that can change something is in the log before the app runs; and the receipt records the app's status and a digest of its body. Neither framework is a dependency. Next.js pages, Server Actions, and its middleware file are not covered ([the door in your Node app](docs/door-middleware.md), tutorial 48).
338
+ - The door checks Web Bot Auth signatures (svayatta/pm#18): with `webBotAuth`, an RFC 9421 signature tagged `web-bot-auth` is checked against the Ed25519 key the `Signature-Agent` origin publishes in its directory, fetched over https from that origin only, for origins listed in `agents`, with a timeout, a size cap, and a cache. It must cover `@authority` (one of `authorities`) and the `Signature-Agent` member, be at most five minutes old, and carry a nonce that serves one request. A signed arrival without a grant is `verified` as its origin; a grant under its agent's signature is bound to its sender, and under another agent's it is `wrong-sender` ([the door](docs/door.md#web-bot-auth-signatures), tutorial 47).
327
339
  - A cheaper receipt hot path: a Cedar policy is parsed once per text instead of on every decision (a few slots, evicted oldest first), and the local log keeps one descriptor open for its appends, reopened when a prune replaces the file. The log lock reads its owner's start time once per process instead of running `ps` on every append on macOS. The receipt format, the decisions, and what is fsynced are unchanged. `bun run bench` times each step, Cedar and Rego both; [docs/performance.md](docs/performance.md) has the numbers.
328
340
  - 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).
329
341
  - 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).
@@ -333,6 +345,7 @@ The design is several producers feeding one verifier. The SDK is the top of the
333
345
  - 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).
334
346
  - `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.
335
347
  - 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).
348
+ - The door behind stock nginx and Envoy: with `"authz": true` the door relays nothing and answers nginx `auth_request` and Envoy `ext_authz` (HTTP mode) checks from `X-Original-Method` and `X-Original-URI`: 200 with the receipt id and class for the proxy to pass upstream, or 403, and a request that can change something is committed to the log before the 200. It never sees the body or the origin's answer, so its receipts say `issuer.framework: "authz"`, an allow is `withheld`, and all three verifiers run `door authz decided, relayed nothing`. `deploy/door/` has the stock configs and `demo.sh`, which CI runs ([the door](docs/door.md#behind-nginx-or-envoy-authz-mode), tutorial 49).
336
349
  - 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).
337
350
  - 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).
338
351
  - 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)).
package/dist/capture.d.ts CHANGED
@@ -90,6 +90,8 @@ export declare function ruleFor(capture: CaptureConfig | undefined, tool: string
90
90
  * issuer both call this, so the fact arguments kept in clear and the view agree.
91
91
  */
92
92
  export declare function effectiveRule(capture: CaptureConfig | undefined, tool: string, unknownTool?: boolean): CaptureRule | undefined;
93
+ /** The same test for any signed content: an attestation envelope that binds this receipt, this tool, and `digest`, and nothing else. A partner engine's verdict is signed this way, over the verdict's digest. */
94
+ export declare function isPlainEnvelope(envelope: unknown, receiptId: unknown, tool: unknown, digest: string): boolean;
93
95
  /** The one mode a rule withholds in: encrypted when any side is, else digest; clear when no side is private. */
94
96
  export declare function ruleMode(rule: CaptureRule | undefined): CaptureMode;
95
97
  export declare const pathKey: (p: Path) => string;
package/dist/capture.js CHANGED
@@ -156,9 +156,13 @@ export function effectiveRule(capture, tool, unknownTool = false) {
156
156
  * rule publishes from the same upstream.
157
157
  */
158
158
  function isPlainAttestation(envelope, receiptId, tool, result) {
159
+ return isObject(result) && isPlainEnvelope(envelope, receiptId, tool, contentDigest(result));
160
+ }
161
+ /** The same test for any signed content: an attestation envelope that binds this receipt, this tool, and `digest`, and nothing else. A partner engine's verdict is signed this way, over the verdict's digest. */
162
+ export function isPlainEnvelope(envelope, receiptId, tool, digest) {
159
163
  if (!isObject(envelope) || !exactKeys(envelope, ["payload", "payloadType", "signatures"]))
160
164
  return false;
161
- if (envelope.payloadType !== UPSTREAM_TYPE || typeof envelope.payload !== "string" || !isObject(result))
165
+ if (envelope.payloadType !== UPSTREAM_TYPE || typeof envelope.payload !== "string")
162
166
  return false;
163
167
  const sigs = envelope.signatures;
164
168
  if (!Array.isArray(sigs) || sigs.length !== 1)
@@ -176,7 +180,7 @@ function isPlainAttestation(envelope, receiptId, tool, result) {
176
180
  // compared as bytes: decoding to text would turn an invalid byte into U+FFFD and let it through
177
181
  if (!isObject(p) || !exactKeys(p, ["contentDigest", "receiptId", "tool"]) || !bytes.equals(Buffer.from(canonicalize(p), "utf8")))
178
182
  return false;
179
- return p.receiptId === receiptId && p.tool === tool && p.contentDigest === contentDigest(result);
183
+ return p.receiptId === receiptId && p.tool === tool && p.contentDigest === digest;
180
184
  }
181
185
  catch {
182
186
  return false;
@@ -396,6 +400,13 @@ export function privateView(predicate, rule, key, ctx = {}, prior) {
396
400
  if (argsSide)
397
401
  fields(["facts", name, "args"], v, { clear: new Set(ownOf(ctx.clearFactArgs, name) ?? []), key: argsSide.key });
398
402
  }
403
+ else if (f === "attestation") {
404
+ // a fact its source signed (the door's partner verdict): kept beside a value the rule leaves in clear only
405
+ // when it is exactly the plain attestation of that value for this receipt and route, as an upstream's is
406
+ if (!factsSide && !ctx.unknownTool && isPlainEnvelope(v, predicate.receiptId, predicate.tool.name, digestOf(fact.value)))
407
+ continue;
408
+ hide(["facts", name, f], v, factsSide ? factsSide.key : k);
409
+ }
399
410
  else if (!CLEAR_IN.fact.has(f))
400
411
  hide(["facts", name, f], v, k);
401
412
  }
package/dist/check.d.ts CHANGED
@@ -15,7 +15,7 @@ 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. */
18
+ /** True when the file is a door config rather than a gateway config: it names an origin, door routes, or answers authz checks, which no gateway config does. An in-process door's config has routes and no origin. */
19
19
  export declare function isDoorConfig(configPath: string): boolean;
20
20
  /**
21
21
  * The agents named by permits that do not also require a verified arrival. At the door the principal is the agent of a
package/dist/check.js CHANGED
@@ -51,11 +51,11 @@ function onPath(command) {
51
51
  return existsSync(command);
52
52
  return (process.env.PATH ?? "").split(delimiter).some((d) => d && existsSync(join(d, command)));
53
53
  }
54
- /** True when the file is a door config rather than a gateway config: it names an origin, which no gateway config has. */
54
+ /** True when the file is a door config rather than a gateway config: it names an origin, door routes, or answers authz checks, which no gateway config does. An in-process door's config has routes and no origin. */
55
55
  export function isDoorConfig(configPath) {
56
56
  try {
57
57
  const raw = JSON.parse(readFileSync(configPath, "utf8"));
58
- return !!raw && typeof raw === "object" && !Array.isArray(raw) && "origin" in raw && !("upstream" in raw) && !("upstreams" in raw);
58
+ return !!raw && typeof raw === "object" && !Array.isArray(raw) && ("origin" in raw || "routes" in raw || "authz" in raw) && !("upstream" in raw) && !("upstreams" in raw) && !("agents" in raw);
59
59
  }
60
60
  catch {
61
61
  return false;
@@ -164,14 +164,20 @@ export function checkDoorConfig(configPath) {
164
164
  add("warn", "routes", `no routes: every arrival is the action "${cfg.unmatchedRoute}"`);
165
165
  else
166
166
  add("ok", "routes", `${cfg.routes.length} route(s); unmatched arrivals are "${cfg.unmatchedRoute}"`);
167
- const origin = new URL(cfg.origin.url);
168
- if (origin.protocol !== "https:" && !["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname))
169
- add("warn", "origin", `${cfg.origin.url} is plain HTTP to a remote host; the relayed traffic is not encrypted on that leg`);
170
- else
171
- add("ok", "origin", `relays to ${cfg.origin.url}`);
172
- for (const [, variable] of Object.entries(cfg.origin.headerEnv ?? {}))
173
- if (!process.env[variable])
174
- add("error", "credentials", `origin header variable ${variable} is not set in this environment`);
167
+ if (cfg.authz)
168
+ add("ok", "authz", "answers nginx auth_request and Envoy ext_authz checks: the proxy relays, and the receipts record the decision, never the body or the origin's answer");
169
+ else if (!cfg.origin)
170
+ add("ok", "origin", "no origin: a config for the door in-process (Express or Next.js); `agent-custody door` needs origin.url, or authz: true behind nginx or Envoy");
171
+ else {
172
+ const origin = new URL(cfg.origin.url);
173
+ if (origin.protocol !== "https:" && !["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname))
174
+ add("warn", "origin", `${cfg.origin.url} is plain HTTP to a remote host; the relayed traffic is not encrypted on that leg`);
175
+ else
176
+ add("ok", "origin", `relays to ${cfg.origin.url}`);
177
+ for (const [, variable] of Object.entries(cfg.origin.headerEnv ?? {}))
178
+ if (!process.env[variable])
179
+ add("error", "credentials", `origin header variable ${variable} is not set in this environment`);
180
+ }
175
181
  if (cfg.log?.tokenEnv && !process.env[cfg.log.tokenEnv])
176
182
  add("error", "credentials", `log token variable ${cfg.log.tokenEnv} is not set in this environment`);
177
183
  if (cfg.splunk?.tokenEnv && !process.env[cfg.splunk.tokenEnv])
@@ -191,6 +197,24 @@ export function checkDoorConfig(configPath) {
191
197
  }
192
198
  else
193
199
  add("ok", "challenge", "no challenge: an unknown arrival has no way to become anything else on this door");
200
+ if (cfg.webBotAuth) {
201
+ const w = cfg.webBotAuth;
202
+ add("ok", "web bot auth", `Ed25519 signatures tagged web-bot-auth from ${w.agents.join(", ")} are checked against their directories, for ${w.authorities.join(", ")}, at most ${w.maxAgeSeconds} s after created; a verified signature without a grant makes the arrival verified as its origin`);
203
+ if (!w.requireNonce)
204
+ add("warn", "web bot auth", `requireNonce is false: a signature without a nonce can be replayed for up to ${w.maxAgeSeconds + w.clockSkewSeconds} s, and a minimal one covers only the authority, so the replay may use any method and path`);
205
+ }
206
+ else
207
+ add("ok", "web bot auth", "no webBotAuth: a Signature-Input header is recorded as signature \"unchecked\", a claim");
208
+ if (cfg.partner) {
209
+ const p = cfg.partner;
210
+ try {
211
+ loadPublicKey(p.keyFile);
212
+ add("ok", "partner", `${p.engine} at ${p.url} is asked about ${p.routes.join(", ")} within ${p.timeoutMs} ms; only a verdict signed under ${p.keyFile} for the arrival reaches context.facts.partner. Without one: ${p.onFailure === "deny" ? "the arrival is refused with 503" : "the policy decides without the fact"}`);
213
+ }
214
+ catch (e) {
215
+ add("error", "partner", `${p.keyFile}: ${e instanceof Error ? e.message : String(e)}`);
216
+ }
217
+ }
194
218
  const dir = writableAncestor(cfg.receiptsDir);
195
219
  if (!dir)
196
220
  add("error", "paths", `${cfg.receiptsDir} cannot be created: no writable directory above it`);
package/dist/cli.js CHANGED
@@ -102,7 +102,9 @@ const USAGE = `agent-custody <command>
102
102
  door --config <door.json> [--port 8780] [--host 127.0.0.1]
103
103
  a reverse proxy in front of your own site or API: every arrival classified (verified by a
104
104
  trusted grant, claimed, or unknown), decided by the Cedar policy for its route, relayed to the
105
- origin or refused with 403, and receipted either way; GET /.well-known/agent-custody-door
105
+ origin or refused with 403, and receipted either way; GET /.well-known/agent-custody-door.
106
+ With "authz": true in the config it relays nothing and answers nginx auth_request and
107
+ Envoy ext_authz checks instead: 200 with the receipt headers, or 403
106
108
  egress --config <egress.json> [--port 8791] [--host 127.0.0.1]
107
109
  the egress witness: a forward proxy (CONNECT and plain HTTP, no TLS interception) for a
108
110
  locked-down agent's calls that do not go to the gateway. Each agent proves itself with its own
@@ -379,7 +381,7 @@ async function main(argv) {
379
381
  const cfg = loadDoorConfig(values.config);
380
382
  const host = await createDoorHost(cfg, { autoFlush: true });
381
383
  const running = await serveDoor(host, { port: Number(values.port), host: values.host });
382
- console.error(`agent-custody door: ${running.url} keyid=${host.keyid} in front of ${cfg.origin.url}; ${cfg.routes.length} route(s), unmatched arrivals are "${cfg.unmatchedRoute}"`);
384
+ console.error(`agent-custody door: ${running.url} keyid=${host.keyid} ${cfg.authz ? "answering authz checks" : `in front of ${cfg.origin?.url}`}; ${cfg.routes.length} route(s), unmatched arrivals are "${cfg.unmatchedRoute}"`);
383
385
  await untilStopped();
384
386
  await running.close();
385
387
  await host.close();
package/dist/config.d.ts CHANGED
@@ -388,12 +388,13 @@ export declare const DoorConfigSchema: z.ZodObject<{
388
388
  identity: z.ZodObject<{
389
389
  keyFile: z.ZodString;
390
390
  }, z.core.$strip>;
391
- origin: z.ZodObject<{
391
+ origin: z.ZodOptional<z.ZodObject<{
392
392
  url: z.ZodString;
393
393
  headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
394
394
  headerEnv: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
395
395
  timeoutMs: z.ZodDefault<z.ZodNumber>;
396
- }, z.core.$strip>;
396
+ }, z.core.$strip>>;
397
+ authz: z.ZodOptional<z.ZodBoolean>;
397
398
  routes: z.ZodDefault<z.ZodArray<z.ZodObject<{
398
399
  name: z.ZodString;
399
400
  methods: z.ZodOptional<z.ZodArray<z.ZodEnum<{
@@ -432,6 +433,30 @@ export declare const DoorConfigSchema: z.ZodObject<{
432
433
  action: z.ZodOptional<z.ZodString>;
433
434
  maxInFlight: z.ZodDefault<z.ZodNumber>;
434
435
  }, z.core.$strip>>;
436
+ webBotAuth: z.ZodOptional<z.ZodObject<{
437
+ agents: z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
438
+ authorities: z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
439
+ requireNonce: z.ZodDefault<z.ZodBoolean>;
440
+ maxAgeSeconds: z.ZodDefault<z.ZodNumber>;
441
+ clockSkewSeconds: z.ZodDefault<z.ZodNumber>;
442
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
443
+ maxDirectoryBytes: z.ZodDefault<z.ZodNumber>;
444
+ cacheSeconds: z.ZodDefault<z.ZodNumber>;
445
+ maxNonces: z.ZodDefault<z.ZodNumber>;
446
+ }, z.core.$strip>>;
447
+ partner: z.ZodOptional<z.ZodObject<{
448
+ engine: z.ZodString;
449
+ url: z.ZodString;
450
+ keyFile: z.ZodString;
451
+ routes: z.ZodArray<z.ZodString>;
452
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
453
+ onFailure: z.ZodDefault<z.ZodEnum<{
454
+ absent: "absent";
455
+ deny: "deny";
456
+ }>>;
457
+ maxInFlight: z.ZodDefault<z.ZodNumber>;
458
+ maxResponseBytes: z.ZodDefault<z.ZodNumber>;
459
+ }, z.core.$strip>>;
435
460
  receiptsDir: z.ZodString;
436
461
  logFile: z.ZodOptional<z.ZodString>;
437
462
  log: z.ZodOptional<z.ZodObject<{
package/dist/config.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { dirname, resolve } from "node:path";
4
+ import { agentOrigin, normalizeAuthority } from "./web-bot-auth.js";
4
5
  /** Where receipts are logged: a local file, or a log reached over HTTP whose bearer token comes from an environment variable. */
5
6
  const LogSchema = z.object({ url: z.string().url(), tokenEnv: z.string().min(1).optional(), /** send leaf hashes only; the log never holds the receipt. Use it for any log run by someone else */ hashOnly: z.boolean().optional(), /** milliseconds one append may take before the log counts as unreachable; default 10000 */ timeoutMs: z.number().int().positive().optional(), /** the log's public key files; every append's answer is checked against them before a call is forwarded. Without them the log's key document is fetched from the log itself on first use and pinned, which catches a log that turns dishonest later but not one dishonest from the start; required with precommit. */ keys: z.array(z.string().min(1)).optional(), /** the id the log must write into every tree head; an answer for another log is refused */ logId: z.string().min(1).optional() });
6
7
  export const ONE_LOG = "exactly one of logFile or log is required";
@@ -240,13 +241,15 @@ const DoorRouteSchema = z.object({
240
241
  */
241
242
  export const DoorConfigSchema = z.object({
242
243
  identity: z.object({ keyFile: z.string() }),
243
- /** where allowed requests go: the site or API the door stands in front of */
244
+ /** where allowed requests go: the site or API the door stands in front of. The proxy needs it unless `authz` is set; the in-process door (`door-app.ts`) passes the request to the app instead and refuses a config that names one */
244
245
  origin: z.object({
245
246
  url: z.string().url(),
246
247
  headers: z.record(z.string(), z.string()).optional(),
247
248
  headerEnv: z.record(z.string(), z.string().min(1)).optional(),
248
249
  timeoutMs: z.number().int().positive().default(30_000),
249
- }),
250
+ }).optional(),
251
+ /** answer nginx `auth_request` and Envoy `ext_authz` checks instead of relaying: 200 with the receipt headers or 403, from `X-Original-Method` and `X-Original-URI`. The door never sees the body or the origin's answer */
252
+ authz: z.boolean().optional(),
250
253
  routes: z.array(DoorRouteSchema).default([]),
251
254
  /** the action name for an arrival no route matches; default "other" */
252
255
  unmatchedRoute: z.string().min(1).default("other"),
@@ -281,6 +284,64 @@ export const DoorConfigSchema = z.object({
281
284
  /** checks with the provider at once; an arrival past this is `unavailable`, never relayed on a pass it did not get. Default 64 */
282
285
  maxInFlight: z.number().int().positive().default(64),
283
286
  }).refine((c) => !c.action || c.provider === "turnstile", { message: "challenge.action is a Turnstile field; hCaptcha does not report an action" }).optional(),
287
+ /**
288
+ * Web Bot Auth: an RFC 9421 signature tagged `web-bot-auth`, Ed25519, checked against the key the `Signature-Agent`
289
+ * origin publishes at /.well-known/http-message-signatures-directory. The door fetches only the directories of `agents`,
290
+ * so an arrival cannot point it at a URL of its choosing.
291
+ */
292
+ webBotAuth: z.object({
293
+ /** the signature agents whose directories the door fetches, as https origins (`https://crawler.example`) */
294
+ agents: z.array(z.string().refine((u) => { try {
295
+ return agentOrigin(u) === new URL(u).origin;
296
+ }
297
+ catch {
298
+ return false;
299
+ } }, { message: "a signature agent is an https origin, with no path, query, or credentials" }).transform((u) => new URL(u).origin)).min(1),
300
+ /** the authorities (host, or host:port) this door serves; a signature must cover `@authority` and name one of them */
301
+ authorities: z.array(z.string().min(1).transform(normalizeAuthority)).min(1),
302
+ /** refuse a signature without a nonce; with one, a signature serves one request. Default true */
303
+ requireNonce: z.boolean().default(true),
304
+ /** the longest after `created` a signature is accepted, whatever its `expires`. Default 300 */
305
+ maxAgeSeconds: z.number().int().positive().default(300),
306
+ /** how far the signer's clock may be from the door's. Default 60 */
307
+ clockSkewSeconds: z.number().int().nonnegative().default(60),
308
+ /** one directory fetch's budget. Default 3000 */
309
+ timeoutMs: z.number().int().positive().default(3_000),
310
+ /** the largest directory the door reads. Default 64 KiB */
311
+ maxDirectoryBytes: z.number().int().positive().default(64 * 1024),
312
+ /** how long a fetched directory is kept; a failed fetch is retried after 30 s. Default 300 */
313
+ cacheSeconds: z.number().int().positive().default(300),
314
+ /** nonces remembered at once; past this a signature is `unavailable`. Default 100000 */
315
+ maxNonces: z.number().int().positive().default(100_000),
316
+ }).optional(),
317
+ /**
318
+ * A partner detection engine (Cloudflare Bot Management, HUMAN, DataDome, behind an adapter that holds a signing key):
319
+ * the door asks it about each arrival on `routes`, naming the receipt it is writing, and the engine signs its verdict
320
+ * for that receipt. Only a verdict whose signature verifies under `keyFile` reaches the policy, as
321
+ * `context.facts.partner`, and the receipt records it as attested.
322
+ */
323
+ partner: z.object({
324
+ /** the engine's name; the signed verdict must name the same engine */
325
+ engine: z.string().min(1).max(64),
326
+ /** where the door POSTs its question about an arrival */
327
+ url: z.string().url(),
328
+ /** the engine's Ed25519 public key file; the verdict's signature must verify under it */
329
+ keyFile: z.string(),
330
+ /** the route names whose arrivals the engine is asked about, or ["*"] */
331
+ routes: z.array(z.string().min(1)).min(1),
332
+ /** one question's budget, the answer's body included. Default 1500 */
333
+ timeoutMs: z.number().int().positive().default(1_500),
334
+ /**
335
+ * When no verified verdict is had (the engine is unreachable, slow, busy, or answers with a bad signature or a
336
+ * verdict for another arrival): "deny" (default) refuses the arrival with 503, whatever the policy says; "absent"
337
+ * leaves the `partner` fact out, so the policy decides without it and a rule that requires it denies. Never allow.
338
+ */
339
+ onFailure: z.enum(["deny", "absent"]).default("deny"),
340
+ /** questions waiting on the engine at once; an arrival past this has no verdict (`unavailable`). Default 64 */
341
+ maxInFlight: z.number().int().positive().default(64),
342
+ /** the largest answer the door reads. Default 16 KiB */
343
+ maxResponseBytes: z.number().int().positive().default(16 * 1024),
344
+ }).optional(),
284
345
  receiptsDir: z.string(),
285
346
  logFile: z.string().optional(),
286
347
  log: LogSchema.optional(),
@@ -289,6 +350,8 @@ export const DoorConfigSchema = z.object({
289
350
  capture: CaptureSchema.optional(),
290
351
  captureKeyEnv: z.string().min(1).optional(),
291
352
  }).refine(hasOneLog, oneLog).refine((c) => new Set(c.routes.map((r) => r.name)).size === c.routes.length, { message: "route names must be unique" })
353
+ .refine((c) => !c.partner || c.partner.routes.every((r) => r === "*" || r === c.unmatchedRoute || c.routes.some((x) => x.name === r)), { message: "partner.routes names a route the door does not have" })
354
+ .refine((c) => !c.authz || c.trustProxy, { message: "authz needs trustProxy: true, since every check comes from the proxy and the arrival's address is the last in its X-Forwarded-For" })
292
355
  .refine((c) => !c.log || !!c.log.keys?.length, { message: "a remote log needs log.keys: the log's public key files, pinned, to check its answer before a request is relayed" });
293
356
  /**
294
357
  * The egress witness: a forward proxy in the agent's network path for every connection that does not go to the gateway.
@@ -340,6 +403,7 @@ export function loadDoorConfig(path) {
340
403
  receiptsDir: r(cfg.receiptsDir),
341
404
  ...(cfg.logFile ? { logFile: r(cfg.logFile) } : {}),
342
405
  ...(cfg.log?.keys ? { log: { ...cfg.log, keys: cfg.log.keys.map(r) } } : {}),
406
+ ...(cfg.partner ? { partner: { ...cfg.partner, keyFile: r(cfg.partner.keyFile) } } : {}),
343
407
  };
344
408
  }
345
409
  /**
@@ -0,0 +1,28 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { type DoorConfig } from "./config.ts";
3
+ import { type DoorOptions } from "./door.ts";
4
+ import type { FlushResult } from "./issue.ts";
5
+ /** The receipt's `issuer.framework` for an arrival the middleware decided */
6
+ export declare const MIDDLEWARE_FRAMEWORK = "node-middleware";
7
+ /** The receipt's `issuer.framework` for an arrival a wrapped route handler decided */
8
+ export declare const ROUTE_FRAMEWORK = "fetch-route";
9
+ export interface DoorAppOptions extends Omit<DoorOptions, "autoFlush"> {
10
+ /** appends the outbox at start and every 30 seconds. Default true: the app is serving */
11
+ autoFlush?: boolean;
12
+ }
13
+ /** A Connect-style middleware that is also the door's handle: one config, one key, one log, one rate count for the process. */
14
+ export interface InProcessDoor {
15
+ (req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void): void;
16
+ /** wraps a fetch-style route handler (a Next.js App Router `GET` or `POST`): the handler runs only for an arrival the policy allows */
17
+ route<R extends Request, C extends unknown[]>(handler: (req: R, ...rest: C) => Response | Promise<Response>): (req: R, ...rest: C) => Promise<Response>;
18
+ keyid: string;
19
+ policyDigest(): string;
20
+ flushOutbox(): Promise<FlushResult>;
21
+ pendingReceipts(): number;
22
+ close(): void;
23
+ }
24
+ /**
25
+ * The door in-process, from a door config without `origin` (a path, read with `loadDoorConfig`, or a config already
26
+ * loaded). Throws at once on a config the door cannot serve: a missing key, a policy that does not parse, an `origin`, `authz`.
27
+ */
28
+ export declare function door(config: string | DoorConfig, options?: DoorAppOptions): InProcessDoor;