@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/dist/door-core.js CHANGED
@@ -3,8 +3,10 @@ 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";
8
10
  import { createHistoryTracker, createSeenCounter, fingerprintKey, FORM_REPORT_HEADER, historySource, observationOf, signalsOf } from "./door-signals.js";
9
11
  import { createPartnerEngine, PARTNER_FACT, PARTNER_TOOL } from "./door-partner.js";
10
12
  import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
@@ -129,6 +131,36 @@ export function createRateTracker(now = () => performance.now(), limits = {}) {
129
131
  clearInterval(timer); },
130
132
  };
131
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
+ }
132
164
  const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "proxy-connection"]);
133
165
  /** request headers the receipt records in clear; everything else is relayed and not recorded */
134
166
  const RECORDED_HEADERS = ["user-agent", "content-type", "accept", "host"];
@@ -276,12 +308,15 @@ export function signedRequestOf(req) {
276
308
  * Without a grant, a Web Bot Auth signature the door verified (`signature`, from `createWebBotAuthVerifier`) makes the
277
309
  * arrival `verified` as its signature agent. With both, the signature binds the grant to its sender when the grant names
278
310
  * that signature agent; a grant presented under another agent's signature is `wrong-sender` and the arrival `claimed`.
279
- * 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.
280
315
  * An `x-agent-custody-agent` header or a signature that did not verify alone is `claimed`. Nothing at all is `unknown`.
281
316
  * Without `signature`, a `Signature-Input` header is recorded as `unchecked`. `revoked`, when given, says why a grant
282
317
  * that verified is revoked (from its chain's digests, leaf first), or null when it is not; a revoked grant is `claimed`.
283
318
  */
284
- export function classifyArrival(req, trusted, route, trustProxy, at, signature, revoked) {
319
+ export function classifyArrival(req, trusted, route, trustProxy, at, signature, revoked, registry, contentDigest) {
285
320
  const url = requestUrl(req);
286
321
  const method = (req.method ?? "GET").toUpperCase();
287
322
  const declaredRaw = req.headers[AGENT_HEADER];
@@ -292,6 +327,8 @@ export function classifyArrival(req, trusted, route, trustProxy, at, signature,
292
327
  // only on the last line, with a verified grant for that did:key. Everywhere else it is invalid, so that no policy
293
328
  // takes it for a checked identity.
294
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";
295
332
  const norm = normalizePath(url.pathname);
296
333
  const baseOf = (s) => ({
297
334
  signature: s.outcome,
@@ -299,18 +336,19 @@ export function classifyArrival(req, trusted, route, trustProxy, at, signature,
299
336
  ...("keyid" in s && s.keyid ? { signatureKeyid: s.keyid } : {}),
300
337
  ...("error" in s ? { signatureError: s.error } : {}),
301
338
  ...(declared ? { declared } : {}),
339
+ ...(passport ? { passport } : {}),
302
340
  remote: remoteOf(req, trustProxy),
303
341
  method,
304
342
  path: "path" in norm ? norm.path : url.pathname,
305
343
  route,
306
344
  });
307
- 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);
308
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);
309
347
  if (!envelope) {
310
- if (signer && !didSigner)
348
+ if (signer && (!didSigner || admitted))
311
349
  return { arrival: { class: "verified", subject: signer.agent, grant: "absent", ...base }, signer };
312
- const claimed = !!declared || sig.outcome !== "absent";
313
- 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 } };
314
352
  }
315
353
  const checked = verifyDelegation(envelope, trusted);
316
354
  const asserted = decodeDelegation(envelope)?.agent;
@@ -378,6 +416,9 @@ const json = jsonAnswer;
378
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. */
379
417
  export function createDoorCoreWith(cfg, io, framework, opts = {}) {
380
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");
381
422
  const revoked = io.revoked;
382
423
  const captureSecret = cfg.captureKeyEnv ? io.secret(cfg.captureKeyEnv) : undefined;
383
424
  if (cfg.captureKeyEnv && captureSecret === undefined)
@@ -415,6 +456,37 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
415
456
  if (!hasPermitRule(first.text))
416
457
  console.error(`agent-custody door: ${io.policySource} has no permit rule, so every arrival is refused`);
417
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
+ };
418
490
  const currentPolicy = () => {
419
491
  try {
420
492
  const next = readPolicy();
@@ -444,8 +516,24 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
444
516
  const route = "path" in norm ? matchRoute(cfg.routes, cfg.unmatchedRoute, method, path) : cfg.unmatchedRoute;
445
517
  const presented = webBotAuth && req.headers["signature-input"] !== undefined ? parseGrantHeader(req) : null;
446
518
  const trustedGrant = presented ? verifyDelegation(presented, trusted) : undefined;
447
- const signature = webBotAuth ? await webBotAuth.verify(signedRequestOf(req), trustedGrant?.ok ? trustedGrant.delegation.agent : undefined) : undefined;
448
- 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 };
449
537
  const checkedAgent = arrival.class === "verified";
450
538
  const by = checkedAgent ? "agent" : "remote";
451
539
  const source = `${by}:${checkedAgent ? arrival.subject : arrival.remote}`;
@@ -479,8 +567,6 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
479
567
  }
480
568
  }
481
569
  const { text: policyText, digest: pDigest } = currentPolicy();
482
- const read = readArrivalBody ? await readArrivalBody(cfg.maxBodyBytes) : null;
483
- const body = read === null ? Buffer.alloc(0) : "body" in read ? read.body : null;
484
570
  const headers = {};
485
571
  for (const name of RECORDED_HEADERS) {
486
572
  const v = req.headers[name];
@@ -604,7 +690,7 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
604
690
  release: () => void (inFlight -= 1),
605
691
  busy: () => json(503, { "retry-after": "1" }, { error: `the door is handling ${cfg.maxInFlight} requests; this one was not read, decided, or relayed. Retry` }),
606
692
  decide,
607
- consumed: (name, req, arrival) => name === GRANT_HEADER || name === AGENT_HEADER || name === challengeHeader || (!!history && name === FORM_REPORT_HEADER) ||
693
+ consumed: (name, req, arrival) => name === GRANT_HEADER || name === AGENT_HEADER || name === PASSPORT_HEADER || name === challengeHeader || (!!history && name === FORM_REPORT_HEADER) ||
608
694
  // the grant travelled in Authorization: it is the door's credential, not the origin's
609
695
  (name === "authorization" && arrival.grant !== "absent" && !req.headers[GRANT_HEADER]),
610
696
  async record(d, execution) {
@@ -57,6 +57,10 @@ export interface DoorWorkerEnv {
57
57
  LOG_HASH_ONLY?: string;
58
58
  /** principal keys whose grants are a passport, SPKI PEM */
59
59
  TRUSTED_PRINCIPAL_KEYS?: string;
60
+ /** agent registry keys whose passports admit an agent, SPKI PEM */
61
+ TRUSTED_REGISTRY_KEYS?: string;
62
+ /** the site's admission lists, the JSON of a door's `admissionLists` file */
63
+ ADMISSION_LISTS?: string;
60
64
  /** a JSON array of revoked grant digests, as in a gateway's or door's `revokedGrants` file */
61
65
  REVOKED_GRANTS?: string;
62
66
  /** secret: the door's signing key, PKCS8 PEM (`agent-custody keygen`) */
@@ -19,6 +19,8 @@ const NOT_IN_A_WORKER = {
19
19
  logFile: "the log is LOG_URL",
20
20
  log: "the log is LOG_URL, LOG_KEYS, LOG_ID, LOG_TOKEN",
21
21
  trustedPrincipalKeys: "trusted principal keys are the TRUSTED_PRINCIPAL_KEYS variable",
22
+ trustedRegistryKeys: "trusted registry keys are the TRUSTED_REGISTRY_KEYS variable",
23
+ admissionLists: "admission lists are the ADMISSION_LISTS variable",
22
24
  revokedGrants: "revoked grants are the REVOKED_GRANTS variable",
23
25
  authz: "a Worker relays; nginx and Envoy ask a Node door",
24
26
  trustProxy: "the Worker reads the client's address from Cloudflare (CF-Connecting-IP)",
@@ -149,8 +151,10 @@ export function workerDoorIO(env, f) {
149
151
  return {
150
152
  key,
151
153
  trustedPrincipalKeys: pemKeys(env.TRUSTED_PRINCIPAL_KEYS),
154
+ trustedRegistryKeys: pemKeys(env.TRUSTED_REGISTRY_KEYS),
152
155
  readPolicy: () => ({ text: env.DOOR_POLICY, key: "DOOR_POLICY" }),
153
156
  policySource: "the DOOR_POLICY variable",
157
+ ...(env.ADMISSION_LISTS ? { readAdmission: () => ({ text: env.ADMISSION_LISTS, key: "ADMISSION_LISTS" }), admissionSource: "the ADMISSION_LISTS variable" } : {}),
154
158
  revoked: (digests) => (!digests.some((d) => revoked.has(d)) ? null : revoked.has(digests[0]) ? "the grant has been revoked" : "a grant above it in its chain has been revoked"),
155
159
  secret: (name) => (typeof env[name] === "string" ? env[name] : undefined),
156
160
  issuer: (capture) => createObjectIssuer(key, store, sink, { capture }),
package/dist/door.js CHANGED
@@ -48,6 +48,7 @@ export function nodeDoorIO(cfg, options = {}) {
48
48
  return {
49
49
  key,
50
50
  trustedPrincipalKeys: cfg.trustedPrincipalKeys.map(loadPublicKey),
51
+ trustedRegistryKeys: cfg.trustedRegistryKeys.map(loadPublicKey),
51
52
  // the bytes and the metadata come from one open file
52
53
  readPolicy() {
53
54
  const fd = openSync(cfg.policyFile, "r");
@@ -60,6 +61,21 @@ export function nodeDoorIO(cfg, options = {}) {
60
61
  }
61
62
  },
62
63
  policySource: cfg.policyFile,
64
+ ...(cfg.admissionLists ? {
65
+ readAdmission(known) {
66
+ const fd = openSync(cfg.admissionLists, "r");
67
+ try {
68
+ const st = fstatSync(fd);
69
+ const key = `${st.ino}:${st.mtimeMs}:${st.ctimeMs}:${st.size}`;
70
+ // a file of 64 full lists is tens of megabytes: it is read only when it has changed
71
+ return key === known ? { key } : { text: readFileSync(fd, "utf8"), key };
72
+ }
73
+ finally {
74
+ closeSync(fd);
75
+ }
76
+ },
77
+ admissionSource: cfg.admissionLists,
78
+ } : {}),
63
79
  revoked(chainDigests) {
64
80
  try {
65
81
  revocations.reload();
@@ -0,0 +1,24 @@
1
+ import { z } from "zod";
2
+ export declare const ERC8004_REGISTRATION_TYPE = "https://eips.ethereum.org/EIPS/eip-8004#registration-v1";
3
+ /** `eip155:<chainId>:<Identity Registry address>`, as ERC-8004 names a registry */
4
+ export declare const ERC8004_REGISTRY: RegExp;
5
+ export declare const Erc8004LinkSchema: z.ZodObject<{
6
+ agentRegistry: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
7
+ agentId: z.ZodString;
8
+ }, z.core.$strip>;
9
+ export type Erc8004Link = z.infer<typeof Erc8004LinkSchema>;
10
+ /** A link as the registry checked it: the token's owner and the block it read, and when. */
11
+ export interface Erc8004Checked extends Erc8004Link {
12
+ owner: string;
13
+ block: number;
14
+ /** sha256 of the registration file's bytes */
15
+ fileDigest: string;
16
+ checkedAt: string;
17
+ }
18
+ export type Erc8004Check = {
19
+ ok: true;
20
+ link: Erc8004Checked;
21
+ } | {
22
+ ok: false;
23
+ error: string;
24
+ };
@@ -0,0 +1,11 @@
1
+ // The ERC-8004 link as the registry stores it and a passport carries it: the names and shapes only, so that the
2
+ // registry, and a door that reads a passport, need nothing that reads a chain.
3
+ import { z } from "zod";
4
+ export const ERC8004_REGISTRATION_TYPE = "https://eips.ethereum.org/EIPS/eip-8004#registration-v1";
5
+ /** `eip155:<chainId>:<Identity Registry address>`, as ERC-8004 names a registry */
6
+ export const ERC8004_REGISTRY = /^eip155:([1-9][0-9]{0,11}):(0x[0-9a-fA-F]{40})$/;
7
+ export const Erc8004LinkSchema = z.object({
8
+ agentRegistry: z.string().regex(ERC8004_REGISTRY, { message: "agentRegistry is eip155:<chain id>:<registry address>" }).transform((r) => r.toLowerCase()),
9
+ /** the token id, in decimal: a uint256 does not fit in a JSON number */
10
+ agentId: z.string().regex(/^(0|[1-9][0-9]{0,77})$/, { message: "agentId is the token id in decimal" }).refine((v) => !/^[0-9]+$/.test(v) || BigInt(v) < 2n ** 256n, { message: "agentId is not a uint256" }),
11
+ });
@@ -0,0 +1,26 @@
1
+ export { ERC8004_REGISTRATION_TYPE, ERC8004_REGISTRY, Erc8004LinkSchema, type Erc8004Check, type Erc8004Checked, type Erc8004Link } from "./erc8004-link.ts";
2
+ import { type Erc8004Check, type Erc8004Link } from "./erc8004-link.ts";
3
+ export interface Erc8004ResolverOptions {
4
+ /** a JSON-RPC URL for each chain id the registry reads; from the environment, since a provider's URL often carries its key */
5
+ rpc: Record<string, string>;
6
+ /** an https IPFS gateway (`https://ipfs.io`); without one an `ipfs://` registration file is refused */
7
+ ipfsGateway?: string;
8
+ timeoutMs?: number;
9
+ maxFileBytes?: number;
10
+ /** for the JSON-RPC calls; the global fetch by default */
11
+ fetch?: typeof fetch;
12
+ /** fetches an https registration file; by default over node:https, refusing internal addresses and redirects. For tests */
13
+ fetchFile?: (url: string, o: {
14
+ timeoutMs: number;
15
+ maxBytes: number;
16
+ signal: AbortSignal;
17
+ }) => Promise<Buffer>;
18
+ }
19
+ export interface Erc8004Resolver {
20
+ /** the chain ids it has an RPC URL for */
21
+ chains: string[];
22
+ check(link: Erc8004Link, didKey: string, now?: Date): Promise<Erc8004Check>;
23
+ }
24
+ /** The string an ABI-encoded `string` return value holds; throws when the encoding does not hold together. */
25
+ export declare function decodeAbiString(hex: string, maxBytes: number): string;
26
+ export declare function createErc8004Resolver(o: Erc8004ResolverOptions): Erc8004Resolver;
@@ -0,0 +1,208 @@
1
+ // An ERC-8004 identity for a registered agent. The registry links an agent to its token in an ERC-8004 Identity
2
+ // Registry only when the chain and the token's registration file agree with the registry's own entry: the token
3
+ // exists, its registration file is a v1 file that is active, names that very token among its registrations, and lists
4
+ // the agent's did:key as a DID service. The check runs on the registry, never at the door: a door reads the link from
5
+ // the passport the registry signed. The chain is read through JSON-RPC (eth_call at one block), and the file is
6
+ // fetched once, over https or through a configured IPFS gateway, with a timeout and a size cap, never from an internal
7
+ // address. ERC-8004 is a draft, so only the registration-v1 file type is accepted.
8
+ import { request as httpsRequest } from "node:https";
9
+ import { z } from "zod";
10
+ import { sha256Hex } from "./crypto.js";
11
+ import { internalAddress, isAddressLiteral } from "./addresses.js";
12
+ import { publicOnlyLookup } from "./egress.js";
13
+ export { ERC8004_REGISTRATION_TYPE, ERC8004_REGISTRY, Erc8004LinkSchema } from "./erc8004-link.js";
14
+ import { ERC8004_REGISTRATION_TYPE, ERC8004_REGISTRY } from "./erc8004-link.js";
15
+ const OWNER_OF = "0x6352211e";
16
+ const TOKEN_URI = "0xc87b56dd";
17
+ const word = (n) => n.toString(16).padStart(64, "0");
18
+ class ChainError extends Error {
19
+ }
20
+ /** The string an ABI-encoded `string` return value holds; throws when the encoding does not hold together. */
21
+ export function decodeAbiString(hex, maxBytes) {
22
+ const h = hex.replace(/^0x/, "");
23
+ if (!/^[0-9a-f]*$/i.test(h) || h.length < 128)
24
+ throw new ChainError("the answer is not an ABI-encoded string");
25
+ const offset = Number.parseInt(h.slice(0, 64), 16) * 2;
26
+ const length = Number.parseInt(h.slice(offset, offset + 64), 16);
27
+ if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset + 64 > h.length)
28
+ throw new ChainError("the answer is not an ABI-encoded string");
29
+ if (length > maxBytes)
30
+ throw new ChainError(`the token URI is longer than ${maxBytes} bytes`);
31
+ const data = h.slice(offset + 64, offset + 64 + length * 2);
32
+ if (data.length !== length * 2)
33
+ throw new ChainError("the answer is shorter than the string it encodes");
34
+ return Buffer.from(data, "hex").toString("utf8");
35
+ }
36
+ /** An https GET that never dials an internal address for a host name, follows no redirect, and stops at the size cap. */
37
+ function httpsFile(url, o) {
38
+ // an address literal is never looked up, so the lookup's filter does not see it
39
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, "");
40
+ if (isAddressLiteral(host) && internalAddress(host))
41
+ return Promise.reject(new Error(`${host} is an internal address; the registry does not fetch from it`));
42
+ return new Promise((resolve, reject) => {
43
+ const req = httpsRequest(url, { method: "GET", headers: { accept: "application/json" }, lookup: publicOnlyLookup(), timeout: o.timeoutMs, signal: o.signal }, (res) => {
44
+ if ((res.statusCode ?? 0) >= 300) {
45
+ res.resume();
46
+ return reject(new Error(`${url} answered ${res.statusCode}${res.headers.location ? `, a redirect, which the registry does not follow` : ""}`));
47
+ }
48
+ const chunks = [];
49
+ let size = 0;
50
+ res.on("data", (c) => {
51
+ size += c.length;
52
+ if (size > o.maxBytes) {
53
+ req.destroy();
54
+ reject(new Error(`${url} is larger than ${o.maxBytes} bytes`));
55
+ }
56
+ else
57
+ chunks.push(c);
58
+ });
59
+ res.on("end", () => resolve(Buffer.concat(chunks)));
60
+ res.on("error", reject);
61
+ });
62
+ req.on("timeout", () => req.destroy(new Error(`${url} did not answer within ${o.timeoutMs} ms`)));
63
+ req.on("error", reject);
64
+ req.end();
65
+ });
66
+ }
67
+ const RegistrationSchema = z.object({
68
+ type: z.literal(ERC8004_REGISTRATION_TYPE),
69
+ active: z.boolean(),
70
+ services: z.array(z.object({ name: z.string(), endpoint: z.string() }).passthrough()).max(256),
71
+ registrations: z.array(z.object({ agentId: z.union([z.string(), z.number()]), agentRegistry: z.string() }).passthrough()).max(256),
72
+ }).passthrough();
73
+ export function createErc8004Resolver(o) {
74
+ const timeoutMs = o.timeoutMs ?? 5_000;
75
+ const maxFileBytes = o.maxFileBytes ?? 64 * 1024;
76
+ const f = o.fetch ?? fetch;
77
+ const fetchFile = o.fetchFile ?? httpsFile;
78
+ // `timeout` on node:https is the socket's idle time, so a host that sends a byte now and then would never trip it;
79
+ // the whole fetch ends at the deadline, whatever the fetcher does with the signal
80
+ const fileWithin = (url) => {
81
+ const signal = AbortSignal.timeout(timeoutMs);
82
+ const late = new Promise((_, reject) => {
83
+ const stop = () => reject(new Error(`${url} did not finish within ${timeoutMs} ms`));
84
+ if (signal.aborted)
85
+ stop();
86
+ else
87
+ signal.addEventListener("abort", stop, { once: true });
88
+ });
89
+ return Promise.race([fetchFile(url, { timeoutMs, maxBytes: maxFileBytes, signal }), late]);
90
+ };
91
+ for (const [chain, url] of Object.entries(o.rpc)) {
92
+ if (!/^[1-9][0-9]{0,11}$/.test(chain))
93
+ throw new Error(`ERC-8004: "${chain}" is not a chain id`);
94
+ if (!/^https?:\/\//.test(url))
95
+ throw new Error(`ERC-8004: the RPC URL for chain ${chain} is not http(s)`);
96
+ }
97
+ if (o.ipfsGateway && !o.ipfsGateway.startsWith("https://"))
98
+ throw new Error("ERC-8004: the IPFS gateway must be https");
99
+ const gateway = o.ipfsGateway?.replace(/\/+$/, "");
100
+ const rpc = async (url, method, params) => {
101
+ let res;
102
+ try {
103
+ res = await f(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }), signal: AbortSignal.timeout(timeoutMs) });
104
+ }
105
+ catch (e) {
106
+ throw new ChainError(`the chain's RPC could not be reached: ${e instanceof Error ? e.message : String(e)}`);
107
+ }
108
+ if (!res.ok)
109
+ throw new ChainError(`the chain's RPC answered ${res.status}`);
110
+ const body = (await res.json().catch(() => null));
111
+ if (body?.error)
112
+ throw new ChainError(`the chain refused ${method}: ${String(body.error.message ?? "no message").slice(0, 200)}`);
113
+ if (typeof body?.result !== "string")
114
+ throw new ChainError(`the chain's answer to ${method} is not a hex string`);
115
+ return body.result;
116
+ };
117
+ /** The registration file's bytes for a token URI: inline, over https, or through the IPFS gateway. */
118
+ const fileOf = async (uri) => {
119
+ const inline = /^data:application\/json(;charset=utf-8)?(;base64)?,(.*)$/is.exec(uri);
120
+ if (inline) {
121
+ const bytes = inline[2] ? Buffer.from(inline[3], "base64") : Buffer.from(decodeURIComponent(inline[3]), "utf8");
122
+ if (bytes.length > maxFileBytes)
123
+ throw new Error(`the inline registration file is larger than ${maxFileBytes} bytes`);
124
+ return bytes;
125
+ }
126
+ if (uri.startsWith("ipfs://")) {
127
+ if (!gateway)
128
+ throw new Error("the registration file is on IPFS, and this registry has no IPFS gateway configured");
129
+ const path = uri.slice("ipfs://".length).replace(/^ipfs\//, "");
130
+ const [cid, ...segments] = path.split("/");
131
+ // the token's owner writes this path: a "." or ".." segment would climb out of /ipfs/ to any path on the gateway
132
+ if (!cid || !/^[A-Za-z0-9]+$/.test(cid) || segments.some((p) => !/^[A-Za-z0-9._~-]+$/.test(p) || p === "." || p === ".."))
133
+ throw new Error("the IPFS URI is not a CID and a path of plain segments");
134
+ const prefix = `${new URL(gateway).pathname.replace(/\/+$/, "")}/ipfs/${cid}`;
135
+ const url = new URL(`${gateway}/ipfs/${path}`);
136
+ if (url.origin !== new URL(gateway).origin || (url.pathname !== prefix && !url.pathname.startsWith(`${prefix}/`)))
137
+ throw new Error("the IPFS URI leaves the gateway's /ipfs/ path");
138
+ return fileWithin(url.toString());
139
+ }
140
+ if (uri.startsWith("https://")) {
141
+ const u = new URL(uri);
142
+ if (u.username || u.password)
143
+ throw new Error("the registration file's URL carries credentials");
144
+ return fileWithin(u.toString());
145
+ }
146
+ throw new Error(`the token URI is not https, ipfs, or an inline JSON data URI: ${uri.slice(0, 60)}`);
147
+ };
148
+ async function check(link, didKey, now = new Date()) {
149
+ const m = ERC8004_REGISTRY.exec(link.agentRegistry);
150
+ if (!m)
151
+ return { ok: false, error: "agentRegistry is not eip155:<chain id>:<registry address>" };
152
+ const [, chain, registry] = m;
153
+ const url = o.rpc[chain];
154
+ if (!url)
155
+ return { ok: false, error: `this registry reads no ERC-8004 registry on chain ${chain}; it reads chains ${Object.keys(o.rpc).join(", ") || "none"}` };
156
+ const token = word(BigInt(link.agentId));
157
+ try {
158
+ const blockHex = await rpc(url, "eth_blockNumber", []);
159
+ const block = Number.parseInt(blockHex, 16);
160
+ if (!Number.isSafeInteger(block))
161
+ throw new ChainError("the chain's block number is not a number");
162
+ let ownerWord;
163
+ try {
164
+ ownerWord = await rpc(url, "eth_call", [{ to: registry, data: `${OWNER_OF}${token}` }, blockHex]);
165
+ }
166
+ catch (e) {
167
+ if (e instanceof ChainError && e.message.startsWith("the chain refused"))
168
+ return { ok: false, error: `token ${link.agentId} does not exist in ${link.agentRegistry} (${e.message})` };
169
+ throw e;
170
+ }
171
+ const owner = `0x${ownerWord.replace(/^0x/, "").slice(-40)}`.toLowerCase();
172
+ if (!/^0x[0-9a-f]{40}$/.test(owner) || /^0x0{40}$/.test(owner))
173
+ return { ok: false, error: `token ${link.agentId} in ${link.agentRegistry} has no owner` };
174
+ const uri = decodeAbiString(await rpc(url, "eth_call", [{ to: registry, data: `${TOKEN_URI}${token}` }, blockHex]), Math.ceil(maxFileBytes * 1.4) + 64);
175
+ let bytes;
176
+ try {
177
+ bytes = await fileOf(uri.trim());
178
+ }
179
+ catch (e) {
180
+ return { ok: false, error: `the registration file could not be read: ${e instanceof Error ? e.message : String(e)}` };
181
+ }
182
+ let raw;
183
+ try {
184
+ raw = JSON.parse(bytes.toString("utf8"));
185
+ }
186
+ catch {
187
+ return { ok: false, error: "the registration file is not JSON" };
188
+ }
189
+ const parsed = RegistrationSchema.safeParse(raw);
190
+ if (!parsed.success)
191
+ return { ok: false, error: `the registration file is not an ERC-8004 registration-v1 file: ${parsed.error.issues.slice(0, 3).map((i) => `${i.path.join(".") || "file"} ${i.message}`).join("; ")}` };
192
+ const file = parsed.data;
193
+ if (!file.active)
194
+ return { ok: false, error: "the registration file says the agent is not active" };
195
+ if (!file.registrations.some((r) => String(r.agentId) === link.agentId && r.agentRegistry.toLowerCase() === link.agentRegistry))
196
+ return { ok: false, error: `the registration file does not list token ${link.agentId} of ${link.agentRegistry} among its registrations` };
197
+ if (!file.services.some((s) => s.name === "DID" && s.endpoint === didKey))
198
+ return { ok: false, error: `the registration file lists no DID service with the agent's key ${didKey}` };
199
+ return { ok: true, link: { agentRegistry: link.agentRegistry, agentId: link.agentId, owner, block, fileDigest: sha256Hex(bytes), checkedAt: now.toISOString() } };
200
+ }
201
+ catch (e) {
202
+ if (e instanceof ChainError)
203
+ return { ok: false, error: e.message };
204
+ throw e;
205
+ }
206
+ }
207
+ return { chains: Object.keys(o.rpc), check };
208
+ }
package/dist/index.d.ts CHANGED
@@ -7,8 +7,8 @@ export { hecEvent, splunkExporter } from "./splunk.ts";
7
7
  export { serveConsole, type ConsoleOptions, type RunningConsole } from "./console.ts";
8
8
  export { checkConfig, formatFindings, type CheckFinding, type CheckOptions } from "./check.ts";
9
9
  export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.ts";
10
- export { AGENT_HEADER, ARRIVAL_FACT, CLASS_HEADER, DOOR_DEFAULT_CAPTURE, DOOR_VERSION, MAX_CHALLENGE_TOKEN, RECEIPT_HEADER, RATE_BURST_MS, RATE_MINUTE_MS, cedarArgs, classifyArrival, createDoorHost, createRateTracker, matchRoute, normalizePath, remoteOf, serveDoor, signedRequestOf, verifyChallengeToken } from "./door.ts";
11
- export { DIRECTORY_MEDIA_TYPE, DIRECTORY_PATH, WEB_BOT_AUTH_TAG, agentOrigin, createMemoryNonceStore, createWebBotAuthVerifier, jwkThumbprint, normalizeAuthority, parseDictionary, signatureBase } from "./web-bot-auth.ts";
10
+ export { AGENT_HEADER, ARRIVAL_FACT, CLASS_HEADER, DOOR_DEFAULT_CAPTURE, DOOR_VERSION, MAX_CHALLENGE_TOKEN, RECEIPT_HEADER, RATE_BURST_MS, RATE_MINUTE_MS, PASSPORT_COVERED, cedarArgs, classifyArrival, createDoorHost, createRateTracker, matchRoute, normalizePath, remoteOf, serveDoor, signedRequestOf, verifyChallengeToken } from "./door.ts";
11
+ export { DIRECTORY_MEDIA_TYPE, DIRECTORY_PATH, WEB_BOT_AUTH_TAG, agentOrigin, contentDigestMatches, createMemoryNonceStore, createWebBotAuthVerifier, jwkThumbprint, normalizeAuthority, parseDictionary, signatureBase } from "./web-bot-auth.ts";
12
12
  export { DESTINATION_FACT, EGRESS_VERSION, PROXY_REALM, checkProxyCredential, createEgressHost, destinationName, normalizeHost, parseAuthority, publicOnlyLookup, serveEgress } from "./egress.ts";
13
13
  export { internalAddress } from "./addresses.ts";
14
14
  export { DRAFT_WARNING, draftEgressPolicy } from "./egress-draft.ts";
@@ -29,7 +29,7 @@ export { challengeLabels, DOOR_QUESTIONS, DoorLabelSchema, doorErrorRates, forma
29
29
  export type { DoorArrivals, DoorLabel, DoorQuestion, ErrorRateRow, LabelSource } from "./door-error-rates.ts";
30
30
  export { buildDoorTestSet, DOOR_TEST_KINDS, formatTestKinds } from "./door-test-set.ts";
31
31
  export type { DoorTestSet, TestKind } from "./door-test-set.ts";
32
- export type { Arrival, ArrivalChallenge, ArrivalClass, ArrivalRate, ChallengeCheck, Classified, DoorHost, DoorOptions, DoorRequest, DoorServerOptions, RateTracker, RateTrackerLimits, RunningDoor } from "./door.ts";
32
+ export type { Arrival, ArrivalChallenge, ArrivalAdmission, ArrivalClass, ArrivalPassport, ArrivalRate, ChallengeCheck, Classified, DoorHost, DoorOptions, DoorRequest, DoorServerOptions, RateTracker, RateTrackerLimits, RunningDoor } from "./door.ts";
33
33
  export type { NonceState, NonceStore, SignatureCheck, SignedRequest, WebBotAuthOptions, WebBotAuthVerifier } from "./web-bot-auth.ts";
34
34
  export * from "./capture.ts";
35
35
  export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.ts";
@@ -71,6 +71,12 @@ export * from "./operations.ts";
71
71
  export * from "./crypto.ts";
72
72
  export * from "./delegation.ts";
73
73
  export { base58btcDecode, base58btcEncode, DID_KEY_PREFIX, didKeyOf, publicKeyFromDidKey } from "./did-key.ts";
74
+ export { DEFAULT_PASSPORT_SECONDS, MAX_PASSPORT_HEADER, MAX_PASSPORT_SECONDS, PASSPORT_HEADER, PASSPORT_TYPE, PassportSchema, REGISTRY_DOCUMENT_PATH, issuePassport, parsePassportHeader, passportDigest, passportHeader, registrationMessage, registrationProof, verifyPassport } from "./registry.ts";
75
+ export type { AgentEntry, Passport, PassportVerifyResult } from "./registry.ts";
76
+ export { AdmissionListsSchema, canonicalAgent, canonicalRegistry, compileAdmissionLists, LIST_NAME, MAX_LIST_ENTRIES, MAX_LISTS } from "./admission.ts";
77
+ export type { AdmissionEntry, AdmissionLists, ArrivalIdentity } from "./admission.ts";
78
+ export { createErc8004Resolver, decodeAbiString, ERC8004_REGISTRATION_TYPE, ERC8004_REGISTRY, Erc8004LinkSchema } from "./erc8004.ts";
79
+ export type { Erc8004Check, Erc8004Checked, Erc8004Link, Erc8004Resolver, Erc8004ResolverOptions } from "./erc8004.ts";
74
80
  export * from "./approval.ts";
75
81
  export * from "./approval-requests.ts";
76
82
  export * from "./gateway.ts";
package/dist/index.js CHANGED
@@ -6,8 +6,8 @@ export { hecEvent, splunkExporter } from "./splunk.js";
6
6
  export { serveConsole } from "./console.js";
7
7
  export { checkConfig, formatFindings } from "./check.js";
8
8
  export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.js";
9
- export { AGENT_HEADER, ARRIVAL_FACT, CLASS_HEADER, DOOR_DEFAULT_CAPTURE, DOOR_VERSION, MAX_CHALLENGE_TOKEN, RECEIPT_HEADER, RATE_BURST_MS, RATE_MINUTE_MS, cedarArgs, classifyArrival, createDoorHost, createRateTracker, matchRoute, normalizePath, remoteOf, serveDoor, signedRequestOf, verifyChallengeToken } from "./door.js";
10
- export { DIRECTORY_MEDIA_TYPE, DIRECTORY_PATH, WEB_BOT_AUTH_TAG, agentOrigin, createMemoryNonceStore, createWebBotAuthVerifier, jwkThumbprint, normalizeAuthority, parseDictionary, signatureBase } from "./web-bot-auth.js";
9
+ export { AGENT_HEADER, ARRIVAL_FACT, CLASS_HEADER, DOOR_DEFAULT_CAPTURE, DOOR_VERSION, MAX_CHALLENGE_TOKEN, RECEIPT_HEADER, RATE_BURST_MS, RATE_MINUTE_MS, PASSPORT_COVERED, cedarArgs, classifyArrival, createDoorHost, createRateTracker, matchRoute, normalizePath, remoteOf, serveDoor, signedRequestOf, verifyChallengeToken } from "./door.js";
10
+ export { DIRECTORY_MEDIA_TYPE, DIRECTORY_PATH, WEB_BOT_AUTH_TAG, agentOrigin, contentDigestMatches, createMemoryNonceStore, createWebBotAuthVerifier, jwkThumbprint, normalizeAuthority, parseDictionary, signatureBase } from "./web-bot-auth.js";
11
11
  export { DESTINATION_FACT, EGRESS_VERSION, PROXY_REALM, checkProxyCredential, createEgressHost, destinationName, normalizeHost, parseAuthority, publicOnlyLookup, serveEgress } from "./egress.js";
12
12
  export { internalAddress } from "./addresses.js";
13
13
  export { DRAFT_WARNING, draftEgressPolicy } from "./egress-draft.js";
@@ -39,6 +39,9 @@ export * from "./operations.js";
39
39
  export * from "./crypto.js";
40
40
  export * from "./delegation.js";
41
41
  export { base58btcDecode, base58btcEncode, DID_KEY_PREFIX, didKeyOf, publicKeyFromDidKey } from "./did-key.js";
42
+ export { DEFAULT_PASSPORT_SECONDS, MAX_PASSPORT_HEADER, MAX_PASSPORT_SECONDS, PASSPORT_HEADER, PASSPORT_TYPE, PassportSchema, REGISTRY_DOCUMENT_PATH, issuePassport, parsePassportHeader, passportDigest, passportHeader, registrationMessage, registrationProof, verifyPassport } from "./registry.js";
43
+ export { AdmissionListsSchema, canonicalAgent, canonicalRegistry, compileAdmissionLists, LIST_NAME, MAX_LIST_ENTRIES, MAX_LISTS } from "./admission.js";
44
+ export { createErc8004Resolver, decodeAbiString, ERC8004_REGISTRATION_TYPE, ERC8004_REGISTRY, Erc8004LinkSchema } from "./erc8004.js";
42
45
  export * from "./approval.js";
43
46
  export * from "./approval-requests.js";
44
47
  export * from "./gateway.js";
@@ -33,6 +33,8 @@ export interface PostgresLogOptions {
33
33
  /** table name prefix; default "log_", giving log_leaves, log_tenants, log_tokens */
34
34
  prefix?: string;
35
35
  }
36
+ /** Runs `fn` inside one transaction on one connection, whichever kind of client this is. */
37
+ export declare function transaction<T>(client: PostgresLike, fn: (q: PostgresLike["query"]) => Promise<T>): Promise<T>;
36
38
  /** One tenant's log in Postgres. Leaves are hashes only; the table never holds a receipt. */
37
39
  export declare class PostgresLog implements LogBackend {
38
40
  readonly tenant: string;
@@ -85,7 +87,7 @@ export interface TokenRecord {
85
87
  /** the last append with this token, to within a minute; null when never used since the column came */
86
88
  lastUsedAt: string | null;
87
89
  }
88
- export declare const AUDIT_ACTIONS: readonly ["tenant.add", "tenant.disable", "tenant.plan", "token.add", "token.revoke", "policy.add", "policy.remove", "sso.set", "sso.remove", "user.mfa-reset"];
90
+ export declare const AUDIT_ACTIONS: readonly ["tenant.add", "tenant.disable", "tenant.plan", "token.add", "token.revoke", "policy.add", "policy.remove", "sso.set", "sso.remove", "user.mfa-reset", "agent.register", "agent.update", "agent.revoke"];
89
91
  /** One administrative action: who did what to which tenant, when. Written by every mutation and never deleted. */
90
92
  export interface AuditEntry {
91
93
  id: number;
package/dist/log-store.js CHANGED
@@ -48,7 +48,7 @@ function queued(client, fn) {
48
48
  return next;
49
49
  }
50
50
  /** Runs `fn` inside one transaction on one connection, whichever kind of client this is. */
51
- async function transaction(client, fn) {
51
+ export async function transaction(client, fn) {
52
52
  if (!client.connect)
53
53
  return queued(client, () => singleConnectionTransaction(client, fn));
54
54
  {
@@ -174,7 +174,7 @@ export class PostgresLog {
174
174
  export const PLANS = ["free", "team", "enterprise"];
175
175
  export const PLAN_QUOTAS = { free: 10_000, team: 1_000_000, enterprise: null };
176
176
  const sha256hex = (s) => createHash("sha256").update(s).digest("hex");
177
- export const AUDIT_ACTIONS = ["tenant.add", "tenant.disable", "tenant.plan", "token.add", "token.revoke", "policy.add", "policy.remove", "sso.set", "sso.remove", "user.mfa-reset"];
177
+ export const AUDIT_ACTIONS = ["tenant.add", "tenant.disable", "tenant.plan", "token.add", "token.revoke", "policy.add", "policy.remove", "sso.set", "sso.remove", "user.mfa-reset", "agent.register", "agent.update", "agent.revoke"];
178
178
  /** Tenants and their tokens, in Postgres. Tokens are stored hashed; a lookup hashes what the caller presented. */
179
179
  export class PostgresTenancy {
180
180
  client;