@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.
- package/README.md +15 -1
- package/dist/admission.d.ts +75 -0
- package/dist/admission.js +136 -0
- package/dist/check.js +48 -4
- package/dist/cli.js +63 -4
- package/dist/config.d.ts +11 -1
- package/dist/config.js +10 -2
- package/dist/door-core.d.ts +82 -2
- package/dist/door-core.js +113 -12
- package/dist/door-worker.d.ts +14 -0
- package/dist/door-worker.js +33 -1
- package/dist/door.d.ts +1 -1
- package/dist/door.js +18 -1
- package/dist/erc8004-link.d.ts +24 -0
- package/dist/erc8004-link.js +11 -0
- package/dist/erc8004.d.ts +26 -0
- package/dist/erc8004.js +208 -0
- package/dist/index.d.ts +9 -3
- package/dist/index.js +5 -2
- package/dist/log-store.d.ts +3 -1
- package/dist/log-store.js +2 -2
- package/dist/passport.d.ts +66 -0
- package/dist/passport.js +127 -0
- package/dist/portal.d.ts +14 -0
- package/dist/portal.js +109 -0
- package/dist/registry.d.ts +170 -0
- package/dist/registry.js +331 -0
- package/dist/web-bot-auth.d.ts +9 -3
- package/dist/web-bot-auth.js +31 -4
- package/docs/admission-lists.md +91 -0
- package/docs/agent-registry.md +191 -0
- package/docs/door-quickstart.md +2 -2
- package/docs/door-wordpress.md +128 -0
- package/docs/door-worker.md +1 -1
- package/docs/door.md +7 -3
- package/docs/github-action.md +2 -2
- package/docs/tutorials.md +4 -0
- package/docs/usage.md +1 -1
- package/package.json +2 -1
package/dist/door-core.d.ts
CHANGED
|
@@ -46,6 +46,10 @@ export interface Arrival {
|
|
|
46
46
|
signatureError?: string;
|
|
47
47
|
/** the agent name from the `x-agent-custody-agent` header, when sent; a claim */
|
|
48
48
|
declared?: string;
|
|
49
|
+
/** what became of an agent registry passport; absent when none was presented */
|
|
50
|
+
passport?: ArrivalPassport;
|
|
51
|
+
/** the site's admission lists this arrival's agent is on, when the door has lists; absent otherwise, and from `classifyArrival` alone */
|
|
52
|
+
admission?: ArrivalAdmission;
|
|
49
53
|
remote: string;
|
|
50
54
|
method: string;
|
|
51
55
|
path: string;
|
|
@@ -136,6 +140,64 @@ export interface RateTracker {
|
|
|
136
140
|
* the windows nor drops new ones; an injected clock that goes back is held at the last time seen. `now` is for tests.
|
|
137
141
|
*/
|
|
138
142
|
export declare function createRateTracker(now?: () => number, limits?: RateTrackerLimits): RateTracker;
|
|
143
|
+
/**
|
|
144
|
+
* What became of the passport an arrival presented. `verified`: a trusted registry key signed it, it is in its window,
|
|
145
|
+
* and the request is signed by the did:key it names, with a signature that covers the passport, `@method`, `@path`,
|
|
146
|
+
* `@query`, and, on a method that can change something, a `Content-Digest` that matches the body; that alone makes an arrival
|
|
147
|
+
* without a grant `verified`. `unbound`: it verified and the request is signed by its key, but the signature does not
|
|
148
|
+
* cover all of that, so it could be a signature made for another request with a public passport attached.
|
|
149
|
+
* `wrong-sender`: it verified, and the request is not signed by its key. `invalid`: it did not verify, or the header is
|
|
150
|
+
* not a passport. `unchecked`: the door trusts no registry key. Only a `verified` passport puts the registry's entry in
|
|
151
|
+
* the fact: a passport is public, and an entry the signer is not bound to would let anyone carry another agent's
|
|
152
|
+
* capabilities into the policy. The passport itself is recorded too, so a reader with the registry's key can check it again.
|
|
153
|
+
*/
|
|
154
|
+
export interface ArrivalPassport {
|
|
155
|
+
outcome: "verified" | "unbound" | "wrong-sender" | "invalid" | "unchecked";
|
|
156
|
+
error?: string;
|
|
157
|
+
/** the registry that signed it, when it verified */
|
|
158
|
+
registry?: string;
|
|
159
|
+
/** the did:key it names, when it verified */
|
|
160
|
+
agent?: string;
|
|
161
|
+
registryKeyid?: string;
|
|
162
|
+
agentId?: string;
|
|
163
|
+
name?: string;
|
|
164
|
+
owner?: string;
|
|
165
|
+
capabilities?: string[];
|
|
166
|
+
/** the agent's version, as its owner registered it */
|
|
167
|
+
agentVersion?: string;
|
|
168
|
+
/** the tool endpoints its owner says it calls: a claim the registry passed on, not a fact the door checked */
|
|
169
|
+
endpoints?: string[];
|
|
170
|
+
/** the agent's ERC-8004 identity, as the registry checked it against the chain */
|
|
171
|
+
erc8004?: {
|
|
172
|
+
agentRegistry: string;
|
|
173
|
+
agentId: string;
|
|
174
|
+
owner: string;
|
|
175
|
+
block: number;
|
|
176
|
+
};
|
|
177
|
+
expiresAt?: string;
|
|
178
|
+
/** sha256 over the passport's signed payload */
|
|
179
|
+
digest?: string;
|
|
180
|
+
envelope?: Envelope;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* The admission lists an arrival's agent is on, by name, sorted, and the sha256 of the lists file in force. Only a
|
|
184
|
+
* `verified` arrival is on any list: by its subject, or by the registry entry or ERC-8004 identity of its verified
|
|
185
|
+
* passport. The names mean what the policy makes of them.
|
|
186
|
+
*/
|
|
187
|
+
export interface ArrivalAdmission {
|
|
188
|
+
lists: string[];
|
|
189
|
+
digest: string;
|
|
190
|
+
}
|
|
191
|
+
/** Trusted registry keys for the door's IO: the keys, and the URL that each bound key's passports may name, by keyid. */
|
|
192
|
+
export declare function registryKeysOf(keys: {
|
|
193
|
+
ref: PublicKeyRef;
|
|
194
|
+
registry?: string;
|
|
195
|
+
}[]): {
|
|
196
|
+
trustedRegistryKeys: PublicKeyRef[];
|
|
197
|
+
registryUrls: Record<string, string>;
|
|
198
|
+
};
|
|
199
|
+
/** The components a signature must cover for the passport it carries to admit its agent. */
|
|
200
|
+
export declare const PASSPORT_COVERED: readonly ["@method", "@path", "@query", "x-agent-custody-passport"];
|
|
139
201
|
export interface Classified {
|
|
140
202
|
arrival: Arrival;
|
|
141
203
|
/** set when the arrival is verified by a grant: the grant, as presented */
|
|
@@ -234,12 +296,15 @@ export declare function signedRequestOf(req: DoorRequest): SignedRequest;
|
|
|
234
296
|
* Without a grant, a Web Bot Auth signature the door verified (`signature`, from `createWebBotAuthVerifier`) makes the
|
|
235
297
|
* arrival `verified` as its signature agent. With both, the signature binds the grant to its sender when the grant names
|
|
236
298
|
* that signature agent; a grant presented under another agent's signature is `wrong-sender` and the arrival `claimed`.
|
|
237
|
-
* A signature by a did:key's own key binds a grant that names that did:key in the same way
|
|
299
|
+
* 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
|
|
300
|
+
* passport from a trusted registry (`registry`) that names that did:key, and the arrival is `verified` as the did:key;
|
|
301
|
+
* a request that presents a grant is judged by its grant, and its passport is only recorded. Otherwise a did:key
|
|
302
|
+
* signature counts for nothing.
|
|
238
303
|
* An `x-agent-custody-agent` header or a signature that did not verify alone is `claimed`. Nothing at all is `unknown`.
|
|
239
304
|
* Without `signature`, a `Signature-Input` header is recorded as `unchecked`. `revoked`, when given, says why a grant
|
|
240
305
|
* that verified is revoked (from its chain's digests, leaf first), or null when it is not; a revoked grant is `claimed`.
|
|
241
306
|
*/
|
|
242
|
-
export declare function classifyArrival(req: DoorRequest, trusted: PublicKeyRef[], route: string, trustProxy: boolean, at: string, signature?: SignatureCheck, revoked?: (chainDigests: string[]) => string | null): Classified;
|
|
307
|
+
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, registryUrls?: Record<string, string>): Classified;
|
|
243
308
|
/** The body as the door read it: whole, or how many bytes had arrived when it passed the limit. */
|
|
244
309
|
export type BodyRead = {
|
|
245
310
|
body: Buffer;
|
|
@@ -327,6 +392,10 @@ export interface DoorIO {
|
|
|
327
392
|
key: KeyPair;
|
|
328
393
|
/** principal keys whose grants are a passport */
|
|
329
394
|
trustedPrincipalKeys: PublicKeyRef[];
|
|
395
|
+
/** agent registry keys whose passports admit the did:key they name */
|
|
396
|
+
trustedRegistryKeys?: PublicKeyRef[];
|
|
397
|
+
/** the one registry URL a registry key's passports may name, by the key's keyid; a key absent here may name any */
|
|
398
|
+
registryUrls?: Record<string, string>;
|
|
330
399
|
/** the policy text, and a value that changes whenever the text may have; read on every arrival. Throws when it cannot be read: the policy in force stays */
|
|
331
400
|
readPolicy(): {
|
|
332
401
|
text: string;
|
|
@@ -334,6 +403,17 @@ export interface DoorIO {
|
|
|
334
403
|
};
|
|
335
404
|
/** names the policy in messages: its file, or the variable it came from */
|
|
336
405
|
policySource: string;
|
|
406
|
+
/**
|
|
407
|
+
* a value that changes whenever the admission lists file may have, and its text, which may be left out when the key
|
|
408
|
+
* is `known`, the key of the lists in force; asked on every arrival. Absent when the door has no lists. Throws when it
|
|
409
|
+
* cannot be read: the lists in force stay
|
|
410
|
+
*/
|
|
411
|
+
readAdmission?(known?: string): {
|
|
412
|
+
text?: string;
|
|
413
|
+
key: string;
|
|
414
|
+
};
|
|
415
|
+
/** names the admission lists in messages */
|
|
416
|
+
admissionSource?: string;
|
|
337
417
|
/** why a grant with these chain digests (leaf first) is revoked, or null when it is not. A list that cannot be read must revoke: return the reason */
|
|
338
418
|
revoked(chainDigests: string[]): string | null;
|
|
339
419
|
/** 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,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 { canonicalRegistry, 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,51 @@ export function createRateTracker(now = () => performance.now(), limits = {}) {
|
|
|
129
131
|
clearInterval(timer); },
|
|
130
132
|
};
|
|
131
133
|
}
|
|
134
|
+
/** Trusted registry keys for the door's IO: the keys, and the URL that each bound key's passports may name, by keyid. */
|
|
135
|
+
export function registryKeysOf(keys) {
|
|
136
|
+
// one key listed twice must say one thing: two registries, or bound and also bare, cannot both hold
|
|
137
|
+
const seen = new Map();
|
|
138
|
+
for (const k of keys) {
|
|
139
|
+
if (seen.has(k.ref.keyid) && seen.get(k.ref.keyid) !== k.registry)
|
|
140
|
+
throw new Error(`the registry key ${k.ref.keyid} is listed twice, for ${seen.get(k.ref.keyid) ?? "any registry"} and for ${k.registry ?? "any registry"}; list it once, bound to its one registry`);
|
|
141
|
+
seen.set(k.ref.keyid, k.registry);
|
|
142
|
+
}
|
|
143
|
+
return { trustedRegistryKeys: keys.map((k) => k.ref), registryUrls: Object.fromEntries(keys.filter((k) => k.registry !== undefined).map((k) => [k.ref.keyid, k.registry])) };
|
|
144
|
+
}
|
|
145
|
+
/** The components a signature must cover for the passport it carries to admit its agent. */
|
|
146
|
+
export const PASSPORT_COVERED = ["@method", "@path", "@query", PASSPORT_HEADER];
|
|
147
|
+
/**
|
|
148
|
+
* The passport check for an arrival. `signer` is the did:key whose signature on this request the door verified, with
|
|
149
|
+
* the components it covered; `contentDigest` is true when a `Content-Digest` field matched the body the door read.
|
|
150
|
+
*/
|
|
151
|
+
function checkPassport(req, method, registry, at, signer, contentDigest, registryUrls = {}) {
|
|
152
|
+
const raw = req.headers[PASSPORT_HEADER];
|
|
153
|
+
if (raw === undefined)
|
|
154
|
+
return undefined;
|
|
155
|
+
const env = parsePassportHeader(req.headers);
|
|
156
|
+
if (!env)
|
|
157
|
+
return { outcome: "invalid", error: `the ${PASSPORT_HEADER} header is not a base64url DSSE envelope of at most ${MAX_PASSPORT_HEADER} characters` };
|
|
158
|
+
if (!registry?.length)
|
|
159
|
+
return { outcome: "unchecked" };
|
|
160
|
+
const v = verifyPassport(env, registry, at);
|
|
161
|
+
if (!v.ok)
|
|
162
|
+
return { outcome: "invalid", error: v.error };
|
|
163
|
+
const p = v.passport;
|
|
164
|
+
// a registry writes its own URL into the passports it signs; a key bound to one URL must not vouch for another registry's agents
|
|
165
|
+
const bound = registryUrls[v.keyid];
|
|
166
|
+
if (bound !== undefined && canonicalRegistry(p.registry) !== canonicalRegistry(bound))
|
|
167
|
+
return { outcome: "invalid", error: `the passport names the registry ${p.registry}, and the key ${v.keyid} that signed it is trusted for ${bound} only` };
|
|
168
|
+
const named = { registry: p.registry, agent: p.agent };
|
|
169
|
+
if (signer?.agent !== p.agent)
|
|
170
|
+
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 };
|
|
171
|
+
const writes = !SAFE_METHODS.has(method);
|
|
172
|
+
const missing = [...PASSPORT_COVERED, ...(writes ? ["content-digest"] : [])].filter((c) => !signer.covered?.includes(c));
|
|
173
|
+
if (missing.length)
|
|
174
|
+
return { outcome: "unbound", error: `the signature does not cover ${missing.join(", ")}, which bind the passport to this request`, ...named };
|
|
175
|
+
if (writes && !contentDigest)
|
|
176
|
+
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" };
|
|
177
|
+
return { outcome: "verified", ...named, registryKeyid: v.keyid, agentId: p.agentId, name: p.name, owner: p.owner, capabilities: p.capabilities, ...(p.agentVersion ? { agentVersion: p.agentVersion } : {}), ...(p.endpoints ? { endpoints: p.endpoints } : {}), ...(p.erc8004 ? { erc8004: p.erc8004 } : {}), expiresAt: p.expiresAt, digest: v.digest, envelope: env };
|
|
178
|
+
}
|
|
132
179
|
const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "proxy-connection"]);
|
|
133
180
|
/** request headers the receipt records in clear; everything else is relayed and not recorded */
|
|
134
181
|
const RECORDED_HEADERS = ["user-agent", "content-type", "accept", "host"];
|
|
@@ -276,12 +323,15 @@ export function signedRequestOf(req) {
|
|
|
276
323
|
* Without a grant, a Web Bot Auth signature the door verified (`signature`, from `createWebBotAuthVerifier`) makes the
|
|
277
324
|
* arrival `verified` as its signature agent. With both, the signature binds the grant to its sender when the grant names
|
|
278
325
|
* 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
|
|
326
|
+
* 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
|
|
327
|
+
* passport from a trusted registry (`registry`) that names that did:key, and the arrival is `verified` as the did:key;
|
|
328
|
+
* a request that presents a grant is judged by its grant, and its passport is only recorded. Otherwise a did:key
|
|
329
|
+
* signature counts for nothing.
|
|
280
330
|
* An `x-agent-custody-agent` header or a signature that did not verify alone is `claimed`. Nothing at all is `unknown`.
|
|
281
331
|
* Without `signature`, a `Signature-Input` header is recorded as `unchecked`. `revoked`, when given, says why a grant
|
|
282
332
|
* that verified is revoked (from its chain's digests, leaf first), or null when it is not; a revoked grant is `claimed`.
|
|
283
333
|
*/
|
|
284
|
-
export function classifyArrival(req, trusted, route, trustProxy, at, signature, revoked) {
|
|
334
|
+
export function classifyArrival(req, trusted, route, trustProxy, at, signature, revoked, registry, contentDigest, registryUrls) {
|
|
285
335
|
const url = requestUrl(req);
|
|
286
336
|
const method = (req.method ?? "GET").toUpperCase();
|
|
287
337
|
const declaredRaw = req.headers[AGENT_HEADER];
|
|
@@ -292,6 +342,8 @@ export function classifyArrival(req, trusted, route, trustProxy, at, signature,
|
|
|
292
342
|
// only on the last line, with a verified grant for that did:key. Everywhere else it is invalid, so that no policy
|
|
293
343
|
// takes it for a checked identity.
|
|
294
344
|
const didSigner = signer?.agent.startsWith(DID_KEY_PREFIX) ? signer : undefined;
|
|
345
|
+
const passport = checkPassport(req, method, registry, at, didSigner ? { agent: didSigner.agent, ...(sig.outcome === "verified" && sig.covered ? { covered: sig.covered } : {}) } : undefined, contentDigest, registryUrls);
|
|
346
|
+
const admitted = passport?.outcome === "verified";
|
|
295
347
|
const norm = normalizePath(url.pathname);
|
|
296
348
|
const baseOf = (s) => ({
|
|
297
349
|
signature: s.outcome,
|
|
@@ -299,18 +351,19 @@ export function classifyArrival(req, trusted, route, trustProxy, at, signature,
|
|
|
299
351
|
...("keyid" in s && s.keyid ? { signatureKeyid: s.keyid } : {}),
|
|
300
352
|
...("error" in s ? { signatureError: s.error } : {}),
|
|
301
353
|
...(declared ? { declared } : {}),
|
|
354
|
+
...(passport ? { passport } : {}),
|
|
302
355
|
remote: remoteOf(req, trustProxy),
|
|
303
356
|
method,
|
|
304
357
|
path: "path" in norm ? norm.path : url.pathname,
|
|
305
358
|
route,
|
|
306
359
|
});
|
|
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
360
|
const envelope = parseGrantHeader(req);
|
|
361
|
+
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
362
|
if (!envelope) {
|
|
310
|
-
if (signer && !didSigner)
|
|
363
|
+
if (signer && (!didSigner || admitted))
|
|
311
364
|
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 } };
|
|
365
|
+
const claimed = !!declared || sig.outcome !== "absent" || !!passport;
|
|
366
|
+
return { arrival: { class: claimed ? "claimed" : "unknown", subject: declared ?? passport?.agent ?? "unknown", grant: "absent", ...base } };
|
|
314
367
|
}
|
|
315
368
|
const checked = verifyDelegation(envelope, trusted);
|
|
316
369
|
const asserted = decodeDelegation(envelope)?.agent;
|
|
@@ -378,6 +431,9 @@ const json = jsonAnswer;
|
|
|
378
431
|
/** 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
432
|
export function createDoorCoreWith(cfg, io, framework, opts = {}) {
|
|
380
433
|
const trusted = io.trustedPrincipalKeys;
|
|
434
|
+
const registry = io.trustedRegistryKeys ?? [];
|
|
435
|
+
if (registry.length && !cfg.webBotAuth)
|
|
436
|
+
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
437
|
const revoked = io.revoked;
|
|
382
438
|
const captureSecret = cfg.captureKeyEnv ? io.secret(cfg.captureKeyEnv) : undefined;
|
|
383
439
|
if (cfg.captureKeyEnv && captureSecret === undefined)
|
|
@@ -415,6 +471,37 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
|
|
|
415
471
|
if (!hasPermitRule(first.text))
|
|
416
472
|
console.error(`agent-custody door: ${io.policySource} has no permit rule, so every arrival is refused`);
|
|
417
473
|
let policyNow = { text: first.text, digest: policyDigest(first.text), key: first.key };
|
|
474
|
+
// The admission lists, re-read like the policy: a file that cannot be read or is not valid leaves the lists in force,
|
|
475
|
+
// because emptying them would drop every agent from a block list as well as from an allow list.
|
|
476
|
+
let admissionNow;
|
|
477
|
+
if (io.readAdmission) {
|
|
478
|
+
const a = io.readAdmission();
|
|
479
|
+
if (a.text === undefined)
|
|
480
|
+
throw new Error(`${io.admissionSource}: the admission lists were not read`);
|
|
481
|
+
admissionNow = { lists: compileAdmissionLists(a.text), key: a.key };
|
|
482
|
+
}
|
|
483
|
+
const currentAdmission = () => {
|
|
484
|
+
if (!io.readAdmission || !admissionNow)
|
|
485
|
+
return undefined;
|
|
486
|
+
try {
|
|
487
|
+
const next = io.readAdmission(admissionNow.key);
|
|
488
|
+
if (next.key !== admissionNow.key) {
|
|
489
|
+
try {
|
|
490
|
+
if (next.text === undefined)
|
|
491
|
+
throw new Error("the file changed and its text was not read");
|
|
492
|
+
admissionNow = { lists: compileAdmissionLists(next.text), key: next.key };
|
|
493
|
+
}
|
|
494
|
+
catch (e) {
|
|
495
|
+
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`);
|
|
496
|
+
admissionNow = { ...admissionNow, key: next.key };
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
catch (e) {
|
|
501
|
+
console.error(`agent-custody door: cannot read ${io.admissionSource}: ${e instanceof Error ? e.message : String(e)}; lists ${admissionNow.lists.digest} stay in force`);
|
|
502
|
+
}
|
|
503
|
+
return admissionNow.lists;
|
|
504
|
+
};
|
|
418
505
|
const currentPolicy = () => {
|
|
419
506
|
try {
|
|
420
507
|
const next = readPolicy();
|
|
@@ -444,8 +531,24 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
|
|
|
444
531
|
const route = "path" in norm ? matchRoute(cfg.routes, cfg.unmatchedRoute, method, path) : cfg.unmatchedRoute;
|
|
445
532
|
const presented = webBotAuth && req.headers["signature-input"] !== undefined ? parseGrantHeader(req) : null;
|
|
446
533
|
const trustedGrant = presented ? verifyDelegation(presented, trusted) : undefined;
|
|
447
|
-
|
|
448
|
-
|
|
534
|
+
// a did:key signature keeps its nonce only for an agent that a trusted grant or a trusted passport names; both are
|
|
535
|
+
// given, so that a grant header, trusted or not, cannot stop the nonce of a signature that a passport is checked against
|
|
536
|
+
const passportEnv = webBotAuth && registry.length && req.headers["signature-input"] !== undefined ? parsePassportHeader(req.headers) : null;
|
|
537
|
+
// a passport not yet valid at this door (its registry's clock is ahead) still keeps the nonce, or the same request
|
|
538
|
+
// could be sent again, and admitted, once the passport's window opens
|
|
539
|
+
const signedPassport = passportEnv ? passportSignedBy(passportEnv, registry) : undefined;
|
|
540
|
+
const passportAgent = signedPassport?.ok && Date.parse(timestamp) <= Date.parse(signedPassport.passport.expiresAt) ? signedPassport.passport.agent : undefined;
|
|
541
|
+
const keyAgents = [...(trustedGrant?.ok ? [trustedGrant.delegation.agent] : []), ...(passportAgent ? [passportAgent] : [])];
|
|
542
|
+
const signature = webBotAuth ? await webBotAuth.verify(signedRequestOf(req), keyAgents) : undefined;
|
|
543
|
+
// the body is read before the arrival is classified: a passport on a write binds to it through Content-Digest
|
|
544
|
+
const read = readArrivalBody ? await readArrivalBody(cfg.maxBodyBytes) : null;
|
|
545
|
+
const body = read === null ? Buffer.alloc(0) : "body" in read ? read.body : null;
|
|
546
|
+
const digestField = req.headers["content-digest"];
|
|
547
|
+
const contentDigest = read !== null && body !== null && typeof digestField === "string" && contentDigestMatches(digestField, body);
|
|
548
|
+
const { arrival, delegation, signer } = classifyArrival(req, trusted, route, !!cfg.trustProxy, timestamp, signature, revoked, registry, contentDigest, io.registryUrls);
|
|
549
|
+
const admission = currentAdmission();
|
|
550
|
+
if (admission)
|
|
551
|
+
arrival.admission = { lists: admission.match(arrival), digest: admission.digest };
|
|
449
552
|
const checkedAgent = arrival.class === "verified";
|
|
450
553
|
const by = checkedAgent ? "agent" : "remote";
|
|
451
554
|
const source = `${by}:${checkedAgent ? arrival.subject : arrival.remote}`;
|
|
@@ -479,8 +582,6 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
|
|
|
479
582
|
}
|
|
480
583
|
}
|
|
481
584
|
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
585
|
const headers = {};
|
|
485
586
|
for (const name of RECORDED_HEADERS) {
|
|
486
587
|
const v = req.headers[name];
|
|
@@ -604,7 +705,7 @@ export function createDoorCoreWith(cfg, io, framework, opts = {}) {
|
|
|
604
705
|
release: () => void (inFlight -= 1),
|
|
605
706
|
busy: () => json(503, { "retry-after": "1" }, { error: `the door is handling ${cfg.maxInFlight} requests; this one was not read, decided, or relayed. Retry` }),
|
|
606
707
|
decide,
|
|
607
|
-
consumed: (name, req, arrival) => name === GRANT_HEADER || name === AGENT_HEADER || name === challengeHeader || (!!history && name === FORM_REPORT_HEADER) ||
|
|
708
|
+
consumed: (name, req, arrival) => name === GRANT_HEADER || name === AGENT_HEADER || name === PASSPORT_HEADER || name === challengeHeader || (!!history && name === FORM_REPORT_HEADER) ||
|
|
608
709
|
// the grant travelled in Authorization: it is the door's credential, not the origin's
|
|
609
710
|
(name === "authorization" && arrival.grant !== "absent" && !req.headers[GRANT_HEADER]),
|
|
610
711
|
async record(d, execution) {
|
package/dist/door-worker.d.ts
CHANGED
|
@@ -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`) */
|
|
@@ -88,6 +92,16 @@ interface CfProperties {
|
|
|
88
92
|
export declare const CLOUDFLARE_FACT = "cloudflare";
|
|
89
93
|
/** Every SPKI PEM block in a variable. */
|
|
90
94
|
export declare function pemKeys(text: string | undefined): PublicKeyRef[];
|
|
95
|
+
/**
|
|
96
|
+
* The trusted registry keys: PEM public keys, each trusted for any registry URL, or a JSON list of
|
|
97
|
+
* `{ publicKeyPem, registry }`, the shape of the `keys` in a registry's key document, that binds each key to the one
|
|
98
|
+
* registry URL its passports may name. A JSON object, such as a whole key document, is refused: its PEM would
|
|
99
|
+
* otherwise be read as a bare key and bound to nothing.
|
|
100
|
+
*/
|
|
101
|
+
export declare function registryKeys(text: string | undefined): {
|
|
102
|
+
trustedRegistryKeys: PublicKeyRef[];
|
|
103
|
+
registryUrls: Record<string, string>;
|
|
104
|
+
};
|
|
91
105
|
/**
|
|
92
106
|
* The door config from the Worker's bindings, checked by the same schema as a Node door's. The fields that name files
|
|
93
107
|
* are refused in DOOR_CONFIG, and the placeholders put in their place say where the Worker gets each one; nothing reads them.
|
package/dist/door-worker.js
CHANGED
|
@@ -3,9 +3,10 @@
|
|
|
3
3
|
// variables; receipts go to an R2 bucket and to the log over HTTP; Web Bot Auth nonces go to a Durable Object. Built for workerd by scripts/build-door-worker.ts,
|
|
4
4
|
// deployed from deploy/door/cloudflare-worker/.
|
|
5
5
|
import { createPrivateKey, createPublicKey } from "node:crypto";
|
|
6
|
+
import { z } from "zod";
|
|
6
7
|
import { DoorConfigSchema } from "./config.js";
|
|
7
8
|
import { keyidOf, publicKeyFromPem } from "./crypto.js";
|
|
8
|
-
import { createDoorCoreWith, DOOR_VERSION, jsonAnswer, readStream, RECEIPT_HEADER, relayedAnswer, relayToOrigin } from "./door-core.js";
|
|
9
|
+
import { createDoorCoreWith, registryKeysOf, DOOR_VERSION, jsonAnswer, readStream, RECEIPT_HEADER, relayedAnswer, relayToOrigin } from "./door-core.js";
|
|
9
10
|
import { FORM_SCRIPT_PATH, formScript } from "./door-form.js";
|
|
10
11
|
import { httpLog } from "./log-http.js";
|
|
11
12
|
import { createObjectIssuer } from "./object-issuer.js";
|
|
@@ -19,6 +20,8 @@ const NOT_IN_A_WORKER = {
|
|
|
19
20
|
logFile: "the log is LOG_URL",
|
|
20
21
|
log: "the log is LOG_URL, LOG_KEYS, LOG_ID, LOG_TOKEN",
|
|
21
22
|
trustedPrincipalKeys: "trusted principal keys are the TRUSTED_PRINCIPAL_KEYS variable",
|
|
23
|
+
trustedRegistryKeys: "trusted registry keys are the TRUSTED_REGISTRY_KEYS variable",
|
|
24
|
+
admissionLists: "admission lists are the ADMISSION_LISTS variable",
|
|
22
25
|
revokedGrants: "revoked grants are the REVOKED_GRANTS variable",
|
|
23
26
|
authz: "a Worker relays; nginx and Envoy ask a Node door",
|
|
24
27
|
trustProxy: "the Worker reads the client's address from Cloudflare (CF-Connecting-IP)",
|
|
@@ -30,6 +33,33 @@ const NOT_IN_A_WORKER = {
|
|
|
30
33
|
export function pemKeys(text) {
|
|
31
34
|
return [...(text ?? "").matchAll(/-----BEGIN PUBLIC KEY-----[\s\S]+?-----END PUBLIC KEY-----/g)].map((m) => publicKeyFromPem(m[0]));
|
|
32
35
|
}
|
|
36
|
+
// `registry` is required: with the key document's other fields allowed through, a misspelt or missing one would
|
|
37
|
+
// otherwise leave the key trusted for any registry, and a Worker has no check to warn of it
|
|
38
|
+
const BoundRegistryKeysSchema = z.array(z.object({ publicKeyPem: z.string().min(1), registry: z.string().url().refine((u) => /^https?:\/\//.test(u), { message: "registry is an http(s) URL" }) }).passthrough()).min(1);
|
|
39
|
+
/**
|
|
40
|
+
* The trusted registry keys: PEM public keys, each trusted for any registry URL, or a JSON list of
|
|
41
|
+
* `{ publicKeyPem, registry }`, the shape of the `keys` in a registry's key document, that binds each key to the one
|
|
42
|
+
* registry URL its passports may name. A JSON object, such as a whole key document, is refused: its PEM would
|
|
43
|
+
* otherwise be read as a bare key and bound to nothing.
|
|
44
|
+
*/
|
|
45
|
+
export function registryKeys(text) {
|
|
46
|
+
const t = (text ?? "").trim();
|
|
47
|
+
if (t.startsWith("{"))
|
|
48
|
+
throw new Error("TRUSTED_REGISTRY_KEYS is a JSON object; give PEM keys, or a JSON list of { publicKeyPem, registry } (the key document's keys, each with the registry's URL)");
|
|
49
|
+
if (!t.startsWith("["))
|
|
50
|
+
return registryKeysOf(pemKeys(t).map((ref) => ({ ref })));
|
|
51
|
+
let raw;
|
|
52
|
+
try {
|
|
53
|
+
raw = JSON.parse(t);
|
|
54
|
+
}
|
|
55
|
+
catch (e) {
|
|
56
|
+
throw new Error(`TRUSTED_REGISTRY_KEYS starts with [ and is not JSON: ${e instanceof Error ? e.message : String(e)}`);
|
|
57
|
+
}
|
|
58
|
+
const parsed = BoundRegistryKeysSchema.safeParse(raw);
|
|
59
|
+
if (!parsed.success)
|
|
60
|
+
throw new Error(`TRUSTED_REGISTRY_KEYS is not a list of { publicKeyPem, registry }: ${parsed.error.issues.slice(0, 3).map((i) => `${i.path.join(".")} ${i.message}`).join("; ")}`);
|
|
61
|
+
return registryKeysOf(parsed.data.map((e) => ({ ref: publicKeyFromPem(e.publicKeyPem), registry: e.registry })));
|
|
62
|
+
}
|
|
33
63
|
/**
|
|
34
64
|
* The door config from the Worker's bindings, checked by the same schema as a Node door's. The fields that name files
|
|
35
65
|
* are refused in DOOR_CONFIG, and the placeholders put in their place say where the Worker gets each one; nothing reads them.
|
|
@@ -149,8 +179,10 @@ export function workerDoorIO(env, f) {
|
|
|
149
179
|
return {
|
|
150
180
|
key,
|
|
151
181
|
trustedPrincipalKeys: pemKeys(env.TRUSTED_PRINCIPAL_KEYS),
|
|
182
|
+
...registryKeys(env.TRUSTED_REGISTRY_KEYS),
|
|
152
183
|
readPolicy: () => ({ text: env.DOOR_POLICY, key: "DOOR_POLICY" }),
|
|
153
184
|
policySource: "the DOOR_POLICY variable",
|
|
185
|
+
...(env.ADMISSION_LISTS ? { readAdmission: () => ({ text: env.ADMISSION_LISTS, key: "ADMISSION_LISTS" }), admissionSource: "the ADMISSION_LISTS variable" } : {}),
|
|
154
186
|
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
187
|
secret: (name) => (typeof env[name] === "string" ? env[name] : undefined),
|
|
156
188
|
issuer: (capture) => createObjectIssuer(key, store, sink, { capture }),
|
package/dist/door.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type IncomingMessage, type ServerResponse } from "node:http";
|
|
2
|
-
import type
|
|
2
|
+
import { type DoorConfig } from "./config.ts";
|
|
3
3
|
import { type FlushResult } from "./issue.ts";
|
|
4
4
|
import { type LogSink } from "./log-sink.ts";
|
|
5
5
|
import { type ReceiptExporter } from "./otel.ts";
|
package/dist/door.js
CHANGED
|
@@ -9,13 +9,14 @@
|
|
|
9
9
|
import { randomUUID } from "node:crypto";
|
|
10
10
|
import { closeSync, fstatSync, openSync, readFileSync } from "node:fs";
|
|
11
11
|
import { createServer } from "node:http";
|
|
12
|
+
import { registryKeyEntry } from "./config.js";
|
|
12
13
|
import { loadPrivateKey, loadPublicKey } from "./crypto.js";
|
|
13
14
|
import { createIssuer } from "./issue.js";
|
|
14
15
|
import { openLog } from "./log-sink.js";
|
|
15
16
|
import { FORM_SCRIPT_PATH, formScript } from "./door-form.js";
|
|
16
17
|
import { createRevocationList } from "./revocation.js";
|
|
17
18
|
import { openExporter } from "./otel.js";
|
|
18
|
-
import { AUTHZ_ALLOWED_REASON, DOOR_VERSION, RECEIPT_HEADER, authzTarget, createDoorCoreWith, jsonAnswer as json, relayedAnswer, relayToOrigin } from "./door-core.js";
|
|
19
|
+
import { AUTHZ_ALLOWED_REASON, DOOR_VERSION, RECEIPT_HEADER, authzTarget, createDoorCoreWith, registryKeysOf, jsonAnswer as json, relayedAnswer, relayToOrigin } from "./door-core.js";
|
|
19
20
|
export * from "./door-core.js";
|
|
20
21
|
/** The body, or how many bytes had arrived when it passed the limit; the rest is drained and dropped. */
|
|
21
22
|
export function readBody(req, max) {
|
|
@@ -48,6 +49,7 @@ export function nodeDoorIO(cfg, options = {}) {
|
|
|
48
49
|
return {
|
|
49
50
|
key,
|
|
50
51
|
trustedPrincipalKeys: cfg.trustedPrincipalKeys.map(loadPublicKey),
|
|
52
|
+
...registryKeysOf(cfg.trustedRegistryKeys.map(registryKeyEntry).map((e) => ({ ref: loadPublicKey(e.key), ...(e.registry ? { registry: e.registry } : {}) }))),
|
|
51
53
|
// the bytes and the metadata come from one open file
|
|
52
54
|
readPolicy() {
|
|
53
55
|
const fd = openSync(cfg.policyFile, "r");
|
|
@@ -60,6 +62,21 @@ export function nodeDoorIO(cfg, options = {}) {
|
|
|
60
62
|
}
|
|
61
63
|
},
|
|
62
64
|
policySource: cfg.policyFile,
|
|
65
|
+
...(cfg.admissionLists ? {
|
|
66
|
+
readAdmission(known) {
|
|
67
|
+
const fd = openSync(cfg.admissionLists, "r");
|
|
68
|
+
try {
|
|
69
|
+
const st = fstatSync(fd);
|
|
70
|
+
const key = `${st.ino}:${st.mtimeMs}:${st.ctimeMs}:${st.size}`;
|
|
71
|
+
// a file of 64 full lists is tens of megabytes: it is read only when it has changed
|
|
72
|
+
return key === known ? { key } : { text: readFileSync(fd, "utf8"), key };
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
closeSync(fd);
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
admissionSource: cfg.admissionLists,
|
|
79
|
+
} : {}),
|
|
63
80
|
revoked(chainDigests) {
|
|
64
81
|
try {
|
|
65
82
|
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;
|