@agent-custody/receipts 0.16.6 → 0.16.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +24 -9
  2. package/dist/capture.d.ts +2 -0
  3. package/dist/capture.js +13 -2
  4. package/dist/check.d.ts +1 -1
  5. package/dist/check.js +34 -10
  6. package/dist/cli.js +34 -3
  7. package/dist/config.d.ts +32 -2
  8. package/dist/config.js +68 -4
  9. package/dist/door-app.d.ts +28 -0
  10. package/dist/door-app.js +244 -0
  11. package/dist/door-partner.d.ts +66 -0
  12. package/dist/door-partner.js +94 -0
  13. package/dist/door.d.ts +139 -10
  14. package/dist/door.js +297 -137
  15. package/dist/gateway-http.d.ts +1 -1
  16. package/dist/index.d.ts +4 -2
  17. package/dist/index.js +2 -1
  18. package/dist/perathos.js +3 -2
  19. package/dist/policy.d.ts +11 -0
  20. package/dist/policy.js +41 -1
  21. package/dist/receipt.d.ts +4 -1
  22. package/dist/refunds-init.d.ts +37 -0
  23. package/dist/refunds-init.js +193 -0
  24. package/dist/rest.d.ts +2 -0
  25. package/dist/rest.js +18 -2
  26. package/dist/verify.js +44 -4
  27. package/dist/web-bot-auth.d.ts +105 -0
  28. package/dist/web-bot-auth.js +508 -0
  29. package/docs/door-languages.md +168 -0
  30. package/docs/door-middleware.md +216 -0
  31. package/docs/door-quickstart.md +1 -1
  32. package/docs/door-signals.md +42 -5
  33. package/docs/door.md +124 -15
  34. package/docs/egress.md +2 -0
  35. package/docs/github-action.md +2 -2
  36. package/docs/perathos.md +13 -10
  37. package/docs/policies.md +1 -1
  38. package/docs/sdk.md +11 -0
  39. package/docs/tutorials.md +5 -0
  40. package/docs/usage.md +5 -5
  41. package/docs/verification.md +2 -0
  42. package/package.json +7 -1
  43. package/vectors/audit.json +27 -27
  44. package/vectors/canonical.json +5 -5
  45. package/vectors/receipts.json +1701 -1210
@@ -0,0 +1,508 @@
1
+ // Web Bot Auth at the door: an RFC 9421 HTTP message signature, checked against the Ed25519 key that the signer's own
2
+ // origin publishes in its key directory (draft-meunier-web-bot-auth-architecture-05,
3
+ // draft-meunier-http-message-signatures-directory-05). A signature that checks proves the request was signed by a key
4
+ // published at the `Signature-Agent` origin, for this door's authority, inside a short window. It proves nothing about
5
+ // the body, the path, or the method unless the signature covers them.
6
+ import { createHash, createPublicKey, verify as cryptoVerify } from "node:crypto";
7
+ export const DIRECTORY_PATH = "/.well-known/http-message-signatures-directory";
8
+ export const DIRECTORY_MEDIA_TYPE = "application/http-message-signatures-directory+json";
9
+ export const WEB_BOT_AUTH_TAG = "web-bot-auth";
10
+ /** an unreachable or unusable directory is asked again after this long, however long a good one is kept */
11
+ const DIRECTORY_RETRY_MS = 30_000;
12
+ class SfParser {
13
+ i = 0;
14
+ s;
15
+ constructor(s) {
16
+ this.s = s;
17
+ }
18
+ fail(what) {
19
+ throw new Error(`not a structured field: ${what} at character ${this.i}`);
20
+ }
21
+ peek() {
22
+ return this.s[this.i];
23
+ }
24
+ sp() {
25
+ while (this.s[this.i] === " ")
26
+ this.i++;
27
+ }
28
+ ows() {
29
+ while (this.s[this.i] === " " || this.s[this.i] === "\t")
30
+ this.i++;
31
+ }
32
+ key() {
33
+ const start = this.i;
34
+ if (!/[a-z*]/.test(this.peek() ?? ""))
35
+ this.fail("a key starts with a lowercase letter or *");
36
+ while (/[a-z0-9_\-.*]/.test(this.peek() ?? ""))
37
+ this.i++;
38
+ return this.s.slice(start, this.i);
39
+ }
40
+ bare() {
41
+ const c = this.peek() ?? "";
42
+ if (c === "-" || /[0-9]/.test(c))
43
+ return this.number();
44
+ if (c === '"')
45
+ return this.string();
46
+ if (c === "*" || /[A-Za-z]/.test(c))
47
+ return this.token();
48
+ if (c === ":")
49
+ return this.bytes();
50
+ if (c === "?")
51
+ return this.boolean();
52
+ return this.fail("an item");
53
+ }
54
+ number() {
55
+ const start = this.i;
56
+ if (this.peek() === "-")
57
+ this.i++;
58
+ while (/[0-9.]/.test(this.peek() ?? ""))
59
+ this.i++;
60
+ const text = this.s.slice(start, this.i);
61
+ if (/^-?[0-9]{1,15}$/.test(text))
62
+ return { t: "integer", v: Number(text) };
63
+ if (/^-?[0-9]{1,12}\.[0-9]{1,3}$/.test(text))
64
+ return { t: "decimal", v: Number(text) };
65
+ return this.fail("a number");
66
+ }
67
+ string() {
68
+ this.i++;
69
+ let out = "";
70
+ for (;;) {
71
+ const c = this.s[this.i++];
72
+ if (c === undefined)
73
+ this.fail("an unterminated string");
74
+ if (c === "\\") {
75
+ const n = this.s[this.i++];
76
+ if (n !== '"' && n !== "\\")
77
+ this.fail("an escape other than \\\" or \\\\");
78
+ out += n;
79
+ }
80
+ else if (c === '"')
81
+ return { t: "string", v: out };
82
+ else if (c < " " || c > "~")
83
+ this.fail("a character outside a string's range");
84
+ else
85
+ out += c;
86
+ }
87
+ }
88
+ token() {
89
+ const start = this.i;
90
+ this.i++;
91
+ while (/[!#$%&'*+\-.^_`|~0-9A-Za-z:/]/.test(this.peek() ?? ""))
92
+ this.i++;
93
+ return { t: "token", v: this.s.slice(start, this.i) };
94
+ }
95
+ bytes() {
96
+ this.i++;
97
+ const start = this.i;
98
+ while (/[A-Za-z0-9+/=]/.test(this.peek() ?? ""))
99
+ this.i++;
100
+ if (this.peek() !== ":")
101
+ this.fail("an unterminated byte sequence");
102
+ const v = Buffer.from(this.s.slice(start, this.i), "base64");
103
+ this.i++;
104
+ return { t: "bytes", v };
105
+ }
106
+ boolean() {
107
+ this.i++;
108
+ const c = this.s[this.i++];
109
+ if (c !== "0" && c !== "1")
110
+ this.fail("a boolean");
111
+ return { t: "boolean", v: c === "1" };
112
+ }
113
+ params() {
114
+ const out = [];
115
+ while (this.peek() === ";") {
116
+ this.i++;
117
+ this.sp();
118
+ const k = this.key();
119
+ let v = { t: "boolean", v: true };
120
+ if (this.peek() === "=") {
121
+ this.i++;
122
+ v = this.bare();
123
+ }
124
+ const at = out.findIndex(([name]) => name === k);
125
+ if (at >= 0)
126
+ out[at] = [k, v];
127
+ else
128
+ out.push([k, v]);
129
+ }
130
+ return out;
131
+ }
132
+ item() {
133
+ const item = this.bare();
134
+ return { item, params: this.params() };
135
+ }
136
+ member() {
137
+ if (this.peek() !== "(")
138
+ return this.item();
139
+ this.i++;
140
+ const list = [];
141
+ for (;;) {
142
+ this.sp();
143
+ if (this.peek() === ")") {
144
+ this.i++;
145
+ return { list, params: this.params() };
146
+ }
147
+ list.push(this.item());
148
+ if (this.peek() !== " " && this.peek() !== ")")
149
+ this.fail("an inner list");
150
+ }
151
+ }
152
+ end() {
153
+ this.sp();
154
+ if (this.i !== this.s.length)
155
+ this.fail("trailing characters");
156
+ }
157
+ }
158
+ /** An RFC 8941 dictionary. A later member of the same name replaces an earlier one, as the RFC says. */
159
+ export function parseDictionary(text) {
160
+ const p = new SfParser(text);
161
+ const out = new Map();
162
+ p.sp();
163
+ if (p.i === text.length)
164
+ return out;
165
+ for (;;) {
166
+ const k = p.key();
167
+ let m;
168
+ if (p.peek() === "=") {
169
+ p.i++;
170
+ m = p.member();
171
+ }
172
+ else
173
+ m = { item: { t: "boolean", v: true }, params: p.params() };
174
+ out.delete(k);
175
+ out.set(k, m);
176
+ p.ows();
177
+ if (p.i === text.length)
178
+ return out;
179
+ if (p.peek() !== ",")
180
+ p.fail("a comma between members");
181
+ p.i++;
182
+ p.ows();
183
+ if (p.i === text.length)
184
+ p.fail("a trailing comma");
185
+ }
186
+ }
187
+ /** An RFC 8941 item on its own, such as a legacy `Signature-Agent: "https://..."`. */
188
+ export function parseItem(text) {
189
+ const p = new SfParser(text);
190
+ p.sp();
191
+ const it = p.item();
192
+ p.end();
193
+ return it;
194
+ }
195
+ function serializeBare(b) {
196
+ switch (b.t) {
197
+ case "string": return `"${b.v.replace(/[\\"]/g, (c) => `\\${c}`)}"`;
198
+ case "token": return b.v;
199
+ case "integer": return String(b.v);
200
+ case "decimal": {
201
+ const r = Math.round(b.v * 1000) / 1000;
202
+ return Number.isInteger(r) ? `${r}.0` : String(r);
203
+ }
204
+ case "bytes": return `:${b.v.toString("base64")}:`;
205
+ case "boolean": return b.v ? "?1" : "?0";
206
+ }
207
+ }
208
+ const serializeParams = (ps) => ps.map(([k, v]) => (v.t === "boolean" && v.v ? `;${k}` : `;${k}=${serializeBare(v)}`)).join("");
209
+ const serializeItem = (i) => serializeBare(i.item) + serializeParams(i.params);
210
+ export const serializeMember = (m) => ("list" in m ? `(${m.list.map(serializeItem).join(" ")})${serializeParams(m.params)}` : serializeItem(m));
211
+ const param = (ps, name) => ps.find(([k]) => k === name)?.[1];
212
+ /** A host as RFC 9421 compares it: lowercase, without the default port of https or http. */
213
+ export function normalizeAuthority(host) {
214
+ return host.trim().toLowerCase().replace(/:(443|80)$/, "");
215
+ }
216
+ /**
217
+ * The RFC 9421 signature base (section 2.5) for the covered components and their parameters. Supports `@method`,
218
+ * `@authority`, `@path`, `@query`, and header fields, whole or one dictionary member (`;key`). Any other derived
219
+ * component or component parameter is refused rather than guessed at.
220
+ */
221
+ export function signatureBase(req, input) {
222
+ const lines = [];
223
+ const seen = new Set();
224
+ const q = req.target.indexOf("?");
225
+ const rawPath = q >= 0 ? req.target.slice(0, q) : req.target;
226
+ for (const c of input.list) {
227
+ if (c.item.t !== "string")
228
+ throw new Error("a covered component is not a string");
229
+ const name = c.item.v;
230
+ const id = serializeItem(c);
231
+ if (seen.has(id))
232
+ throw new Error(`the component ${id} is covered twice`);
233
+ seen.add(id);
234
+ let value;
235
+ if (name.startsWith("@")) {
236
+ if (c.params.length)
237
+ throw new Error(`the component ${id} has parameters this door does not support`);
238
+ if (name === "@method")
239
+ value = req.method;
240
+ else if (name === "@authority")
241
+ value = req.authority;
242
+ else if (name === "@path")
243
+ value = rawPath || "/";
244
+ else if (name === "@query")
245
+ value = q >= 0 ? req.target.slice(q) : "?";
246
+ else
247
+ throw new Error(`the component ${name} is not one this door checks (it checks @method, @authority, @path, @query, and header fields)`);
248
+ }
249
+ else {
250
+ if (name !== name.toLowerCase())
251
+ throw new Error(`the component name ${name} is not lowercase`);
252
+ const values = req.header(name);
253
+ if (!values)
254
+ throw new Error(`the request has no ${name} field, which the signature covers`);
255
+ const joined = values.map((v) => v.trim()).join(", ");
256
+ const key = param(c.params, "key");
257
+ if (c.params.some(([k]) => k !== "key"))
258
+ throw new Error(`the component ${id} has parameters this door does not support`);
259
+ if (key) {
260
+ if (key.t !== "string")
261
+ throw new Error(`the key of ${name} is not a string`);
262
+ const member = parseDictionary(joined).get(key.v);
263
+ if (!member)
264
+ throw new Error(`the ${name} field has no member ${key.v}`);
265
+ value = serializeMember(member);
266
+ }
267
+ else
268
+ value = joined;
269
+ }
270
+ lines.push(`${id}: ${value}`);
271
+ }
272
+ lines.push(`"@signature-params": ${serializeMember(input)}`);
273
+ return lines.join("\n");
274
+ }
275
+ /** The RFC 7638 thumbprint of an Ed25519 JWK (RFC 8037 appendix A.3): the base64url SHA-256 of `{"crv","kty","x"}`. */
276
+ export function jwkThumbprint(x) {
277
+ return createHash("sha256").update(`{"crv":"Ed25519","kty":"OKP","x":"${x}"}`).digest("base64url");
278
+ }
279
+ /** A response body up to `max` bytes; null when it passes that, and the rest is not read. */
280
+ export async function readCapped(res, max) {
281
+ if (!res.body)
282
+ return Buffer.alloc(0);
283
+ const reader = res.body.getReader();
284
+ const chunks = [];
285
+ let size = 0;
286
+ for (;;) {
287
+ const { done, value } = await reader.read();
288
+ if (done)
289
+ return Buffer.concat(chunks);
290
+ size += value.length;
291
+ if (size > max) {
292
+ await reader.cancel().catch(() => undefined);
293
+ return null;
294
+ }
295
+ chunks.push(value);
296
+ }
297
+ }
298
+ /** The directory's Ed25519 keys by thumbprint. Keys of other types are skipped: this door checks Ed25519 only. */
299
+ function parseDirectory(body) {
300
+ const doc = JSON.parse(body.toString("utf8"));
301
+ if (!doc || !Array.isArray(doc.keys))
302
+ throw new Error("the directory is not a JWKS: no keys array");
303
+ const keys = new Map();
304
+ for (const k of doc.keys) {
305
+ if (!k || k.kty !== "OKP" || k.crv !== "Ed25519" || typeof k.x !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(k.x))
306
+ continue;
307
+ const key = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: k.x }, format: "jwk" });
308
+ keys.set(jwkThumbprint(k.x), { key, ...(typeof k.nbf === "number" ? { nbf: k.nbf } : {}), ...(typeof k.exp === "number" ? { exp: k.exp } : {}) });
309
+ }
310
+ return keys;
311
+ }
312
+ /** An https origin with nothing after it, as the config holds it; throws on anything else. */
313
+ export function agentOrigin(uri) {
314
+ const u = new URL(uri);
315
+ if (u.protocol !== "https:")
316
+ throw new Error(`the signature agent ${uri} is not https`);
317
+ if (u.username || u.password || u.search || u.hash || (u.pathname !== "/" && u.pathname !== DIRECTORY_PATH))
318
+ throw new Error(`the signature agent ${uri} is not an origin or its directory`);
319
+ return u.origin;
320
+ }
321
+ /**
322
+ * Checks Web Bot Auth signatures. The directory of each configured agent is fetched from
323
+ * `<origin>/.well-known/http-message-signatures-directory` over https, never following a redirect, within `timeoutMs`
324
+ * and `maxDirectoryBytes`, and kept for `cacheSeconds` (a failure for 30 seconds). A nonce is remembered until the
325
+ * signature it came with could no longer be accepted, so a signature serves one request. `now` is for tests.
326
+ */
327
+ export function createWebBotAuthVerifier(opts, f, now = () => Date.now()) {
328
+ const agents = new Set(opts.agents.map(agentOrigin));
329
+ const authorities = new Set(opts.authorities.map(normalizeAuthority));
330
+ const cache = new Map();
331
+ const inflight = new Map();
332
+ const nonces = new Map();
333
+ const fetchDirectory = async (origin) => {
334
+ const url = `${origin}${DIRECTORY_PATH}`;
335
+ try {
336
+ const res = await f(url, { headers: { accept: DIRECTORY_MEDIA_TYPE }, redirect: "manual", signal: AbortSignal.timeout(opts.timeoutMs) });
337
+ if (res.status >= 300 && res.status < 400) {
338
+ await res.body?.cancel().catch(() => undefined);
339
+ return { ok: false, outcome: "invalid", error: `the directory at ${url} redirected${res.headers.get("location") ? ` to ${res.headers.get("location")}` : ""}; a directory is served from the signature agent's own origin` };
340
+ }
341
+ if (!res.ok) {
342
+ await res.body?.cancel().catch(() => undefined);
343
+ return { ok: false, outcome: "unavailable", error: `the directory at ${url} answered ${res.status}` };
344
+ }
345
+ const type = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
346
+ if (type !== DIRECTORY_MEDIA_TYPE) {
347
+ await res.body?.cancel().catch(() => undefined);
348
+ return { ok: false, outcome: "invalid", error: `the directory at ${url} is served as ${type || "no media type"}, not ${DIRECTORY_MEDIA_TYPE}` };
349
+ }
350
+ const body = await readCapped(res, opts.maxDirectoryBytes);
351
+ if (!body)
352
+ return { ok: false, outcome: "invalid", error: `the directory at ${url} is larger than ${opts.maxDirectoryBytes} bytes` };
353
+ try {
354
+ return { ok: true, keys: parseDirectory(body) };
355
+ }
356
+ catch (e) {
357
+ return { ok: false, outcome: "invalid", error: `the directory at ${url} is not usable: ${e instanceof Error ? e.message : String(e)}` };
358
+ }
359
+ }
360
+ catch (e) {
361
+ return { ok: false, outcome: "unavailable", error: `the directory at ${url} could not be fetched: ${e instanceof Error ? e.message : String(e)}` };
362
+ }
363
+ };
364
+ const directory = (origin) => {
365
+ const hit = cache.get(origin);
366
+ if (hit && now() - hit.at < (hit.dir.ok ? opts.cacheSeconds * 1000 : Math.min(DIRECTORY_RETRY_MS, opts.cacheSeconds * 1000)))
367
+ return Promise.resolve(hit.dir);
368
+ const pending = inflight.get(origin);
369
+ if (pending)
370
+ return pending;
371
+ const p = fetchDirectory(origin).then((dir) => {
372
+ cache.set(origin, { at: now(), dir });
373
+ inflight.delete(origin);
374
+ return dir;
375
+ });
376
+ inflight.set(origin, p);
377
+ return p;
378
+ };
379
+ const roomForNonce = () => {
380
+ if (nonces.size < opts.maxNonces)
381
+ return true;
382
+ const t = now();
383
+ for (const [k, until] of nonces)
384
+ if (until <= t)
385
+ nonces.delete(k);
386
+ return nonces.size < opts.maxNonces;
387
+ };
388
+ async function verify(req) {
389
+ const inputText = req.header("signature-input");
390
+ const sigText = req.header("signature");
391
+ if (!inputText && !sigText)
392
+ return { outcome: "absent" };
393
+ const invalid = (error, extra = {}) => ({ outcome: "invalid", error, ...extra });
394
+ if (!inputText || !sigText)
395
+ return invalid(`${inputText ? "Signature-Input" : "Signature"} arrived without ${inputText ? "Signature" : "Signature-Input"}`);
396
+ let inputs;
397
+ let sigs;
398
+ try {
399
+ inputs = parseDictionary(inputText.join(", "));
400
+ sigs = parseDictionary(sigText.join(", "));
401
+ }
402
+ catch (e) {
403
+ return invalid(`the signature headers do not parse: ${e instanceof Error ? e.message : String(e)}`);
404
+ }
405
+ // the first signature tagged web-bot-auth; another tag is a signature for some other purpose
406
+ const entry = [...inputs].find(([, m]) => "list" in m && param(m.params, "tag")?.t === "string" && param(m.params, "tag").v === WEB_BOT_AUTH_TAG);
407
+ if (!entry)
408
+ return invalid(`no signature is tagged ${WEB_BOT_AUTH_TAG}`);
409
+ const [label, member] = entry;
410
+ const input = member;
411
+ const sig = sigs.get(label);
412
+ if (!sig || "list" in sig || sig.item.t !== "bytes")
413
+ return invalid(`the Signature field has no byte sequence for ${label}`);
414
+ const keyidP = param(input.params, "keyid");
415
+ const createdP = param(input.params, "created");
416
+ const expiresP = param(input.params, "expires");
417
+ const algP = param(input.params, "alg");
418
+ const nonceP = param(input.params, "nonce");
419
+ if (keyidP?.t !== "string")
420
+ return invalid(`${label} has no keyid`);
421
+ const keyid = keyidP.v;
422
+ if (createdP?.t !== "integer" || expiresP?.t !== "integer")
423
+ return invalid(`${label} needs both created and expires`, { keyid });
424
+ if (algP && !(algP.t === "string" && algP.v === "ed25519"))
425
+ return invalid(`${label} uses alg ${serializeBare(algP)}; this door checks ed25519 only`, { keyid });
426
+ if (nonceP && nonceP.t !== "string")
427
+ return invalid(`${label} has a nonce that is not a string`, { keyid });
428
+ // the covered components: @authority, and the Signature-Agent member that names the directory
429
+ const covered = input.list;
430
+ if (!covered.some((c) => c.item.t === "string" && c.item.v === "@authority" && c.params.length === 0))
431
+ return invalid(`${label} does not cover @authority`, { keyid });
432
+ const agentComponent = covered.find((c) => c.item.t === "string" && c.item.v === "signature-agent");
433
+ const agentText = req.header("signature-agent");
434
+ if (!agentComponent || !agentText)
435
+ return invalid(agentText ? `${label} does not cover signature-agent` : "no Signature-Agent field names the signer's directory", { keyid });
436
+ let agentUri;
437
+ try {
438
+ const key = param(agentComponent.params, "key");
439
+ const named = key?.t === "string" ? parseDictionary(agentText.join(", ")).get(key.v) : parseItem(agentText.join(", "));
440
+ if (!named || "list" in named || named.item.t !== "string")
441
+ return invalid(`the Signature-Agent ${key?.t === "string" ? `member ${key.v} ` : ""}is not a string`, { keyid });
442
+ agentUri = named.item.v;
443
+ }
444
+ catch (e) {
445
+ return invalid(`the Signature-Agent field does not parse: ${e instanceof Error ? e.message : String(e)}`, { keyid });
446
+ }
447
+ let agent;
448
+ try {
449
+ agent = agentOrigin(agentUri);
450
+ }
451
+ catch (e) {
452
+ return invalid(e instanceof Error ? e.message : String(e), { keyid });
453
+ }
454
+ if (!agents.has(agent))
455
+ return invalid(`${agent} is not a signature agent this door is configured to check`, { agent, keyid });
456
+ // the window: created is not in the future, the signature has not expired, and it is no older than maxAgeSeconds
457
+ const t = now() / 1000;
458
+ const skew = opts.clockSkewSeconds;
459
+ const created = createdP.v;
460
+ const expires = expiresP.v;
461
+ if (created > t + skew)
462
+ return invalid(`${label} was created ${Math.round(created - t)} s in the future`, { agent, keyid });
463
+ if (expires <= created)
464
+ return invalid(`${label} expires before it was created`, { agent, keyid });
465
+ if (t > expires + skew)
466
+ return invalid(`${label} expired at ${new Date(expires * 1000).toISOString()}`, { agent, keyid });
467
+ if (t > created + opts.maxAgeSeconds + skew)
468
+ return invalid(`${label} was created ${Math.round(t - created)} s ago, more than the ${opts.maxAgeSeconds} s this door accepts`, { agent, keyid });
469
+ if (!authorities.has(req.authority))
470
+ return invalid(`@authority ${req.authority || "(none)"} is not an authority this door serves`, { agent, keyid });
471
+ let base;
472
+ try {
473
+ base = signatureBase(req, input);
474
+ }
475
+ catch (e) {
476
+ return invalid(e instanceof Error ? e.message : String(e), { agent, keyid });
477
+ }
478
+ if (opts.requireNonce && !nonceP)
479
+ return invalid(`${label} has no nonce, and this door requires one`, { agent, keyid });
480
+ const nonceKey = nonceP ? `${agent} ${keyid} ${nonceP.v}` : undefined;
481
+ if (nonceKey) {
482
+ const until = nonces.get(nonceKey);
483
+ if (until !== undefined && until > now())
484
+ return invalid(`${label} repeats a nonce already used`, { agent, keyid });
485
+ if (!roomForNonce())
486
+ return { outcome: "unavailable", error: `the door holds ${opts.maxNonces} nonces and cannot record another`, agent, keyid };
487
+ }
488
+ const dir = await directory(agent);
489
+ if (!dir.ok)
490
+ return { outcome: dir.outcome, error: dir.error, agent, keyid };
491
+ const k = dir.keys.get(keyid);
492
+ if (!k)
493
+ return invalid(`keyid ${keyid} is not an Ed25519 key in ${agent}'s directory`, { agent, keyid });
494
+ if ((k.nbf !== undefined && t + skew < k.nbf) || (k.exp !== undefined && t - skew > k.exp))
495
+ return invalid(`keyid ${keyid} is outside the validity its directory gives it`, { agent, keyid });
496
+ if (!cryptoVerify(null, Buffer.from(base, "utf8"), k.key, sig.item.v))
497
+ return invalid(`${label} does not verify with ${agent}'s key ${keyid}`, { agent, keyid });
498
+ if (nonceKey) {
499
+ // checked again: another arrival with this nonce may have verified while the directory was fetched
500
+ const until = nonces.get(nonceKey);
501
+ if (until !== undefined && until > now())
502
+ return invalid(`${label} repeats a nonce already used`, { agent, keyid });
503
+ nonces.set(nonceKey, (Math.min(expires, created + opts.maxAgeSeconds) + skew) * 1000 + 1000);
504
+ }
505
+ return { outcome: "verified", agent, keyid, label };
506
+ }
507
+ return { verify, nonces: () => nonces.size };
508
+ }