@agentlaw/gateway 0.1.0

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/src/cli.ts ADDED
@@ -0,0 +1,526 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import readline from "node:readline";
6
+ import { stringify as stringifyYaml } from "yaml";
7
+ import {
8
+ generateKeyPair,
9
+ lintManifest,
10
+ loadPolicy,
11
+ parseManifest,
12
+ policyHash,
13
+ PolicyError,
14
+ signManifest,
15
+ verifyManifest,
16
+ evaluate,
17
+ type EvalContext,
18
+ type PolicyManifest,
19
+ } from "@agentlaw/core";
20
+ import { verifyAuditDir } from "@agentlaw/audit";
21
+ import {
22
+ publishEnvironment,
23
+ resolveConfig as resolveSupabaseConfig,
24
+ SupabaseAgentLawSink,
25
+ SupabaseApprovalChannel,
26
+ } from "@agentlaw/sink-supabase";
27
+ import { runGateway, type GatewayOptions } from "./proxy/facade.js";
28
+
29
+ const USAGE = `agentlaw — deterministic security contract for AI agents
30
+
31
+ Usage:
32
+ agentlaw [run] --policy <file> --trust <pub.pem> [--server-name <n>] [--audit-dir <dir>]
33
+ [--environment <name>] -- <server command...>
34
+ run the MCP policy gateway. --environment
35
+ names this gateway to the Supabase console
36
+ (AGENTLAW_SUPABASE_URL/_KEY) and is required
37
+ for approvals.mode:external to reach a human
38
+ on another device; defaults to --server-name.
39
+ agentlaw init [dir] scaffold policy.yaml + keys
40
+ agentlaw wizard [dir] interactive: pick a use-case template,
41
+ generate + sign a policy from it
42
+ agentlaw validate <policy> [--trust <pub.pem>] schema + signature check
43
+ agentlaw hash <policy> print the policy hash
44
+ agentlaw keygen [--out-dir <dir>] [--name <n>] generate an ed25519 keypair
45
+ agentlaw sign <policy> --key <priv.pem> --key-id <id> [--out <file>]
46
+ agentlaw verify <policy> --trust <pub.pem> [--trust <pub2.pem> ...]
47
+ agentlaw explain <policy> --tool <name> [--server <s>] [--args <json>] [--allow-unsigned]
48
+ [--now <iso|epoch-ms>] [--session-age <ms>] probe time-based rules
49
+ agentlaw audit verify <dir> verify the audit hash chain
50
+
51
+ Diagnostics go to stderr; results go to stdout. Exit code 0 = OK, 1 = rejected/broken, 2 = usage error.`;
52
+
53
+ function log(message: string): void {
54
+ process.stderr.write(message + "\n");
55
+ }
56
+
57
+ function out(message: string): void {
58
+ process.stdout.write(message + "\n");
59
+ }
60
+
61
+ function fail(message: string, code = 1): never {
62
+ log(`error: ${message}`);
63
+ process.exit(code);
64
+ }
65
+
66
+ function readManifestFile(path: string): PolicyManifest {
67
+ return parseManifest(readFileSync(path, "utf8"));
68
+ }
69
+
70
+ function readTrust(paths: string[]): string[] {
71
+ return paths.map((path) => readFileSync(path, "utf8"));
72
+ }
73
+
74
+ function cmdValidate(args: string[]): void {
75
+ const { values, positionals } = parseArgs({
76
+ args,
77
+ options: { trust: { type: "string", multiple: true } },
78
+ allowPositionals: true,
79
+ });
80
+ const policyPath = positionals[0] ?? fail("validate: missing <policy>", 2);
81
+ const manifest = readManifestFile(policyPath);
82
+
83
+ for (const warning of lintManifest(manifest)) log(`warning: ${warning}`);
84
+
85
+ if (values.trust && values.trust.length > 0) {
86
+ const result = verifyManifest(manifest, { trustedPublicKeysPem: readTrust(values.trust) });
87
+ if (!result.valid) fail(`signature rejected: ${result.reason}`);
88
+ log(`signature: valid (keyId=${result.keyId})`);
89
+ }
90
+
91
+ out(`OK ${manifest.metadata.name}@${manifest.metadata.version} rules=${manifest.rules.length} hash=${policyHash(manifest)}`);
92
+ }
93
+
94
+ function cmdHash(args: string[]): void {
95
+ const path = args[0] ?? fail("hash: missing <policy>", 2);
96
+ out(policyHash(readManifestFile(path)));
97
+ }
98
+
99
+ function cmdKeygen(args: string[]): void {
100
+ const { values } = parseArgs({
101
+ args,
102
+ options: {
103
+ "out-dir": { type: "string", default: "." },
104
+ name: { type: "string", default: "agentlaw" },
105
+ },
106
+ });
107
+ const dir = resolve(values["out-dir"]!);
108
+ mkdirSync(dir, { recursive: true });
109
+ const privatePath = join(dir, `${values.name}.key`);
110
+ const publicPath = join(dir, `${values.name}.pub`);
111
+ if (existsSync(privatePath)) fail(`refusing to overwrite existing key: ${privatePath}`);
112
+
113
+ const keys = generateKeyPair();
114
+ writeFileSync(privatePath, keys.privateKeyPem, { mode: 0o600 });
115
+ writeFileSync(publicPath, keys.publicKeyPem);
116
+ log(`private key: ${privatePath} (keep it OFF the machine where agents run)`);
117
+ log(`public key: ${publicPath} (pass to the gateway via --trust)`);
118
+ }
119
+
120
+ function cmdSign(args: string[]): void {
121
+ const { values, positionals } = parseArgs({
122
+ args,
123
+ options: {
124
+ key: { type: "string" },
125
+ "key-id": { type: "string" },
126
+ out: { type: "string" },
127
+ },
128
+ allowPositionals: true,
129
+ });
130
+ const policyPath = positionals[0] ?? fail("sign: missing <policy>", 2);
131
+ if (!values.key) fail("sign: --key <private.pem> is required", 2);
132
+ if (!values["key-id"]) fail("sign: --key-id <id> is required", 2);
133
+
134
+ const manifest = readManifestFile(policyPath);
135
+ delete manifest.signature; // re-signing replaces any previous signature
136
+ const signed = signManifest(manifest, {
137
+ privateKeyPem: readFileSync(values.key, "utf8"),
138
+ keyId: values["key-id"],
139
+ });
140
+ const target = values.out ?? policyPath;
141
+ writeFileSync(target, stringifyYaml(signed));
142
+ log(`signed ${target} (keyId=${values["key-id"]})`);
143
+ out(policyHash(signed));
144
+ }
145
+
146
+ function cmdVerify(args: string[]): void {
147
+ const { values, positionals } = parseArgs({
148
+ args,
149
+ options: { trust: { type: "string", multiple: true } },
150
+ allowPositionals: true,
151
+ });
152
+ const policyPath = positionals[0] ?? fail("verify: missing <policy>", 2);
153
+ if (!values.trust || values.trust.length === 0) fail("verify: at least one --trust <pub.pem> is required", 2);
154
+
155
+ const manifest = readManifestFile(policyPath);
156
+ const result = verifyManifest(manifest, { trustedPublicKeysPem: readTrust(values.trust) });
157
+ if (!result.valid) fail(`signature rejected: ${result.reason}`);
158
+ out(`VALID keyId=${result.keyId} hash=${policyHash(manifest)}`);
159
+ }
160
+
161
+ function cmdExplain(args: string[]): void {
162
+ const { values, positionals } = parseArgs({
163
+ args,
164
+ options: {
165
+ tool: { type: "string" },
166
+ server: { type: "string" },
167
+ args: { type: "string" },
168
+ now: { type: "string" },
169
+ "session-age": { type: "string" },
170
+ trust: { type: "string", multiple: true },
171
+ "allow-unsigned": { type: "boolean", default: false },
172
+ },
173
+ allowPositionals: true,
174
+ });
175
+ const policyPath = positionals[0] ?? fail("explain: missing <policy>", 2);
176
+ if (!values.tool) fail("explain: --tool <name> is required", 2);
177
+
178
+ const loaded = loadPolicy({
179
+ path: policyPath,
180
+ trustedPublicKeysPem: values.trust ? readTrust(values.trust) : [],
181
+ allowUnsigned: values["allow-unsigned"],
182
+ });
183
+ if (loaded.unsigned) log("warning: evaluating an UNSIGNED policy (--allow-unsigned)");
184
+
185
+ let callArgs: Record<string, unknown> | undefined;
186
+ if (values.args) {
187
+ try {
188
+ callArgs = JSON.parse(values.args) as Record<string, unknown>;
189
+ } catch {
190
+ fail("explain: --args must be valid JSON", 2);
191
+ }
192
+ }
193
+
194
+ // `--now` accepts an ISO instant or epoch ms; defaults to the real clock.
195
+ // `--session-age <ms>` sets how long the session has run, so `$sessionAgeMs`
196
+ // rules and validity windows can be probed deterministically.
197
+ let now = Date.now();
198
+ if (values.now !== undefined) {
199
+ const parsed = /^\d+$/.test(values.now) ? Number(values.now) : Date.parse(values.now);
200
+ if (Number.isNaN(parsed)) fail("explain: --now must be epoch ms or an ISO-8601 instant", 2);
201
+ now = parsed;
202
+ }
203
+ let context: EvalContext = {};
204
+ if (values["session-age"] !== undefined) {
205
+ const ageMs = Number(values["session-age"]);
206
+ if (!Number.isFinite(ageMs) || ageMs < 0) fail("explain: --session-age must be a non-negative number of ms", 2);
207
+ context = { sessionStartedAt: now - ageMs };
208
+ }
209
+
210
+ const verdict = evaluate(
211
+ loaded.compiled,
212
+ {
213
+ tool: values.tool,
214
+ ...(values.server !== undefined ? { server: values.server } : {}),
215
+ ...(callArgs !== undefined ? { args: callArgs } : {}),
216
+ },
217
+ now,
218
+ context,
219
+ );
220
+ out(JSON.stringify({ policy: loaded.hash, ...verdict }, null, 2));
221
+ process.exitCode = verdict.decision === "deny" ? 1 : 0;
222
+ }
223
+
224
+ async function cmdAudit(args: string[]): Promise<void> {
225
+ const [sub, dir] = args;
226
+ if (sub !== "verify" || !dir) fail("usage: agentlaw audit verify <dir>", 2);
227
+ const report = await verifyAuditDir(dir);
228
+ if (report.ok) {
229
+ out(`OK ${report.entries} entries across ${report.files.length} file(s) — chain intact`);
230
+ return;
231
+ }
232
+ const err = report.error!;
233
+ fail(`chain BROKEN at ${err.file}:${err.line}${err.seq !== undefined ? ` (seq ${err.seq})` : ""} — ${err.reason}`);
234
+ }
235
+
236
+ const EXAMPLE_POLICY = `apiVersion: agentlaw/v1alpha1
237
+ kind: PolicyManifest
238
+ metadata:
239
+ name: my-agent-policy
240
+ version: 0.1.0
241
+ description: Starter policy — reads allowed, writes need approval, everything else denied.
242
+ defaults:
243
+ effect: deny
244
+ rules:
245
+ - id: reads
246
+ match: { tool: ["read_*", "list_*", "get_*", "search_*"] }
247
+ effect: allow
248
+ - id: writes-need-approval
249
+ match: { tool: ["write_*", "edit_*", "create_*", "move_*"] }
250
+ effect: approve
251
+ reason: write operations require human approval
252
+ - id: no-delete
253
+ match: { tool: ["delete_*", "remove_*"] }
254
+ effect: forbid
255
+ reason: destructive operations are forbidden by policy
256
+ limits:
257
+ - { match: { tool: "*" }, max: 120, per: 1m }
258
+ `;
259
+
260
+ function cmdInit(args: string[]): void {
261
+ const dir = resolve(args[0] ?? ".");
262
+ mkdirSync(dir, { recursive: true });
263
+ const policyPath = join(dir, "policy.yaml");
264
+ if (existsSync(policyPath)) fail(`refusing to overwrite existing ${policyPath}`);
265
+ writeFileSync(policyPath, EXAMPLE_POLICY);
266
+ cmdKeygen(["--out-dir", dir, "--name", "policy"]);
267
+ log(`policy: ${policyPath}`);
268
+ log("");
269
+ log("next steps:");
270
+ log(` 1. edit ${policyPath} to match your tools`);
271
+ log(` 2. agentlaw sign ${policyPath} --key ${join(dir, "policy.key")} --key-id my-key`);
272
+ log(` 3. wrap your MCP server:`);
273
+ log(` npx @agentlaw/gateway --policy policy.yaml --trust policy.pub -- <your MCP server command>`);
274
+ }
275
+
276
+ function paymentsPolicy(params: { approveAbove: number; hourlyLimit: number }): string {
277
+ return `apiVersion: agentlaw/v1alpha1
278
+ kind: PolicyManifest
279
+ metadata:
280
+ name: payments-policy
281
+ version: 0.1.0
282
+ description: Payments — auto-approve below a threshold, human approval above it and after too many calls in an hour.
283
+ defaults:
284
+ effect: deny
285
+ rules:
286
+ - id: pay-decision
287
+ match: { tool: create_payment }
288
+ when:
289
+ - { arg: amount, op: gte, value: ${params.approveAbove} }
290
+ effect: approve
291
+ else: allow
292
+ reason: payments under ${params.approveAbove} clear automatically
293
+ limits:
294
+ - id: pay-hourly
295
+ match: { tool: create_payment }
296
+ max: ${params.hourlyLimit}
297
+ per: 1h
298
+ onExceeded: approve
299
+ approvals:
300
+ mode: terminal
301
+ timeoutMs: 300000
302
+ `;
303
+ }
304
+
305
+ function filesystemPolicy(params: { sandboxRoot: string }): string {
306
+ const escaped = params.sandboxRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
307
+ return `apiVersion: agentlaw/v1alpha1
308
+ kind: PolicyManifest
309
+ metadata:
310
+ name: filesystem-policy
311
+ version: 0.1.0
312
+ description: Filesystem agent — sandboxed writes, shell forbidden.
313
+ defaults:
314
+ effect: deny
315
+ rules:
316
+ - id: fs-write-sandbox
317
+ match: { tool: [write_file, edit_file] }
318
+ when:
319
+ - { arg: path, op: matches, value: "^${escaped}" }
320
+ effect: allow
321
+ else: deny
322
+ reason: writes only inside the sandbox
323
+ - id: shell-forbidden
324
+ match: { tool: shell }
325
+ effect: forbid
326
+ reason: shell execution is never allowed
327
+ `;
328
+ }
329
+
330
+ async function cmdWizard(args: string[]): Promise<void> {
331
+ const dir = resolve(args[0] ?? ".");
332
+ mkdirSync(dir, { recursive: true });
333
+ const policyPath = join(dir, "policy.yaml");
334
+ if (existsSync(policyPath)) fail(`refusing to overwrite existing ${policyPath}`);
335
+
336
+ // NOTE: deliberately NOT readline's `.question()` in a sequential-await
337
+ // style — on Windows, repeated `question()` calls against non-TTY stdin
338
+ // (piped/redirected) reliably stall after the first answer (reproduced
339
+ // standalone, unrelated to this codebase: a Node/libuv quirk, not a bug
340
+ // in this file). Pulling lines from the readline async iterator instead
341
+ // is unaffected and works identically for a live terminal.
342
+ const rl = readline.createInterface({ input: process.stdin });
343
+ const lines = rl[Symbol.asyncIterator]();
344
+ const ask = async (promptText: string): Promise<string> => {
345
+ process.stdout.write(promptText);
346
+ const { value, done } = await lines.next();
347
+ return done ? "" : value.trim();
348
+ };
349
+
350
+ let policyText: string;
351
+ try {
352
+ out("AgentLaw policy wizard — pick a starting point:");
353
+ out(" 1) Payments & billing (approval threshold + hourly rate escalation)");
354
+ out(" 2) Filesystem / coding agent (sandboxed writes, shell forbidden)");
355
+ out(" 3) Blank starter (same as `agentlaw init`)");
356
+ const choice = await ask("use case [1-3]: ");
357
+
358
+ if (choice === "1") {
359
+ const approveAboveRaw = await ask("auto-approve payments below what amount? [100]: ");
360
+ const hourlyLimitRaw = await ask("max create_payment calls per hour before requiring approval? [5]: ");
361
+ policyText = paymentsPolicy({
362
+ approveAbove: Number(approveAboveRaw || "100"),
363
+ hourlyLimit: Number(hourlyLimitRaw || "5"),
364
+ });
365
+ } else if (choice === "2") {
366
+ const sandboxRootRaw = await ask("sandbox root path? [/home/dev/sandbox/]: ");
367
+ policyText = filesystemPolicy({ sandboxRoot: sandboxRootRaw || "/home/dev/sandbox/" });
368
+ } else {
369
+ policyText = EXAMPLE_POLICY;
370
+ }
371
+ } finally {
372
+ rl.close();
373
+ }
374
+
375
+ writeFileSync(policyPath, policyText);
376
+ cmdKeygen(["--out-dir", dir, "--name", "policy"]);
377
+
378
+ // Sign immediately with the keypair just generated for this policy — this
379
+ // is a human running the wizard interactively at their own terminal with a
380
+ // brand-new local dev key, squarely "the signer is a human" (see RFC-0001).
381
+ // A general re-sign of an existing/shared key stays the manual `agentlaw
382
+ // sign` step.
383
+ const manifest = readManifestFile(policyPath);
384
+ delete manifest.signature;
385
+ const signed = signManifest(manifest, {
386
+ privateKeyPem: readFileSync(join(dir, "policy.key"), "utf8"),
387
+ keyId: "wizard",
388
+ });
389
+ writeFileSync(policyPath, stringifyYaml(signed));
390
+
391
+ for (const warning of lintManifest(signed)) log(`warning: ${warning}`);
392
+
393
+ log("");
394
+ log(`policy: ${policyPath} (signed, keyId=wizard)`);
395
+ log(`hash: ${policyHash(signed)}`);
396
+ log("");
397
+ log("next steps:");
398
+ log(` wrap your MCP server:`);
399
+ log(` npx @agentlaw/gateway --policy ${policyPath} --trust ${join(dir, "policy.pub")} -- <your MCP server command>`);
400
+ log("");
401
+ log(` move ${join(dir, "policy.key")} off this machine (secret manager / CI secret) before using this beyond local dev.`);
402
+ log(
403
+ ` note: this CLI is your operator shell — anything that can already run "agentlaw keygen && agentlaw sign" ` +
404
+ `here could mint its own valid signature too. The real security boundary is tool-call enforcement, not shell access to this command.`,
405
+ );
406
+ }
407
+
408
+ async function cmdRun(argv: string[]): Promise<void> {
409
+ const sep = argv.indexOf("--");
410
+ if (sep === -1 || sep === argv.length - 1) {
411
+ fail("run: expected `-- <downstream MCP server command>` after the flags", 2);
412
+ }
413
+ const { values } = parseArgs({
414
+ args: argv.slice(0, sep),
415
+ options: {
416
+ policy: { type: "string" },
417
+ trust: { type: "string", multiple: true },
418
+ "allow-unsigned": { type: "boolean", default: false },
419
+ "server-name": { type: "string", default: "server" },
420
+ "audit-dir": { type: "string" },
421
+ environment: { type: "string" },
422
+ },
423
+ });
424
+ if (!values.policy) fail("run: --policy <file> is required", 2);
425
+
426
+ // Fail-closed: any policy problem exits BEFORE stdio opens — the MCP
427
+ // client sees a failed server and zero tools, never an unguarded one.
428
+ const loaded = loadPolicy({
429
+ path: values.policy,
430
+ trustedPublicKeysPem: values.trust ? readTrust(values.trust) : [],
431
+ allowUnsigned: values["allow-unsigned"],
432
+ });
433
+ if (loaded.unsigned) log("warning: running with an UNSIGNED policy (--allow-unsigned)");
434
+
435
+ // `approvals.mode: external` is the cross-host channel: writes a pending row
436
+ // to Supabase and polls until a human resolves it from the console, instead
437
+ // of the local-TTY `terminal` prompt. Only wired when Supabase is actually
438
+ // configured (AGENTLAW_SUPABASE_URL/KEY, or --environment's matching env) —
439
+ // unconfigured stays fail-closed, same as any other unwired mode.
440
+ let approvalChannel: GatewayOptions["approvalChannel"];
441
+ let remoteAuditSink: GatewayOptions["remoteAuditSink"];
442
+ if (loaded.manifest.approvals?.mode === "external") {
443
+ const environment = values.environment ?? values["server-name"]!;
444
+ const supabaseConfig = { environment };
445
+ if (resolveSupabaseConfig(supabaseConfig)) {
446
+ const sink = new SupabaseAgentLawSink(supabaseConfig, loaded.hash);
447
+ remoteAuditSink = sink;
448
+ approvalChannel = new SupabaseApprovalChannel(supabaseConfig);
449
+ await publishEnvironment(supabaseConfig, {
450
+ kind: "mcp",
451
+ policyHash: loaded.hash,
452
+ policy: loaded.manifest,
453
+ mode: "enforce",
454
+ signed: !loaded.unsigned,
455
+ ...(loaded.keyId !== undefined ? { keyId: loaded.keyId } : {}),
456
+ });
457
+ } else {
458
+ log(
459
+ `warning: approvals.mode is "external" but Supabase isn't configured ` +
460
+ `(AGENTLAW_SUPABASE_URL/AGENTLAW_SUPABASE_KEY) — approve verdicts will fail closed.`,
461
+ );
462
+ }
463
+ }
464
+
465
+ const [command, ...args] = argv.slice(sep + 1) as [string, ...string[]];
466
+ await runGateway({
467
+ loaded,
468
+ serverName: values["server-name"]!,
469
+ command,
470
+ args,
471
+ ...(values["audit-dir"] !== undefined ? { auditDir: values["audit-dir"] } : {}),
472
+ ...(approvalChannel !== undefined ? { approvalChannel } : {}),
473
+ ...(remoteAuditSink !== undefined ? { remoteAuditSink } : {}),
474
+ });
475
+ }
476
+
477
+ async function main(): Promise<void> {
478
+ const [command, ...rest] = process.argv.slice(2);
479
+ const argv = process.argv.slice(2);
480
+ // `npx @agentlaw/gateway --policy … -- <cmd>` (no subcommand) runs the gateway.
481
+ if (command !== undefined && command.startsWith("-") && argv.includes("--")) {
482
+ try {
483
+ return await cmdRun(argv);
484
+ } catch (err) {
485
+ if (err instanceof PolicyError) fail(`[${err.code}] ${err.message}`);
486
+ throw err;
487
+ }
488
+ }
489
+ try {
490
+ switch (command) {
491
+ case "run":
492
+ return await cmdRun(rest);
493
+ case "init":
494
+ return cmdInit(rest);
495
+ case "wizard":
496
+ return await cmdWizard(rest);
497
+ case "validate":
498
+ return cmdValidate(rest);
499
+ case "hash":
500
+ return cmdHash(rest);
501
+ case "keygen":
502
+ return cmdKeygen(rest);
503
+ case "sign":
504
+ return cmdSign(rest);
505
+ case "verify":
506
+ return cmdVerify(rest);
507
+ case "explain":
508
+ return cmdExplain(rest);
509
+ case "audit":
510
+ return await cmdAudit(rest);
511
+ case undefined:
512
+ case "help":
513
+ case "--help":
514
+ case "-h":
515
+ out(USAGE);
516
+ return;
517
+ default:
518
+ fail(`unknown command "${command}"\n\n${USAGE}`, 2);
519
+ }
520
+ } catch (err) {
521
+ if (err instanceof PolicyError) fail(`[${err.code}] ${err.message}`);
522
+ throw err;
523
+ }
524
+ }
525
+
526
+ await main();
package/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @agentlaw/gateway — programmatic surface.
3
+ * Multi-server config lands in F3; the CLI is available via the
4
+ * `agentlaw` bin.
5
+ */
6
+ export { scopedEnv } from "./proxy/credscope.js";
7
+ export { runGateway, type GatewayOptions } from "./proxy/facade.js";
8
+ export type { ApprovalChannel, ApprovalRequest } from "./approvals/types.js";
9
+ export { TerminalApprovalChannel } from "./approvals/terminal-channel.js";
10
+ export { requestApprovalWithTimeout, type ApprovalOutcome, type ApprovalResult } from "./approvals/broker.js";
@@ -0,0 +1,24 @@
1
+ import { getDefaultEnvironment } from "@modelcontextprotocol/sdk/client/stdio.js";
2
+ import type { CredentialScope } from "@agentlaw/core";
3
+
4
+ /**
5
+ * Environment for a spawned downstream server, per the policy's
6
+ * `credentials` block. Absent block = "none": the child gets only the SDK's
7
+ * minimal safe environment — a credential the policy never named cannot
8
+ * leak into a tool process.
9
+ */
10
+ export function scopedEnv(scope: CredentialScope | undefined): Record<string, string> {
11
+ const base = getDefaultEnvironment();
12
+ if (!scope || scope.env === "none") return base;
13
+ if (scope.env === "inherit") {
14
+ return Object.fromEntries(
15
+ Object.entries(process.env).filter(([, v]) => v !== undefined),
16
+ ) as Record<string, string>;
17
+ }
18
+ const out = { ...base };
19
+ for (const name of scope.allow ?? []) {
20
+ const value = process.env[name];
21
+ if (value !== undefined) out[name] = value;
22
+ }
23
+ return out;
24
+ }