@agent-custody/receipts 0.7.0 → 0.9.0

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 (51) hide show
  1. package/README.md +29 -13
  2. package/dist/approval.d.ts +74 -0
  3. package/dist/approval.js +196 -0
  4. package/dist/capture.js +49 -1
  5. package/dist/check.d.ts +19 -0
  6. package/dist/check.js +288 -0
  7. package/dist/cli.js +238 -11
  8. package/dist/config.d.ts +85 -0
  9. package/dist/config.js +72 -2
  10. package/dist/console-page.d.ts +4 -0
  11. package/dist/console-page.js +342 -0
  12. package/dist/console.d.ts +20 -0
  13. package/dist/console.js +521 -0
  14. package/dist/gateway.d.ts +9 -0
  15. package/dist/gateway.js +335 -45
  16. package/dist/index.d.ts +9 -2
  17. package/dist/index.js +7 -1
  18. package/dist/issue.d.ts +8 -3
  19. package/dist/issue.js +13 -4
  20. package/dist/log-store.d.ts +3 -2
  21. package/dist/log-store.js +2 -0
  22. package/dist/operations.d.ts +101 -0
  23. package/dist/operations.js +239 -0
  24. package/dist/otel.js +12 -5
  25. package/dist/policy.d.ts +2 -0
  26. package/dist/policy.js +10 -0
  27. package/dist/portal.d.ts +78 -4
  28. package/dist/portal.js +516 -26
  29. package/dist/receipt.d.ts +36 -1
  30. package/dist/rest.js +14 -1
  31. package/dist/simulate.d.ts +58 -0
  32. package/dist/simulate.js +204 -0
  33. package/dist/splunk.js +11 -4
  34. package/dist/sso.d.ts +47 -0
  35. package/dist/sso.js +161 -0
  36. package/dist/verify.d.ts +2 -0
  37. package/dist/verify.js +241 -7
  38. package/docs/approvals.md +107 -0
  39. package/docs/codex-recovery.md +132 -0
  40. package/docs/configuration.md +224 -0
  41. package/docs/console.md +79 -0
  42. package/docs/financial-operations.md +99 -0
  43. package/docs/policies.md +23 -0
  44. package/docs/threat-model.md +13 -0
  45. package/docs/tutorials.md +9 -0
  46. package/docs/usage.md +49 -4
  47. package/docs/verification.md +26 -8
  48. package/package.json +8 -2
  49. package/vectors/audit.json +27 -27
  50. package/vectors/canonical.json +5 -5
  51. package/vectors/receipts.json +2866 -464
@@ -0,0 +1,521 @@
1
+ // The gateway console: a small admin service, separate from the gateway, for the person who runs it. It shows what the
2
+ // gateway is configured to do and what it has done, validates and simulates a policy change before it is saved, and
3
+ // revokes a grant. It never holds a principal's private key and never signs; everything it shows is read from the
4
+ // gateway's own config, receipts, and revocation file, and everything it changes is the policy file or the revocation
5
+ // file, both of which the gateway reads. Every change is recorded in an append-only audit file.
6
+ import * as cedar from "@cedar-policy/cedar-wasm/nodejs";
7
+ import { createHash, timingSafeEqual } from "node:crypto";
8
+ import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
9
+ import { createServer } from "node:http";
10
+ import { basename, dirname, join } from "node:path";
11
+ import { checkConfig } from "./check.js";
12
+ import { loadConfig } from "./config.js";
13
+ import { loadPrivateKey, loadPublicKey } from "./crypto.js";
14
+ import { decodeDelegation, delegationValidAt, grantDigest, verifyDelegation } from "./delegation.js";
15
+ import { writeRevokedGrants } from "./gateway.js";
16
+ import { CONSOLE_CSP, CONSOLE_HTML } from "./console-page.js";
17
+ import { hasPermitRule, policyDigest } from "./policy.js";
18
+ import { simulatePolicy } from "./simulate.js";
19
+ import { verifyBundle } from "./verify.js";
20
+ const MAX_BODY = 1_000_000;
21
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
22
+ class HttpError extends Error {
23
+ status;
24
+ constructor(status, message) {
25
+ super(message);
26
+ this.status = status;
27
+ }
28
+ }
29
+ const sha = (s) => createHash("sha256").update(s).digest();
30
+ function atomicWrite(path, text) {
31
+ const tmp = `${path}.${process.pid}.tmp`;
32
+ writeFileSync(tmp, text);
33
+ renameSync(tmp, path);
34
+ }
35
+ async function readBody(req) {
36
+ const chunks = [];
37
+ let size = 0;
38
+ for await (const chunk of req) {
39
+ size += chunk.length;
40
+ if (size > MAX_BODY)
41
+ throw new HttpError(413, "the request body is too large");
42
+ chunks.push(chunk);
43
+ }
44
+ if (!size)
45
+ return {};
46
+ try {
47
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
48
+ }
49
+ catch {
50
+ throw new HttpError(400, "the body is not JSON");
51
+ }
52
+ }
53
+ const object = (v) => {
54
+ if (!v || typeof v !== "object" || Array.isArray(v))
55
+ throw new HttpError(400, "the body must be a JSON object");
56
+ return v;
57
+ };
58
+ const decodePredicate = (bundle) => {
59
+ try {
60
+ return JSON.parse(Buffer.from(bundle.envelope.payload, "base64").toString("utf8")).predicate;
61
+ }
62
+ catch {
63
+ return null;
64
+ }
65
+ };
66
+ /**
67
+ * What an operator should be asked to confirm before a policy is saved: no permit rule at all, or a permit rule that has no
68
+ * condition and names no action, which allows every tool in a grant's scopes. Replaying recorded calls cannot show the
69
+ * second one: it changes nothing for a history that never used what it allows.
70
+ */
71
+ function policyIssues(text) {
72
+ const issues = [];
73
+ if (!hasPermitRule(text))
74
+ issues.push("The policy has no permit rule, so every call would be denied.");
75
+ const parts = cedar.policySetTextToParts(text);
76
+ if (parts.type === "success") {
77
+ for (const p of parts.policies) {
78
+ const j = cedar.policyToJson(p);
79
+ if (j.type === "success" && j.json.effect === "permit" && j.json.action?.op === "All" && !(j.json.conditions?.length)) {
80
+ const who = j.json.principal?.op === "All" ? "for every agent" : "for the agent it names";
81
+ issues.push(`A permit rule has no action and no condition: it allows every tool in a grant's scopes, ${who}. A replay cannot show this, because it only re-decides calls that already happened.`);
82
+ }
83
+ }
84
+ }
85
+ return issues;
86
+ }
87
+ export async function serveConsole(options) {
88
+ const log = options.log ?? ((m) => console.error(m));
89
+ const tokenHash = sha(options.token);
90
+ if (!options.token)
91
+ throw new Error("the console needs a token");
92
+ loadConfig(options.configFile);
93
+ const state = options.stateDir ?? join(dirname(loadConfig(options.configFile).receiptsDir), "console");
94
+ mkdirSync(join(state, "policy-history"), { recursive: true });
95
+ const auditFile = join(state, "audit.jsonl");
96
+ let connecting = false;
97
+ const audit = (action, detail, by) => {
98
+ appendFileSync(auditFile, JSON.stringify({ at: new Date().toISOString(), by, action, ...detail }) + "\n");
99
+ };
100
+ /** the keys the console verifies receipts with: the gateway's own public key and the trusted principals' */
101
+ const keysOf = (cfg) => {
102
+ const problems = [];
103
+ const issuerKeys = [];
104
+ try {
105
+ if (existsSync(cfg.identity.keyFile)) {
106
+ const k = loadPrivateKey(cfg.identity.keyFile);
107
+ issuerKeys.push({ publicKey: k.publicKey, keyid: k.keyid });
108
+ }
109
+ else
110
+ problems.push("the gateway key does not exist yet, so receipts cannot be verified");
111
+ }
112
+ catch (e) {
113
+ problems.push(`the gateway key: ${e instanceof Error ? e.message : String(e)}`);
114
+ }
115
+ const principalKeys = [];
116
+ for (const f of cfg.trustedPrincipalKeys) {
117
+ try {
118
+ principalKeys.push(loadPublicKey(f));
119
+ }
120
+ catch (e) {
121
+ problems.push(`${f}: ${e instanceof Error ? e.message : String(e)}`);
122
+ }
123
+ }
124
+ return { issuerKeys, principalKeys, problems };
125
+ };
126
+ const revokedList = (cfg) => {
127
+ if (!cfg.revokedGrants || !existsSync(cfg.revokedGrants))
128
+ return [];
129
+ const list = JSON.parse(readFileSync(cfg.revokedGrants, "utf8"));
130
+ return Array.isArray(list) ? list.filter((d) => typeof d === "string") : [];
131
+ };
132
+ /** the receipt files, newest first; an authorization that has no receipt is not one */
133
+ const receiptFiles = (cfg) => {
134
+ if (!existsSync(cfg.receiptsDir))
135
+ return [];
136
+ return readdirSync(cfg.receiptsDir)
137
+ .filter((n) => n.endsWith(".json") && !n.endsWith(".authorization.json") && UUID.test(n.slice(0, -5)))
138
+ .map((n) => ({ id: n.slice(0, -5), file: join(cfg.receiptsDir, n), mtime: statSync(join(cfg.receiptsDir, n)).mtimeMs }))
139
+ .sort((a, b) => b.mtime - a.mtime);
140
+ };
141
+ const verifyOptionsFor = (cfg, keys) => ({
142
+ issuerKeys: keys.issuerKeys,
143
+ principalKeys: keys.principalKeys,
144
+ ...(cfg.logFile && existsSync(cfg.logFile) ? { logFile: cfg.logFile } : {}),
145
+ });
146
+ const summarize = (id, file, cfg, keys) => {
147
+ let bundle;
148
+ try {
149
+ bundle = JSON.parse(readFileSync(file, "utf8"));
150
+ }
151
+ catch {
152
+ return { id, readable: false, verified: false, failing: ["the file is not readable JSON"] };
153
+ }
154
+ const p = decodePredicate(bundle);
155
+ const v = keys.issuerKeys.length ? verifyBundle(bundle, verifyOptionsFor(cfg, keys)) : null;
156
+ const execution = (p?.execution ?? {});
157
+ return {
158
+ id,
159
+ readable: true,
160
+ timestamp: p?.timestamp ?? null,
161
+ tool: p?.tool?.name ?? null,
162
+ agent: p?.agent?.id ?? null,
163
+ principal: p?.principal?.id ?? null,
164
+ decision: p?.policy?.decision ?? null,
165
+ enforced: p?.policy?.enforced !== false,
166
+ status: execution.status ?? null,
167
+ reason: execution.reason ?? null,
168
+ issuer: p?.issuer?.kind ?? null,
169
+ verified: v ? v.ok : false,
170
+ failing: v ? v.checks.filter((c) => !c.ok).map((c) => c.name) : ["no gateway key to verify with"],
171
+ };
172
+ };
173
+ const gatewayHealth = async () => {
174
+ if (!options.gatewayUrl)
175
+ return null;
176
+ try {
177
+ const r = await fetch(new URL("health", options.gatewayUrl.endsWith("/") ? options.gatewayUrl : `${options.gatewayUrl}/`), { signal: AbortSignal.timeout(2000) });
178
+ const body = (await r.json());
179
+ return { reachable: r.ok, sessions: body.sessions ?? null, keyid: body.keyid ?? null };
180
+ }
181
+ catch (e) {
182
+ return { reachable: false, error: e instanceof Error ? e.message : String(e) };
183
+ }
184
+ };
185
+ const upstreamsOf = (cfg) => (cfg.upstreams ?? (cfg.upstream ? [{ name: "upstream", ...cfg.upstream }] : [])).map((u) => {
186
+ const name = "name" in u ? u.name : "upstream";
187
+ if ("rest" in u)
188
+ return { name, kind: "rest", target: u.rest.baseUrl, tools: u.rest.tools.map((t) => t.name) };
189
+ if ("a2a" in u)
190
+ return { name, kind: "a2a", target: u.a2a.url, tools: [`${u.a2a.prefix}.send`, `${u.a2a.prefix}.card`] };
191
+ if ("url" in u)
192
+ return { name, kind: "mcp-http", target: u.url, tools: null };
193
+ return { name, kind: "mcp-stdio", target: [u.command, ...u.args].join(" "), tools: null };
194
+ });
195
+ // saves are serialised in this process, and a lock file in the state directory serialises another console on the same one
196
+ const lockFile = join(state, "policy.lock");
197
+ let saving = Promise.resolve();
198
+ const withPolicyLock = (fn) => {
199
+ const run = saving.then(async () => {
200
+ const deadline = Date.now() + 5_000;
201
+ for (;;) {
202
+ try {
203
+ closeSync(openSync(lockFile, "wx"));
204
+ break;
205
+ }
206
+ catch (e) {
207
+ if (e.code !== "EEXIST")
208
+ throw e;
209
+ try {
210
+ if (Date.now() - statSync(lockFile).mtimeMs > 30_000) {
211
+ unlinkSync(lockFile);
212
+ continue;
213
+ }
214
+ }
215
+ catch {
216
+ continue;
217
+ }
218
+ if (Date.now() > deadline)
219
+ throw new HttpError(409, "another save is in progress; try again");
220
+ await new Promise((r) => setTimeout(r, 50));
221
+ }
222
+ }
223
+ try {
224
+ return fn();
225
+ }
226
+ finally {
227
+ try {
228
+ unlinkSync(lockFile);
229
+ }
230
+ catch {
231
+ /* already gone */
232
+ }
233
+ }
234
+ });
235
+ saving = run.catch(() => { });
236
+ return run;
237
+ };
238
+ const routes = {
239
+ "GET /api/overview": async () => {
240
+ const cfg = loadConfig(options.configFile);
241
+ const keys = keysOf(cfg);
242
+ const receipts = receiptFiles(cfg);
243
+ return {
244
+ configFile: options.configFile,
245
+ mode: cfg.mode ?? "enforce",
246
+ precommit: cfg.precommit,
247
+ log: cfg.log ? { kind: "remote", url: cfg.log.url, hashOnly: !!cfg.log.hashOnly } : { kind: "local", file: cfg.logFile },
248
+ upstreams: upstreamsOf(cfg),
249
+ facts: cfg.facts.map((f) => ({ name: f.name, tool: f.tool, forTools: f.forTools })),
250
+ gatewayKeyid: keys.issuerKeys[0]?.keyid ?? null,
251
+ principals: keys.principalKeys.map((k) => k.keyid),
252
+ keyProblems: keys.problems,
253
+ revokedCount: revokedList(cfg).length,
254
+ revocationFile: cfg.revokedGrants ?? null,
255
+ receiptCount: receipts.length,
256
+ lastReceiptAt: receipts[0] ? new Date(receipts[0].mtime).toISOString() : null,
257
+ gateway: await gatewayHealth(),
258
+ findings: await checkConfig(options.configFile, { environment: "skip" }),
259
+ };
260
+ },
261
+ "POST /api/check": async (req) => {
262
+ const connect = object(await readBody(req)).connect === true;
263
+ if (connect) {
264
+ if (connecting)
265
+ throw new HttpError(409, "a connect check is already running");
266
+ connecting = true;
267
+ }
268
+ const stop = new AbortController();
269
+ const timer = connect ? setTimeout(() => stop.abort(), options.checkTimeoutMs ?? 60_000) : undefined;
270
+ try {
271
+ const findings = await checkConfig(options.configFile, { connect, environment: "skip", signal: stop.signal });
272
+ if (stop.signal.aborted)
273
+ throw new HttpError(504, "the check took too long and was stopped; the upstreams it started were closed");
274
+ return { findings };
275
+ }
276
+ finally {
277
+ clearTimeout(timer);
278
+ if (connect)
279
+ connecting = false;
280
+ }
281
+ },
282
+ "GET /api/policy": async () => {
283
+ const cfg = loadConfig(options.configFile);
284
+ const text = readFileSync(cfg.policyFile, "utf8");
285
+ return { path: cfg.policyFile, text, digest: policyDigest(text), history: readdirSync(join(state, "policy-history")).sort().reverse().slice(0, 20) };
286
+ },
287
+ "POST /api/policy/validate": async (req) => {
288
+ const text = String(object(await readBody(req)).text ?? "");
289
+ const r = cedar.checkParsePolicySet({ staticPolicies: text });
290
+ const errors = r.type === "success" ? [] : r.errors.map((e) => e.message);
291
+ return { ok: r.type === "success", errors, digest: policyDigest(text), issues: r.type === "success" ? policyIssues(text) : [] };
292
+ },
293
+ "POST /api/policy/simulate": async (req) => {
294
+ const text = String(object(await readBody(req)).text ?? "");
295
+ const cfg = loadConfig(options.configFile);
296
+ const keys = keysOf(cfg);
297
+ if (!keys.issuerKeys.length)
298
+ throw new HttpError(409, "there is no gateway key to verify receipts with, so there is nothing to replay");
299
+ const predicates = [];
300
+ let unverified = 0;
301
+ for (const f of receiptFiles(cfg).slice(0, 1000)) {
302
+ try {
303
+ const bundle = JSON.parse(readFileSync(f.file, "utf8"));
304
+ const p = decodePredicate(bundle);
305
+ if (p && verifyBundle(bundle, verifyOptionsFor(cfg, keys)).ok)
306
+ predicates.push(p);
307
+ else
308
+ unverified++;
309
+ }
310
+ catch {
311
+ unverified++;
312
+ }
313
+ }
314
+ let report;
315
+ try {
316
+ report = simulatePolicy(text, predicates);
317
+ }
318
+ catch (e) {
319
+ throw new HttpError(400, e instanceof Error ? e.message : String(e));
320
+ }
321
+ return {
322
+ replayed: predicates.length,
323
+ unverified,
324
+ report: {
325
+ policyDigest: report.policyDigest,
326
+ total: report.total,
327
+ evaluated: report.evaluated,
328
+ unchanged: report.unchanged,
329
+ complete: report.complete,
330
+ changes: report.changes.slice(0, 200).map((c) => ({ receiptId: c.receiptId, tool: c.tool, from: c.previous.decision, to: c.proposed.decision })),
331
+ changeCount: report.changes.length,
332
+ skipped: report.skipped.slice(0, 50),
333
+ },
334
+ };
335
+ },
336
+ "PUT /api/policy": async (req, _url, by) => {
337
+ const body = object(await readBody(req));
338
+ const text = String(body.text ?? "");
339
+ const parsed = cedar.checkParsePolicySet({ staticPolicies: text });
340
+ if (parsed.type !== "success")
341
+ throw new HttpError(400, `the policy does not parse: ${parsed.errors.map((e) => e.message).join("; ")}`);
342
+ const issues = policyIssues(text);
343
+ if (issues.length && body.confirm !== true)
344
+ throw new HttpError(400, `confirm before saving: ${issues.join(" ")}`);
345
+ // from reading the digest to the rename, nothing else may save: two tabs that loaded the same digest would otherwise both pass the
346
+ // check, the later rename would win, and the history of the lost edit would not even be the version it replaced
347
+ return withPolicyLock(() => {
348
+ const cfg = loadConfig(options.configFile);
349
+ const current = readFileSync(cfg.policyFile, "utf8");
350
+ if (body.expectDigest !== policyDigest(current))
351
+ throw new HttpError(409, "the policy file changed since you loaded it; reload and try again");
352
+ writeFileSync(join(state, "policy-history", `${new Date().toISOString().replace(/[:.]/g, "-")}-${policyDigest(current).slice(0, 12)}.cedar`), current);
353
+ try {
354
+ atomicWrite(cfg.policyFile, text);
355
+ }
356
+ catch (e) {
357
+ throw new HttpError(500, `the policy file cannot be written (${e instanceof Error ? e.message : String(e)}); mount the config directory read-write for the console`);
358
+ }
359
+ audit("policy.save", { file: cfg.policyFile, from: policyDigest(current), to: policyDigest(text), bytes: text.length, confirmed: issues }, by);
360
+ return { digest: policyDigest(text), note: "saved; the gateway reads the policy when it starts, so restart it to apply the change" };
361
+ });
362
+ },
363
+ "POST /api/grants/inspect": async (req) => {
364
+ const body = object(await readBody(req));
365
+ const cfg = loadConfig(options.configFile);
366
+ const keys = keysOf(cfg);
367
+ const env = (typeof body.grant === "string" ? safeJson(body.grant) : body.grant);
368
+ if (!env || typeof env !== "object")
369
+ throw new HttpError(400, "send the grant as a JSON object or a JSON string");
370
+ const decoded = decodeDelegation(env);
371
+ if (!decoded)
372
+ throw new HttpError(400, "this is not a delegation grant");
373
+ const digest = grantDigest(env);
374
+ const verified = verifyDelegation(env, keys.principalKeys);
375
+ const revoked = revokedList(cfg).includes(digest);
376
+ const now = new Date().toISOString();
377
+ let status;
378
+ if (!verified.ok)
379
+ status = "invalid";
380
+ else if (revoked)
381
+ status = "revoked";
382
+ else if (!delegationValidAt(verified.delegation, now))
383
+ status = Date.parse(verified.delegation.expiresAt) < Date.now() ? "expired" : "not yet valid";
384
+ else
385
+ status = "valid";
386
+ return {
387
+ status,
388
+ error: verified.ok ? null : verified.error,
389
+ digest,
390
+ agent: decoded.agent,
391
+ principal: decoded.principal,
392
+ scopes: decoded.scopes,
393
+ issuedAt: decoded.issuedAt,
394
+ expiresAt: decoded.expiresAt,
395
+ delegated: !!decoded.parent,
396
+ canDelegate: !!decoded.agentKey,
397
+ revoked,
398
+ };
399
+ },
400
+ "POST /api/grants/revoke": async (req, _url, by) => {
401
+ const body = object(await readBody(req));
402
+ const cfg = loadConfig(options.configFile);
403
+ if (!cfg.revokedGrants)
404
+ throw new HttpError(409, "the config has no revokedGrants file, which is where the gateway looks for revoked grants");
405
+ const env = (typeof body.grant === "string" ? safeJson(body.grant) : body.grant);
406
+ if (!env || typeof env !== "object")
407
+ throw new HttpError(400, "send the grant as a JSON object or a JSON string");
408
+ const decoded = decodeDelegation(env);
409
+ if (!decoded)
410
+ throw new HttpError(400, "this is not a delegation grant");
411
+ const digest = grantDigest(env);
412
+ const list = revokedList(cfg);
413
+ if (!list.includes(digest))
414
+ writeRevokedGrants(cfg.revokedGrants, [...list, digest]);
415
+ audit("grant.revoke", { agent: decoded.agent, principal: decoded.principal, digest, already: list.includes(digest) }, by);
416
+ return { digest, agent: decoded.agent, note: "the gateway refuses this grant, and every grant delegated from it, on its next call" };
417
+ },
418
+ "GET /api/revocations": async () => ({ digests: revokedList(loadConfig(options.configFile)) }),
419
+ "GET /api/receipts": async (_req, url) => {
420
+ const cfg = loadConfig(options.configFile);
421
+ const keys = keysOf(cfg);
422
+ const limit = Math.min(Math.max(Number(url.searchParams.get("limit") ?? 50) || 50, 1), 200);
423
+ const files = receiptFiles(cfg);
424
+ return { total: files.length, receipts: files.slice(0, limit).map((f) => summarize(f.id, f.file, cfg, keys)), problems: keys.problems };
425
+ },
426
+ "GET /api/audit": async () => ({
427
+ entries: existsSync(auditFile) ? readFileSync(auditFile, "utf8").trim().split("\n").filter(Boolean).slice(-200).reverse().map((l) => JSON.parse(l)) : [],
428
+ }),
429
+ };
430
+ const safeJson = (s) => {
431
+ try {
432
+ return JSON.parse(s);
433
+ }
434
+ catch {
435
+ throw new HttpError(400, "the grant is not valid JSON");
436
+ }
437
+ };
438
+ const json = (res, status, body) => {
439
+ // a body that was refused unread leaves the connection with data on it: close it, so the next request does not reuse it
440
+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff", ...(status === 413 ? { connection: "close" } : {}) });
441
+ res.end(JSON.stringify(body));
442
+ };
443
+ // a wrong token is slow to retry: five misses from one address lock it out for a minute
444
+ const misses = new Map();
445
+ const authorized = (req) => {
446
+ const ip = req.socket.remoteAddress ?? "unknown";
447
+ const m = misses.get(ip);
448
+ if (m && m.until > Date.now())
449
+ return { ok: false, status: 429, message: "too many wrong tokens; try again in a minute" };
450
+ const header = req.headers.authorization ?? "";
451
+ const presented = header.startsWith("Bearer ") ? header.slice(7) : "";
452
+ if (presented && timingSafeEqual(sha(presented), tokenHash)) {
453
+ misses.delete(ip);
454
+ return { ok: true, by: `console@${ip}` };
455
+ }
456
+ // a request with no token at all is not a guess at one, so it does not count towards the lockout
457
+ if (presented) {
458
+ const n = (m?.n ?? 0) + 1;
459
+ misses.set(ip, n >= 5 ? { n: 0, until: Date.now() + 60_000 } : { n, until: 0 });
460
+ }
461
+ return { ok: false, status: 401, message: "a valid bearer token is required" };
462
+ };
463
+ const server = createServer(async (req, res) => {
464
+ try {
465
+ const url = new URL(req.url ?? "/", "http://localhost");
466
+ if (req.method === "GET" && url.pathname === "/healthz")
467
+ return json(res, 200, { ok: true });
468
+ if (req.method === "GET" && url.pathname === "/") {
469
+ res.writeHead(200, {
470
+ "content-type": "text/html; charset=utf-8",
471
+ "content-security-policy": CONSOLE_CSP,
472
+ "x-content-type-options": "nosniff",
473
+ "x-frame-options": "DENY",
474
+ "referrer-policy": "no-referrer",
475
+ "cache-control": "no-store",
476
+ });
477
+ return void res.end(CONSOLE_HTML);
478
+ }
479
+ if (!url.pathname.startsWith("/api/"))
480
+ return json(res, 404, { error: "not found" });
481
+ const auth = authorized(req);
482
+ if (!auth.ok)
483
+ return json(res, auth.status, { error: auth.message });
484
+ const receiptId = url.pathname.match(/^\/api\/receipts\/([^/]+)$/);
485
+ if (req.method === "GET" && receiptId) {
486
+ const id = receiptId[1];
487
+ if (!UUID.test(id))
488
+ return json(res, 400, { error: "a receipt id is a UUID" });
489
+ const cfg = loadConfig(options.configFile);
490
+ const file = join(cfg.receiptsDir, `${id}.json`);
491
+ if (!existsSync(file) || basename(file) !== `${id}.json`)
492
+ return json(res, 404, { error: "no such receipt" });
493
+ const bundle = JSON.parse(readFileSync(file, "utf8"));
494
+ return json(res, 200, { summary: summarize(id, file, cfg, keysOf(cfg)), statement: decodePredicate(bundle) });
495
+ }
496
+ const handler = routes[`${req.method} ${url.pathname}`];
497
+ if (!handler)
498
+ return json(res, 404, { error: "not found" });
499
+ json(res, 200, await handler(req, url, auth.by));
500
+ }
501
+ catch (e) {
502
+ if (e instanceof HttpError)
503
+ return json(res, e.status, { error: e.message });
504
+ log(`agent-custody console: ${e instanceof Error ? e.stack ?? e.message : String(e)}`);
505
+ json(res, 500, { error: e instanceof Error ? e.message : "internal error" });
506
+ }
507
+ });
508
+ await new Promise((resolve, reject) => {
509
+ server.once("error", reject);
510
+ server.listen(options.port ?? 8795, options.host ?? "127.0.0.1", resolve);
511
+ });
512
+ const addr = server.address();
513
+ const host = options.host ?? "127.0.0.1";
514
+ return {
515
+ url: `http://${host === "0.0.0.0" ? "127.0.0.1" : host}:${addr.port}/`,
516
+ close: () => new Promise((resolve) => {
517
+ server.close(() => resolve());
518
+ server.closeAllConnections();
519
+ }),
520
+ };
521
+ }
package/dist/gateway.d.ts CHANGED
@@ -4,9 +4,12 @@ import { type Envelope } from "./crypto.ts";
4
4
  import { type Delegation } from "./delegation.ts";
5
5
  import { type LogSink } from "./log-sink.ts";
6
6
  import { type ReceiptExporter } from "./otel.ts";
7
+ import type { ReceiptBundle } from "./receipt.ts";
7
8
  export declare const GATEWAY_VERSION = "0.1.0";
8
9
  export declare const RECEIPT_META_KEY = "agent-custody/receipt";
9
10
  export declare const MODEL_META_KEY = "agent-custody/model";
11
+ /** Set by the gateway on the answer to a retry of a financial operation: the receipt of the retry itself. `agent-custody/receipt` stays the receipt that holds the operation's outcome. */
12
+ export declare const RETRY_RECEIPT_META_KEY = "agent-custody/retry-receipt";
10
13
  /** Set by the gateway on the call it forwards upstream: the receipt id, and the agent and principal from the attested grant. */
11
14
  export declare const AGENT_META_KEY = "agent-custody/agent";
12
15
  export declare const PRINCIPAL_META_KEY = "agent-custody/principal";
@@ -41,6 +44,8 @@ export interface GatewayOptions {
41
44
  log?: LogSink;
42
45
  /** told about every receipt after it is written, in place of the exporter the config names */
43
46
  exporter?: ReceiptExporter;
47
+ /** cancels the start while it is connecting to the upstreams: every upstream already started is closed and the call rejects */
48
+ signal?: AbortSignal;
44
49
  }
45
50
  /**
46
51
  * The shared part of a gateway: the key, the policy, the issuer, the log, the upstreams, and the fact lookups. One host
@@ -54,6 +59,10 @@ export interface GatewayHost {
54
59
  revoke(grantDigest: string): void;
55
60
  /** the digests revoked so far */
56
61
  revoked(): string[];
62
+ /** the names of every tool the upstreams offer, before any grant narrows them */
63
+ tools(): string[];
64
+ /** Operator-only provider lookup. Never exposed as an agent tool. Unknown/pending reservations remain held until a terminal reconciliation receipt is committed. */
65
+ reconcile(operationId: string): Promise<ReceiptBundle>;
57
66
  /** closes the upstreams; every session opened from this host is finished with */
58
67
  close(): Promise<void>;
59
68
  }