@agent-custody/receipts 0.16.9 → 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,7 @@ 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
292
293
  src/revocation.ts the revoked-grants file the gateway and the door share: re-read when it changes, written by rename
293
294
  src/approval.ts exact-action human approvals, distinct trusted signatures, persistent single-use consumption
294
295
  src/receipt.ts receipt and authorization statement types and provenance labels
@@ -297,6 +298,7 @@ src/gateway.ts the MCP proxy: a host (key, policy, upstreams, log) and a ses
297
298
  src/operations.ts SQLite operation claims and daily budget reservations, retained across retries and process crashes
298
299
  src/gateway-http.ts the gateway over Streamable HTTP: one process, a session per connection, each under the grant it presents
299
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
300
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
301
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
302
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
@@ -335,6 +337,8 @@ The design is several producers feeding one verifier. The SDK is the top of the
335
337
 
336
338
  **Done**
337
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).
338
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)).
339
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).
340
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).
@@ -395,14 +399,14 @@ The design is several producers feeding one verifier. The SDK is the top of the
395
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.
396
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.
397
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).
398
- - 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).
399
403
 
400
404
  **Next, in the order it pays off**
401
405
  <!-- #region receipts-next -->
402
406
  The first three close the gap between a log the operator cannot rewrite and a record the operator cannot shape.
403
407
 
404
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).
405
- 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).
406
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).
407
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).
408
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/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,7 +82,8 @@ 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
@@ -145,6 +147,7 @@ const USAGE = `agent-custody <command>
145
147
  policy simulate --policy <proposed.cedar|.rego> --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--approval-key <pub>]... [--log-key <pub>]... [--json] [--out <file>]
146
148
  completeness --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--log-key <pub>]... [--log <log.jsonl>] [--log-id <id>]
147
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)
148
151
  [--id-path id] [--amount-field amount] [--currency-field currency] [--beneficiary <arg>=<field>]... [--json]
149
152
  for an auditor: lists the provider's objects in the window with a read-only key, and
150
153
  matches each to a verified receipt by the provider's object id; reports actions with no
@@ -274,23 +277,27 @@ async function main(argv) {
274
277
  scopes: { type: "string" },
275
278
  "ttl-hours": { type: "string", default: "24" },
276
279
  "agent-key": { type: "string" },
280
+ "did-key": { type: "boolean", default: false },
277
281
  out: { type: "string" },
278
282
  },
279
283
  });
280
- if (!values.key || !values.principal || !values.agent || !values.scopes || !values.out)
281
- 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");
282
289
  const now = Date.now();
283
290
  const env = createDelegation(loadPrivateKey(values.key), {
284
291
  version: "0.1",
285
292
  principal: values.principal,
286
- agent: values.agent,
293
+ agent,
287
294
  scopes: values.scopes.split(",").map((s) => s.trim()).filter(Boolean),
288
295
  issuedAt: new Date(now).toISOString(),
289
296
  expiresAt: new Date(now + Number(values["ttl-hours"]) * 3600_000).toISOString(),
290
297
  ...(values["agent-key"] ? { agentKey: readFileSync(values["agent-key"], "utf8") } : {}),
291
298
  });
292
299
  writeFileSync(values.out, JSON.stringify(env, null, 2));
293
- console.log(`wrote ${values.out}`);
300
+ console.log(`wrote ${values.out}${values["did-key"] ? ` for ${agent}` : ""}`);
294
301
  return 0;
295
302
  }
296
303
  case "delegate": {
@@ -1021,7 +1028,8 @@ async function main(argv) {
1021
1028
  log: { type: "string" },
1022
1029
  "log-id": { type: "string" },
1023
1030
  provider: { type: "string" },
1024
- object: { type: "string", default: "refunds" },
1031
+ object: { type: "string" },
1032
+ repo: { type: "string" },
1025
1033
  "key-env": { type: "string" },
1026
1034
  tool: { type: "string", multiple: true },
1027
1035
  since: { type: "string" },
@@ -1034,12 +1042,18 @@ async function main(argv) {
1034
1042
  },
1035
1043
  });
1036
1044
  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}"`);
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}"`);
1043
1057
  const sinceMs = Date.parse(values.since);
1044
1058
  const untilMs = Date.parse(values.until);
1045
1059
  if (!Number.isFinite(sinceMs) || !Number.isFinite(untilMs) || untilMs <= sinceMs)
@@ -1061,7 +1075,7 @@ async function main(argv) {
1061
1075
  ...(values.log ? { logFile: values.log } : {}),
1062
1076
  ...(values["log-id"] ? { logId: values["log-id"] } : {}),
1063
1077
  },
1064
- 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 }),
1065
1079
  tools: values.tool,
1066
1080
  sinceMs,
1067
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(", ")}`));
@@ -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
+ }
package/dist/door.d.ts CHANGED
@@ -240,6 +240,8 @@ export interface DoorHost {
240
240
  handle(req: IncomingMessage, res: ServerResponse): Promise<void>;
241
241
  flushOutbox(): Promise<FlushResult>;
242
242
  pendingReceipts(): number;
243
+ /** the form protector script, when the door has a challenge to protect forms with */
244
+ formScript?(): string | null;
243
245
  close(): Promise<void>;
244
246
  }
245
247
  /** The body as the door read it: whole, or how many bytes had arrived when it passed the limit. */
@@ -329,6 +331,10 @@ export interface RunningDoor {
329
331
  url: string;
330
332
  close(): Promise<void>;
331
333
  }
332
- /** Serves a door host over plain HTTP. Bind to loopback or put TLS in front. `GET /.well-known/agent-custody-door` answers the key id and the policy digest. */
334
+ /**
335
+ * Serves a door host over plain HTTP. Bind to loopback or put TLS in front. `GET /.well-known/agent-custody-door` answers
336
+ * the key id and the policy digest; with a challenge configured, `GET /.well-known/agent-custody-door/form.js` is the
337
+ * form protector script.
338
+ */
333
339
  export declare function serveDoor(host: DoorHost, opts: DoorServerOptions): Promise<RunningDoor>;
334
340
  export {};
package/dist/door.js CHANGED
@@ -10,13 +10,15 @@ import { randomUUID } from "node:crypto";
10
10
  import { closeSync, fstatSync, openSync, readFileSync } from "node:fs";
11
11
  import { createServer } from "node:http";
12
12
  import { captureKeyFrom } from "./capture.js";
13
- import { digestOf, loadPrivateKey, loadPublicKey, sha256Hex } from "./crypto.js";
13
+ import { digestOf, loadPrivateKey, loadPublicKey, publicKeyFromPem, sha256Hex } from "./crypto.js";
14
+ import { DID_KEY_PREFIX, publicKeyFromDidKey } from "./did-key.js";
14
15
  import { decodeDelegation, delegationValidAt, grantChainDigests, verifyDelegation } from "./delegation.js";
15
16
  import { parseGrantHeader, GRANT_HEADER } from "./gateway-http.js";
16
17
  import { createIssuer, ReceiptPending } from "./issue.js";
17
18
  import { createWebBotAuthVerifier, normalizeAuthority } from "./web-bot-auth.js";
18
19
  import { createPartnerEngine, PARTNER_FACT, PARTNER_TOOL } from "./door-partner.js";
19
20
  import { openLog } from "./log-sink.js";
21
+ import { FORM_SCRIPT_PATH, formScript } from "./door-form.js";
20
22
  import { createRevocationList } from "./revocation.js";
21
23
  import { openExporter } from "./otel.js";
22
24
  import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
@@ -318,6 +320,17 @@ export function classifyArrival(req, trusted, route, trustProxy, at, signature,
318
320
  const revocation = revoked?.(grantChainDigests(envelope));
319
321
  if (revocation)
320
322
  return { arrival: { class: "claimed", subject: grant.agent, grant: "revoked", grantError: revocation, ...base } };
323
+ // An agent named by a did:key is its key: the identifier must decode to an Ed25519 key, and the grant's agentKey, if
324
+ // it names one, must be that key, or the grant says two things about who the agent is. Every link of a chain, since a
325
+ // parent's agentKey is what verified the link below it.
326
+ for (const [i, link] of checked.chain.entries()) {
327
+ if (!link.agent.startsWith(DID_KEY_PREFIX))
328
+ continue;
329
+ const named = didKeyAgent(link.agent, link.agentKey);
330
+ const where = i === checked.chain.length - 1 ? "" : `link ${i} (${link.agent}): `;
331
+ if (named)
332
+ return { arrival: { class: "claimed", subject: grant.agent, grant: "invalid", grantError: where + named, ...base } };
333
+ }
321
334
  if (!delegationValidAt(grant, at))
322
335
  return { arrival: { class: "claimed", subject: grant.agent, grant: "invalid", grantError: "the grant is outside its validity window", ...base } };
323
336
  if (!grant.scopes.includes(route))
@@ -327,6 +340,26 @@ export function classifyArrival(req, trusted, route, trustProxy, at, signature,
327
340
  return { arrival: { class: "claimed", subject: grant.agent, grant: "wrong-sender", grantError: `the grant names agent "${grant.agent}", and the request is signed by ${signer.agent}`, ...base } };
328
341
  return { arrival: { class: "verified", subject: grant.agent, grant: "verified", ...base }, delegation: { envelope, grant, principalKeyid: checked.keyid }, ...(signer ? { signer } : {}) };
329
342
  }
343
+ /** Why a did:key agent does not check out, or null when it decodes and agrees with the grant's agentKey. */
344
+ function didKeyAgent(did, agentKey) {
345
+ let named;
346
+ try {
347
+ named = publicKeyFromDidKey(did);
348
+ }
349
+ catch (e) {
350
+ return `the grant's did:key agent does not decode: ${e instanceof Error ? e.message : String(e)}`;
351
+ }
352
+ if (agentKey === undefined)
353
+ return null;
354
+ try {
355
+ if (publicKeyFromPem(agentKey).keyid === named.keyid)
356
+ return null;
357
+ }
358
+ catch {
359
+ return "the grant's agentKey is not a public key";
360
+ }
361
+ return "the grant's agentKey is not the key its did:key agent names";
362
+ }
330
363
  /** methods that must not change anything at the origin; every other method is relayed only after its receipt is committed to the log */
331
364
  const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
332
365
  /** The body, or how many bytes had arrived when it passed the limit; the rest is drained and dropped. */
@@ -810,6 +843,7 @@ export async function createDoorHost(cfg, options = {}) {
810
843
  handle,
811
844
  flushOutbox: core.flushOutbox,
812
845
  pendingReceipts: core.pendingReceipts,
846
+ formScript: () => (cfg.challenge ? formScript(cfg.challenge) : null),
813
847
  async close() {
814
848
  core.close();
815
849
  },
@@ -854,12 +888,17 @@ function createAuthzHost(cfg, options) {
854
888
  handle,
855
889
  flushOutbox: core.flushOutbox,
856
890
  pendingReceipts: core.pendingReceipts,
891
+ formScript: () => (cfg.challenge ? formScript(cfg.challenge) : null),
857
892
  async close() {
858
893
  core.close();
859
894
  },
860
895
  };
861
896
  }
862
- /** Serves a door host over plain HTTP. Bind to loopback or put TLS in front. `GET /.well-known/agent-custody-door` answers the key id and the policy digest. */
897
+ /**
898
+ * Serves a door host over plain HTTP. Bind to loopback or put TLS in front. `GET /.well-known/agent-custody-door` answers
899
+ * the key id and the policy digest; with a challenge configured, `GET /.well-known/agent-custody-door/form.js` is the
900
+ * form protector script.
901
+ */
863
902
  export async function serveDoor(host, opts) {
864
903
  const bind = opts.host ?? "127.0.0.1";
865
904
  const log = opts.log ?? ((m) => console.error(m));
@@ -869,6 +908,17 @@ export async function serveDoor(host, opts) {
869
908
  res.end(JSON.stringify({ keyid: host.keyid, policyDigest: host.policyDigest(), version: DOOR_VERSION, pendingReceipts: host.pendingReceipts() }));
870
909
  return;
871
910
  }
911
+ if (req.method === "GET" && (req.url ?? "").split("?")[0] === FORM_SCRIPT_PATH) {
912
+ const script = host.formScript?.() ?? null;
913
+ if (!script) {
914
+ res.writeHead(404, { "content-type": "application/json", "cache-control": "no-store" });
915
+ res.end(JSON.stringify({ error: "this door has no challenge configured, so it has no form protector" }));
916
+ return;
917
+ }
918
+ res.writeHead(200, { "content-type": "text/javascript; charset=utf-8", "cache-control": "public, max-age=300", "x-content-type-options": "nosniff" });
919
+ res.end(script);
920
+ return;
921
+ }
872
922
  host.handle(req, res).catch((e) => {
873
923
  log(`agent-custody door: ${e instanceof Error ? e.message : String(e)}`);
874
924
  if (!res.headersSent) {
package/dist/index.d.ts CHANGED
@@ -20,6 +20,7 @@ export { formatPerathosReport, PERATHOS_RECEIPT_V1, perathosHead, perathosReceip
20
20
  export type { PerathosCheck, PerathosOptions, PerathosReport } from "./perathos.ts";
21
21
  export { loadAcsGuardianConfig } from "./config.ts";
22
22
  export type { AcsGuardianConfig } from "./config.ts";
23
+ export { FORM_SCRIPT_PATH, formScript } from "./door-form.ts";
23
24
  export type { Arrival, ArrivalChallenge, ArrivalClass, ArrivalRate, ChallengeCheck, Classified, DoorHost, DoorOptions, DoorRequest, DoorServerOptions, RateTracker, RateTrackerLimits, RunningDoor } from "./door.ts";
24
25
  export type { SignatureCheck, SignedRequest, WebBotAuthOptions, WebBotAuthVerifier } from "./web-bot-auth.ts";
25
26
  export * from "./capture.ts";
@@ -41,8 +42,8 @@ export { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoi
41
42
  export { adminRoutes, welcomeSheet } from "./log-admin.ts";
42
43
  export { fetchWitnessKeys, Witness } from "./witness.ts";
43
44
  export { Anchor, ANCHOR_CHAINS, anchorCalldata, anchorLeaf, checkAnchorRecord, resolveAnchorChain } from "./anchor.ts";
44
- export { checkCompleteness, formatCompleteness, stripeSource } from "./completeness.ts";
45
- export type { CompletenessOptions, CompletenessReport, ProviderObject, ProviderSource, StripeObject, StripeSourceOptions } from "./completeness.ts";
45
+ export { checkCompleteness, formatCompleteness, githubSource, stripeSource } from "./completeness.ts";
46
+ export type { CompletenessOptions, CompletenessReport, GitHubObject, GitHubSourceOptions, ProviderObject, ProviderSource, StripeObject, StripeSourceOptions } from "./completeness.ts";
46
47
  export type { AnchorChain, AnchorCheck, AnchorCheckOptions, AnchorOptions, AnchorRecord, AnchorRun, AnchorTenantOutcome, AnchorTxOutcome } from "./anchor.ts";
47
48
  export { evmChain } from "./anchor-evm.ts";
48
49
  export type { EvmChainOptions } from "./anchor-evm.ts";
@@ -61,6 +62,7 @@ export * from "./config.ts";
61
62
  export * from "./operations.ts";
62
63
  export * from "./crypto.ts";
63
64
  export * from "./delegation.ts";
65
+ export { base58btcDecode, base58btcEncode, DID_KEY_PREFIX, didKeyOf, publicKeyFromDidKey } from "./did-key.ts";
64
66
  export * from "./approval.ts";
65
67
  export * from "./gateway.ts";
66
68
  export * from "./issue.ts";
package/dist/index.js CHANGED
@@ -14,6 +14,7 @@ export { DRAFT_WARNING, draftEgressPolicy } from "./egress-draft.js";
14
14
  export { ACS_ERROR, ACS_GUARDIAN_VERSION, ACS_METHODS, ACS_RECEIPT_KEY, ACS_STEP_FACT, ACS_VERSION, acsEntryHash, createAcsGuardian } from "./acs.js";
15
15
  export { formatPerathosReport, PERATHOS_RECEIPT_V1, perathosHead, perathosReceiptHash, verifyPerathosLog } from "./perathos.js";
16
16
  export { loadAcsGuardianConfig } from "./config.js";
17
+ export { FORM_SCRIPT_PATH, formScript } from "./door-form.js";
17
18
  export * from "./capture.js";
18
19
  export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.js";
19
20
  export { deliverMail, founderNote, PortalStore, portalHandler, readSession, readSessionVia, sendFollowUps, servePortal, signSession, SsoRefusedError, stripeRequest, verifyStripeSignature } from "./portal.js";
@@ -26,13 +27,14 @@ export { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoi
26
27
  export { adminRoutes, welcomeSheet } from "./log-admin.js";
27
28
  export { fetchWitnessKeys, Witness } from "./witness.js";
28
29
  export { Anchor, ANCHOR_CHAINS, anchorCalldata, anchorLeaf, checkAnchorRecord, resolveAnchorChain } from "./anchor.js";
29
- export { checkCompleteness, formatCompleteness, stripeSource } from "./completeness.js";
30
+ export { checkCompleteness, formatCompleteness, githubSource, stripeSource } from "./completeness.js";
30
31
  export { evmChain } from "./anchor-evm.js";
31
32
  export { checkLog, formatLogCheck } from "./log-check.js";
32
33
  export * from "./config.js";
33
34
  export * from "./operations.js";
34
35
  export * from "./crypto.js";
35
36
  export * from "./delegation.js";
37
+ export { base58btcDecode, base58btcEncode, DID_KEY_PREFIX, didKeyOf, publicKeyFromDidKey } from "./did-key.js";
36
38
  export * from "./approval.js";
37
39
  export * from "./gateway.js";
38
40
  export * from "./issue.js";
@@ -1,6 +1,6 @@
1
1
  # Completeness
2
2
 
3
- A verified receipt proves what went through the gateway. Nothing on the gateway's side can see an action that never went through it: whoever holds the Stripe key can issue a refund straight through Stripe's API. The provider's own record is the only place that action shows. `agent-custody completeness` lets an auditor check it, with a read-only key of their own.
3
+ A verified receipt proves what went through the gateway. Nothing on the gateway's side can see an action that never went through it: whoever holds the Stripe key can issue a refund straight through Stripe's API. The provider's own record is the only place that action shows. `agent-custody completeness` lets an auditor check it, with a read-only key of their own. It supports two providers: Stripe and GitHub.
4
4
 
5
5
  ## What it reports
6
6
 
@@ -8,7 +8,7 @@ For a window and a set of tools, it lists the provider's objects and matches eac
8
8
 
9
9
  | section | meaning | what to do |
10
10
  | --- | --- | --- |
11
- | provider actions with no receipt | an object the provider created in the window that no verified receipt names | the finding this command exists for: an action taken outside the gateway, or by a gateway whose receipts you were not given |
11
+ | provider actions with no receipt | an object the provider created in the window that no verified receipt names, or a second object with an id that a receipt already accounts for | the finding this command exists for: an action taken outside the gateway, or by a gateway whose receipts you were not given |
12
12
  | receipts the provider does not have | an executed receipt in the window whose object the provider has no record of | a receipt for something that did not happen at the provider, or an object in another account or mode |
13
13
  | mismatches | a matched pair whose amount, currency (ignoring case), or a beneficiary field differs | the receipt and the provider disagree about what happened |
14
14
  | one provider object, several receipts | more than one verified receipt names the same provider object; each is still compared with it | one action recorded twice, or receipts that contradict each other |
@@ -37,23 +37,54 @@ agent-custody completeness --receipts ./receipts --issuer-key gateway.pub --prin
37
37
  | --- | --- | --- |
38
38
  | `--receipts <dir>` | | the auditor's copy of the receipts directory, authorization files included |
39
39
  | `--issuer-key`, `--principal-key`, `--approval-key`, `--log-key`, `--log`, `--log-id` | | how each receipt is verified, as for `verify` |
40
- | `--provider stripe` | | the provider; Stripe is the only one so far |
41
- | `--object` | `refunds` | `refunds`, `payouts`, or `transfers` |
42
- | `--key-env NAME` | | the environment variable holding the read-only key; never a flag value |
40
+ | `--provider` | | `stripe` or `github` |
41
+ | `--object` | `refunds` for Stripe, `pushes` for GitHub | Stripe: `refunds`, `payouts`, or `transfers`. GitHub: `pushes`, `merges`, or `releases` |
42
+ | `--repo <owner>/<name>` | | GitHub only: the repository to list |
43
+ | `--key-env NAME` | | the environment variable holding the read-only key or token; never a flag value |
43
44
  | `--tool <name>` | | each tool whose executed calls create provider objects; repeatable |
44
45
  | `--since`, `--until` | | the window, ISO times; `--until` is exclusive |
45
- | `--id-path` | `id` | where the provider's object id sits in the JSON of the result's first text item; Stripe's own response uses `id` |
46
+ | `--id-path` | `id` | where the provider's object id sits in the JSON of the result's first text item, a string or an integer; Stripe's own response uses `id` |
46
47
  | `--amount-field`, `--currency-field` | `amount`, `currency` | the call arguments compared with the provider's amount and currency |
47
48
  | `--beneficiary <arg>=<field>` | | a call argument that must equal a provider field, such as `charge=charge` or `customer_id=metadata.customer_id`; repeatable |
48
49
  | `--json` | | the full report as JSON |
49
50
 
50
51
  Use a restricted Stripe key with read-only access to the objects you check. The command only lists objects: it never creates, retries, or reconciles anything. The operator's `reconcile` command is a different thing: it settles one financial operation through the gateway and writes a receipt.
51
52
 
53
+ ## GitHub
54
+
55
+ ```bash
56
+ export GITHUB_AUDIT_TOKEN=github_pat_... # a fine-grained token with read-only access to Contents, held by the auditor
57
+ agent-custody completeness --receipts ./receipts --issuer-key gateway.pub --principal-key principal.pub \
58
+ --log log.jsonl --provider github --repo acme/shop --object merges --key-env GITHUB_AUDIT_TOKEN \
59
+ --tool github.merge_pull_request --id-path sha --since 2026-10-01T00:00:00Z --until 2026-11-01T00:00:00Z
60
+ ```
61
+
62
+ Each run checks one repository and one object kind. Run the command one time for each kind that the agents can do.
63
+
64
+ | `--object` | what GitHub lists | the id that the receipt must carry | `--id-path` for GitHub's own response |
65
+ | --- | --- | --- | --- |
66
+ | `pushes` | each push, each force push, and each branch creation, from the repository's activity list | the commit that the branch moved to (`after`) | `object.sha` for a created or updated ref, `commit.sha` for a written file |
67
+ | `merges` | each merged pull request, merge queue included, from the same activity list | the commit that the branch moved to: the merge commit | `sha` |
68
+ | `releases` | each release, by its publication time, or by its creation time while it is a draft | the release's numeric id | `id` |
69
+
70
+ GitHub objects have no amount and no currency, so those comparisons do not run. `--beneficiary` compares a call argument with a field of the listed object, for example `--beneficiary tag_name=tag_name` for releases.
71
+
72
+ Limits that apply to GitHub only:
73
+
74
+ - **Deleted branches are not supported.** GitHub answers a branch deletion with an empty body, so a receipt carries no identifier that the activity list also has.
75
+ - **A branch creation is a push.** GitHub lists a push that creates a branch only as a branch creation, so `pushes` includes each branch creation. A branch that someone creates in the GitHub web interface is listed too.
76
+ - **A commit identifies a push.** The id is the commit, not the branch. A receipt accounts for one listed action with its id. When the same commit goes to a second branch, or a force push moves a branch back to it, the report lists that action as a provider action with no receipt. This is correct for an action outside the gateway. When an agent moves two branches to the same commit through the gateway, two receipts name one id: the report lists them under "one provider object, several receipts", and you compare them by hand.
77
+ - **GitHub records some pushes twice.** Entries with the same branch, the same two commits, and the same time are read as one push.
78
+ - **Releases are slow on a large repository.** GitHub gives no time order for releases, so each run reads every page of them.
79
+ - **A push of several commits has one id.** The id is the last commit, which is the commit that the tool's result must carry.
80
+ - **Draft releases.** GitHub shows a draft release only to a token with write access. A read-only token lists published releases.
81
+ - **Tags are not listed.** The activity list covers branches.
82
+
52
83
  ## Limits
53
84
 
54
85
  - **The receipts you were given.** The check proves completeness against those receipts. A second gateway, or a second receipts directory, that issued receipts you were not handed shows up as provider actions with no receipt, which is the correct finding.
55
86
  - **One provider account and mode per run.** Test-mode and live-mode objects are separate lists.
56
87
  - **The id must be readable.** A capture rule that withholds the result content also withholds the object id inside it, and such receipts are reported as unmatchable, never as matched or missing. A rule that keeps `content` in clear (`result: { mode: "digest", clear: ["content"] }`) leaves the id readable. Likewise, keep the amount, currency, and beneficiary arguments in clear, or those comparisons are reported as unmatchable. Reading values from disclosures is still to come.
57
- - **Stripe first.** Other providers, and on-chain transfers from an agent's wallet, are `ProviderSource` implementations still to come.
88
+ - **Stripe and GitHub.** Other providers, and on-chain transfers from an agent's wallet, are `ProviderSource` implementations still to come.
58
89
 
59
- In code, `checkCompleteness({ receiptsDir, verify, source, tools, sinceMs, untilMs })` returns the report, `stripeSource({ secretKey, object })` lists Stripe objects, and `formatCompleteness(report)` prints it. Example 35 runs the whole check against a stand-in for Stripe's list API.
90
+ In code, `checkCompleteness({ receiptsDir, verify, source, tools, sinceMs, untilMs })` returns the report, `stripeSource({ secretKey, object })` lists Stripe objects, `githubSource({ token, repo, object })` lists GitHub objects, and `formatCompleteness(report)` prints it. Example 35 runs the whole check against a stand-in for Stripe's list API, and example 53 runs it against a stand-in for GitHub's activity list.
@@ -178,6 +178,17 @@ RESULT: VERIFIED
178
178
 
179
179
  The refund was in the log before your handler ran. The output is cut to the lines that matter; the full report lists every check. Your receipt ids differ; take them from the `x-agent-custody-receipt` headers. The output above is from the Express app, run from this repository at the commit that added the in-process door, with the headers cut to the door's; a Next.js route's receipt says `door / fetch-route`.
180
180
 
181
+ ## A form protected by the challenge
182
+
183
+ With `challenge` in the config, a page protects a form with one line, `<script src="/.well-known/agent-custody-door/form.js" defer></script>` ([protecting a form with one line](door.md#protecting-a-form-with-one-line)). In Express the middleware answers that path itself, before it decides anything. In Next.js, add a route at `app/.well-known/agent-custody-door/form.js/route.ts`:
184
+
185
+ ```ts
186
+ import { guard } from "@/lib/door";
187
+ export const GET = () => new Response(guard.formScript(), { headers: { "content-type": "text/javascript; charset=utf-8" } });
188
+ ```
189
+
190
+ The form's own route is wrapped as any other: `export const POST = guard.route(handler)`.
191
+
181
192
  ## What your code receives
182
193
 
183
194
  An allowed request reaches your code with:
@@ -17,7 +17,7 @@ Three labels run through the table:
17
17
  | `class: "unknown"` | observed | Nothing was presented | That the arrival is a person. A browser, a crawler, and a script that sends no headers are all `unknown`. There is no `human` class, and a policy that admits `unknown` on a route admits everything on that route |
18
18
  | `grant: "verified"` | checked | As `class: "verified"` | |
19
19
  | `grant: "out-of-scope"` | checked | The grant verified and is valid, but this route is not among its scopes. `subject` is the agent it names | That the agent may do anything here. The principal did not grant this route |
20
- | `grant: "invalid"` | checked | The grant did not verify against a trusted key, did not decode, or is outside its window. `grantError` says which | Who signed it. A grant from an untrusted principal is `invalid` even when it is genuine |
20
+ | `grant: "invalid"` | checked | The grant did not verify against a trusted key, did not decode, or is outside its window; or it, or a grant above it in its chain, names its agent by a did:key that does not decode to an Ed25519 key, or that is not the key in its `agentKey`. `grantError` says which | Who signed it. A grant from an untrusted principal is `invalid` even when it is genuine. A did:key grant that is not `invalid` is `verified` without any proof that the sender holds the key: it is bearer-grade like any grant, and no request signature binds it, since a Web Bot Auth signature names an https origin, never a did:key |
21
21
  | `grant: "revoked"` | checked | The grant verified against a trusted key, and it, or a grant above it in its chain, is in the door's `revokedGrants` file; or that file could not be read, which revokes every grant until it can. `grantError` says which | That the agent misbehaved. The operator withdrew the grant, for whatever reason; the revocation file does not record why |
22
22
  | `grant: "wrong-sender"` | checked | The grant verified and is in scope, and the request is signed, verifiably, by a signature agent the grant does not name. The arrival is `claimed` | Which of the two is lying. The grant was handed on or taken; the door does not admit it as the agent it names |
23
23
  | `grant: "absent"` | observed | No grant header | |
package/docs/door.md CHANGED
@@ -67,9 +67,11 @@ There is no `human` class. The door cannot tell a person from a program that pre
67
67
 
68
68
  **A grant alone is bearer-grade; a grant under its agent's signature is bound to its sender.** The door checks the grant's signature, window, and scope. On its own, that does not show that the sender holds the agent's key. Anyone who holds the grant's bytes is that agent until the grant expires, and every verified receipt carries the grant in `delegation`, so a person who can read one receipt can replay its grant. When the request also carries a Web Bot Auth signature that the door verified, and the grant names that signature agent (`"agent": "https://crawler.example"`), the grant is bound to its sender: a thief has the grant's bytes but not the agent's signing key, and a captured signature serves one request (its nonce) for at most `maxAgeSeconds`. A grant presented under another agent's signature is `wrong-sender`, and the arrival is `claimed`. A grant with no signature, or with one that did not verify, is still verified, bearer-grade, as before, so a route that needs the binding says so in its policy: `context.facts.arrival.grant == "verified" && context.facts.arrival.signature == "verified"` holds only for a bound grant, since a mismatch makes `grant` `wrong-sender`. For bearer grants, issue door grants with short lifetimes (minutes, not days), scope them to the routes they need, bound what a route allows per call in the policy, and treat receipt files and logs as holding live credentials until those grants expire.
69
69
 
70
+ **A did:key agent.** <a id="a-did-key-agent"></a>A grant may name its agent by a [did:key](https://w3c-ccg.github.io/did-key-spec/), the identifier of its Ed25519 key, `did:key:z6Mk...`: `agent-custody grant --agent-key agent.pub --did-key ...` issues one. The door checks the identifier after the principal's signature, on the grant and on every grant above it in its chain: it must decode to an Ed25519 key, and when that grant also carries `agentKey`, that must be the same key. A parent's `agentKey` is what verified the link below it, so a parent whose did:key and `agentKey` disagree makes the arrival `claimed` too, with `link <n>` in `grantError`. An identifier longer than 100 characters is refused before it is decoded. Either failure makes the arrival `claimed` with `grant: "invalid"` and the reason in `grantError`, because the grant says two things about who the agent is, or something that names no key. A grant that checks is `verified`, as any other, with the did:key as `subject`, the Cedar principal (`Agent::"did:key:z6Mk..."`), and the receipt's agent, attested. A did:key says which key; it does not prove that the sender holds it. Alone, a did:key grant is bearer-grade like any grant, and a Web Bot Auth signature names an https origin, not a did:key, so a did:key grant under a signature is `wrong-sender`.
71
+
70
72
  **Revoking a grant.** <a id="revoking-a-grant"></a>With `revokedGrants` in the config, a grant can be withdrawn before it expires: the file is the gateway's, a JSON array of grant digests, and `agent-custody revoke --config door.json --grant grant.json` appends one. The door re-reads the file when it changes and checks every grant against it after the signature and before the window and the scope, so a running door classifies the next arrival that carries the grant as `claimed` with `grant: "revoked"`, and the Cedar principal is not the agent. Revoking a grant revokes every grant delegated from it (`grantError` says "a grant above it in its chain has been revoked"). A file that is there and cannot be read stops the door from starting; one that becomes unreadable while it runs makes every grant `revoked` until it can be read, so a broken list never lets a grant through. A missing file is an empty list. Without `revokedGrants`, a grant stands until it expires, and `check` warns when the door trusts principals.
71
73
 
72
- **Challenging a human.** The door builds no CAPTCHA. With `challenge` configured, a page in front of a protected route renders the provider's widget (Cloudflare Turnstile or hCaptcha) with `siteKey`, and sends the token the widget produced in the `challenge.header` header of its request. The door posts the token and the secret from `secretEnv` to the provider's `siteverify` endpoint, with a timeout, and records the answer as `challenge.outcome`. It adds the arrival's address as `remoteip` only with `trustProxy`, where that address is the client's; without it the socket's address may be a proxy's, and the provider would refuse a token the client solved. It never follows a redirect, which would resend the secret and the token elsewhere. To hCaptcha it also sends `siteKey` as `sitekey`: an hCaptcha secret belongs to the account, and without it a token solved on the account's easiest widget would pass on the hardest. A Turnstile secret belongs to one widget already. `success` alone does not pass: the token must have been issued on one of `hostnames`, and for `action` when one is set, or a token solved on another site that uses this site key, or for another widget, would count. At most `maxInFlight` checks wait on the provider at once; an arrival past that is `unavailable`. The token is stripped before the request is relayed, and neither the token nor the secret is recorded. A policy admits a person on a form route with
74
+ <a id="challenging-a-human"></a>**Challenging a human.** The door builds no CAPTCHA. With `challenge` configured, a page in front of a protected route renders the provider's widget (Cloudflare Turnstile or hCaptcha) with `siteKey`, and sends the token the widget produced in the `challenge.header` header of its request. The door posts the token and the secret from `secretEnv` to the provider's `siteverify` endpoint, with a timeout, and records the answer as `challenge.outcome`. It adds the arrival's address as `remoteip` only with `trustProxy`, where that address is the client's; without it the socket's address may be a proxy's, and the provider would refuse a token the client solved. It never follows a redirect, which would resend the secret and the token elsewhere. To hCaptcha it also sends `siteKey` as `sitekey`: an hCaptcha secret belongs to the account, and without it a token solved on the account's easiest widget would pass on the hardest. A Turnstile secret belongs to one widget already. `success` alone does not pass: the token must have been issued on one of `hostnames`, and for `action` when one is set, or a token solved on another site that uses this site key, or for another widget, would count. At most `maxInFlight` checks wait on the provider at once; an arrival past that is `unavailable`. The token is stripped before the request is relayed, and neither the token nor the secret is recorded. A policy admits a person on a form route with
73
75
 
74
76
  ```cedar
75
77
  permit(principal, action == Action::"refund", resource)
@@ -80,6 +82,32 @@ and a refused arrival that has not passed is told how in the 403 body: `challeng
80
82
 
81
83
  **A token serves one request.** Turnstile and hCaptcha refuse a token they have seen (`timeout-or-duplicate`, `already-seen-response`), and the door keeps no pass between requests: it does not set a cookie or remember an address. So the page must take a new token for every request it sends to a challenged route, and for every retry: call `turnstile.reset()` or `hcaptcha.reset()` after each request, and wait for the new token before the next. The door checks the token before it reads the body, so a request refused for its size (413), its path (400), or by the policy has used its token too. A second request that sends the same token is `failed`, and the person sees another 403. The outcome is a signal, not a class: a `verified` agent that also passes a challenge is still the agent its grant names, and an `unknown` arrival that passes is still `unknown`, with `challenge.outcome: "passed"` beside it. What the provider's pass means, and what it does not, is in [door signals](door-signals.md). Passkeys are not a provider here: a passkey proves possession of a credential the site registered, which is a login, not a challenge, and belongs to the origin.
82
84
 
85
+ ### Protecting a form with one line
86
+
87
+ A form on a static site cannot set a header, and the door reads the challenge token from one. With `challenge` configured, the door serves a script that bridges the two, at `/.well-known/agent-custody-door/form.js`. The page adds one line:
88
+
89
+ ```html
90
+ <script src="/.well-known/agent-custody-door/form.js" defer></script>
91
+ ```
92
+
93
+ The script is built from the challenge config: the provider, the public site key, the header, and the action. The secret is never in it. In the browser it does the following:
94
+ - It loads the provider's script (`challenges.cloudflare.com` for Turnstile, `js.hcaptcha.com` for hCaptcha) and renders the widget in every form on the page whose method is POST and whose action is on the page's own origin. A GET form, or one that posts to another site, is left alone. To protect only some forms, give a selector on the tag: `<script src="..." data-forms="#contact" defer></script>`.
95
+ - On submit it sends the form with `fetch`, the widget's token in the door's challenge header and the form's fields as the browser would send them (form-encoded, or multipart when the form says `enctype="multipart/form-data"`). A submit button's `formaction`, `formmethod`, and `formenctype` override the form's, as in a native post; a button that posts with GET, or to another site, is left to the browser. It removes the widget's own copy of the token from the fields, so the token never reaches the receipt.
96
+ - It follows the answer as a form post would. A redirect is followed; an HTML page replaces the current one; a refusal leaves the page and says why under the widget. Then it resets the widget, because [a token serves one request](#challenging-a-human).
97
+
98
+ The door decides the request as any other arrival: the token is verified with the provider, the outcome is the arrival's `challenge` signal, and the policy for the form's route decides. The site's backend gets the request with `X-Agent-Custody-Receipt`, or never hears of it. A client without JavaScript, or a bot that posts the form directly, sends no token: when the route's policy requires `context.facts.arrival.challenge.outcome == "passed"`, as it should for a protected form, that arrival gets the 403 with the way in.
99
+
100
+ What to get right:
101
+ - **`hostnames`** must name the hosts the page is served on, or a passed token fails.
102
+ - **A form handler that redirects** must answer 303 (or 302) to a URL on the same site. The script follows it as a page load. A redirect to another site fails in `fetch`, because the request carried the challenge header: the door has already relayed the form, so the page says the answer did not arrive and the form may have been sent. A 307 or 308 makes the browser send the POST again with the same token, which the provider refuses as a duplicate.
103
+ - **Not covered, and refused rather than let through:** a form added to the page after the script ran; a form sent from code with `form.submit()`, which fires no submit event; and a form the script skips because its own method is GET or its own action is on another site, which gets no widget, so a button on it with `formmethod="post"` and an action on this site posts with no token. Each posts natively, and the policy refuses it with a bare 403.
104
+ - **A button that posts natively** (GET, or to another site) takes no token with it: the script disables the widget's hidden token fields first, so hCaptcha's live token does not reach another site's body or a query string.
105
+ - **A Content-Security-Policy** must allow the provider's script and frame (`script-src` and `frame-src` for the hosts above), and the script itself (`script-src 'self'` when the door serves the site).
106
+ - **In authz mode** the proxy serves the site, so route `/.well-known/agent-custody-door/form.js` to the door (`location = /.well-known/agent-custody-door/form.js { proxy_pass http://door:8780; }`).
107
+ - **In-process**, the Express middleware serves the script itself; a Next.js site adds a route that returns `guard.formScript()` ([the door in your Node app](door-middleware.md#a-form-protected-by-the-challenge)).
108
+
109
+ The tests run the script in a DOM stand-in against a real door and a stand-in provider. By hand, with Cloudflare's test keys below and a static page, the widget rendered and passed in a browser, the form reached the site with its receipt id, and a POST without the script was refused 403. The script is served with a query string as well (`form.js?v=2`), so a cache-busting habit does not break it. Tutorial: [54-door-form.ts](../examples/54-door-form.ts).
110
+
83
111
  ### A run against Turnstile's test keys
84
112
 
85
113
  The tests stub `siteverify`. This run calls the real one once. Cloudflare publishes [test keys](https://developers.cloudflare.com/turnstile/troubleshooting/testing/) that need no account: the site key `1x00000000000000000000AA`, the secret `1x0000000000000000000000000000000AA` (validation always succeeds), the secret `2x0000000000000000000000000000000AA` (validation always fails), and the dummy token `XXXX.DUMMY.TOKEN.XXXX`. The test secrets accept only the dummy token. Cloudflare answers a test key with the hostname `example.com`, so the config names that hostname. These secrets are public. A real secret still goes only into the environment, never into the config or a flag.
@@ -20,7 +20,7 @@ jobs:
20
20
  runs-on: ubuntu-latest
21
21
  steps:
22
22
  - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
23
- - uses: svayatta/agent-custody@<commit sha of the release> # 0.16.9
23
+ - uses: svayatta/agent-custody@<commit sha of the release> # 0.16.10
24
24
  with:
25
25
  path: .custody/receipts
26
26
  issuer-key: .custody/keys/agent.pub
@@ -37,7 +37,7 @@ Pin the action to the commit of a release, as you pin every other action. A movi
37
37
  | `principal-key` | the public key files of the principals whose grants a gateway receipt carries, one path on each line; SDK and Claude Code hook receipts need none | |
38
38
  | `log-url` | the URL of the log; the action fetches the log key from it (`verify --log-url`) | |
39
39
  | `log-id` | the id that every tree head must name (`verify --log-id`) | |
40
- | `version` | the `@agent-custody/receipts` version that `npx` runs | `0.16.9` |
40
+ | `version` | the `@agent-custody/receipts` version that `npx` runs | `0.16.10` |
41
41
  | `github-token` | a token that can write pull request comments; an empty value writes the job summary only | `github.token` |
42
42
  | `comment-author` | the login of the account that `github-token` posts as; the action edits only a comment from this account | `github-actions[bot]` |
43
43
 
@@ -53,7 +53,7 @@ Each row names the attacker, the move, the defence, and whether the defence is a
53
53
  | Rewrite a receipt after the fact | The receipt's envelope is signed by the gateway key, which the operator holds, so the signature alone does not stop this. What stops it is the log: the leaf hash of the original envelope is in a tree whose head the log signed, and a rewritten receipt has a different hash with no inclusion proof. | evidence, with a remote log; deployment, with a local log the operator can rewrite |
54
54
  | Drop a receipt | The log's tree only grows, and consistency proofs between any two heads show nothing was removed. A receipt the operator never logged never existed as evidence, which is the point of `precommit` for consequential calls: the authorization leaf goes in before the action. [Strict mode](usage.md#strict-mode) does that for every call, with a remote hash-only log and no outbox, and its receipts say so, so a verifier can require it; a modified gateway can still claim strict mode. | evidence for logged receipts; withheld calls for pre-committed tools, and for every call under strict mode |
55
55
  | Forge a receipt for an action that never happened | Nothing in the log stops the operator logging a fabricated receipt; the log commits to existence, not truth. What limits it: the upstream's signature over the result when the upstream signs, provider attestations where the provider delivers them, and the principal's signature on the grant. A forged receipt for a signing upstream fails its `upstream` checks. | evidence, where the upstream signs; otherwise the operator's word |
56
- | Act outside the gateway with the provider's own credentials | Nothing on the gateway's side sees it. `agent-custody completeness` lists the provider's objects with the auditor's own read-only key and reports each one that no verified receipt names; a forged receipt file fails verification and cannot cover for it. | evidence, for a provider that lists its objects (Stripe today) |
56
+ | Act outside the gateway with the provider's own credentials | Nothing on the gateway's side sees it. `agent-custody completeness` lists the provider's objects with the auditor's own read-only key and reports each one that no verified receipt names; a forged receipt file fails verification and cannot cover for it. | evidence, for a provider that lists its objects (Stripe and GitHub today) |
57
57
  | Replace the policy and claim a different one decided | The receipt carries the sha256 of the policy text; a verifier with the policy file can check it, and a policy change is a different digest in every later receipt. | evidence |
58
58
  | Produce a second, cleaner history | With a remote log, both histories would need heads signed by the log's key at the same size with different roots; the checkpoints host and the witness make that detectable. With a local log, a copy taken earlier by someone else is the only defence. | evidence with a witnessed remote log |
59
59
  | Erase what an agent believed | `forget` erases the value and leaves a digest keyed by a forget key held outside the ledger, so the erasure is provable without the value. A forget with `none` leaves nothing and the custody pack says so. | evidence |
package/docs/tutorials.md CHANGED
@@ -61,6 +61,9 @@ Suggested reading order is the numbering. Output lands in `examples-out/`, which
61
61
  | 49 | the door behind stock nginx or Envoy: authz checks instead of relaying | [49-door-authz.ts](../examples/49-door-authz.ts) | the door with `authz: true` answers checks as nginx `auth_request` sends them (`X-Original-Method`, `X-Original-URI`): a catalogue read 200 and an unknown refund 403; a verified agent's refund is committed to the log before the 200; a check that names no original request is refused 400 with no receipt; each receipt verifies and its report says it records the decision, not the origin's answer. `deploy/door/demo.sh` runs the real nginx and Envoy | `src/door.ts`, `src/config.ts` |
62
62
  | 50 | the refund pilot in one command: `init refunds`, then `--run` | [50-init-refunds.ts](../examples/50-init-refunds.ts) | keys, a grant, a refund policy and a Stripe gateway config written in one call; a test payment, an over-limit refund refused before Stripe, a refund through the gateway, a retry refused because the gateway finds the first refund, and the receipt verified, against a stand-in Stripe |
63
63
  | 52 | the door asks a partner detection engine, and the engine signs its verdict | [52-door-partner-verdict.ts](../examples/52-door-partner-verdict.ts) | a stub engine (`scripts/fake-partner.ts`) signs a verdict for each arrival's receipt and route; a browser's `human` verdict is relayed and a bot's refused by a policy on `context.facts.partner`; the receipt carries the verdict as an attested fact and verifies with the engine's key as an upstream key, and not without it; a verdict replayed from another arrival is refused with 503, and so is an arrival when the engine times out (`onFailure: "deny"`), even on a route the policy alone would allow | `src/door-partner.ts`, `src/door.ts` |
64
+ | 53 | completeness from the provider's side, for GitHub | [53-completeness-github.ts](../examples/53-completeness-github.ts) | two pull requests merged through a wrapped tool and a push made with another token; the auditor lists the repository's activity with a read-only token, matches the two merges to verified receipts, and reports the push as an action with no receipt |
65
+ | 54 | the form protector: one script tag puts the door's challenge in front of a plain HTML form | [54-door-form.ts](../examples/54-door-form.ts) | a static site's contact form behind the door; the door serves the script built from its challenge config, without the secret; a direct post with no token is refused and never reaches the site; a post with a passing token reaches it with the receipt id; both receipts verify |
66
+ | 55 | a grant that names its agent by a did:key, checked at the door | [55-did-key-grant.ts](../examples/55-did-key-grant.ts) | an agent's Ed25519 key and its did:key; a principal's grant for the did:key is verified at the door; a garbled did:key, and a grant whose agentKey is another key, are claimed; nothing presented is unknown; every receipt verifies |
64
67
 
65
68
  ## How policies are defined, in one paragraph
66
69
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-custody/receipts",
3
- "version": "0.16.9",
3
+ "version": "0.16.10",
4
4
  "mcpName": "io.github.svayatta/agent-custody",
5
5
  "description": "Proof of what your AI agents did. Give your agents real power, without losing control of them: signed, verifiable receipts for tool calls, an MCP gateway with Cedar or Rego policy, and a Merkle transparency log.",
6
6
  "license": "Apache-2.0",