@agent-custody/receipts 0.16.7 → 0.16.8

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
@@ -72,6 +72,8 @@ const bundle = JSON.parse(readFileSync("receipts/<id>.json", "utf8"));
72
72
  verifyBundle(bundle, { issuerKeys: [loadPublicKey("keys/app.pub")], logFile: "log.jsonl" }).ok; // true
73
73
  ```
74
74
 
75
+ To put the gateway in front of Stripe refunds instead, with a refund policy and a test-mode refund verified end to end, run `npx -y @agent-custody/receipts init refunds --dir refunds`, then the same with `--run` ([getting started](../../site/guide/getting-started.md#stripe-refunds-in-one-command)).
76
+
75
77
  To see first what it would have caught, `npx -y @agent-custody/receipts audit-sessions --since 7d` reads your past Claude Code transcripts against the starter policy and writes nothing ([docs/sdk.md](docs/sdk.md#before-you-install-your-past-sessions)). For your own Claude Code sessions, one command does the whole setup (key, config in observe mode, starter deny policy, hooks), and `agent-custody report` lists the calls the policy would have denied: `npm install -g @agent-custody/receipts`, then `agent-custody init claude-code`, then see [docs/sdk.md](docs/sdk.md#claude-code).
76
78
 
77
79
  Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the Vercel AI SDK, LangChain, OpenClaw, DeepSeek Harness, Hermes and Google ADK, are in [docs/sdk.md](docs/sdk.md). To enforce rather than record, put the gateway between the agent and its tools: `npx @agent-custody/receipts gateway --config gateway.json`, set up in [docs/usage.md](docs/usage.md); between an agent and the agents it delegates to over A2A, `--a2a` serves the gateway as an A2A agent itself. The gateway is listed in the [MCP Registry](https://registry.modelcontextprotocol.io/) as `io.github.svayatta/agent-custody`; its entry is [server.json](server.json), published after each npm release by running the `mcp-registry` workflow from the Actions tab (GitHub OIDC, no token).
package/dist/cli.js CHANGED
@@ -38,6 +38,7 @@ import { TREEHEAD_TYPE } from "./receipt.js";
38
38
  import { MerkleLog } from "./log.js";
39
39
  import { createSdkIssuer } from "./sdk/index.js";
40
40
  import { initClaudeCode } from "./claude-init.js";
41
+ import { initRefunds, runRefunds, STRIPE_KEY_ENV } from "./refunds-init.js";
41
42
  import { denyReport, formatDenyReport } from "./deny-report.js";
42
43
  import { fileURLToPath } from "node:url";
43
44
  import { handleHookEvent } from "./sdk/claude.js";
@@ -119,6 +120,10 @@ const USAGE = `agent-custody <command>
119
120
  init claude-code [--dir <dir>] [--user] [--enforce] [--log-url <url> [--log-id <id>] [--log-token-env NAME] [--log-key <pub>]]
120
121
  one command for your own Claude Code sessions: an agent key, sdk.json in observe mode, a starter deny
121
122
  policy, and the three hooks in .claude/settings.local.json (--user: ~/.claude/settings.json). Safe to run twice
123
+ init refunds [--dir agent-custody-refunds] [--limit 5000] [--currency gbp] [--ttl-hours 24] [--run]
124
+ a gateway in front of Stripe refunds: keys, a grant, a refund policy, and a config. --run (with
125
+ STRIPE_SECRET_KEY, test mode only) makes a test payment, refunds it through the gateway, has an
126
+ over-limit refund refused, and verifies the receipt
122
127
  audit-sessions [--since 7d|24h|<date>|all] [--dir <claude projects dir>] [--policy <file.cedar>] [--counts] [--json]
123
128
  a read-only preview: which of your past Claude Code tool calls the policy would have denied, from the transcripts; writes nothing
124
129
  report --config <sdk.json> the calls that the policy would have denied, from the receipts: tool, command or path, rule, receipt id;
@@ -439,8 +444,32 @@ async function main(argv) {
439
444
  }
440
445
  case "init": {
441
446
  const [target, ...args] = rest;
447
+ if (target === "refunds") {
448
+ const { values } = parseArgs({
449
+ args,
450
+ options: {
451
+ dir: { type: "string", default: "agent-custody-refunds" },
452
+ limit: { type: "string", default: "5000" },
453
+ currency: { type: "string", default: "gbp" },
454
+ "ttl-hours": { type: "string", default: "24" },
455
+ run: { type: "boolean", default: false },
456
+ "stripe-url": { type: "string" },
457
+ },
458
+ });
459
+ if (!existsSync(join(resolve(values.dir), "gateway.json"))) {
460
+ initRefunds({ dir: values.dir, limit: Number(values.limit), currency: values.currency, ttlHours: Number(values["ttl-hours"]), ...(values["stripe-url"] ? { stripeUrl: values["stripe-url"] } : {}) });
461
+ }
462
+ else if (!values.run)
463
+ throw new Error(`${join(resolve(values.dir), "gateway.json")} already exists; add --run to make a test refund with it, or remove ${values.dir}`);
464
+ if (!values.run) {
465
+ console.log(`\nNext: export ${STRIPE_KEY_ENV}=sk_test_... and run agent-custody init refunds --dir ${values.dir} --run`);
466
+ return 0;
467
+ }
468
+ const result = await runRefunds({ dir: values.dir });
469
+ return result.verified && result.refused ? 0 : 1;
470
+ }
442
471
  if (target !== "claude-code")
443
- throw new Error("init needs a target: init claude-code");
472
+ throw new Error("init needs a target: init claude-code or init refunds");
444
473
  const { values } = parseArgs({
445
474
  args,
446
475
  options: {
package/dist/config.d.ts CHANGED
@@ -14,6 +14,7 @@ declare const RestToolSchema: z.ZodObject<{
14
14
  path: z.ZodString;
15
15
  query: z.ZodOptional<z.ZodArray<z.ZodString>>;
16
16
  body: z.ZodDefault<z.ZodEnum<{
17
+ form: "form";
17
18
  json: "json";
18
19
  none: "none";
19
20
  }>>;
@@ -40,6 +41,7 @@ declare const RestUpstreamSchema: z.ZodObject<{
40
41
  path: z.ZodString;
41
42
  query: z.ZodOptional<z.ZodArray<z.ZodString>>;
42
43
  body: z.ZodDefault<z.ZodEnum<{
44
+ form: "form";
43
45
  json: "json";
44
46
  none: "none";
45
47
  }>>;
@@ -83,6 +85,7 @@ declare const UpstreamSchema: z.ZodUnion<readonly [z.ZodObject<{
83
85
  path: z.ZodString;
84
86
  query: z.ZodOptional<z.ZodArray<z.ZodString>>;
85
87
  body: z.ZodDefault<z.ZodEnum<{
88
+ form: "form";
86
89
  json: "json";
87
90
  none: "none";
88
91
  }>>;
@@ -187,6 +190,7 @@ export declare const GatewayConfigSchema: z.ZodObject<{
187
190
  path: z.ZodString;
188
191
  query: z.ZodOptional<z.ZodArray<z.ZodString>>;
189
192
  body: z.ZodDefault<z.ZodEnum<{
193
+ form: "form";
190
194
  json: "json";
191
195
  none: "none";
192
196
  }>>;
@@ -229,6 +233,7 @@ export declare const GatewayConfigSchema: z.ZodObject<{
229
233
  path: z.ZodString;
230
234
  query: z.ZodOptional<z.ZodArray<z.ZodString>>;
231
235
  body: z.ZodDefault<z.ZodEnum<{
236
+ form: "form";
232
237
  json: "json";
233
238
  none: "none";
234
239
  }>>;
package/dist/config.js CHANGED
@@ -22,8 +22,8 @@ const RestToolSchema = z.object({
22
22
  path: z.string().min(1),
23
23
  /** argument names sent as query parameters, when the default placement is not wanted */
24
24
  query: z.array(z.string().min(1)).optional(),
25
- /** "none" sends no body even on POST */
26
- body: z.enum(["json", "none"]).default("json"),
25
+ /** "none" sends no body even on POST; "form" sends application/x-www-form-urlencoded, nesting as `a[b]` and `a[0]`, which Stripe's v1 API expects */
26
+ body: z.enum(["json", "form", "none"]).default("json"),
27
27
  /** The gateway supplies its durable operation key in this header; callers cannot choose or override it. */
28
28
  idempotencyHeader: z.string().regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/).optional(),
29
29
  /** the JSON Schema the agent sees; default accepts any object */
package/dist/policy.d.ts CHANGED
@@ -32,4 +32,15 @@ export declare function policyDigest(policyText: string): string;
32
32
  * returned, and the evaluation is a deny with that error.
33
33
  */
34
34
  export declare function reservedCedarForm(value: unknown, path?: string): string | null;
35
+ /**
36
+ * A fact as Cedar can read it. JSON null has no Cedar form and refuses the whole context, and real APIs return nulls for
37
+ * unset fields, so a null field is left out and reads as absent (`has` is false). A null inside a list cannot be left
38
+ * out without moving the elements after it, which would change what `list[0]` or `contains` means, so it is an error:
39
+ * the returned path, and the call is denied. Only Cedar needs this; Rego and OPA read null as it is.
40
+ */
41
+ export declare function cedarFactValue(value: unknown, path?: string): {
42
+ value: unknown;
43
+ } | {
44
+ nullAt: string;
45
+ };
35
46
  export declare function evaluate(policyText: string, req: PolicyRequest): PolicyDecision;
package/dist/policy.js CHANGED
@@ -62,6 +62,39 @@ export function reservedCedarForm(value, path = "args") {
62
62
  }
63
63
  return null;
64
64
  }
65
+ /**
66
+ * A fact as Cedar can read it. JSON null has no Cedar form and refuses the whole context, and real APIs return nulls for
67
+ * unset fields, so a null field is left out and reads as absent (`has` is false). A null inside a list cannot be left
68
+ * out without moving the elements after it, which would change what `list[0]` or `contains` means, so it is an error:
69
+ * the returned path, and the call is denied. Only Cedar needs this; Rego and OPA read null as it is.
70
+ */
71
+ export function cedarFactValue(value, path = "facts") {
72
+ if (Array.isArray(value)) {
73
+ const out = [];
74
+ for (let i = 0; i < value.length; i++) {
75
+ if (value[i] === null)
76
+ return { nullAt: `${path}[${i}]` };
77
+ const r = cedarFactValue(value[i], `${path}[${i}]`);
78
+ if ("nullAt" in r)
79
+ return r;
80
+ out.push(r.value);
81
+ }
82
+ return { value: out };
83
+ }
84
+ if (value && typeof value === "object") {
85
+ const out = {};
86
+ for (const [k, v] of Object.entries(value)) {
87
+ if (v === null)
88
+ continue;
89
+ const r = cedarFactValue(v, `${path}.${k}`);
90
+ if ("nullAt" in r)
91
+ return r;
92
+ out[k] = r.value;
93
+ }
94
+ return { value: out };
95
+ }
96
+ return { value };
97
+ }
65
98
  /** Policy sets kept parsed, most recently used last. A reload or a second gateway in the process takes another slot. */
66
99
  const PARSED_SLOTS = 8;
67
100
  const parsed = new Map();
@@ -110,11 +143,18 @@ export function evaluate(policyText, req) {
110
143
  return { decision: "deny", reasons: [], errors: [`argument ${reserved} uses a reserved Cedar form; arguments are data, never entities or extension values`], policyDigest: digest };
111
144
  if (policy.parseErrors.length > 0)
112
145
  return { decision: "deny", reasons: [], errors: [...policy.parseErrors], policyDigest: digest };
146
+ let context = req.context;
147
+ if (context.facts !== undefined) {
148
+ const facts = cedarFactValue(context.facts);
149
+ if ("nullAt" in facts)
150
+ return { decision: "deny", reasons: [], errors: [`${facts.nullAt} is null inside a list, which Cedar cannot read; the call is denied rather than the list compacted`], policyDigest: digest };
151
+ context = { ...context, facts: facts.value };
152
+ }
113
153
  const answer = cedar.statefulIsAuthorized({
114
154
  principal: { type: "Agent", id: req.agentId },
115
155
  action: { type: "Action", id: req.tool },
116
156
  resource: { type: "Tool", id: req.tool },
117
- context: req.context,
157
+ context: context,
118
158
  preparsedPolicySetId: policy.slot,
119
159
  entities: [],
120
160
  });
@@ -0,0 +1,37 @@
1
+ export declare const STRIPE_BEARER_ENV = "AGENT_CUSTODY_STRIPE_BEARER";
2
+ export declare const STRIPE_KEY_ENV = "STRIPE_SECRET_KEY";
3
+ export interface InitRefundsOptions {
4
+ dir: string;
5
+ /** the largest refund the policy permits, in minor units */
6
+ limit: number;
7
+ /** ISO 4217, lowercase as Stripe writes it */
8
+ currency: string;
9
+ ttlHours: number;
10
+ /** where Stripe is; a stand-in in tests */
11
+ stripeUrl?: string;
12
+ print?: (line: string) => void;
13
+ }
14
+ export declare function refundsPolicy(limit: number, currency: string): string;
15
+ /** Writes keys, a grant, the policy, and a gateway config into `dir`. Refuses a directory that already holds a config. */
16
+ export declare function initRefunds(o: InitRefundsOptions): {
17
+ dir: string;
18
+ configFile: string;
19
+ };
20
+ export interface RunRefundsOptions {
21
+ dir: string;
22
+ /** default process.env; holds STRIPE_SECRET_KEY */
23
+ env?: Record<string, string | undefined>;
24
+ fetch?: typeof fetch;
25
+ print?: (line: string) => void;
26
+ }
27
+ export interface RunRefundsResult {
28
+ paymentIntent: string;
29
+ refundReceipt: string;
30
+ refused: boolean;
31
+ verified: boolean;
32
+ }
33
+ /**
34
+ * Makes a test-mode payment, refunds part of it through the gateway, asks for a refund over the limit, and verifies the
35
+ * refund's receipt. Refuses any key that is not a Stripe test-mode key, so it cannot move real money.
36
+ */
37
+ export declare function runRefunds(o: RunRefundsOptions): Promise<RunRefundsResult>;
@@ -0,0 +1,193 @@
1
+ // `agent-custody init refunds`: a working gateway in front of Stripe refunds in one command, and with `--run`, one
2
+ // test-mode refund through it, one refused, and the receipt verified. It is the pilot in a box: what a team needs to see
3
+ // an agent's refund decided by their policy, sent with a key the agent never holds, and checked by someone else.
4
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { join, resolve } from "node:path";
6
+ import { loadConfig } from "./config.js";
7
+ import { generateKeyPair, loadPublicKey, writeKeyPair } from "./crypto.js";
8
+ import { createDelegation } from "./delegation.js";
9
+ import { createGateway, RECEIPT_META_KEY } from "./gateway.js";
10
+ import { formEncode } from "./rest.js";
11
+ import { formatReport, verifyBundle } from "./verify.js";
12
+ export const STRIPE_BEARER_ENV = "AGENT_CUSTODY_STRIPE_BEARER";
13
+ export const STRIPE_KEY_ENV = "STRIPE_SECRET_KEY";
14
+ const AGENT = "refund-agent";
15
+ const PRINCIPAL = "pilot-principal";
16
+ export function refundsPolicy(limit, currency) {
17
+ return `// The agent may read a payment and its refunds, so the gateway can look them up before a refund.
18
+ permit(principal, action == Action::"stripe.payment_intent", resource);
19
+ permit(principal, action == Action::"stripe.refunds", resource);
20
+
21
+ // One refund per payment, of more than 0 and at most ${limit} (minor units, ${currency.toUpperCase()}), only against a
22
+ // payment the gateway itself looked up as succeeded in this currency, never more than it received, and only while the
23
+ // gateway's own lookup finds no refund on it yet. A retry after a lost response finds the first refund and is denied, so
24
+ // it cannot pay twice. context.facts comes from the gateway's own calls to Stripe, never from the agent.
25
+ @reason("one refund per payment, up to the limit, for a payment the gateway saw succeed")
26
+ permit(principal, action == Action::"stripe.refund", resource)
27
+ when {
28
+ context.args has amount &&
29
+ context.args.amount > 0 &&
30
+ context.args.amount <= ${limit} &&
31
+ context.facts has payment &&
32
+ context.facts.payment.status == "succeeded" &&
33
+ context.facts.payment.currency == "${currency}" &&
34
+ context.args.amount <= context.facts.payment.amount_received &&
35
+ context.facts has refunds &&
36
+ context.facts.refunds.data.isEmpty()
37
+ };
38
+ `;
39
+ }
40
+ /** Writes keys, a grant, the policy, and a gateway config into `dir`. Refuses a directory that already holds a config. */
41
+ export function initRefunds(o) {
42
+ const print = o.print ?? ((l) => console.log(l));
43
+ if (!Number.isSafeInteger(o.limit) || o.limit <= 0)
44
+ throw new Error("--limit is a positive whole number of minor units, e.g. 5000 for 50.00");
45
+ if (!/^[a-z]{3}$/.test(o.currency))
46
+ throw new Error("--currency is a three-letter code such as gbp");
47
+ if (!(o.ttlHours > 0))
48
+ throw new Error("--ttl-hours must be positive");
49
+ const dir = resolve(o.dir);
50
+ const configFile = join(dir, "gateway.json");
51
+ if (existsSync(configFile))
52
+ throw new Error(`${configFile} already exists; remove ${dir} to start again, or run with --run`);
53
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
54
+ const gateway = writeKeyPair(generateKeyPair(), join(dir, "keys"), "gateway");
55
+ const principalKp = generateKeyPair();
56
+ const principal = writeKeyPair(principalKp, join(dir, "keys"), "principal");
57
+ print(`1. keys: the gateway's (${gateway.pubFile}) and the principal's, who signs the agent's grant`);
58
+ const now = Date.now();
59
+ const grant = createDelegation(principalKp, {
60
+ version: "0.1",
61
+ principal: PRINCIPAL,
62
+ agent: AGENT,
63
+ scopes: ["stripe.payment_intent", "stripe.refunds", "stripe.refund"],
64
+ issuedAt: new Date(now - 1000).toISOString(),
65
+ expiresAt: new Date(now + o.ttlHours * 3600_000).toISOString(),
66
+ });
67
+ writeFileSync(join(dir, "grant.json"), JSON.stringify(grant, null, 2));
68
+ print(`2. grant.json: ${PRINCIPAL} lets ${AGENT} read payments and their refunds, and refund them, for ${o.ttlHours} hours`);
69
+ writeFileSync(join(dir, "policy.cedar"), refundsPolicy(o.limit, o.currency));
70
+ print(`3. policy.cedar: one refund per payment, up to ${o.limit} ${o.currency.toUpperCase()} minor units, for a payment the gateway saw succeed`);
71
+ const config = {
72
+ identity: { keyFile: "keys/gateway.key" },
73
+ upstream: {
74
+ rest: {
75
+ baseUrl: o.stripeUrl ?? "https://api.stripe.com",
76
+ headerEnv: { authorization: STRIPE_BEARER_ENV },
77
+ tools: [
78
+ { name: "stripe.payment_intent", method: "GET", path: "/v1/payment_intents/{id}", description: "Read a payment", inputSchema: { type: "object", properties: { id: { type: "string" } }, required: ["id"] } },
79
+ { name: "stripe.refunds", method: "GET", path: "/v1/refunds", description: "List a payment's refunds", inputSchema: { type: "object", properties: { payment_intent: { type: "string" } }, required: ["payment_intent"] } },
80
+ {
81
+ name: "stripe.refund", method: "POST", path: "/v1/refunds", body: "form", description: "Refund a payment, amount in minor units",
82
+ inputSchema: { type: "object", properties: { payment_intent: { type: "string" }, amount: { type: "integer" }, reason: { type: "string" } }, required: ["payment_intent", "amount"] },
83
+ },
84
+ ],
85
+ },
86
+ },
87
+ grantFile: "grant.json",
88
+ trustedPrincipalKeys: ["keys/principal.pub"],
89
+ policyFile: "policy.cedar",
90
+ facts: [
91
+ { name: "payment", tool: "stripe.payment_intent", args: { id: "$args.payment_intent" }, forTools: ["stripe.refund"] },
92
+ { name: "refunds", tool: "stripe.refunds", args: { payment_intent: "$args.payment_intent" }, forTools: ["stripe.refund"] },
93
+ ],
94
+ precommit: ["stripe.refund"],
95
+ receiptsDir: "receipts",
96
+ logFile: "log.jsonl",
97
+ };
98
+ writeFileSync(configFile, JSON.stringify(config, null, 2));
99
+ print(`4. gateway.json: Stripe as the upstream, the key read from ${STRIPE_BEARER_ENV}, each refund authorized in the log before it is sent`);
100
+ print(` principal key: ${principal.pubFile}`);
101
+ return { dir, configFile };
102
+ }
103
+ /**
104
+ * Makes a test-mode payment, refunds part of it through the gateway, asks for a refund over the limit, and verifies the
105
+ * refund's receipt. Refuses any key that is not a Stripe test-mode key, so it cannot move real money.
106
+ */
107
+ export async function runRefunds(o) {
108
+ const env = o.env ?? process.env;
109
+ const f = o.fetch ?? fetch;
110
+ const print = o.print ?? ((l) => console.log(l));
111
+ const dir = resolve(o.dir);
112
+ const configFile = join(dir, "gateway.json");
113
+ if (!existsSync(configFile))
114
+ throw new Error(`${configFile} not found; run init refunds --dir ${o.dir} first`);
115
+ const key = env[STRIPE_KEY_ENV];
116
+ if (!key)
117
+ throw new Error(`${STRIPE_KEY_ENV} is not set: export a Stripe test-mode secret key (sk_test_...)`);
118
+ if (!/^(sk|rk)_test_/.test(key))
119
+ throw new Error(`${STRIPE_KEY_ENV} is not a test-mode key; init refunds --run only runs in Stripe test mode`);
120
+ const cfg = loadConfig(configFile);
121
+ const rest = cfg.upstream && "rest" in cfg.upstream ? cfg.upstream.rest : undefined;
122
+ if (!rest)
123
+ throw new Error(`${configFile} has no REST upstream; it was not written by init refunds`);
124
+ const limit = Number(/context\.args\.amount <= (\d+)/.exec(readFileSync(cfg.policyFile, "utf8"))?.[1]);
125
+ const currency = /context\.facts\.payment\.currency == "([a-z]{3})"/.exec(readFileSync(cfg.policyFile, "utf8"))?.[1];
126
+ if (!Number.isSafeInteger(limit) || !currency)
127
+ throw new Error(`${cfg.policyFile}: cannot read the limit and currency init refunds wrote`);
128
+ const payment = await stripeForm(f, rest.baseUrl, key, "/v1/payment_intents", {
129
+ amount: limit * 2,
130
+ currency,
131
+ payment_method: "pm_card_visa",
132
+ confirm: true,
133
+ automatic_payment_methods: { enabled: true, allow_redirects: "never" },
134
+ });
135
+ const pi = String(payment.id);
136
+ print(`5. a test payment of ${limit * 2} ${currency.toUpperCase()} minor units, made directly with Stripe: ${pi} (${String(payment.status)})`);
137
+ const previous = process.env[STRIPE_BEARER_ENV];
138
+ process.env[STRIPE_BEARER_ENV] = `Bearer ${key}`;
139
+ const gw = await createGateway(cfg);
140
+ try {
141
+ const receiptOf = (r) => {
142
+ const id = String(r._meta?.[RECEIPT_META_KEY]);
143
+ const bundle = JSON.parse(readFileSync(join(cfg.receiptsDir, `${id}.json`), "utf8"));
144
+ return { id, bundle, p: JSON.parse(Buffer.from(bundle.envelope.payload, "base64").toString()).predicate };
145
+ };
146
+ // A refusal counts only when the receipt shows the policy denied it and nothing was sent; a Stripe error is not one.
147
+ const refusedByPolicy = (p) => p.policy?.decision === "deny" && p.execution.status === "denied";
148
+ const over = receiptOf(await gw.handleCall({ name: "stripe.refund", arguments: { payment_intent: pi, amount: limit + 1 } }));
149
+ print(`6. the agent asks for ${limit + 1}, over the limit: ${refusedByPolicy(over.p) ? "refused by policy, and never sent to Stripe" : `not refused by policy (${over.p.execution.status})`}; receipt ${over.id}`);
150
+ const ok = await gw.handleCall({ name: "stripe.refund", arguments: { payment_intent: pi, amount: limit } });
151
+ const refund = receiptOf(ok);
152
+ const receiptId = refund.id;
153
+ const text = ok.content[0]?.text ?? "";
154
+ print(`7. the agent asks for ${limit}: ${refund.p.execution.status === "executed" ? "refunded" : "not done: " + text}; receipt ${receiptId}`);
155
+ const again = receiptOf(await gw.handleCall({ name: "stripe.refund", arguments: { payment_intent: pi, amount: limit } }));
156
+ print(`8. the agent retries the same refund, as after a lost response: ${refusedByPolicy(again.p) ? "refused, because the gateway found the first refund" : `not refused by policy (${again.p.execution.status})`}; receipt ${again.id}`);
157
+ const bundle = refund.bundle;
158
+ const v = verifyBundle(bundle, {
159
+ issuerKeys: [loadPublicKey(cfg.identity.keyFile.replace(/\.key$/, ".pub"))],
160
+ principalKeys: cfg.trustedPrincipalKeys.map(loadPublicKey),
161
+ logFile: cfg.logFile,
162
+ });
163
+ print(`9. the refund's receipt, checked with the gateway's and the principal's public keys and the log: ${v.ok ? "VALID" : "INVALID"}`);
164
+ for (const line of formatReport(v).split("\n").filter((l) => /^RESULT|^tool|^execution|^policy|^authorization/.test(l)))
165
+ print(` ${line}`);
166
+ const verified = v.ok && refund.p.execution.status === "executed";
167
+ const refused = refusedByPolicy(over.p) && refusedByPolicy(again.p);
168
+ if (verified && refused) {
169
+ print(`\nRun the gateway for an agent: export ${STRIPE_BEARER_ENV}="Bearer $${STRIPE_KEY_ENV}" and agent-custody gateway --config ${configFile}`);
170
+ print(`Anyone can check a receipt: agent-custody verify ${join(cfg.receiptsDir, `${receiptId}.json`)} --issuer-key ${cfg.identity.keyFile.replace(/\.key$/, ".pub")} --principal-key ${cfg.trustedPrincipalKeys[0]} --log ${cfg.logFile}`);
171
+ }
172
+ return { paymentIntent: pi, refundReceipt: receiptId, refused, verified };
173
+ }
174
+ finally {
175
+ await gw.close();
176
+ if (previous === undefined)
177
+ delete process.env[STRIPE_BEARER_ENV];
178
+ else
179
+ process.env[STRIPE_BEARER_ENV] = previous;
180
+ }
181
+ }
182
+ async function stripeForm(f, base, key, path, body) {
183
+ const res = await f(new URL(path.replace(/^\//, ""), base.endsWith("/") ? base : `${base}/`), {
184
+ method: "POST",
185
+ headers: { authorization: `Bearer ${key}`, "content-type": "application/x-www-form-urlencoded" },
186
+ body: formEncode(body),
187
+ signal: AbortSignal.timeout(30_000),
188
+ });
189
+ const json = (await res.json().catch(() => ({})));
190
+ if (!res.ok)
191
+ throw new Error(`Stripe ${path}: HTTP ${res.status} ${JSON.stringify(json.error?.message ?? json)}`);
192
+ return json;
193
+ }
package/dist/rest.d.ts CHANGED
@@ -17,6 +17,8 @@ export interface RestOptions {
17
17
  /** the environment the header secrets are read from; default process.env */
18
18
  env?: Record<string, string | undefined>;
19
19
  }
20
+ /** Form-encodes an object, nesting as `a[b]=` and `a[0]=`; null and undefined are left out. */
21
+ export declare function formEncode(value: Record<string, unknown>): string;
20
22
  /** Builds the request for one tool call: path parameters substituted, the rest of the arguments as query or body. */
21
23
  export declare function buildRequest(base: string, tool: RestToolConfig, args: Record<string, unknown>): {
22
24
  url: URL;
package/dist/rest.js CHANGED
@@ -1,5 +1,21 @@
1
1
  import { OPERATION_META_KEY } from "./operations.js";
2
2
  const encode = (v) => encodeURIComponent(typeof v === "string" ? v : JSON.stringify(v));
3
+ /** Form-encodes an object, nesting as `a[b]=` and `a[0]=`; null and undefined are left out. */
4
+ export function formEncode(value) {
5
+ const pairs = [];
6
+ const walk = (key, v) => {
7
+ if (v === null || v === undefined)
8
+ return;
9
+ if (Array.isArray(v))
10
+ return v.forEach((item, i) => walk(`${key}[${i}]`, item));
11
+ if (typeof v === "object")
12
+ return Object.entries(v).forEach(([k, item]) => walk(`${key}[${k}]`, item));
13
+ pairs.push([key, String(v)]);
14
+ };
15
+ for (const [k, v] of Object.entries(value))
16
+ walk(k, v);
17
+ return new URLSearchParams(pairs).toString();
18
+ }
3
19
  /** Builds the request for one tool call: path parameters substituted, the rest of the arguments as query or body. */
4
20
  export function buildRequest(base, tool, args) {
5
21
  const rest = { ...args };
@@ -19,7 +35,7 @@ export function buildRequest(base, tool, args) {
19
35
  url.searchParams.set(name, typeof rest[name] === "string" ? rest[name] : JSON.stringify(rest[name]));
20
36
  delete rest[name];
21
37
  }
22
- const body = method === "GET" || method === "DELETE" || tool.body === "none" ? null : JSON.stringify(rest);
38
+ const body = method === "GET" || method === "DELETE" || tool.body === "none" ? null : tool.body === "form" ? formEncode(rest) : JSON.stringify(rest);
23
39
  return { url, method, body };
24
40
  }
25
41
  /** A REST API as an upstream. Tools are what the config declares; credentials come from the environment at startup, never from the agent. */
@@ -43,7 +59,7 @@ export function restUpstream(name, cfg, opts = {}) {
43
59
  if (!tool)
44
60
  throw new Error(`upstream ${name} has no tool "${params.name}"`);
45
61
  const { url, method, body } = buildRequest(cfg.baseUrl, tool, params.arguments ?? {});
46
- const requestHeaders = new Headers({ accept: "application/json", ...(body !== null ? { "content-type": "application/json" } : {}), ...headers });
62
+ const requestHeaders = new Headers({ accept: "application/json", ...(body !== null ? { "content-type": tool.body === "form" ? "application/x-www-form-urlencoded" : "application/json" } : {}), ...headers });
47
63
  if (tool.idempotencyHeader) {
48
64
  const operation = params._meta?.[OPERATION_META_KEY];
49
65
  if (!operation || typeof operation !== "object" || !Object.hasOwn(operation, "id") || !Object.hasOwn(operation, "idempotencyKey"))
package/docs/egress.md CHANGED
@@ -9,6 +9,8 @@ The gateway holds an agent's tool credentials and receipts every call made throu
9
9
  - relays the connection or refuses it;
10
10
  - signs a receipt either way, with `issuer.kind: "egress"`. The receipt goes to the log like any other.
11
11
 
12
+ ![The egress witness, animated: a locked-down agent pod reaches the outside only through the gateway or the witness. A direct call to Stripe is refused and receipted, a permitted host is relayed and receipted by bytes and times, a connection with no proxy credential is refused, and one that ignores the proxy is dropped by the network policy with no receipt.](../../../site/public/egress-witness.svg)
13
+
12
14
  **It needs lockdown.** A proxy alone is advice: an agent can ignore `HTTPS_PROXY` and connect directly. The witness means something only when the agent's network reaches nothing but the gateway and the witness. The witness runs anywhere Node 22 runs, but the lockdown belongs to the platform the agent runs on. `deploy/gateway/lockdown` ships it for Kubernetes (a NetworkPolicy), docker compose (an internal network), and a Linux VM or bare metal (`lockdown/vm`: an nftables rule on the agent's Unix user, a systemd drop-in for the agent's unit, a unit for the witness, and a script that runs the lockdown checks). On a cloud task or a laptop, you build the default-deny egress with that platform's own firewall. [Credential custody and lockdown](../../../site/guide/credential-custody.md) explains each.
13
15
 
14
16
  **What it cannot see.** Every page about the witness repeats this list:
@@ -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.7
23
+ - uses: svayatta/agent-custody@<commit sha of the release> # 0.16.8
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.7` |
40
+ | `version` | the `@agent-custody/receipts` version that `npx` runs | `0.16.8` |
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
 
package/docs/policies.md CHANGED
@@ -12,7 +12,7 @@ For an intercepted call to tool `T` by the agent named in the grant:
12
12
  | `action` | `Action::"<T>"` |
13
13
  | `resource` | `Tool::"<T>"` |
14
14
  | `context.args` | the call's arguments, exactly as the agent sent them. **Provenance: claimed.** |
15
- | `context.facts` | results of the gateway's own upstream lookups configured in `facts`. **Provenance: observed.** |
15
+ | `context.facts` | results of the gateway's own upstream lookups configured in `facts`. In Cedar, a `null` field is left out, because Cedar has no null, so `context.facts.payment has description` is false when Stripe returned `"description": null`; a `null` inside a list denies the call, because leaving it out would move the elements after it. The receipt keeps the result as returned, and Rego and OPA policies see it unchanged. **Provenance: observed.** |
16
16
  | `context.grant` | `{ principal, scopes }` from the signed delegation. **Provenance: attested.** |
17
17
 
18
18
  No entity hierarchy or schema is loaded yet, so policies reason about `context` and the three identifiers above.
package/docs/sdk.md CHANGED
@@ -167,6 +167,17 @@ agent-custody report --config ~/.config/agent-custody/sdk.json
167
167
 
168
168
  `node examples/38-incident-replay.ts` runs the hook in enforce mode with scripted events. `terraform plan` runs. `terraform destroy -auto-approve` and `rm -rf ~` are denied before they run, and a reviewer verifies the denial receipts with the public key only. The page [An incident replay](../../../site/guide/incident-replay.md) shows the output and the limit: a credential in the agent's environment goes around the hook.
169
169
 
170
+ ### What the hook does not stop
171
+
172
+ The hook stops a shell command, a file edit, or an MCP tool call that the agent makes. Read these limits before you rely on it.
173
+
174
+ - **A credential in the agent's environment goes around the hook.** If the shell of the agent holds a cloud key or a database password, a process that the agent starts can use it. The hook does not stop that process.
175
+ - **The starter list matches the text of a command.** It catches the plain form of each command. It is not a sandbox.
176
+ - **Some tools are not seen.** The hook matches `Bash`, `Write`, `Edit`, `MultiEdit`, `NotebookEdit`, and MCP tools. It does not see `Read`, `Grep`, `Glob`, `WebFetch`, `WebSearch`, or `Task`. The starter deny list has rules for `Bash` only.
177
+ - **The record is the agent's own report.** Every field is `claimed`. The signature shows that the record did not change after the hook wrote it. It does not show that the hook saw every call.
178
+
179
+ To cover more, keep production credentials out of the agent's environment, and put a gateway between the agent and the tools that touch production. [Credential custody and egress lockdown](../../../site/guide/credential-custody.md) shows how. The [threat model](threat-model.md) lists what each part defends, and what it does not. No independent witness runs yet, and the hosted log is not anchored on mainnet yet.
180
+
170
181
  ### Register the hook by hand
171
182
 
172
183
  Register the hook command in `.claude/settings.json`. The same command handles all three events.
package/docs/tutorials.md CHANGED
@@ -59,6 +59,7 @@ Suggested reading order is the numbering. Output lands in `examples-out/`, which
59
59
  | 47 | the door checks Web Bot Auth signatures | [47-web-bot-auth.ts](../examples/47-web-bot-auth.ts) | a crawler publishes its Ed25519 key in a directory at its own origin (served by a stub here) and signs each request (RFC 9421, tag `web-bot-auth`); unsigned it is unknown and refused, signed it is verified as `https://crawler.example` with no grant and the directory is fetched once; the same request again is a replay, a signature made for another site is refused; a grant naming the crawler under its signature is bound to its sender, another agent's grant under it is `wrong-sender`; the receipts verify | `src/web-bot-auth.ts`, `src/door.ts`, `src/config.ts` |
60
60
  | 48 | the door in-process: Express middleware and a Next.js route-handler wrapper | [48-door-app.ts](../examples/48-door-app.ts) | `door.json` without an origin; an Express shop with `app.use(door)` before `express.json()`; an unknown arrival reads the catalogue and is refused a refund that the app never sees; an agent with a grant refunds £45, committed to the log before the app runs, its body reaching `express.json()` and its grant stripped; the same door wraps a fetch-style `POST` handler as a Next.js route; every receipt records the app's status and body digest and verifies | `src/door-app.ts`, `src/door.ts` |
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
+ | 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 |
62
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` |
63
64
 
64
65
  ## How policies are defined, in one paragraph
package/docs/usage.md CHANGED
@@ -94,16 +94,16 @@ An upstream need not be an MCP server. A plain HTTP API is described as tools:
94
94
  "baseUrl": "https://api.stripe.com",
95
95
  "headerEnv": { "authorization": "STRIPE_BEARER" },
96
96
  "tools": [
97
- { "name": "customer.lookup", "method": "GET", "path": "/v1/customers/{customer_id}",
98
- "inputSchema": { "type": "object", "properties": { "customer_id": { "type": "string" } }, "required": ["customer_id"] } },
99
- { "name": "stripe.refund", "method": "POST", "path": "/v1/refunds", "description": "Refund a customer, amount in minor units",
100
- "inputSchema": { "type": "object", "properties": { "customer_id": { "type": "string" }, "amount": { "type": "integer" } }, "required": ["customer_id", "amount"] } }
97
+ { "name": "stripe.payment_intent", "method": "GET", "path": "/v1/payment_intents/{id}",
98
+ "inputSchema": { "type": "object", "properties": { "id": { "type": "string" } }, "required": ["id"] } },
99
+ { "name": "stripe.refund", "method": "POST", "path": "/v1/refunds", "body": "form", "description": "Refund a payment, amount in minor units",
100
+ "inputSchema": { "type": "object", "properties": { "payment_intent": { "type": "string" }, "amount": { "type": "integer" } }, "required": ["payment_intent", "amount"] } }
101
101
  ]
102
102
  }
103
103
  }
104
104
  ```
105
105
 
106
- `{name}` segments in `path` are filled from the call's arguments; the remaining arguments go to the query string on GET and DELETE and to a JSON body otherwise, or `query` names the ones that go to the query and `body: "none"` sends no body. `headers` are sent as written; `headerEnv` maps a header to an environment variable read once at startup, so the credential is never in the file and never reaches the agent, and a missing variable fails at startup. The response body is the tool result, JSON kept as JSON, and a non-2xx status is a failed execution with the API's answer in the receipt. Everything else is unchanged: the tools appear in the grant's scopes, `facts` may name a REST tool for a lookup, `precommit` applies, and each call has a receipt. `rest` can be one of several `upstreams` beside MCP servers. This is how an agent's direct HTTP calls come under custody: they become tool calls through the gateway. Tutorial 17 runs one against a stand-in API.
106
+ `{name}` segments in `path` are filled from the call's arguments; the remaining arguments go to the query string on GET and DELETE and to a JSON body otherwise, or `query` names the ones that go to the query and `body: "none"` sends no body; `body: "form"` sends `application/x-www-form-urlencoded` instead, nesting objects and arrays as `a[b]` and `a[0]` and leaving out nulls, which is what Stripe's v1 API reads. `headers` are sent as written; `headerEnv` maps a header to an environment variable read once at startup, so the credential is never in the file and never reaches the agent, and a missing variable fails at startup. The response body is the tool result, JSON kept as JSON, and a non-2xx status is a failed execution with the API's answer in the receipt. Everything else is unchanged: the tools appear in the grant's scopes, `facts` may name a REST tool for a lookup, `precommit` applies, and each call has a receipt. `rest` can be one of several `upstreams` beside MCP servers. This is how an agent's direct HTTP calls come under custody: they become tool calls through the gateway. Tutorial 17 runs one against a stand-in API. `agent-custody init refunds` writes this setup for Stripe in one command, with a refund policy, a grant, and keys, and `--run` makes a test-mode refund through it and verifies the receipt ([getting started](../../../site/guide/getting-started.md#stripe-refunds-in-one-command), tutorial 50).
107
107
 
108
108
  Another agent is an upstream too. An agent that speaks the A2A protocol publishes an agent card and takes tasks as messages; described as an upstream, delegating to it becomes a tool call:
109
109
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-custody/receipts",
3
- "version": "0.16.7",
3
+ "version": "0.16.8",
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",