@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.
Files changed (54) hide show
  1. package/README.md +23 -5
  2. package/dist/admission.d.ts +62 -0
  3. package/dist/admission.js +101 -0
  4. package/dist/check.js +42 -3
  5. package/dist/cli.js +179 -7
  6. package/dist/config.d.ts +6 -1
  7. package/dist/config.js +21 -2
  8. package/dist/door-app.js +1 -1
  9. package/dist/door-core.d.ts +81 -3
  10. package/dist/door-core.js +113 -13
  11. package/dist/door-error-rates.d.ts +102 -0
  12. package/dist/door-error-rates.js +178 -0
  13. package/dist/door-form.d.ts +7 -2
  14. package/dist/door-form.js +52 -4
  15. package/dist/door-measure.d.ts +153 -0
  16. package/dist/door-measure.js +325 -0
  17. package/dist/door-signals.d.ts +414 -0
  18. package/dist/door-signals.js +555 -0
  19. package/dist/door-test-set.d.ts +43 -0
  20. package/dist/door-test-set.js +117 -0
  21. package/dist/door-worker.d.ts +20 -1
  22. package/dist/door-worker.js +30 -2
  23. package/dist/door.js +18 -2
  24. package/dist/erc8004-link.d.ts +24 -0
  25. package/dist/erc8004-link.js +11 -0
  26. package/dist/erc8004.d.ts +26 -0
  27. package/dist/erc8004.js +208 -0
  28. package/dist/index.d.ts +17 -3
  29. package/dist/index.js +9 -2
  30. package/dist/lock.d.ts +5 -0
  31. package/dist/lock.js +1 -1
  32. package/dist/log-store.d.ts +3 -1
  33. package/dist/log-store.js +2 -2
  34. package/dist/passport.d.ts +53 -0
  35. package/dist/passport.js +87 -0
  36. package/dist/portal.d.ts +14 -0
  37. package/dist/portal.js +102 -0
  38. package/dist/registry.d.ts +145 -0
  39. package/dist/registry.js +294 -0
  40. package/dist/web-bot-auth.d.ts +9 -3
  41. package/dist/web-bot-auth.js +31 -4
  42. package/docs/admission-lists.md +89 -0
  43. package/docs/agent-registry.md +173 -0
  44. package/docs/door-error-rates.md +490 -0
  45. package/docs/door-languages.md +3 -1
  46. package/docs/door-middleware.md +6 -1
  47. package/docs/door-quickstart.md +2 -2
  48. package/docs/door-signals.md +112 -2
  49. package/docs/door-worker.md +14 -1
  50. package/docs/door.md +37 -6
  51. package/docs/github-action.md +2 -2
  52. package/docs/tutorials.md +7 -0
  53. package/docs/usage.md +1 -1
  54. package/package.json +2 -1
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>;
@@ -466,6 +468,9 @@ export declare const DoorConfigSchema: z.ZodObject<{
466
468
  maxInFlight: z.ZodDefault<z.ZodNumber>;
467
469
  maxResponseBytes: z.ZodDefault<z.ZodNumber>;
468
470
  }, z.core.$strip>>;
471
+ behaviour: z.ZodOptional<z.ZodObject<{
472
+ tlsHeader: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
473
+ }, z.core.$strict>>;
469
474
  receiptsDir: z.ZodString;
470
475
  logFile: z.ZodOptional<z.ZodString>;
471
476
  log: z.ZodOptional<z.ZodObject<{
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 */
@@ -349,6 +353,18 @@ export const DoorConfigSchema = z.object({
349
353
  /** the largest answer the door reads. Default 16 KiB */
350
354
  maxResponseBytes: z.number().int().positive().default(16 * 1024),
351
355
  }).optional(),
356
+ /**
357
+ * The door's own behavioural and fingerprint signals (door-signals.ts): the header fingerprint, the TLS fingerprint,
358
+ * the pace, the navigation, and the form report. Present, even empty, it adds `fingerprint` and `behaviour` to the
359
+ * arrival fact. They are signals for the policy to read; the door refuses nothing because of them.
360
+ */
361
+ behaviour: z.strictObject({
362
+ /**
363
+ * The request header in which your proxy puts the client's JA4 TLS fingerprint. The proxy must overwrite the
364
+ * header on every request, or a client can send its own. Needs `trustProxy`
365
+ */
366
+ tlsHeader: z.string().regex(/^[A-Za-z0-9-]{1,64}$/, "a header name has letters, digits, and hyphens").transform((h) => h.toLowerCase()).optional(),
367
+ }).optional(),
352
368
  receiptsDir: z.string(),
353
369
  logFile: z.string().optional(),
354
370
  log: LogSchema.optional(),
@@ -357,6 +373,7 @@ export const DoorConfigSchema = z.object({
357
373
  capture: CaptureSchema.optional(),
358
374
  captureKeyEnv: z.string().min(1).optional(),
359
375
  }).refine(hasOneLog, oneLog).refine((c) => new Set(c.routes.map((r) => r.name)).size === c.routes.length, { message: "route names must be unique" })
376
+ .refine((c) => !c.behaviour?.tlsHeader || c.trustProxy, { path: ["behaviour", "tlsHeader"], message: "behaviour.tlsHeader needs trustProxy: true, since only a proxy in front of the door sees the TLS handshake; without one the header is the client's" })
360
377
  .refine((c) => !c.partner || c.partner.routes.every((r) => r === "*" || r === c.unmatchedRoute || c.routes.some((x) => x.name === r)), { message: "partner.routes names a route the door does not have" })
361
378
  .refine((c) => !c.authz || c.trustProxy, { message: "authz needs trustProxy: true, since every check comes from the proxy and the arrival's address is the last in its X-Forwarded-For" })
362
379
  .refine((c) => !c.log || !!c.log.keys?.length, { message: "a remote log needs log.keys: the log's public key files, pinned, to check its answer before a request is relayed" });
@@ -406,7 +423,9 @@ export function loadDoorConfig(path) {
406
423
  ...cfg,
407
424
  identity: { keyFile: r(cfg.identity.keyFile) },
408
425
  trustedPrincipalKeys: cfg.trustedPrincipalKeys.map(r),
426
+ trustedRegistryKeys: cfg.trustedRegistryKeys.map(r),
409
427
  ...(cfg.revokedGrants ? { revokedGrants: r(cfg.revokedGrants) } : {}),
428
+ ...(cfg.admissionLists ? { admissionLists: r(cfg.admissionLists) } : {}),
410
429
  policyFile: r(cfg.policyFile),
411
430
  receiptsDir: r(cfg.receiptsDir),
412
431
  ...(cfg.logFile ? { logFile: r(cfg.logFile) } : {}),
package/dist/door-app.js CHANGED
@@ -113,7 +113,7 @@ export function door(config, options = {}) {
113
113
  if (cfg.authz)
114
114
  throw new Error("the in-process door passes an allowed request to the app it runs in; authz is for the door answering nginx or Envoy checks (`agent-custody door`)");
115
115
  const core = createDoorCore(cfg, { ...options, autoFlush: options.autoFlush ?? true }, MIDDLEWARE_FRAMEWORK);
116
- const script = cfg.challenge ? formScript(cfg.challenge) : null;
116
+ const script = cfg.challenge ? formScript(cfg.challenge, !!cfg.behaviour) : null;
117
117
  const middleware = (req, res, next) => {
118
118
  // the script is public and the same for every arrival: served, not decided or receipted
119
119
  if (script && req.method === "GET" && (req.url ?? "").split("?")[0] === FORM_SCRIPT_PATH) {
@@ -6,6 +6,7 @@ import { type Delegation } from "./delegation.ts";
6
6
  import type { Issuer } from "./issue.ts";
7
7
  import { type FlushResult } from "./receipt-pending.ts";
8
8
  import { type NonceStore, type SignatureCheck, type SignedRequest } from "./web-bot-auth.ts";
9
+ import { type ArrivalBehaviour, type ArrivalFingerprint, type TlsObservation } from "./door-signals.ts";
9
10
  import { type ArrivalPartner } from "./door-partner.ts";
10
11
  import type { AuthorizationBundle, ReceiptPredicate } from "./receipt.ts";
11
12
  export declare const DOOR_VERSION = "0.1.0";
@@ -45,6 +46,10 @@ export interface Arrival {
45
46
  signatureError?: string;
46
47
  /** the agent name from the `x-agent-custody-agent` header, when sent; a claim */
47
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;
48
53
  remote: string;
49
54
  method: string;
50
55
  path: string;
@@ -55,6 +60,10 @@ export interface Arrival {
55
60
  challenge?: ArrivalChallenge;
56
61
  /** what became of the question to the partner engine, when the door asks one about this route; absent otherwise, and from `classifyArrival` alone. The verdict itself is the `partner` fact, present only when `outcome` is `verified` */
57
62
  partner?: ArrivalPartner;
63
+ /** what the request and its connection look like, when the door has `behaviour` configured; absent otherwise, and from `classifyArrival` alone. Signals, never a verdict (door-signals.ts) */
64
+ fingerprint?: ArrivalFingerprint;
65
+ /** how the source acts over time, when the door has `behaviour` configured; absent otherwise, and from `classifyArrival` alone */
66
+ behaviour?: ArrivalBehaviour;
58
67
  }
59
68
  /**
60
69
  * The outcome of a human challenge. `passed`: the provider confirmed the token, so the provider judged a person present
@@ -131,6 +140,52 @@ export interface RateTracker {
131
140
  * the windows nor drops new ones; an injected clock that goes back is held at the last time seen. `now` is for tests.
132
141
  */
133
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"];
134
189
  export interface Classified {
135
190
  arrival: Arrival;
136
191
  /** set when the arrival is verified by a grant: the grant, as presented */
@@ -190,6 +245,13 @@ export interface DoorRequest {
190
245
  headers: IncomingHttpHeaders;
191
246
  /** every value of each field, as Node keeps them; read for an HTTP message signature */
192
247
  headersDistinct?: Record<string, string[] | undefined>;
248
+ /** names and values in turn, in the order received, as Node keeps them; read for the header fingerprint */
249
+ rawHeaders?: string[] | undefined;
250
+ /** what the host knows of the client's connection (a Worker reads it from `request.cf`); never read from a header */
251
+ transport?: {
252
+ secure?: boolean;
253
+ tls?: TlsObservation;
254
+ } | undefined;
193
255
  socket: {
194
256
  remoteAddress?: string | undefined;
195
257
  };
@@ -222,12 +284,15 @@ export declare function signedRequestOf(req: DoorRequest): SignedRequest;
222
284
  * Without a grant, a Web Bot Auth signature the door verified (`signature`, from `createWebBotAuthVerifier`) makes the
223
285
  * arrival `verified` as its signature agent. With both, the signature binds the grant to its sender when the grant names
224
286
  * that signature agent; a grant presented under another agent's signature is `wrong-sender` and the arrival `claimed`.
225
- * 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.
226
291
  * An `x-agent-custody-agent` header or a signature that did not verify alone is `claimed`. Nothing at all is `unknown`.
227
292
  * Without `signature`, a `Signature-Input` header is recorded as `unchecked`. `revoked`, when given, says why a grant
228
293
  * that verified is revoked (from its chain's digests, leaf first), or null when it is not; a revoked grant is `claimed`.
229
294
  */
230
- 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;
231
296
  /** The body as the door read it: whole, or how many bytes had arrived when it passed the limit. */
232
297
  export type BodyRead = {
233
298
  body: Buffer;
@@ -291,7 +356,7 @@ export interface DoorCore {
291
356
  * `context.facts.<name>`. A name the door uses itself (`arrival`, `partner`) is refused.
292
357
  */
293
358
  decide(req: DoorRequest, receiptId: string, read: ((max: number) => Promise<BodyRead>) | null, framework?: string, observed?: Record<string, ObservedFact>): Promise<DoorDecision>;
294
- /** a header the door consumed and never passes on: the grant (and `Authorization` when it carried it), the declared agent, the challenge token */
359
+ /** a header the door consumed and never passes on: the grant (and `Authorization` when it carried it), the declared agent, the challenge token, and with `behaviour` the form report */
295
360
  consumed(name: string, req: DoorRequest, arrival: Arrival): boolean;
296
361
  /** writes the receipt; null when it could not be written, after saying why on stderr */
297
362
  record(d: DoorDecision, execution: Execution): Promise<{
@@ -315,6 +380,8 @@ export interface DoorIO {
315
380
  key: KeyPair;
316
381
  /** principal keys whose grants are a passport */
317
382
  trustedPrincipalKeys: PublicKeyRef[];
383
+ /** agent registry keys whose passports admit the did:key they name */
384
+ trustedRegistryKeys?: PublicKeyRef[];
318
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 */
319
386
  readPolicy(): {
320
387
  text: string;
@@ -322,6 +389,17 @@ export interface DoorIO {
322
389
  };
323
390
  /** names the policy in messages: its file, or the variable it came from */
324
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;
325
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 */
326
404
  revoked(chainDigests: string[]): string | null;
327
405
  /** a secret by the name the config gives it (`captureKeyEnv`, `challenge.secretEnv`), or undefined when it is not set */
package/dist/door-core.js CHANGED
@@ -3,8 +3,11 @@ import { digestOf, sha256Hex } from "./crypto.js";
3
3
  import { DID_KEY_PREFIX } from "./did-key.js";
4
4
  import { decodeDelegation, delegationValidAt, grantChainDigests, verifyDelegation } from "./delegation.js";
5
5
  import { parseGrantHeader, GRANT_HEADER } from "./grant-header.js";
6
+ import { MAX_PASSPORT_HEADER, PASSPORT_HEADER, parsePassportHeader, passportSignedBy, verifyPassport } from "./passport.js";
7
+ import { compileAdmissionLists } from "./admission.js";
6
8
  import { ReceiptPending } from "./receipt-pending.js";
7
- import { createWebBotAuthVerifier, normalizeAuthority } from "./web-bot-auth.js";
9
+ import { contentDigestMatches, createWebBotAuthVerifier, normalizeAuthority } from "./web-bot-auth.js";
10
+ import { createHistoryTracker, createSeenCounter, fingerprintKey, FORM_REPORT_HEADER, historySource, observationOf, signalsOf } from "./door-signals.js";
8
11
  import { createPartnerEngine, PARTNER_FACT, PARTNER_TOOL } from "./door-partner.js";
9
12
  import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
10
13
  export const DOOR_VERSION = "0.1.0";
@@ -128,6 +131,36 @@ export function createRateTracker(now = () => performance.now(), limits = {}) {
128
131
  clearInterval(timer); },
129
132
  };
130
133
  }
134
+ /** The components a signature must cover for the passport it carries to admit its agent. */
135
+ export const PASSPORT_COVERED = ["@method", "@path", "@query", PASSPORT_HEADER];
136
+ /**
137
+ * The passport check for an arrival. `signer` is the did:key whose signature on this request the door verified, with
138
+ * the components it covered; `contentDigest` is true when a `Content-Digest` field matched the body the door read.
139
+ */
140
+ function checkPassport(req, method, registry, at, signer, contentDigest) {
141
+ const raw = req.headers[PASSPORT_HEADER];
142
+ if (raw === undefined)
143
+ return undefined;
144
+ const env = parsePassportHeader(req.headers);
145
+ if (!env)
146
+ return { outcome: "invalid", error: `the ${PASSPORT_HEADER} header is not a base64url DSSE envelope of at most ${MAX_PASSPORT_HEADER} characters` };
147
+ if (!registry?.length)
148
+ return { outcome: "unchecked" };
149
+ const v = verifyPassport(env, registry, at);
150
+ if (!v.ok)
151
+ return { outcome: "invalid", error: v.error };
152
+ const p = v.passport;
153
+ const named = { registry: p.registry, agent: p.agent };
154
+ if (signer?.agent !== p.agent)
155
+ return { outcome: "wrong-sender", error: signer ? `the passport names ${p.agent}, and the request is signed by ${signer.agent}` : `the passport names ${p.agent}, and the request carries no signature by that key that the door verified`, ...named };
156
+ const writes = !SAFE_METHODS.has(method);
157
+ const missing = [...PASSPORT_COVERED, ...(writes ? ["content-digest"] : [])].filter((c) => !signer.covered?.includes(c));
158
+ if (missing.length)
159
+ return { outcome: "unbound", error: `the signature does not cover ${missing.join(", ")}, which bind the passport to this request`, ...named };
160
+ if (writes && !contentDigest)
161
+ return { outcome: "unbound", error: "the Content-Digest the signature covers does not match the body the door read, or the door did not read the body" };
162
+ return { outcome: "verified", ...named, registryKeyid: v.keyid, agentId: p.agentId, name: p.name, owner: p.owner, capabilities: p.capabilities, ...(p.erc8004 ? { erc8004: p.erc8004 } : {}), expiresAt: p.expiresAt, digest: v.digest, envelope: env };
163
+ }
131
164
  const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "proxy-connection"]);
132
165
  /** request headers the receipt records in clear; everything else is relayed and not recorded */
133
166
  const RECORDED_HEADERS = ["user-agent", "content-type", "accept", "host"];
@@ -275,12 +308,15 @@ export function signedRequestOf(req) {
275
308
  * Without a grant, a Web Bot Auth signature the door verified (`signature`, from `createWebBotAuthVerifier`) makes the
276
309
  * arrival `verified` as its signature agent. With both, the signature binds the grant to its sender when the grant names
277
310
  * that signature agent; a grant presented under another agent's signature is `wrong-sender` and the arrival `claimed`.
278
- * 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.
311
+ * 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
312
+ * passport from a trusted registry (`registry`) that names that did:key, and the arrival is `verified` as the did:key;
313
+ * a request that presents a grant is judged by its grant, and its passport is only recorded. Otherwise a did:key
314
+ * signature counts for nothing.
279
315
  * An `x-agent-custody-agent` header or a signature that did not verify alone is `claimed`. Nothing at all is `unknown`.
280
316
  * Without `signature`, a `Signature-Input` header is recorded as `unchecked`. `revoked`, when given, says why a grant
281
317
  * that verified is revoked (from its chain's digests, leaf first), or null when it is not; a revoked grant is `claimed`.
282
318
  */
283
- export function classifyArrival(req, trusted, route, trustProxy, at, signature, revoked) {
319
+ export function classifyArrival(req, trusted, route, trustProxy, at, signature, revoked, registry, contentDigest) {
284
320
  const url = requestUrl(req);
285
321
  const method = (req.method ?? "GET").toUpperCase();
286
322
  const declaredRaw = req.headers[AGENT_HEADER];
@@ -291,6 +327,8 @@ export function classifyArrival(req, trusted, route, trustProxy, at, signature,
291
327
  // only on the last line, with a verified grant for that did:key. Everywhere else it is invalid, so that no policy
292
328
  // takes it for a checked identity.
293
329
  const didSigner = signer?.agent.startsWith(DID_KEY_PREFIX) ? signer : undefined;
330
+ const passport = checkPassport(req, method, registry, at, didSigner ? { agent: didSigner.agent, ...(sig.outcome === "verified" && sig.covered ? { covered: sig.covered } : {}) } : undefined, contentDigest);
331
+ const admitted = passport?.outcome === "verified";
294
332
  const norm = normalizePath(url.pathname);
295
333
  const baseOf = (s) => ({
296
334
  signature: s.outcome,
@@ -298,18 +336,19 @@ export function classifyArrival(req, trusted, route, trustProxy, at, signature,
298
336
  ...("keyid" in s && s.keyid ? { signatureKeyid: s.keyid } : {}),
299
337
  ...("error" in s ? { signatureError: s.error } : {}),
300
338
  ...(declared ? { declared } : {}),
339
+ ...(passport ? { passport } : {}),
301
340
  remote: remoteOf(req, trustProxy),
302
341
  method,
303
342
  path: "path" in norm ? norm.path : url.pathname,
304
343
  route,
305
344
  });
306
- const base = baseOf(didSigner ? { outcome: "invalid", error: `the request is signed by the key of ${didSigner.agent}, and no verified grant in the request names that did:key`, ...didSigner } : sig);
307
345
  const envelope = parseGrantHeader(req);
346
+ const base = baseOf(didSigner && !(admitted && !envelope) ? { outcome: "invalid", error: `the request is signed by the key of ${didSigner.agent}, and no verified grant in the request names that did:key${admitted ? "" : ", nor a passport from a trusted registry"}`, ...didSigner } : sig);
308
347
  if (!envelope) {
309
- if (signer && !didSigner)
348
+ if (signer && (!didSigner || admitted))
310
349
  return { arrival: { class: "verified", subject: signer.agent, grant: "absent", ...base }, signer };
311
- const claimed = !!declared || sig.outcome !== "absent";
312
- return { arrival: { class: claimed ? "claimed" : "unknown", subject: declared ?? "unknown", grant: "absent", ...base } };
350
+ const claimed = !!declared || sig.outcome !== "absent" || !!passport;
351
+ return { arrival: { class: claimed ? "claimed" : "unknown", subject: declared ?? passport?.agent ?? "unknown", grant: "absent", ...base } };
313
352
  }
314
353
  const checked = verifyDelegation(envelope, trusted);
315
354
  const asserted = decodeDelegation(envelope)?.agent;
@@ -377,6 +416,9 @@ const json = jsonAnswer;
377
416
  /** The decision loop for a door config over the given I/O; `framework` is the receipt's `issuer.framework`. Throws when the config cannot be served. */
378
417
  export function createDoorCoreWith(cfg, io, framework, opts = {}) {
379
418
  const trusted = io.trustedPrincipalKeys;
419
+ const registry = io.trustedRegistryKeys ?? [];
420
+ if (registry.length && !cfg.webBotAuth)
421
+ throw new Error("trustedRegistryKeys needs webBotAuth: a passport admits an agent only on a request its did:key signed, and webBotAuth checks that signature");
380
422
  const revoked = io.revoked;
381
423
  const captureSecret = cfg.captureKeyEnv ? io.secret(cfg.captureKeyEnv) : undefined;
382
424
  if (cfg.captureKeyEnv && captureSecret === undefined)
@@ -399,6 +441,9 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
399
441
  const issuedBy = { kind: "door", keyid: issuer.keyid, version: DOOR_VERSION, framework };
400
442
  const precommit = new Set(cfg.precommit);
401
443
  const rates = createRateTracker(undefined, { sweepTimer: io.timers });
444
+ // one process's memory, like the rate counts
445
+ const history = cfg.behaviour ? createHistoryTracker() : undefined;
446
+ const fingerprints = createSeenCounter();
402
447
  const webBotAuth = cfg.webBotAuth ? createWebBotAuthVerifier(cfg.webBotAuth, f, undefined, io.nonceStore) : undefined;
403
448
  const partner = cfg.partner ? createPartnerEngine(cfg.partner, f) : undefined;
404
449
  // The policy, re-read on every arrival, as the gateway does; a text that does not parse is refused and the policy in
@@ -411,6 +456,37 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
411
456
  if (!hasPermitRule(first.text))
412
457
  console.error(`agent-custody door: ${io.policySource} has no permit rule, so every arrival is refused`);
413
458
  let policyNow = { text: first.text, digest: policyDigest(first.text), key: first.key };
459
+ // The admission lists, re-read like the policy: a file that cannot be read or is not valid leaves the lists in force,
460
+ // because emptying them would drop every agent from a block list as well as from an allow list.
461
+ let admissionNow;
462
+ if (io.readAdmission) {
463
+ const a = io.readAdmission();
464
+ if (a.text === undefined)
465
+ throw new Error(`${io.admissionSource}: the admission lists were not read`);
466
+ admissionNow = { lists: compileAdmissionLists(a.text), key: a.key };
467
+ }
468
+ const currentAdmission = () => {
469
+ if (!io.readAdmission || !admissionNow)
470
+ return undefined;
471
+ try {
472
+ const next = io.readAdmission(admissionNow.key);
473
+ if (next.key !== admissionNow.key) {
474
+ try {
475
+ if (next.text === undefined)
476
+ throw new Error("the file changed and its text was not read");
477
+ admissionNow = { lists: compileAdmissionLists(next.text), key: next.key };
478
+ }
479
+ catch (e) {
480
+ console.error(`agent-custody door: ADMISSION LISTS NOT RELOADED: ${io.admissionSource}: ${e instanceof Error ? e.message : String(e)}; lists ${admissionNow.lists.digest} stay in force`);
481
+ admissionNow = { ...admissionNow, key: next.key };
482
+ }
483
+ }
484
+ }
485
+ catch (e) {
486
+ console.error(`agent-custody door: cannot read ${io.admissionSource}: ${e instanceof Error ? e.message : String(e)}; lists ${admissionNow.lists.digest} stay in force`);
487
+ }
488
+ return admissionNow.lists;
489
+ };
414
490
  const currentPolicy = () => {
415
491
  try {
416
492
  const next = readPolicy();
@@ -440,11 +516,37 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
440
516
  const route = "path" in norm ? matchRoute(cfg.routes, cfg.unmatchedRoute, method, path) : cfg.unmatchedRoute;
441
517
  const presented = webBotAuth && req.headers["signature-input"] !== undefined ? parseGrantHeader(req) : null;
442
518
  const trustedGrant = presented ? verifyDelegation(presented, trusted) : undefined;
443
- const signature = webBotAuth ? await webBotAuth.verify(signedRequestOf(req), trustedGrant?.ok ? trustedGrant.delegation.agent : undefined) : undefined;
444
- const { arrival, delegation, signer } = classifyArrival(req, trusted, route, !!cfg.trustProxy, timestamp, signature, revoked);
519
+ // a did:key signature keeps its nonce only for an agent that a trusted grant or a trusted passport names; both are
520
+ // given, so that a grant header, trusted or not, cannot stop the nonce of a signature that a passport is checked against
521
+ const passportEnv = webBotAuth && registry.length && req.headers["signature-input"] !== undefined ? parsePassportHeader(req.headers) : null;
522
+ // a passport not yet valid at this door (its registry's clock is ahead) still keeps the nonce, or the same request
523
+ // could be sent again, and admitted, once the passport's window opens
524
+ const signedPassport = passportEnv ? passportSignedBy(passportEnv, registry) : undefined;
525
+ const passportAgent = signedPassport?.ok && Date.parse(timestamp) <= Date.parse(signedPassport.passport.expiresAt) ? signedPassport.passport.agent : undefined;
526
+ const keyAgents = [...(trustedGrant?.ok ? [trustedGrant.delegation.agent] : []), ...(passportAgent ? [passportAgent] : [])];
527
+ const signature = webBotAuth ? await webBotAuth.verify(signedRequestOf(req), keyAgents) : undefined;
528
+ // the body is read before the arrival is classified: a passport on a write binds to it through Content-Digest
529
+ const read = readArrivalBody ? await readArrivalBody(cfg.maxBodyBytes) : null;
530
+ const body = read === null ? Buffer.alloc(0) : "body" in read ? read.body : null;
531
+ const digestField = req.headers["content-digest"];
532
+ const contentDigest = read !== null && body !== null && typeof digestField === "string" && contentDigestMatches(digestField, body);
533
+ const { arrival, delegation, signer } = classifyArrival(req, trusted, route, !!cfg.trustProxy, timestamp, signature, revoked, registry, contentDigest);
534
+ const admission = currentAdmission();
535
+ if (admission)
536
+ arrival.admission = { lists: admission.match(arrival), digest: admission.digest };
445
537
  const checkedAgent = arrival.class === "verified";
446
538
  const by = checkedAgent ? "agent" : "remote";
447
- arrival.rate = { by, ...rates.hit(`${by}:${checkedAgent ? arrival.subject : arrival.remote}`) };
539
+ const source = `${by}:${checkedAgent ? arrival.subject : arrival.remote}`;
540
+ arrival.rate = { by, ...rates.hit(source) };
541
+ if (history) {
542
+ // in authz mode the proxy selects the headers of a check, so the header set is not the client's
543
+ const seen = observationOf(req, performance.now(), method, arrival.path, { trustProxy: !!cfg.trustProxy, ...(cfg.behaviour?.tlsHeader ? { tlsHeader: cfg.behaviour.tlsHeader } : {}), own: challengeHeader ? [challengeHeader] : [], partialHeaders: !!cfg.authz });
544
+ const signals = signalsOf(seen, history.record(checkedAgent ? source : `remote:${historySource(arrival.remote)}`, seen));
545
+ const key = fingerprintKey(signals.fingerprint);
546
+ if (key !== undefined)
547
+ signals.fingerprint.seen = fingerprints.hit(key, seen.at);
548
+ Object.assign(arrival, signals);
549
+ }
448
550
  if (cfg.challenge && challengeHeader) {
449
551
  const c = cfg.challenge;
450
552
  const token = req.headers[challengeHeader];
@@ -465,8 +567,6 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
465
567
  }
466
568
  }
467
569
  const { text: policyText, digest: pDigest } = currentPolicy();
468
- const read = readArrivalBody ? await readArrivalBody(cfg.maxBodyBytes) : null;
469
- const body = read === null ? Buffer.alloc(0) : "body" in read ? read.body : null;
470
570
  const headers = {};
471
571
  for (const name of RECORDED_HEADERS) {
472
572
  const v = req.headers[name];
@@ -590,7 +690,7 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
590
690
  release: () => void (inFlight -= 1),
591
691
  busy: () => json(503, { "retry-after": "1" }, { error: `the door is handling ${cfg.maxInFlight} requests; this one was not read, decided, or relayed. Retry` }),
592
692
  decide,
593
- consumed: (name, req, arrival) => name === GRANT_HEADER || name === AGENT_HEADER || name === challengeHeader ||
693
+ consumed: (name, req, arrival) => name === GRANT_HEADER || name === AGENT_HEADER || name === PASSPORT_HEADER || name === challengeHeader || (!!history && name === FORM_REPORT_HEADER) ||
594
694
  // the grant travelled in Authorization: it is the door's credential, not the origin's
595
695
  (name === "authorization" && arrival.grant !== "absent" && !req.headers[GRANT_HEADER]),
596
696
  async record(d, execution) {
@@ -0,0 +1,102 @@
1
+ import { z } from "zod";
2
+ import type { PublicKeyRef } from "./crypto.ts";
3
+ import { type Arrival } from "./door-core.ts";
4
+ import { type LabelQuestion } from "./door-measure.ts";
5
+ /**
6
+ * Where a label came from. `test-set`: the arrival was built to be that kind, so the label is true by construction.
7
+ * `operator`: a person who knows the traffic said so. `challenge`: derived from a passed Turnstile or hCaptcha check,
8
+ * so it carries the provider's own error rate. `door`: the door's own check said so (a verified agent, from
9
+ * `door labels`). Such a label is good for the flags and never for a question about `class`, which would score the
10
+ * door against itself; its `validFor` says so.
11
+ */
12
+ export declare const LABEL_SOURCES: readonly ["test-set", "operator", "challenge", "door"];
13
+ export type LabelSource = (typeof LABEL_SOURCES)[number];
14
+ /**
15
+ * One line of a labels file: what one receipt's arrival really was. A line that `door labels --receipt-ids` exports is
16
+ * also a record of `door measure`, so the fields of that format are accepted here and not read.
17
+ */
18
+ export declare const DoorLabelSchema: z.ZodObject<{
19
+ receiptId: z.ZodString;
20
+ kind: z.ZodString;
21
+ automated: z.ZodBoolean;
22
+ genuine: z.ZodNullable<z.ZodBoolean>;
23
+ source: z.ZodEnum<{
24
+ challenge: "challenge";
25
+ door: "door";
26
+ operator: "operator";
27
+ "test-set": "test-set";
28
+ }>;
29
+ validFor: z.ZodOptional<z.ZodArray<z.ZodEnum<{
30
+ agent: "agent";
31
+ "behaviour.form.fast": "behaviour.form.fast";
32
+ "behaviour.form.noInput": "behaviour.form.noInput";
33
+ "behaviour.navigation.directWrite": "behaviour.navigation.directWrite";
34
+ "behaviour.timing.regular": "behaviour.timing.regular";
35
+ "fingerprint.headers.fetchInvalid": "fingerprint.headers.fetchInvalid";
36
+ "fingerprint.headers.hintsMismatch": "fingerprint.headers.hintsMismatch";
37
+ "fingerprint.headers.mismatch": "fingerprint.headers.mismatch";
38
+ "fingerprint.tls.knownTool": "fingerprint.tls.knownTool";
39
+ "fingerprint.tls.mismatch": "fingerprint.tls.mismatch";
40
+ verified: "verified";
41
+ }>>>;
42
+ set: z.ZodOptional<z.ZodString>;
43
+ session: z.ZodOptional<z.ZodString>;
44
+ label: z.ZodOptional<z.ZodEnum<{
45
+ automated: "automated";
46
+ human: "human";
47
+ }>>;
48
+ labelSource: z.ZodOptional<z.ZodString>;
49
+ flags: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodBoolean>>;
50
+ }, z.core.$strict>;
51
+ export type DoorLabel = z.infer<typeof DoorLabelSchema>;
52
+ export interface DoorQuestion {
53
+ id: LabelQuestion;
54
+ asks: string;
55
+ /** what an error is for this question */
56
+ wrong: string;
57
+ applies: (label: DoorLabel) => boolean;
58
+ isWrong: (arrival: Arrival, label: DoorLabel) => boolean;
59
+ }
60
+ /** The questions the door's signals answer today. Each is scored only on the labels it applies to. */
61
+ export declare const DOOR_QUESTIONS: DoorQuestion[];
62
+ export interface ErrorRateRow {
63
+ question: DoorQuestion["id"];
64
+ kind: string;
65
+ source: LabelSource;
66
+ arrivals: number;
67
+ wrong: number;
68
+ rate: number;
69
+ /** the Wilson score interval at 95% */
70
+ low: number;
71
+ high: number;
72
+ }
73
+ /** The Wilson score interval for `errors` in `n` at 95%. With no errors it still gives an upper bound, which is the honest figure for a small sample. */
74
+ export declare function wilson(errors: number, n: number): {
75
+ low: number;
76
+ high: number;
77
+ };
78
+ export interface DoorArrivals {
79
+ arrivals: Map<string, Arrival>;
80
+ skipped: {
81
+ file: string;
82
+ reason: string;
83
+ }[];
84
+ }
85
+ /** The arrival fact of every door receipt in `dir` that verifies under `issuerKeys`, the principal keys that sign its grants, and the log, when given. Anything else is skipped with its reason. */
86
+ export declare function readDoorArrivals(dir: string, opts: {
87
+ issuerKeys: PublicKeyRef[];
88
+ principalKeys?: PublicKeyRef[];
89
+ logKeys?: PublicKeyRef[];
90
+ logFile?: string;
91
+ }): DoorArrivals;
92
+ /** A labels file: one JSON object per line, as `DoorLabelSchema`. A line that does not parse throws with its number; a receipt labelled twice throws. */
93
+ export declare function parseLabels(text: string): DoorLabel[];
94
+ /** Labels from passed challenges, for receipts that have no label: the provider judged a person present. They carry the provider's error rate. */
95
+ export declare function challengeLabels(arrivals: Map<string, Arrival>, labelled: Iterable<string>): DoorLabel[];
96
+ /** One row per question, label source, and kind. `unmatched` lists labels whose receipt was not read or did not verify. */
97
+ export declare function doorErrorRates(arrivals: Map<string, Arrival>, labels: DoorLabel[]): {
98
+ rows: ErrorRateRow[];
99
+ unmatched: string[];
100
+ };
101
+ /** The rows as Markdown: a table per question, each row one kind from one label source. */
102
+ export declare function formatErrorRates(rows: ErrorRateRow[]): string;