@agent-custody/receipts 0.16.2 → 0.16.3

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
@@ -363,7 +363,7 @@ The design is several producers feeding one verifier. The SDK is the top of the
363
363
  - The signer, keys, and checkpoints: the key in its own process (`signer`, `--signer-url`), the key document at `/.well-known/agent-custody-log.json` fetched and pinned by `verify --log-url` and `audit --log-url`, and signed checkpoints per log published to a directory and a table for a verifier who was not watching. Phase 3 of [issue #6](https://github.com/svayatta/agent-custody/issues/6).
364
364
  - The log over Postgres: `log --db-env`, leaves as hashes in one table keyed by tenant, one writer per tenant by advisory lock, tenants and hashed tokens in tables managed by `log-admin`, rate limits and a body cap, retries in the sink, and `import` for an existing file log. Phase 2 of [issue #6](https://github.com/svayatta/agent-custody/issues/6).
365
365
  - A log for someone else: `hashOnly` sends leaf hashes so the log never holds a receipt; the reference server runs several tenant logs at `/t/<tenant>/` with their own tokens and ids; tree heads name their log and the verifier checks it with `--log-id`. Phase 1 of the hosted log, [issue #6](https://github.com/svayatta/agent-custody/issues/6).
366
- - OpenTelemetry export: with `otel` in either config, every receipt is also one span at the collector the team already runs, trace id equal to the receipt id, attributes for tool, agent, principal, status, decision, and log position; after the receipt, best effort, never on the evidence path. A reconciliation receipt is marked and carries no policy decision, so a dashboard never counts it as a second allowed call.
366
+ - OpenTelemetry export: with `otel` in either config, every receipt is also one span at the collector the team already runs, trace id equal to the receipt id, attributes for tool, agent, principal, status, decision, and log position; after the receipt, best effort, never on the evidence path. A door receipt is a `SERVER` span, since it records an inbound request, and every other receipt is a `CLIENT` span. A reconciliation receipt is marked and carries no policy decision, so a dashboard never counts it as a second allowed call.
367
367
  - Delegation chains for sub-agents: a grant that names the agent's key lets it delegate a narrower grant, with the parent embedded, up to three deep; the verifier and the gateway walk the chain to the principal, refusing any link that escalates scope, widens the window, changes the principal, or is signed by the wrong key; the receipt names the sub-agent and the principal and carries the chain. Pinned by the `gateway-chain-*` vectors and mirrored in the browser verifier.
368
368
  - One gateway for many agents: `gateway --http` serves the gateway over Streamable HTTP, one session per connection under the grant that connection presents, sessions sharing the upstreams and the policy and nothing else; a platform team runs one gateway in front of the tools instead of one process per agent.
369
369
  - Splunk export: with `splunk` in either config, every receipt is also one event at the HTTP Event Collector, with the receipt id, tool, agent, principal, status, decision, and log position as searchable fields and the token from the environment; the same best-effort rule.
package/dist/check.d.ts CHANGED
@@ -25,5 +25,9 @@ export declare function isDoorConfig(configPath: string): boolean;
25
25
  export declare function permitsNamingAgentWithoutVerifiedArrival(policyText: string): string[];
26
26
  /** `agent-custody check` on a door config: what the door would fail on at startup, and what it would silently do less than the config seems to promise. */
27
27
  export declare function checkDoorConfig(configPath: string): CheckFinding[];
28
+ /** True when the file is an egress witness config: it names agents, and no upstream or origin. */
29
+ export declare function isEgressConfig(configPath: string): boolean;
30
+ /** `agent-custody check` on an egress witness config: what the witness would fail on at startup. */
31
+ export declare function checkEgressConfig(configPath: string): CheckFinding[];
28
32
  export declare function checkConfig(configPath: string, options?: CheckOptions): Promise<CheckFinding[]>;
29
33
  export declare function formatFindings(findings: CheckFinding[]): string;
package/dist/check.js CHANGED
@@ -6,7 +6,7 @@ import * as cedar from "@cedar-policy/cedar-wasm/nodejs";
6
6
  import { accessSync, constants, existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
7
7
  import { tmpdir } from "node:os";
8
8
  import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
9
- import { DoorConfigSchema, GatewayConfigSchema, loadConfig, loadDoorConfig, strictRefusals } from "./config.js";
9
+ import { DoorConfigSchema, EgressConfigSchema, GatewayConfigSchema, loadConfig, loadDoorConfig, loadEgressConfig, ONE_LOG, strictRefusals } from "./config.js";
10
10
  import { generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
11
11
  import { delegationValidAt, verifyDelegation } from "./delegation.js";
12
12
  import { hasPermitRule } from "./policy.js";
@@ -200,6 +200,98 @@ export function checkDoorConfig(configPath) {
200
200
  }
201
201
  return out;
202
202
  }
203
+ /** True when the file is an egress witness config: it names agents, and no upstream or origin. */
204
+ export function isEgressConfig(configPath) {
205
+ try {
206
+ const raw = JSON.parse(readFileSync(configPath, "utf8"));
207
+ return !!raw && typeof raw === "object" && !Array.isArray(raw) && "agents" in raw && !("upstream" in raw) && !("upstreams" in raw) && !("origin" in raw);
208
+ }
209
+ catch {
210
+ return false;
211
+ }
212
+ }
213
+ /** `agent-custody check` on an egress witness config: what the witness would fail on at startup. */
214
+ export function checkEgressConfig(configPath) {
215
+ const out = [];
216
+ const add = (level, check, message) => out.push({ level, check, message });
217
+ let raw;
218
+ try {
219
+ raw = JSON.parse(readFileSync(configPath, "utf8"));
220
+ }
221
+ catch (e) {
222
+ add("error", "config", `${configPath} is not readable JSON: ${e instanceof Error ? e.message : String(e)}`);
223
+ return out;
224
+ }
225
+ const known = Object.keys(EgressConfigSchema.shape);
226
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
227
+ for (const key of Object.keys(raw)) {
228
+ if (known.includes(key))
229
+ continue;
230
+ const near = known.find((k) => distance(k.toLowerCase(), key.toLowerCase()) <= 2);
231
+ add("error", "config", `unknown key "${key}" is ignored by the egress witness${near ? `; did you mean "${near}"?` : ""} A mistyped key leaves the setting it was meant for at its default`);
232
+ }
233
+ }
234
+ const parsed = EgressConfigSchema.safeParse(raw);
235
+ if (!parsed.success) {
236
+ for (const issue of parsed.error.issues)
237
+ add("error", issue.message === ONE_LOG ? "log" : "config", `${issue.path.join(".") || "(root)"}: ${issue.message}`);
238
+ return out;
239
+ }
240
+ add("ok", "config", "the config parses");
241
+ const cfg = loadEgressConfig(configPath);
242
+ add("ok", "log", cfg.logFile ? `receipts are logged to ${cfg.logFile}` : `receipts are logged to ${cfg.log.url}`);
243
+ if (!existsSync(cfg.identity.keyFile))
244
+ add("error", "key", `${cfg.identity.keyFile} does not exist, and the witness does not start without it; \`agent-custody keygen\` creates it, and the container creates it at EGRESS_KEY before it starts the witness`);
245
+ else {
246
+ try {
247
+ loadPrivateKey(cfg.identity.keyFile);
248
+ add("ok", "key", `the witness key at ${cfg.identity.keyFile} loads`);
249
+ if (process.platform !== "win32" && (statSync(cfg.identity.keyFile).mode & 0o077) !== 0)
250
+ add("warn", "key", `${cfg.identity.keyFile} is readable by other users; make it mode 0600`);
251
+ }
252
+ catch (e) {
253
+ add("error", "key", `${cfg.identity.keyFile}: ${e instanceof Error ? e.message : String(e)}`);
254
+ }
255
+ }
256
+ const unset = cfg.agents.filter((a) => !process.env[a.secretEnv]);
257
+ for (const a of unset)
258
+ add("error", "credentials", `agent ${a.id}: the secret variable ${a.secretEnv} is not set in this environment`);
259
+ if (!unset.length)
260
+ add("ok", "credentials", cfg.agents.length === 1 ? "the agent's secret variable is set" : `the secret variables of all ${cfg.agents.length} agents are set`);
261
+ if (!existsSync(cfg.policyFile))
262
+ add("error", "policy", `${cfg.policyFile} does not exist`);
263
+ else if (isRegoFile(cfg.policyFile)) {
264
+ const errors = compileRego(readFileSync(cfg.policyFile, "utf8")).errors;
265
+ for (const e of errors)
266
+ add("error", "policy", `${cfg.policyFile}: ${e}`);
267
+ if (!errors.length)
268
+ add("ok", "policy", "the Rego policy compiles");
269
+ }
270
+ else {
271
+ const text = readFileSync(cfg.policyFile, "utf8");
272
+ const r = cedar.checkParsePolicySet({ staticPolicies: text });
273
+ if (r.type !== "success")
274
+ for (const e of r.errors)
275
+ add("error", "policy", `${cfg.policyFile}: ${e.message}`);
276
+ else if (!hasPermitRule(text))
277
+ add("warn", "policy", `${cfg.policyFile} has no permit rule, so every connection is refused`);
278
+ else
279
+ add("ok", "policy", "the policy parses");
280
+ }
281
+ if (cfg.mode === "observe")
282
+ add("warn", "mode", "observe mode relays every connection from a known agent and records what the policy would have decided; nothing is refused by policy");
283
+ if (cfg.log?.tokenEnv && !process.env[cfg.log.tokenEnv])
284
+ add("error", "credentials", `log token variable ${cfg.log.tokenEnv} is not set in this environment`);
285
+ if (cfg.splunk?.tokenEnv && !process.env[cfg.splunk.tokenEnv])
286
+ add("error", "credentials", `splunk token variable ${cfg.splunk.tokenEnv} is not set in this environment`);
287
+ for (const v of Object.values(cfg.otel?.headersEnv ?? {}))
288
+ if (!process.env[v])
289
+ add("error", "credentials", `otel header variable ${v} is not set in this environment`);
290
+ for (const f of cfg.log?.keys ?? [])
291
+ if (!existsSync(f))
292
+ add("error", "log keys", `${f} does not exist`);
293
+ return out;
294
+ }
203
295
  export async function checkConfig(configPath, options = {}) {
204
296
  const out = [];
205
297
  const add = (level, check, message) => out.push({ level, check, message });
package/dist/cli.js CHANGED
@@ -30,7 +30,7 @@ import { CheckpointPublisher, fileResolver } from "./log-sink.js";
30
30
  import { createRequire } from "node:module";
31
31
  import { pruneLog } from "./retention.js";
32
32
  import { serveSidecar } from "./sidecar.js";
33
- import { checkConfig, checkDoorConfig, formatFindings, isDoorConfig } from "./check.js";
33
+ import { checkConfig, checkDoorConfig, checkEgressConfig, formatFindings, isDoorConfig, isEgressConfig } from "./check.js";
34
34
  import { serveConsole } from "./console.js";
35
35
  import { TREEHEAD_TYPE } from "./receipt.js";
36
36
  import { MerkleLog } from "./log.js";
@@ -307,7 +307,7 @@ async function main(argv) {
307
307
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, connect: { type: "boolean", default: false }, json: { type: "boolean", default: false } } });
308
308
  if (!values.config)
309
309
  throw new Error("check needs --config");
310
- const findings = isDoorConfig(values.config) ? checkDoorConfig(values.config) : await checkConfig(values.config, { connect: values.connect });
310
+ const findings = isDoorConfig(values.config) ? checkDoorConfig(values.config) : isEgressConfig(values.config) ? checkEgressConfig(values.config) : await checkConfig(values.config, { connect: values.connect });
311
311
  console.log(values.json ? JSON.stringify(findings, null, 2) : formatFindings(findings));
312
312
  return findings.some((f) => f.level === "error") ? 1 : 0;
313
313
  }
package/dist/config.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ export declare const ONE_LOG = "exactly one of logFile or log is required";
2
3
  /** One REST endpoint offered to the agent as a tool. `{name}` segments in the path come from the call's arguments; the rest go to the query on GET and DELETE, or to a JSON body otherwise. */
3
4
  declare const RestToolSchema: z.ZodObject<{
4
5
  name: z.ZodString;
package/dist/config.js CHANGED
@@ -3,7 +3,8 @@ import { readFileSync } from "node:fs";
3
3
  import { dirname, resolve } from "node:path";
4
4
  /** Where receipts are logged: a local file, or a log reached over HTTP whose bearer token comes from an environment variable. */
5
5
  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
- const oneLog = { message: "exactly one of logFile or log is required" };
6
+ export const ONE_LOG = "exactly one of logFile or log is required";
7
+ const oneLog = { message: ONE_LOG };
7
8
  /** Optional OpenTelemetry export: every receipt also becomes a span at this OTLP/HTTP collector, after it is issued. Never on the evidence path. */
8
9
  const OtelSchema = z.object({ url: z.string().url(), headersEnv: z.record(z.string(), z.string().min(1)).optional(), serviceName: z.string().min(1).optional() });
9
10
  const SplunkSchema = z.object({ url: z.string().url(), tokenEnv: z.string().min(1), index: z.string().min(1).optional(), source: z.string().min(1).optional(), sourcetype: z.string().min(1).optional(), host: z.string().min(1).optional() });
package/dist/otel.js CHANGED
@@ -47,7 +47,7 @@ export function spanFor(p, bundle, serviceName) {
47
47
  traceId,
48
48
  spanId: traceId.slice(0, 16),
49
49
  name: reconciliation ? `${p.tool.name} reconciliation` : `${p.tool.name}`,
50
- kind: 3, // CLIENT: the agent calling out
50
+ kind: p.issuer.kind === "door" ? 2 : 3, // SERVER for an inbound request; CLIENT for the agent calling out
51
51
  startTimeUnixNano: start.toString(),
52
52
  endTimeUnixNano: (end > start ? end : start).toString(),
53
53
  attributes,
package/docs/door.md CHANGED
@@ -84,6 +84,173 @@ and a refused arrival that has not passed is told how in the 403 body: `challeng
84
84
 
85
85
  **A token serves one request.** Turnstile and hCaptcha refuse a token they have seen (`timeout-or-duplicate`, `already-seen-response`), and the door keeps no pass between requests: it does not set a cookie or remember an address. So the page must take a new token for every request it sends to a challenged route, and for every retry: call `turnstile.reset()` or `hcaptcha.reset()` after each request, and wait for the new token before the next. The door checks the token before it reads the body, so a request refused for its size (413), its path (400), or by the policy has used its token too. A second request that sends the same token is `failed`, and the person sees another 403. The outcome is a signal, not a class: a `verified` agent that also passes a challenge is still the agent its grant names, and an `unknown` arrival that passes is still `unknown`, with `challenge.outcome: "passed"` beside it. What the provider's pass means, and what it does not, is in [door signals](door-signals.md). Passkeys are not a provider here: a passkey proves possession of a credential the site registered, which is a login, not a challenge, and belongs to the origin.
86
86
 
87
+ ### A run against Turnstile's test keys
88
+
89
+ The tests stub `siteverify`. This run calls the real one once. Cloudflare publishes [test keys](https://developers.cloudflare.com/turnstile/troubleshooting/testing/) that need no account: the site key `1x00000000000000000000AA`, the secret `1x0000000000000000000000000000000AA` (validation always succeeds), the secret `2x0000000000000000000000000000000AA` (validation always fails), and the dummy token `XXXX.DUMMY.TOKEN.XXXX`. The test secrets accept only the dummy token. Cloudflare answers a test key with the hostname `example.com`, so the config names that hostname. These secrets are public. A real secret still goes only into the environment, never into the config or a flag.
90
+
91
+ The run used the CLI from this repository on 2026-11-10. `policy.cedar`:
92
+
93
+ ```cedar
94
+ // The form is for an arrival that has passed the challenge.
95
+ permit(principal, action == Action::"form", resource)
96
+ when { context.facts.arrival.challenge.outcome == "passed" };
97
+ ```
98
+
99
+ `door.json`:
100
+
101
+ ```json
102
+ {
103
+ "identity": { "keyFile": "keys/door.key" },
104
+ "origin": { "url": "http://127.0.0.1:3000" },
105
+ "routes": [{ "name": "form", "methods": ["POST"], "path": "/form" }],
106
+ "policyFile": "policy.cedar",
107
+ "receiptsDir": "receipts",
108
+ "logFile": "log.jsonl",
109
+ "challenge": {
110
+ "provider": "turnstile",
111
+ "siteKey": "1x00000000000000000000AA",
112
+ "secretEnv": "TURNSTILE_SECRET",
113
+ "hostnames": ["example.com"]
114
+ }
115
+ }
116
+ ```
117
+
118
+ A stand-in origin answers every request with `{"ok":true}`:
119
+
120
+ ```bash
121
+ agent-custody keygen --dir keys --name door
122
+ node -e 'require("http").createServer((q,s)=>{s.setHeader("content-type","application/json");s.end(JSON.stringify({ok:true}))}).listen(3000,"127.0.0.1")' &
123
+ ```
124
+
125
+ **The pass run.** Start the door with the secret that always succeeds, and send the dummy token:
126
+
127
+ ```bash
128
+ TURNSTILE_SECRET=1x0000000000000000000000000000000AA agent-custody door --config door.json --port 8780 &
129
+ curl -sS -i -X POST http://127.0.0.1:8780/form -H 'content-type: application/json' \
130
+ -H 'x-agent-custody-challenge: XXXX.DUMMY.TOKEN.XXXX' -d '{"name":"test"}'
131
+ ```
132
+
133
+ ```text
134
+ HTTP/1.1 200 OK
135
+ x-agent-custody-receipt: 74c1e645-3b3e-4306-a70c-057ea0e61d41
136
+ content-type: application/json
137
+ date: Tue, 10 Nov 2026 02:24:05 GMT
138
+ x-agent-custody-class: unknown
139
+ Connection: keep-alive
140
+ Keep-Alive: timeout=5
141
+ Transfer-Encoding: chunked
142
+
143
+ {"ok":true}
144
+ ```
145
+
146
+ **The fail run.** Stop the door. Start it again with the secret that always fails, and send the same request:
147
+
148
+ ```bash
149
+ TURNSTILE_SECRET=2x0000000000000000000000000000000AA agent-custody door --config door.json --port 8780 &
150
+ curl -sS -i -X POST http://127.0.0.1:8780/form -H 'content-type: application/json' \
151
+ -H 'x-agent-custody-challenge: XXXX.DUMMY.TOKEN.XXXX' -d '{"name":"test"}'
152
+ ```
153
+
154
+ ```text
155
+ HTTP/1.1 403 Forbidden
156
+ x-agent-custody-receipt: 01b840df-6a79-408a-9d3b-32dac88787d8
157
+ content-type: application/json
158
+ cache-control: no-store
159
+ x-agent-custody-class: unknown
160
+ Date: Tue, 10 Nov 2026 02:24:13 GMT
161
+ Connection: keep-alive
162
+ Keep-Alive: timeout=5
163
+ Transfer-Encoding: chunked
164
+
165
+ {"error":"refused by the door's policy","reason":"no permit policy matched","receipt":"01b840df-6a79-408a-9d3b-32dac88787d8","challenge":{"provider":"turnstile","siteKey":"1x00000000000000000000AA","header":"x-agent-custody-challenge"}}
166
+ ```
167
+
168
+ **Verify both receipts.** Both exit 0:
169
+
170
+ ```bash
171
+ agent-custody verify receipts/74c1e645-3b3e-4306-a70c-057ea0e61d41.json --issuer-key keys/door.pub --log log.jsonl
172
+ ```
173
+
174
+ ```text
175
+ PASS receipt signature (issuer key) (keyid e316d40ebc50)
176
+ PASS receipt payload type
177
+ PASS structural parts in clear
178
+ PASS issuer kind is known (door / http)
179
+ PASS issuer keyid matches signer
180
+ PASS door receipt carries a policy decision
181
+ PASS principal is claimed, not attested (no signed delegation in this receipt)
182
+ PASS request args digest (committed, not recomputed: 1 value(s) withheld; disclose them to recompute)
183
+ PASS execution result digest
184
+ PASS withheld facts.arrival.resultDigest (committed, not recomputed: 1 value(s) withheld; disclose them to recompute)
185
+ PASS policy decision consistent with execution (allow -> executed)
186
+ PASS no policy errors on an allow
187
+ PASS authorization signature (issuer key) (keyid e316d40ebc50)
188
+ PASS authorization names this call (form for receipt 74c1e645-3b3)
189
+ PASS authorization tree head signature (keyid e316d40ebc50)
190
+ PASS authorization log inclusion proof (leaf 0 of 1)
191
+ PASS authorization logged before execution (authorization leaf 0, receipt leaf 1)
192
+ PASS tree head signature (issuer key e316d40ebc50)
193
+ PASS tree head matches inclusion proof size
194
+ PASS log inclusion proof (leaf 1 of 2, root 67f4115b31c2)
195
+ PASS log file root matches tree head (recomputed 67f4115b31c2)
196
+
197
+ RESULT: VERIFIED
198
+
199
+ ISSUER: door (http), unknown issuer kind
200
+
201
+ field provenance value
202
+ principal claimed (none)
203
+ agent claimed unknown
204
+ model claimed (none supplied)
205
+ tool observed form
206
+ args claimed {"$rest":{"$custody":"withheld","sha256":"8f41daf2…"},"bodyBytes":15,"headers":{"accept":"*/*","content-type":"application/json","host":"127.0.0.1:8780","user-agent":"curl/8.7.1"},"method":"POST","path":"/form"}
207
+ fact.arrival observed {"challenge":{"outcome":"passed","provider":"turnstile"},"class":"unknown","grant":"absent","method":"POST","path":"/form","rate":{"burst":1,"by":"remote","minute":1},"remote":"127.0.0.1","route":"form","signature":false,"subject":"unknown"}
208
+ policy observed allow [policy0] policy 71e3eefa3599
209
+ authorization observed committed to the log as leaf 0, before the call was forwarded
210
+ execution observed executed
211
+ ```
212
+
213
+ ```bash
214
+ agent-custody verify receipts/01b840df-6a79-408a-9d3b-32dac88787d8.json --issuer-key keys/door.pub --log log.jsonl
215
+ ```
216
+
217
+ ```text
218
+ PASS receipt signature (issuer key) (keyid e316d40ebc50)
219
+ PASS receipt payload type
220
+ PASS structural parts in clear
221
+ PASS issuer kind is known (door / http)
222
+ PASS issuer keyid matches signer
223
+ PASS door receipt carries a policy decision
224
+ PASS principal is claimed, not attested (no signed delegation in this receipt)
225
+ PASS request args digest (committed, not recomputed: 1 value(s) withheld; disclose them to recompute)
226
+ PASS withheld facts.arrival.resultDigest (committed, not recomputed: 1 value(s) withheld; disclose them to recompute)
227
+ PASS withheld execution.reason (committed, not recomputed: 1 value(s) withheld; disclose them to recompute)
228
+ PASS policy decision consistent with execution (deny -> denied)
229
+ PASS no policy errors on an allow
230
+ PASS tree head signature (issuer key e316d40ebc50)
231
+ PASS tree head matches inclusion proof size
232
+ PASS log inclusion proof (leaf 2 of 3, root 54a065656fa2)
233
+ PASS log file root matches tree head (recomputed 54a065656fa2)
234
+
235
+ RESULT: VERIFIED
236
+
237
+ ISSUER: door (http), unknown issuer kind
238
+
239
+ field provenance value
240
+ principal claimed (none)
241
+ agent claimed unknown
242
+ model claimed (none supplied)
243
+ tool observed form
244
+ args claimed {"$rest":{"$custody":"withheld","sha256":"255b518c…"},"bodyBytes":15,"headers":{"accept":"*/*","content-type":"application/json","host":"127.0.0.1:8780","user-agent":"curl/8.7.1"},"method":"POST","path":"/form"}
245
+ fact.arrival observed {"challenge":{"error":"invalid-input-response","outcome":"failed","provider":"turnstile"},"class":"unknown","grant":"absent","method":"POST","path":"/form","rate":{"burst":1,"by":"remote","minute":1},"remote":"127.0.0.1","route":"form","signature":false,"subject":"unknown"}
246
+ policy observed deny [] policy 71e3eefa3599
247
+ execution observed denied: (reason withheld under the capture rule)
248
+ ```
249
+
250
+ The pass run's receipt records `challenge.outcome: "passed"`, and the door relayed the request. The fail run's receipt records `challenge.outcome: "failed"` with Cloudflare's code `invalid-input-response`, and the policy refused the request. The token does not appear in either receipt.
251
+
252
+ **What this run shows, and what it does not.** Test keys prove the wire path, not bot detection. The door reaches the real `siteverify`, sends the secret and the token, and records the answer. A test secret gives a fixed answer and no widget runs, so the run says nothing about how well Turnstile tells a person from a bot. The run did not exercise the `unavailable` outcome, a hostname mismatch, an action mismatch, the `timeout-or-duplicate` code, or `remoteip` (the config sets no `trustProxy`, so the door sent none). `test/door.test.ts` covers those against a stubbed `siteverify`. In the output above, the two `sha256` digests are shortened to eight characters and `…`. Nothing else is changed. The CLI was `agent-custody` 0.16.2, run from this repository at commit `64285ef`.
253
+
87
254
  ## How an arrival becomes a Cedar request
88
255
 
89
256
  | Cedar slot | value |
package/docs/egress.md CHANGED
@@ -44,6 +44,8 @@ Each receipt is an **observed bypass**: evidence that the agent connected to a d
44
44
 
45
45
  Run it with `agent-custody egress --config egress.json [--port 8791] [--host 127.0.0.1]`.
46
46
 
47
+ `agent-custody check --config egress.json` reports what it can find before the witness starts: unknown keys; a key file that is missing or does not load (the witness does not start without it); an unset secret variable of an agent, and an unset `log.tokenEnv`, `splunk.tokenEnv`, or `otel.headersEnv` variable (by name, never the value); a missing `log.keys` file; a policy that does not exist, a Cedar policy that does not parse, or a Rego policy that does not compile (this needs `opa` on PATH, as the witness does); and that exactly one of `logFile` and `log` is set. It warns on a key file that other users can read, a Cedar policy with no permit rule, and `mode: "observe"`. It exits 1 on an error.
48
+
47
49
  ## How an agent uses it
48
50
 
49
51
  The agent sets `HTTPS_PROXY` and `HTTP_PROXY` to `http://<agent id>:<secret>@<witness>:8791`, and `NO_PROXY` to the gateway's host, because the gateway receipts its own calls. Most HTTP clients send the credential from the URL as `Proxy-Authorization: Basic`. Node's `fetch` reads these variables when `NODE_USE_ENV_PROXY=1` is set, on versions that support it. Other clients need their own proxy setting.
@@ -171,7 +173,6 @@ Vectors `egress-*` and `resigned-egress-*` in `vectors/receipts.json` cover them
171
173
 
172
174
  - Record the byte counts of a connection open when the witness is killed: the committed authorization is in the log, the closing receipt is not.
173
175
  - Identify an agent by its source address or by a signed grant. Today only per-agent proxy credentials identify an agent.
174
- - `agent-custody check` does not read an egress config yet.
175
176
  - Ask an OPA server for the decision. A `.rego` file works; `opa: { url }` does not, because the decision is made synchronously before the relay.
176
177
 
177
178
  Tutorials: [41-egress.ts](../examples/41-egress.ts), and [44-egress-rego.ts](../examples/44-egress-rego.ts) for a Rego policy.
@@ -20,7 +20,7 @@ jobs:
20
20
  runs-on: ubuntu-latest
21
21
  steps:
22
22
  - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
23
- - uses: svayatta/agent-custody@<commit sha of the release> # 0.16.2
23
+ - uses: svayatta/agent-custody@<commit sha of the release> # 0.16.3
24
24
  with:
25
25
  path: .custody/receipts
26
26
  issuer-key: .custody/keys/agent.pub
@@ -37,7 +37,7 @@ Pin the action to the commit of a release, as you pin every other action. A movi
37
37
  | `principal-key` | the public key files of the principals whose grants a gateway receipt carries, one path on each line; SDK and Claude Code hook receipts need none | |
38
38
  | `log-url` | the URL of the log; the action fetches the log key from it (`verify --log-url`) | |
39
39
  | `log-id` | the id that every tree head must name (`verify --log-id`) | |
40
- | `version` | the `@agent-custody/receipts` version that `npx` runs | `0.16.2` |
40
+ | `version` | the `@agent-custody/receipts` version that `npx` runs | `0.16.3` |
41
41
  | `github-token` | a token that can write pull request comments; an empty value writes the job summary only | `github.token` |
42
42
  | `comment-author` | the login of the account that `github-token` posts as; the action edits only a comment from this account | `github-actions[bot]` |
43
43
 
package/docs/usage.md CHANGED
@@ -125,7 +125,7 @@ At startup the gateway fetches the agent's card from `<url>/.well-known/agent-ca
125
125
 
126
126
  Exactly one of the two. The bearer token comes from the named environment variable, never from the file, and a missing variable fails at startup. Add `"hashOnly": true` for any log run by someone else: the gateway then sends only the leaf hash, sha256 of the receipt envelope with the RFC 6962 prefix, so the log commits to the receipt without ever holding it, and the receipts with their arguments and results stay in `receiptsDir`. The verifier does not change; it hashes the envelope itself. A log that serves several tenants is reached at `<url>/t/<tenant>/`, and each of its tree heads names its log, which a verifier checks with `--log-id`. With a remote log the tree head in each receipt is signed by the log's key, and a verifier must be given that key with `--log-key`. The gateway does not take the log's answer on trust either: the tree head in every append's answer must verify against the log's keys, name the expected log, match the proof's size, and the inclusion proof must place that very leaf under the signed root, all before a pre-committed call is forwarded and before any receipt is handed out; an answer that fails any of it is a refusal. `"keys": ["keys/log.pub"]` pins the log's public keys, `"logId"` the id its heads must carry; without `keys` the log's key document at `/.well-known/agent-custody-log.json` is fetched from the log itself once, on the first append, and pinned. That catches a log that turns dishonest later, not one that is dishonest from the start, so a gateway config with `precommit` and a remote log must list `keys`. When the log rotates its key, add the new public key to `keys`; a gateway that fetched the keys needs a restart. An append that gets no answer within `timeoutMs` (default 10000) counts as unreachable and is retried like a server error, so a log that accepts connections and never answers cannot hold a call forever. If the log does not take a receipt, the gateway keeps the signed receipt in `receipts/outbox/<receiptId>.json` and returns the real outcome of the call to the agent, with the receipt id and `_meta["agent-custody/log-pending"]: true`. The gateway appends the outbox at startup and every 30 seconds, and writes `receipts/<receiptId>.json` when the log takes the receipt. Until then no bundle exists, so no receipt that was never logged is handed out. The table [below](#when-the-log-fails) gives each case. For a tool named in `precommit` the order is reversed, below, and the action never happens. A fact lookup is different: it runs before the policy decides, because the policy decides on it, and only once the intercepted tool is in the grant's scope, so a fact tool must be a read. Naming a fact tool in `precommit` is refused at startup; `"*"` covers the tools the agent calls, not the gateway's own lookups. Every lookup is on the receipt with its arguments. The reference log server is `node src/cli.ts log --file log.jsonl --key keys/log.key --port 8787 --token-env AGENT_CUSTODY_LOG_TOKEN [--log-id <id>] [--tenants tenants.json]`. It serves `POST /append` with `{leaf}` or `{leafHash}` (token required when one is configured), `GET /root?size=N`, `GET /consistency?old=M&new=N`, and `GET /head`; [verification.md](verification.md) says what each proves. `--log-id` writes that id into every tree head. `--tenants` names a JSON file, `{ "acme": { "file": "acme.jsonl", "tokenEnv": "ACME_TOKEN", "logId": "acme-eu" } }`, and each tenant is its own log at `/t/acme/…` with its own token and id; the default log stays at the root paths. With `--hash-only` the server refuses `{leaf}` at append and accepts only `{leafHash}`, so a log run for other people never receives a receipt regardless of the client's configuration; the hosted deployment sets it. With `--db-env DATABASE_URL` the server keeps its logs in Postgres instead of files, and needs the `pg` package beside it: leaves as hashes in one table keyed by tenant, one writer per tenant enforced with an advisory lock so a second instance is safe, tenants and their tokens in tables of their own with tokens stored only as hashes, and rate limits per token (50 appends a second, burst 100, a 64 KB body cap; a refused append answers 429 with `retry-after`, and the gateway's sink retries a few times). Tenants are managed with `log-admin --db-env DATABASE_URL`: `tenant add <id> [--log-id <id>]`, `token add <tenant> --label <text>` (the token is printed once), `token revoke <tenant> <hash-prefix>`, `tenant disable <id>`, `tenant plan <id> <free|team|enterprise>`, and `import --file log.jsonl [--tenant default]` to bring an existing file log in as hashes. Every tenant is on a plan, `free` unless moved: free allows ten thousand appends a calendar month, team a million, enterprise has no allowance. An append past the allowance is refused with 429, the numbers, and a `retry-after` that reaches the start of next month; the gateway behind it then withholds pre-committed calls and financial operations, so a tenant out of quota never acts on those without evidence. Any other call is forwarded, and its receipt waits in the outbox ([below](#when-the-log-fails)). The tenant's own `GET /t/<name>/usage` reports the plan and quota beside the month's appends. The tenant portal, `agent-custody portal --db-env DATABASE_URL --secret-env PORTAL_SECRET --public-url <log url> [--checkpoints-url <url>] [--portal-url <url>] [--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]`, is the self-serve front of the same tables: a team registers with an email, a password (scrypt), and a tenant id and gets the tenant and its first key shown once with the welcome sheet; the dashboard shows appends against the plan, the tree size and root, the latest checkpoint, the log's URLs, keys, and the audit rows; keys are minted and revoked there, recorded as `portal:<email>`; the export command is on the page; and with the three Stripe variables the team plan is bought through Stripe Checkout, the signed webhook moving the plan (`stripe:<event>` in the audit trail) and the customer portal handling cancellation. Sessions are a signed cookie, `SameSite=Strict`, and every write needs a JSON body. Each member has a role (`owner`, `admin`, `reviewer`, `readonly`), an account can turn on TOTP MFA, and the operator can set up single sign-on through the tenant's own OIDC or SAML identity provider with `log-admin sso set`; the [hosted log reference](https://docs.agent-custody.dev/reference/hosted) lists the routes. SAML needs `@node-saml/node-saml` beside the CLI. The compose file runs it as the `portal` service at `PORTAL_HOST`. The root paths serve the tenant `default`, created on first start with `--log-id`, and `--token-env` still works for it. The key that signs tree heads can live in its own process: `agent-custody signer --key keys/log.key --port 8790 --token-env SIGNER_TOKEN` holds it and answers `POST /sign` with the shared secret and `GET /keys` to anyone; the log server then runs with `--signer-url http://signer:8790/ --signer-token-env SIGNER_TOKEN` instead of `--key`, and the process that faces the internet never holds the key. Either way the log serves its keys at `/.well-known/agent-custody-log.json`, current key first and retired keys (`--retired-key old.pub`) after it, so verifiers fetch and pin them with `verify --log-url` and `audit --log-url` rather than receiving a key file from the operator. With `--checkpoint-dir <dir>` the server publishes a signed checkpoint, every `--checkpoint-every` seconds (default 300), for each log whose tree has grown, and every `--checkpoint-heartbeat` seconds (default 21600, six hours) for a log that has not, so a quiet log's latest checkpoint is never more than six hours old and the monitor can tell quiet from stalled, as `<dir>/<tenant>/<treeSize>.json` and `latest.json`, and with a database also as rows; `GET /checkpoints?since=<size>` and `GET /t/<tenant>/checkpoints` list them. Serve the directory read-only from a second host, so the record of what the log signed does not depend on the log's API being up; a verifier who kept an earlier head audits against a later checkpoint with `audit --older <bundle> --newer <checkpoint> --log-url <url>`. With `--admin-token-env ADMIN_TOKEN` (Postgres only) the server also serves the operator's page at `/admin` and its API under `/admin/`: list and create tenants, mint a token that is shown once beside the tenant's welcome sheet, revoke tokens, disable tenants. Everything under `/admin`, the page included, needs the admin token: the browser asks for it (any user name, the token as the password) and an API client sends it as a bearer; a handful of wrong attempts from one address are throttled for a minute. Every change made there or with `log-admin` is recorded: who (the name entered at the browser prompt and the address, `bearer` for an API client, or the user and host for the command line), what (`tenant.add`, `tenant.disable`, `token.add`, `token.revoke`), which tenant, and the detail, never the token itself; the page shows it under Activity, `GET /admin/audit?tenant=&limit=` and `log-admin audit` list it, and a tenant reads their own rows at `GET /t/<name>/audit` with their token. Nothing else is stored by the page. Behind a reverse proxy, start the server with `--trust-proxy` so those per-address limits key on `X-Forwarded-For` instead of on the proxy's own address, and only there, since the header is otherwise the client's to forge. `--public-url` and `--checkpoints-url` fill the sheet in. The witness closes the last gap: `agent-custody witness --key witness.key --log-url <url> --checkpoints-url <url> --out <dir> [--tenant <name>]...` runs on a machine the log's operator does not control, fetches each watched log's latest checkpoint, verifies it against the log's published keys, proves with the log's consistency proof that it extends the last head the witness signed, and countersigns it into `<dir>/<tenant>/<size>.json` and `latest.json`; a checkpoint that does not extend, or a second history at the same size, gets `ALARM.json` instead. Its key document is `<dir>/.well-known/agent-custody-witness.json`. Serve `<dir>` from the witness's own host; verifiers add `--witness-url` (or `--witness-key`) to `audit`, and the newer head must then carry the witness's signature. Two more things an operator needs. `agent-custody log-check --log-url <url> --checkpoints-url <url> [--witness-url <url>] [--tenant <name>]... [--max-lag <seconds>]` is the outside monitor: it verifies the head against the published keys, that the latest checkpoint verifies and keeps up with the head, that the head extends the checkpoint, and, with a witness, that the witness has countersigned, keeps up, and has raised no alarm; it exits 1 on any failure, so cron or a scheduled workflow on a machine that is not the log's turns it into an alert. `GET /health` on the server is the liveness check for a load balancer. And `GET /admin/usage?month=YYYY-MM`, on the admin page and as `/admin/usage.csv`, is the metering: appends per tenant for the month, leaves in total, live tokens, the numbers any invoice rests on. A tenant needs none of that to leave with their evidence: `agent-custody log-export --log-url <url> --tenant <name> --token-env AGENT_CUSTODY_LOG_TOKEN --out <dir>` fetches, with their own token, every leaf hash (`GET /t/<name>/leaves?since=&limit=`, pages of up to ten thousand), the signed head, the published keys, the signed checkpoints, their own usage (`GET /t/<name>/usage?month=`), and the administrative actions on their tenant (`GET /t/<name>/audit`, into `audit.json`), checks that the head and every checkpoint verify against the keys and that the leaves fetched hash to their roots, and writes `log.jsonl` in the format `verify --log` and `audit --log` read, so the export verifies receipts with no server at all. It exits 1 and says what did not add up if anything does not. Both routes answer only to that tenant's token. [deploy/](../../deploy/README.md) runs the server, the signer, Postgres, and the checkpoints host as containers, and [deploy/witness/](../../deploy/witness/) the witness.
127
127
 
128
- `otel`, optional in both the gateway and SDK configs, sends every receipt to the collector you already run as one span over OTLP/HTTP, after the receipt is issued: `"otel": { "url": "http://localhost:4318", "headersEnv": { "x-api-key": "OTEL_KEY" }, "serviceName": "support-agents" }`. The span's trace id is the receipt id, its attributes carry the tool, agent, principal, execution status, policy decision, and log position, and its status is an error only when the upstream failed or errored, since a denial is the policy working. Export is best effort: a collector that is down or refuses costs a line on stderr, never a receipt. Tutorial 18 shows it against a stand-in collector.
128
+ `otel`, optional in both the gateway and SDK configs, sends every receipt to the collector you already run as one span over OTLP/HTTP, after the receipt is issued: `"otel": { "url": "http://localhost:4318", "headersEnv": { "x-api-key": "OTEL_KEY" }, "serviceName": "support-agents" }`. The span's trace id is the receipt id, its attributes carry the tool, agent, principal, execution status, policy decision, and log position, and its status is an error only when the upstream failed or errored, since a denial is the policy working. A door receipt records an inbound request, so its span kind is `SERVER`; every other issuer's span is `CLIENT`. Export is best effort: a collector that is down or refuses costs a line on stderr, never a receipt. Tutorial 18 shows it against a stand-in collector.
129
129
 
130
130
  `splunk`, optional in both configs and usable beside `otel`, sends every receipt to a Splunk HTTP Event Collector as one event: `"splunk": { "url": "https://splunk.example.com:8088", "tokenEnv": "HEC_TOKEN", "index": "agents" }`, with optional `source` (default `agent-custody`), `sourcetype` (default `agent-custody:receipt`), and `host`. The token is read from the named environment variable at startup and never appears in the config. Each event carries `receipt_id`, `tool`, `agent`, `principal`, `status`, `reason`, `policy_decision`, `policy_digest`, `args_digest`, `log_leaf_index`, `log_tree_size`, and `authorization_leaf_index` as plain fields, so a search like `sourcetype="agent-custody:receipt" status=denied` needs no field extraction and every alert leads to the receipt by id. The same rule holds: the event is a copy, the receipt is the evidence, and a collector outage costs a warning. Tutorial 19 shows it.
131
131
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-custody/receipts",
3
- "version": "0.16.2",
3
+ "version": "0.16.3",
4
4
  "mcpName": "io.github.svayatta/agent-custody",
5
5
  "description": "Proof of what your AI agents did. Give your agents real power, without losing control of them: signed, verifiable receipts for tool calls, an MCP gateway with Cedar or Rego policy, and a Merkle transparency log.",
6
6
  "license": "Apache-2.0",