@agent-custody/receipts 0.16.10 → 0.16.11

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 (62) hide show
  1. package/README.md +20 -9
  2. package/dist/approval-requests.d.ts +114 -0
  3. package/dist/approval-requests.js +198 -0
  4. package/dist/approval.d.ts +8 -0
  5. package/dist/approval.js +10 -3
  6. package/dist/check.js +2 -0
  7. package/dist/cli.js +68 -2
  8. package/dist/completeness.d.ts +11 -2
  9. package/dist/completeness.js +45 -9
  10. package/dist/config.d.ts +3 -0
  11. package/dist/config.js +6 -1
  12. package/dist/console-page.js +87 -2
  13. package/dist/console.js +72 -0
  14. package/dist/crypto.d.ts +2 -0
  15. package/dist/crypto.js +2 -1
  16. package/dist/delegation.d.ts +1 -1
  17. package/dist/delegation.js +19 -2
  18. package/dist/did-key.d.ts +2 -0
  19. package/dist/did-key.js +21 -1
  20. package/dist/door-core.d.ts +373 -0
  21. package/dist/door-core.js +743 -0
  22. package/dist/door-worker.d.ts +133 -0
  23. package/dist/door-worker.js +259 -0
  24. package/dist/door.d.ts +11 -293
  25. package/dist/door.js +43 -753
  26. package/dist/gateway-http.d.ts +1 -6
  27. package/dist/gateway-http.js +2 -19
  28. package/dist/gateway.js +24 -3
  29. package/dist/grant-header.d.ts +8 -0
  30. package/dist/grant-header.js +19 -0
  31. package/dist/index.d.ts +3 -2
  32. package/dist/index.js +2 -1
  33. package/dist/issue.d.ts +2 -16
  34. package/dist/issue.js +2 -12
  35. package/dist/log-http.d.ts +37 -0
  36. package/dist/log-http.js +74 -0
  37. package/dist/log-sink.d.ts +3 -37
  38. package/dist/log-sink.js +5 -71
  39. package/dist/log.d.ts +2 -27
  40. package/dist/log.js +2 -173
  41. package/dist/merkle.d.ts +27 -0
  42. package/dist/merkle.js +175 -0
  43. package/dist/object-issuer.d.ts +29 -0
  44. package/dist/object-issuer.js +172 -0
  45. package/dist/receipt-pending.d.ts +16 -0
  46. package/dist/receipt-pending.js +14 -0
  47. package/dist/web-bot-auth.d.ts +26 -6
  48. package/dist/web-bot-auth.js +116 -56
  49. package/docs/approvals.md +33 -0
  50. package/docs/completeness.md +44 -5
  51. package/docs/console.md +11 -4
  52. package/docs/door-quickstart.md +53 -17
  53. package/docs/door-signals.md +5 -5
  54. package/docs/door-worker.md +81 -0
  55. package/docs/door.md +10 -8
  56. package/docs/github-action.md +2 -2
  57. package/docs/tutorials.md +2 -0
  58. package/docs/verification.md +1 -1
  59. package/package.json +3 -1
  60. package/vectors/audit.json +27 -27
  61. package/vectors/canonical.json +5 -5
  62. package/vectors/receipts.json +1645 -1549
package/dist/cli.js CHANGED
@@ -7,6 +7,8 @@ import { closeSync, constants as fsConstants, existsSync, fchmodSync, openSync,
7
7
  import { dirname, join, resolve } from "node:path";
8
8
  import { loadAcsGuardianConfig, loadConfig, loadDoorConfig, loadEgressConfig, loadSdkConfig } from "./config.js";
9
9
  import { dsseVerify, generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
10
+ import { DEFAULT_APPROVAL_LIFETIME_SECONDS } from "./approval.js";
11
+ import { approvalRequestExpiresAt, approveApprovalRequest, denyApprovalRequest, listApprovalRequests, readApprovalRequest } from "./approval-requests.js";
10
12
  import { createDelegation, decodeDelegation, delegateFrom, grantDigest } from "./delegation.js";
11
13
  import { didKeyOf } from "./did-key.js";
12
14
  import { createGateway, createGatewayHost, serveStdio, writeRevokedGrants } from "./gateway.js";
@@ -64,6 +66,13 @@ function untilStopped() {
64
66
  const SERVICES = new Set(["serve", "witness", "signer", "portal", "log", "console", "door", "egress"]);
65
67
  /** a command that waits for untilStopped(); a stdio gateway runs until its input closes and keeps the default signal behaviour */
66
68
  const runsUntilStopped = (cmd, args) => !!cmd && ((SERVICES.has(cmd) && !(cmd === "egress" && args[0] === "draft-policy")) || (cmd === "gateway" && (args.includes("--http") || args.includes("--a2a"))));
69
+ /** `90s`, `10m`, or `1h`, in seconds. */
70
+ function durationSeconds(text) {
71
+ const m = /^(\d+)([smh])$/.exec(text.trim());
72
+ if (!m || Number(m[1]) <= 0)
73
+ throw new Error(`--expires takes 90s, 10m, or 1h; got "${text}"`);
74
+ return Number(m[1]) * { s: 1, m: 60, h: 3600 }[m[2]];
75
+ }
67
76
  /** A secret kept in a file that only this process can read, such as a container secret mounted at /run/secrets. The file's path is not a secret; its contents are. */
68
77
  function tokenFromFile(path) {
69
78
  const v = readFileSync(path, "utf8").trim();
@@ -88,6 +97,10 @@ const USAGE = `agent-custody <command>
88
97
  a narrower grant for a sub-agent, signed by the agent the parent names; the parent travels inside
89
98
  reveal <bundle> --capture-key-env NAME --issuer-key <pub> [--out <file>] [--include-salts] the values a receipt withheld (capture mode encrypted), as a disclosure file
90
99
  for verify --disclose; needs the customer's capture key
100
+ approvals list|show <id>|approve <id> --key <file> [--expires 10m]|deny <id> [--reason <text>] --config <gateway.json>
101
+ human in the loop: the approval requests a gateway with approvals.requests left for
102
+ calls that came without an approval; approve signs the exact call with your key, and
103
+ the same call sent again is forwarded once
91
104
  revoke --config <gateway.json|door.json> --grant <grant.json>
92
105
  revokes a grant: its digest goes into the config's revokedGrants file. At a gateway, every
93
106
  session under it or under a grant delegated from it refuses its next call, and no new session opens for them;
@@ -148,9 +161,10 @@ const USAGE = `agent-custody <command>
148
161
  completeness --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--log-key <pub>]... [--log <log.jsonl>] [--log-id <id>]
149
162
  --provider stripe --object refunds|payouts|transfers --key-env NAME --tool <name>... --since <ISO> --until <ISO>
150
163
  (or --provider github --repo <owner>/<name> --object pushes|merges|releases)
151
- [--id-path id] [--amount-field amount] [--currency-field currency] [--beneficiary <arg>=<field>]... [--json]
164
+ [--id-path id] [--receipt-id-path metadata.agent_custody_receipt] [--amount-field amount] [--currency-field currency] [--beneficiary <arg>=<field>]... [--json]
152
165
  for an auditor: lists the provider's objects in the window with a read-only key, and
153
- matches each to a verified receipt by the provider's object id; reports actions with no
166
+ matches each to a verified receipt: a gateway receipt by the provider's object id, a door
167
+ receipt by the receipt id the object carries; reports actions with no
154
168
  receipt, receipts the provider does not have, and mismatched amounts; exits 1 unless complete
155
169
  replay verified local receipts against a proposed policy using their recorded inputs;
156
170
  --out saves the full JSON report. Exits 1 when any call could not be evaluated.
@@ -334,6 +348,56 @@ async function main(argv) {
334
348
  console.log(values.json ? JSON.stringify(findings, null, 2) : formatFindings(findings));
335
349
  return findings.some((f) => f.level === "error") ? 1 : 0;
336
350
  }
351
+ case "approvals": {
352
+ const sub = rest[0];
353
+ const listing = sub === "list";
354
+ const id = listing ? undefined : rest[1];
355
+ const { values } = parseArgs({ args: rest.slice(listing ? 1 : 2), options: { config: { type: "string" }, key: { type: "string" }, expires: { type: "string", default: "10m" }, reason: { type: "string" }, all: { type: "boolean", default: false }, json: { type: "boolean", default: false } } });
356
+ if (!values.config)
357
+ throw new Error("approvals needs --config: the gateway config whose approvals.requests.dir holds the requests");
358
+ const cfg = loadConfig(values.config);
359
+ const dir = cfg.approvals?.requests?.dir;
360
+ if (!dir)
361
+ throw new Error(`approvals needs approvals.requests.dir in ${values.config}`);
362
+ if (listing) {
363
+ const all = listApprovalRequests(dir).filter((r) => values.all || r.status === "pending");
364
+ if (values.json)
365
+ console.log(JSON.stringify(all, null, 2));
366
+ else if (!all.length)
367
+ console.log("no approval requests waiting");
368
+ else
369
+ for (const r of all)
370
+ console.log(`${r.requestId} ${r.status.padEnd(8)} ${r.createdAt} ${r.binding.agent} → ${r.binding.tool} for ${r.binding.principal}${r.requiredApprovers === 2 ? ` (two approvers, ${new Set(r.envelope?.signatures.map((x) => x.keyid) ?? []).size} signed)` : ""}`);
371
+ return 0;
372
+ }
373
+ if (!id)
374
+ throw new Error(`approvals ${sub ?? ""} needs a request id`);
375
+ if (sub === "show") {
376
+ const r = readApprovalRequest(dir, id);
377
+ if (!r)
378
+ throw new Error(`no approval request ${id} in ${dir}`);
379
+ console.log(JSON.stringify(values.json ? r : { requestId: r.requestId, status: r.status, createdAt: r.createdAt, principal: r.binding.principal, agent: r.binding.agent, tool: r.binding.tool, arguments: r.binding.args, ...(r.binding.fields ? { fields: r.binding.fields } : {}), requiredApprovers: r.requiredApprovers, signedBy: r.envelope?.signatures.map((x) => x.keyid) ?? [], ...(r.reason ? { reason: r.reason } : {}) }, null, 2));
380
+ return 0;
381
+ }
382
+ if (sub === "approve") {
383
+ if (!values.key)
384
+ throw new Error("approvals approve needs --key: the approver's private key");
385
+ const max = cfg.approvals?.maxLifetimeSeconds ?? DEFAULT_APPROVAL_LIFETIME_SECONDS;
386
+ const seconds = durationSeconds(values.expires);
387
+ if (seconds > max)
388
+ throw new Error(`--expires ${values.expires} is longer than the gateway accepts (approvals.maxLifetimeSeconds ${max})`);
389
+ const r = approveApprovalRequest(dir, id, loadPrivateKey(values.key), { expiresAt: new Date(Date.now() + seconds * 1000).toISOString(), trusted: cfg.approvals.trustedKeys.map(loadPublicKey), maxLifetimeSeconds: max });
390
+ const until = approvalRequestExpiresAt(r);
391
+ console.log(r.status === "approved" ? `approved ${id}: ${r.binding.agent} may send ${r.binding.tool} with exactly these arguments, once, until ${until}` : `signed ${id}, valid until ${until}: it needs a second approver with a different key`);
392
+ return 0;
393
+ }
394
+ if (sub === "deny") {
395
+ denyApprovalRequest(dir, id, values.reason ? { reason: values.reason } : {});
396
+ console.log(`denied ${id}: the gateway refuses that exact call, and says so, until the request is deleted`);
397
+ return 0;
398
+ }
399
+ throw new Error("approvals takes list, show <id>, approve <id> --key <file>, or deny <id> [--reason <text>]");
400
+ }
337
401
  case "revoke": {
338
402
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, grant: { type: "string" } } });
339
403
  if (!values.config || !values.grant)
@@ -1035,6 +1099,7 @@ async function main(argv) {
1035
1099
  since: { type: "string" },
1036
1100
  until: { type: "string" },
1037
1101
  "id-path": { type: "string" },
1102
+ "receipt-id-path": { type: "string" },
1038
1103
  "amount-field": { type: "string" },
1039
1104
  "currency-field": { type: "string" },
1040
1105
  beneficiary: { type: "string", multiple: true },
@@ -1080,6 +1145,7 @@ async function main(argv) {
1080
1145
  sinceMs,
1081
1146
  untilMs,
1082
1147
  ...(values["id-path"] ? { idPath: values["id-path"] } : {}),
1148
+ ...(values["receipt-id-path"] ? { receiptIdPath: values["receipt-id-path"] } : {}),
1083
1149
  ...(values["amount-field"] ? { amountField: values["amount-field"] } : {}),
1084
1150
  ...(values["currency-field"] ? { currencyField: values["currency-field"] } : {}),
1085
1151
  ...(Object.keys(beneficiary).length ? { beneficiary } : {}),
@@ -1,3 +1,4 @@
1
+ import type { IssuerKind } from "./receipt.ts";
1
2
  import { type VerifyOptions } from "./verify.ts";
2
3
  /** One provider object, reduced to what the comparison reads. */
3
4
  export interface ProviderObject {
@@ -52,7 +53,13 @@ export interface CompletenessOptions {
52
53
  untilMs: number;
53
54
  /** where the provider's object id sits in the JSON of the result's first text item; default "id" */
54
55
  idPath?: string;
55
- /** the call argument that holds the amount in minor units; default "amount" */
56
+ /**
57
+ * where a provider object carries the id of the door receipt that relayed its request; default
58
+ * "metadata.agent_custody_receipt". A door receipt matches only by this field, only when the origin answered 2xx,
59
+ * and only an object created within `marginMs` of the receipt.
60
+ */
61
+ receiptIdPath?: string;
62
+ /** the call argument that holds the amount in minor units; default "amount". For a door receipt, a field of the JSON body */
56
63
  amountField?: string;
57
64
  /** the call argument that holds the currency; default "currency", compared case-insensitively when both sides have one */
58
65
  currencyField?: string;
@@ -72,9 +79,11 @@ export interface CompletenessReport {
72
79
  until: string;
73
80
  };
74
81
  receiptsRead: number;
82
+ /** `kind` is the issuer kind of the receipt: `gateway` matched by the provider id, `door` by the receipt id the object carries */
75
83
  matched: {
76
84
  receiptId: string;
77
85
  providerId: string;
86
+ kind: IssuerKind;
78
87
  }[];
79
88
  /** provider objects in the window with no verified receipt: actions taken outside the gateway */
80
89
  providerOnly: {
@@ -84,7 +93,7 @@ export interface CompletenessReport {
84
93
  currency?: string;
85
94
  repeated?: true;
86
95
  }[];
87
- /** executed receipts in the window whose provider object the provider does not have */
96
+ /** executed receipts in the window whose provider object the provider does not have; never a door receipt, which names no provider object */
88
97
  receiptOnly: {
89
98
  receiptId: string;
90
99
  providerId: string;
@@ -2,7 +2,9 @@
2
2
  // can see an action that never did. An auditor with a read-only key of their own lists the provider's objects over a
3
3
  // window and matches each one to a verified receipt by the provider's object id, which the receipt's result carries.
4
4
  // A provider object with no receipt is an action taken outside the gateway; a receipt with no provider object is an
5
- // action the provider does not have. Nothing here writes, retries, or calls the provider for anything but a list.
5
+ // action the provider does not have. A door receipt records the origin's answer by digest only, so it carries no
6
+ // provider id: it is matched by its own receipt id, which the origin copies from the door's receipt header into the
7
+ // provider object. Nothing here writes, retries, or calls the provider for anything but a list.
6
8
  import { readdirSync, readFileSync } from "node:fs";
7
9
  import { join } from "node:path";
8
10
  import { isCommitment, REST } from "./capture.js";
@@ -146,8 +148,18 @@ function argOf(args, field) {
146
148
  return isCommitment(args[field]) ? { withheld: true } : { value: args[field] };
147
149
  return isCommitment(args[REST]) ? { withheld: true } : { value: undefined };
148
150
  }
151
+ /** A door receipt's arguments are the HTTP request: the call's own arguments are the JSON body, or withheld with it. */
152
+ function doorArgs(args) {
153
+ if (!Object.hasOwn(args, "body"))
154
+ return isCommitment(args[REST]) ? { [REST]: args[REST] } : {};
155
+ const body = args.body;
156
+ if (isCommitment(body))
157
+ return { [REST]: body };
158
+ return body && typeof body === "object" && !Array.isArray(body) ? body : {};
159
+ }
149
160
  export async function checkCompleteness(o) {
150
161
  const idPath = o.idPath ?? "id";
162
+ const receiptIdPath = o.receiptIdPath ?? "metadata.agent_custody_receipt";
151
163
  const amountField = o.amountField ?? "amount";
152
164
  const currencyField = o.currencyField ?? "currency";
153
165
  const margin = o.marginMs ?? 15 * 60_000;
@@ -171,6 +183,7 @@ export async function checkCompleteness(o) {
171
183
  const names = readdirSync(o.receiptsDir, { withFileTypes: true }).filter((e) => (e.isFile() || e.isSymbolicLink()) && e.name.endsWith(".json")).map((e) => e.name).sort();
172
184
  const outcomes = new Set();
173
185
  const byProviderId = new Map();
186
+ const doorReceipts = new Map();
174
187
  for (const name of names) {
175
188
  if (name.endsWith(AUTHORIZATION))
176
189
  continue;
@@ -196,6 +209,13 @@ export async function checkCompleteness(o) {
196
209
  outcomes.add(p.receiptId);
197
210
  if (!tools.has(p.tool.name) || p.reconciliation || p.execution.status !== "executed")
198
211
  continue;
212
+ if (p.issuer.kind === "door") {
213
+ // the door records any origin answer below 500 as executed; only a 2xx can have made the object
214
+ const status = p.execution.result?.status;
215
+ if (typeof status === "number" && status >= 200 && status < 300)
216
+ doorReceipts.set(p.receiptId, p);
217
+ continue;
218
+ }
199
219
  const id = providerIdOf(p, idPath);
200
220
  if ("reason" in id) {
201
221
  if (inWindow(Date.parse(p.timestamp)))
@@ -223,24 +243,34 @@ export async function checkCompleteness(o) {
223
243
  report.forwardedWithoutOutcome.push({ receiptId: auth.receiptId, tool: auth.tool.name });
224
244
  }
225
245
  const seen = new Set();
246
+ const claimed = new Set();
226
247
  for await (const obj of o.source.list(o.sinceMs - margin, o.untilMs + margin)) {
227
- // a second object with an id already listed is another action: the receipts for that id account for the first one
248
+ // a second object with an id already listed, or naming a door receipt already claimed, is another action: the
249
+ // receipt accounts for the first one
228
250
  const repeated = seen.has(obj.id);
229
251
  seen.add(obj.id);
230
- const receipts = byProviderId.get(obj.id) ?? [];
252
+ const tag = at(obj.raw, receiptIdPath);
253
+ const tagged = typeof tag === "string" ? doorReceipts.get(tag) : undefined;
254
+ // the object is made while the door relays: a receipt from another time cannot account for it
255
+ const door = tagged && Math.abs(obj.createdMs - Date.parse(tagged.timestamp)) <= margin ? tagged : undefined;
256
+ const doorRepeated = !!door && claimed.has(door.receiptId);
257
+ if (door)
258
+ claimed.add(door.receiptId);
259
+ const named = [...(byProviderId.get(obj.id) ?? []), ...(door ? [door] : [])];
260
+ const receipts = [...(repeated ? [] : byProviderId.get(obj.id) ?? []), ...(door && !doorRepeated ? [door] : [])];
231
261
  // the margin finds a receipt across the window's edge; it does not widen the period reported on
232
- const inScope = inWindow(obj.createdMs) || receipts.some((p) => inWindow(Date.parse(p.timestamp)));
262
+ const inScope = inWindow(obj.createdMs) || named.some((p) => inWindow(Date.parse(p.timestamp)));
233
263
  if (!inScope)
234
264
  continue;
235
- if (!receipts.length || repeated) {
236
- report.providerOnly.push({ providerId: obj.id, created: iso(obj.createdMs), ...(obj.amount !== undefined ? { amount: obj.amount } : {}), ...(obj.currency !== undefined ? { currency: obj.currency } : {}), ...(repeated && receipts.length ? { repeated: true } : {}) });
265
+ if (!receipts.length) {
266
+ report.providerOnly.push({ providerId: obj.id, created: iso(obj.createdMs), ...(obj.amount !== undefined ? { amount: obj.amount } : {}), ...(obj.currency !== undefined ? { currency: obj.currency } : {}), ...(named.length ? { repeated: true } : {}) });
237
267
  continue;
238
268
  }
239
269
  if (receipts.length > 1)
240
270
  report.duplicates.push({ providerId: obj.id, receiptIds: receipts.map((p) => p.receiptId) });
241
271
  for (const p of receipts) {
242
- report.matched.push({ receiptId: p.receiptId, providerId: obj.id });
243
- const args = p.request.args;
272
+ report.matched.push({ receiptId: p.receiptId, providerId: obj.id, kind: p.issuer.kind });
273
+ const args = p.issuer.kind === "door" ? doorArgs(p.request.args) : p.request.args;
244
274
  const withheld = (arg) => report.unmatchable.push({ receiptId: p.receiptId, reason: `the argument "${arg}" is withheld under a capture rule, so it cannot be compared` });
245
275
  const amount = argOf(args, amountField);
246
276
  if ("withheld" in amount) {
@@ -279,8 +309,14 @@ export async function checkCompleteness(o) {
279
309
  report.complete = [report.providerOnly, report.receiptOnly, report.mismatches, report.duplicates, report.unverified, report.unmatchable, report.forwardedWithoutOutcome].every((l) => l.length === 0);
280
310
  return report;
281
311
  }
312
+ function matchedByKind(r) {
313
+ const counts = new Map();
314
+ for (const m of r.matched)
315
+ counts.set(m.kind, (counts.get(m.kind) ?? 0) + 1);
316
+ return counts.size ? ` (${[...counts].map(([k, n]) => `${n} ${k}`).join(", ")})` : "";
317
+ }
282
318
  export function formatCompleteness(r) {
283
- const lines = [`${r.provider} for ${r.tools.join(", ")}, ${r.window.since} to ${r.window.until}: ${r.receiptsRead} receipt(s) read, ${r.matched.length} matched`];
319
+ const lines = [`${r.provider} for ${r.tools.join(", ")}, ${r.window.since} to ${r.window.until}: ${r.receiptsRead} receipt(s) read, ${r.matched.length} matched${matchedByKind(r)}`];
284
320
  const section = (title, rows) => {
285
321
  if (rows.length)
286
322
  lines.push("", `${title} (${rows.length})`, ...rows.map((row) => ` ${row}`));
package/dist/config.d.ts CHANGED
@@ -275,6 +275,9 @@ export declare const GatewayConfigSchema: z.ZodObject<{
275
275
  trustedKeys: z.ZodArray<z.ZodString>;
276
276
  usedDir: z.ZodString;
277
277
  maxLifetimeSeconds: z.ZodOptional<z.ZodNumber>;
278
+ requests: z.ZodOptional<z.ZodObject<{
279
+ dir: z.ZodString;
280
+ }, z.core.$strip>>;
278
281
  tools: z.ZodArray<z.ZodObject<{
279
282
  tool: z.ZodString;
280
283
  minApprovers: z.ZodDefault<z.ZodUnion<readonly [z.ZodLiteral<1>, z.ZodLiteral<2>]>>;
package/dist/config.js CHANGED
@@ -74,6 +74,11 @@ const ApprovalsSchema = z.object({
74
74
  usedDir: z.string().min(1),
75
75
  /** The longest lifetime (expiresAt minus issuedAt) that the gateway accepts. The signer chooses the expiry, and this caps it. Default: 3600. */
76
76
  maxLifetimeSeconds: z.number().int().positive().optional(),
77
+ /**
78
+ * Human in the loop: a protected call that arrives without an approval also leaves a request in `dir`, which an approver
79
+ * signs with `agent-custody approvals approve`; the same call sent again then takes the signed envelope from it.
80
+ */
81
+ requests: z.object({ dir: z.string().min(1) }).optional(),
77
82
  tools: z.array(z.object({
78
83
  tool: z.string().min(1),
79
84
  minApprovers: z.union([z.literal(1), z.literal(2)]).default(1),
@@ -223,7 +228,7 @@ export function loadConfig(path) {
223
228
  ...(cfg.logFile ? { logFile: r(cfg.logFile) } : {}),
224
229
  ...(cfg.log?.keys ? { log: { ...cfg.log, keys: cfg.log.keys.map(r) } } : {}),
225
230
  ...(cfg.revokedGrants ? { revokedGrants: r(cfg.revokedGrants) } : {}),
226
- ...(cfg.approvals ? { approvals: { ...cfg.approvals, trustedKeys: cfg.approvals.trustedKeys.map(r), usedDir: r(cfg.approvals.usedDir) } } : {}),
231
+ ...(cfg.approvals ? { approvals: { ...cfg.approvals, trustedKeys: cfg.approvals.trustedKeys.map(r), usedDir: r(cfg.approvals.usedDir), ...(cfg.approvals.requests ? { requests: { dir: r(cfg.approvals.requests.dir) } } : {}) } } : {}),
227
232
  ...(cfg.operations ? { operations: { ...cfg.operations, database: r(cfg.operations.database) } } : {}),
228
233
  };
229
234
  }
@@ -34,6 +34,7 @@ textarea { width: 100%; min-height: 280px; background: var(--code); color: var(-
34
34
  [hidden] { display: none !important; }
35
35
  .mt { margin-top: 16px; }
36
36
  textarea.short { min-height: 140px; }
37
+ pre.args { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 360px; overflow: auto; }
37
38
  dialog { background: var(--panel); color: var(--ink); border: 1px solid var(--line); border-radius: 8px; padding: 16px; max-width: min(480px, calc(100vw - 32px)); }
38
39
  dialog::backdrop { background: rgba(0, 0, 0, .5); }
39
40
  dialog h3 { margin: 0 0 8px; }
@@ -56,7 +57,7 @@ const SCRIPT = String.raw `
56
57
  var token = '';
57
58
  try { token = sessionStorage.getItem(KEY) || ''; } catch (e) {}
58
59
  var view = document.getElementById('view');
59
- var tabs = ['Overview', 'Check', 'Policy', 'Grants', 'Receipts', 'Audit'];
60
+ var tabs = ['Overview', 'Check', 'Policy', 'Grants', 'Approvals', 'Receipts', 'Audit'];
60
61
  var current = 'Overview';
61
62
  var policyDigest = '';
62
63
  var dirty = false;
@@ -95,6 +96,29 @@ const SCRIPT = String.raw `
95
96
  });
96
97
  }
97
98
  function fail(e) { say(e.message || String(e), true); }
99
+ function b64bytes(s) { var bin = atob(s); var u = new Uint8Array(bin.length); for (var i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i); return u; }
100
+ function bytes64(buf) { var u = new Uint8Array(buf); var s = ''; for (var i = 0; i < u.length; i++) s += String.fromCharCode(u[i]); return btoa(s); }
101
+ function hexOf(buf) { return Array.prototype.map.call(new Uint8Array(buf), function (b) { return ('0' + b.toString(16)).slice(-2); }).join(''); }
102
+ // Sign the DSSE bytes with an Ed25519 PKCS8 key from a file the approver picks. The key stays in this page; the keyid is
103
+ // the gateway's own: sha256 of the public key's SPKI DER.
104
+ function signWith(file, paeB64) {
105
+ var key;
106
+ return file.text().then(function (pem) {
107
+ var m = /-----BEGIN PRIVATE KEY-----([\s\S]+?)-----END PRIVATE KEY-----/.exec(pem);
108
+ if (!m) throw new Error('That is not a private key. Choose the .key file agent-custody keygen wrote for you.');
109
+ return crypto.subtle.importKey('pkcs8', b64bytes(m[1].replace(/\s+/g, '')), { name: 'Ed25519' }, true, ['sign']);
110
+ }).then(function (k) {
111
+ key = k;
112
+ return crypto.subtle.exportKey('jwk', k);
113
+ }).then(function (jwk) {
114
+ var x = jwk.x.replace(/-/g, '+').replace(/_/g, '/');
115
+ while (x.length % 4) x += '=';
116
+ var spki = new Uint8Array(44);
117
+ spki.set([0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00]);
118
+ spki.set(b64bytes(x), 12);
119
+ return Promise.all([crypto.subtle.digest('SHA-256', spki), crypto.subtle.sign({ name: 'Ed25519' }, key, b64bytes(paeB64))]);
120
+ }).then(function (r) { return { keyid: hexOf(r[0]), sig: bytes64(r[1]) }; });
121
+ }
98
122
  function signOut() {
99
123
  token = '';
100
124
  try { sessionStorage.removeItem(KEY); } catch (e) {}
@@ -154,7 +178,7 @@ const SCRIPT = String.raw `
154
178
  });
155
179
  }
156
180
 
157
- var ACTIONS = { 'policy.save': 'Policy saved', 'grant.revoke': 'Grant revoked' };
181
+ var ACTIONS = { 'policy.save': 'Policy saved', 'grant.revoke': 'Grant revoked', 'approval.sign': 'Approval signed', 'approval.deny': 'Approval denied' };
158
182
  function historyTable(files) {
159
183
  var t = h('table', null, h('tr', null, h('th', { text: 'saved' }), h('th', { text: 'digest' })));
160
184
  files.forEach(function (f) {
@@ -350,6 +374,67 @@ const SCRIPT = String.raw `
350
374
  });
351
375
  },
352
376
 
377
+ Approvals: function () {
378
+ return api('GET', '/api/approvals').then(function (a) {
379
+ var title = h('h2', { text: 'Approvals' });
380
+ if (!a.configured) return h('div', null, title, h('p', { class: 'muted', text: 'Approval requests are off. With approvals.requests.dir in the gateway config, a protected call that arrives with no approval leaves a request here for a person to read and sign.' }));
381
+ var detail = h('div');
382
+ var pending = a.requests.filter(function (r) { return r.status === 'pending'; });
383
+ var t = h('table', null, h('tr', null, h('th', { text: 'asked' }), h('th', { text: 'agent' }), h('th', { text: 'tool' }), h('th', { text: 'for' }), h('th', { text: 'status' }), h('th', { text: '' })));
384
+ a.requests.forEach(function (r) {
385
+ var st = r.status === 'pending' && r.requiredApprovers === 2 ? 'pending, ' + r.signedBy.length + ' of 2 signed' : r.status;
386
+ t.appendChild(h('tr', null, h('td', null, when(r.createdAt)), h('td', { text: r.agent }), h('td', null, h('code', { text: r.tool })), h('td', { text: r.principal }),
387
+ h('td', null, h('span', { class: 'pill', text: st })), h('td', null, h('button', { type: 'button', class: 'link', onclick: function () { open(r); } }, r.status === 'pending' ? 'Review' : 'View'))));
388
+ });
389
+ function open(r) {
390
+ var head = h('h3', { tabindex: '-1', text: (r.status === 'pending' ? 'Review ' : 'Request ') + r.requestId });
391
+ var rows = [['agent', r.agent], ['tool', h('code', { text: r.tool })], ['principal', r.principal], ['asked', when(r.createdAt)], ['refused call', h('code', { text: r.receiptId })],
392
+ ['approvers needed', String(r.requiredApprovers)], ['signed by', r.signedBy.length ? r.signedBy.map(short).join(', ') : 'nobody yet'], ['status', r.status + (r.reason ? ': ' + r.reason : '')]];
393
+ var card = h('div', { class: 'card detail' }, head, kv(rows), h('p', { text: 'The exact arguments. An approval covers these and nothing else: a changed value is a new request.' }),
394
+ h('pre', { class: 'args', text: JSON.stringify(r.arguments, null, 2) }));
395
+ if (r.status === 'pending') {
396
+ var choices = [[300, '5 minutes'], [600, '10 minutes'], [900, '15 minutes'], [1800, '30 minutes'], [3600, '1 hour']].filter(function (c) { return c[0] <= a.maxLifetimeSeconds; });
397
+ if (!choices.length) choices = [[a.maxLifetimeSeconds, a.maxLifetimeSeconds + ' seconds']];
398
+ var expires = h('select', { 'aria-label': 'Valid for' });
399
+ choices.forEach(function (c, i) { expires.appendChild(h('option', { value: String(c[0]), selected: i === Math.min(1, choices.length - 1) }, c[1])); });
400
+ var file = h('input', { type: 'file', accept: '.key,.pem', 'aria-label': 'Approver key file' });
401
+ var reason = h('input', { type: 'text', 'aria-label': 'Reason for denying', placeholder: 'Reason (optional)', maxlength: '1000' });
402
+ var status = h('span', { role: 'status', class: 'inline' });
403
+ var note = function (text, bad) { status.textContent = text; status.className = bad ? 'bad inline' : 'inline'; };
404
+ var approve = function () {
405
+ var f = file.files && file.files[0];
406
+ if (!f) return note('Choose your approver key file first. It is read in this browser to sign, and never sent.', true);
407
+ if (!window.crypto || !crypto.subtle) return note('This page cannot sign: the browser only offers signing on https or on localhost.', true);
408
+ note('Signing…');
409
+ var prepared;
410
+ api('POST', '/api/approvals/prepare', { requestId: r.requestId, expiresInSeconds: Number(expires.value) })
411
+ .then(function (p) { prepared = p; return signWith(f, p.pae); })
412
+ .then(function (s) { return api('POST', '/api/approvals/sign', { requestId: r.requestId, payload: prepared.payload, keyid: s.keyid, sig: s.sig }); })
413
+ .then(function (res) { file.value = ''; show('Approvals'); say(res.note); })
414
+ .catch(function (e) { note(e.message || String(e), true); });
415
+ };
416
+ var deny = function () {
417
+ ask('Deny this request?', ['The gateway will keep refusing this exact call, and tell the agent so, until the request is deleted.'], 'Deny', true).then(function (yes) {
418
+ if (!yes) return;
419
+ api('POST', '/api/approvals/deny', { requestId: r.requestId, reason: reason.value }).then(function (res) { show('Approvals'); say(res.note); }).catch(fail);
420
+ });
421
+ };
422
+ card.appendChild(h('div', { class: 'card' }, h('h3', { text: r.signedBy.length ? 'Countersign' : 'Approve' }),
423
+ h('p', { class: 'muted', text: 'Your key is read by this browser to sign the call, and only the signature is sent. The key must be one of the gateway\'s trusted approver keys' + (r.signedBy.length ? ', and not the one that already signed.' : '.') }),
424
+ h('div', { class: 'row' }, h('label', null, 'Key file ', file), h('label', null, 'Valid for ', expires),
425
+ h('button', { type: 'button', class: 'primary', onclick: approve }, r.signedBy.length ? 'Countersign' : 'Sign and approve'), status),
426
+ h('div', { class: 'row mt' }, reason, h('button', { type: 'button', class: 'secondary', onclick: deny }, 'Deny'))));
427
+ }
428
+ card.appendChild(h('div', { class: 'row' }, h('button', { type: 'button', class: 'secondary', onclick: function () { clear(detail); } }, 'Close')));
429
+ clear(detail).appendChild(card);
430
+ head.focus();
431
+ }
432
+ return h('div', null, title,
433
+ h('p', { class: 'muted', text: pending.length + ' waiting for a person. A protected call that came with no approval waits here; once it is approved, the agent sends the same call again and it goes through once.' }),
434
+ h('div', { class: 'card scroll' }, a.requests.length ? t : h('p', { class: 'muted', text: 'No requests yet.' })), detail);
435
+ });
436
+ },
437
+
353
438
  Audit: function () {
354
439
  return api('GET', '/api/audit').then(function (a) {
355
440
  var t = h('table', null, h('tr', null, h('th', { text: 'when' }), h('th', { text: 'by' }), h('th', { text: 'action' }), h('th', { text: 'detail' })));
package/dist/console.js CHANGED
@@ -8,6 +8,8 @@ import { createHash, timingSafeEqual } from "node:crypto";
8
8
  import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
9
9
  import { createServer } from "node:http";
10
10
  import { basename, dirname, join } from "node:path";
11
+ import { DEFAULT_APPROVAL_LIFETIME_SECONDS } from "./approval.js";
12
+ import { approvalRequestPayload, denyApprovalRequest, listApprovalRequests, signApprovalRequest } from "./approval-requests.js";
11
13
  import { checkConfig } from "./check.js";
12
14
  import { loadConfig } from "./config.js";
13
15
  import { loadPrivateKey, loadPublicKey } from "./crypto.js";
@@ -425,6 +427,54 @@ export async function serveConsole(options) {
425
427
  audit("grant.revoke", { agent: decoded.agent, principal: decoded.principal, digest, already: list.includes(digest) }, by);
426
428
  return { digest, agent: decoded.agent, note: "the gateway refuses this grant, and every grant delegated from it, on its next call" };
427
429
  },
430
+ "GET /api/approvals": async () => {
431
+ const cfg = loadConfig(options.configFile);
432
+ const dir = cfg.approvals?.requests?.dir;
433
+ if (!dir)
434
+ return { configured: false };
435
+ const all = listApprovalRequests(dir);
436
+ const shown = [...all.filter((r) => r.status === "pending"), ...all.filter((r) => r.status !== "pending").reverse().slice(0, 50)];
437
+ return {
438
+ configured: true,
439
+ maxLifetimeSeconds: cfg.approvals.maxLifetimeSeconds ?? DEFAULT_APPROVAL_LIFETIME_SECONDS,
440
+ trustedKeyids: approverKeys(cfg).map((k) => k.keyid),
441
+ requests: shown.map((r) => ({
442
+ requestId: r.requestId, status: r.status, createdAt: r.createdAt, decidedAt: r.decidedAt ?? null, receiptId: r.receiptId,
443
+ principal: r.binding.principal, agent: r.binding.agent, tool: r.binding.tool, arguments: r.binding.args, fields: r.binding.fields ?? null,
444
+ requiredApprovers: r.requiredApprovers, signedBy: r.envelope?.signatures.map((s) => s.keyid) ?? [], reason: r.reason ?? null,
445
+ })),
446
+ };
447
+ },
448
+ // The console signs nothing: the browser signs these bytes with the approver's key, which never reaches the server.
449
+ "POST /api/approvals/prepare": async (req) => {
450
+ const body = object(await readBody(req));
451
+ const { dir, cfg } = requestsDir();
452
+ const max = cfg.approvals.maxLifetimeSeconds ?? DEFAULT_APPROVAL_LIFETIME_SECONDS;
453
+ const seconds = body.expiresInSeconds;
454
+ if (typeof seconds !== "number" || !Number.isInteger(seconds) || seconds <= 0 || seconds > max)
455
+ throw new HttpError(400, `expiresInSeconds is a whole number of seconds from 1 to ${max}, the gateway's approvals.maxLifetimeSeconds`);
456
+ return decided(() => approvalRequestPayload(dir, requestIdOf(body), { expiresAt: new Date(Date.now() + seconds * 1000).toISOString() }));
457
+ },
458
+ "POST /api/approvals/sign": async (req, _url, by) => {
459
+ const body = object(await readBody(req));
460
+ const { dir, cfg } = requestsDir();
461
+ const requestId = requestIdOf(body);
462
+ for (const f of ["payload", "keyid", "sig"])
463
+ if (typeof body[f] !== "string" || !body[f])
464
+ throw new HttpError(400, `send ${f} as a string`);
465
+ const r = decided(() => signApprovalRequest(dir, requestId, { payload: body.payload, keyid: body.keyid, sig: body.sig }, approverKeys(cfg), { maxLifetimeSeconds: cfg.approvals.maxLifetimeSeconds ?? DEFAULT_APPROVAL_LIFETIME_SECONDS }));
466
+ audit("approval.sign", { requestId, agent: r.binding.agent, tool: r.binding.tool, keyid: body.keyid, status: r.status }, by);
467
+ return { status: r.status, note: r.status === "approved" ? `Approved. ${r.binding.agent} may send ${r.binding.tool} with exactly these arguments, once.` : "Signed. It needs a second approver with a different key." };
468
+ },
469
+ "POST /api/approvals/deny": async (req, _url, by) => {
470
+ const body = object(await readBody(req));
471
+ const { dir } = requestsDir();
472
+ const requestId = requestIdOf(body);
473
+ const reason = typeof body.reason === "string" && body.reason.trim() ? body.reason.trim() : undefined;
474
+ const r = decided(() => denyApprovalRequest(dir, requestId, reason ? { reason } : {}));
475
+ audit("approval.deny", { requestId, agent: r.binding.agent, tool: r.binding.tool, ...(reason ? { reason } : {}) }, by);
476
+ return { status: r.status, note: "Denied. The gateway refuses that exact call, and tells the agent so, until the request is deleted." };
477
+ },
428
478
  "GET /api/revocations": async () => ({ digests: revokedList(loadConfig(options.configFile)) }),
429
479
  "GET /api/receipts": async (_req, url) => {
430
480
  const cfg = loadConfig(options.configFile);
@@ -437,6 +487,28 @@ export async function serveConsole(options) {
437
487
  entries: existsSync(auditFile) ? readFileSync(auditFile, "utf8").trim().split("\n").filter(Boolean).slice(-200).reverse().map((l) => JSON.parse(l)) : [],
438
488
  }),
439
489
  };
490
+ const approverKeys = (cfg) => (cfg.approvals?.trustedKeys ?? []).map(loadPublicKey);
491
+ const requestsDir = () => {
492
+ const cfg = loadConfig(options.configFile);
493
+ const dir = cfg.approvals?.requests?.dir;
494
+ if (!dir)
495
+ throw new HttpError(409, "the config has no approvals.requests.dir, which is where the gateway leaves approval requests");
496
+ return { dir, cfg };
497
+ };
498
+ const requestIdOf = (body) => {
499
+ if (typeof body.requestId !== "string" || !/^[0-9a-f]{32}$/.test(body.requestId))
500
+ throw new HttpError(400, "a request id is 32 hex characters");
501
+ return body.requestId;
502
+ };
503
+ // a request that is gone, already decided, or a signature that does not verify is the caller's conflict, not a crash
504
+ const decided = (f) => {
505
+ try {
506
+ return f();
507
+ }
508
+ catch (e) {
509
+ throw new HttpError(409, e instanceof Error ? e.message : String(e));
510
+ }
511
+ };
440
512
  const safeJson = (s) => {
441
513
  try {
442
514
  return JSON.parse(s);
package/dist/crypto.d.ts CHANGED
@@ -33,6 +33,8 @@ export interface Envelope {
33
33
  sig: string;
34
34
  }[];
35
35
  }
36
+ /** The DSSE pre-authentication encoding: the bytes a DSSE signature is made over. */
37
+ export declare function pae(payloadType: string, payload: Buffer): Buffer;
36
38
  export declare function dsseSign(payloadType: string, payloadObj: unknown, kp: KeyPair): Envelope;
37
39
  /** Adds a signature over the same payload: a countersignature, the DSSE way. The envelope keeps every earlier signature. */
38
40
  export declare function dsseCountersign(env: Envelope, kp: KeyPair): Envelope;
package/dist/crypto.js CHANGED
@@ -64,7 +64,8 @@ export function publicKeyFromPem(pem) {
64
64
  const publicKey = createPublicKey(pem);
65
65
  return { publicKey, keyid: keyidOf(publicKey) };
66
66
  }
67
- function pae(payloadType, payload) {
67
+ /** The DSSE pre-authentication encoding: the bytes a DSSE signature is made over. */
68
+ export function pae(payloadType, payload) {
68
69
  const header = `DSSEv1 ${Buffer.byteLength(payloadType)} ${payloadType} ${payload.length} `;
69
70
  return Buffer.concat([Buffer.from(header), payload]);
70
71
  }
@@ -52,7 +52,7 @@ export type DelegationVerifyResult = {
52
52
  error: string;
53
53
  };
54
54
  /** Verifies a grant, walking its chain to a grant signed by one of the trusted principal keys. */
55
- export declare function verifyDelegation(env: Envelope, trustedPrincipals: PublicKeyRef[], depth?: number): DelegationVerifyResult;
55
+ export declare function verifyDelegation(env: Envelope, trustedPrincipals: PublicKeyRef[]): DelegationVerifyResult;
56
56
  /** True when `at` (ISO) lies inside the grant's validity window. */
57
57
  /**
58
58
  * What names a grant for revocation: sha256 over the payload its signature covers. Extra signatures or envelope fields
@@ -6,6 +6,7 @@
6
6
  // parent's, and the principal is the same throughout. The receipt then names the sub-agent as the agent and the
7
7
  // principal as the principal, exactly as with a direct grant, and the whole chain travels inside the receipt.
8
8
  import { z } from "zod";
9
+ import { DID_KEY_PREFIX, didKeyAgentFault } from "./did-key.js";
9
10
  import { dsseSign, dsseVerify, publicKeyFromPem, sha256Hex } from "./crypto.js";
10
11
  export const DELEGATION_TYPE = "application/vnd.agent-custody.delegation+json";
11
12
  /** the longest chain a verifier walks: the principal's grant and up to three delegations below it */
@@ -68,7 +69,23 @@ export function delegateFrom(parent, agentKey, sub) {
68
69
  return createDelegation(agentKey, { version: "0.1", principal: p.principal, agent: sub.agent, scopes: sub.scopes, issuedAt, expiresAt, ...(sub.agentKey ? { agentKey: sub.agentKey } : {}), parent });
69
70
  }
70
71
  /** Verifies a grant, walking its chain to a grant signed by one of the trusted principal keys. */
71
- export function verifyDelegation(env, trustedPrincipals, depth = 1) {
72
+ export function verifyDelegation(env, trustedPrincipals) {
73
+ const checked = verifyChain(env, trustedPrincipals, 1);
74
+ if (!checked.ok)
75
+ return checked;
76
+ // An agent named by a did:key is its key: the identifier must decode to an Ed25519 key, and the grant's agentKey, if
77
+ // it names one, must be that key, or the grant says two things about who the agent is. Every link of a chain, since a
78
+ // parent's agentKey is what verified the link below it.
79
+ for (const [i, link] of checked.chain.entries()) {
80
+ if (!link.agent.startsWith(DID_KEY_PREFIX))
81
+ continue;
82
+ const fault = didKeyAgentFault(link.agent, link.agentKey);
83
+ if (fault)
84
+ return { ok: false, error: (i === checked.chain.length - 1 ? "" : `link ${i} (${link.agent}): `) + fault };
85
+ }
86
+ return checked;
87
+ }
88
+ function verifyChain(env, trustedPrincipals, depth) {
72
89
  if (env.payloadType !== DELEGATION_TYPE)
73
90
  return { ok: false, error: `unexpected payloadType ${env.payloadType}` };
74
91
  if (depth > MAX_DELEGATION_DEPTH)
@@ -85,7 +102,7 @@ export function verifyDelegation(env, trustedPrincipals, depth = 1) {
85
102
  return { ok: false, error: `invalid delegation: ${parsed.error.message}` };
86
103
  return { ok: true, delegation: parsed.data, keyid: r.keyid, chain: [parsed.data] };
87
104
  }
88
- const up = verifyDelegation(unverified.parent, trustedPrincipals, depth + 1);
105
+ const up = verifyChain(unverified.parent, trustedPrincipals, depth + 1);
89
106
  if (!up.ok)
90
107
  return { ok: false, error: `link ${depth}: ${up.error}` };
91
108
  const parent = up.delegation;
package/dist/did-key.d.ts CHANGED
@@ -7,3 +7,5 @@ export declare function base58btcDecode(text: string): Uint8Array;
7
7
  export declare function didKeyOf(publicKey: KeyObject): string;
8
8
  /** The Ed25519 key a did:key names; throws, saying why, when it does not decode to one. */
9
9
  export declare function publicKeyFromDidKey(did: string): PublicKeyRef;
10
+ /** Why a did:key agent does not check out, or null when it decodes and agrees with the grant's agentKey. */
11
+ export declare function didKeyAgentFault(did: string, agentKey: string | undefined): string | null;