@agent-custody/receipts 0.16.5 → 0.16.7

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 (65) hide show
  1. package/README.md +29 -13
  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 +54 -9
  7. package/dist/config.d.ts +27 -2
  8. package/dist/config.js +66 -2
  9. package/dist/console-page.js +144 -50
  10. package/dist/deny-report.d.ts +7 -0
  11. package/dist/deny-report.js +8 -3
  12. package/dist/design.d.ts +11 -0
  13. package/dist/design.js +91 -0
  14. package/dist/door-app.d.ts +28 -0
  15. package/dist/door-app.js +244 -0
  16. package/dist/door-partner.d.ts +66 -0
  17. package/dist/door-partner.js +94 -0
  18. package/dist/door.d.ts +139 -10
  19. package/dist/door.js +297 -137
  20. package/dist/gateway-http.d.ts +1 -1
  21. package/dist/index.d.ts +8 -2
  22. package/dist/index.js +5 -1
  23. package/dist/log-admin.js +100 -59
  24. package/dist/log-store.d.ts +8 -2
  25. package/dist/log-store.js +22 -12
  26. package/dist/perathos.d.ts +50 -0
  27. package/dist/perathos.js +188 -0
  28. package/dist/portal.d.ts +66 -5
  29. package/dist/portal.js +895 -242
  30. package/dist/receipt.d.ts +4 -1
  31. package/dist/session-audit.d.ts +46 -0
  32. package/dist/session-audit.js +150 -0
  33. package/dist/site-links.d.ts +23 -0
  34. package/dist/site-links.js +29 -0
  35. package/dist/verify.js +44 -4
  36. package/dist/web-bot-auth.d.ts +105 -0
  37. package/dist/web-bot-auth.js +508 -0
  38. package/docs/acs.md +2 -0
  39. package/docs/approvals.md +1 -1
  40. package/docs/completeness.md +1 -1
  41. package/docs/configuration.md +2 -0
  42. package/docs/console.md +11 -2
  43. package/docs/door-languages.md +168 -0
  44. package/docs/door-middleware.md +216 -0
  45. package/docs/door-quickstart.md +1 -1
  46. package/docs/door-signals.md +43 -6
  47. package/docs/door.md +129 -32
  48. package/docs/egress.md +3 -1
  49. package/docs/github-action.md +2 -2
  50. package/docs/mandates.md +1 -1
  51. package/docs/perathos.md +100 -0
  52. package/docs/sdk.md +32 -1
  53. package/docs/threat-model.md +2 -1
  54. package/docs/tutorials.md +6 -0
  55. package/docs/usage.md +3 -1
  56. package/docs/verification.md +3 -1
  57. package/package.json +7 -1
  58. package/vectors/audit.json +27 -27
  59. package/vectors/canonical.json +5 -5
  60. package/vectors/interop/perathos/LICENSE +21 -0
  61. package/vectors/interop/perathos/README.md +17 -0
  62. package/vectors/interop/perathos/pocketos-replay/session.head.json +11 -0
  63. package/vectors/interop/perathos/pocketos-replay/session.jsonl +8 -0
  64. package/vectors/interop/perathos/pocketos-replay/verification.json +65 -0
  65. 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
+ }
package/docs/acs.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # The ACS Guardian
2
2
 
3
+ > How it works and when to use it. Every field, route, and flag is in [the reference](../../../site/reference/acs.md).
4
+
3
5
  The [OWASP Agent Control Standard](https://github.com/GenAI-Security-Project/agent-control-standard) (ACS) is a wire contract between an agent and a separate policy point. Before the agent acts, its instrumentation sends a JSON-RPC 2.0 hook, such as `steps/toolCallRequest`, to a **Guardian**. The Guardian answers `allow`, `deny`, `modify`, `ask`, or `defer`, and the agent is expected to honor the answer. `agent-custody acs` is a Guardian for two of those hooks. It decides each one with a Cedar policy and returns the decision with a signed, logged receipt (`issuer.kind: "guardian"`). A third party can check that receipt with the Guardian's public key alone.
4
6
 
5
7
  This is a spike: enough to show the two fit together. It is not an ACS-Core conformant Guardian. The list of what it leaves out is [below](#what-it-does-not-implement). It was written against the ACS repository at commit `db457a8` (`version.txt` 0.1.4, schemas under `specification/v0.1.0/`).
package/docs/approvals.md CHANGED
@@ -1,4 +1,4 @@
1
- # Payload-bound human approvals
1
+ # Human approvals
2
2
 
3
3
  A delegation lets an agent use a tool. A human approval authorizes one exact call: this principal, this agent, this tool, and every argument, until a short expiry. The gateway requires the signed approval before forwarding a protected call. A flag such as `approved: true` in the arguments has no authority.
4
4
 
@@ -1,4 +1,4 @@
1
- # Completeness: matching the provider's records against the receipts
1
+ # Completeness
2
2
 
3
3
  A verified receipt proves what went through the gateway. Nothing on the gateway's side can see an action that never went through it: whoever holds the Stripe key can issue a refund straight through Stripe's API. The provider's own record is the only place that action shows. `agent-custody completeness` lets an auditor check it, with a read-only key of their own.
4
4
 
@@ -1,5 +1,7 @@
1
1
  # Configuring the gateway
2
2
 
3
+ > A walk through the gateway's config files. Every field, with its type, is in [the gateway reference](../../../site/reference/gateway.md).
4
+
3
5
  Who may use which tools, and where those tools live, is set in three files and a few environment variables. This page is the map: what each one decides, how they fit together, a worked example with two agents on one shared gateway, how it all works in the Docker image, and how to check a config before you start. The full list of config keys is in [the gateway reference](/reference/gateway); the Cedar and Rego languages are in [policies.md](policies.md).
4
6
 
5
7
  ## What you configure, and where
package/docs/console.md CHANGED
@@ -1,4 +1,4 @@
1
- # The gateway console
1
+ # Gateway console
2
2
 
3
3
  A small admin service for the person who runs a gateway. It shows what the gateway is configured to do and what it has done, validates and replays a policy change before it is saved, and revokes a grant. It is a separate process from the gateway, behind a token, so the gateway never serves an admin page next to the agents' credentials.
4
4
 
@@ -32,9 +32,18 @@ It listens on `127.0.0.1:8795` and prints the URL. Open it and sign in with the
32
32
  | **Check** | the same checks as `agent-custody check`, except that the credential variables are **not** checked: the console deliberately does not hold the gateway's credentials, so it cannot tell whether they are set where the gateway runs. "Connect" starts the upstreams and lists their tools only for a config that names no credentials; otherwise it says to run `agent-custody check --connect` where the gateway runs, for example `docker compose exec gateway agent-custody check --config /config/gateway.json --connect`. A connect check that does not finish in 60 seconds is stopped and the upstreams it started are closed ([configuration.md](configuration.md#check-it-before-you-start-it)) |
33
33
  | **Policy** | the policy file in an editor. *Validate* asks Cedar to parse it. *Replay recorded calls* runs it against the verified receipts, using each call's own arguments and facts, and lists the decisions that would change, with their receipts. **A replay only re-decides calls that already happened**: a limit that no recorded call reached, or removing one, can show no change, so it is not a test of what a policy allows. *Save* writes it, keeping the previous version and recording the change |
34
34
  | **Grants** | paste a grant to see whether the gateway would accept it (valid, expired, revoked, signed by a key it does not trust) and what it allows; *Revoke* adds its digest to the revocation file, and the gateway refuses it, and every grant delegated from it, on its next call. Lists the revoked digests |
35
- | **Receipts** | the newest receipts with their agent, tool, decision, and outcome, each verified against the gateway key, the trusted principals, and the local log; a receipt that does not verify says which checks failed; a row opens the full statement |
35
+ | **Receipts** | the newest receipts with their agent, tool, decision, and outcome, each verified against the gateway key, the trusted principals, and the local log; a receipt that does not verify says which checks failed; the id in a row opens a summary of the statement, with the full statement behind *Raw JSON* |
36
36
  | **Audit** | every change made through the console: who, when, and what, with the policy's digest before and after |
37
37
 
38
+ ## Use the page
39
+
40
+ - **The tab is in the URL.** The hash is `#tab=policy`, `#tab=receipts`, and so on. Copy the URL to link to a tab. Back and Forward move between the tabs that you opened.
41
+ - **Results show beside the button.** The result of *Save* shows beside *Save*. The result of *Revoke* shows beside *Revoke*. Both are announced to a screen reader.
42
+ - **Unsaved policy edits are not lost without a warning.** A tab change with unsaved edits opens a dialog that asks you to discard them or to keep editing. Closing or reloading the page shows the browser's own warning.
43
+ - **Save and Revoke ask in the page.** The dialog names the policy file or the grant (the agent and the digest). Escape and *Cancel* do nothing. For *Revoke*, the focus starts on *Cancel*.
44
+ - **A receipt opens from its id.** The id in each row is a button, so the keyboard and a screen reader can open it. The detail shows the tool, the decision, the status, the time, the agent, the principal, whether a grant was presented, the digests, and whether the receipt verifies. The full statement is behind *Raw JSON*. The focus moves to the detail when it opens and returns to the id when you press *Close*.
45
+ - **Times show in your local time.** The UTC value shows when you hold the pointer over a time.
46
+
38
47
  ## What a saved policy does
39
48
 
40
49
  A running gateway re-reads `policy.cedar` when it changes, so **a saved policy applies from the gateway's next call**, with no restart, and the gateway records the change in `receipts/policy-reloads.jsonl`. The save is guarded: Cedar must parse the text; and the operator must confirm a policy that has no `permit` rule (a `permit(` in a comment does not count), because every call would be denied, or a `permit` rule with **no action and no condition**, which allows every tool in a grant's scopes and which a replay cannot show. A save made from a copy that is no longer the file on disk is refused with `409`. The digest check, the history copy, and the write happen under one lock, in this process and, through a lock file in the state directory, across consoles that share it, so two administrators cannot overwrite each other. The previous version is kept under `console/policy-history/` and the change goes in the audit trail.