@agent-custody/receipts 0.16.11 → 0.16.13
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 +23 -5
- package/dist/admission.d.ts +62 -0
- package/dist/admission.js +101 -0
- package/dist/check.js +42 -3
- package/dist/cli.js +179 -7
- package/dist/config.d.ts +6 -1
- package/dist/config.js +21 -2
- package/dist/door-app.js +1 -1
- package/dist/door-core.d.ts +81 -3
- package/dist/door-core.js +113 -13
- package/dist/door-error-rates.d.ts +102 -0
- package/dist/door-error-rates.js +178 -0
- package/dist/door-form.d.ts +7 -2
- package/dist/door-form.js +52 -4
- package/dist/door-measure.d.ts +153 -0
- package/dist/door-measure.js +325 -0
- package/dist/door-signals.d.ts +414 -0
- package/dist/door-signals.js +555 -0
- package/dist/door-test-set.d.ts +43 -0
- package/dist/door-test-set.js +117 -0
- package/dist/door-worker.d.ts +20 -1
- package/dist/door-worker.js +30 -2
- package/dist/door.js +18 -2
- package/dist/erc8004-link.d.ts +24 -0
- package/dist/erc8004-link.js +11 -0
- package/dist/erc8004.d.ts +26 -0
- package/dist/erc8004.js +208 -0
- package/dist/index.d.ts +17 -3
- package/dist/index.js +9 -2
- package/dist/lock.d.ts +5 -0
- package/dist/lock.js +1 -1
- package/dist/log-store.d.ts +3 -1
- package/dist/log-store.js +2 -2
- package/dist/passport.d.ts +53 -0
- package/dist/passport.js +87 -0
- package/dist/portal.d.ts +14 -0
- package/dist/portal.js +102 -0
- package/dist/registry.d.ts +145 -0
- package/dist/registry.js +294 -0
- package/dist/web-bot-auth.d.ts +9 -3
- package/dist/web-bot-auth.js +31 -4
- package/docs/admission-lists.md +89 -0
- package/docs/agent-registry.md +173 -0
- package/docs/door-error-rates.md +490 -0
- package/docs/door-languages.md +3 -1
- package/docs/door-middleware.md +6 -1
- package/docs/door-quickstart.md +2 -2
- package/docs/door-signals.md +112 -2
- package/docs/door-worker.md +14 -1
- package/docs/door.md +37 -6
- package/docs/github-action.md +2 -2
- package/docs/tutorials.md +7 -0
- package/docs/usage.md +1 -1
- package/package.json +2 -1
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,
|
|
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, a Web Bot Auth signature checked against the signer's key directory, or a passport from an [agent registry](docs/agent-registry.md) you trust under its agent's signature, 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,10 @@ 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
|
|
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
|
+
- [The agent registry](docs/agent-registry.md): an organisation registers its agents on the portal by their did:keys and the portal signs each a passport; a door that holds only the registry's key admits them as `verified`, and its policy reads their owner and capabilities
|
|
28
|
+
- [Admission lists](docs/admission-lists.md): a site's own named lists of agents (by registry entry, ERC-8004 identity, or key) that its door matches and its policy reads, and the registry's search by capability that fills them
|
|
29
|
+
- [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
30
|
- [Financial operations](docs/financial-operations.md): durable operation ids, provider idempotency keys, atomic daily budget reservations, and reconciliation receipts for uncertain outcomes
|
|
28
31
|
- [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
32
|
- [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 +311,17 @@ src/door.ts the door in Node: a reverse proxy in front of your own HTTP s
|
|
|
308
311
|
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
312
|
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
313
|
src/door-form.ts the form protector: the script the door serves at /.well-known/agent-custody-door/form.js, from its challenge config
|
|
314
|
+
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
|
|
315
|
+
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
316
|
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
317
|
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
|
|
318
|
+
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
|
|
319
|
+
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
|
|
320
|
+
src/admission.ts admission lists: the lists file, compiled for lookup, and the match of a verified arrival against it by registry entry, ERC-8004 identity, or subject
|
|
321
|
+
src/erc8004.ts the ERC-8004 link check: reads ownerOf and tokenURI at one block over JSON-RPC, fetches the registration file (never from an internal address), and matches its registrations and DID service
|
|
322
|
+
src/erc8004-link.ts the ERC-8004 link's names and shapes, apart from the chain reads, so a door needs nothing that reads a chain
|
|
323
|
+
src/passport.ts the agent registry's passport and its check: what a door needs, apart from the registry's table, so the door imports no database code
|
|
324
|
+
src/registry.ts the agent registry: registrations with the key's proof, the registry's table, passport issuance, and its key document
|
|
313
325
|
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
326
|
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
327
|
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 +341,12 @@ src/verify.ts offline verification, the human-readable report, and the audi
|
|
|
329
341
|
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
342
|
src/deny-report.ts `report`: verifies the receipts of an SDK config and lists the calls the policy would have denied
|
|
331
343
|
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
|
|
344
|
+
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
345
|
src/retention.ts pruning the log: leaves become their hashes, bundles are removed, proofs survive
|
|
334
346
|
src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
|
|
335
347
|
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`)
|
|
348
|
+
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`)
|
|
349
|
+
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
350
|
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
351
|
test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
|
|
339
352
|
adapter tests against the real packages, and tests that run every policy in docs/policies.md and site/guide/egress-policies.md
|
|
@@ -342,10 +355,15 @@ docs/ tutorials, usage (gateway), codex-recovery (live demo), appro
|
|
|
342
355
|
|
|
343
356
|
## Plan
|
|
344
357
|
|
|
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
|
|
358
|
+
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
359
|
|
|
347
360
|
**Done**
|
|
348
361
|
|
|
362
|
+
- Capability index and admission lists (svayatta/pm#22): the registry answers `GET /registry/agents?capability=` with its active agents, a page at a time. A door with `admissionLists` reads a site's named lists of agents, each entry a registry entry, an ERC-8004 identity, or a verified subject, and records in `arrival.admission` the lists a verified arrival's agent is on and the digest of the lists in force; the policy decides what each list means, and the decision is a receipt. A claim, or a passport the signer is not bound to, puts no agent on a list. The file is re-read when it changes, and a broken one leaves the lists in force ([admission lists](docs/admission-lists.md), tutorial 64).
|
|
363
|
+
- The agent registry (svayatta/pm#21): with a registry key, `agent-custody portal` also runs an agent registry. A tenant registers each agent by its own Ed25519 did:key, with the key's proof that it holds it, a contact, capabilities, and an expiry, and the portal signs it a passport that lives a day. The registry publishes its key document at `/.well-known/agent-custody-registry.json`, each agent's entry and key, and fresh passports to anyone. A door with the registry's key in `trustedRegistryKeys` admits an agent that sends its passport and signs the request with that did:key, covering the passport, the method, the path, and a digest of the body, as `verified`, with no setup per agent and no call to the registry; the passport's entry is in the arrival fact for the policy, and under another key it is `wrong-sender`. Revocation stops new passports and reaches the door when the last one expires. With an RPC per chain, the registry also links an agent to its ERC-8004 identity, only when the token's registration file lists the agent's did:key, and the passport carries the link for the door's policy; the door reads no chain ([the agent registry](docs/agent-registry.md), tutorials 62 and 63).
|
|
364
|
+
- 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.
|
|
365
|
+
- 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.
|
|
366
|
+
- 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
367
|
- 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
368
|
- 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
369
|
- 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).
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export declare const LIST_NAME: RegExp;
|
|
3
|
+
export declare const MAX_LISTS = 64;
|
|
4
|
+
export declare const MAX_LIST_ENTRIES = 10000;
|
|
5
|
+
/**
|
|
6
|
+
* One spelling for a URL, so that a list entry matches whatever case, default port, or trailing slash it was written
|
|
7
|
+
* with: a bare origin becomes `URL.origin` (how the door names a Web Bot Auth agent), any other URL its `href`. A value
|
|
8
|
+
* that is not an http(s) URL, such as a did:key, is left as it is.
|
|
9
|
+
*/
|
|
10
|
+
export declare function canonicalAgent(v: string): string;
|
|
11
|
+
/** A registry's URL as its passports name it: `URL.href`, so `https://APP.example:443` is `https://app.example/`. */
|
|
12
|
+
export declare const canonicalRegistry: (v: string) => string;
|
|
13
|
+
declare const EntrySchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
14
|
+
registry: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
15
|
+
agentId: z.ZodString;
|
|
16
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
17
|
+
erc8004: z.ZodObject<{
|
|
18
|
+
agentRegistry: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
19
|
+
agentId: z.ZodString;
|
|
20
|
+
}, z.core.$strict>;
|
|
21
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
22
|
+
agent: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
23
|
+
}, z.core.$strict>]>;
|
|
24
|
+
export type AdmissionEntry = z.infer<typeof EntrySchema>;
|
|
25
|
+
export declare const AdmissionListsSchema: z.ZodObject<{
|
|
26
|
+
lists: z.ZodRecord<z.ZodString, z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
|
|
27
|
+
registry: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
28
|
+
agentId: z.ZodString;
|
|
29
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
30
|
+
erc8004: z.ZodObject<{
|
|
31
|
+
agentRegistry: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
32
|
+
agentId: z.ZodString;
|
|
33
|
+
}, z.core.$strict>;
|
|
34
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
35
|
+
agent: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
36
|
+
}, z.core.$strict>]>>>;
|
|
37
|
+
}, z.core.$strict>;
|
|
38
|
+
/** The lists in force, compiled for lookup, with the sha256 of the file they came from. */
|
|
39
|
+
export interface AdmissionLists {
|
|
40
|
+
digest: string;
|
|
41
|
+
names: string[];
|
|
42
|
+
match(identity: ArrivalIdentity): string[];
|
|
43
|
+
}
|
|
44
|
+
/** What the door checked about an arrival, as far as a list can name it. */
|
|
45
|
+
export interface ArrivalIdentity {
|
|
46
|
+
/** the arrival's class; only `verified` matches anything */
|
|
47
|
+
class: string;
|
|
48
|
+
subject: string;
|
|
49
|
+
/** the passport, when its outcome is `verified` */
|
|
50
|
+
passport?: {
|
|
51
|
+
outcome: string;
|
|
52
|
+
registry?: string;
|
|
53
|
+
agentId?: string;
|
|
54
|
+
erc8004?: {
|
|
55
|
+
agentRegistry: string;
|
|
56
|
+
agentId: string;
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/** Parses and compiles a lists file; throws, naming what is wrong, when it is not one. */
|
|
61
|
+
export declare function compileAdmissionLists(text: string): AdmissionLists;
|
|
62
|
+
export {};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Admission lists: a site's own named lists of agents ("partners", "blocked"), which its Cedar policy references. The
|
|
2
|
+
// door matches each arrival against them and records the names of the lists the arrival's agent is on, with a digest
|
|
3
|
+
// of the lists in force, in the arrival fact; the policy decides what each list means, and the receipt records the
|
|
4
|
+
// decision. A list names agents only by what the door checks: a registry entry or an ERC-8004 identity from a verified
|
|
5
|
+
// passport, or the subject of a verified arrival (a did:key, a Web Bot Auth origin, or the agent a trusted grant names).
|
|
6
|
+
// An arrival the door did not verify is on no list, so a claim cannot put an agent on one, nor take it off a block list
|
|
7
|
+
// the policy reads as "forbid unless listed".
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { sha256Hex } from "./crypto.js";
|
|
10
|
+
import { ERC8004_REGISTRY } from "./erc8004-link.js";
|
|
11
|
+
import { AGENT_ID } from "./passport.js";
|
|
12
|
+
export const LIST_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
13
|
+
export const MAX_LISTS = 64;
|
|
14
|
+
export const MAX_LIST_ENTRIES = 10_000;
|
|
15
|
+
/**
|
|
16
|
+
* One spelling for a URL, so that a list entry matches whatever case, default port, or trailing slash it was written
|
|
17
|
+
* with: a bare origin becomes `URL.origin` (how the door names a Web Bot Auth agent), any other URL its `href`. A value
|
|
18
|
+
* that is not an http(s) URL, such as a did:key, is left as it is.
|
|
19
|
+
*/
|
|
20
|
+
export function canonicalAgent(v) {
|
|
21
|
+
if (!/^https?:\/\//i.test(v))
|
|
22
|
+
return v;
|
|
23
|
+
try {
|
|
24
|
+
const u = new URL(v);
|
|
25
|
+
return u.pathname === "/" && !u.search && !u.hash && !u.username && !u.password ? u.origin : u.href;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return v;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** A registry's URL as its passports name it: `URL.href`, so `https://APP.example:443` is `https://app.example/`. */
|
|
32
|
+
export const canonicalRegistry = (v) => {
|
|
33
|
+
try {
|
|
34
|
+
return new URL(v).href;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return v;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const EntrySchema = z.union([
|
|
41
|
+
/** a registry entry: the registry's URL, as its passports name it, and the agent's id there; it survives key rotation */
|
|
42
|
+
z.object({ registry: z.string().url().max(200).transform(canonicalRegistry), agentId: z.string().regex(AGENT_ID) }).strict(),
|
|
43
|
+
/** an ERC-8004 identity, as a verified passport's registry checked it on chain */
|
|
44
|
+
z.object({ erc8004: z.object({ agentRegistry: z.string().regex(ERC8004_REGISTRY).transform((r) => r.toLowerCase()), agentId: z.string().regex(/^(0|[1-9][0-9]{0,77})$/) }).strict() }).strict(),
|
|
45
|
+
/** the subject of a verified arrival: a did:key, a Web Bot Auth signature agent's origin, or a grant's agent */
|
|
46
|
+
z.object({ agent: z.string().min(1).max(200).transform(canonicalAgent) }).strict(),
|
|
47
|
+
]);
|
|
48
|
+
export const AdmissionListsSchema = z.object({
|
|
49
|
+
lists: z.record(z.string(), z.array(EntrySchema).max(MAX_LIST_ENTRIES)).superRefine((lists, ctx) => {
|
|
50
|
+
const names = Object.keys(lists);
|
|
51
|
+
if (names.length > MAX_LISTS)
|
|
52
|
+
ctx.addIssue({ code: "custom", message: `at most ${MAX_LISTS} lists` });
|
|
53
|
+
for (const name of names)
|
|
54
|
+
if (!LIST_NAME.test(name))
|
|
55
|
+
ctx.addIssue({ code: "custom", path: [name], message: `"${name.slice(0, 40)}": a list name is lowercase letters, digits, and . _ -, at most 64 characters` });
|
|
56
|
+
}),
|
|
57
|
+
}).strict();
|
|
58
|
+
const keyOf = (e) => ("registry" in e ? `registry ${e.registry} ${e.agentId}` : "erc8004" in e ? `erc8004 ${e.erc8004.agentRegistry} ${e.erc8004.agentId}` : `agent ${e.agent}`);
|
|
59
|
+
/** Parses and compiles a lists file; throws, naming what is wrong, when it is not one. */
|
|
60
|
+
export function compileAdmissionLists(text) {
|
|
61
|
+
let raw;
|
|
62
|
+
try {
|
|
63
|
+
raw = JSON.parse(text);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
throw new Error("the admission lists are not JSON");
|
|
67
|
+
}
|
|
68
|
+
const parsed = AdmissionListsSchema.safeParse(raw);
|
|
69
|
+
if (!parsed.success)
|
|
70
|
+
throw new Error(`the admission lists are not valid: ${parsed.error.issues.slice(0, 5).map((i) => `${i.path.join(".") || "file"} ${i.message}`).join("; ")}`);
|
|
71
|
+
const index = new Map();
|
|
72
|
+
for (const [name, entries] of Object.entries(parsed.data.lists)) {
|
|
73
|
+
for (const e of entries) {
|
|
74
|
+
const k = keyOf(e);
|
|
75
|
+
const on = index.get(k) ?? new Set();
|
|
76
|
+
on.add(name);
|
|
77
|
+
index.set(k, on);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const names = Object.keys(parsed.data.lists).sort();
|
|
81
|
+
return {
|
|
82
|
+
digest: sha256Hex(text),
|
|
83
|
+
names,
|
|
84
|
+
match(a) {
|
|
85
|
+
if (a.class !== "verified")
|
|
86
|
+
return [];
|
|
87
|
+
const keys = [`agent ${canonicalAgent(a.subject)}`];
|
|
88
|
+
const p = a.passport;
|
|
89
|
+
if (p?.outcome === "verified" && p.registry && p.agentId) {
|
|
90
|
+
keys.push(`registry ${canonicalRegistry(p.registry)} ${p.agentId}`);
|
|
91
|
+
if (p.erc8004)
|
|
92
|
+
keys.push(`erc8004 ${p.erc8004.agentRegistry.toLowerCase()} ${p.erc8004.agentId}`);
|
|
93
|
+
}
|
|
94
|
+
const on = new Set();
|
|
95
|
+
for (const k of keys)
|
|
96
|
+
for (const name of index.get(k) ?? [])
|
|
97
|
+
on.add(name);
|
|
98
|
+
return [...on].sort();
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
package/dist/check.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// config, the keys, the policy, the grant, the environment, and the paths; --connect also starts the upstreams, which
|
|
3
3
|
// is where tool-name collisions and unreachable servers show up, and compares every tool name the config mentions with
|
|
4
4
|
// the tools the upstreams actually offer.
|
|
5
|
+
import { compileAdmissionLists } from "./admission.js";
|
|
5
6
|
import * as cedar from "@cedar-policy/cedar-wasm/nodejs";
|
|
6
7
|
import { accessSync, constants, existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
7
8
|
import { tmpdir } from "node:os";
|
|
@@ -137,10 +138,27 @@ export function checkDoorConfig(configPath) {
|
|
|
137
138
|
add("error", "principal keys", `${f}: ${e instanceof Error ? e.message : String(e)}`);
|
|
138
139
|
}
|
|
139
140
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
141
|
+
let registries = 0;
|
|
142
|
+
for (const f of cfg.trustedRegistryKeys) {
|
|
143
|
+
try {
|
|
144
|
+
loadPublicKey(f);
|
|
145
|
+
registries++;
|
|
146
|
+
}
|
|
147
|
+
catch (e) {
|
|
148
|
+
add("error", "registry keys", `${f}: ${e instanceof Error ? e.message : String(e)}`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const signatures = !!cfg.webBotAuth && cfg.webBotAuth.agents.length > 0;
|
|
152
|
+
if (cfg.trustedPrincipalKeys.length === 0 && cfg.trustedRegistryKeys.length === 0 && !signatures)
|
|
153
|
+
add("warn", "principal keys", "no trusted principal keys, registry keys, or signature agents: no arrival can be verified, every one is claimed or unknown");
|
|
154
|
+
else if (cfg.trustedPrincipalKeys.length > 0 && principals === cfg.trustedPrincipalKeys.length)
|
|
143
155
|
add("ok", "principal keys", `${principals} trusted principal key${principals === 1 ? "" : "s"} load`);
|
|
156
|
+
if (cfg.trustedRegistryKeys.length > 0) {
|
|
157
|
+
if (!cfg.webBotAuth)
|
|
158
|
+
add("error", "registry keys", "trustedRegistryKeys needs webBotAuth: a passport admits an agent only on a request its did:key signed, and webBotAuth checks that signature");
|
|
159
|
+
else if (registries === cfg.trustedRegistryKeys.length)
|
|
160
|
+
add("ok", "registry keys", `${registries} trusted registry key${registries === 1 ? "" : "s"} load`);
|
|
161
|
+
}
|
|
144
162
|
if (!existsSync(cfg.policyFile))
|
|
145
163
|
add("error", "policy", `${cfg.policyFile} does not exist`);
|
|
146
164
|
else {
|
|
@@ -215,6 +233,18 @@ export function checkDoorConfig(configPath) {
|
|
|
215
233
|
add("error", "partner", `${p.keyFile}: ${e instanceof Error ? e.message : String(e)}`);
|
|
216
234
|
}
|
|
217
235
|
}
|
|
236
|
+
if (cfg.behaviour) {
|
|
237
|
+
const b = cfg.behaviour;
|
|
238
|
+
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`);
|
|
239
|
+
if (b.tlsHeader)
|
|
240
|
+
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`);
|
|
241
|
+
else
|
|
242
|
+
add("ok", "behaviour", "no behaviour.tlsHeader: the arrival fact has no TLS fingerprint");
|
|
243
|
+
if (!cfg.challenge)
|
|
244
|
+
add("ok", "behaviour", "no challenge: the door serves no form protector script, so no arrival carries a form report");
|
|
245
|
+
if (cfg.authz)
|
|
246
|
+
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");
|
|
247
|
+
}
|
|
218
248
|
const dir = writableAncestor(cfg.receiptsDir);
|
|
219
249
|
if (!dir)
|
|
220
250
|
add("error", "paths", `${cfg.receiptsDir} cannot be created: no writable directory above it`);
|
|
@@ -242,6 +272,15 @@ export function checkDoorConfig(configPath) {
|
|
|
242
272
|
}
|
|
243
273
|
else if (cfg.trustedPrincipalKeys.length > 0)
|
|
244
274
|
add("warn", "revokedGrants", "no revokedGrants file: a grant cannot be revoked at this door before it expires");
|
|
275
|
+
if (cfg.admissionLists) {
|
|
276
|
+
try {
|
|
277
|
+
const lists = compileAdmissionLists(readFileSync(cfg.admissionLists, "utf8"));
|
|
278
|
+
add("ok", "admissionLists", `${lists.names.length} admission list(s) in ${cfg.admissionLists}: ${lists.names.join(", ") || "none"}`);
|
|
279
|
+
}
|
|
280
|
+
catch (e) {
|
|
281
|
+
add("error", "admissionLists", `${cfg.admissionLists}: ${e instanceof Error ? e.message : String(e)}; the door refuses to start, and a file that stops reading while it runs leaves the lists in force`);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
245
284
|
return out;
|
|
246
285
|
}
|
|
247
286
|
/** True when the file is an egress witness config: it names agents, and no upstream or origin. */
|
package/dist/cli.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
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
|
-
import { dsseVerify, generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
|
|
10
|
+
import { dsseVerify, generateKeyPair, keyidOf, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
|
|
11
|
+
import { createPrivateKey, createPublicKey } from "node:crypto";
|
|
10
12
|
import { DEFAULT_APPROVAL_LIFETIME_SECONDS } from "./approval.js";
|
|
11
13
|
import { approvalRequestExpiresAt, approveApprovalRequest, denyApprovalRequest, listApprovalRequests, readApprovalRequest } from "./approval-requests.js";
|
|
12
14
|
import { createDelegation, decodeDelegation, delegateFrom, grantDigest } from "./delegation.js";
|
|
@@ -16,6 +18,8 @@ import { postgresResolver, serveLog } from "./log-sink.js";
|
|
|
16
18
|
import { importLogFile, PostgresTenancy } from "./log-store.js";
|
|
17
19
|
import { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoints.js";
|
|
18
20
|
import { connectSigner, fetchLogKeys, localSigner, serveSigner } from "./signer.js";
|
|
21
|
+
import { registrationProof } from "./registry.js";
|
|
22
|
+
import { createErc8004Resolver } from "./erc8004.js";
|
|
19
23
|
import { fetchWitnessKeys, Witness } from "./witness.js";
|
|
20
24
|
import { checkLog, formatLogCheck } from "./log-check.js";
|
|
21
25
|
import { Anchor, ANCHOR_CHAINS, resolveAnchorChain } from "./anchor.js";
|
|
@@ -23,6 +27,9 @@ import { checkCompleteness, formatCompleteness, githubSource, stripeSource } fro
|
|
|
23
27
|
import { evmChain } from "./anchor-evm.js";
|
|
24
28
|
import { serveHttp } from "./gateway-http.js";
|
|
25
29
|
import { createDoorHost, serveDoor } from "./door.js";
|
|
30
|
+
import { challengeLabels, doorErrorRates, formatErrorRates, parseLabels, readDoorArrivals } from "./door-error-rates.js";
|
|
31
|
+
import { buildDoorTestSet } from "./door-test-set.js";
|
|
32
|
+
import { createMeasure, formatMeasure, labelsFromReceipts, parseLabelledRecord } from "./door-measure.js";
|
|
26
33
|
import { createEgressHost, serveEgress } from "./egress.js";
|
|
27
34
|
import { draftEgressPolicy } from "./egress-draft.js";
|
|
28
35
|
import { createAcsGuardian } from "./acs.js";
|
|
@@ -65,7 +72,41 @@ function untilStopped() {
|
|
|
65
72
|
}
|
|
66
73
|
const SERVICES = new Set(["serve", "witness", "signer", "portal", "log", "console", "door", "egress"]);
|
|
67
74
|
/** 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"))));
|
|
75
|
+
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"))));
|
|
76
|
+
async function doorErrorRatesCommand(args) {
|
|
77
|
+
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 } } });
|
|
78
|
+
let read;
|
|
79
|
+
let labels;
|
|
80
|
+
if (values["test-set"]) {
|
|
81
|
+
const perKind = Number(values["per-kind"]);
|
|
82
|
+
if (!Number.isInteger(perKind) || perKind < 1 || perKind > 10_000)
|
|
83
|
+
throw new Error("--per-kind takes a whole number from 1 to 10000");
|
|
84
|
+
const dir = mkdtempSync(join(tmpdir(), "agent-custody-door-test-set-"));
|
|
85
|
+
try {
|
|
86
|
+
const set = await buildDoorTestSet(dir, { perKind });
|
|
87
|
+
read = readDoorArrivals(set.receiptsDir, { issuerKeys: [set.doorKey], principalKeys: [set.principalKey] });
|
|
88
|
+
labels = set.labels;
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
rmSync(dir, { recursive: true, force: true });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
if (!values.receipts || !values.labels || !values["issuer-key"]?.length)
|
|
96
|
+
throw new Error("door error-rates needs --receipts <dir> --labels <labels.jsonl> --issuer-key <door.pub>, or --test-set");
|
|
97
|
+
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 } : {}) });
|
|
98
|
+
labels = parseLabels(readFileSync(values.labels, "utf8"));
|
|
99
|
+
if (values["challenge-labels"])
|
|
100
|
+
labels = [...labels, ...challengeLabels(read.arrivals, labels.map((l) => l.receiptId))];
|
|
101
|
+
}
|
|
102
|
+
const { rows, unmatched } = doorErrorRates(read.arrivals, labels);
|
|
103
|
+
for (const s of read.skipped)
|
|
104
|
+
console.error(`skipped ${s.file}: ${s.reason}`);
|
|
105
|
+
if (unmatched.length)
|
|
106
|
+
console.error(`${unmatched.length} label(s) name a receipt that was not read or did not verify, and are not scored`);
|
|
107
|
+
process.stdout.write(values.json ? JSON.stringify({ rows, skipped: read.skipped, unmatched }, null, 2) + "\n" : formatErrorRates(rows));
|
|
108
|
+
return 0;
|
|
109
|
+
}
|
|
69
110
|
/** `90s`, `10m`, or `1h`, in seconds. */
|
|
70
111
|
function durationSeconds(text) {
|
|
71
112
|
const m = /^(\d+)([smh])$/.exec(text.trim());
|
|
@@ -123,6 +164,27 @@ const USAGE = `agent-custody <command>
|
|
|
123
164
|
origin or refused with 403, and receipted either way; GET /.well-known/agent-custody-door.
|
|
124
165
|
With "authz": true in the config it relays nothing and answers nginx auth_request and
|
|
125
166
|
Envoy ext_authz checks instead: 200 with the receipt headers, or 403
|
|
167
|
+
door error-rates --receipts <dir> --labels <labels.jsonl> --issuer-key <door.pub>... [--principal-key <pub>]...
|
|
168
|
+
[--log <log.jsonl>] [--log-key <pub>]... [--challenge-labels] [--json]
|
|
169
|
+
door error-rates --test-set [--per-kind 200] [--json]
|
|
170
|
+
the credential signals: how often the door's class is wrong for each kind of arrival, from
|
|
171
|
+
labelled receipts, with a 95% interval; never pooled across kinds. --test-set builds the published
|
|
172
|
+
labelled set in memory and scores it. Receipts that do not verify are skipped (door-error-rates.md).
|
|
173
|
+
Use it when you have receipts and know what each arrival was
|
|
174
|
+
door measure <labelled.jsonl>... [--json]
|
|
175
|
+
the behaviour and fingerprint flags: how often each flag is wrong on labelled arrivals. For each set
|
|
176
|
+
and flag, the false-positive rate on humans and the detection rate on automated clients, per session
|
|
177
|
+
and per arrival, each with a 95% Wilson interval. Replays each recorded session through the door's
|
|
178
|
+
own functions. Use it when you have a labelled set: a recording, a public dataset, or the output of
|
|
179
|
+
door labels
|
|
180
|
+
door labels --receipts <dir> --issuer-key <door.pub>... [--principal-key <pub>]... [--log-key <pub>]... [--log <log.jsonl>] [--set own-door]
|
|
181
|
+
[--receipt-ids] [--out <file>]
|
|
182
|
+
a labelled set from your own door's verified receipts, for door measure: an arrival that passed the
|
|
183
|
+
challenge is human, a verified agent's arrival is automated, the rest are left out. Each line holds
|
|
184
|
+
the label and the flags only: no path, address, agent name, header, or time. It uploads nothing. A
|
|
185
|
+
verified agent's receipt verifies only with the key of the principal that signed its grant.
|
|
186
|
+
--receipt-ids adds each receipt's id, and the file is then also a labels file for door error-rates.
|
|
187
|
+
Use it when you have receipts and no labels of your own
|
|
126
188
|
egress --config <egress.json> [--port 8791] [--host 127.0.0.1]
|
|
127
189
|
the egress witness: a forward proxy (CONNECT and plain HTTP, no TLS interception) for a
|
|
128
190
|
locked-down agent's calls that do not go to the gateway. Each agent proves itself with its own
|
|
@@ -209,7 +271,13 @@ const USAGE = `agent-custody <command>
|
|
|
209
271
|
log-admin --db-env NAME user mfa-reset <email> turns MFA off for a portal account that lost its authenticator
|
|
210
272
|
portal --db-env NAME --secret-env NAME --public-url <log url> [--checkpoints-url <url>] [--portal-url <url>] [--port 8792] [--host 127.0.0.1]
|
|
211
273
|
[--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]
|
|
274
|
+
[--registry-key-env NAME | --registry-signer-url <url> [--registry-signer-token-env NAME]] [--passport-seconds 86400]
|
|
275
|
+
[--erc8004-rpc-env <chain id>=NAME]... [--ipfs-gateway <https url>] [--erc8004-recheck-seconds 3600]
|
|
212
276
|
the tenant portal: register, first key, usage against plan, keys, billing, export
|
|
277
|
+
with a registry key, also the agent registry: register agents, sign their passports
|
|
278
|
+
with an RPC per chain, it links agents to ERC-8004 identities it checks on chain
|
|
279
|
+
registry proof --key <agent.key> --registry <portal url> --tenant <id>
|
|
280
|
+
prints { agent, proof }: the agent's did:key and its signature for registering it
|
|
213
281
|
log-admin --db-env NAME import --file <log.jsonl> [--tenant default] copies a file log into the database as hashes
|
|
214
282
|
portal-followup --db-env NAME --secret-env NAME --mail-key-env NAME --mail-from <address> [--mail-notify <address>] [--mail-reply-to <address>]
|
|
215
283
|
[--signer <name>] [--signer-role <role>] [--portal-url <url>] [--dry-run]
|
|
@@ -454,6 +522,60 @@ async function main(argv) {
|
|
|
454
522
|
return 0;
|
|
455
523
|
}
|
|
456
524
|
case "door": {
|
|
525
|
+
if (rest[0] === "error-rates")
|
|
526
|
+
return doorErrorRatesCommand(rest.slice(1));
|
|
527
|
+
if (rest[0] === "measure") {
|
|
528
|
+
const { values, positionals } = parseArgs({ args: rest.slice(1), allowPositionals: true, options: { json: { type: "boolean", default: false } } });
|
|
529
|
+
if (!positionals.length)
|
|
530
|
+
throw new Error("door measure needs at least one labelled set: door measure <labelled.jsonl>... [--json]");
|
|
531
|
+
const m = createMeasure();
|
|
532
|
+
for (const file of positionals) {
|
|
533
|
+
let line = 0;
|
|
534
|
+
for await (const text of createInterface({ input: createReadStream(file), crlfDelay: Infinity })) {
|
|
535
|
+
line++;
|
|
536
|
+
if (!text.trim())
|
|
537
|
+
continue;
|
|
538
|
+
try {
|
|
539
|
+
m.add(parseLabelledRecord(text));
|
|
540
|
+
}
|
|
541
|
+
catch (e) {
|
|
542
|
+
throw new Error(`${file}:${line}: ${e instanceof Error ? e.message : String(e)}`);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
const result = m.result();
|
|
547
|
+
console.log(values.json ? JSON.stringify(result, null, 2) : formatMeasure(result));
|
|
548
|
+
return result.sets.length ? 0 : 1;
|
|
549
|
+
}
|
|
550
|
+
if (rest[0] === "labels") {
|
|
551
|
+
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" } } });
|
|
552
|
+
if (!values.receipts || !values["issuer-key"]?.length)
|
|
553
|
+
throw new Error("door labels needs --receipts <dir> --issuer-key <door.pub>");
|
|
554
|
+
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 } : {}) };
|
|
555
|
+
const predicates = [];
|
|
556
|
+
let unverified = 0;
|
|
557
|
+
for (const file of receiptFiles(values.receipts)) {
|
|
558
|
+
try {
|
|
559
|
+
const checked = verifyBundle(JSON.parse(readFileSync(file, "utf8")), keys);
|
|
560
|
+
if (checked.ok && checked.statement)
|
|
561
|
+
predicates.push(checked.statement.predicate);
|
|
562
|
+
else
|
|
563
|
+
unverified++;
|
|
564
|
+
}
|
|
565
|
+
catch {
|
|
566
|
+
unverified++;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
const labels = labelsFromReceipts(predicates, values.set, { receiptIds: values["receipt-ids"] });
|
|
570
|
+
const text = labels.records.map((r) => JSON.stringify(r)).join("\n") + (labels.records.length ? "\n" : "");
|
|
571
|
+
if (values.out)
|
|
572
|
+
writeFileSync(values.out, text);
|
|
573
|
+
else
|
|
574
|
+
process.stdout.write(text);
|
|
575
|
+
const count = (label) => labels.records.filter((r) => r.label === label).length;
|
|
576
|
+
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`);
|
|
577
|
+
return labels.records.length ? 0 : 1;
|
|
578
|
+
}
|
|
457
579
|
const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, port: { type: "string", default: "8780" }, host: { type: "string", default: "127.0.0.1" } } });
|
|
458
580
|
if (!values.config)
|
|
459
581
|
throw new Error("door needs --config");
|
|
@@ -731,10 +853,60 @@ async function main(argv) {
|
|
|
731
853
|
console.log(`${values["dry-run"] ? "would send" : "sent"} ${r.sent.length}, skipped ${r.skipped.length} (operator's own), failed ${r.failed.length}${r.sent.length ? `: ${r.sent.join(", ")}` : ""}`);
|
|
732
854
|
return r.failed.length ? 1 : 0;
|
|
733
855
|
}
|
|
856
|
+
case "registry": {
|
|
857
|
+
const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { key: { type: "string" }, registry: { type: "string" }, tenant: { type: "string" } } });
|
|
858
|
+
if (positionals[0] !== "proof")
|
|
859
|
+
throw new Error("usage: registry proof --key <agent.key> --registry <portal url> --tenant <id>");
|
|
860
|
+
if (!values.key || !values.registry || !values.tenant)
|
|
861
|
+
throw new Error("registry proof needs --key, --registry, and --tenant");
|
|
862
|
+
// the URL as the portal names itself: with its trailing slash
|
|
863
|
+
console.log(JSON.stringify(registrationProof(loadPrivateKey(values.key), values.registry.replace(/\/?$/, "/"), values.tenant)));
|
|
864
|
+
return 0;
|
|
865
|
+
}
|
|
734
866
|
case "portal": {
|
|
735
|
-
const { values } = parseArgs({ args: rest, options: { "db-env": { type: "string" }, "secret-env": { type: "string" }, "public-url": { type: "string" }, "checkpoints-url": { type: "string" }, "portal-url": { type: "string" }, port: { type: "string", default: "8792" }, host: { type: "string", default: "127.0.0.1" }, "stripe-key-env": { type: "string" }, "stripe-webhook-env": { type: "string" }, "stripe-price-team": { type: "string" }, "mail-key-env": { type: "string" }, "mail-from": { type: "string" }, "mail-notify": { type: "string" }, "mail-reply-to": { type: "string" }, "github-client-id": { type: "string" }, "github-secret-env": { type: "string" }, "google-client-id": { type: "string" }, "google-secret-env": { type: "string" }, "trust-proxy": { type: "boolean", default: false } } });
|
|
867
|
+
const { values } = parseArgs({ args: rest, options: { "db-env": { type: "string" }, "secret-env": { type: "string" }, "public-url": { type: "string" }, "checkpoints-url": { type: "string" }, "portal-url": { type: "string" }, port: { type: "string", default: "8792" }, host: { type: "string", default: "127.0.0.1" }, "stripe-key-env": { type: "string" }, "stripe-webhook-env": { type: "string" }, "stripe-price-team": { type: "string" }, "mail-key-env": { type: "string" }, "mail-from": { type: "string" }, "mail-notify": { type: "string" }, "mail-reply-to": { type: "string" }, "github-client-id": { type: "string" }, "github-secret-env": { type: "string" }, "google-client-id": { type: "string" }, "google-secret-env": { type: "string" }, "trust-proxy": { type: "boolean", default: false }, "registry-key-env": { type: "string" }, "registry-signer-url": { type: "string" }, "registry-signer-token-env": { type: "string" }, "passport-seconds": { type: "string" }, "erc8004-rpc-env": { type: "string", multiple: true }, "ipfs-gateway": { type: "string" }, "erc8004-recheck-seconds": { type: "string" } } });
|
|
736
868
|
if (!values["db-env"] || !values["secret-env"] || !values["public-url"])
|
|
737
869
|
throw new Error("portal needs --db-env, --secret-env, and --public-url");
|
|
870
|
+
// the registry's key is its own, never the log's: in the environment, or held by a signer process
|
|
871
|
+
let registry;
|
|
872
|
+
if (values["registry-key-env"] && values["registry-signer-url"])
|
|
873
|
+
throw new Error("give --registry-key-env or --registry-signer-url, not both");
|
|
874
|
+
if (values["registry-key-env"] || values["registry-signer-url"]) {
|
|
875
|
+
if (!values["portal-url"])
|
|
876
|
+
throw new Error("the agent registry needs --portal-url: it names the registry in every passport");
|
|
877
|
+
let signer;
|
|
878
|
+
if (values["registry-key-env"]) {
|
|
879
|
+
const pem = process.env[values["registry-key-env"]];
|
|
880
|
+
if (!pem)
|
|
881
|
+
throw new Error(`portal: environment variable ${values["registry-key-env"]} is not set`);
|
|
882
|
+
const privateKey = createPrivateKey(pem);
|
|
883
|
+
const publicKey = createPublicKey(privateKey);
|
|
884
|
+
signer = localSigner({ privateKey, publicKey, keyid: keyidOf(publicKey) });
|
|
885
|
+
}
|
|
886
|
+
else {
|
|
887
|
+
const token = values["registry-signer-token-env"] ? process.env[values["registry-signer-token-env"]] : undefined;
|
|
888
|
+
if (values["registry-signer-token-env"] && !token)
|
|
889
|
+
throw new Error(`portal: environment variable ${values["registry-signer-token-env"]} is not set`);
|
|
890
|
+
signer = await connectSigner(values["registry-signer-url"], token ? { token } : {});
|
|
891
|
+
}
|
|
892
|
+
// each RPC URL is read from the environment: a provider's URL often carries its key
|
|
893
|
+
const rpc = {};
|
|
894
|
+
for (const pair of values["erc8004-rpc-env"] ?? []) {
|
|
895
|
+
const [chain, env] = pair.split("=");
|
|
896
|
+
if (!chain || !env)
|
|
897
|
+
throw new Error(`--erc8004-rpc-env takes <chain id>=<variable>, got ${pair}`);
|
|
898
|
+
const rpcUrl = process.env[env];
|
|
899
|
+
if (!rpcUrl)
|
|
900
|
+
throw new Error(`portal: environment variable ${env} is not set`);
|
|
901
|
+
rpc[chain] = rpcUrl;
|
|
902
|
+
}
|
|
903
|
+
if (!Object.keys(rpc).length && (values["ipfs-gateway"] || values["erc8004-recheck-seconds"]))
|
|
904
|
+
throw new Error("--ipfs-gateway and --erc8004-recheck-seconds need --erc8004-rpc-env");
|
|
905
|
+
const erc8004 = Object.keys(rpc).length ? createErc8004Resolver({ rpc, ...(values["ipfs-gateway"] ? { ipfsGateway: values["ipfs-gateway"] } : {}) }) : undefined;
|
|
906
|
+
registry = { signer, ...(values["passport-seconds"] ? { passportSeconds: Number(values["passport-seconds"]) } : {}), ...(erc8004 ? { erc8004 } : {}), ...(values["erc8004-recheck-seconds"] ? { erc8004RecheckSeconds: Number(values["erc8004-recheck-seconds"]) } : {}) };
|
|
907
|
+
}
|
|
908
|
+
else if (values["passport-seconds"] || values["registry-signer-token-env"] || values["erc8004-rpc-env"])
|
|
909
|
+
throw new Error("--passport-seconds, --registry-signer-token-env, and --erc8004-rpc-env need --registry-key-env or --registry-signer-url");
|
|
738
910
|
let oauth;
|
|
739
911
|
for (const p of ["github", "google"]) {
|
|
740
912
|
const id = values[`${p}-client-id`];
|
|
@@ -781,8 +953,8 @@ async function main(argv) {
|
|
|
781
953
|
catch {
|
|
782
954
|
// the log may not be reachable from here at start; the sheet then omits the keyid
|
|
783
955
|
}
|
|
784
|
-
const running = await servePortal({ tenancy, client, secret, publicUrl: values["public-url"], ...(values["checkpoints-url"] ? { checkpointsUrl: values["checkpoints-url"] } : {}), ...(values["portal-url"] ? { portalUrl: values["portal-url"] } : {}), ...(keyid ? { keyid } : {}), ...(stripe ? { stripe } : {}), ...(mail ? { mail } : {}), ...(oauth ? { oauth } : {}), trustProxy: values["trust-proxy"] }, { port: Number(values.port), host: values.host });
|
|
785
|
-
console.error(`agent-custody portal: ${running.url} log=${values["public-url"]} billing=${stripe ? "stripe" : "off"}${values["trust-proxy"] ? " trust-proxy" : ""}`);
|
|
956
|
+
const running = await servePortal({ tenancy, client, secret, publicUrl: values["public-url"], ...(values["checkpoints-url"] ? { checkpointsUrl: values["checkpoints-url"] } : {}), ...(values["portal-url"] ? { portalUrl: values["portal-url"] } : {}), ...(keyid ? { keyid } : {}), ...(stripe ? { stripe } : {}), ...(mail ? { mail } : {}), ...(oauth ? { oauth } : {}), ...(registry ? { registry } : {}), trustProxy: values["trust-proxy"] }, { port: Number(values.port), host: values.host });
|
|
957
|
+
console.error(`agent-custody portal: ${running.url} log=${values["public-url"]} billing=${stripe ? "stripe" : "off"} registry=${registry ? registry.signer.keyid.slice(0, 16) : "off"}${values["trust-proxy"] ? " trust-proxy" : ""}`);
|
|
786
958
|
await untilStopped();
|
|
787
959
|
await running.close();
|
|
788
960
|
return 0;
|