@agent-custody/receipts 0.16.7 → 0.16.9
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 +3 -0
- package/dist/check.js +17 -0
- package/dist/cli.js +38 -6
- package/dist/config.d.ts +6 -0
- package/dist/config.js +5 -2
- package/dist/door.d.ts +5 -3
- package/dist/door.js +23 -4
- package/dist/gateway.d.ts +1 -2
- package/dist/gateway.js +12 -50
- package/dist/policy.d.ts +11 -0
- package/dist/policy.js +41 -1
- package/dist/refunds-init.d.ts +37 -0
- package/dist/refunds-init.js +193 -0
- package/dist/rest.d.ts +2 -0
- package/dist/rest.js +18 -2
- package/dist/revocation.d.ts +14 -0
- package/dist/revocation.js +53 -0
- package/docs/door-signals.md +3 -2
- package/docs/door.md +8 -5
- package/docs/egress.md +2 -0
- package/docs/github-action.md +2 -2
- package/docs/policies.md +1 -1
- package/docs/sdk.md +11 -0
- package/docs/tutorials.md +2 -1
- package/docs/usage.md +5 -5
- package/package.json +1 -1
- package/vectors/audit.json +27 -27
- package/vectors/canonical.json +5 -5
- package/vectors/receipts.json +1868 -1332
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).
|
|
@@ -287,6 +289,7 @@ src/policy-rego.ts Rego: compiled with opa build, evaluated in-process with the
|
|
|
287
289
|
src/opa-server.ts an OPA server's Data API as the policy, with bundle revisions as the digest
|
|
288
290
|
src/simulate.ts replay recorded policy decisions against a proposed Cedar or Rego policy, grouped changes and run digest
|
|
289
291
|
src/delegation.ts signed delegation grants
|
|
292
|
+
src/revocation.ts the revoked-grants file the gateway and the door share: re-read when it changes, written by rename
|
|
290
293
|
src/approval.ts exact-action human approvals, distinct trusted signatures, persistent single-use consumption
|
|
291
294
|
src/receipt.ts receipt and authorization statement types and provenance labels
|
|
292
295
|
src/issue.ts sign, log, and write a receipt, or commit an authorization first; shared by every producer
|
package/dist/check.js
CHANGED
|
@@ -225,6 +225,23 @@ export function checkDoorConfig(configPath) {
|
|
|
225
225
|
if (!ldir)
|
|
226
226
|
add("error", "paths", `${cfg.logFile} cannot be written`);
|
|
227
227
|
}
|
|
228
|
+
if (cfg.revokedGrants) {
|
|
229
|
+
if (!existsSync(cfg.revokedGrants))
|
|
230
|
+
add("ok", "revokedGrants", `no grant is revoked yet; \`agent-custody revoke --config\` creates ${cfg.revokedGrants}`);
|
|
231
|
+
else {
|
|
232
|
+
try {
|
|
233
|
+
const list = JSON.parse(readFileSync(cfg.revokedGrants, "utf8"));
|
|
234
|
+
if (!Array.isArray(list))
|
|
235
|
+
throw new Error("expected a JSON array of grant digests");
|
|
236
|
+
add("ok", "revokedGrants", `${list.length} revoked grant(s) in ${cfg.revokedGrants}`);
|
|
237
|
+
}
|
|
238
|
+
catch (e) {
|
|
239
|
+
add("error", "revokedGrants", `${cfg.revokedGrants}: ${e instanceof Error ? e.message : String(e)}; the door refuses to start, and a file that becomes unreadable while it runs makes every grant revoked`);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
else if (cfg.trustedPrincipalKeys.length > 0)
|
|
244
|
+
add("warn", "revokedGrants", "no revokedGrants file: a grant cannot be revoked at this door before it expires");
|
|
228
245
|
return out;
|
|
229
246
|
}
|
|
230
247
|
/** True when the file is an egress witness config: it names agents, and no upstream or origin. */
|
package/dist/cli.js
CHANGED
|
@@ -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";
|
|
@@ -85,8 +86,10 @@ const USAGE = `agent-custody <command>
|
|
|
85
86
|
a narrower grant for a sub-agent, signed by the agent the parent names; the parent travels inside
|
|
86
87
|
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
|
|
87
88
|
for verify --disclose; needs the customer's capture key
|
|
88
|
-
revoke --config <gateway.json> --grant <grant.json>
|
|
89
|
-
|
|
89
|
+
revoke --config <gateway.json|door.json> --grant <grant.json>
|
|
90
|
+
revokes a grant: its digest goes into the config's revokedGrants file. At a gateway, every
|
|
91
|
+
session under it or under a grant delegated from it refuses its next call, and no new session opens for them;
|
|
92
|
+
at a door, an arrival carrying it, or a grant delegated from it, is claimed with grant "revoked"
|
|
90
93
|
reconcile --config <gateway.json> --operation <uuid> operator-only provider lookup; commits a receipt before closing an unknown/pending financial operation
|
|
91
94
|
console --config <gateway.json> [--port 8795] [--host 127.0.0.1] [--token-env CONSOLE_TOKEN | --token-file <path>] [--gateway-url <url>] [--state-dir <dir>]
|
|
92
95
|
the admin console for a gateway: its config and tools, a config check, receipts with a verdict each, a policy editor that
|
|
@@ -119,6 +122,10 @@ const USAGE = `agent-custody <command>
|
|
|
119
122
|
init claude-code [--dir <dir>] [--user] [--enforce] [--log-url <url> [--log-id <id>] [--log-token-env NAME] [--log-key <pub>]]
|
|
120
123
|
one command for your own Claude Code sessions: an agent key, sdk.json in observe mode, a starter deny
|
|
121
124
|
policy, and the three hooks in .claude/settings.local.json (--user: ~/.claude/settings.json). Safe to run twice
|
|
125
|
+
init refunds [--dir agent-custody-refunds] [--limit 5000] [--currency gbp] [--ttl-hours 24] [--run]
|
|
126
|
+
a gateway in front of Stripe refunds: keys, a grant, a refund policy, and a config. --run (with
|
|
127
|
+
STRIPE_SECRET_KEY, test mode only) makes a test payment, refunds it through the gateway, has an
|
|
128
|
+
over-limit refund refused, and verifies the receipt
|
|
122
129
|
audit-sessions [--since 7d|24h|<date>|all] [--dir <claude projects dir>] [--policy <file.cedar>] [--counts] [--json]
|
|
123
130
|
a read-only preview: which of your past Claude Code tool calls the policy would have denied, from the transcripts; writes nothing
|
|
124
131
|
report --config <sdk.json> the calls that the policy would have denied, from the receipts: tool, command or path, rule, receipt id;
|
|
@@ -324,9 +331,10 @@ async function main(argv) {
|
|
|
324
331
|
const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, grant: { type: "string" } } });
|
|
325
332
|
if (!values.config || !values.grant)
|
|
326
333
|
throw new Error("revoke needs --config and --grant");
|
|
327
|
-
const
|
|
334
|
+
const door = isDoorConfig(values.config);
|
|
335
|
+
const cfg = door ? loadDoorConfig(values.config) : loadConfig(values.config);
|
|
328
336
|
if (!cfg.revokedGrants)
|
|
329
|
-
throw new Error(
|
|
337
|
+
throw new Error(`revoke needs revokedGrants in the config: the file the ${door ? "door re-reads on every arrival" : "gateway re-reads on every call"}`);
|
|
330
338
|
const envelope = JSON.parse(readFileSync(values.grant, "utf8"));
|
|
331
339
|
const chain = decodeDelegation(envelope);
|
|
332
340
|
if (!chain)
|
|
@@ -335,7 +343,7 @@ async function main(argv) {
|
|
|
335
343
|
const list = existsSync(cfg.revokedGrants) ? JSON.parse(readFileSync(cfg.revokedGrants, "utf8")) : [];
|
|
336
344
|
if (!list.includes(digest))
|
|
337
345
|
writeRevokedGrants(cfg.revokedGrants, [...list, digest]);
|
|
338
|
-
console.log(`revoked ${chain.agent}'s grant from ${chain.principal} (${digest.slice(0, 12)}…): ${cfg.revokedGrants} now lists ${list.includes(digest) ? list.length : list.length + 1} grant(s); a running gateway refuses it on its next call`);
|
|
346
|
+
console.log(`revoked ${chain.agent}'s grant from ${chain.principal} (${digest.slice(0, 12)}…): ${cfg.revokedGrants} now lists ${list.includes(digest) ? list.length : list.length + 1} grant(s); ${door ? "a running door classifies it as revoked on its next arrival" : "a running gateway refuses it on its next call"}`);
|
|
339
347
|
return 0;
|
|
340
348
|
}
|
|
341
349
|
case "gateway": {
|
|
@@ -439,8 +447,32 @@ async function main(argv) {
|
|
|
439
447
|
}
|
|
440
448
|
case "init": {
|
|
441
449
|
const [target, ...args] = rest;
|
|
450
|
+
if (target === "refunds") {
|
|
451
|
+
const { values } = parseArgs({
|
|
452
|
+
args,
|
|
453
|
+
options: {
|
|
454
|
+
dir: { type: "string", default: "agent-custody-refunds" },
|
|
455
|
+
limit: { type: "string", default: "5000" },
|
|
456
|
+
currency: { type: "string", default: "gbp" },
|
|
457
|
+
"ttl-hours": { type: "string", default: "24" },
|
|
458
|
+
run: { type: "boolean", default: false },
|
|
459
|
+
"stripe-url": { type: "string" },
|
|
460
|
+
},
|
|
461
|
+
});
|
|
462
|
+
if (!existsSync(join(resolve(values.dir), "gateway.json"))) {
|
|
463
|
+
initRefunds({ dir: values.dir, limit: Number(values.limit), currency: values.currency, ttlHours: Number(values["ttl-hours"]), ...(values["stripe-url"] ? { stripeUrl: values["stripe-url"] } : {}) });
|
|
464
|
+
}
|
|
465
|
+
else if (!values.run)
|
|
466
|
+
throw new Error(`${join(resolve(values.dir), "gateway.json")} already exists; add --run to make a test refund with it, or remove ${values.dir}`);
|
|
467
|
+
if (!values.run) {
|
|
468
|
+
console.log(`\nNext: export ${STRIPE_KEY_ENV}=sk_test_... and run agent-custody init refunds --dir ${values.dir} --run`);
|
|
469
|
+
return 0;
|
|
470
|
+
}
|
|
471
|
+
const result = await runRefunds({ dir: values.dir });
|
|
472
|
+
return result.verified && result.refused ? 0 : 1;
|
|
473
|
+
}
|
|
442
474
|
if (target !== "claude-code")
|
|
443
|
-
throw new Error("init needs a target: init claude-code");
|
|
475
|
+
throw new Error("init needs a target: init claude-code or init refunds");
|
|
444
476
|
const { values } = parseArgs({
|
|
445
477
|
args,
|
|
446
478
|
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
|
}>>;
|
|
@@ -410,6 +415,7 @@ export declare const DoorConfigSchema: z.ZodObject<{
|
|
|
410
415
|
}, z.core.$strip>>>;
|
|
411
416
|
unmatchedRoute: z.ZodDefault<z.ZodString>;
|
|
412
417
|
trustedPrincipalKeys: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
418
|
+
revokedGrants: z.ZodOptional<z.ZodString>;
|
|
413
419
|
policyFile: z.ZodString;
|
|
414
420
|
mode: z.ZodOptional<z.ZodEnum<{
|
|
415
421
|
enforce: "enforce";
|
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 */
|
|
@@ -255,6 +255,8 @@ export const DoorConfigSchema = z.object({
|
|
|
255
255
|
unmatchedRoute: z.string().min(1).default("other"),
|
|
256
256
|
/** principal keys whose grants the door accepts as a passport: an arrival carrying one of their grants, in scope for its route, is `verified` */
|
|
257
257
|
trustedPrincipalKeys: z.array(z.string()).default([]),
|
|
258
|
+
/** a JSON file listing digests of revoked grant envelopes, the same file and format as the gateway's (`agent-custody revoke --config door.json` appends to it); re-read whenever it changes, checked on every arrival. A grant it lists, or one whose chain it lists, is `revoked` */
|
|
259
|
+
revokedGrants: z.string().min(1).optional(),
|
|
258
260
|
policyFile: z.string(),
|
|
259
261
|
/** "enforce" (default) refuses what the policy denies; "observe" forwards everything and records the decision with `enforced: false` */
|
|
260
262
|
mode: z.enum(["enforce", "observe"]).optional(),
|
|
@@ -399,6 +401,7 @@ export function loadDoorConfig(path) {
|
|
|
399
401
|
...cfg,
|
|
400
402
|
identity: { keyFile: r(cfg.identity.keyFile) },
|
|
401
403
|
trustedPrincipalKeys: cfg.trustedPrincipalKeys.map(r),
|
|
404
|
+
...(cfg.revokedGrants ? { revokedGrants: r(cfg.revokedGrants) } : {}),
|
|
402
405
|
policyFile: r(cfg.policyFile),
|
|
403
406
|
receiptsDir: r(cfg.receiptsDir),
|
|
404
407
|
...(cfg.logFile ? { logFile: r(cfg.logFile) } : {}),
|
package/dist/door.d.ts
CHANGED
|
@@ -30,10 +30,11 @@ export interface Arrival {
|
|
|
30
30
|
subject: string;
|
|
31
31
|
/**
|
|
32
32
|
* What became of the grant header: a trusted grant in scope for this route, one out of scope, one that did not verify,
|
|
33
|
+
* one revoked (`revoked`: it, or a grant above it in its chain, is in `revokedGrants`, or that file cannot be read),
|
|
33
34
|
* one presented by another agent (`wrong-sender`: the request is signed by a signature agent the grant does not name),
|
|
34
35
|
* or none.
|
|
35
36
|
*/
|
|
36
|
-
grant: "verified" | "out-of-scope" | "invalid" | "wrong-sender" | "absent";
|
|
37
|
+
grant: "verified" | "out-of-scope" | "invalid" | "revoked" | "wrong-sender" | "absent";
|
|
37
38
|
grantError?: string;
|
|
38
39
|
/** What became of an RFC 9421 signature tagged `web-bot-auth`: see `SignatureCheck`. `unchecked` when the door has no `webBotAuth` config */
|
|
39
40
|
signature: SignatureCheck["outcome"];
|
|
@@ -220,9 +221,10 @@ export declare function signedRequestOf(req: DoorRequest): SignedRequest;
|
|
|
220
221
|
* arrival `verified` as its signature agent. With both, the signature binds the grant to its sender when the grant names
|
|
221
222
|
* that signature agent; a grant presented under another agent's signature is `wrong-sender` and the arrival `claimed`.
|
|
222
223
|
* An `x-agent-custody-agent` header or a signature that did not verify alone is `claimed`. Nothing at all is `unknown`.
|
|
223
|
-
* Without `signature`, a `Signature-Input` header is recorded as `unchecked`.
|
|
224
|
+
* Without `signature`, a `Signature-Input` header is recorded as `unchecked`. `revoked`, when given, says why a grant
|
|
225
|
+
* that verified is revoked (from its chain's digests, leaf first), or null when it is not; a revoked grant is `claimed`.
|
|
224
226
|
*/
|
|
225
|
-
export declare function classifyArrival(req: DoorRequest, trusted: PublicKeyRef[], route: string, trustProxy: boolean, at: string, signature?: SignatureCheck): Classified;
|
|
227
|
+
export declare function classifyArrival(req: DoorRequest, trusted: PublicKeyRef[], route: string, trustProxy: boolean, at: string, signature?: SignatureCheck, revoked?: (chainDigests: string[]) => string | null): Classified;
|
|
226
228
|
export interface DoorOptions {
|
|
227
229
|
/** the log to append to, in place of the one the config names; for embedding and tests */
|
|
228
230
|
log?: LogSink;
|
package/dist/door.js
CHANGED
|
@@ -11,12 +11,13 @@ import { closeSync, fstatSync, openSync, readFileSync } from "node:fs";
|
|
|
11
11
|
import { createServer } from "node:http";
|
|
12
12
|
import { captureKeyFrom } from "./capture.js";
|
|
13
13
|
import { digestOf, loadPrivateKey, loadPublicKey, sha256Hex } from "./crypto.js";
|
|
14
|
-
import { decodeDelegation, delegationValidAt, verifyDelegation } from "./delegation.js";
|
|
14
|
+
import { decodeDelegation, delegationValidAt, grantChainDigests, verifyDelegation } from "./delegation.js";
|
|
15
15
|
import { parseGrantHeader, GRANT_HEADER } from "./gateway-http.js";
|
|
16
16
|
import { createIssuer, ReceiptPending } from "./issue.js";
|
|
17
17
|
import { createWebBotAuthVerifier, normalizeAuthority } from "./web-bot-auth.js";
|
|
18
18
|
import { createPartnerEngine, PARTNER_FACT, PARTNER_TOOL } from "./door-partner.js";
|
|
19
19
|
import { openLog } from "./log-sink.js";
|
|
20
|
+
import { createRevocationList } from "./revocation.js";
|
|
20
21
|
import { openExporter } from "./otel.js";
|
|
21
22
|
import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
|
|
22
23
|
export const DOOR_VERSION = "0.1.0";
|
|
@@ -283,9 +284,10 @@ export function signedRequestOf(req) {
|
|
|
283
284
|
* arrival `verified` as its signature agent. With both, the signature binds the grant to its sender when the grant names
|
|
284
285
|
* that signature agent; a grant presented under another agent's signature is `wrong-sender` and the arrival `claimed`.
|
|
285
286
|
* An `x-agent-custody-agent` header or a signature that did not verify alone is `claimed`. Nothing at all is `unknown`.
|
|
286
|
-
* Without `signature`, a `Signature-Input` header is recorded as `unchecked`.
|
|
287
|
+
* Without `signature`, a `Signature-Input` header is recorded as `unchecked`. `revoked`, when given, says why a grant
|
|
288
|
+
* that verified is revoked (from its chain's digests, leaf first), or null when it is not; a revoked grant is `claimed`.
|
|
287
289
|
*/
|
|
288
|
-
export function classifyArrival(req, trusted, route, trustProxy, at, signature) {
|
|
290
|
+
export function classifyArrival(req, trusted, route, trustProxy, at, signature, revoked) {
|
|
289
291
|
const url = requestUrl(req);
|
|
290
292
|
const method = (req.method ?? "GET").toUpperCase();
|
|
291
293
|
const declaredRaw = req.headers[AGENT_HEADER];
|
|
@@ -313,6 +315,9 @@ export function classifyArrival(req, trusted, route, trustProxy, at, signature)
|
|
|
313
315
|
if (!checked.ok)
|
|
314
316
|
return { arrival: { class: "claimed", subject, grant: "invalid", grantError: checked.error, ...base } };
|
|
315
317
|
const grant = checked.delegation;
|
|
318
|
+
const revocation = revoked?.(grantChainDigests(envelope));
|
|
319
|
+
if (revocation)
|
|
320
|
+
return { arrival: { class: "claimed", subject: grant.agent, grant: "revoked", grantError: revocation, ...base } };
|
|
316
321
|
if (!delegationValidAt(grant, at))
|
|
317
322
|
return { arrival: { class: "claimed", subject: grant.agent, grant: "invalid", grantError: "the grant is outside its validity window", ...base } };
|
|
318
323
|
if (!grant.scopes.includes(route))
|
|
@@ -388,6 +393,20 @@ const json = (status, headers, body) => ({ status, headers: { "content-type": "a
|
|
|
388
393
|
export function createDoorCore(cfg, options, framework) {
|
|
389
394
|
const key = loadPrivateKey(cfg.identity.keyFile);
|
|
390
395
|
const trusted = cfg.trustedPrincipalKeys.map(loadPublicKey);
|
|
396
|
+
const revocations = createRevocationList(cfg.revokedGrants);
|
|
397
|
+
revocations.reload();
|
|
398
|
+
const revoked = (chainDigests) => {
|
|
399
|
+
try {
|
|
400
|
+
revocations.reload();
|
|
401
|
+
}
|
|
402
|
+
catch (e) {
|
|
403
|
+
// fail closed: a revocation list that cannot be read revokes every grant until it can
|
|
404
|
+
return `the grant cannot be checked against the revocation list (${e instanceof Error ? e.message : String(e)})`;
|
|
405
|
+
}
|
|
406
|
+
if (!revocations.has(chainDigests))
|
|
407
|
+
return null;
|
|
408
|
+
return revocations.has(chainDigests.slice(0, 1)) ? "the grant has been revoked" : "a grant above it in its chain has been revoked";
|
|
409
|
+
};
|
|
391
410
|
const captureKey = cfg.captureKeyEnv ? captureKeyFrom(process.env[cfg.captureKeyEnv] ?? (() => { throw new Error(`capture key: environment variable ${cfg.captureKeyEnv} is not set`); })()) : undefined;
|
|
392
411
|
for (const [route, rule] of Object.entries(cfg.capture ?? {})) {
|
|
393
412
|
for (const side of [rule.args, rule.result, rule.facts])
|
|
@@ -453,7 +472,7 @@ export function createDoorCore(cfg, options, framework) {
|
|
|
453
472
|
const path = "path" in norm ? norm.path : url.pathname;
|
|
454
473
|
const route = "path" in norm ? matchRoute(cfg.routes, cfg.unmatchedRoute, method, path) : cfg.unmatchedRoute;
|
|
455
474
|
const signature = webBotAuth ? await webBotAuth.verify(signedRequestOf(req)) : undefined;
|
|
456
|
-
const { arrival, delegation, signer } = classifyArrival(req, trusted, route, !!cfg.trustProxy, timestamp, signature);
|
|
475
|
+
const { arrival, delegation, signer } = classifyArrival(req, trusted, route, !!cfg.trustProxy, timestamp, signature, revoked);
|
|
457
476
|
const checkedAgent = arrival.class === "verified";
|
|
458
477
|
const by = checkedAgent ? "agent" : "remote";
|
|
459
478
|
arrival.rate = { by, ...rates.hit(`${by}:${checkedAgent ? arrival.subject : arrival.remote}`) };
|
package/dist/gateway.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { type FlushResult } from "./issue.ts";
|
|
|
6
6
|
import { type LogSink } from "./log-sink.ts";
|
|
7
7
|
import { type ReceiptExporter } from "./otel.ts";
|
|
8
8
|
import type { ReceiptBundle } from "./receipt.ts";
|
|
9
|
+
export { writeRevokedGrants } from "./revocation.ts";
|
|
9
10
|
export declare const GATEWAY_VERSION = "0.1.0";
|
|
10
11
|
export declare const RECEIPT_META_KEY = "agent-custody/receipt";
|
|
11
12
|
export declare const MODEL_META_KEY = "agent-custody/model";
|
|
@@ -80,8 +81,6 @@ export interface GatewayHost {
|
|
|
80
81
|
/** closes the upstreams; every session opened from this host is finished with */
|
|
81
82
|
close(): Promise<void>;
|
|
82
83
|
}
|
|
83
|
-
/** Writes the revocation list whole, by rename, so a gateway re-reading it never sees half a file. */
|
|
84
|
-
export declare function writeRevokedGrants(path: string, digests: string[]): void;
|
|
85
84
|
export declare function createGatewayHost(cfg: GatewayConfig, options?: GatewayOptions): Promise<GatewayHost>;
|
|
86
85
|
/** One gateway for the grant the config names: what `agent-custody gateway` serves over stdio. Closing it closes the host. */
|
|
87
86
|
export declare function createGateway(cfg: GatewayConfig, options?: GatewayOptions): Promise<Gateway>;
|
package/dist/gateway.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// The MCP gateway: sits between an agent and its upstreams, MCP servers or REST APIs, enforces scope + Cedar policy,
|
|
2
2
|
// and emits a signed, logged receipt for every tool call, allowed or denied.
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
|
-
import { appendFileSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync,
|
|
4
|
+
import { appendFileSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, statSync } from "node:fs";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
7
7
|
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
@@ -23,6 +23,8 @@ import { captureKeyFrom, effectiveRule } from "./capture.js";
|
|
|
23
23
|
import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
|
|
24
24
|
import { compileRego, evaluateRego, isRegoFile } from "./policy-rego.js";
|
|
25
25
|
import { createOpaServerPolicy } from "./opa-server.js";
|
|
26
|
+
import { createRevocationList } from "./revocation.js";
|
|
27
|
+
export { writeRevokedGrants } from "./revocation.js";
|
|
26
28
|
import { OPERATION_META_KEY, OperationStore, ownerAlive } from "./operations.js";
|
|
27
29
|
export const GATEWAY_VERSION = "0.1.0";
|
|
28
30
|
export const RECEIPT_META_KEY = "agent-custody/receipt";
|
|
@@ -87,12 +89,6 @@ export function upstreamEnv(extra) {
|
|
|
87
89
|
}
|
|
88
90
|
return { ...base, ...(extra ?? {}) };
|
|
89
91
|
}
|
|
90
|
-
/** Writes the revocation list whole, by rename, so a gateway re-reading it never sees half a file. */
|
|
91
|
-
export function writeRevokedGrants(path, digests) {
|
|
92
|
-
const tmp = `${path}.${process.pid}.tmp`;
|
|
93
|
-
writeFileSync(tmp, JSON.stringify(digests, null, 2) + "\n");
|
|
94
|
-
renameSync(tmp, path);
|
|
95
|
-
}
|
|
96
92
|
export async function createGatewayHost(cfg, options = {}) {
|
|
97
93
|
const gatewayKey = loadPrivateKey(cfg.identity.keyFile);
|
|
98
94
|
const trusted = cfg.trustedPrincipalKeys.map(loadPublicKey);
|
|
@@ -250,41 +246,10 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
250
246
|
if (cfg.approvals?.tools.some((rule) => rule.tool === f.tool))
|
|
251
247
|
throw new Error(`fact "${f.name}" uses tool ${f.tool}, which requires approval; a fact lookup must be a read that does not require approval`);
|
|
252
248
|
}
|
|
253
|
-
// Revoked grants
|
|
254
|
-
//
|
|
255
|
-
|
|
256
|
-
const
|
|
257
|
-
let revokedSeen = "";
|
|
258
|
-
const reloadRevoked = () => {
|
|
259
|
-
if (!cfg.revokedGrants)
|
|
260
|
-
return;
|
|
261
|
-
if (!existsSync(cfg.revokedGrants)) {
|
|
262
|
-
if (revokedSeen !== "absent") {
|
|
263
|
-
revokedSet.clear();
|
|
264
|
-
revokedSeen = "absent";
|
|
265
|
-
}
|
|
266
|
-
return;
|
|
267
|
-
}
|
|
268
|
-
// inode as well as mtime: `revoke` replaces the file by rename, so two writes in one mtime tick are still seen
|
|
269
|
-
const st = statSync(cfg.revokedGrants);
|
|
270
|
-
const m = `${st.ino}:${st.mtimeMs}:${st.size}`;
|
|
271
|
-
if (m === revokedSeen)
|
|
272
|
-
return;
|
|
273
|
-
const list = JSON.parse(readFileSync(cfg.revokedGrants, "utf8"));
|
|
274
|
-
if (!Array.isArray(list))
|
|
275
|
-
throw new Error(`${cfg.revokedGrants}: expected a JSON array of grant digests`);
|
|
276
|
-
revokedSet.clear();
|
|
277
|
-
for (const d of list)
|
|
278
|
-
if (typeof d === "string")
|
|
279
|
-
revokedSet.add(d);
|
|
280
|
-
revokedSeen = m;
|
|
281
|
-
};
|
|
282
|
-
const revoke = (digest) => {
|
|
283
|
-
reloadRevoked();
|
|
284
|
-
revokedSet.add(digest);
|
|
285
|
-
if (cfg.revokedGrants)
|
|
286
|
-
writeRevokedGrants(cfg.revokedGrants, [...revokedSet]);
|
|
287
|
-
};
|
|
249
|
+
// Revoked grants, re-read whenever the file changes. Checked when a session opens and again on every call, so
|
|
250
|
+
// revocation takes effect on the next call of a running session, without a key rotation.
|
|
251
|
+
const revocations = createRevocationList(cfg.revokedGrants);
|
|
252
|
+
const revoke = (digest) => revocations.add(digest);
|
|
288
253
|
// One host, as many upstreams as the agents' jobs need. Each tool name belongs to exactly one upstream, decided at
|
|
289
254
|
// startup, so a receipt's tool is unambiguous and consumed facts flow across them.
|
|
290
255
|
const upstreamConfigs = cfg.upstreams ? cfg.upstreams.map((u) => ({ name: u.name, cfg: u })) : [{ name: "upstream", cfg: cfg.upstream }];
|
|
@@ -425,19 +390,19 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
425
390
|
const principalKeyid = grant.keyid;
|
|
426
391
|
const chainDigests = grantChainDigests(grantEnvelope);
|
|
427
392
|
const grantDigest = chainDigests[0];
|
|
428
|
-
|
|
429
|
-
if (
|
|
393
|
+
revocations.reload();
|
|
394
|
+
if (revocations.has(chainDigests))
|
|
430
395
|
throw new Error("delegation grant has been revoked");
|
|
431
396
|
/** Why the grant is not in force at `at`, or null. Asked on every call, and again just before a forward. */
|
|
432
397
|
const grantProblem = (at = new Date().toISOString()) => {
|
|
433
398
|
try {
|
|
434
|
-
|
|
399
|
+
revocations.reload();
|
|
435
400
|
}
|
|
436
401
|
catch (e) {
|
|
437
402
|
// fail closed: a revocation list that cannot be read revokes everything until it can
|
|
438
403
|
return `cannot be checked against the revocation list (${e instanceof Error ? e.message : String(e)})`;
|
|
439
404
|
}
|
|
440
|
-
if (
|
|
405
|
+
if (revocations.has(chainDigests))
|
|
441
406
|
return "has been revoked";
|
|
442
407
|
if (!delegationValidAt(delegation, at))
|
|
443
408
|
return Date.parse(at) < Date.parse(delegation.issuedAt) ? "is not yet valid" : "has expired";
|
|
@@ -780,10 +745,7 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
780
745
|
revoke,
|
|
781
746
|
policyDigest: () => currentPolicy().digest,
|
|
782
747
|
tools: () => advertised.map((t) => t.name),
|
|
783
|
-
revoked: () =>
|
|
784
|
-
reloadRevoked();
|
|
785
|
-
return [...revokedSet];
|
|
786
|
-
},
|
|
748
|
+
revoked: () => revocations.list(),
|
|
787
749
|
async reconcile(operationId) {
|
|
788
750
|
if (!operations)
|
|
789
751
|
throw new Error("gateway has no financial operations configured");
|
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:
|
|
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>;
|