@agent-custody/receipts 0.16.9 → 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 (68) hide show
  1. package/README.md +24 -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 +96 -16
  8. package/dist/completeness.d.ts +28 -2
  9. package/dist/completeness.js +102 -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 +11 -0
  19. package/dist/did-key.js +86 -0
  20. package/dist/door-app.d.ts +3 -0
  21. package/dist/door-app.js +10 -0
  22. package/dist/door-core.d.ts +373 -0
  23. package/dist/door-core.js +743 -0
  24. package/dist/door-form.d.ts +6 -0
  25. package/dist/door-form.js +97 -0
  26. package/dist/door-worker.d.ts +133 -0
  27. package/dist/door-worker.js +259 -0
  28. package/dist/door.d.ts +18 -294
  29. package/dist/door.js +62 -722
  30. package/dist/gateway-http.d.ts +1 -6
  31. package/dist/gateway-http.js +2 -19
  32. package/dist/gateway.js +24 -3
  33. package/dist/grant-header.d.ts +8 -0
  34. package/dist/grant-header.js +19 -0
  35. package/dist/index.d.ts +7 -4
  36. package/dist/index.js +5 -2
  37. package/dist/issue.d.ts +2 -16
  38. package/dist/issue.js +2 -12
  39. package/dist/log-http.d.ts +37 -0
  40. package/dist/log-http.js +74 -0
  41. package/dist/log-sink.d.ts +3 -37
  42. package/dist/log-sink.js +5 -71
  43. package/dist/log.d.ts +2 -27
  44. package/dist/log.js +2 -173
  45. package/dist/merkle.d.ts +27 -0
  46. package/dist/merkle.js +175 -0
  47. package/dist/object-issuer.d.ts +29 -0
  48. package/dist/object-issuer.js +172 -0
  49. package/dist/receipt-pending.d.ts +16 -0
  50. package/dist/receipt-pending.js +14 -0
  51. package/dist/web-bot-auth.d.ts +26 -6
  52. package/dist/web-bot-auth.js +116 -56
  53. package/docs/approvals.md +33 -0
  54. package/docs/completeness.md +82 -12
  55. package/docs/console.md +11 -4
  56. package/docs/door-middleware.md +11 -0
  57. package/docs/door-quickstart.md +53 -17
  58. package/docs/door-signals.md +5 -5
  59. package/docs/door-worker.md +81 -0
  60. package/docs/door.md +38 -8
  61. package/docs/github-action.md +2 -2
  62. package/docs/threat-model.md +1 -1
  63. package/docs/tutorials.md +5 -0
  64. package/docs/verification.md +1 -1
  65. package/package.json +3 -1
  66. package/vectors/audit.json +27 -27
  67. package/vectors/canonical.json +5 -5
  68. package/vectors/receipts.json +1645 -1549
package/dist/cli.js CHANGED
@@ -7,7 +7,10 @@ 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";
13
+ import { didKeyOf } from "./did-key.js";
11
14
  import { createGateway, createGatewayHost, serveStdio, writeRevokedGrants } from "./gateway.js";
12
15
  import { postgresResolver, serveLog } from "./log-sink.js";
13
16
  import { importLogFile, PostgresTenancy } from "./log-store.js";
@@ -16,7 +19,7 @@ import { connectSigner, fetchLogKeys, localSigner, serveSigner } from "./signer.
16
19
  import { fetchWitnessKeys, Witness } from "./witness.js";
17
20
  import { checkLog, formatLogCheck } from "./log-check.js";
18
21
  import { Anchor, ANCHOR_CHAINS, resolveAnchorChain } from "./anchor.js";
19
- import { checkCompleteness, formatCompleteness, stripeSource } from "./completeness.js";
22
+ import { checkCompleteness, formatCompleteness, githubSource, stripeSource } from "./completeness.js";
20
23
  import { evmChain } from "./anchor-evm.js";
21
24
  import { serveHttp } from "./gateway-http.js";
22
25
  import { createDoorHost, serveDoor } from "./door.js";
@@ -63,6 +66,13 @@ function untilStopped() {
63
66
  const SERVICES = new Set(["serve", "witness", "signer", "portal", "log", "console", "door", "egress"]);
64
67
  /** a command that waits for untilStopped(); a stdio gateway runs until its input closes and keeps the default signal behaviour */
65
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
+ }
66
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. */
67
77
  function tokenFromFile(path) {
68
78
  const v = readFileSync(path, "utf8").trim();
@@ -81,11 +91,16 @@ const USAGE = `agent-custody <command>
81
91
 
82
92
  keygen --dir <dir> --name <name>
83
93
  grant --key <principal.key> --principal <id> --agent <id> --scopes <a,b> [--ttl-hours 24] [--agent-key <agent.pub>] --out <file>
84
- --agent-key names the agent's own key in the grant, so the agent may delegate
94
+ --agent-key names the agent's own key in the grant, so the agent may delegate;
95
+ --did-key with --agent-key and no --agent names the agent by that key's did:key
85
96
  delegate --key <agent.key> --parent <grant.json> --agent <sub-agent> --scopes <a,b> [--ttl-hours N] [--agent-key <sub.pub>] --out <file>
86
97
  a narrower grant for a sub-agent, signed by the agent the parent names; the parent travels inside
87
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
88
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
89
104
  revoke --config <gateway.json|door.json> --grant <grant.json>
90
105
  revokes a grant: its digest goes into the config's revokedGrants file. At a gateway, every
91
106
  session under it or under a grant delegated from it refuses its next call, and no new session opens for them;
@@ -145,9 +160,11 @@ const USAGE = `agent-custody <command>
145
160
  policy simulate --policy <proposed.cedar|.rego> --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--approval-key <pub>]... [--log-key <pub>]... [--json] [--out <file>]
146
161
  completeness --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--log-key <pub>]... [--log <log.jsonl>] [--log-id <id>]
147
162
  --provider stripe --object refunds|payouts|transfers --key-env NAME --tool <name>... --since <ISO> --until <ISO>
148
- [--id-path id] [--amount-field amount] [--currency-field currency] [--beneficiary <arg>=<field>]... [--json]
163
+ (or --provider github --repo <owner>/<name> --object pushes|merges|releases)
164
+ [--id-path id] [--receipt-id-path metadata.agent_custody_receipt] [--amount-field amount] [--currency-field currency] [--beneficiary <arg>=<field>]... [--json]
149
165
  for an auditor: lists the provider's objects in the window with a read-only key, and
150
- 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
151
168
  receipt, receipts the provider does not have, and mismatched amounts; exits 1 unless complete
152
169
  replay verified local receipts against a proposed policy using their recorded inputs;
153
170
  --out saves the full JSON report. Exits 1 when any call could not be evaluated.
@@ -274,23 +291,27 @@ async function main(argv) {
274
291
  scopes: { type: "string" },
275
292
  "ttl-hours": { type: "string", default: "24" },
276
293
  "agent-key": { type: "string" },
294
+ "did-key": { type: "boolean", default: false },
277
295
  out: { type: "string" },
278
296
  },
279
297
  });
280
- if (!values.key || !values.principal || !values.agent || !values.scopes || !values.out)
281
- throw new Error("grant needs --key --principal --agent --scopes --out");
298
+ if (values["did-key"] && (!values["agent-key"] || values.agent))
299
+ throw new Error("--did-key names the agent by the did:key of --agent-key, so it needs --agent-key and no --agent");
300
+ const agent = values["did-key"] ? didKeyOf(loadPublicKey(values["agent-key"]).publicKey) : values.agent;
301
+ if (!values.key || !values.principal || !agent || !values.scopes || !values.out)
302
+ throw new Error("grant needs --key --principal --agent (or --agent-key with --did-key) --scopes --out");
282
303
  const now = Date.now();
283
304
  const env = createDelegation(loadPrivateKey(values.key), {
284
305
  version: "0.1",
285
306
  principal: values.principal,
286
- agent: values.agent,
307
+ agent,
287
308
  scopes: values.scopes.split(",").map((s) => s.trim()).filter(Boolean),
288
309
  issuedAt: new Date(now).toISOString(),
289
310
  expiresAt: new Date(now + Number(values["ttl-hours"]) * 3600_000).toISOString(),
290
311
  ...(values["agent-key"] ? { agentKey: readFileSync(values["agent-key"], "utf8") } : {}),
291
312
  });
292
313
  writeFileSync(values.out, JSON.stringify(env, null, 2));
293
- console.log(`wrote ${values.out}`);
314
+ console.log(`wrote ${values.out}${values["did-key"] ? ` for ${agent}` : ""}`);
294
315
  return 0;
295
316
  }
296
317
  case "delegate": {
@@ -327,6 +348,56 @@ async function main(argv) {
327
348
  console.log(values.json ? JSON.stringify(findings, null, 2) : formatFindings(findings));
328
349
  return findings.some((f) => f.level === "error") ? 1 : 0;
329
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
+ }
330
401
  case "revoke": {
331
402
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, grant: { type: "string" } } });
332
403
  if (!values.config || !values.grant)
@@ -1021,12 +1092,14 @@ async function main(argv) {
1021
1092
  log: { type: "string" },
1022
1093
  "log-id": { type: "string" },
1023
1094
  provider: { type: "string" },
1024
- object: { type: "string", default: "refunds" },
1095
+ object: { type: "string" },
1096
+ repo: { type: "string" },
1025
1097
  "key-env": { type: "string" },
1026
1098
  tool: { type: "string", multiple: true },
1027
1099
  since: { type: "string" },
1028
1100
  until: { type: "string" },
1029
1101
  "id-path": { type: "string" },
1102
+ "receipt-id-path": { type: "string" },
1030
1103
  "amount-field": { type: "string" },
1031
1104
  "currency-field": { type: "string" },
1032
1105
  beneficiary: { type: "string", multiple: true },
@@ -1034,12 +1107,18 @@ async function main(argv) {
1034
1107
  },
1035
1108
  });
1036
1109
  if (!values.receipts || !values["issuer-key"]?.length || !values["key-env"] || !values.tool?.length || !values.since || !values.until)
1037
- throw new Error("completeness needs --receipts, --issuer-key, --provider stripe, --key-env, --tool, --since and --until");
1038
- if (values.provider !== "stripe")
1039
- throw new Error(`completeness supports --provider stripe; got "${values.provider ?? ""}"`);
1040
- const objects = ["refunds", "payouts", "transfers"];
1041
- if (!objects.includes(values.object))
1042
- throw new Error(`--object is one of ${objects.join(", ")}; got "${values.object}"`);
1110
+ throw new Error("completeness needs --receipts, --issuer-key, --provider, --key-env, --tool, --since and --until");
1111
+ if (values.provider !== "stripe" && values.provider !== "github")
1112
+ throw new Error(`completeness supports --provider stripe or github; got "${values.provider ?? ""}"`);
1113
+ const github = values.provider === "github";
1114
+ if (github && !values.repo)
1115
+ throw new Error("--provider github needs --repo <owner>/<name>");
1116
+ if (!github && values.repo)
1117
+ throw new Error("--repo is for --provider github");
1118
+ const objects = github ? ["pushes", "merges", "releases"] : ["refunds", "payouts", "transfers"];
1119
+ const object = values.object ?? objects[0];
1120
+ if (!objects.includes(object))
1121
+ throw new Error(`--object is one of ${objects.join(", ")}; got "${object}"`);
1043
1122
  const sinceMs = Date.parse(values.since);
1044
1123
  const untilMs = Date.parse(values.until);
1045
1124
  if (!Number.isFinite(sinceMs) || !Number.isFinite(untilMs) || untilMs <= sinceMs)
@@ -1061,11 +1140,12 @@ async function main(argv) {
1061
1140
  ...(values.log ? { logFile: values.log } : {}),
1062
1141
  ...(values["log-id"] ? { logId: values["log-id"] } : {}),
1063
1142
  },
1064
- source: stripeSource({ secretKey: secretFrom(values["key-env"]), object: values.object }),
1143
+ source: github ? githubSource({ token: secretFrom(values["key-env"]), repo: values.repo, object: object }) : stripeSource({ secretKey: secretFrom(values["key-env"]), object: object }),
1065
1144
  tools: values.tool,
1066
1145
  sinceMs,
1067
1146
  untilMs,
1068
1147
  ...(values["id-path"] ? { idPath: values["id-path"] } : {}),
1148
+ ...(values["receipt-id-path"] ? { receiptIdPath: values["receipt-id-path"] } : {}),
1069
1149
  ...(values["amount-field"] ? { amountField: values["amount-field"] } : {}),
1070
1150
  ...(values["currency-field"] ? { currencyField: values["currency-field"] } : {}),
1071
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 {
@@ -24,6 +25,22 @@ export interface StripeSourceOptions {
24
25
  }
25
26
  /** Lists Stripe objects created in the window, every page, with `created[gte]` and `created[lt]`. */
26
27
  export declare function stripeSource(o: StripeSourceOptions): ProviderSource;
28
+ export type GitHubObject = "pushes" | "merges" | "releases";
29
+ export interface GitHubSourceOptions {
30
+ /** a read-only token; from the environment, never a flag */
31
+ token: string;
32
+ /** the repository, as "owner/name" */
33
+ repo: string;
34
+ object: GitHubObject;
35
+ baseUrl?: string;
36
+ fetch?: typeof fetch;
37
+ }
38
+ /**
39
+ * Lists one repository's pushes or merged pull requests (from its activity list) or its releases, every page. The id of
40
+ * a push or a merge is the commit the ref moved to (`after`); the id of a release is its numeric id, as a string. A push
41
+ * that creates a branch is listed only as `branch_creation`, so `pushes` reads that kind too.
42
+ */
43
+ export declare function githubSource(o: GitHubSourceOptions): ProviderSource;
27
44
  export interface CompletenessOptions {
28
45
  /** the auditor's copy of the receipts directory */
29
46
  receiptsDir: string;
@@ -36,7 +53,13 @@ export interface CompletenessOptions {
36
53
  untilMs: number;
37
54
  /** where the provider's object id sits in the JSON of the result's first text item; default "id" */
38
55
  idPath?: string;
39
- /** 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 */
40
63
  amountField?: string;
41
64
  /** the call argument that holds the currency; default "currency", compared case-insensitively when both sides have one */
42
65
  currencyField?: string;
@@ -56,9 +79,11 @@ export interface CompletenessReport {
56
79
  until: string;
57
80
  };
58
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 */
59
83
  matched: {
60
84
  receiptId: string;
61
85
  providerId: string;
86
+ kind: IssuerKind;
62
87
  }[];
63
88
  /** provider objects in the window with no verified receipt: actions taken outside the gateway */
64
89
  providerOnly: {
@@ -66,8 +91,9 @@ export interface CompletenessReport {
66
91
  created: string;
67
92
  amount?: number;
68
93
  currency?: string;
94
+ repeated?: true;
69
95
  }[];
70
- /** 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 */
71
97
  receiptOnly: {
72
98
  receiptId: string;
73
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";
@@ -46,6 +48,59 @@ export function stripeSource(o) {
46
48
  },
47
49
  };
48
50
  }
51
+ const GITHUB_ACTIVITY = { pushes: ["push", "force_push", "branch_creation"], merges: ["pr_merge", "merge_queue_merge"] };
52
+ /**
53
+ * Lists one repository's pushes or merged pull requests (from its activity list) or its releases, every page. The id of
54
+ * a push or a merge is the commit the ref moved to (`after`); the id of a release is its numeric id, as a string. A push
55
+ * that creates a branch is listed only as `branch_creation`, so `pushes` reads that kind too.
56
+ */
57
+ export function githubSource(o) {
58
+ if (!/^[\w.-]+\/[\w.-]+$/.test(o.repo))
59
+ throw new Error(`github: the repository is "owner/name"; got "${o.repo}"`);
60
+ const f = o.fetch ?? fetch;
61
+ const base = new URL(o.baseUrl ?? "https://api.github.com/");
62
+ const kinds = GITHUB_ACTIVITY[o.object];
63
+ return {
64
+ name: `github ${o.object} in ${o.repo}`,
65
+ async *list(sinceMs, untilMs) {
66
+ let url = new URL(`repos/${o.repo}/${kinds ? "activity" : "releases"}?per_page=100`, base);
67
+ const listed = new Set();
68
+ while (url) {
69
+ // the next page comes from a response header: the token goes only to the host it was given for
70
+ if (url.origin !== base.origin)
71
+ throw new Error(`github ${o.object}: the next page is on another host, ${url.origin}`);
72
+ const res = await f(url, { headers: { authorization: `Bearer ${o.token}`, accept: "application/vnd.github+json", "x-github-api-version": "2022-11-28" }, signal: AbortSignal.timeout(15_000) });
73
+ if (!res.ok)
74
+ throw new Error(`github ${o.object}: HTTP ${res.status}`);
75
+ const page = (await res.json());
76
+ if (!Array.isArray(page))
77
+ throw new Error(`github ${o.object}: the answer is not a list`);
78
+ let older = false;
79
+ for (const obj of page) {
80
+ const id = kinds ? obj.after : obj.id;
81
+ const createdMs = Date.parse(String(kinds ? obj.timestamp : (obj.published_at ?? obj.created_at)));
82
+ if (!(typeof id === "string" ? id.length : Number.isSafeInteger(id)) || !Number.isFinite(createdMs))
83
+ throw new Error(`github ${o.object}: an object without an id or a time`);
84
+ // the activity list is newest first, so nothing after an older entry is in the window; releases have no such order
85
+ if (kinds && createdMs < sinceMs)
86
+ older = true;
87
+ if (createdMs < sinceMs || createdMs >= untilMs || (kinds && !kinds.includes(String(obj.activity_type))))
88
+ continue;
89
+ if (kinds) {
90
+ // GitHub records some pushes twice: the same ref, commits, and time under two activity ids
91
+ const move = [obj.ref, obj.before, obj.after, obj.timestamp].join(" ");
92
+ if (listed.has(move))
93
+ continue;
94
+ listed.add(move);
95
+ }
96
+ yield { id: String(id), createdMs, raw: obj };
97
+ }
98
+ const next = older ? undefined : /<([^>]+)>;\s*rel="next"/.exec(res.headers.get("link") ?? "")?.[1];
99
+ url = next ? new URL(next) : undefined;
100
+ }
101
+ },
102
+ };
103
+ }
49
104
  const AUTHORIZATION = ".authorization.json";
50
105
  const iso = (ms) => new Date(ms).toISOString();
51
106
  function at(value, path) {
@@ -83,7 +138,9 @@ function providerIdOf(p, idPath) {
83
138
  return { reason: "the result's text is not JSON" };
84
139
  }
85
140
  const id = at(parsed, idPath);
86
- return typeof id === "string" && id.length ? { id } : { reason: `the result has no string at "${idPath}"` };
141
+ if (Number.isSafeInteger(id))
142
+ return { id: String(id) };
143
+ return typeof id === "string" && id.length ? { id } : { reason: `the result has no string or integer at "${idPath}"` };
87
144
  }
88
145
  /** A call argument, or that a capture rule withholds it: listed fields stay in clear beside one `$rest` commitment. */
89
146
  function argOf(args, field) {
@@ -91,8 +148,18 @@ function argOf(args, field) {
91
148
  return isCommitment(args[field]) ? { withheld: true } : { value: args[field] };
92
149
  return isCommitment(args[REST]) ? { withheld: true } : { value: undefined };
93
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
+ }
94
160
  export async function checkCompleteness(o) {
95
161
  const idPath = o.idPath ?? "id";
162
+ const receiptIdPath = o.receiptIdPath ?? "metadata.agent_custody_receipt";
96
163
  const amountField = o.amountField ?? "amount";
97
164
  const currencyField = o.currencyField ?? "currency";
98
165
  const margin = o.marginMs ?? 15 * 60_000;
@@ -116,6 +183,7 @@ export async function checkCompleteness(o) {
116
183
  const names = readdirSync(o.receiptsDir, { withFileTypes: true }).filter((e) => (e.isFile() || e.isSymbolicLink()) && e.name.endsWith(".json")).map((e) => e.name).sort();
117
184
  const outcomes = new Set();
118
185
  const byProviderId = new Map();
186
+ const doorReceipts = new Map();
119
187
  for (const name of names) {
120
188
  if (name.endsWith(AUTHORIZATION))
121
189
  continue;
@@ -141,6 +209,13 @@ export async function checkCompleteness(o) {
141
209
  outcomes.add(p.receiptId);
142
210
  if (!tools.has(p.tool.name) || p.reconciliation || p.execution.status !== "executed")
143
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
+ }
144
219
  const id = providerIdOf(p, idPath);
145
220
  if ("reason" in id) {
146
221
  if (inWindow(Date.parse(p.timestamp)))
@@ -168,22 +243,34 @@ export async function checkCompleteness(o) {
168
243
  report.forwardedWithoutOutcome.push({ receiptId: auth.receiptId, tool: auth.tool.name });
169
244
  }
170
245
  const seen = new Set();
246
+ const claimed = new Set();
171
247
  for await (const obj of o.source.list(o.sinceMs - margin, o.untilMs + margin)) {
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
250
+ const repeated = seen.has(obj.id);
172
251
  seen.add(obj.id);
173
- 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] : [])];
174
261
  // the margin finds a receipt across the window's edge; it does not widen the period reported on
175
- 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)));
176
263
  if (!inScope)
177
264
  continue;
178
265
  if (!receipts.length) {
179
- report.providerOnly.push({ providerId: obj.id, created: iso(obj.createdMs), ...(obj.amount !== undefined ? { amount: obj.amount } : {}), ...(obj.currency !== undefined ? { currency: obj.currency } : {}) });
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 } : {}) });
180
267
  continue;
181
268
  }
182
269
  if (receipts.length > 1)
183
270
  report.duplicates.push({ providerId: obj.id, receiptIds: receipts.map((p) => p.receiptId) });
184
271
  for (const p of receipts) {
185
- report.matched.push({ receiptId: p.receiptId, providerId: obj.id });
186
- 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;
187
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` });
188
275
  const amount = argOf(args, amountField);
189
276
  if ("withheld" in amount) {
@@ -222,13 +309,19 @@ export async function checkCompleteness(o) {
222
309
  report.complete = [report.providerOnly, report.receiptOnly, report.mismatches, report.duplicates, report.unverified, report.unmatchable, report.forwardedWithoutOutcome].every((l) => l.length === 0);
223
310
  return report;
224
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
+ }
225
318
  export function formatCompleteness(r) {
226
- 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)}`];
227
320
  const section = (title, rows) => {
228
321
  if (rows.length)
229
322
  lines.push("", `${title} (${rows.length})`, ...rows.map((row) => ` ${row}`));
230
323
  };
231
- section("PROVIDER ACTIONS WITH NO RECEIPT", r.providerOnly.map((x) => `${x.providerId} created ${x.created}${x.amount !== undefined ? ` amount ${x.amount}${x.currency ? ` ${x.currency}` : ""}` : ""}`));
324
+ section("PROVIDER ACTIONS WITH NO RECEIPT", r.providerOnly.map((x) => `${x.providerId} created ${x.created}${x.amount !== undefined ? ` amount ${x.amount}${x.currency ? ` ${x.currency}` : ""}` : ""}${x.repeated ? "; the receipt for this id accounts for another action" : ""}`));
232
325
  section("RECEIPTS THE PROVIDER DOES NOT HAVE", r.receiptOnly.map((x) => `${x.receiptId} names ${x.providerId}, signed ${x.timestamp}`));
233
326
  section("MISMATCHES", r.mismatches.map((x) => `${x.receiptId} / ${x.providerId}: ${x.field} is ${JSON.stringify(x.receipt)} in the receipt, ${JSON.stringify(x.provider)} at the provider`));
234
327
  section("ONE PROVIDER OBJECT, SEVERAL RECEIPTS", r.duplicates.map((x) => `${x.providerId} is named by ${x.receiptIds.join(", ")}`));
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' })));