@agent-custody/receipts 0.16.6 → 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.
Files changed (45) hide show
  1. package/README.md +24 -9
  2. package/dist/capture.d.ts +2 -0
  3. package/dist/capture.js +13 -2
  4. package/dist/check.d.ts +1 -1
  5. package/dist/check.js +34 -10
  6. package/dist/cli.js +34 -3
  7. package/dist/config.d.ts +32 -2
  8. package/dist/config.js +68 -4
  9. package/dist/door-app.d.ts +28 -0
  10. package/dist/door-app.js +244 -0
  11. package/dist/door-partner.d.ts +66 -0
  12. package/dist/door-partner.js +94 -0
  13. package/dist/door.d.ts +139 -10
  14. package/dist/door.js +297 -137
  15. package/dist/gateway-http.d.ts +1 -1
  16. package/dist/index.d.ts +4 -2
  17. package/dist/index.js +2 -1
  18. package/dist/perathos.js +3 -2
  19. package/dist/policy.d.ts +11 -0
  20. package/dist/policy.js +41 -1
  21. package/dist/receipt.d.ts +4 -1
  22. package/dist/refunds-init.d.ts +37 -0
  23. package/dist/refunds-init.js +193 -0
  24. package/dist/rest.d.ts +2 -0
  25. package/dist/rest.js +18 -2
  26. package/dist/verify.js +44 -4
  27. package/dist/web-bot-auth.d.ts +105 -0
  28. package/dist/web-bot-auth.js +508 -0
  29. package/docs/door-languages.md +168 -0
  30. package/docs/door-middleware.md +216 -0
  31. package/docs/door-quickstart.md +1 -1
  32. package/docs/door-signals.md +42 -5
  33. package/docs/door.md +124 -15
  34. package/docs/egress.md +2 -0
  35. package/docs/github-action.md +2 -2
  36. package/docs/perathos.md +13 -10
  37. package/docs/policies.md +1 -1
  38. package/docs/sdk.md +11 -0
  39. package/docs/tutorials.md +5 -0
  40. package/docs/usage.md +5 -5
  41. package/docs/verification.md +2 -0
  42. package/package.json +7 -1
  43. package/vectors/audit.json +27 -27
  44. package/vectors/canonical.json +5 -5
  45. package/vectors/receipts.json +1701 -1210
@@ -4,7 +4,7 @@ import { type GatewayHost } from "./gateway.ts";
4
4
  export declare const GRANT_HEADER = "x-agent-custody-grant";
5
5
  /** The header value that presents a grant: the DSSE envelope as base64url JSON. Send it as `Authorization: Bearer <value>` or as `X-Agent-Custody-Grant`. */
6
6
  export declare function grantHeader(envelope: Envelope): string;
7
- export declare function parseGrantHeader(req: IncomingMessage): Envelope | null;
7
+ export declare function parseGrantHeader(req: Pick<IncomingMessage, "headers">): Envelope | null;
8
8
  export interface HttpGatewayOptions {
9
9
  port: number;
10
10
  host?: string;
package/dist/index.d.ts CHANGED
@@ -7,7 +7,8 @@ export { hecEvent, splunkExporter } from "./splunk.ts";
7
7
  export { serveConsole, type ConsoleOptions, type RunningConsole } from "./console.ts";
8
8
  export { checkConfig, formatFindings, type CheckFinding, type CheckOptions } from "./check.ts";
9
9
  export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.ts";
10
- export { AGENT_HEADER, ARRIVAL_FACT, CLASS_HEADER, DOOR_DEFAULT_CAPTURE, DOOR_VERSION, MAX_CHALLENGE_TOKEN, RECEIPT_HEADER, RATE_BURST_MS, RATE_MINUTE_MS, cedarArgs, classifyArrival, createDoorHost, createRateTracker, matchRoute, normalizePath, remoteOf, serveDoor, verifyChallengeToken } from "./door.ts";
10
+ export { AGENT_HEADER, ARRIVAL_FACT, CLASS_HEADER, DOOR_DEFAULT_CAPTURE, DOOR_VERSION, MAX_CHALLENGE_TOKEN, RECEIPT_HEADER, RATE_BURST_MS, RATE_MINUTE_MS, cedarArgs, classifyArrival, createDoorHost, createRateTracker, matchRoute, normalizePath, remoteOf, serveDoor, signedRequestOf, verifyChallengeToken } from "./door.ts";
11
+ export { DIRECTORY_MEDIA_TYPE, DIRECTORY_PATH, WEB_BOT_AUTH_TAG, agentOrigin, createWebBotAuthVerifier, jwkThumbprint, normalizeAuthority, parseDictionary, signatureBase } from "./web-bot-auth.ts";
11
12
  export { DESTINATION_FACT, EGRESS_VERSION, PROXY_REALM, checkProxyCredential, createEgressHost, destinationName, normalizeHost, parseAuthority, publicOnlyLookup, serveEgress } from "./egress.ts";
12
13
  export { internalAddress } from "./addresses.ts";
13
14
  export { DRAFT_WARNING, draftEgressPolicy } from "./egress-draft.ts";
@@ -19,7 +20,8 @@ export { formatPerathosReport, PERATHOS_RECEIPT_V1, perathosHead, perathosReceip
19
20
  export type { PerathosCheck, PerathosOptions, PerathosReport } from "./perathos.ts";
20
21
  export { loadAcsGuardianConfig } from "./config.ts";
21
22
  export type { AcsGuardianConfig } from "./config.ts";
22
- export type { Arrival, ArrivalChallenge, ArrivalClass, ArrivalRate, ChallengeCheck, Classified, DoorHost, DoorOptions, DoorServerOptions, RateTracker, RateTrackerLimits, RunningDoor } from "./door.ts";
23
+ export type { Arrival, ArrivalChallenge, ArrivalClass, ArrivalRate, ChallengeCheck, Classified, DoorHost, DoorOptions, DoorRequest, DoorServerOptions, RateTracker, RateTrackerLimits, RunningDoor } from "./door.ts";
24
+ export type { SignatureCheck, SignedRequest, WebBotAuthOptions, WebBotAuthVerifier } from "./web-bot-auth.ts";
23
25
  export * from "./capture.ts";
24
26
  export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.ts";
25
27
  export { deliverMail, founderNote, PortalStore, portalHandler, readSession, readSessionVia, sendFollowUps, servePortal, signSession, SsoRefusedError, stripeRequest, verifyStripeSignature } from "./portal.ts";
package/dist/index.js CHANGED
@@ -6,7 +6,8 @@ export { hecEvent, splunkExporter } from "./splunk.js";
6
6
  export { serveConsole } from "./console.js";
7
7
  export { checkConfig, formatFindings } from "./check.js";
8
8
  export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.js";
9
- export { AGENT_HEADER, ARRIVAL_FACT, CLASS_HEADER, DOOR_DEFAULT_CAPTURE, DOOR_VERSION, MAX_CHALLENGE_TOKEN, RECEIPT_HEADER, RATE_BURST_MS, RATE_MINUTE_MS, cedarArgs, classifyArrival, createDoorHost, createRateTracker, matchRoute, normalizePath, remoteOf, serveDoor, verifyChallengeToken } from "./door.js";
9
+ export { AGENT_HEADER, ARRIVAL_FACT, CLASS_HEADER, DOOR_DEFAULT_CAPTURE, DOOR_VERSION, MAX_CHALLENGE_TOKEN, RECEIPT_HEADER, RATE_BURST_MS, RATE_MINUTE_MS, cedarArgs, classifyArrival, createDoorHost, createRateTracker, matchRoute, normalizePath, remoteOf, serveDoor, signedRequestOf, verifyChallengeToken } from "./door.js";
10
+ export { DIRECTORY_MEDIA_TYPE, DIRECTORY_PATH, WEB_BOT_AUTH_TAG, agentOrigin, createWebBotAuthVerifier, jwkThumbprint, normalizeAuthority, parseDictionary, signatureBase } from "./web-bot-auth.js";
10
11
  export { DESTINATION_FACT, EGRESS_VERSION, PROXY_REALM, checkProxyCredential, createEgressHost, destinationName, normalizeHost, parseAuthority, publicOnlyLookup, serveEgress } from "./egress.js";
11
12
  export { internalAddress } from "./addresses.js";
12
13
  export { DRAFT_WARNING, draftEgressPolicy } from "./egress-draft.js";
package/dist/perathos.js CHANGED
@@ -3,7 +3,8 @@
3
3
  * verification rules of their published spec (docs/specs/RECEIPT_V1.md in perathos-protocol/perathos). Written from
4
4
  * that spec alone, so a Perathos log and an agent-custody receipt can be checked with one tool, each for what it proves.
5
5
  *
6
- * A Perathos log is recorded by hooks inside the agent's host and sealed by checkpoints signed with a key held there.
6
+ * A Perathos log is recorded on the agent's host, by hooks or an MCP proxy, and sealed by checkpoints signed with a key
7
+ * that is on that host or, with a remote signer, usable from it.
7
8
  * A valid log shows that the key holder sealed this sequence and nothing up to the last checkpoint changed since. It
8
9
  * does not show that an enforcement point outside the agent saw each call, which is what an agent-custody receipt
9
10
  * attests, so the report says which kind of evidence it is. RFC 3161 anchors are not checked here.
@@ -166,7 +167,7 @@ export function verifyPerathosLog(text, opts = {}) {
166
167
  signerFailures,
167
168
  firstTs: typeof receipts[0]?.ts === "string" ? receipts[0].ts : null,
168
169
  lastTs: typeof receipts.at(-1)?.ts === "string" ? receipts.at(-1).ts : null,
169
- provenance: `perathos.receipt/v1, recorded by hooks inside the agent's host (${agent ?? "unknown"}); the checkpoint key is held on that host, so a valid log shows that the key holder sealed this sequence, not that an enforcement point outside the agent saw each call; times are the host's clock, and RFC 3161 anchors were not checked`,
170
+ provenance: `perathos.receipt/v1, recorded on the agent's host (${agent ?? "unknown"}) by hooks or an MCP proxy; the checkpoint key, or the credential for a remote signer, is on that host, so a valid log shows that the key holder sealed this sequence, not that an enforcement point outside the agent saw each call; times are the host's clock, and RFC 3161 anchors were not checked`,
170
171
  };
171
172
  }
172
173
  /** The report as text, in the style of `verify`. */
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
  });
package/dist/receipt.d.ts CHANGED
@@ -36,7 +36,10 @@ export interface FactRecord {
36
36
  value: unknown;
37
37
  /** the digest of the lookup's full result; under a capture rule a commitment to that result (the receipt shows only the selected value, the rest is private), named in the `capture` note */
38
38
  resultDigest: string | Commitment;
39
- provenance: "observed";
39
+ /** `attested` only when `attestation` carries its source's signature over `value` for this receipt and tool, checked by the issuer; a verifier checks it again under the source's key */
40
+ provenance: "observed" | "attested";
41
+ /** the source's attestation envelope (upstream.ts format, over the digest of `value`); the door's partner verdict carries one. Withheld unless it is exactly that plain attestation beside a value in clear */
42
+ attestation?: Envelope | Commitment;
40
43
  }
41
44
  /** A gateway's durable financial operation identity; execution still describes only the tool/API call. */
42
45
  export interface OperationEvidence {
@@ -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/dist/verify.js CHANGED
@@ -211,6 +211,11 @@ export function verifyBundle(bundle, opts) {
211
211
  // A door decides every arrival by policy; an arrival carries a grant only when it chose to present one.
212
212
  if (p.issuer.kind === "door")
213
213
  add("door receipt carries a policy decision", p.policy !== null);
214
+ // In authz mode the door answers a proxy's check and relays nothing: the receipt is a decision, never a result.
215
+ if (p.issuer.kind === "door" && p.issuer.framework === "authz") {
216
+ const decided = p.execution.status === "withheld" || (p.execution.status === "denied" && p.policy?.decision === "deny");
217
+ add("door authz decided, relayed nothing", decided, decided ? `${p.policy?.decision}; a decision for the proxy, which relays: the door saw neither the body nor the origin's answer` : `the receipt says ${p.execution.status} with a policy ${p.policy?.decision ?? "absent"}`);
218
+ }
214
219
  // An egress witness saw a connection that went around the gateway: where it went and how much, never what was sent.
215
220
  // Its destination is its own observation; its agent is only as good as the proxy credential it checked.
216
221
  if (p.issuer.kind === "egress") {
@@ -373,6 +378,32 @@ export function verifyBundle(bundle, opts) {
373
378
  const how = back.restored.get(pathKey(w));
374
379
  add(`withheld ${pathText(w)}`, !problem, problem ?? (how ? `holds against the ${how} value` : committedNote([w])));
375
380
  }
381
+ // A fact its source signed (the door's partner verdict): the issuer marks it attested after checking the signature
382
+ // under its configured key, and the reader checks it again under the key it trusts for that source. The signature
383
+ // binds this receipt and route, so a verdict moved from another arrival fails here.
384
+ for (const [name, f] of Object.entries(p.facts)) {
385
+ if (f.provenance !== "attested")
386
+ continue;
387
+ const label = `fact ${name} signature (upstream key)`;
388
+ const value = region(["facts", name, "value"]);
389
+ const envPath = ["facts", name, "attestation"];
390
+ const stillWithheld = (note?.withheld ?? []).some((w) => pathKey(w) === pathKey(envPath)) && back.missing.some((w) => pathKey(w) === pathKey(envPath));
391
+ const restored = full.facts[name];
392
+ const env = restored?.attestation;
393
+ const wellFormed = !!env && typeof env === "object" && typeof env.payload === "string" && Array.isArray(env.signatures);
394
+ if (value.problem || value.missing.length)
395
+ add(`fact ${name} signature not checked`, true, "the value is withheld; disclose it or give the capture key to check its signature");
396
+ else if (stillWithheld)
397
+ add(label, false, "the value is in clear but its signature is withheld; disclose it or give the capture key to check it");
398
+ else if (!wellFormed)
399
+ add(label, false, "the fact is marked attested and carries no signature, and the capture note does not say it is withheld");
400
+ else if (!opts.upstreamKeys?.length)
401
+ add(label, false, "the fact is marked attested; give the signer's public key (--upstream-key) to check it");
402
+ else {
403
+ const u = checkUpstream(env, opts.upstreamKeys, { receiptId: p.receiptId, tool: p.tool.name, contentDigest: digestOf(restored.value) });
404
+ add(label, u.ok, u.ok ? `keyid ${short(u.keyid)}` : u.error);
405
+ }
406
+ }
376
407
  const evidence = executedOrFailed && "upstream" in p.execution ? p.execution.upstream : undefined;
377
408
  if (executedOrFailed && evidence) {
378
409
  // The evidence as restored: the delivery body or the signed envelope may have been withheld with the result. A
@@ -567,10 +598,13 @@ export function auditExtends(older, newer, proof, keys, logId, opts = {}) {
567
598
  }
568
599
  return { ok: checks.every((c) => c.ok), checks, older: a, newer: b };
569
600
  }
601
+ /** What kind of evidence the issuer gives; a door answering a proxy's authz check gives a decision only. */
602
+ const issuerNote = (issuer) => (issuer.kind === "door" && issuer.framework === "authz" ? ISSUER_NOTE["door/authz"] : ISSUER_NOTE[issuer.kind] ?? "unknown issuer kind");
570
603
  const ISSUER_NOTE = {
571
604
  gateway: "enforced outside the agent's process; the agent could neither skip nor forge this receipt",
572
605
  sdk: "self-reported by the agent's own process; tamper-evident after issue, but nothing here was enforced outside the agent",
573
606
  door: "enforced in front of the business's own HTTP surface; the arriving party could not forge this receipt and is attested only when it presented a grant, and a request that reached the origin some other way leaves no receipt",
607
+ "door/authz": "decided by the door for a proxy in front of the business's own HTTP surface (nginx auth_request or Envoy ext_authz): the receipt records the decision, not the result, since the proxy relayed an allowed request and the door saw neither its body nor the origin's answer; the arriving party could not forge this receipt and is attested only when it presented a grant",
574
608
  guardian: "decided by an ACS Guardian outside the agent's process and signed with its own key, so the decision is attributable to it; the call is the agent's own report, and the agent could skip the Guardian or ignore its answer",
575
609
  egress: "observed by a forward proxy in the agent's network path, for a connection that went around the gateway: where it went and how much, never what was sent; the agent is known only by the proxy credential the witness checked, and a connection that skipped the proxy (no lockdown) leaves no receipt at all",
576
610
  };
@@ -585,7 +619,7 @@ export function formatReport(r) {
585
619
  return lines.join("\n");
586
620
  const p = r.statement.predicate;
587
621
  lines.push("");
588
- lines.push(`ISSUER: ${p.issuer.kind}${p.issuer.framework ? ` (${p.issuer.framework})` : ""}${p.issuer.strict ? ", strict mode" : ""}, ${ISSUER_NOTE[p.issuer.kind] ?? "unknown issuer kind"}`);
622
+ lines.push(`ISSUER: ${p.issuer.kind}${p.issuer.framework ? ` (${p.issuer.framework})` : ""}${p.issuer.strict ? ", strict mode" : ""}, ${issuerNote(p.issuer)}`);
589
623
  lines.push("");
590
624
  lines.push("field provenance value");
591
625
  const row = (f, prov, v) => lines.push(`${f.padEnd(15)} ${prov.padEnd(11)} ${typeof v === "string" ? v : JSON.stringify(v)}`);
@@ -597,8 +631,14 @@ export function formatReport(r) {
597
631
  row("model", p.model.provenance, p.model.id === null ? "(none supplied)" : idText(p.model.id));
598
632
  row("tool", p.tool.provenance, p.tool.name);
599
633
  row("args", p.request.provenance, p.request.args);
600
- for (const [k, f] of Object.entries(p.facts))
601
- row(`fact.${k}`, f.provenance, f.value);
634
+ for (const [k, f] of Object.entries(p.facts)) {
635
+ if (f.provenance !== "attested") {
636
+ row(`fact.${k}`, f.provenance, f.value);
637
+ continue;
638
+ }
639
+ const signed = r.checks.find((c) => c.name === `fact ${k} signature (upstream key)`);
640
+ row(`fact.${k}`, f.provenance, `${JSON.stringify(f.value)}${signed ? (signed.ok ? ` (signed by ${signed.detail})` : " (signature FAILED)") : " (signature not checked)"}`);
641
+ }
602
642
  if (p.reconciliation)
603
643
  row("policy", "-", "(none evaluated: a provider read, not a call)");
604
644
  else if (p.policy)
@@ -611,7 +651,7 @@ export function formatReport(r) {
611
651
  const committed = r.checks.filter((c) => c.name.startsWith("authorization ")).every((c) => c.ok);
612
652
  row("authorization", "observed", committed ? `committed to the log as leaf ${p.authorization.inclusion.leafIndex}, before the call was forwarded` : "carried, but its checks FAILED");
613
653
  }
614
- else if (p.execution.status === "withheld" && p.issuer.kind !== "guardian")
654
+ else if (p.execution.status === "withheld" && p.issuer.kind !== "guardian" && !(p.issuer.kind === "door" && p.issuer.framework === "authz"))
615
655
  row("authorization", "observed", "the log would not commit it; the call was not forwarded");
616
656
  if (p.approval)
617
657
  row("approval", p.approval.provenance, `${p.approval.status}; ${p.approval.requiredApprovers} approver(s) required${p.approval.consumedAt ? `; consumed ${p.approval.consumedAt}` : ""}${typeof p.approval.reason === "string" ? `; ${p.approval.reason}` : ""}`);
@@ -0,0 +1,105 @@
1
+ export declare const DIRECTORY_PATH = "/.well-known/http-message-signatures-directory";
2
+ export declare const DIRECTORY_MEDIA_TYPE = "application/http-message-signatures-directory+json";
3
+ export declare const WEB_BOT_AUTH_TAG = "web-bot-auth";
4
+ export type BareItem = {
5
+ t: "string";
6
+ v: string;
7
+ } | {
8
+ t: "token";
9
+ v: string;
10
+ } | {
11
+ t: "integer";
12
+ v: number;
13
+ } | {
14
+ t: "decimal";
15
+ v: number;
16
+ } | {
17
+ t: "bytes";
18
+ v: Buffer;
19
+ } | {
20
+ t: "boolean";
21
+ v: boolean;
22
+ };
23
+ export type Params = [string, BareItem][];
24
+ export interface SfItem {
25
+ item: BareItem;
26
+ params: Params;
27
+ }
28
+ export interface SfInnerList {
29
+ list: SfItem[];
30
+ params: Params;
31
+ }
32
+ export type SfMember = SfItem | SfInnerList;
33
+ /** An RFC 8941 dictionary. A later member of the same name replaces an earlier one, as the RFC says. */
34
+ export declare function parseDictionary(text: string): Map<string, SfMember>;
35
+ /** An RFC 8941 item on its own, such as a legacy `Signature-Agent: "https://..."`. */
36
+ export declare function parseItem(text: string): SfItem;
37
+ export declare const serializeMember: (m: SfMember) => string;
38
+ /** What a signature base is built from: the request as the door received it. */
39
+ export interface SignedRequest {
40
+ method: string;
41
+ /** the request target as received, path and query, never decoded */
42
+ target: string;
43
+ /** the authority the request was sent to, normalised (`normalizeAuthority`) */
44
+ authority: string;
45
+ /** every value of a header field, lowercase name; undefined when the field is absent */
46
+ header(name: string): string[] | undefined;
47
+ }
48
+ /** A host as RFC 9421 compares it: lowercase, without the default port of https or http. */
49
+ export declare function normalizeAuthority(host: string): string;
50
+ /**
51
+ * The RFC 9421 signature base (section 2.5) for the covered components and their parameters. Supports `@method`,
52
+ * `@authority`, `@path`, `@query`, and header fields, whole or one dictionary member (`;key`). Any other derived
53
+ * component or component parameter is refused rather than guessed at.
54
+ */
55
+ export declare function signatureBase(req: SignedRequest, input: SfInnerList): string;
56
+ /** The RFC 7638 thumbprint of an Ed25519 JWK (RFC 8037 appendix A.3): the base64url SHA-256 of `{"crv","kty","x"}`. */
57
+ export declare function jwkThumbprint(x: string): string;
58
+ export interface WebBotAuthOptions {
59
+ /** the signature agents, as https origins, whose directories the door may fetch; any other is refused unfetched */
60
+ agents: string[];
61
+ /** the authorities this door serves; a signature covering any other `@authority` is refused */
62
+ authorities: string[];
63
+ requireNonce: boolean;
64
+ maxAgeSeconds: number;
65
+ clockSkewSeconds: number;
66
+ timeoutMs: number;
67
+ maxDirectoryBytes: number;
68
+ cacheSeconds: number;
69
+ maxNonces: number;
70
+ }
71
+ /**
72
+ * What the door made of a request's signature. `verified`: a signature tagged `web-bot-auth` checked against a key
73
+ * that `agent`'s directory publishes. `invalid`: the signature, its parameters, its agent, or the directory was wrong.
74
+ * `unavailable`: the directory could not be fetched, or the door could not record the nonce. `unchecked`: a signature
75
+ * arrived and the door has no `webBotAuth` config. `absent`: no `Signature-Input`.
76
+ */
77
+ export type SignatureCheck = {
78
+ outcome: "verified";
79
+ agent: string;
80
+ keyid: string;
81
+ label: string;
82
+ } | {
83
+ outcome: "invalid" | "unavailable";
84
+ error: string;
85
+ agent?: string;
86
+ keyid?: string;
87
+ } | {
88
+ outcome: "unchecked" | "absent";
89
+ };
90
+ export interface WebBotAuthVerifier {
91
+ verify(req: SignedRequest): Promise<SignatureCheck>;
92
+ /** nonces held now */
93
+ nonces(): number;
94
+ }
95
+ /** A response body up to `max` bytes; null when it passes that, and the rest is not read. */
96
+ export declare function readCapped(res: Response, max: number): Promise<Buffer | null>;
97
+ /** An https origin with nothing after it, as the config holds it; throws on anything else. */
98
+ export declare function agentOrigin(uri: string): string;
99
+ /**
100
+ * Checks Web Bot Auth signatures. The directory of each configured agent is fetched from
101
+ * `<origin>/.well-known/http-message-signatures-directory` over https, never following a redirect, within `timeoutMs`
102
+ * and `maxDirectoryBytes`, and kept for `cacheSeconds` (a failure for 30 seconds). A nonce is remembered until the
103
+ * signature it came with could no longer be accepted, so a signature serves one request. `now` is for tests.
104
+ */
105
+ export declare function createWebBotAuthVerifier(opts: WebBotAuthOptions, f: typeof fetch, now?: () => number): WebBotAuthVerifier;