@agent-custody/receipts 0.16.12 → 0.16.14

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.
@@ -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 { AGENT_VERSION, compareVersions, DEFAULT_PASSPORT_SECONDS, EndpointSchema, MAX_AGENT_HISTORY, MAX_ENDPOINT_CHARS, 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 { AGENT_VERSION, compareVersions, DEFAULT_PASSPORT_SECONDS, EndpointSchema, MAX_AGENT_HISTORY, MAX_ENDPOINT_CHARS, 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;
@@ -0,0 +1,66 @@
1
+ import { z } from "zod";
2
+ import { type Envelope, type PublicKeyRef } from "./crypto.ts";
3
+ export declare const PASSPORT_TYPE = "application/vnd.agent-custody.passport+json";
4
+ /** the header an agent presents its passport in: the DSSE envelope as base64url JSON */
5
+ export declare const PASSPORT_HEADER = "x-agent-custody-passport";
6
+ /** where a registry publishes its keys and how it issues passports */
7
+ export declare const REGISTRY_DOCUMENT_PATH = "/.well-known/agent-custody-registry.json";
8
+ /** a passport header longer than this is not read */
9
+ export declare const MAX_PASSPORT_HEADER = 8192;
10
+ /** how long a passport lives unless the registry is configured otherwise */
11
+ export declare const DEFAULT_PASSPORT_SECONDS = 86400;
12
+ export declare const MAX_PASSPORT_SECONDS: number;
13
+ export declare const AGENT_ID: RegExp;
14
+ export declare const CAPABILITY: RegExp;
15
+ export declare const DID_KEY: RegExp;
16
+ /** an agent's version: MAJOR.MINOR.PATCH, numbers only, compared as numbers */
17
+ export declare const AGENT_VERSION: RegExp;
18
+ /** Orders two versions that match AGENT_VERSION: negative, zero, or positive. */
19
+ export declare function compareVersions(a: string, b: string): number;
20
+ /** A tool endpoint an agent says it calls: a host name, or an https or wss URL (an MCP server). A claim, never checked by the registry. */
21
+ export declare const EndpointSchema: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
22
+ /**
23
+ * The most characters the declared endpoints of one agent may take, together. With the largest of every other field, a
24
+ * passport stays within MAX_PASSPORT_HEADER, so a door can always read it.
25
+ */
26
+ export declare const MAX_ENDPOINT_CHARS = 1024;
27
+ export declare const text: (max: number) => z.ZodString;
28
+ export declare const PassportSchema: z.ZodObject<{
29
+ version: z.ZodLiteral<"0.1">;
30
+ registry: z.ZodString;
31
+ agentId: z.ZodString;
32
+ agent: z.ZodString;
33
+ name: z.ZodString;
34
+ owner: z.ZodString;
35
+ contact: z.ZodString;
36
+ capabilities: z.ZodArray<z.ZodString>;
37
+ agentVersion: z.ZodOptional<z.ZodString>;
38
+ endpoints: z.ZodOptional<z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>>;
39
+ erc8004: z.ZodOptional<z.ZodObject<{
40
+ agentRegistry: z.ZodString;
41
+ agentId: z.ZodString;
42
+ owner: z.ZodString;
43
+ block: z.ZodNumber;
44
+ }, z.core.$strip>>;
45
+ issuedAt: z.ZodISODateTime;
46
+ expiresAt: z.ZodISODateTime;
47
+ }, z.core.$strip>;
48
+ export type Passport = z.infer<typeof PassportSchema>;
49
+ export type PassportVerifyResult = {
50
+ ok: true;
51
+ passport: Passport;
52
+ keyid: string;
53
+ digest: string;
54
+ } | {
55
+ ok: false;
56
+ error: string;
57
+ };
58
+ /** What a passport names by: sha256 over the payload its signature covers. */
59
+ export declare const passportDigest: (env: Envelope) => string;
60
+ /** Checks a passport: signed by one of the registry keys, well formed, naming a did:key that decodes, and valid at `at`. */
61
+ export declare function verifyPassport(env: Envelope, registryKeys: PublicKeyRef[], at: string): PassportVerifyResult;
62
+ /** A passport signed by one of the registry keys, well formed, naming a did:key that decodes, whatever its window. */
63
+ export declare function passportSignedBy(env: Envelope, registryKeys: PublicKeyRef[]): PassportVerifyResult;
64
+ export declare function passportHeader(env: Envelope): string;
65
+ /** The passport an arrival presented, unverified; null when there is none or it is not an envelope. */
66
+ export declare function parsePassportHeader(headers: Record<string, string | string[] | undefined>): Envelope | null;
@@ -0,0 +1,127 @@
1
+ // The passport an agent registry signs, and its check: what a door needs of the registry, with nothing that keeps or
2
+ // stores agents, so that a door, the Worker's included, imports no database or file code.
3
+ import { z } from "zod";
4
+ import { dsseVerify, sha256Hex } from "./crypto.js";
5
+ import { publicKeyFromDidKey } from "./did-key.js";
6
+ import { ERC8004_REGISTRY } from "./erc8004-link.js";
7
+ export const PASSPORT_TYPE = "application/vnd.agent-custody.passport+json";
8
+ /** the header an agent presents its passport in: the DSSE envelope as base64url JSON */
9
+ export const PASSPORT_HEADER = "x-agent-custody-passport";
10
+ /** where a registry publishes its keys and how it issues passports */
11
+ export const REGISTRY_DOCUMENT_PATH = "/.well-known/agent-custody-registry.json";
12
+ /** a passport header longer than this is not read */
13
+ export const MAX_PASSPORT_HEADER = 8192;
14
+ /** how long a passport lives unless the registry is configured otherwise */
15
+ export const DEFAULT_PASSPORT_SECONDS = 86_400;
16
+ export const MAX_PASSPORT_SECONDS = 7 * 86_400;
17
+ export const AGENT_ID = /^agt_[0-9a-f]{16}$/;
18
+ export const CAPABILITY = /^[a-z0-9][a-z0-9._:-]{0,63}$/;
19
+ export const DID_KEY = /^did:key:z[1-9A-HJ-NP-Za-km-z]{40,60}$/;
20
+ /** an agent's version: MAJOR.MINOR.PATCH, numbers only, compared as numbers */
21
+ export const AGENT_VERSION = /^(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})$/;
22
+ /** Orders two versions that match AGENT_VERSION: negative, zero, or positive. */
23
+ export function compareVersions(a, b) {
24
+ // anything else would compare as NaN, which is neither below nor above, and a range check would let it through
25
+ if (!AGENT_VERSION.test(a) || !AGENT_VERSION.test(b))
26
+ throw new Error(`not a version, MAJOR.MINOR.PATCH: ${!AGENT_VERSION.test(a) ? a : b}`.slice(0, 120));
27
+ const x = a.split(".").map(Number);
28
+ const y = b.split(".").map(Number);
29
+ for (let i = 0; i < 3; i++)
30
+ if (x[i] !== y[i])
31
+ return x[i] - y[i];
32
+ return 0;
33
+ }
34
+ const HOSTNAME = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,62}$/;
35
+ /** A tool endpoint an agent says it calls: a host name, or an https or wss URL (an MCP server). A claim, never checked by the registry. */
36
+ export const EndpointSchema = z.string().max(200)
37
+ .refine((v) => !/[\s\u0000-\u001f\u007f]/.test(v), { message: "an endpoint has no white space or control characters" })
38
+ .refine((v) => {
39
+ if (HOSTNAME.test(v))
40
+ return true;
41
+ try {
42
+ const u = new URL(v);
43
+ return (u.protocol === "https:" || u.protocol === "wss:") && !u.username && !u.password && HOSTNAME.test(u.hostname);
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ }, { message: "an endpoint is a lowercase host name, or an https or wss URL without credentials" })
49
+ // one spelling: a URL is kept as its href, so what the passport carries is what the URL means
50
+ .transform((v) => (HOSTNAME.test(v) ? v : new URL(v).href));
51
+ /**
52
+ * The most characters the declared endpoints of one agent may take, together. With the largest of every other field, a
53
+ * passport stays within MAX_PASSPORT_HEADER, so a door can always read it.
54
+ */
55
+ export const MAX_ENDPOINT_CHARS = 1024;
56
+ export const text = (max) => z.string().trim().min(1).max(max).refine((s) => !/[\u0000-\u001f\u007f]/.test(s), { message: "control characters are not allowed" });
57
+ export const PassportSchema = z.object({
58
+ version: z.literal("0.1"),
59
+ /** the registry that issued it: its public URL */
60
+ registry: z.string().url().max(200),
61
+ agentId: z.string().regex(AGENT_ID),
62
+ /** the agent's key; a door admits the passport only on a request this key signed */
63
+ agent: z.string().regex(DID_KEY),
64
+ name: text(100),
65
+ /** the portal tenant that registered the agent */
66
+ owner: text(64),
67
+ /** how a site reaches the agent's operator */
68
+ contact: text(200),
69
+ capabilities: z.array(z.string().regex(CAPABILITY)).max(32),
70
+ /** the version of the agent its owner registered; absent when none was */
71
+ agentVersion: z.string().regex(AGENT_VERSION).optional(),
72
+ /** the tool endpoints the agent's owner says it calls: a claim, which the registry does not check */
73
+ endpoints: z.array(EndpointSchema).max(32).optional(),
74
+ /** the agent's ERC-8004 identity, as the registry last checked it against the chain; absent when it has none or the check is stale */
75
+ erc8004: z.object({ agentRegistry: z.string().regex(ERC8004_REGISTRY), agentId: z.string().regex(/^[0-9]{1,78}$/), owner: z.string().regex(/^0x[0-9a-f]{40}$/), block: z.number().int().nonnegative() }).optional(),
76
+ issuedAt: z.iso.datetime({ offset: true }),
77
+ expiresAt: z.iso.datetime({ offset: true }),
78
+ });
79
+ /** What a passport names by: sha256 over the payload its signature covers. */
80
+ export const passportDigest = (env) => sha256Hex(Buffer.from(env.payload, "base64"));
81
+ /** Checks a passport: signed by one of the registry keys, well formed, naming a did:key that decodes, and valid at `at`. */
82
+ export function verifyPassport(env, registryKeys, at) {
83
+ const r = passportSignedBy(env, registryKeys);
84
+ if (!r.ok)
85
+ return r;
86
+ const t = Date.parse(at);
87
+ if (t < Date.parse(r.passport.issuedAt) || t > Date.parse(r.passport.expiresAt))
88
+ return { ok: false, error: `the passport is valid from ${r.passport.issuedAt} to ${r.passport.expiresAt}` };
89
+ return r;
90
+ }
91
+ /** A passport signed by one of the registry keys, well formed, naming a did:key that decodes, whatever its window. */
92
+ export function passportSignedBy(env, registryKeys) {
93
+ if (env.payloadType !== PASSPORT_TYPE)
94
+ return { ok: false, error: `the passport's payloadType is ${String(env.payloadType).slice(0, 80)}, not ${PASSPORT_TYPE}` };
95
+ if (registryKeys.length === 0)
96
+ return { ok: false, error: "the door trusts no registry key" };
97
+ const r = dsseVerify(env, registryKeys);
98
+ if (!r.ok)
99
+ return { ok: false, error: `the passport is not signed by a trusted registry key: ${r.error}` };
100
+ const parsed = PassportSchema.safeParse(r.payload);
101
+ if (!parsed.success)
102
+ return { ok: false, error: `the passport is not well formed: ${parsed.error.issues.map((i) => `${i.path.join(".")} ${i.message}`).join("; ")}` };
103
+ const p = parsed.data;
104
+ try {
105
+ publicKeyFromDidKey(p.agent);
106
+ }
107
+ catch (e) {
108
+ return { ok: false, error: `the passport's agent key does not decode: ${e instanceof Error ? e.message : String(e)}` };
109
+ }
110
+ return { ok: true, passport: p, keyid: r.keyid, digest: passportDigest(env) };
111
+ }
112
+ export function passportHeader(env) {
113
+ return Buffer.from(JSON.stringify(env)).toString("base64url");
114
+ }
115
+ /** The passport an arrival presented, unverified; null when there is none or it is not an envelope. */
116
+ export function parsePassportHeader(headers) {
117
+ const raw = headers[PASSPORT_HEADER];
118
+ if (typeof raw !== "string" || !raw || raw.length > MAX_PASSPORT_HEADER)
119
+ return null;
120
+ try {
121
+ const parsed = JSON.parse(Buffer.from(raw, "base64url").toString("utf8"));
122
+ return parsed && typeof parsed === "object" && typeof parsed.payloadType === "string" && typeof parsed.payload === "string" && Array.isArray(parsed.signatures) ? parsed : null;
123
+ }
124
+ catch {
125
+ return null;
126
+ }
127
+ }
package/dist/portal.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type IncomingMessage, type ServerResponse } from "node:http";
2
2
  import { type Plan, type PostgresLike, type PostgresTenancy } from "./log-store.ts";
3
+ import type { Erc8004Resolver } from "./erc8004.ts";
4
+ import type { Signer } from "./signer.ts";
3
5
  import { type OidcConfig, type SamlConfig, type SsoIdentity } from "./sso.ts";
4
6
  export interface StripeOptions {
5
7
  secretKey: string;
@@ -55,6 +57,18 @@ export interface PortalOptions {
55
57
  trustProxy?: boolean;
56
58
  /** table prefix; default portal_ */
57
59
  prefix?: string;
60
+ /**
61
+ * The agent registry: organisations register their agents, and the portal signs their passports with `signer`, a key
62
+ * of its own (not the log's). Needs `portalUrl`, which names the registry in every passport. Off when absent.
63
+ */
64
+ registry?: {
65
+ signer: Signer;
66
+ passportSeconds?: number;
67
+ /** links agents to ERC-8004 identities, checked against the chain; without it a link is refused */
68
+ erc8004?: Erc8004Resolver;
69
+ /** how old a link's last check may be for a passport to carry it; an older one is checked again first. Default 3600 */
70
+ erc8004RecheckSeconds?: number;
71
+ };
58
72
  log?: (message: string) => void;
59
73
  }
60
74
  export interface PortalUser {