@agent-custody/receipts 0.16.11 → 0.16.12

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, 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 site already on Cloudflare runs the same decision at the edge, as a Worker that receipts to an R2 bucket and the hosted log ([the door as a Cloudflare Worker](docs/door-worker.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)).
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 site already on Cloudflare runs the same decision at the edge, as a Worker that receipts to an R2 bucket and the hosted log ([the door as a Cloudflare Worker](docs/door-worker.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. With `behaviour` in its config the door adds its own behaviour and fingerprint signals to each arrival: seven flags that the policy reads as reasons to ask for a challenge or a grant. Each flag is wrong for some arrivals, and the door refuses nothing because of one ([door signals](docs/door-signals.md), [door error rates](docs/door-error-rates.md)). 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.
@@ -23,7 +23,8 @@ Anyone holding the public keys can verify a receipt offline. The agent is not tr
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
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
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
26
+ - [Door signals](docs/door-signals.md): every field of the arrival fact and of a partner engine's signed verdict, and the door's own behaviour and fingerprint signals, labelled checked, observed, or a claim, with what each does and does not mean, who gets flagged wrongly, and how a policy should read it
27
+ - [Door error rates](docs/door-error-rates.md): how `agent-custody door measure` measures how often each flag of the door's signals is wrong, and the measured rates
27
28
  - [Financial operations](docs/financial-operations.md): durable operation ids, provider idempotency keys, atomic daily budget reservations, and reconciliation receipts for uncertain outcomes
28
29
  - [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
29
30
  - [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
@@ -308,8 +309,12 @@ src/door.ts the door in Node: a reverse proxy in front of your own HTTP s
308
309
  src/door-worker.ts the door as a Cloudflare Worker: its DoorIO from the Worker's bindings (key secret, policy and config variables, R2 and the log), the fetch and cron handlers, Cloudflare Bot Management as an observed fact, and the Durable Object (`DoorNonce`) that keeps Web Bot Auth nonces for every isolate
309
310
  src/object-issuer.ts the receipt issuer over an object store (R2): bundles, authorizations, salts, and the outbox, by the file issuer's rules
310
311
  src/door-form.ts the form protector: the script the door serves at /.well-known/agent-custody-door/form.js, from its challenge config
312
+ src/door-error-rates.ts the door's error rates from labelled receipts: the labels file, the questions, verified reading, per-kind rows with Wilson intervals
313
+ src/door-test-set.ts the published labelled test set: arrivals of twelve known kinds decided by the door core in memory, with their labels
311
314
  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
312
315
  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 in a store (one process's memory unless the door is given another); a did:key keyid checked against its own key
316
+ src/door-signals.ts the door's behaviour and fingerprint signals: the header fingerprint, the TLS fingerprint, the pace, the navigation, and the form report, each a pure function of one observation and the history of its source; the bounded history tracker; the seven flags
317
+ src/door-measure.ts the measure behind `door measure` and `door labels`: replays labelled arrivals through the signal functions of door-signals.ts and counts how often each flag is wrong
313
318
  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
314
319
  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
315
320
  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
@@ -329,11 +334,12 @@ src/verify.ts offline verification, the human-readable report, and the audi
329
334
  src/claude-init.ts `init claude-code`: the agent key, the observe-mode config, the starter policy, and the three hooks merged into the settings file with absolute paths
330
335
  src/deny-report.ts `report`: verifies the receipts of an SDK config and lists the calls the policy would have denied
331
336
  templates/ the starter Cedar policy that `init claude-code` copies (shipped in the package)
332
- src/cli.ts keygen, grant, gateway, door, egress, egress draft-policy, acs, init, report, hook, serve, log, prune, verify, reveal, audit, policy simulate
337
+ src/cli.ts keygen, grant, gateway, door, door measure, door labels, egress, egress draft-policy, acs, init, report, hook, serve, log, prune, verify, reveal, audit, policy simulate
333
338
  src/retention.ts pruning the log: leaves become their hashes, bundles are removed, proofs survive
334
339
  src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
335
340
  tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
336
- 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), the door Worker's build for workerd (`build-door-worker.ts`, also wrangler's build command), 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`)
341
+ 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), the door Worker's build for workerd (`build-door-worker.ts`, also wrangler's build command), 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`), and the measured blocks of the door error-rate page (`door-error-rates-page.ts`)
342
+ labelled/ the labelled arrivals that `door measure` reads, their manifest, the measured results, and the counts that the adapter scripts wrote (docs/door-error-rates.md)
337
343
  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
338
344
  test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
339
345
  adapter tests against the real packages, and tests that run every policy in docs/policies.md and site/guide/egress-policies.md
@@ -342,10 +348,13 @@ docs/ tutorials, usage (gateway), codex-recovery (live demo), appro
342
348
 
343
349
  ## Plan
344
350
 
345
- 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.
351
+ 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 step is AP2 mandates as a passport.
346
352
 
347
353
  **Done**
348
354
 
355
+ - Demo 1, the refund, API leg (svayatta/pm#41): `bun run demo:refund` (tutorial 59) puts the door in front of a shop's refund API and pays through two gateway lanes. A passport holder is paid once; over the limit or with a forged passport it is refused at the door; an agent with no passport waits for a person to approve the exact refund; an auditor verifies every receipt and finds a refund made in Stripe directly. It runs cold twice in a row in the tests. The phone leg waits for the tells service and the Twilio hook.
356
+ - Door error rates (svayatta/pm#12): `agent-custody door error-rates` scores door receipts against a labels file (from an operator, a built test set, or passed challenges), one row per kind and label source with a 95% Wilson interval, never pooled, and only over receipts that verify. `--test-set` builds the published labelled set of twelve kinds in memory. [door-error-rates.md](docs/door-error-rates.md) publishes the first rates with the method: `verified` went to the genuine agents only, and a program that presents nothing is `unknown` like a person, which credentials alone cannot change. Tutorial 58.
357
+ - The door's behaviour and fingerprint signals: with `behaviour` in the door config, each arrival fact also carries `fingerprint` (what the `User-Agent` states, a hash of the header order, and the TLS fingerprint that your proxy or Cloudflare gives) and `behaviour` (the pace of the source, whether a page load came before a write, and the form report of the form protector script). Nine flags mark an arrival that does not look or act as its `User-Agent` states. The door refuses nothing because of a signal: only the policy reads them, as reasons to ask for a challenge or a grant. The history behind them is one process's memory, and the form report is a claim. `agent-custody door measure` replays a labelled set through the same functions, and `agent-custody door labels` exports one from a door's own receipts ([door signals](docs/door-signals.md), [door error rates](docs/door-error-rates.md), tutorials 60 and 61).
349
358
  - The door as a Cloudflare Worker (#387): `deploy/door/cloudflare-worker` puts the door's own decision loop at Cloudflare's edge. The key is a Worker secret; the config and the policy are variables; receipts go to an R2 bucket and the hosted log. A request that can change something reaches the origin only once both have its authorization. A safe request's receipt waits in the bucket's outbox when the log is down, and a cron trigger appends it. Web Bot Auth and grants are checked as at any door, with each nonce in a Durable Object that every isolate reaches, so a signature replayed to another isolate is refused; Cloudflare Bot Management enters as an observed fact. The bundle `wrangler deploy` builds is tested in workerd, and its receipts verify with `agent-custody verify` ([the door as a Cloudflare Worker](docs/door-worker.md), tutorial 56). A run against Cloudflare itself is still to be recorded.
350
359
  - did:key identity on grants (#255): a grant may name its agent by the did:key of its Ed25519 key (`grant --agent-key agent.pub --did-key`). The door checks that the identifier decodes and agrees with the grant's `agentKey`; a grant that does not is `claimed`, one that does is `verified` with the did:key as the agent ([a did:key agent](docs/door.md#a-did-key-agent), tutorial 55). The gateway and the three verifiers run the same check (#405): the gateway refuses such a grant when the session opens, and a verifier fails `delegation signature (principal key)`. A request signature (RFC 9421) whose `keyid` is the did:key binds the grant to its sender (#406, [a did:key signature](docs/door.md#a-did-key-signature)).
351
360
  - The form protector (svayatta/pm#14): with `challenge` configured, the door serves `/.well-known/agent-custody-door/form.js`, and one script tag on a page puts the Turnstile or hCaptcha widget in its same-origin POST forms. The script sends each form with the token in the door's header and follows the answer as a form post would, so a static site's form reaches its backend with a receipt id, and a direct post with no token is refused ([protecting a form with one line](docs/door.md#protecting-a-form-with-one-line), tutorial 54).
package/dist/check.js CHANGED
@@ -215,6 +215,18 @@ export function checkDoorConfig(configPath) {
215
215
  add("error", "partner", `${p.keyFile}: ${e instanceof Error ? e.message : String(e)}`);
216
216
  }
217
217
  }
218
+ if (cfg.behaviour) {
219
+ const b = cfg.behaviour;
220
+ add("ok", "behaviour", `the door's own signals are context.facts.arrival.fingerprint and context.facts.arrival.behaviour; they are signals, the door refuses nothing because of them, and the history behind them is this process's memory`);
221
+ if (b.tlsHeader)
222
+ add("warn", "behaviour", `the TLS fingerprint is read from the ${b.tlsHeader} header: make sure that the proxy in front of the door overwrites it on every request, or a client can send its own`);
223
+ else
224
+ add("ok", "behaviour", "no behaviour.tlsHeader: the arrival fact has no TLS fingerprint");
225
+ if (!cfg.challenge)
226
+ add("ok", "behaviour", "no challenge: the door serves no form protector script, so no arrival carries a form report");
227
+ if (cfg.authz)
228
+ add("ok", "behaviour", "authz mode: the proxy selects the headers of a check, so the header fingerprint has no order and no mismatch flag; forward referer, accept, sec-fetch-*, and the form report header for the other signals");
229
+ }
218
230
  const dir = writableAncestor(cfg.receiptsDir);
219
231
  if (!dir)
220
232
  add("error", "paths", `${cfg.receiptsDir} cannot be created: no writable directory above it`);
package/dist/cli.js CHANGED
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { hostname, userInfo } from "node:os";
2
+ import { hostname, tmpdir, userInfo } from "node:os";
3
3
  import { captureKeyFrom, getAt, pathText, restorePaths, setAt } from "./capture.js";
4
4
  import { saltsFileFor } from "./retention.js";
5
5
  import { parseArgs } from "node:util";
6
- import { closeSync, constants as fsConstants, existsSync, fchmodSync, openSync, readFileSync, readdirSync, writeFileSync, writeSync } from "node:fs";
6
+ import { closeSync, constants as fsConstants, createReadStream, existsSync, fchmodSync, mkdtempSync, openSync, readFileSync, readdirSync, rmSync, writeFileSync, writeSync } from "node:fs";
7
+ import { createInterface } from "node:readline";
7
8
  import { dirname, join, resolve } from "node:path";
8
9
  import { loadAcsGuardianConfig, loadConfig, loadDoorConfig, loadEgressConfig, loadSdkConfig } from "./config.js";
9
10
  import { dsseVerify, generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
@@ -23,6 +24,9 @@ import { checkCompleteness, formatCompleteness, githubSource, stripeSource } fro
23
24
  import { evmChain } from "./anchor-evm.js";
24
25
  import { serveHttp } from "./gateway-http.js";
25
26
  import { createDoorHost, serveDoor } from "./door.js";
27
+ import { challengeLabels, doorErrorRates, formatErrorRates, parseLabels, readDoorArrivals } from "./door-error-rates.js";
28
+ import { buildDoorTestSet } from "./door-test-set.js";
29
+ import { createMeasure, formatMeasure, labelsFromReceipts, parseLabelledRecord } from "./door-measure.js";
26
30
  import { createEgressHost, serveEgress } from "./egress.js";
27
31
  import { draftEgressPolicy } from "./egress-draft.js";
28
32
  import { createAcsGuardian } from "./acs.js";
@@ -65,7 +69,41 @@ function untilStopped() {
65
69
  }
66
70
  const SERVICES = new Set(["serve", "witness", "signer", "portal", "log", "console", "door", "egress"]);
67
71
  /** a command that waits for untilStopped(); a stdio gateway runs until its input closes and keeps the default signal behaviour */
68
- const runsUntilStopped = (cmd, args) => !!cmd && ((SERVICES.has(cmd) && !(cmd === "egress" && args[0] === "draft-policy")) || (cmd === "gateway" && (args.includes("--http") || args.includes("--a2a"))));
72
+ const runsUntilStopped = (cmd, args) => !!cmd && ((SERVICES.has(cmd) && !(cmd === "egress" && args[0] === "draft-policy") && !(cmd === "door" && ["error-rates", "measure", "labels"].includes(args[0] ?? ""))) || (cmd === "gateway" && (args.includes("--http") || args.includes("--a2a"))));
73
+ async function doorErrorRatesCommand(args) {
74
+ const { values } = parseArgs({ args, options: { receipts: { type: "string" }, labels: { type: "string" }, "issuer-key": { type: "string", multiple: true }, "principal-key": { type: "string", multiple: true }, log: { type: "string" }, "log-key": { type: "string", multiple: true }, "challenge-labels": { type: "boolean", default: false }, "test-set": { type: "boolean", default: false }, "per-kind": { type: "string", default: "200" }, json: { type: "boolean", default: false } } });
75
+ let read;
76
+ let labels;
77
+ if (values["test-set"]) {
78
+ const perKind = Number(values["per-kind"]);
79
+ if (!Number.isInteger(perKind) || perKind < 1 || perKind > 10_000)
80
+ throw new Error("--per-kind takes a whole number from 1 to 10000");
81
+ const dir = mkdtempSync(join(tmpdir(), "agent-custody-door-test-set-"));
82
+ try {
83
+ const set = await buildDoorTestSet(dir, { perKind });
84
+ read = readDoorArrivals(set.receiptsDir, { issuerKeys: [set.doorKey], principalKeys: [set.principalKey] });
85
+ labels = set.labels;
86
+ }
87
+ finally {
88
+ rmSync(dir, { recursive: true, force: true });
89
+ }
90
+ }
91
+ else {
92
+ if (!values.receipts || !values.labels || !values["issuer-key"]?.length)
93
+ throw new Error("door error-rates needs --receipts <dir> --labels <labels.jsonl> --issuer-key <door.pub>, or --test-set");
94
+ read = readDoorArrivals(values.receipts, { issuerKeys: values["issuer-key"].map(loadPublicKey), principalKeys: (values["principal-key"] ?? []).map(loadPublicKey), logKeys: (values["log-key"] ?? []).map(loadPublicKey), ...(values.log ? { logFile: values.log } : {}) });
95
+ labels = parseLabels(readFileSync(values.labels, "utf8"));
96
+ if (values["challenge-labels"])
97
+ labels = [...labels, ...challengeLabels(read.arrivals, labels.map((l) => l.receiptId))];
98
+ }
99
+ const { rows, unmatched } = doorErrorRates(read.arrivals, labels);
100
+ for (const s of read.skipped)
101
+ console.error(`skipped ${s.file}: ${s.reason}`);
102
+ if (unmatched.length)
103
+ console.error(`${unmatched.length} label(s) name a receipt that was not read or did not verify, and are not scored`);
104
+ process.stdout.write(values.json ? JSON.stringify({ rows, skipped: read.skipped, unmatched }, null, 2) + "\n" : formatErrorRates(rows));
105
+ return 0;
106
+ }
69
107
  /** `90s`, `10m`, or `1h`, in seconds. */
70
108
  function durationSeconds(text) {
71
109
  const m = /^(\d+)([smh])$/.exec(text.trim());
@@ -123,6 +161,27 @@ const USAGE = `agent-custody <command>
123
161
  origin or refused with 403, and receipted either way; GET /.well-known/agent-custody-door.
124
162
  With "authz": true in the config it relays nothing and answers nginx auth_request and
125
163
  Envoy ext_authz checks instead: 200 with the receipt headers, or 403
164
+ door error-rates --receipts <dir> --labels <labels.jsonl> --issuer-key <door.pub>... [--principal-key <pub>]...
165
+ [--log <log.jsonl>] [--log-key <pub>]... [--challenge-labels] [--json]
166
+ door error-rates --test-set [--per-kind 200] [--json]
167
+ the credential signals: how often the door's class is wrong for each kind of arrival, from
168
+ labelled receipts, with a 95% interval; never pooled across kinds. --test-set builds the published
169
+ labelled set in memory and scores it. Receipts that do not verify are skipped (door-error-rates.md).
170
+ Use it when you have receipts and know what each arrival was
171
+ door measure <labelled.jsonl>... [--json]
172
+ the behaviour and fingerprint flags: how often each flag is wrong on labelled arrivals. For each set
173
+ and flag, the false-positive rate on humans and the detection rate on automated clients, per session
174
+ and per arrival, each with a 95% Wilson interval. Replays each recorded session through the door's
175
+ own functions. Use it when you have a labelled set: a recording, a public dataset, or the output of
176
+ door labels
177
+ door labels --receipts <dir> --issuer-key <door.pub>... [--principal-key <pub>]... [--log-key <pub>]... [--log <log.jsonl>] [--set own-door]
178
+ [--receipt-ids] [--out <file>]
179
+ a labelled set from your own door's verified receipts, for door measure: an arrival that passed the
180
+ challenge is human, a verified agent's arrival is automated, the rest are left out. Each line holds
181
+ the label and the flags only: no path, address, agent name, header, or time. It uploads nothing. A
182
+ verified agent's receipt verifies only with the key of the principal that signed its grant.
183
+ --receipt-ids adds each receipt's id, and the file is then also a labels file for door error-rates.
184
+ Use it when you have receipts and no labels of your own
126
185
  egress --config <egress.json> [--port 8791] [--host 127.0.0.1]
127
186
  the egress witness: a forward proxy (CONNECT and plain HTTP, no TLS interception) for a
128
187
  locked-down agent's calls that do not go to the gateway. Each agent proves itself with its own
@@ -454,6 +513,60 @@ async function main(argv) {
454
513
  return 0;
455
514
  }
456
515
  case "door": {
516
+ if (rest[0] === "error-rates")
517
+ return doorErrorRatesCommand(rest.slice(1));
518
+ if (rest[0] === "measure") {
519
+ const { values, positionals } = parseArgs({ args: rest.slice(1), allowPositionals: true, options: { json: { type: "boolean", default: false } } });
520
+ if (!positionals.length)
521
+ throw new Error("door measure needs at least one labelled set: door measure <labelled.jsonl>... [--json]");
522
+ const m = createMeasure();
523
+ for (const file of positionals) {
524
+ let line = 0;
525
+ for await (const text of createInterface({ input: createReadStream(file), crlfDelay: Infinity })) {
526
+ line++;
527
+ if (!text.trim())
528
+ continue;
529
+ try {
530
+ m.add(parseLabelledRecord(text));
531
+ }
532
+ catch (e) {
533
+ throw new Error(`${file}:${line}: ${e instanceof Error ? e.message : String(e)}`);
534
+ }
535
+ }
536
+ }
537
+ const result = m.result();
538
+ console.log(values.json ? JSON.stringify(result, null, 2) : formatMeasure(result));
539
+ return result.sets.length ? 0 : 1;
540
+ }
541
+ if (rest[0] === "labels") {
542
+ const { values } = parseArgs({ args: rest.slice(1), options: { receipts: { type: "string" }, "issuer-key": { type: "string", multiple: true }, "principal-key": { type: "string", multiple: true }, "log-key": { type: "string", multiple: true }, log: { type: "string" }, set: { type: "string", default: "own-door" }, "receipt-ids": { type: "boolean", default: false }, out: { type: "string" } } });
543
+ if (!values.receipts || !values["issuer-key"]?.length)
544
+ throw new Error("door labels needs --receipts <dir> --issuer-key <door.pub>");
545
+ const keys = { issuerKeys: values["issuer-key"].map(loadPublicKey), principalKeys: (values["principal-key"] ?? []).map(loadPublicKey), logKeys: (values["log-key"] ?? []).map(loadPublicKey), ...(values.log ? { logFile: values.log } : {}) };
546
+ const predicates = [];
547
+ let unverified = 0;
548
+ for (const file of receiptFiles(values.receipts)) {
549
+ try {
550
+ const checked = verifyBundle(JSON.parse(readFileSync(file, "utf8")), keys);
551
+ if (checked.ok && checked.statement)
552
+ predicates.push(checked.statement.predicate);
553
+ else
554
+ unverified++;
555
+ }
556
+ catch {
557
+ unverified++;
558
+ }
559
+ }
560
+ const labels = labelsFromReceipts(predicates, values.set, { receiptIds: values["receipt-ids"] });
561
+ const text = labels.records.map((r) => JSON.stringify(r)).join("\n") + (labels.records.length ? "\n" : "");
562
+ if (values.out)
563
+ writeFileSync(values.out, text);
564
+ else
565
+ process.stdout.write(text);
566
+ const count = (label) => labels.records.filter((r) => r.label === label).length;
567
+ console.error(`door labels: ${labels.read} door receipt(s) read, ${unverified} file(s) skipped (not a receipt that verifies with these keys${unverified && !values["principal-key"]?.length ? "; a verified agent's receipt needs --principal-key" : ""}); ${count("human")} human (challenge passed), ${count("automated")} automated (verified agent), ${labels.unlabelled} without a label, ${labels.noSignals} without signals (the door had no "behaviour" config). Nothing was uploaded: the output is yours to inspect and to send or not`);
568
+ return labels.records.length ? 0 : 1;
569
+ }
457
570
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, port: { type: "string", default: "8780" }, host: { type: "string", default: "127.0.0.1" } } });
458
571
  if (!values.config)
459
572
  throw new Error("door needs --config");
package/dist/config.d.ts CHANGED
@@ -466,6 +466,9 @@ export declare const DoorConfigSchema: z.ZodObject<{
466
466
  maxInFlight: z.ZodDefault<z.ZodNumber>;
467
467
  maxResponseBytes: z.ZodDefault<z.ZodNumber>;
468
468
  }, z.core.$strip>>;
469
+ behaviour: z.ZodOptional<z.ZodObject<{
470
+ tlsHeader: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
471
+ }, z.core.$strict>>;
469
472
  receiptsDir: z.ZodString;
470
473
  logFile: z.ZodOptional<z.ZodString>;
471
474
  log: z.ZodOptional<z.ZodObject<{
package/dist/config.js CHANGED
@@ -349,6 +349,18 @@ export const DoorConfigSchema = z.object({
349
349
  /** the largest answer the door reads. Default 16 KiB */
350
350
  maxResponseBytes: z.number().int().positive().default(16 * 1024),
351
351
  }).optional(),
352
+ /**
353
+ * The door's own behavioural and fingerprint signals (door-signals.ts): the header fingerprint, the TLS fingerprint,
354
+ * the pace, the navigation, and the form report. Present, even empty, it adds `fingerprint` and `behaviour` to the
355
+ * arrival fact. They are signals for the policy to read; the door refuses nothing because of them.
356
+ */
357
+ behaviour: z.strictObject({
358
+ /**
359
+ * The request header in which your proxy puts the client's JA4 TLS fingerprint. The proxy must overwrite the
360
+ * header on every request, or a client can send its own. Needs `trustProxy`
361
+ */
362
+ tlsHeader: z.string().regex(/^[A-Za-z0-9-]{1,64}$/, "a header name has letters, digits, and hyphens").transform((h) => h.toLowerCase()).optional(),
363
+ }).optional(),
352
364
  receiptsDir: z.string(),
353
365
  logFile: z.string().optional(),
354
366
  log: LogSchema.optional(),
@@ -357,6 +369,7 @@ export const DoorConfigSchema = z.object({
357
369
  capture: CaptureSchema.optional(),
358
370
  captureKeyEnv: z.string().min(1).optional(),
359
371
  }).refine(hasOneLog, oneLog).refine((c) => new Set(c.routes.map((r) => r.name)).size === c.routes.length, { message: "route names must be unique" })
372
+ .refine((c) => !c.behaviour?.tlsHeader || c.trustProxy, { path: ["behaviour", "tlsHeader"], message: "behaviour.tlsHeader needs trustProxy: true, since only a proxy in front of the door sees the TLS handshake; without one the header is the client's" })
360
373
  .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" })
361
374
  .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" })
362
375
  .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" });
package/dist/door-app.js CHANGED
@@ -113,7 +113,7 @@ export function door(config, options = {}) {
113
113
  if (cfg.authz)
114
114
  throw new Error("the in-process door passes an allowed request to the app it runs in; authz is for the door answering nginx or Envoy checks (`agent-custody door`)");
115
115
  const core = createDoorCore(cfg, { ...options, autoFlush: options.autoFlush ?? true }, MIDDLEWARE_FRAMEWORK);
116
- const script = cfg.challenge ? formScript(cfg.challenge) : null;
116
+ const script = cfg.challenge ? formScript(cfg.challenge, !!cfg.behaviour) : null;
117
117
  const middleware = (req, res, next) => {
118
118
  // the script is public and the same for every arrival: served, not decided or receipted
119
119
  if (script && req.method === "GET" && (req.url ?? "").split("?")[0] === FORM_SCRIPT_PATH) {
@@ -6,6 +6,7 @@ import { type Delegation } from "./delegation.ts";
6
6
  import type { Issuer } from "./issue.ts";
7
7
  import { type FlushResult } from "./receipt-pending.ts";
8
8
  import { type NonceStore, type SignatureCheck, type SignedRequest } from "./web-bot-auth.ts";
9
+ import { type ArrivalBehaviour, type ArrivalFingerprint, type TlsObservation } from "./door-signals.ts";
9
10
  import { type ArrivalPartner } from "./door-partner.ts";
10
11
  import type { AuthorizationBundle, ReceiptPredicate } from "./receipt.ts";
11
12
  export declare const DOOR_VERSION = "0.1.0";
@@ -55,6 +56,10 @@ export interface Arrival {
55
56
  challenge?: ArrivalChallenge;
56
57
  /** what became of the question to the partner engine, when the door asks one about this route; absent otherwise, and from `classifyArrival` alone. The verdict itself is the `partner` fact, present only when `outcome` is `verified` */
57
58
  partner?: ArrivalPartner;
59
+ /** what the request and its connection look like, when the door has `behaviour` configured; absent otherwise, and from `classifyArrival` alone. Signals, never a verdict (door-signals.ts) */
60
+ fingerprint?: ArrivalFingerprint;
61
+ /** how the source acts over time, when the door has `behaviour` configured; absent otherwise, and from `classifyArrival` alone */
62
+ behaviour?: ArrivalBehaviour;
58
63
  }
59
64
  /**
60
65
  * The outcome of a human challenge. `passed`: the provider confirmed the token, so the provider judged a person present
@@ -190,6 +195,13 @@ export interface DoorRequest {
190
195
  headers: IncomingHttpHeaders;
191
196
  /** every value of each field, as Node keeps them; read for an HTTP message signature */
192
197
  headersDistinct?: Record<string, string[] | undefined>;
198
+ /** names and values in turn, in the order received, as Node keeps them; read for the header fingerprint */
199
+ rawHeaders?: string[] | undefined;
200
+ /** what the host knows of the client's connection (a Worker reads it from `request.cf`); never read from a header */
201
+ transport?: {
202
+ secure?: boolean;
203
+ tls?: TlsObservation;
204
+ } | undefined;
193
205
  socket: {
194
206
  remoteAddress?: string | undefined;
195
207
  };
@@ -291,7 +303,7 @@ export interface DoorCore {
291
303
  * `context.facts.<name>`. A name the door uses itself (`arrival`, `partner`) is refused.
292
304
  */
293
305
  decide(req: DoorRequest, receiptId: string, read: ((max: number) => Promise<BodyRead>) | null, framework?: string, observed?: Record<string, ObservedFact>): Promise<DoorDecision>;
294
- /** a header the door consumed and never passes on: the grant (and `Authorization` when it carried it), the declared agent, the challenge token */
306
+ /** a header the door consumed and never passes on: the grant (and `Authorization` when it carried it), the declared agent, the challenge token, and with `behaviour` the form report */
295
307
  consumed(name: string, req: DoorRequest, arrival: Arrival): boolean;
296
308
  /** writes the receipt; null when it could not be written, after saying why on stderr */
297
309
  record(d: DoorDecision, execution: Execution): Promise<{
package/dist/door-core.js CHANGED
@@ -5,6 +5,7 @@ import { decodeDelegation, delegationValidAt, grantChainDigests, verifyDelegatio
5
5
  import { parseGrantHeader, GRANT_HEADER } from "./grant-header.js";
6
6
  import { ReceiptPending } from "./receipt-pending.js";
7
7
  import { createWebBotAuthVerifier, normalizeAuthority } from "./web-bot-auth.js";
8
+ import { createHistoryTracker, createSeenCounter, fingerprintKey, FORM_REPORT_HEADER, historySource, observationOf, signalsOf } from "./door-signals.js";
8
9
  import { createPartnerEngine, PARTNER_FACT, PARTNER_TOOL } from "./door-partner.js";
9
10
  import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
10
11
  export const DOOR_VERSION = "0.1.0";
@@ -399,6 +400,9 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
399
400
  const issuedBy = { kind: "door", keyid: issuer.keyid, version: DOOR_VERSION, framework };
400
401
  const precommit = new Set(cfg.precommit);
401
402
  const rates = createRateTracker(undefined, { sweepTimer: io.timers });
403
+ // one process's memory, like the rate counts
404
+ const history = cfg.behaviour ? createHistoryTracker() : undefined;
405
+ const fingerprints = createSeenCounter();
402
406
  const webBotAuth = cfg.webBotAuth ? createWebBotAuthVerifier(cfg.webBotAuth, f, undefined, io.nonceStore) : undefined;
403
407
  const partner = cfg.partner ? createPartnerEngine(cfg.partner, f) : undefined;
404
408
  // The policy, re-read on every arrival, as the gateway does; a text that does not parse is refused and the policy in
@@ -444,7 +448,17 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
444
448
  const { arrival, delegation, signer } = classifyArrival(req, trusted, route, !!cfg.trustProxy, timestamp, signature, revoked);
445
449
  const checkedAgent = arrival.class === "verified";
446
450
  const by = checkedAgent ? "agent" : "remote";
447
- arrival.rate = { by, ...rates.hit(`${by}:${checkedAgent ? arrival.subject : arrival.remote}`) };
451
+ const source = `${by}:${checkedAgent ? arrival.subject : arrival.remote}`;
452
+ arrival.rate = { by, ...rates.hit(source) };
453
+ if (history) {
454
+ // in authz mode the proxy selects the headers of a check, so the header set is not the client's
455
+ const seen = observationOf(req, performance.now(), method, arrival.path, { trustProxy: !!cfg.trustProxy, ...(cfg.behaviour?.tlsHeader ? { tlsHeader: cfg.behaviour.tlsHeader } : {}), own: challengeHeader ? [challengeHeader] : [], partialHeaders: !!cfg.authz });
456
+ const signals = signalsOf(seen, history.record(checkedAgent ? source : `remote:${historySource(arrival.remote)}`, seen));
457
+ const key = fingerprintKey(signals.fingerprint);
458
+ if (key !== undefined)
459
+ signals.fingerprint.seen = fingerprints.hit(key, seen.at);
460
+ Object.assign(arrival, signals);
461
+ }
448
462
  if (cfg.challenge && challengeHeader) {
449
463
  const c = cfg.challenge;
450
464
  const token = req.headers[challengeHeader];
@@ -590,7 +604,7 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
590
604
  release: () => void (inFlight -= 1),
591
605
  busy: () => json(503, { "retry-after": "1" }, { error: `the door is handling ${cfg.maxInFlight} requests; this one was not read, decided, or relayed. Retry` }),
592
606
  decide,
593
- consumed: (name, req, arrival) => name === GRANT_HEADER || name === AGENT_HEADER || name === challengeHeader ||
607
+ consumed: (name, req, arrival) => name === GRANT_HEADER || name === AGENT_HEADER || name === challengeHeader || (!!history && name === FORM_REPORT_HEADER) ||
594
608
  // the grant travelled in Authorization: it is the door's credential, not the origin's
595
609
  (name === "authorization" && arrival.grant !== "absent" && !req.headers[GRANT_HEADER]),
596
610
  async record(d, execution) {
@@ -0,0 +1,102 @@
1
+ import { z } from "zod";
2
+ import type { PublicKeyRef } from "./crypto.ts";
3
+ import { type Arrival } from "./door-core.ts";
4
+ import { type LabelQuestion } from "./door-measure.ts";
5
+ /**
6
+ * Where a label came from. `test-set`: the arrival was built to be that kind, so the label is true by construction.
7
+ * `operator`: a person who knows the traffic said so. `challenge`: derived from a passed Turnstile or hCaptcha check,
8
+ * so it carries the provider's own error rate. `door`: the door's own check said so (a verified agent, from
9
+ * `door labels`). Such a label is good for the flags and never for a question about `class`, which would score the
10
+ * door against itself; its `validFor` says so.
11
+ */
12
+ export declare const LABEL_SOURCES: readonly ["test-set", "operator", "challenge", "door"];
13
+ export type LabelSource = (typeof LABEL_SOURCES)[number];
14
+ /**
15
+ * One line of a labels file: what one receipt's arrival really was. A line that `door labels --receipt-ids` exports is
16
+ * also a record of `door measure`, so the fields of that format are accepted here and not read.
17
+ */
18
+ export declare const DoorLabelSchema: z.ZodObject<{
19
+ receiptId: z.ZodString;
20
+ kind: z.ZodString;
21
+ automated: z.ZodBoolean;
22
+ genuine: z.ZodNullable<z.ZodBoolean>;
23
+ source: z.ZodEnum<{
24
+ challenge: "challenge";
25
+ door: "door";
26
+ operator: "operator";
27
+ "test-set": "test-set";
28
+ }>;
29
+ validFor: z.ZodOptional<z.ZodArray<z.ZodEnum<{
30
+ agent: "agent";
31
+ "behaviour.form.fast": "behaviour.form.fast";
32
+ "behaviour.form.noInput": "behaviour.form.noInput";
33
+ "behaviour.navigation.directWrite": "behaviour.navigation.directWrite";
34
+ "behaviour.timing.regular": "behaviour.timing.regular";
35
+ "fingerprint.headers.fetchInvalid": "fingerprint.headers.fetchInvalid";
36
+ "fingerprint.headers.hintsMismatch": "fingerprint.headers.hintsMismatch";
37
+ "fingerprint.headers.mismatch": "fingerprint.headers.mismatch";
38
+ "fingerprint.tls.knownTool": "fingerprint.tls.knownTool";
39
+ "fingerprint.tls.mismatch": "fingerprint.tls.mismatch";
40
+ verified: "verified";
41
+ }>>>;
42
+ set: z.ZodOptional<z.ZodString>;
43
+ session: z.ZodOptional<z.ZodString>;
44
+ label: z.ZodOptional<z.ZodEnum<{
45
+ automated: "automated";
46
+ human: "human";
47
+ }>>;
48
+ labelSource: z.ZodOptional<z.ZodString>;
49
+ flags: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodBoolean>>;
50
+ }, z.core.$strict>;
51
+ export type DoorLabel = z.infer<typeof DoorLabelSchema>;
52
+ export interface DoorQuestion {
53
+ id: LabelQuestion;
54
+ asks: string;
55
+ /** what an error is for this question */
56
+ wrong: string;
57
+ applies: (label: DoorLabel) => boolean;
58
+ isWrong: (arrival: Arrival, label: DoorLabel) => boolean;
59
+ }
60
+ /** The questions the door's signals answer today. Each is scored only on the labels it applies to. */
61
+ export declare const DOOR_QUESTIONS: DoorQuestion[];
62
+ export interface ErrorRateRow {
63
+ question: DoorQuestion["id"];
64
+ kind: string;
65
+ source: LabelSource;
66
+ arrivals: number;
67
+ wrong: number;
68
+ rate: number;
69
+ /** the Wilson score interval at 95% */
70
+ low: number;
71
+ high: number;
72
+ }
73
+ /** The Wilson score interval for `errors` in `n` at 95%. With no errors it still gives an upper bound, which is the honest figure for a small sample. */
74
+ export declare function wilson(errors: number, n: number): {
75
+ low: number;
76
+ high: number;
77
+ };
78
+ export interface DoorArrivals {
79
+ arrivals: Map<string, Arrival>;
80
+ skipped: {
81
+ file: string;
82
+ reason: string;
83
+ }[];
84
+ }
85
+ /** The arrival fact of every door receipt in `dir` that verifies under `issuerKeys`, the principal keys that sign its grants, and the log, when given. Anything else is skipped with its reason. */
86
+ export declare function readDoorArrivals(dir: string, opts: {
87
+ issuerKeys: PublicKeyRef[];
88
+ principalKeys?: PublicKeyRef[];
89
+ logKeys?: PublicKeyRef[];
90
+ logFile?: string;
91
+ }): DoorArrivals;
92
+ /** A labels file: one JSON object per line, as `DoorLabelSchema`. A line that does not parse throws with its number; a receipt labelled twice throws. */
93
+ export declare function parseLabels(text: string): DoorLabel[];
94
+ /** Labels from passed challenges, for receipts that have no label: the provider judged a person present. They carry the provider's error rate. */
95
+ export declare function challengeLabels(arrivals: Map<string, Arrival>, labelled: Iterable<string>): DoorLabel[];
96
+ /** One row per question, label source, and kind. `unmatched` lists labels whose receipt was not read or did not verify. */
97
+ export declare function doorErrorRates(arrivals: Map<string, Arrival>, labels: DoorLabel[]): {
98
+ rows: ErrorRateRow[];
99
+ unmatched: string[];
100
+ };
101
+ /** The rows as Markdown: a table per question, each row one kind from one label source. */
102
+ export declare function formatErrorRates(rows: ErrorRateRow[]): string;