@agentlaw/gateway 0.1.0 → 0.1.1
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/LICENSE +202 -0
- package/README.md +36 -3
- package/dist/approvals/broker.d.ts +2 -0
- package/dist/approvals/broker.d.ts.map +1 -1
- package/dist/approvals/broker.js +11 -2
- package/dist/approvals/broker.js.map +1 -1
- package/dist/approvals/terminal-channel.d.ts +2 -0
- package/dist/approvals/terminal-channel.d.ts.map +1 -1
- package/dist/approvals/terminal-channel.js +21 -5
- package/dist/approvals/terminal-channel.js.map +1 -1
- package/dist/approvals/types.d.ts +27 -1
- package/dist/approvals/types.d.ts.map +1 -1
- package/dist/cli.js +186 -12
- package/dist/cli.js.map +1 -1
- package/dist/http/evaluate-server.d.ts +56 -0
- package/dist/http/evaluate-server.d.ts.map +1 -0
- package/dist/http/evaluate-server.js +212 -0
- package/dist/http/evaluate-server.js.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/proxy/facade.d.ts +14 -0
- package/dist/proxy/facade.d.ts.map +1 -1
- package/dist/proxy/facade.js +81 -1
- package/dist/proxy/facade.js.map +1 -1
- package/dist/proxy/facts.d.ts +39 -0
- package/dist/proxy/facts.d.ts.map +1 -0
- package/dist/proxy/facts.js +54 -0
- package/dist/proxy/facts.js.map +1 -0
- package/package.json +18 -13
- package/src/approvals/broker.ts +13 -2
- package/src/approvals/terminal-channel.ts +26 -6
- package/src/approvals/types.ts +28 -1
- package/src/cli.ts +185 -12
- package/src/http/evaluate-server.ts +251 -0
- package/src/index.ts +10 -1
- package/src/proxy/facade.ts +95 -1
- package/src/proxy/facts.ts +75 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentlaw/gateway",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "The agentlaw CLI and MCP policy gateway: enforce a signed policy manifest on every tool call an AI agent makes.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -23,16 +23,17 @@
|
|
|
23
23
|
"src"
|
|
24
24
|
],
|
|
25
25
|
"scripts": {
|
|
26
|
-
"build": "tsc -
|
|
27
|
-
"typecheck": "tsc -
|
|
28
|
-
"pretest": "tsc -
|
|
26
|
+
"build": "tsc -p .",
|
|
27
|
+
"typecheck": "tsc -p . --noEmit",
|
|
28
|
+
"pretest": "tsc -p .",
|
|
29
29
|
"dev": "tsx src/cli.ts",
|
|
30
|
-
"test": "node --import tsx --test \"test/**/*.test.ts\""
|
|
30
|
+
"test": "node --import tsx --test \"test/**/*.test.ts\"",
|
|
31
|
+
"prepublishOnly": "npm run build && npm test"
|
|
31
32
|
},
|
|
32
33
|
"dependencies": {
|
|
33
|
-
"@agentlaw/audit": "0.1.
|
|
34
|
-
"@agentlaw/core": "0.1.
|
|
35
|
-
"@agentlaw/sink-supabase": "0.1.
|
|
34
|
+
"@agentlaw/audit": "0.1.1",
|
|
35
|
+
"@agentlaw/core": "0.1.1",
|
|
36
|
+
"@agentlaw/sink-supabase": "0.1.1",
|
|
36
37
|
"@modelcontextprotocol/sdk": "^1.25.2",
|
|
37
38
|
"yaml": "^2.7.0"
|
|
38
39
|
},
|
|
@@ -42,11 +43,10 @@
|
|
|
42
43
|
},
|
|
43
44
|
"repository": {
|
|
44
45
|
"type": "git",
|
|
45
|
-
"url": "git+https://github.com/Mounaji-Webs/agentlaw.git"
|
|
46
|
-
"directory": "packages/gateway"
|
|
46
|
+
"url": "git+https://github.com/Mounaji-Webs/agentlaw-gateway.git"
|
|
47
47
|
},
|
|
48
|
-
"homepage": "https://agentlaw
|
|
49
|
-
"bugs": "https://github.com/Mounaji-Webs/agentlaw/issues",
|
|
48
|
+
"homepage": "https://github.com/Mounaji-Webs/agentlaw-gateway#readme",
|
|
49
|
+
"bugs": "https://github.com/Mounaji-Webs/agentlaw-gateway/issues",
|
|
50
50
|
"keywords": [
|
|
51
51
|
"ai-agents",
|
|
52
52
|
"security",
|
|
@@ -57,5 +57,10 @@
|
|
|
57
57
|
"cli",
|
|
58
58
|
"gateway",
|
|
59
59
|
"model-context-protocol"
|
|
60
|
-
]
|
|
60
|
+
],
|
|
61
|
+
"devDependencies": {
|
|
62
|
+
"@types/node": "^26.6.6",
|
|
63
|
+
"tsx": "^4.20.0",
|
|
64
|
+
"typescript": "^5.8.0"
|
|
65
|
+
}
|
|
61
66
|
}
|
package/src/approvals/broker.ts
CHANGED
|
@@ -4,6 +4,8 @@ export type ApprovalOutcome = "approved" | "denied" | "timeout";
|
|
|
4
4
|
|
|
5
5
|
export interface ApprovalResult {
|
|
6
6
|
outcome: ApprovalOutcome;
|
|
7
|
+
/** Where the human resolved it, when the channel says so (never on timeout). */
|
|
8
|
+
via?: string;
|
|
7
9
|
}
|
|
8
10
|
|
|
9
11
|
/**
|
|
@@ -18,13 +20,22 @@ export async function requestApprovalWithTimeout(
|
|
|
18
20
|
timeoutMs: number,
|
|
19
21
|
): Promise<ApprovalResult> {
|
|
20
22
|
let timer: NodeJS.Timeout;
|
|
23
|
+
// The channel learns OUR deadline, not a clock of its own that starts later:
|
|
24
|
+
// otherwise a vote can land after we timed out and still read as approved.
|
|
25
|
+
const deadlineAt = Date.now() + timeoutMs;
|
|
21
26
|
const timeout = new Promise<ApprovalResult>((resolveTimeout) => {
|
|
22
27
|
timer = setTimeout(() => resolveTimeout({ outcome: "timeout" }), timeoutMs);
|
|
23
28
|
});
|
|
24
29
|
const answer = (async (): Promise<ApprovalResult> => {
|
|
25
30
|
try {
|
|
26
|
-
const
|
|
27
|
-
|
|
31
|
+
const answer = await channel.requestApproval({ ...request, deadlineAt });
|
|
32
|
+
// Fail-closed normalization: only a literal `true` (or `{approved: true}`)
|
|
33
|
+
// opens. A truthy string or a malformed object is a denial.
|
|
34
|
+
const approved = answer === true || (typeof answer === "object" && answer !== null && answer.approved === true);
|
|
35
|
+
const via = typeof answer === "object" && answer !== null && typeof answer.via === "string" && answer.via.trim() !== ""
|
|
36
|
+
? answer.via.trim().slice(0, 120)
|
|
37
|
+
: undefined;
|
|
38
|
+
return via ? { outcome: approved ? "approved" : "denied", via } : { outcome: approved ? "approved" : "denied" };
|
|
28
39
|
} catch {
|
|
29
40
|
return { outcome: "denied" };
|
|
30
41
|
}
|
|
@@ -9,6 +9,31 @@ function ttyPaths(): { inPath: string; outPath: string } {
|
|
|
9
9
|
: { inPath: "/dev/tty", outPath: "/dev/tty" };
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
+
/**
|
|
13
|
+
* Control characters (C0, DEL, C1 — `\u009b` is an 8-bit CSI) and the bidi
|
|
14
|
+
* overrides/isolates, shown as `\uXXXX` instead of reaching the terminal.
|
|
15
|
+
* The tool name is chosen by the agent, not by the downstream server: without
|
|
16
|
+
* this, `tool: "Read\n args: {}\n approve this call? [y/N] \u001b[8m"` paints
|
|
17
|
+
* a fake prompt and hides the real one, and a U+202E in the args reorders what
|
|
18
|
+
* the human reads. `JSON.stringify` alone escapes C0 but not C1 nor bidi.
|
|
19
|
+
*/
|
|
20
|
+
const UNSAFE = /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
|
|
21
|
+
|
|
22
|
+
function visible(text: string): string {
|
|
23
|
+
return text.replace(UNSAFE, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The exact text the human is asked to approve — exported for tests. */
|
|
27
|
+
export function approvalQuestion(request: ApprovalRequest): string {
|
|
28
|
+
const reason = request.reason ? ` (${visible(request.reason)})` : "";
|
|
29
|
+
return (
|
|
30
|
+
`\n[agentlaw] APPROVAL REQUIRED — rule=${visible(request.ruleId)} server=${visible(request.server)} ` +
|
|
31
|
+
`tool=${visible(request.tool)}${reason}\n` +
|
|
32
|
+
` args: ${visible(JSON.stringify(request.args))}\n` +
|
|
33
|
+
` approve this call? [y/N] `
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
12
37
|
/**
|
|
13
38
|
* Prompts a human on the enforcement host's controlling terminal.
|
|
14
39
|
*
|
|
@@ -42,12 +67,7 @@ export class TerminalApprovalChannel implements ApprovalChannel {
|
|
|
42
67
|
const output = new tty.WriteStream(outFd);
|
|
43
68
|
const rl = createInterface({ input, output });
|
|
44
69
|
try {
|
|
45
|
-
const
|
|
46
|
-
const question =
|
|
47
|
-
`\n[agentlaw] APPROVAL REQUIRED — rule=${request.ruleId} server=${request.server} tool=${request.tool}${reason}\n` +
|
|
48
|
-
` args: ${JSON.stringify(request.args)}\n` +
|
|
49
|
-
` approve this call? [y/N] `;
|
|
50
|
-
const answer = await rl.question(question);
|
|
70
|
+
const answer = await rl.question(approvalQuestion(request));
|
|
51
71
|
return /^y(es)?$/i.test(answer.trim());
|
|
52
72
|
} finally {
|
|
53
73
|
rl.close();
|
package/src/approvals/types.ts
CHANGED
|
@@ -4,6 +4,22 @@ export interface ApprovalRequest {
|
|
|
4
4
|
tool: string;
|
|
5
5
|
args: Record<string, unknown>;
|
|
6
6
|
reason?: string;
|
|
7
|
+
/**
|
|
8
|
+
* Id of the agent session that made the call, stamped
|
|
9
|
+
* by the host (`--session` / `AGENTLAW_SESSION`), never taken from the tool
|
|
10
|
+
* call's args. A channel that reaches a human (e.g. an approval UI) uses it to route
|
|
11
|
+
* the human's questions back to that session. Absent when the host gave none.
|
|
12
|
+
*/
|
|
13
|
+
session?: string;
|
|
14
|
+
/**
|
|
15
|
+
* When the gateway stops waiting (epoch ms, `Date.now()` clock), stamped by
|
|
16
|
+
* the broker from manifest.approvals.timeoutMs right before it asks. A
|
|
17
|
+
* channel that leaves the answer somewhere a human can still vote (a
|
|
18
|
+
* Supabase row, an approval UI card) must make that vote expire at this instant:
|
|
19
|
+
* a "yes" that lands after the gateway already timed out is not a yes.
|
|
20
|
+
* Absent when the caller didn't go through the broker.
|
|
21
|
+
*/
|
|
22
|
+
deadlineAt?: number;
|
|
7
23
|
}
|
|
8
24
|
|
|
9
25
|
/**
|
|
@@ -13,5 +29,16 @@ export interface ApprovalRequest {
|
|
|
13
29
|
* buggy channel can never fail open.
|
|
14
30
|
*/
|
|
15
31
|
export interface ApprovalChannel {
|
|
16
|
-
requestApproval(request: ApprovalRequest): Promise<boolean>;
|
|
32
|
+
requestApproval(request: ApprovalRequest): Promise<boolean | ApprovalAnswer>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The richer answer a channel MAY give: who-knows-where the human said it.
|
|
37
|
+
* `via` lands in the `approval_resolved` audit entry (e.g. `ui:host-1` when
|
|
38
|
+
* the approval was resolved from an approval UI card). Only
|
|
39
|
+
* `approved === true` opens — anything else is a denial.
|
|
40
|
+
*/
|
|
41
|
+
export interface ApprovalAnswer {
|
|
42
|
+
approved: boolean;
|
|
43
|
+
via?: string;
|
|
17
44
|
}
|
package/src/cli.ts
CHANGED
|
@@ -9,15 +9,17 @@ import {
|
|
|
9
9
|
lintManifest,
|
|
10
10
|
loadPolicy,
|
|
11
11
|
parseManifest,
|
|
12
|
+
parseManifestWithSource,
|
|
12
13
|
policyHash,
|
|
13
14
|
PolicyError,
|
|
14
15
|
signManifest,
|
|
15
|
-
|
|
16
|
+
verifyParsedManifest,
|
|
16
17
|
evaluate,
|
|
18
|
+
type DelegationRevocation,
|
|
17
19
|
type EvalContext,
|
|
18
20
|
type PolicyManifest,
|
|
19
21
|
} from "@agentlaw/core";
|
|
20
|
-
import { verifyAuditDir } from "@agentlaw/audit";
|
|
22
|
+
import { AuditWriter, verifyAuditDir } from "@agentlaw/audit";
|
|
21
23
|
import {
|
|
22
24
|
publishEnvironment,
|
|
23
25
|
resolveConfig as resolveSupabaseConfig,
|
|
@@ -25,17 +27,31 @@ import {
|
|
|
25
27
|
SupabaseApprovalChannel,
|
|
26
28
|
} from "@agentlaw/sink-supabase";
|
|
27
29
|
import { runGateway, type GatewayOptions } from "./proxy/facade.js";
|
|
30
|
+
import { githubPrFacts } from "./proxy/facts.js";
|
|
31
|
+
import { startEvaluateServer } from "./http/evaluate-server.js";
|
|
28
32
|
|
|
29
33
|
const USAGE = `agentlaw — deterministic security contract for AI agents
|
|
30
34
|
|
|
31
35
|
Usage:
|
|
32
|
-
agentlaw [run] --policy <file> --trust <pub.pem> [--server-name <n>] [--audit-dir <dir>]
|
|
33
|
-
[--environment <name>] -- <server command...>
|
|
36
|
+
agentlaw [run] --policy <file> --trust <pub.pem> [--server-name <n>] [--audit-dir <dir>] [--session <id>]
|
|
37
|
+
[--environment <name>] [--facts github-pr] -- <server command...>
|
|
34
38
|
run the MCP policy gateway. --environment
|
|
35
39
|
names this gateway to the Supabase console
|
|
36
40
|
(AGENTLAW_SUPABASE_URL/_KEY) and is required
|
|
37
41
|
for approvals.mode:external to reach a human
|
|
38
42
|
on another device; defaults to --server-name.
|
|
43
|
+
--facts github-pr resolves $prBase/$baseMismatch
|
|
44
|
+
from GitHub (AGENTLAW_GITHUB_TOKEN|GITHUB_TOKEN)
|
|
45
|
+
before each evaluation: the PR's real base.
|
|
46
|
+
agentlaw serve --policy <file> --trust <pub.pem> --environment <name> [--port 4950] [--host 127.0.0.1]
|
|
47
|
+
[--server-name <n>] [--audit-dir <dir>] [--no-auth] [--require-expiry]
|
|
48
|
+
HTTP evaluator: POST /evaluate {environment, tool, args}
|
|
49
|
+
-> {decision, ruleId, reason?}. Signed policy only; every
|
|
50
|
+
verdict is audited before it is answered. Callers present
|
|
51
|
+
AGENTLAW_EVALUATE_TOKEN as a Bearer token; without it serve
|
|
52
|
+
refuses to start (a reverse proxy makes loopback public).
|
|
53
|
+
--no-auth opts out, and only on a loopback --host.
|
|
54
|
+
--require-expiry refuses a signature without expiresAt.
|
|
39
55
|
agentlaw init [dir] scaffold policy.yaml + keys
|
|
40
56
|
agentlaw wizard [dir] interactive: pick a use-case template,
|
|
41
57
|
generate + sign a policy from it
|
|
@@ -46,6 +62,10 @@ Usage:
|
|
|
46
62
|
agentlaw verify <policy> --trust <pub.pem> [--trust <pub2.pem> ...]
|
|
47
63
|
agentlaw explain <policy> --tool <name> [--server <s>] [--args <json>] [--allow-unsigned]
|
|
48
64
|
[--now <iso|epoch-ms>] [--session-age <ms>] probe time-based rules
|
|
65
|
+
|
|
66
|
+
run, serve, validate, verify and explain take --revocations <file>: a JSON array of
|
|
67
|
+
{"kid": "...", "revokedAt": "<ISO>"} — delegated signing keys that were revoked.
|
|
68
|
+
NOTHING a revoked key signed verifies, before or after revokedAt.
|
|
49
69
|
agentlaw audit verify <dir> verify the audit hash chain
|
|
50
70
|
|
|
51
71
|
Diagnostics go to stderr; results go to stdout. Exit code 0 = OK, 1 = rejected/broken, 2 = usage error.`;
|
|
@@ -71,19 +91,45 @@ function readTrust(paths: string[]): string[] {
|
|
|
71
91
|
return paths.map((path) => readFileSync(path, "utf8"));
|
|
72
92
|
}
|
|
73
93
|
|
|
94
|
+
/**
|
|
95
|
+
* `--revocations <file>`: las llaves delegadas dadas de baja. Sin este flag la
|
|
96
|
+
* protección de `checkDelegation` (signing.ts) no la usaba ningún comando y una
|
|
97
|
+
* política firmada por una llave revocada arrancaba igual. Un archivo ilegible o con otra forma corta el arranque: una
|
|
98
|
+
* lista de bajas que no se pudo leer no puede leerse como "no hay bajas".
|
|
99
|
+
*/
|
|
100
|
+
function readRevocations(path: string | undefined): { revocations?: DelegationRevocation[] } {
|
|
101
|
+
if (path === undefined) return {};
|
|
102
|
+
let parsed: unknown;
|
|
103
|
+
try {
|
|
104
|
+
parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
105
|
+
} catch (err) {
|
|
106
|
+
fail(`--revocations: cannot read ${path} as JSON (${(err as Error).message})`, 2);
|
|
107
|
+
}
|
|
108
|
+
if (!Array.isArray(parsed)) fail("--revocations: expected a JSON array of {kid, revokedAt}", 2);
|
|
109
|
+
const revocations = (parsed as unknown[]).map((r, i) => {
|
|
110
|
+
const o = r as Record<string, unknown> | null;
|
|
111
|
+
if (!o || typeof o !== "object" || typeof o.kid !== "string" || !o.kid || typeof o.revokedAt !== "string") {
|
|
112
|
+
fail(`--revocations: entry ${i} must be {"kid": string, "revokedAt": string}`, 2);
|
|
113
|
+
}
|
|
114
|
+
return { kid: o.kid, revokedAt: o.revokedAt };
|
|
115
|
+
});
|
|
116
|
+
return { revocations };
|
|
117
|
+
}
|
|
118
|
+
|
|
74
119
|
function cmdValidate(args: string[]): void {
|
|
75
120
|
const { values, positionals } = parseArgs({
|
|
76
121
|
args,
|
|
77
|
-
options: { trust: { type: "string", multiple: true } },
|
|
122
|
+
options: { trust: { type: "string", multiple: true }, revocations: { type: "string" } },
|
|
78
123
|
allowPositionals: true,
|
|
79
124
|
});
|
|
80
125
|
const policyPath = positionals[0] ?? fail("validate: missing <policy>", 2);
|
|
81
|
-
const
|
|
126
|
+
const parsed = parseManifestWithSource(readFileSync(policyPath, "utf8"));
|
|
127
|
+
const { manifest } = parsed;
|
|
82
128
|
|
|
83
129
|
for (const warning of lintManifest(manifest)) log(`warning: ${warning}`);
|
|
84
130
|
|
|
85
131
|
if (values.trust && values.trust.length > 0) {
|
|
86
|
-
const result =
|
|
132
|
+
const { result } = verifyParsedManifest(parsed, { trustedPublicKeysPem: readTrust(values.trust), ...readRevocations(values.revocations) });
|
|
87
133
|
if (!result.valid) fail(`signature rejected: ${result.reason}`);
|
|
88
134
|
log(`signature: valid (keyId=${result.keyId})`);
|
|
89
135
|
}
|
|
@@ -146,16 +192,16 @@ function cmdSign(args: string[]): void {
|
|
|
146
192
|
function cmdVerify(args: string[]): void {
|
|
147
193
|
const { values, positionals } = parseArgs({
|
|
148
194
|
args,
|
|
149
|
-
options: { trust: { type: "string", multiple: true } },
|
|
195
|
+
options: { trust: { type: "string", multiple: true }, revocations: { type: "string" } },
|
|
150
196
|
allowPositionals: true,
|
|
151
197
|
});
|
|
152
198
|
const policyPath = positionals[0] ?? fail("verify: missing <policy>", 2);
|
|
153
199
|
if (!values.trust || values.trust.length === 0) fail("verify: at least one --trust <pub.pem> is required", 2);
|
|
154
200
|
|
|
155
|
-
const
|
|
156
|
-
const result =
|
|
201
|
+
const parsed = parseManifestWithSource(readFileSync(policyPath, "utf8"));
|
|
202
|
+
const { result, signedForm } = verifyParsedManifest(parsed, { trustedPublicKeysPem: readTrust(values.trust), ...readRevocations(values.revocations) });
|
|
157
203
|
if (!result.valid) fail(`signature rejected: ${result.reason}`);
|
|
158
|
-
out(`VALID keyId=${result.keyId} hash=${policyHash(
|
|
204
|
+
out(`VALID keyId=${result.keyId} hash=${policyHash(signedForm)}`);
|
|
159
205
|
}
|
|
160
206
|
|
|
161
207
|
function cmdExplain(args: string[]): void {
|
|
@@ -168,6 +214,7 @@ function cmdExplain(args: string[]): void {
|
|
|
168
214
|
now: { type: "string" },
|
|
169
215
|
"session-age": { type: "string" },
|
|
170
216
|
trust: { type: "string", multiple: true },
|
|
217
|
+
revocations: { type: "string" },
|
|
171
218
|
"allow-unsigned": { type: "boolean", default: false },
|
|
172
219
|
},
|
|
173
220
|
allowPositionals: true,
|
|
@@ -176,6 +223,7 @@ function cmdExplain(args: string[]): void {
|
|
|
176
223
|
if (!values.tool) fail("explain: --tool <name> is required", 2);
|
|
177
224
|
|
|
178
225
|
const loaded = loadPolicy({
|
|
226
|
+
...readRevocations(values.revocations),
|
|
179
227
|
path: policyPath,
|
|
180
228
|
trustedPublicKeysPem: values.trust ? readTrust(values.trust) : [],
|
|
181
229
|
allowUnsigned: values["allow-unsigned"],
|
|
@@ -189,6 +237,11 @@ function cmdExplain(args: string[]): void {
|
|
|
189
237
|
} catch {
|
|
190
238
|
fail("explain: --args must be valid JSON", 2);
|
|
191
239
|
}
|
|
240
|
+
// Un array, null o un escalar no son los args de una tool: el motor los
|
|
241
|
+
// trataría como objeto vacío y el veredicto explicaría otra llamada.
|
|
242
|
+
if (callArgs === null || typeof callArgs !== "object" || Array.isArray(callArgs)) {
|
|
243
|
+
fail("explain: --args must be a JSON object", 2);
|
|
244
|
+
}
|
|
192
245
|
}
|
|
193
246
|
|
|
194
247
|
// `--now` accepts an ISO instant or epoch ms; defaults to the real clock.
|
|
@@ -225,6 +278,10 @@ async function cmdAudit(args: string[]): Promise<void> {
|
|
|
225
278
|
const [sub, dir] = args;
|
|
226
279
|
if (sub !== "verify" || !dir) fail("usage: agentlaw audit verify <dir>", 2);
|
|
227
280
|
const report = await verifyAuditDir(dir);
|
|
281
|
+
// Un directorio mal escrito, o una cadena borrada entera, daba "OK 0
|
|
282
|
+
// entries — chain intact": exit 0 sobre nada. Sin archivos no hay cadena
|
|
283
|
+
// que declarar intacta.
|
|
284
|
+
if (report.ok && report.files.length === 0) fail(`no audit files in ${dir} — nothing to verify (wrong path, or the chain was deleted)`);
|
|
228
285
|
if (report.ok) {
|
|
229
286
|
out(`OK ${report.entries} entries across ${report.files.length} file(s) — chain intact`);
|
|
230
287
|
return;
|
|
@@ -415,17 +472,34 @@ async function cmdRun(argv: string[]): Promise<void> {
|
|
|
415
472
|
options: {
|
|
416
473
|
policy: { type: "string" },
|
|
417
474
|
trust: { type: "string", multiple: true },
|
|
475
|
+
revocations: { type: "string" },
|
|
418
476
|
"allow-unsigned": { type: "boolean", default: false },
|
|
419
477
|
"server-name": { type: "string", default: "server" },
|
|
420
478
|
"audit-dir": { type: "string" },
|
|
479
|
+
session: { type: "string" },
|
|
421
480
|
environment: { type: "string" },
|
|
481
|
+
facts: { type: "string", multiple: true },
|
|
422
482
|
},
|
|
423
483
|
});
|
|
424
484
|
if (!values.policy) fail("run: --policy <file> is required", 2);
|
|
425
485
|
|
|
486
|
+
// Host facts (`--facts github-pr`): resolved from the world before each
|
|
487
|
+
// evaluation, never taken from the call. Unknown names fail before stdio opens.
|
|
488
|
+
let facts: GatewayOptions["facts"];
|
|
489
|
+
for (const name of values.facts ?? []) {
|
|
490
|
+
if (name !== "github-pr") fail(`run: --facts ${name}: unknown resolver (known: github-pr)`, 2);
|
|
491
|
+
const token = process.env.AGENTLAW_GITHUB_TOKEN || process.env.GITHUB_TOKEN || process.env.GH_TOKEN || undefined;
|
|
492
|
+
if (!token) {
|
|
493
|
+
log("warning: --facts github-pr without AGENTLAW_GITHUB_TOKEN/GITHUB_TOKEN/GH_TOKEN — $prBase stays absent and rules on it fail closed.");
|
|
494
|
+
}
|
|
495
|
+
const apiBase = process.env.AGENTLAW_GITHUB_API || undefined;
|
|
496
|
+
facts = githubPrFacts({ ...(token !== undefined ? { token } : {}), ...(apiBase !== undefined ? { apiBase } : {}) });
|
|
497
|
+
}
|
|
498
|
+
|
|
426
499
|
// Fail-closed: any policy problem exits BEFORE stdio opens — the MCP
|
|
427
500
|
// client sees a failed server and zero tools, never an unguarded one.
|
|
428
501
|
const loaded = loadPolicy({
|
|
502
|
+
...readRevocations(values.revocations),
|
|
429
503
|
path: values.policy,
|
|
430
504
|
trustedPublicKeysPem: values.trust ? readTrust(values.trust) : [],
|
|
431
505
|
allowUnsigned: values["allow-unsigned"],
|
|
@@ -442,7 +516,17 @@ async function cmdRun(argv: string[]): Promise<void> {
|
|
|
442
516
|
if (loaded.manifest.approvals?.mode === "external") {
|
|
443
517
|
const environment = values.environment ?? values["server-name"]!;
|
|
444
518
|
const supabaseConfig = { environment };
|
|
445
|
-
|
|
519
|
+
const resolvedSupabase = resolveSupabaseConfig(supabaseConfig);
|
|
520
|
+
if (resolvedSupabase) {
|
|
521
|
+
// Audit 2026-10-24 S1: with the service key this process could PATCH its
|
|
522
|
+
// own pending row to approved. AGENTLAW_SINK_SECRET (agentlaw-control
|
|
523
|
+
// db/020) switches the sink to RPCs that can't.
|
|
524
|
+
if (resolvedSupabase.envId && !resolvedSupabase.rpcMode) {
|
|
525
|
+
log(
|
|
526
|
+
"warning: the Supabase sink is using a full-access key — set AGENTLAW_SINK_SECRET " +
|
|
527
|
+
"(least-privilege, agentlaw-control db/020) so this gateway can't approve its own requests.",
|
|
528
|
+
);
|
|
529
|
+
}
|
|
446
530
|
const sink = new SupabaseAgentLawSink(supabaseConfig, loaded.hash);
|
|
447
531
|
remoteAuditSink = sink;
|
|
448
532
|
approvalChannel = new SupabaseApprovalChannel(supabaseConfig);
|
|
@@ -462,6 +546,9 @@ async function cmdRun(argv: string[]): Promise<void> {
|
|
|
462
546
|
}
|
|
463
547
|
}
|
|
464
548
|
|
|
549
|
+
// Session id comes from the host (flag or env), never from a tool call.
|
|
550
|
+
const session = values.session ?? (process.env.AGENTLAW_SESSION || undefined);
|
|
551
|
+
|
|
465
552
|
const [command, ...args] = argv.slice(sep + 1) as [string, ...string[]];
|
|
466
553
|
await runGateway({
|
|
467
554
|
loaded,
|
|
@@ -469,11 +556,95 @@ async function cmdRun(argv: string[]): Promise<void> {
|
|
|
469
556
|
command,
|
|
470
557
|
args,
|
|
471
558
|
...(values["audit-dir"] !== undefined ? { auditDir: values["audit-dir"] } : {}),
|
|
559
|
+
...(session !== undefined ? { session } : {}),
|
|
472
560
|
...(approvalChannel !== undefined ? { approvalChannel } : {}),
|
|
473
561
|
...(remoteAuditSink !== undefined ? { remoteAuditSink } : {}),
|
|
562
|
+
...(facts !== undefined ? { facts } : {}),
|
|
474
563
|
});
|
|
475
564
|
}
|
|
476
565
|
|
|
566
|
+
const LOOPBACK = new Set(["127.0.0.1", "::1", "localhost"]);
|
|
567
|
+
|
|
568
|
+
async function cmdServe(args: string[]): Promise<void> {
|
|
569
|
+
const { values } = parseArgs({
|
|
570
|
+
args,
|
|
571
|
+
options: {
|
|
572
|
+
policy: { type: "string" },
|
|
573
|
+
trust: { type: "string", multiple: true },
|
|
574
|
+
revocations: { type: "string" },
|
|
575
|
+
environment: { type: "string" },
|
|
576
|
+
"server-name": { type: "string" },
|
|
577
|
+
"audit-dir": { type: "string" },
|
|
578
|
+
host: { type: "string", default: "127.0.0.1" },
|
|
579
|
+
port: { type: "string", default: "4950" },
|
|
580
|
+
"no-auth": { type: "boolean", default: false },
|
|
581
|
+
"require-expiry": { type: "boolean", default: false },
|
|
582
|
+
},
|
|
583
|
+
});
|
|
584
|
+
if (!values.policy) fail("serve: --policy <file> is required", 2);
|
|
585
|
+
if (!values.environment) fail("serve: --environment <name> is required", 2);
|
|
586
|
+
if (!values.trust?.length) fail("serve: --trust <pub.pem> is required (serve never runs an unsigned policy)", 2);
|
|
587
|
+
const port = Number(values.port);
|
|
588
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) fail(`serve: bad --port "${values.port}"`, 2);
|
|
589
|
+
const token = process.env.AGENTLAW_EVALUATE_TOKEN || undefined;
|
|
590
|
+
// Auth is the default even on loopback: a Caddy/nginx in front of 127.0.0.1
|
|
591
|
+
// makes "loopback" reachable from the internet without the bind changing.
|
|
592
|
+
if (values["no-auth"]) {
|
|
593
|
+
if (!LOOPBACK.has(values.host!)) fail(`serve: --no-auth is only allowed on a loopback --host, not ${values.host}`, 2);
|
|
594
|
+
if (token) fail("serve: --no-auth and AGENTLAW_EVALUATE_TOKEN are contradictory; pick one", 2);
|
|
595
|
+
} else if (!token) {
|
|
596
|
+
fail("serve: set AGENTLAW_EVALUATE_TOKEN (callers present it as a Bearer token), or pass --no-auth on loopback", 2);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// Fail-closed: a policy that does not verify never opens the port.
|
|
600
|
+
// --require-expiry (E7): sin vencimiento, una versión vieja firmada que
|
|
601
|
+
// permitía más vuelve a cargar si alguien pisa el archivo. Con el flag,
|
|
602
|
+
// una firma "eterna" no abre el puerto.
|
|
603
|
+
const loaded = loadPolicy({
|
|
604
|
+
...readRevocations(values.revocations),
|
|
605
|
+
path: values.policy,
|
|
606
|
+
trustedPublicKeysPem: readTrust(values.trust),
|
|
607
|
+
...(values["require-expiry"] ? { requireExpiry: true } : {}),
|
|
608
|
+
});
|
|
609
|
+
for (const warning of lintManifest(loaded.manifest)) log(`warning: ${warning}`);
|
|
610
|
+
|
|
611
|
+
const audit = await AuditWriter.open({
|
|
612
|
+
dir: values["audit-dir"] ?? loaded.manifest.audit?.dir ?? "./.agentlaw/audit",
|
|
613
|
+
policyHash: loaded.hash,
|
|
614
|
+
});
|
|
615
|
+
audit.append("policy_loaded", {
|
|
616
|
+
policy: loaded.manifest.metadata.name,
|
|
617
|
+
version: loaded.manifest.metadata.version,
|
|
618
|
+
environment: values.environment,
|
|
619
|
+
via: "http",
|
|
620
|
+
...(loaded.keyId !== undefined ? { keyId: loaded.keyId } : {}),
|
|
621
|
+
});
|
|
622
|
+
await audit.flush();
|
|
623
|
+
|
|
624
|
+
const started = await startEvaluateServer({
|
|
625
|
+
loaded,
|
|
626
|
+
environment: values.environment,
|
|
627
|
+
...(values["server-name"] !== undefined ? { serverName: values["server-name"] } : {}),
|
|
628
|
+
audit,
|
|
629
|
+
...(token !== undefined ? { token } : {}),
|
|
630
|
+
host: values.host!,
|
|
631
|
+
port,
|
|
632
|
+
});
|
|
633
|
+
log(`evaluate server for "${values.environment}" on http://${values.host}:${started.port} (policy ${loaded.hash})`);
|
|
634
|
+
|
|
635
|
+
const shutdown = async (): Promise<never> => {
|
|
636
|
+
await started.close();
|
|
637
|
+
try {
|
|
638
|
+
await audit.flush();
|
|
639
|
+
} catch (err) {
|
|
640
|
+
log(`audit flush failed: ${(err as Error).message}`);
|
|
641
|
+
}
|
|
642
|
+
process.exit(0);
|
|
643
|
+
};
|
|
644
|
+
process.on("SIGINT", () => void shutdown());
|
|
645
|
+
process.on("SIGTERM", () => void shutdown());
|
|
646
|
+
}
|
|
647
|
+
|
|
477
648
|
async function main(): Promise<void> {
|
|
478
649
|
const [command, ...rest] = process.argv.slice(2);
|
|
479
650
|
const argv = process.argv.slice(2);
|
|
@@ -490,6 +661,8 @@ async function main(): Promise<void> {
|
|
|
490
661
|
switch (command) {
|
|
491
662
|
case "run":
|
|
492
663
|
return await cmdRun(rest);
|
|
664
|
+
case "serve":
|
|
665
|
+
return await cmdServe(rest);
|
|
493
666
|
case "init":
|
|
494
667
|
return cmdInit(rest);
|
|
495
668
|
case "wizard":
|