@agent-custody/receipts 0.16.8 → 0.16.10

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.
package/README.md CHANGED
@@ -36,7 +36,7 @@ Anyone holding the public keys can verify a receipt offline. The agent is not tr
36
36
  - [What the evidence satisfies](docs/compliance.md): the receipts, packs, and certificates mapped to SOC 2, ISO 27001, UK GDPR, the EU AI Act, FINRA, MAS, Colorado, DORA, the CSA AI Controls Matrix, the OWASP agentic guidance, and ISO/IEC 42001. Each regulation has a primary source, an "as of" date, and a list of what a receipt does not supply
37
37
  - [Anchoring the log on a chain](docs/anchoring.md): the log's checkpoints committed to Ethereum mainnet, or another EVM chain the installation picks, from a published address, what that proves and what it does not, running the anchor, and `log-check` against the chain
38
38
  - [Receipts on a pull request](docs/github-action.md): the GitHub Action that verifies a directory of receipt bundles and posts one table on the pull request, the workflow file to copy, the `export` command that copies the receipts into the branch, and why a committed receipt publishes the call unless a capture rule withholds it
39
- - [Completeness](docs/completeness.md): an auditor's read-only key lists the provider's objects and matches each to a verified receipt, so an action taken outside the gateway shows up
39
+ - [Completeness](docs/completeness.md): an auditor's read-only key lists the provider's objects and matches each to a verified receipt, so an action taken outside the gateway shows up, for Stripe and for GitHub
40
40
  - [Payment mandates and agent identity](docs/mandates.md): the design for fitting grants and receipts to Google's AP2 mandates, Visa's Trusted Agent Protocol and Mastercard Agent Pay; not yet built
41
41
  - [Threat model](docs/threat-model.md): every party who could make a receipt false, the move, what stops it, and whether that is a property of the evidence or of the deployment; and what is not defended
42
42
  - [What a receipt costs](docs/performance.md): each step of the issuer's hot path in microseconds, measured with `bun run bench`, what is and is not fsynced, and where the time goes
@@ -289,6 +289,8 @@ src/policy-rego.ts Rego: compiled with opa build, evaluated in-process with the
289
289
  src/opa-server.ts an OPA server's Data API as the policy, with bundle revisions as the digest
290
290
  src/simulate.ts replay recorded policy decisions against a proposed Cedar or Rego policy, grouped changes and run digest
291
291
  src/delegation.ts signed delegation grants
292
+ src/did-key.ts did:key identifiers for Ed25519 keys (base58btc, multicodec 0xed01): an agent named by its key in a grant
293
+ src/revocation.ts the revoked-grants file the gateway and the door share: re-read when it changes, written by rename
292
294
  src/approval.ts exact-action human approvals, distinct trusted signatures, persistent single-use consumption
293
295
  src/receipt.ts receipt and authorization statement types and provenance labels
294
296
  src/issue.ts sign, log, and write a receipt, or commit an authorization first; shared by every producer
@@ -296,6 +298,7 @@ src/gateway.ts the MCP proxy: a host (key, policy, upstreams, log) and a ses
296
298
  src/operations.ts SQLite operation claims and daily budget reservations, retained across retries and process crashes
297
299
  src/gateway-http.ts the gateway over Streamable HTTP: one process, a session per connection, each under the grant it presents
298
300
  src/door.ts the door: a reverse proxy in front of your own HTTP surface, or the authz check behind nginx and Envoy; every arrival classified, decided per route, relayed or refused, receipted as issuer kind door; its decision loop is shared with door-app.ts
301
+ src/door-form.ts the form protector: the script the door serves at /.well-known/agent-custody-door/form.js, from its challenge config
299
302
  src/door-app.ts the door in-process (`@agent-custody/receipts/door`): Express or Connect middleware and a fetch route-handler wrapper (Next.js), over the same decision loop
300
303
  src/web-bot-auth.ts the door's Web Bot Auth check: RFC 9421 signature base, RFC 8941 dictionaries, Ed25519, the signer's key directory fetched and cached, nonces
301
304
  src/door-partner.ts the door's partner engine slot: asks a detection engine about an arrival, accepts only a verdict signed for that receipt and route (the upstream attestation format), and `signVerdict` for engines
@@ -334,6 +337,8 @@ The design is several producers feeding one verifier. The SDK is the top of the
334
337
 
335
338
  **Done**
336
339
 
340
+ - did:key identity on grants (#255): a grant may name its agent by the did:key of its Ed25519 key (`grant --agent-key agent.pub --did-key`). The door checks that the identifier decodes and agrees with the grant's `agentKey`; a grant that does not is `claimed`, one that does is `verified` with the did:key as the agent ([a did:key agent](docs/door.md#a-did-key-agent), tutorial 55).
341
+ - The form protector (svayatta/pm#14): with `challenge` configured, the door serves `/.well-known/agent-custody-door/form.js`, and one script tag on a page puts the Turnstile or hCaptcha widget in its same-origin POST forms. The script sends each form with the token in the door's header and follows the answer as a form post would, so a static site's form reaches its backend with a receipt id, and a direct post with no token is refused ([protecting a form with one line](docs/door.md#protecting-a-form-with-one-line), tutorial 54).
337
342
  - The door for sites that are not Node (svayatta/pm#4): standard-library middleware for Go `net/http`, Rack (Rails), Django and WSGI, and the JDK `HttpServer`, in `examples/languages/door/`, each a client of the door's authz check. It forwards the method, path, query, and headers, runs the app only on the door's 200 with the receipt id and class in the request and the grant removed, returns any refusal as the door gave it, and answers 503 when the door cannot be reached or does not answer in time. A Spring `OncePerRequestFilter` around the same Java client is a doc snippet, not compiled by the tests ([the door in Go, Rails, Django, and Spring](docs/door-languages.md)).
338
343
  - The door's partner engine slot (svayatta/pm#13): with `partner` in the door config, the door asks a detection engine (Cloudflare Bot Management, HUMAN, DataDome, behind an adapter that holds an Ed25519 key) about each arrival on the listed routes, naming the receipt it is writing. The engine signs its verdict for that receipt and route in the upstream attestation format; only a verdict whose signature verifies under the configured key reaches the policy, as `context.facts.partner`, and lands in the receipt as an attested fact, checked again by all three verifiers with `--upstream-key`. A verdict for another arrival is refused, and an engine that is down, slow, or signs wrongly never becomes an allow: the arrival is refused with 503 (`onFailure: "deny"`, the default) or the policy decides without the fact (`"absent"`) ([the door](docs/door.md#a-partner-engines-verdict), tutorial 52).
339
344
  - The door in-process: `@agent-custody/receipts/door` runs the door's decision loop inside a Node site, the proxy's own code path split out of it. Express takes `app.use(door("door.json"))`; a Next.js App Router route takes `export const POST = guard.route(handler)`. An allowed request reaches the app with the receipt id and the class in its headers, the grant removed, and the body the policy read handed on to the app's own parsers; a refused one never reaches it; a request that can change something is in the log before the app runs; and the receipt records the app's status and a digest of its body. Neither framework is a dependency. Next.js pages, Server Actions, and its middleware file are not covered ([the door in your Node app](docs/door-middleware.md), tutorial 48).
@@ -394,14 +399,14 @@ The design is several producers feeding one verifier. The SDK is the top of the
394
399
  - The [state review console](../state/README.md#explain-one-action): search receipts by transaction, customer, agent or time, read the ten answers, and hand over a portable HTML/JSON case whose signatures, authorizations and inclusion proofs can be verified offline.
395
400
  - A log outage after an ordinary call (issue #149): the signed receipt waits in `receipts/outbox/` and the gateway appends it when the log is back, the agent gets the real outcome marked `log-pending`, `GET /health` counts the pending receipts, and `requirePrecommit` refuses a remote log with an empty `precommit`. The [failure table](docs/usage.md#when-the-log-fails) gives each case.
396
401
  - The anchor (issue #176): `agent-custody anchor` proves each new checkpoint extends the last one it anchored, then commits a Merkle root over them in one transaction from its address to itself, on Ethereum by default or on Base, Arbitrum, Optimism, Polygon, or any EVM chain by id (`--chain`), with a fee cap sized per chain. It publishes each log's record and inclusion proof, sends nothing for an idle log, skips a run above a fee cap, and never has two transactions in flight. Every transaction covers every watched log, and a transaction counts only once its block is finalized, following reorgs. `log-check --anchor-url` checks the record against one or more JSON-RPC endpoints, requires the log id the verifier pinned and the address's newest transaction, and checks the log's head against the anchored checkpoint, so a rewritten or rolled-back tree is caught from the chain alone ([anchoring](docs/anchoring.md), example 33).
397
- - Completeness from the provider's side (issue #178): `agent-custody completeness` lists Stripe's refunds, payouts, or transfers over a window with the auditor's own read-only key, and matches each to a verified receipt by the provider's object id. It reports actions with no receipt, receipts the provider does not have, amount, currency, and beneficiary mismatches, calls forwarded without an outcome receipt, and receipts it cannot match ([completeness](docs/completeness.md), example 35).
402
+ - Completeness from the provider's side (issue #178): `agent-custody completeness` lists Stripe's refunds, payouts, or transfers over a window with the auditor's own read-only key, and matches each to a verified receipt by the provider's object id. It reports actions with no receipt, receipts the provider does not have, amount, currency, and beneficiary mismatches, calls forwarded without an outcome receipt, and receipts it cannot match ([completeness](docs/completeness.md), example 35). `--provider github` does the same check over one repository's pushes, merged pull requests, or releases, matched by the commit or the release id that the receipt's result carries (example 53).
398
403
 
399
404
  **Next, in the order it pays off**
400
405
  <!-- #region receipts-next -->
401
406
  The first three close the gap between a log the operator cannot rewrite and a record the operator cannot shape.
402
407
 
403
408
  1. Run the anchor for log.agent-custody.dev on mainnet: a funded key held only by the anchor service on the host, its records served beside the checkpoints, its address and each tenant's log id published in the welcome sheet and on the security page, and the monitor checking it. The code is done. [Issue #176](https://github.com/svayatta/agent-custody/issues/176).
404
- 2. Completeness beyond Stripe: the same check over GitHub's actions, and over on-chain transfers out of an agent's wallet, where the chain itself lists every transfer. [Issue #178](https://github.com/svayatta/agent-custody/issues/178).
409
+ 2. Completeness beyond Stripe and GitHub: the same check over on-chain transfers out of an agent's wallet, where the chain itself lists every transfer. [Issue #178](https://github.com/svayatta/agent-custody/issues/178).
405
410
  3. A TEE gateway: a confidential container with a reproducible, attested build, the signing key generated and kept in the enclave, TLS ending inside it, and both verifiers checking the path from the receipt key, through the attestation, to the release. It replaces the TEE-hosted signer planned before. [Issue #179](https://github.com/svayatta/agent-custody/issues/179).
406
411
  4. Run the witness for log.agent-custody.dev on a machine and under an account that is not ours, and require it in the welcome sheet. The code is done; what it needs is a second operator. [Issue #116](https://github.com/svayatta/agent-custody/issues/116).
407
412
  5. Post-quantum signatures: ML-DSA beside Ed25519 in the same DSSE envelope, hybrid by default when a PQ key is present, in every signed artefact and in the browser verifier. [Issue #11](https://github.com/svayatta/agent-custody/issues/11).
package/dist/check.js CHANGED
@@ -225,6 +225,23 @@ export function checkDoorConfig(configPath) {
225
225
  if (!ldir)
226
226
  add("error", "paths", `${cfg.logFile} cannot be written`);
227
227
  }
228
+ if (cfg.revokedGrants) {
229
+ if (!existsSync(cfg.revokedGrants))
230
+ add("ok", "revokedGrants", `no grant is revoked yet; \`agent-custody revoke --config\` creates ${cfg.revokedGrants}`);
231
+ else {
232
+ try {
233
+ const list = JSON.parse(readFileSync(cfg.revokedGrants, "utf8"));
234
+ if (!Array.isArray(list))
235
+ throw new Error("expected a JSON array of grant digests");
236
+ add("ok", "revokedGrants", `${list.length} revoked grant(s) in ${cfg.revokedGrants}`);
237
+ }
238
+ catch (e) {
239
+ add("error", "revokedGrants", `${cfg.revokedGrants}: ${e instanceof Error ? e.message : String(e)}; the door refuses to start, and a file that becomes unreadable while it runs makes every grant revoked`);
240
+ }
241
+ }
242
+ }
243
+ else if (cfg.trustedPrincipalKeys.length > 0)
244
+ add("warn", "revokedGrants", "no revokedGrants file: a grant cannot be revoked at this door before it expires");
228
245
  return out;
229
246
  }
230
247
  /** True when the file is an egress witness config: it names agents, and no upstream or origin. */
package/dist/cli.js CHANGED
@@ -8,6 +8,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
10
  import { createDelegation, decodeDelegation, delegateFrom, grantDigest } from "./delegation.js";
11
+ import { didKeyOf } from "./did-key.js";
11
12
  import { createGateway, createGatewayHost, serveStdio, writeRevokedGrants } from "./gateway.js";
12
13
  import { postgresResolver, serveLog } from "./log-sink.js";
13
14
  import { importLogFile, PostgresTenancy } from "./log-store.js";
@@ -16,7 +17,7 @@ import { connectSigner, fetchLogKeys, localSigner, serveSigner } from "./signer.
16
17
  import { fetchWitnessKeys, Witness } from "./witness.js";
17
18
  import { checkLog, formatLogCheck } from "./log-check.js";
18
19
  import { Anchor, ANCHOR_CHAINS, resolveAnchorChain } from "./anchor.js";
19
- import { checkCompleteness, formatCompleteness, stripeSource } from "./completeness.js";
20
+ import { checkCompleteness, formatCompleteness, githubSource, stripeSource } from "./completeness.js";
20
21
  import { evmChain } from "./anchor-evm.js";
21
22
  import { serveHttp } from "./gateway-http.js";
22
23
  import { createDoorHost, serveDoor } from "./door.js";
@@ -81,13 +82,16 @@ const USAGE = `agent-custody <command>
81
82
 
82
83
  keygen --dir <dir> --name <name>
83
84
  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
85
+ --agent-key names the agent's own key in the grant, so the agent may delegate;
86
+ --did-key with --agent-key and no --agent names the agent by that key's did:key
85
87
  delegate --key <agent.key> --parent <grant.json> --agent <sub-agent> --scopes <a,b> [--ttl-hours N] [--agent-key <sub.pub>] --out <file>
86
88
  a narrower grant for a sub-agent, signed by the agent the parent names; the parent travels inside
87
89
  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
90
  for verify --disclose; needs the customer's capture key
89
- revoke --config <gateway.json> --grant <grant.json> revokes a grant: its digest goes into the config's revokedGrants file, every
90
- session under it or under a grant delegated from it refuses its next call, and no new session opens for them
91
+ revoke --config <gateway.json|door.json> --grant <grant.json>
92
+ revokes a grant: its digest goes into the config's revokedGrants file. At a gateway, every
93
+ session under it or under a grant delegated from it refuses its next call, and no new session opens for them;
94
+ at a door, an arrival carrying it, or a grant delegated from it, is claimed with grant "revoked"
91
95
  reconcile --config <gateway.json> --operation <uuid> operator-only provider lookup; commits a receipt before closing an unknown/pending financial operation
92
96
  console --config <gateway.json> [--port 8795] [--host 127.0.0.1] [--token-env CONSOLE_TOKEN | --token-file <path>] [--gateway-url <url>] [--state-dir <dir>]
93
97
  the admin console for a gateway: its config and tools, a config check, receipts with a verdict each, a policy editor that
@@ -143,6 +147,7 @@ const USAGE = `agent-custody <command>
143
147
  policy simulate --policy <proposed.cedar|.rego> --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--approval-key <pub>]... [--log-key <pub>]... [--json] [--out <file>]
144
148
  completeness --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--log-key <pub>]... [--log <log.jsonl>] [--log-id <id>]
145
149
  --provider stripe --object refunds|payouts|transfers --key-env NAME --tool <name>... --since <ISO> --until <ISO>
150
+ (or --provider github --repo <owner>/<name> --object pushes|merges|releases)
146
151
  [--id-path id] [--amount-field amount] [--currency-field currency] [--beneficiary <arg>=<field>]... [--json]
147
152
  for an auditor: lists the provider's objects in the window with a read-only key, and
148
153
  matches each to a verified receipt by the provider's object id; reports actions with no
@@ -272,23 +277,27 @@ async function main(argv) {
272
277
  scopes: { type: "string" },
273
278
  "ttl-hours": { type: "string", default: "24" },
274
279
  "agent-key": { type: "string" },
280
+ "did-key": { type: "boolean", default: false },
275
281
  out: { type: "string" },
276
282
  },
277
283
  });
278
- if (!values.key || !values.principal || !values.agent || !values.scopes || !values.out)
279
- throw new Error("grant needs --key --principal --agent --scopes --out");
284
+ if (values["did-key"] && (!values["agent-key"] || values.agent))
285
+ throw new Error("--did-key names the agent by the did:key of --agent-key, so it needs --agent-key and no --agent");
286
+ const agent = values["did-key"] ? didKeyOf(loadPublicKey(values["agent-key"]).publicKey) : values.agent;
287
+ if (!values.key || !values.principal || !agent || !values.scopes || !values.out)
288
+ throw new Error("grant needs --key --principal --agent (or --agent-key with --did-key) --scopes --out");
280
289
  const now = Date.now();
281
290
  const env = createDelegation(loadPrivateKey(values.key), {
282
291
  version: "0.1",
283
292
  principal: values.principal,
284
- agent: values.agent,
293
+ agent,
285
294
  scopes: values.scopes.split(",").map((s) => s.trim()).filter(Boolean),
286
295
  issuedAt: new Date(now).toISOString(),
287
296
  expiresAt: new Date(now + Number(values["ttl-hours"]) * 3600_000).toISOString(),
288
297
  ...(values["agent-key"] ? { agentKey: readFileSync(values["agent-key"], "utf8") } : {}),
289
298
  });
290
299
  writeFileSync(values.out, JSON.stringify(env, null, 2));
291
- console.log(`wrote ${values.out}`);
300
+ console.log(`wrote ${values.out}${values["did-key"] ? ` for ${agent}` : ""}`);
292
301
  return 0;
293
302
  }
294
303
  case "delegate": {
@@ -329,9 +338,10 @@ async function main(argv) {
329
338
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, grant: { type: "string" } } });
330
339
  if (!values.config || !values.grant)
331
340
  throw new Error("revoke needs --config and --grant");
332
- const cfg = loadConfig(values.config);
341
+ const door = isDoorConfig(values.config);
342
+ const cfg = door ? loadDoorConfig(values.config) : loadConfig(values.config);
333
343
  if (!cfg.revokedGrants)
334
- throw new Error("revoke needs revokedGrants in the config: the file the gateway re-reads on every call");
344
+ throw new Error(`revoke needs revokedGrants in the config: the file the ${door ? "door re-reads on every arrival" : "gateway re-reads on every call"}`);
335
345
  const envelope = JSON.parse(readFileSync(values.grant, "utf8"));
336
346
  const chain = decodeDelegation(envelope);
337
347
  if (!chain)
@@ -340,7 +350,7 @@ async function main(argv) {
340
350
  const list = existsSync(cfg.revokedGrants) ? JSON.parse(readFileSync(cfg.revokedGrants, "utf8")) : [];
341
351
  if (!list.includes(digest))
342
352
  writeRevokedGrants(cfg.revokedGrants, [...list, digest]);
343
- console.log(`revoked ${chain.agent}'s grant from ${chain.principal} (${digest.slice(0, 12)}…): ${cfg.revokedGrants} now lists ${list.includes(digest) ? list.length : list.length + 1} grant(s); a running gateway refuses it on its next call`);
353
+ console.log(`revoked ${chain.agent}'s grant from ${chain.principal} (${digest.slice(0, 12)}…): ${cfg.revokedGrants} now lists ${list.includes(digest) ? list.length : list.length + 1} grant(s); ${door ? "a running door classifies it as revoked on its next arrival" : "a running gateway refuses it on its next call"}`);
344
354
  return 0;
345
355
  }
346
356
  case "gateway": {
@@ -1018,7 +1028,8 @@ async function main(argv) {
1018
1028
  log: { type: "string" },
1019
1029
  "log-id": { type: "string" },
1020
1030
  provider: { type: "string" },
1021
- object: { type: "string", default: "refunds" },
1031
+ object: { type: "string" },
1032
+ repo: { type: "string" },
1022
1033
  "key-env": { type: "string" },
1023
1034
  tool: { type: "string", multiple: true },
1024
1035
  since: { type: "string" },
@@ -1031,12 +1042,18 @@ async function main(argv) {
1031
1042
  },
1032
1043
  });
1033
1044
  if (!values.receipts || !values["issuer-key"]?.length || !values["key-env"] || !values.tool?.length || !values.since || !values.until)
1034
- throw new Error("completeness needs --receipts, --issuer-key, --provider stripe, --key-env, --tool, --since and --until");
1035
- if (values.provider !== "stripe")
1036
- throw new Error(`completeness supports --provider stripe; got "${values.provider ?? ""}"`);
1037
- const objects = ["refunds", "payouts", "transfers"];
1038
- if (!objects.includes(values.object))
1039
- throw new Error(`--object is one of ${objects.join(", ")}; got "${values.object}"`);
1045
+ throw new Error("completeness needs --receipts, --issuer-key, --provider, --key-env, --tool, --since and --until");
1046
+ if (values.provider !== "stripe" && values.provider !== "github")
1047
+ throw new Error(`completeness supports --provider stripe or github; got "${values.provider ?? ""}"`);
1048
+ const github = values.provider === "github";
1049
+ if (github && !values.repo)
1050
+ throw new Error("--provider github needs --repo <owner>/<name>");
1051
+ if (!github && values.repo)
1052
+ throw new Error("--repo is for --provider github");
1053
+ const objects = github ? ["pushes", "merges", "releases"] : ["refunds", "payouts", "transfers"];
1054
+ const object = values.object ?? objects[0];
1055
+ if (!objects.includes(object))
1056
+ throw new Error(`--object is one of ${objects.join(", ")}; got "${object}"`);
1040
1057
  const sinceMs = Date.parse(values.since);
1041
1058
  const untilMs = Date.parse(values.until);
1042
1059
  if (!Number.isFinite(sinceMs) || !Number.isFinite(untilMs) || untilMs <= sinceMs)
@@ -1058,7 +1075,7 @@ async function main(argv) {
1058
1075
  ...(values.log ? { logFile: values.log } : {}),
1059
1076
  ...(values["log-id"] ? { logId: values["log-id"] } : {}),
1060
1077
  },
1061
- source: stripeSource({ secretKey: secretFrom(values["key-env"]), object: values.object }),
1078
+ source: github ? githubSource({ token: secretFrom(values["key-env"]), repo: values.repo, object: object }) : stripeSource({ secretKey: secretFrom(values["key-env"]), object: object }),
1062
1079
  tools: values.tool,
1063
1080
  sinceMs,
1064
1081
  untilMs,
@@ -24,6 +24,22 @@ export interface StripeSourceOptions {
24
24
  }
25
25
  /** Lists Stripe objects created in the window, every page, with `created[gte]` and `created[lt]`. */
26
26
  export declare function stripeSource(o: StripeSourceOptions): ProviderSource;
27
+ export type GitHubObject = "pushes" | "merges" | "releases";
28
+ export interface GitHubSourceOptions {
29
+ /** a read-only token; from the environment, never a flag */
30
+ token: string;
31
+ /** the repository, as "owner/name" */
32
+ repo: string;
33
+ object: GitHubObject;
34
+ baseUrl?: string;
35
+ fetch?: typeof fetch;
36
+ }
37
+ /**
38
+ * Lists one repository's pushes or merged pull requests (from its activity list) or its releases, every page. The id of
39
+ * 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
40
+ * that creates a branch is listed only as `branch_creation`, so `pushes` reads that kind too.
41
+ */
42
+ export declare function githubSource(o: GitHubSourceOptions): ProviderSource;
27
43
  export interface CompletenessOptions {
28
44
  /** the auditor's copy of the receipts directory */
29
45
  receiptsDir: string;
@@ -66,6 +82,7 @@ export interface CompletenessReport {
66
82
  created: string;
67
83
  amount?: number;
68
84
  currency?: string;
85
+ repeated?: true;
69
86
  }[];
70
87
  /** executed receipts in the window whose provider object the provider does not have */
71
88
  receiptOnly: {
@@ -46,6 +46,59 @@ export function stripeSource(o) {
46
46
  },
47
47
  };
48
48
  }
49
+ const GITHUB_ACTIVITY = { pushes: ["push", "force_push", "branch_creation"], merges: ["pr_merge", "merge_queue_merge"] };
50
+ /**
51
+ * Lists one repository's pushes or merged pull requests (from its activity list) or its releases, every page. The id of
52
+ * 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
53
+ * that creates a branch is listed only as `branch_creation`, so `pushes` reads that kind too.
54
+ */
55
+ export function githubSource(o) {
56
+ if (!/^[\w.-]+\/[\w.-]+$/.test(o.repo))
57
+ throw new Error(`github: the repository is "owner/name"; got "${o.repo}"`);
58
+ const f = o.fetch ?? fetch;
59
+ const base = new URL(o.baseUrl ?? "https://api.github.com/");
60
+ const kinds = GITHUB_ACTIVITY[o.object];
61
+ return {
62
+ name: `github ${o.object} in ${o.repo}`,
63
+ async *list(sinceMs, untilMs) {
64
+ let url = new URL(`repos/${o.repo}/${kinds ? "activity" : "releases"}?per_page=100`, base);
65
+ const listed = new Set();
66
+ while (url) {
67
+ // the next page comes from a response header: the token goes only to the host it was given for
68
+ if (url.origin !== base.origin)
69
+ throw new Error(`github ${o.object}: the next page is on another host, ${url.origin}`);
70
+ 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) });
71
+ if (!res.ok)
72
+ throw new Error(`github ${o.object}: HTTP ${res.status}`);
73
+ const page = (await res.json());
74
+ if (!Array.isArray(page))
75
+ throw new Error(`github ${o.object}: the answer is not a list`);
76
+ let older = false;
77
+ for (const obj of page) {
78
+ const id = kinds ? obj.after : obj.id;
79
+ const createdMs = Date.parse(String(kinds ? obj.timestamp : (obj.published_at ?? obj.created_at)));
80
+ if (!(typeof id === "string" ? id.length : Number.isSafeInteger(id)) || !Number.isFinite(createdMs))
81
+ throw new Error(`github ${o.object}: an object without an id or a time`);
82
+ // the activity list is newest first, so nothing after an older entry is in the window; releases have no such order
83
+ if (kinds && createdMs < sinceMs)
84
+ older = true;
85
+ if (createdMs < sinceMs || createdMs >= untilMs || (kinds && !kinds.includes(String(obj.activity_type))))
86
+ continue;
87
+ if (kinds) {
88
+ // GitHub records some pushes twice: the same ref, commits, and time under two activity ids
89
+ const move = [obj.ref, obj.before, obj.after, obj.timestamp].join(" ");
90
+ if (listed.has(move))
91
+ continue;
92
+ listed.add(move);
93
+ }
94
+ yield { id: String(id), createdMs, raw: obj };
95
+ }
96
+ const next = older ? undefined : /<([^>]+)>;\s*rel="next"/.exec(res.headers.get("link") ?? "")?.[1];
97
+ url = next ? new URL(next) : undefined;
98
+ }
99
+ },
100
+ };
101
+ }
49
102
  const AUTHORIZATION = ".authorization.json";
50
103
  const iso = (ms) => new Date(ms).toISOString();
51
104
  function at(value, path) {
@@ -83,7 +136,9 @@ function providerIdOf(p, idPath) {
83
136
  return { reason: "the result's text is not JSON" };
84
137
  }
85
138
  const id = at(parsed, idPath);
86
- return typeof id === "string" && id.length ? { id } : { reason: `the result has no string at "${idPath}"` };
139
+ if (Number.isSafeInteger(id))
140
+ return { id: String(id) };
141
+ return typeof id === "string" && id.length ? { id } : { reason: `the result has no string or integer at "${idPath}"` };
87
142
  }
88
143
  /** A call argument, or that a capture rule withholds it: listed fields stay in clear beside one `$rest` commitment. */
89
144
  function argOf(args, field) {
@@ -169,14 +224,16 @@ export async function checkCompleteness(o) {
169
224
  }
170
225
  const seen = new Set();
171
226
  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
228
+ const repeated = seen.has(obj.id);
172
229
  seen.add(obj.id);
173
230
  const receipts = byProviderId.get(obj.id) ?? [];
174
231
  // the margin finds a receipt across the window's edge; it does not widen the period reported on
175
232
  const inScope = inWindow(obj.createdMs) || receipts.some((p) => inWindow(Date.parse(p.timestamp)));
176
233
  if (!inScope)
177
234
  continue;
178
- 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 } : {}) });
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 } : {}) });
180
237
  continue;
181
238
  }
182
239
  if (receipts.length > 1)
@@ -228,7 +285,7 @@ export function formatCompleteness(r) {
228
285
  if (rows.length)
229
286
  lines.push("", `${title} (${rows.length})`, ...rows.map((row) => ` ${row}`));
230
287
  };
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}` : ""}` : ""}`));
288
+ 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
289
  section("RECEIPTS THE PROVIDER DOES NOT HAVE", r.receiptOnly.map((x) => `${x.receiptId} names ${x.providerId}, signed ${x.timestamp}`));
233
290
  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
291
  section("ONE PROVIDER OBJECT, SEVERAL RECEIPTS", r.duplicates.map((x) => `${x.providerId} is named by ${x.receiptIds.join(", ")}`));
package/dist/config.d.ts CHANGED
@@ -415,6 +415,7 @@ export declare const DoorConfigSchema: z.ZodObject<{
415
415
  }, z.core.$strip>>>;
416
416
  unmatchedRoute: z.ZodDefault<z.ZodString>;
417
417
  trustedPrincipalKeys: z.ZodDefault<z.ZodArray<z.ZodString>>;
418
+ revokedGrants: z.ZodOptional<z.ZodString>;
418
419
  policyFile: z.ZodString;
419
420
  mode: z.ZodOptional<z.ZodEnum<{
420
421
  enforce: "enforce";
package/dist/config.js CHANGED
@@ -255,6 +255,8 @@ export const DoorConfigSchema = z.object({
255
255
  unmatchedRoute: z.string().min(1).default("other"),
256
256
  /** principal keys whose grants the door accepts as a passport: an arrival carrying one of their grants, in scope for its route, is `verified` */
257
257
  trustedPrincipalKeys: z.array(z.string()).default([]),
258
+ /** a JSON file listing digests of revoked grant envelopes, the same file and format as the gateway's (`agent-custody revoke --config door.json` appends to it); re-read whenever it changes, checked on every arrival. A grant it lists, or one whose chain it lists, is `revoked` */
259
+ revokedGrants: z.string().min(1).optional(),
258
260
  policyFile: z.string(),
259
261
  /** "enforce" (default) refuses what the policy denies; "observe" forwards everything and records the decision with `enforced: false` */
260
262
  mode: z.enum(["enforce", "observe"]).optional(),
@@ -399,6 +401,7 @@ export function loadDoorConfig(path) {
399
401
  ...cfg,
400
402
  identity: { keyFile: r(cfg.identity.keyFile) },
401
403
  trustedPrincipalKeys: cfg.trustedPrincipalKeys.map(r),
404
+ ...(cfg.revokedGrants ? { revokedGrants: r(cfg.revokedGrants) } : {}),
402
405
  policyFile: r(cfg.policyFile),
403
406
  receiptsDir: r(cfg.receiptsDir),
404
407
  ...(cfg.logFile ? { logFile: r(cfg.logFile) } : {}),
@@ -0,0 +1,9 @@
1
+ import { type KeyObject } from "node:crypto";
2
+ import { type PublicKeyRef } from "./crypto.ts";
3
+ export declare const DID_KEY_PREFIX = "did:key:";
4
+ export declare function base58btcEncode(bytes: Uint8Array): string;
5
+ export declare function base58btcDecode(text: string): Uint8Array;
6
+ /** The did:key of an Ed25519 public key. */
7
+ export declare function didKeyOf(publicKey: KeyObject): string;
8
+ /** The Ed25519 key a did:key names; throws, saying why, when it does not decode to one. */
9
+ export declare function publicKeyFromDidKey(did: string): PublicKeyRef;
@@ -0,0 +1,66 @@
1
+ // did:key identifiers for Ed25519 keys (W3C CCG did:key method): "did:key:z" followed by the base58btc encoding of the
2
+ // multicodec prefix for ed25519-pub (0xed 0x01) and the 32-byte public key. The identifier is the key: anyone can
3
+ // derive the key from it, and nothing about it says who holds the key or whether a principal trusts it.
4
+ import { createPublicKey } from "node:crypto";
5
+ import { keyidOf } from "./crypto.js";
6
+ const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
7
+ const ED25519_PUB = [0xed, 0x01];
8
+ export const DID_KEY_PREFIX = "did:key:";
9
+ export function base58btcEncode(bytes) {
10
+ let n = 0n;
11
+ for (const b of bytes)
12
+ n = n * 256n + BigInt(b);
13
+ let out = "";
14
+ while (n > 0n) {
15
+ out = ALPHABET[Number(n % 58n)] + out;
16
+ n /= 58n;
17
+ }
18
+ for (const b of bytes) {
19
+ if (b !== 0)
20
+ break;
21
+ out = "1" + out;
22
+ }
23
+ return out;
24
+ }
25
+ export function base58btcDecode(text) {
26
+ let n = 0n;
27
+ for (const ch of text) {
28
+ const v = ALPHABET.indexOf(ch);
29
+ if (v < 0)
30
+ throw new Error(`"${ch}" is not a base58btc character`);
31
+ n = n * 58n + BigInt(v);
32
+ }
33
+ const bytes = [];
34
+ while (n > 0n) {
35
+ bytes.unshift(Number(n % 256n));
36
+ n /= 256n;
37
+ }
38
+ for (const ch of text) {
39
+ if (ch !== "1")
40
+ break;
41
+ bytes.unshift(0);
42
+ }
43
+ return Uint8Array.from(bytes);
44
+ }
45
+ /** The did:key of an Ed25519 public key. */
46
+ export function didKeyOf(publicKey) {
47
+ if (publicKey.asymmetricKeyType !== "ed25519")
48
+ throw new Error(`did:key here is for Ed25519 keys; got ${publicKey.asymmetricKeyType}`);
49
+ const raw = Buffer.from(publicKey.export({ format: "jwk" }).x, "base64url");
50
+ return `${DID_KEY_PREFIX}z${base58btcEncode(Uint8Array.from([...ED25519_PUB, ...raw]))}`;
51
+ }
52
+ /** The Ed25519 key a did:key names; throws, saying why, when it does not decode to one. */
53
+ export function publicKeyFromDidKey(did) {
54
+ // an Ed25519 did:key is 56 characters; the decode is quadratic, so a much longer one is refused before it
55
+ if (did.length > 100)
56
+ throw new Error(`the did:key is ${did.length} characters; an Ed25519 did:key is 56`);
57
+ if (!did.startsWith(`${DID_KEY_PREFIX}z`))
58
+ throw new Error(`"${did.slice(0, 40)}" is not a base58btc did:key (did:key:z...)`);
59
+ const bytes = base58btcDecode(did.slice(DID_KEY_PREFIX.length + 1));
60
+ if (bytes[0] !== ED25519_PUB[0] || bytes[1] !== ED25519_PUB[1])
61
+ throw new Error("the did:key does not name an Ed25519 key (multicodec 0xed01)");
62
+ if (bytes.length !== 34)
63
+ throw new Error(`the did:key's Ed25519 key is ${bytes.length - 2} bytes, not 32`);
64
+ const publicKey = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: Buffer.from(bytes.subarray(2)).toString("base64url") }, format: "jwk" });
65
+ return { publicKey, keyid: keyidOf(publicKey) };
66
+ }
@@ -2,6 +2,7 @@ import type { IncomingMessage, ServerResponse } from "node:http";
2
2
  import { type DoorConfig } from "./config.ts";
3
3
  import { type DoorOptions } from "./door.ts";
4
4
  import type { FlushResult } from "./issue.ts";
5
+ export { FORM_SCRIPT_PATH, formScript } from "./door-form.ts";
5
6
  /** The receipt's `issuer.framework` for an arrival the middleware decided */
6
7
  export declare const MIDDLEWARE_FRAMEWORK = "node-middleware";
7
8
  /** The receipt's `issuer.framework` for an arrival a wrapped route handler decided */
@@ -19,6 +20,8 @@ export interface InProcessDoor {
19
20
  policyDigest(): string;
20
21
  flushOutbox(): Promise<FlushResult>;
21
22
  pendingReceipts(): number;
23
+ /** the form protector script for the config's challenge, or null without one; the middleware serves it at FORM_SCRIPT_PATH */
24
+ formScript(): string | null;
22
25
  close(): void;
23
26
  }
24
27
  /**
package/dist/door-app.js CHANGED
@@ -8,6 +8,8 @@ import { Readable } from "node:stream";
8
8
  import { loadDoorConfig } from "./config.js";
9
9
  import { digestOf } from "./crypto.js";
10
10
  import { CLASS_HEADER, RECEIPT_HEADER, createDoorCore, readBody, readStream, sendAnswer } from "./door.js";
11
+ import { FORM_SCRIPT_PATH, formScript } from "./door-form.js";
12
+ export { FORM_SCRIPT_PATH, formScript } from "./door-form.js";
11
13
  /** The receipt's `issuer.framework` for an arrival the middleware decided */
12
14
  export const MIDDLEWARE_FRAMEWORK = "node-middleware";
13
15
  /** The receipt's `issuer.framework` for an arrival a wrapped route handler decided */
@@ -111,7 +113,14 @@ export function door(config, options = {}) {
111
113
  if (cfg.authz)
112
114
  throw new Error("the in-process door passes an allowed request to the app it runs in; authz is for the door answering nginx or Envoy checks (`agent-custody door`)");
113
115
  const core = createDoorCore(cfg, { ...options, autoFlush: options.autoFlush ?? true }, MIDDLEWARE_FRAMEWORK);
116
+ const script = cfg.challenge ? formScript(cfg.challenge) : null;
114
117
  const middleware = (req, res, next) => {
118
+ // the script is public and the same for every arrival: served, not decided or receipted
119
+ if (script && req.method === "GET" && (req.url ?? "").split("?")[0] === FORM_SCRIPT_PATH) {
120
+ res.writeHead(200, { "content-type": "text/javascript; charset=utf-8", "cache-control": "public, max-age=300", "x-content-type-options": "nosniff" });
121
+ res.end(script);
122
+ return;
123
+ }
115
124
  if (!core.admit()) {
116
125
  req.resume();
117
126
  return sendAnswer(res, core.busy());
@@ -239,6 +248,7 @@ export function door(config, options = {}) {
239
248
  policyDigest: core.policyDigest,
240
249
  flushOutbox: core.flushOutbox,
241
250
  pendingReceipts: core.pendingReceipts,
251
+ formScript: () => script,
242
252
  close: core.close,
243
253
  });
244
254
  }
@@ -0,0 +1,6 @@
1
+ import type { DoorConfig } from "./config.ts";
2
+ export declare const FORM_SCRIPT_PATH = "/.well-known/agent-custody-door/form.js";
3
+ type Challenge = NonNullable<DoorConfig["challenge"]>;
4
+ /** The browser script for a door's challenge config. Public: it carries the provider, the site key, the header, and the action. */
5
+ export declare function formScript(challenge: Challenge): string;
6
+ export {};
@@ -0,0 +1,97 @@
1
+ export const FORM_SCRIPT_PATH = "/.well-known/agent-custody-door/form.js";
2
+ const PROVIDER_SCRIPT = {
3
+ turnstile: "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",
4
+ hcaptcha: "https://js.hcaptcha.com/1/api.js?render=explicit",
5
+ };
6
+ /** The browser script for a door's challenge config. Public: it carries the provider, the site key, the header, and the action. */
7
+ export function formScript(challenge) {
8
+ const settings = { provider: challenge.provider, siteKey: challenge.siteKey, header: challenge.header, src: PROVIDER_SCRIPT[challenge.provider], ...(challenge.action ? { action: challenge.action } : {}) };
9
+ return `// agent-custody door: form protector. Load it with a script tag, src ${FORM_SCRIPT_PATH} and defer; data-forms on the tag selects the forms.
10
+ (() => {
11
+ "use strict";
12
+ const settings = ${JSON.stringify(settings).replace(/</g, "\\u003c")};
13
+ const tag = document.currentScript;
14
+ const selector = (tag && tag.dataset.forms) || "form";
15
+ // the widget's own copies of the token: the door reads it from the header, and a body field would reach the receipt
16
+ const tokenFields = ["cf-turnstile-response", "h-captcha-response", "g-recaptcha-response"];
17
+ const api = () => (settings.provider === "turnstile" ? window.turnstile : window.hcaptcha);
18
+
19
+ const protect = (form) => {
20
+ if ((form.getAttribute("method") || "get").toLowerCase() !== "post") return;
21
+ const target = new URL(form.getAttribute("action") || location.href, location.href);
22
+ if (target.origin !== location.origin) return;
23
+ const box = document.createElement("div");
24
+ box.className = "agent-custody-challenge";
25
+ const note = document.createElement("p");
26
+ note.className = "agent-custody-challenge-note";
27
+ note.setAttribute("role", "status");
28
+ const button = form.querySelector('[type="submit"], button:not([type])');
29
+ if (button) button.before(box, note);
30
+ else form.append(box, note);
31
+ const options = { sitekey: settings.siteKey };
32
+ if (settings.provider === "turnstile") {
33
+ options["response-field"] = false;
34
+ if (settings.action) options.action = settings.action;
35
+ }
36
+ const widget = api().render(box, options);
37
+ let sending = false;
38
+ form.addEventListener("submit", async (event) => {
39
+ // a button's formaction, formmethod, and formenctype override the form's; a GET or another site's action goes natively
40
+ const via = event.submitter;
41
+ const attr = (name, fallback) => (via && via.hasAttribute && via.hasAttribute(name) ? via.getAttribute(name) : fallback);
42
+ const method = (attr("formmethod", form.getAttribute("method")) || "get").toLowerCase();
43
+ const to = new URL(attr("formaction", form.getAttribute("action")) || location.href, location.href);
44
+ if (method !== "post" || to.origin !== location.origin) {
45
+ // the browser reads the fields after this event: a disabled field is left out, so the token does not go along
46
+ for (const name of tokenFields) form.querySelectorAll('[name="' + name + '"]').forEach((el) => { el.disabled = true; });
47
+ return;
48
+ }
49
+ event.preventDefault();
50
+ if (sending) return;
51
+ const token = api().getResponse(widget);
52
+ if (!token) {
53
+ note.textContent = "Complete the check above, then send the form again.";
54
+ return;
55
+ }
56
+ sending = true;
57
+ note.textContent = "";
58
+ const data = new FormData(form, event.submitter || undefined);
59
+ for (const field of tokenFields) data.delete(field);
60
+ const multipart = (attr("formenctype", form.getAttribute("enctype")) || "").toLowerCase() === "multipart/form-data";
61
+ try {
62
+ const res = await fetch(to, { method: "POST", body: multipart ? data : new URLSearchParams(data), headers: { [settings.header]: token }, credentials: "same-origin", signal: AbortSignal.timeout(30000) });
63
+ if (res.redirected) return location.assign(res.url);
64
+ const type = res.headers.get("content-type") || "";
65
+ if (res.status === 403 && type.includes("application/json")) {
66
+ const refusal = await res.json().catch(() => ({}));
67
+ note.textContent = refusal.challenge ? "The check did not pass. Complete it again, then send the form." : "This form was refused (receipt " + (refusal.receipt || "none") + ").";
68
+ return;
69
+ }
70
+ const body = await res.text();
71
+ if (type.includes("text/html")) {
72
+ document.open();
73
+ document.write(body);
74
+ document.close();
75
+ return;
76
+ }
77
+ note.textContent = res.ok ? "Sent." : "The form was not sent: HTTP " + res.status + ".";
78
+ } catch (error) {
79
+ // a failure after the door relayed the form (a redirect to another site, a timeout) looks the same as one before
80
+ note.textContent = "The answer did not arrive, and the form may have been sent. Check before you send it again.";
81
+ } finally {
82
+ sending = false;
83
+ // a token serves one request
84
+ api().reset(widget);
85
+ }
86
+ });
87
+ };
88
+
89
+ const start = () => document.querySelectorAll(selector).forEach(protect);
90
+ const loader = document.createElement("script");
91
+ loader.src = settings.src;
92
+ loader.async = true;
93
+ loader.onload = () => (document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", start) : start());
94
+ document.head.append(loader);
95
+ })();
96
+ `;
97
+ }