@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.
Files changed (39) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +36 -3
  3. package/dist/approvals/broker.d.ts +2 -0
  4. package/dist/approvals/broker.d.ts.map +1 -1
  5. package/dist/approvals/broker.js +11 -2
  6. package/dist/approvals/broker.js.map +1 -1
  7. package/dist/approvals/terminal-channel.d.ts +2 -0
  8. package/dist/approvals/terminal-channel.d.ts.map +1 -1
  9. package/dist/approvals/terminal-channel.js +21 -5
  10. package/dist/approvals/terminal-channel.js.map +1 -1
  11. package/dist/approvals/types.d.ts +27 -1
  12. package/dist/approvals/types.d.ts.map +1 -1
  13. package/dist/cli.js +186 -12
  14. package/dist/cli.js.map +1 -1
  15. package/dist/http/evaluate-server.d.ts +56 -0
  16. package/dist/http/evaluate-server.d.ts.map +1 -0
  17. package/dist/http/evaluate-server.js +212 -0
  18. package/dist/http/evaluate-server.js.map +1 -0
  19. package/dist/index.d.ts +3 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +3 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/proxy/facade.d.ts +14 -0
  24. package/dist/proxy/facade.d.ts.map +1 -1
  25. package/dist/proxy/facade.js +81 -1
  26. package/dist/proxy/facade.js.map +1 -1
  27. package/dist/proxy/facts.d.ts +39 -0
  28. package/dist/proxy/facts.d.ts.map +1 -0
  29. package/dist/proxy/facts.js +54 -0
  30. package/dist/proxy/facts.js.map +1 -0
  31. package/package.json +18 -13
  32. package/src/approvals/broker.ts +13 -2
  33. package/src/approvals/terminal-channel.ts +26 -6
  34. package/src/approvals/types.ts +28 -1
  35. package/src/cli.ts +185 -12
  36. package/src/http/evaluate-server.ts +251 -0
  37. package/src/index.ts +10 -1
  38. package/src/proxy/facade.ts +95 -1
  39. package/src/proxy/facts.ts +75 -0
@@ -0,0 +1,251 @@
1
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
2
+ import { timingSafeEqual } from "node:crypto";
3
+ import { evaluate, type LoadedPolicy, type Verdict } from "@agentlaw/core";
4
+ import { redactArgs } from "@agentlaw/audit";
5
+
6
+ const DEFAULT_REDACT = ["password", "token", "secret", "apiKey"];
7
+ /** A verdict request is a tool name and a handful of facts, never a payload. */
8
+ const MAX_BODY_BYTES = 64 * 1024;
9
+
10
+ /** The slice of AuditWriter this server uses — lets tests inject a failing chain. */
11
+ export interface EvaluateAuditChain {
12
+ append(event: string, fields: Record<string, unknown>): unknown;
13
+ flush(): Promise<void>;
14
+ }
15
+
16
+ export interface EvaluateServerOptions {
17
+ /** Signed, verified policy (from `loadPolicy`). An unsigned one is refused. */
18
+ loaded: LoadedPolicy;
19
+ /** The one environment this evaluator answers for; any other is denied. */
20
+ environment: string;
21
+ /** Server identity used in rule matching (`match.server`). Defaults to `environment`. */
22
+ serverName?: string;
23
+ audit: EvaluateAuditChain;
24
+ /** Bearer token callers must present. Absent = no auth (only for a loopback bind). */
25
+ token?: string;
26
+ now?: () => number;
27
+ }
28
+
29
+ export interface EvaluateResponse {
30
+ decision: "allow" | "approve" | "deny";
31
+ effect?: string;
32
+ ruleId?: string;
33
+ reason?: string;
34
+ policyHash?: string;
35
+ }
36
+
37
+ class BadRequest extends Error {}
38
+
39
+ function send(res: ServerResponse, status: number, body: EvaluateResponse | Record<string, unknown>): void {
40
+ const text = JSON.stringify(body);
41
+ res.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(text) });
42
+ res.end(text);
43
+ }
44
+
45
+ function deny(reason: string, extra: Partial<EvaluateResponse> = {}): EvaluateResponse {
46
+ return { decision: "deny", reason, ...extra };
47
+ }
48
+
49
+ /**
50
+ * Sin token (`serve --no-auth`, sólo en loopback) el que puede pegarle al
51
+ * puerto es también una página abierta en el navegador del operador: por DNS
52
+ * rebinding (un dominio suyo que resuelve a 127.0.0.1) o directo a
53
+ * 127.0.0.1 con un POST "simple" (text/plain, sin preflight). El `Host` de la
54
+ * primera no es loopback; la segunda no puede mandar `application/json` sin
55
+ * preflight. Las dos se cortan acá.
56
+ */
57
+ const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
58
+
59
+ function hostIsLoopback(host: string | undefined): boolean {
60
+ if (!host) return false;
61
+ const h = host.trim().toLowerCase();
62
+ const name = h.startsWith("[") ? h.slice(0, h.indexOf("]") + 1) : h.replace(/:\d+$/, "");
63
+ return LOOPBACK_HOSTS.has(name);
64
+ }
65
+
66
+ function isJsonContentType(value: string | undefined): boolean {
67
+ return (value ?? "").split(";")[0]!.trim().toLowerCase() === "application/json";
68
+ }
69
+
70
+ function tokenMatches(header: string | undefined, token: string): boolean {
71
+ const presented = header?.startsWith("Bearer ") ? header.slice("Bearer ".length) : "";
72
+ const a = Buffer.from(presented);
73
+ const b = Buffer.from(token);
74
+ return a.length === b.length && timingSafeEqual(a, b);
75
+ }
76
+
77
+ async function readJson(req: IncomingMessage): Promise<unknown> {
78
+ const chunks: Buffer[] = [];
79
+ let size = 0;
80
+ for await (const chunk of req) {
81
+ size += (chunk as Buffer).length;
82
+ if (size > MAX_BODY_BYTES) throw new BadRequest("body too large");
83
+ chunks.push(chunk as Buffer);
84
+ }
85
+ try {
86
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
87
+ } catch {
88
+ throw new BadRequest("body is not JSON");
89
+ }
90
+ }
91
+
92
+ function parseCall(body: unknown): { environment: string; tool: string; server?: string; args: Record<string, unknown> } {
93
+ if (typeof body !== "object" || body === null || Array.isArray(body)) throw new BadRequest("body must be an object");
94
+ const b = body as Record<string, unknown>;
95
+ if (typeof b.environment !== "string" || b.environment === "") throw new BadRequest("environment is required");
96
+ if (typeof b.tool !== "string" || b.tool === "") throw new BadRequest("tool is required");
97
+ if (b.server !== undefined && typeof b.server !== "string") throw new BadRequest("server must be a string");
98
+ const args = b.args ?? {};
99
+ if (typeof args !== "object" || args === null || Array.isArray(args)) throw new BadRequest("args must be an object");
100
+ return {
101
+ environment: b.environment,
102
+ tool: b.tool,
103
+ ...(b.server !== undefined ? { server: b.server as string } : {}),
104
+ args: args as Record<string, unknown>,
105
+ };
106
+ }
107
+
108
+ /**
109
+ * The HTTP enforcement point: `POST /evaluate {environment, tool, server?, args}`
110
+ * → `{decision, effect, ruleId, reason?, policyHash}`. For hosts that are not
111
+ * MCP clients (a web app guarding its own write path) but still want the
112
+ * signed policy to decide and the decision to land in the audit chain.
113
+ *
114
+ * Same contract as the stdio gateway, minus the forwarding:
115
+ * - only a SIGNED policy is served — a rule that was proposed but never signed
116
+ * into the manifest does not exist here;
117
+ * - write-ahead audit: the response leaves only after its chain entry is on
118
+ * disk; if the chain cannot be written, the answer is deny;
119
+ * - fail-closed: any internal error answers `deny` (HTTP 500), and the caller
120
+ * treats every non-allow as a no.
121
+ * `server` is pinned: rules match against `serverName`, and a body that names
122
+ * another server is denied (ruleId "server") instead of evaluated — otherwise a
123
+ * caller could dodge a `deny` scoped to one server by sending another name.
124
+ * `approve` is returned as-is: this endpoint has no human channel, and the
125
+ * caller decides what a pending approval means (e.g. treat it as deny).
126
+ */
127
+ export function createEvaluateHandler(options: EvaluateServerOptions) {
128
+ const { loaded, environment, audit } = options;
129
+ if (loaded.unsigned) {
130
+ throw new Error("the evaluate server only serves a signed policy (refusing --allow-unsigned)");
131
+ }
132
+ if (options.token !== undefined && options.token.length === 0) {
133
+ // An empty token would match a request with an empty Bearer: refuse it.
134
+ throw new Error("the evaluate server refuses an empty token (omit it to disable auth on loopback)");
135
+ }
136
+ const serverName = options.serverName ?? environment;
137
+ const redactKeys = loaded.manifest.audit?.redactArgs ?? DEFAULT_REDACT;
138
+ const now = options.now ?? Date.now;
139
+
140
+ return async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
141
+ try {
142
+ const path = (req.url ?? "/").split("?")[0];
143
+ if (path === "/health" && req.method === "GET") {
144
+ send(res, 200, { ok: true, environment, policyHash: loaded.hash, ...(loaded.keyId ? { keyId: loaded.keyId } : {}) });
145
+ return;
146
+ }
147
+ if (path !== "/evaluate") {
148
+ send(res, 404, deny("not found"));
149
+ return;
150
+ }
151
+ if (req.method !== "POST") {
152
+ send(res, 405, deny("method not allowed"));
153
+ return;
154
+ }
155
+ if (options.token !== undefined && !tokenMatches(req.headers.authorization, options.token)) {
156
+ send(res, 401, deny("unauthorized"));
157
+ return;
158
+ }
159
+ if (options.token === undefined) {
160
+ if (!hostIsLoopback(req.headers.host)) {
161
+ send(res, 403, deny("forbidden: without a token only a loopback Host is served"));
162
+ return;
163
+ }
164
+ if (!isJsonContentType(req.headers["content-type"])) {
165
+ send(res, 415, deny("unsupported media type: application/json is required"));
166
+ return;
167
+ }
168
+ }
169
+
170
+ let call: ReturnType<typeof parseCall>;
171
+ try {
172
+ call = parseCall(await readJson(req));
173
+ } catch (err) {
174
+ if (err instanceof BadRequest) {
175
+ send(res, 400, deny(`bad request: ${err.message}`));
176
+ return;
177
+ }
178
+ throw err;
179
+ }
180
+
181
+ const server = call.server ?? serverName;
182
+ const verdict: Verdict =
183
+ call.environment !== environment
184
+ ? {
185
+ decision: "deny",
186
+ effect: "deny",
187
+ ruleId: "environment",
188
+ reason: `this evaluator serves "${environment}", not "${call.environment}"`,
189
+ }
190
+ : server !== serverName
191
+ ? {
192
+ decision: "deny",
193
+ effect: "deny",
194
+ ruleId: "server",
195
+ reason: `this evaluator answers as server "${serverName}", not "${server}"`,
196
+ }
197
+ : evaluate(loaded.compiled, { server, tool: call.tool, args: call.args }, now());
198
+
199
+ const { redacted, argsHash } = redactArgs(call.args, redactKeys);
200
+ audit.append("tool_call", {
201
+ via: "http",
202
+ environment: call.environment,
203
+ server,
204
+ tool: call.tool,
205
+ args: redacted,
206
+ argsHash,
207
+ decision: verdict.decision,
208
+ effect: verdict.effect,
209
+ ruleId: verdict.ruleId,
210
+ ...(verdict.reason !== undefined ? { reason: verdict.reason } : {}),
211
+ });
212
+ await audit.flush(); // write-ahead: no verdict leaves without its record
213
+
214
+ send(res, 200, {
215
+ decision: verdict.decision,
216
+ effect: verdict.effect,
217
+ ruleId: verdict.ruleId,
218
+ ...(verdict.reason !== undefined ? { reason: verdict.reason } : {}),
219
+ policyHash: loaded.hash,
220
+ });
221
+ } catch {
222
+ // Fail-closed: whatever broke (the chain, the evaluator), the answer is no.
223
+ if (!res.headersSent) send(res, 500, deny("internal error"));
224
+ else res.end();
225
+ }
226
+ };
227
+ }
228
+
229
+ export interface StartedEvaluateServer {
230
+ server: Server;
231
+ port: number;
232
+ close(): Promise<void>;
233
+ }
234
+
235
+ export async function startEvaluateServer(
236
+ options: EvaluateServerOptions & { host?: string; port?: number },
237
+ ): Promise<StartedEvaluateServer> {
238
+ const handle = createEvaluateHandler(options);
239
+ const server = createServer((req, res) => void handle(req, res));
240
+ await new Promise<void>((resolve, reject) => {
241
+ server.once("error", reject);
242
+ server.listen(options.port ?? 0, options.host ?? "127.0.0.1", () => resolve());
243
+ });
244
+ const address = server.address();
245
+ const port = typeof address === "object" && address ? address.port : 0;
246
+ return {
247
+ server,
248
+ port,
249
+ close: () => new Promise<void>((resolve) => server.close(() => resolve())),
250
+ };
251
+ }
package/src/index.ts CHANGED
@@ -1,10 +1,19 @@
1
1
  /**
2
2
  * @agentlaw/gateway — programmatic surface.
3
- * Multi-server config lands in F3; the CLI is available via the
3
+ * Multi-server config is planned; the CLI is available via the
4
4
  * `agentlaw` bin.
5
5
  */
6
6
  export { scopedEnv } from "./proxy/credscope.js";
7
7
  export { runGateway, type GatewayOptions } from "./proxy/facade.js";
8
+ export { githubPrFacts, type FactsResolver, type FactsInput, type GithubPrFactsOptions } from "./proxy/facts.js";
8
9
  export type { ApprovalChannel, ApprovalRequest } from "./approvals/types.js";
9
10
  export { TerminalApprovalChannel } from "./approvals/terminal-channel.js";
10
11
  export { requestApprovalWithTimeout, type ApprovalOutcome, type ApprovalResult } from "./approvals/broker.js";
12
+ export {
13
+ createEvaluateHandler,
14
+ startEvaluateServer,
15
+ type EvaluateServerOptions,
16
+ type EvaluateAuditChain,
17
+ type EvaluateResponse,
18
+ type StartedEvaluateServer,
19
+ } from "./http/evaluate-server.js";
@@ -15,6 +15,7 @@ import {
15
15
  ToolListChangedNotificationSchema,
16
16
  type ServerCapabilities,
17
17
  } from "@modelcontextprotocol/sdk/types.js";
18
+ import type { FactsResolver } from "./facts.js";
18
19
  import { evaluate, lintManifest, type LoadedPolicy, type Verdict } from "@agentlaw/core";
19
20
  import { AuditWriter, redactArgs } from "@agentlaw/audit";
20
21
  import { scopedEnv } from "./credscope.js";
@@ -44,6 +45,13 @@ export interface GatewayOptions {
44
45
  * a real TTY or network.
45
46
  */
46
47
  approvalChannel?: ApprovalChannel;
48
+ /**
49
+ * Id of the agent session this gateway serves. Exposed to rules as the
50
+ * `$session` synthetic arg and stamped by the host, never taken from a tool
51
+ * call. Lets the approval bridge route a human's question back to the
52
+ * session that asked.
53
+ */
54
+ session?: string;
47
55
  /**
48
56
  * Best-effort mirror of approval events to a remote store (e.g.
49
57
  * @agentlaw/sink-supabase's SupabaseAgentLawSink), so a console watching
@@ -52,6 +60,12 @@ export interface GatewayOptions {
52
60
  * any failure here is swallowed.
53
61
  */
54
62
  remoteAuditSink?: { append(event: string, fields: Record<string, unknown>): Promise<unknown> };
63
+ /**
64
+ * Resolves host facts (`$prBase`, …) before each evaluation — what is true
65
+ * in the world, not what the agent wrote. A resolver that throws counts as
66
+ * "no facts": rules on them fail closed.
67
+ */
68
+ facts?: FactsResolver;
55
69
  }
56
70
 
57
71
  /** Modes with a real channel implementation. Every other/unset value keeps `approve` fail-closed. */
@@ -100,6 +114,17 @@ export async function runGateway(options: GatewayOptions): Promise<void> {
100
114
  options.approvalChannel ?? (manifest.approvals?.mode === "terminal" ? new TerminalApprovalChannel() : undefined);
101
115
 
102
116
  for (const warning of lintManifest(manifest)) log(`warning: ${warning}`);
117
+ // `lintManifest` judges the FILE; this judges the HOST. A manifest can declare
118
+ // `external` perfectly and still have been started by a process that wired no
119
+ // channel — the file is right, the deployment is not, and no lint can see it.
120
+ // Said once at startup, because the alternative is discovering it an hour
121
+ // later as a refusal that explains nothing.
122
+ if (manifest.approvals?.mode === "external" && !approvalChannel) {
123
+ log(
124
+ 'warning: approvals.mode is "external" but no approval channel was configured — ' +
125
+ "every call needing approval will be denied",
126
+ );
127
+ }
103
128
 
104
129
  const audit = await AuditWriter.open({ dir: auditDir, policyHash: loaded.hash });
105
130
  audit.append("policy_loaded", {
@@ -110,7 +135,20 @@ export async function runGateway(options: GatewayOptions): Promise<void> {
110
135
  ...(loaded.unsigned ? { unsigned: true } : {}),
111
136
  });
112
137
 
138
+ // One shutdown, whoever asks first (signal, client EOF, downstream death).
139
+ // It closes the downstream server BEFORE exiting: `process.exit` does not take
140
+ // the child with it, and an orphaned server holding a pipe nobody reads lives
141
+ // forever — the CI host collected six of them from cancelled jobs (oct-2026).
142
+ let shuttingDown = false;
143
+ let closeDownstream: (() => Promise<void>) | undefined;
113
144
  const shutdown = async (code: number): Promise<never> => {
145
+ if (shuttingDown) return new Promise<never>(() => {});
146
+ shuttingDown = true;
147
+ try {
148
+ await closeDownstream?.();
149
+ } catch (err) {
150
+ log(`downstream close failed: ${(err as Error).message}`);
151
+ }
114
152
  try {
115
153
  await audit.flush();
116
154
  } catch (err) {
@@ -133,7 +171,10 @@ export async function runGateway(options: GatewayOptions): Promise<void> {
133
171
  const caps = downstream.getServerCapabilities() ?? {};
134
172
  log(`downstream "${serverName}" connected (${options.command})`);
135
173
 
174
+ closeDownstream = () => downstreamTransport.close();
175
+
136
176
  downstream.onclose = () => {
177
+ if (shuttingDown) return;
137
178
  audit.append("server_down", { server: serverName });
138
179
  log(`downstream "${serverName}" closed — shutting down (fail-closed)`);
139
180
  void shutdown(1);
@@ -167,8 +208,18 @@ export async function runGateway(options: GatewayOptions): Promise<void> {
167
208
  facade.setRequestHandler(CallToolRequestSchema, async (request) => {
168
209
  const tool = request.params.name;
169
210
  const args = (request.params.arguments ?? {}) as Record<string, unknown>;
211
+ let facts: Record<string, unknown> = {};
212
+ if (options.facts) {
213
+ try {
214
+ facts = await options.facts({ server: serverName, tool, args });
215
+ } catch {
216
+ facts = {};
217
+ }
218
+ }
170
219
  const verdict = evaluate(loaded.compiled, { server: serverName, tool, args }, Date.now(), {
171
220
  sessionStartedAt,
221
+ ...(options.session !== undefined ? { session: options.session } : {}),
222
+ facts,
172
223
  });
173
224
 
174
225
  const { redacted, argsHash } = redactArgs(args, redactKeys);
@@ -181,6 +232,7 @@ export async function runGateway(options: GatewayOptions): Promise<void> {
181
232
  effect: verdict.effect,
182
233
  ruleId: verdict.ruleId,
183
234
  ...(verdict.reason !== undefined ? { reason: verdict.reason } : {}),
235
+ ...(Object.keys(facts).length > 0 ? { facts } : {}),
184
236
  ...(loaded.unsigned ? { unsigned: true } : {}),
185
237
  });
186
238
  await audit.flush(); // write-ahead: the record exists before the action does
@@ -197,9 +249,37 @@ export async function runGateway(options: GatewayOptions): Promise<void> {
197
249
  // so does a wired mode (e.g. "external") with nothing actually
198
250
  // injected via GatewayOptions.approvalChannel: the mode alone never
199
251
  // opens the door.
252
+ const why =
253
+ mode === undefined
254
+ ? "the manifest declares no approvals.mode"
255
+ : WIRED_APPROVAL_MODES.has(mode)
256
+ ? `approvals.mode is "${mode}" but no approval channel was configured`
257
+ : `approvals.mode "${mode}" has no channel implementation`;
200
258
  if (mode && WIRED_APPROVAL_MODES.has(mode) && !approvalChannel) {
201
259
  log(`approvals.mode="${mode}" but no approval channel is configured — denying rule=${verdict.ruleId} (fail-closed)`);
202
260
  }
261
+ // The attempt and its reason go into the CHAIN, not only onto stderr.
262
+ // Without this the audit of a host that was never wired is
263
+ // indistinguishable from the audit of one where nobody ever tried:
264
+ // both show a tool_call and nothing after it. Whoever has to explain
265
+ // the refusal reads the chain, and stderr is long gone by then.
266
+ const noChannelFields = {
267
+ server: serverName,
268
+ tool,
269
+ ruleId: verdict.ruleId,
270
+ argsHash,
271
+ channel: "none",
272
+ };
273
+ audit.append("approval_requested", noChannelFields);
274
+ audit.append("approval_resolved", {
275
+ server: serverName,
276
+ tool,
277
+ ruleId: verdict.ruleId,
278
+ outcome: "denied",
279
+ reason: why,
280
+ });
281
+ await audit.flush();
282
+ await mirrorAudit(options.remoteAuditSink, "approval_requested", noChannelFields);
203
283
  return denyPayload("POLICY_APPROVAL_REQUIRED", verdict);
204
284
  }
205
285
  const timeoutMs = manifest.approvals!.timeoutMs;
@@ -220,8 +300,13 @@ export async function runGateway(options: GatewayOptions): Promise<void> {
220
300
  ruleId: verdict.ruleId,
221
301
  server: serverName,
222
302
  tool,
223
- args,
303
+ // Lo que ve el aprobador y lo que guarda un canal remoto
304
+ // (`agent_approvals`) va redactado igual que el audit: un token en
305
+ // los args no tiene por qué terminar en otra base.
306
+ // El downstream, si se aprueba, recibe los args reales.
307
+ args: redacted as Record<string, unknown>,
224
308
  ...(verdict.reason !== undefined ? { reason: verdict.reason } : {}),
309
+ ...(options.session !== undefined ? { session: options.session } : {}),
225
310
  },
226
311
  timeoutMs,
227
312
  );
@@ -231,6 +316,8 @@ export async function runGateway(options: GatewayOptions): Promise<void> {
231
316
  tool,
232
317
  ruleId: verdict.ruleId,
233
318
  outcome: result.outcome,
319
+ // Dónde se resolvió (`focus:<host>`), si el canal lo sabe.
320
+ ...(result.via !== undefined ? { via: result.via } : {}),
234
321
  };
235
322
  audit.append("approval_resolved", resolvedFields);
236
323
  await audit.flush();
@@ -283,5 +370,12 @@ export async function runGateway(options: GatewayOptions): Promise<void> {
283
370
  void shutdown(0);
284
371
  };
285
372
  await facade.connect(facadeTransport);
373
+ // The SDK's StdioServerTransport never reacts to EOF on stdin, so a client
374
+ // that dies without a close handshake (SIGKILL, a cancelled CI job) left the
375
+ // gateway running with nobody on the other end. EOF IS the disconnect.
376
+ process.stdin.once("end", () => {
377
+ log("client stdin closed — shutting down");
378
+ void shutdown(0);
379
+ });
286
380
  log(`serving policy ${manifest.metadata.name}@${manifest.metadata.version} (${loaded.hash})`);
287
381
  }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Host facts: values the enforcement point resolves ITSELF before evaluating,
3
+ * so a rule can decide on what is true in the world instead of on what the
4
+ * agent wrote in the call. They reach the policy as `$`-prefixed condition
5
+ * args (core `EvalContext.facts`) and shadow anything the model sent.
6
+ */
7
+ export interface FactsInput {
8
+ server: string;
9
+ tool: string;
10
+ args: Record<string, unknown>;
11
+ }
12
+
13
+ /** Returns `$`-prefixed facts. Must not throw for "unknown"; omit the fact instead. */
14
+ export type FactsResolver = (call: FactsInput) => Promise<Record<string, unknown>>;
15
+
16
+ export interface GithubPrFactsOptions {
17
+ /** GitHub token with read access to the repos' pull requests. Absent → no facts. */
18
+ token?: string;
19
+ /** Tools whose `{repo, number}` names a PR. Default: mcp-github-ops' merge_pr / flow_ship. */
20
+ tools?: string[];
21
+ apiBase?: string;
22
+ /** Injected in tests. */
23
+ fetch?: typeof fetch;
24
+ timeoutMs?: number;
25
+ }
26
+
27
+ const REPO_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
28
+
29
+ /**
30
+ * `merge_pr` / `flow_ship` of mcp-github-ops take `{repo, number}` and merge
31
+ * into whatever base the PR has on GitHub — there is no `base` argument. A
32
+ * policy that decides on `arg: base` therefore judges a value the tool ignores
33
+ * and the agent controls. This resolver reads
34
+ * the PR and hands the policy:
35
+ *
36
+ * - `$prBase`: the PR's real base branch;
37
+ * - `$baseMismatch`: true when the call ALSO carries a `base` that differs —
38
+ * an agent claiming another target than the one GitHub will merge into.
39
+ *
40
+ * Fail-closed by absence: any failure (no token, bad args, network, non-200)
41
+ * yields no facts, so rules on `$prBase` do not hold and fall to their `else`.
42
+ */
43
+ export function githubPrFacts(options: GithubPrFactsOptions = {}): FactsResolver {
44
+ const tools = new Set(options.tools ?? ["merge_pr", "flow_ship"]);
45
+ const apiBase = (options.apiBase ?? "https://api.github.com").replace(/\/+$/, "");
46
+ const doFetch = options.fetch ?? fetch;
47
+ const timeoutMs = options.timeoutMs ?? 10_000;
48
+
49
+ return async ({ tool, args }) => {
50
+ if (!tools.has(tool) || !options.token) return {};
51
+ const { repo, number } = args;
52
+ if (typeof repo !== "string" || !REPO_RE.test(repo)) return {};
53
+ if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) return {};
54
+ try {
55
+ const res = await doFetch(`${apiBase}/repos/${repo}/pulls/${number}`, {
56
+ headers: {
57
+ accept: "application/vnd.github+json",
58
+ authorization: `Bearer ${options.token}`,
59
+ "x-github-api-version": "2022-11-28",
60
+ },
61
+ signal: AbortSignal.timeout(timeoutMs),
62
+ });
63
+ if (!res.ok) return {};
64
+ const body = (await res.json()) as { base?: { ref?: unknown } };
65
+ const prBase = body?.base?.ref;
66
+ if (typeof prBase !== "string" || prBase === "") return {};
67
+ return {
68
+ $prBase: prBase,
69
+ $baseMismatch: args.base !== undefined && args.base !== prBase,
70
+ };
71
+ } catch {
72
+ return {};
73
+ }
74
+ };
75
+ }