@agent-custody/receipts 0.16.12 → 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 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. 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)).
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.
@@ -24,6 +24,8 @@ Anyone holding the public keys can verify a receipt offline. The agent is not tr
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
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
27
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
28
30
  - [Financial operations](docs/financial-operations.md): durable operation ids, provider idempotency keys, atomic daily budget reservations, and reconciliation receipts for uncertain outcomes
29
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
@@ -315,6 +317,11 @@ src/door-app.ts the door in-process (`@agent-custody/receipts/door`): Express
315
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
316
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
317
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
318
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
319
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
320
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
@@ -352,6 +359,8 @@ The design is several producers feeding one verifier. The SDK is the top of the
352
359
 
353
360
  **Done**
354
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).
355
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.
356
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.
357
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).
@@ -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
- if (cfg.trustedPrincipalKeys.length === 0)
141
- add("warn", "principal keys", "no trusted principal keys: no arrival can be verified, every one is claimed or unknown");
142
- else if (principals === cfg.trustedPrincipalKeys.length)
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 {
@@ -254,6 +272,15 @@ export function checkDoorConfig(configPath) {
254
272
  }
255
273
  else if (cfg.trustedPrincipalKeys.length > 0)
256
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
+ }
257
284
  return out;
258
285
  }
259
286
  /** True when the file is an egress witness config: it names agents, and no upstream or origin. */
package/dist/cli.js CHANGED
@@ -7,7 +7,8 @@ import { closeSync, constants as fsConstants, createReadStream, existsSync, fchm
7
7
  import { createInterface } from "node:readline";
8
8
  import { dirname, join, resolve } from "node:path";
9
9
  import { loadAcsGuardianConfig, loadConfig, loadDoorConfig, loadEgressConfig, loadSdkConfig } from "./config.js";
10
- 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";
11
12
  import { DEFAULT_APPROVAL_LIFETIME_SECONDS } from "./approval.js";
12
13
  import { approvalRequestExpiresAt, approveApprovalRequest, denyApprovalRequest, listApprovalRequests, readApprovalRequest } from "./approval-requests.js";
13
14
  import { createDelegation, decodeDelegation, delegateFrom, grantDigest } from "./delegation.js";
@@ -17,6 +18,8 @@ import { postgresResolver, serveLog } from "./log-sink.js";
17
18
  import { importLogFile, PostgresTenancy } from "./log-store.js";
18
19
  import { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoints.js";
19
20
  import { connectSigner, fetchLogKeys, localSigner, serveSigner } from "./signer.js";
21
+ import { registrationProof } from "./registry.js";
22
+ import { createErc8004Resolver } from "./erc8004.js";
20
23
  import { fetchWitnessKeys, Witness } from "./witness.js";
21
24
  import { checkLog, formatLogCheck } from "./log-check.js";
22
25
  import { Anchor, ANCHOR_CHAINS, resolveAnchorChain } from "./anchor.js";
@@ -268,7 +271,13 @@ const USAGE = `agent-custody <command>
268
271
  log-admin --db-env NAME user mfa-reset <email> turns MFA off for a portal account that lost its authenticator
269
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]
270
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]
271
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
272
281
  log-admin --db-env NAME import --file <log.jsonl> [--tenant default] copies a file log into the database as hashes
273
282
  portal-followup --db-env NAME --secret-env NAME --mail-key-env NAME --mail-from <address> [--mail-notify <address>] [--mail-reply-to <address>]
274
283
  [--signer <name>] [--signer-role <role>] [--portal-url <url>] [--dry-run]
@@ -844,10 +853,60 @@ async function main(argv) {
844
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(", ")}` : ""}`);
845
854
  return r.failed.length ? 1 : 0;
846
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
+ }
847
866
  case "portal": {
848
- 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" } } });
849
868
  if (!values["db-env"] || !values["secret-env"] || !values["public-url"])
850
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");
851
910
  let oauth;
852
911
  for (const p of ["github", "google"]) {
853
912
  const id = values[`${p}-client-id`];
@@ -894,8 +953,8 @@ async function main(argv) {
894
953
  catch {
895
954
  // the log may not be reachable from here at start; the sheet then omits the keyid
896
955
  }
897
- 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 });
898
- 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" : ""}`);
899
958
  await untilStopped();
900
959
  await running.close();
901
960
  return 0;
package/dist/config.d.ts CHANGED
@@ -418,7 +418,9 @@ export declare const DoorConfigSchema: z.ZodObject<{
418
418
  }, z.core.$strip>>>;
419
419
  unmatchedRoute: z.ZodDefault<z.ZodString>;
420
420
  trustedPrincipalKeys: z.ZodDefault<z.ZodArray<z.ZodString>>;
421
+ trustedRegistryKeys: z.ZodDefault<z.ZodArray<z.ZodString>>;
421
422
  revokedGrants: z.ZodOptional<z.ZodString>;
423
+ admissionLists: z.ZodOptional<z.ZodString>;
422
424
  policyFile: z.ZodString;
423
425
  mode: z.ZodOptional<z.ZodEnum<{
424
426
  enforce: "enforce";
@@ -443,7 +445,7 @@ export declare const DoorConfigSchema: z.ZodObject<{
443
445
  maxInFlight: z.ZodDefault<z.ZodNumber>;
444
446
  }, z.core.$strip>>;
445
447
  webBotAuth: z.ZodOptional<z.ZodObject<{
446
- agents: z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
448
+ agents: z.ZodDefault<z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>>;
447
449
  authorities: z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
448
450
  requireNonce: z.ZodDefault<z.ZodBoolean>;
449
451
  maxAgeSeconds: z.ZodDefault<z.ZodNumber>;
package/dist/config.js CHANGED
@@ -260,8 +260,12 @@ export const DoorConfigSchema = z.object({
260
260
  unmatchedRoute: z.string().min(1).default("other"),
261
261
  /** principal keys whose grants the door accepts as a passport: an arrival carrying one of their grants, in scope for its route, is `verified` */
262
262
  trustedPrincipalKeys: z.array(z.string()).default([]),
263
+ /** agent registry keys (the key document at the registry's /.well-known/agent-custody-registry.json): an arrival that presents a passport one of them signed, and signs the request with the did:key the passport names, is `verified`. Needs `webBotAuth`, which checks the signature */
264
+ trustedRegistryKeys: z.array(z.string()).default([]),
263
265
  /** a JSON file listing digests of revoked grant envelopes, the same file and format as the gateway's (`agent-custody revoke --config door.json` appends to it); re-read whenever it changes, checked on every arrival. A grant it lists, or one whose chain it lists, is `revoked` */
264
266
  revokedGrants: z.string().min(1).optional(),
267
+ /** a JSON file of the site's named admission lists (`{ "lists": { "partners": [ { "registry", "agentId" } | { "erc8004": { "agentRegistry", "agentId" } } | { "agent" } ] } }`); re-read whenever it changes. The names of the lists a verified arrival's agent is on are `arrival.admission.lists` */
268
+ admissionLists: z.string().min(1).optional(),
265
269
  policyFile: z.string(),
266
270
  /** "enforce" (default) refuses what the policy denies; "observe" forwards everything and records the decision with `enforced: false` */
267
271
  mode: z.enum(["enforce", "observe"]).optional(),
@@ -297,13 +301,13 @@ export const DoorConfigSchema = z.object({
297
301
  * so an arrival cannot point it at a URL of its choosing.
298
302
  */
299
303
  webBotAuth: z.object({
300
- /** the signature agents whose directories the door fetches, as https origins (`https://crawler.example`) */
304
+ /** the signature agents whose directories the door fetches, as https origins (`https://crawler.example`). Empty when the door checks only did:key signatures, for a grant or a passport */
301
305
  agents: z.array(z.string().refine((u) => { try {
302
306
  return agentOrigin(u) === new URL(u).origin;
303
307
  }
304
308
  catch {
305
309
  return false;
306
- } }, { message: "a signature agent is an https origin, with no path, query, or credentials" }).transform((u) => new URL(u).origin)).min(1),
310
+ } }, { message: "a signature agent is an https origin, with no path, query, or credentials" }).transform((u) => new URL(u).origin)).default([]),
307
311
  /** the authorities (host, or host:port) this door serves; a signature must cover `@authority` and name one of them */
308
312
  authorities: z.array(z.string().min(1).transform(normalizeAuthority)).min(1),
309
313
  /** refuse a signature without a nonce; with one, a signature serves one request. Default true */
@@ -419,7 +423,9 @@ export function loadDoorConfig(path) {
419
423
  ...cfg,
420
424
  identity: { keyFile: r(cfg.identity.keyFile) },
421
425
  trustedPrincipalKeys: cfg.trustedPrincipalKeys.map(r),
426
+ trustedRegistryKeys: cfg.trustedRegistryKeys.map(r),
422
427
  ...(cfg.revokedGrants ? { revokedGrants: r(cfg.revokedGrants) } : {}),
428
+ ...(cfg.admissionLists ? { admissionLists: r(cfg.admissionLists) } : {}),
423
429
  policyFile: r(cfg.policyFile),
424
430
  receiptsDir: r(cfg.receiptsDir),
425
431
  ...(cfg.logFile ? { logFile: r(cfg.logFile) } : {}),
@@ -46,6 +46,10 @@ export interface Arrival {
46
46
  signatureError?: string;
47
47
  /** the agent name from the `x-agent-custody-agent` header, when sent; a claim */
48
48
  declared?: string;
49
+ /** what became of an agent registry passport; absent when none was presented */
50
+ passport?: ArrivalPassport;
51
+ /** the site's admission lists this arrival's agent is on, when the door has lists; absent otherwise, and from `classifyArrival` alone */
52
+ admission?: ArrivalAdmission;
49
53
  remote: string;
50
54
  method: string;
51
55
  path: string;
@@ -136,6 +140,52 @@ export interface RateTracker {
136
140
  * the windows nor drops new ones; an injected clock that goes back is held at the last time seen. `now` is for tests.
137
141
  */
138
142
  export declare function createRateTracker(now?: () => number, limits?: RateTrackerLimits): RateTracker;
143
+ /**
144
+ * What became of the passport an arrival presented. `verified`: a trusted registry key signed it, it is in its window,
145
+ * and the request is signed by the did:key it names, with a signature that covers the passport, `@method`, `@path`,
146
+ * `@query`, and, on a method that can change something, a `Content-Digest` that matches the body; that alone makes an arrival
147
+ * without a grant `verified`. `unbound`: it verified and the request is signed by its key, but the signature does not
148
+ * cover all of that, so it could be a signature made for another request with a public passport attached.
149
+ * `wrong-sender`: it verified, and the request is not signed by its key. `invalid`: it did not verify, or the header is
150
+ * not a passport. `unchecked`: the door trusts no registry key. Only a `verified` passport puts the registry's entry in
151
+ * the fact: a passport is public, and an entry the signer is not bound to would let anyone carry another agent's
152
+ * capabilities into the policy. The passport itself is recorded too, so a reader with the registry's key can check it again.
153
+ */
154
+ export interface ArrivalPassport {
155
+ outcome: "verified" | "unbound" | "wrong-sender" | "invalid" | "unchecked";
156
+ error?: string;
157
+ /** the registry that signed it, when it verified */
158
+ registry?: string;
159
+ /** the did:key it names, when it verified */
160
+ agent?: string;
161
+ registryKeyid?: string;
162
+ agentId?: string;
163
+ name?: string;
164
+ owner?: string;
165
+ capabilities?: string[];
166
+ /** the agent's ERC-8004 identity, as the registry checked it against the chain */
167
+ erc8004?: {
168
+ agentRegistry: string;
169
+ agentId: string;
170
+ owner: string;
171
+ block: number;
172
+ };
173
+ expiresAt?: string;
174
+ /** sha256 over the passport's signed payload */
175
+ digest?: string;
176
+ envelope?: Envelope;
177
+ }
178
+ /**
179
+ * The admission lists an arrival's agent is on, by name, sorted, and the sha256 of the lists file in force. Only a
180
+ * `verified` arrival is on any list: by its subject, or by the registry entry or ERC-8004 identity of its verified
181
+ * passport. The names mean what the policy makes of them.
182
+ */
183
+ export interface ArrivalAdmission {
184
+ lists: string[];
185
+ digest: string;
186
+ }
187
+ /** The components a signature must cover for the passport it carries to admit its agent. */
188
+ export declare const PASSPORT_COVERED: readonly ["@method", "@path", "@query", "x-agent-custody-passport"];
139
189
  export interface Classified {
140
190
  arrival: Arrival;
141
191
  /** set when the arrival is verified by a grant: the grant, as presented */
@@ -234,12 +284,15 @@ export declare function signedRequestOf(req: DoorRequest): SignedRequest;
234
284
  * Without a grant, a Web Bot Auth signature the door verified (`signature`, from `createWebBotAuthVerifier`) makes the
235
285
  * arrival `verified` as its signature agent. With both, the signature binds the grant to its sender when the grant names
236
286
  * that signature agent; a grant presented under another agent's signature is `wrong-sender` and the arrival `claimed`.
237
- * A signature by a did:key's own key binds a grant that names that did:key in the same way, and counts for nothing else.
287
+ * A signature by a did:key's own key binds a grant that names that did:key in the same way. Without a grant, it binds a
288
+ * passport from a trusted registry (`registry`) that names that did:key, and the arrival is `verified` as the did:key;
289
+ * a request that presents a grant is judged by its grant, and its passport is only recorded. Otherwise a did:key
290
+ * signature counts for nothing.
238
291
  * An `x-agent-custody-agent` header or a signature that did not verify alone is `claimed`. Nothing at all is `unknown`.
239
292
  * Without `signature`, a `Signature-Input` header is recorded as `unchecked`. `revoked`, when given, says why a grant
240
293
  * that verified is revoked (from its chain's digests, leaf first), or null when it is not; a revoked grant is `claimed`.
241
294
  */
242
- export declare function classifyArrival(req: DoorRequest, trusted: PublicKeyRef[], route: string, trustProxy: boolean, at: string, signature?: SignatureCheck, revoked?: (chainDigests: string[]) => string | null): Classified;
295
+ export declare function classifyArrival(req: DoorRequest, trusted: PublicKeyRef[], route: string, trustProxy: boolean, at: string, signature?: SignatureCheck, revoked?: (chainDigests: string[]) => string | null, registry?: PublicKeyRef[], contentDigest?: boolean): Classified;
243
296
  /** The body as the door read it: whole, or how many bytes had arrived when it passed the limit. */
244
297
  export type BodyRead = {
245
298
  body: Buffer;
@@ -327,6 +380,8 @@ export interface DoorIO {
327
380
  key: KeyPair;
328
381
  /** principal keys whose grants are a passport */
329
382
  trustedPrincipalKeys: PublicKeyRef[];
383
+ /** agent registry keys whose passports admit the did:key they name */
384
+ trustedRegistryKeys?: PublicKeyRef[];
330
385
  /** the policy text, and a value that changes whenever the text may have; read on every arrival. Throws when it cannot be read: the policy in force stays */
331
386
  readPolicy(): {
332
387
  text: string;
@@ -334,6 +389,17 @@ export interface DoorIO {
334
389
  };
335
390
  /** names the policy in messages: its file, or the variable it came from */
336
391
  policySource: string;
392
+ /**
393
+ * a value that changes whenever the admission lists file may have, and its text, which may be left out when the key
394
+ * is `known`, the key of the lists in force; asked on every arrival. Absent when the door has no lists. Throws when it
395
+ * cannot be read: the lists in force stay
396
+ */
397
+ readAdmission?(known?: string): {
398
+ text?: string;
399
+ key: string;
400
+ };
401
+ /** names the admission lists in messages */
402
+ admissionSource?: string;
337
403
  /** why a grant with these chain digests (leaf first) is revoked, or null when it is not. A list that cannot be read must revoke: return the reason */
338
404
  revoked(chainDigests: string[]): string | null;
339
405
  /** a secret by the name the config gives it (`captureKeyEnv`, `challenge.secretEnv`), or undefined when it is not set */