@strixgov/mcp-proxy 0.2.5 → 0.3.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.
@@ -0,0 +1,431 @@
1
+ /**
2
+ * HTTP upstream transport for the Strix MCP proxy (Side U of
3
+ * docs/strategy/specs/mcp-proxy-http-transport-scope-v1.md).
4
+ *
5
+ * MCP Client ──stdio──▶ [Strix Proxy] ──Streamable HTTP──▶ hosted MCP server
6
+ *
7
+ * The proxy still speaks stdio to its client. Only the leg to the upstream
8
+ * changes. Everything above the transport (policy, approval gate, signed
9
+ * receipts and outcomes) is untouched, so a call to an HTTP upstream is
10
+ * governed exactly like a call to a stdio upstream.
11
+ *
12
+ * What this module adds is the set of refusals an outbound HTTP leg needs
13
+ * that a child process never did:
14
+ *
15
+ * - The URL must be https. Plain http is accepted only for a loopback
16
+ * host (tests and local servers), never for a remote one.
17
+ * - A URL carrying a username or password is refused: the credential
18
+ * would ride every request line and every error message.
19
+ * - Every request is checked against an origin allow-list (default: the
20
+ * upstream URL's own origin). The MCP SDK can be told by a server to
21
+ * use another endpoint; this is where that stops.
22
+ * - Redirects are refused, all of them. `fetch` is called with
23
+ * `redirect: "manual"` and any 3xx is an error. A redirect is how a
24
+ * request with an Authorization header ends up somewhere it was never
25
+ * meant to go.
26
+ * - The host name is resolved before every request, and the request is
27
+ * refused if any address is private, link-local, loopback (unless the
28
+ * URL itself names a loopback host), or a cloud metadata address.
29
+ * `allowPrivateNetwork: true` admits RFC 1918 / ULA ranges for an
30
+ * upstream inside your own network; metadata and link-local addresses
31
+ * are refused even then.
32
+ * - Header values that carry credentials come from environment variables
33
+ * named in the config, never from the config file itself. Literal
34
+ * values for credential-shaped header names are refused at startup.
35
+ * - Resolved secret values are scrubbed from every error message that
36
+ * leaves this module.
37
+ * - A POST response body larger than `maxResponseBytes` (default 8 MiB)
38
+ * is cut off and reported as UPSTREAM_RESPONSE_TOO_LARGE. The upstream
39
+ * has already acted by then; only the result is discarded.
40
+ * - A POST that does not answer within `timeoutMs` is aborted and
41
+ * reported as UPSTREAM_OUTCOME_UNKNOWN: the request was sent, so the
42
+ * server may have acted. Nothing here retries a call.
43
+ *
44
+ * Residual, stated rather than hidden: the address check and the TCP
45
+ * connect are two separate resolutions, so a host whose DNS answer changes
46
+ * between them (rebinding) is not fully excluded. Pinning the connect to
47
+ * the checked address needs a custom dispatcher; it is listed as a follow-up
48
+ * in the scope packet.
49
+ */
50
+
51
+ import dns from "node:dns/promises";
52
+ import net from "node:net";
53
+
54
+ /** errorCode / audit code for a request sent but not answered in time. */
55
+ export const UPSTREAM_OUTCOME_UNKNOWN = "UPSTREAM_OUTCOME_UNKNOWN";
56
+
57
+ const DEFAULT_TIMEOUT_MS = 60_000;
58
+ const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
59
+
60
+ /** errorCode / audit code for a response body larger than maxResponseBytes. */
61
+ export const UPSTREAM_RESPONSE_TOO_LARGE = "UPSTREAM_RESPONSE_TOO_LARGE";
62
+
63
+ /** Header names whose values must never be written literally in a config. */
64
+ const SENSITIVE_HEADER = /^(authorization|proxy-authorization|cookie)$|token|secret|key|password|credential|auth/i;
65
+
66
+ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
67
+
68
+ export class UpstreamHttpError extends Error {
69
+ constructor(code, message) {
70
+ super(message);
71
+ this.name = "UpstreamHttpError";
72
+ this.code = code;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Validate an `upstream.url` config block and return its normalized form.
78
+ * Throws UpstreamHttpError on any refusal. Pure: no network, no env reads.
79
+ *
80
+ * @param {object} upstream
81
+ */
82
+ export function validateHttpUpstream(upstream) {
83
+ if (!upstream || typeof upstream.url !== "string" || !upstream.url) {
84
+ throw new UpstreamHttpError("INVALID_URL", "upstream.url must be a non-empty string");
85
+ }
86
+ let url;
87
+ try {
88
+ url = new URL(upstream.url);
89
+ } catch {
90
+ throw new UpstreamHttpError("INVALID_URL", "upstream.url is not a valid URL");
91
+ }
92
+ if (url.username || url.password) {
93
+ throw new UpstreamHttpError(
94
+ "CREDENTIAL_IN_URL",
95
+ "upstream.url must not carry a username or password; put the credential in a header sourced from an environment variable",
96
+ );
97
+ }
98
+ const loopback = isLoopbackHost(url.hostname);
99
+ if (url.protocol === "http:") {
100
+ if (!loopback) {
101
+ throw new UpstreamHttpError(
102
+ "INSECURE_URL",
103
+ "upstream.url must be https (plain http is accepted only for a loopback host)",
104
+ );
105
+ }
106
+ } else if (url.protocol !== "https:") {
107
+ throw new UpstreamHttpError("INSECURE_URL", `upstream.url protocol '${url.protocol}' is not supported`);
108
+ }
109
+
110
+ const allowedOrigins = new Set([url.origin]);
111
+ if (upstream.allowedOrigins !== undefined) {
112
+ if (!Array.isArray(upstream.allowedOrigins)) {
113
+ throw new UpstreamHttpError("INVALID_CONFIG", "upstream.allowedOrigins must be an array of origins");
114
+ }
115
+ for (const o of upstream.allowedOrigins) {
116
+ let parsed;
117
+ try {
118
+ parsed = new URL(o);
119
+ } catch {
120
+ throw new UpstreamHttpError("INVALID_CONFIG", `upstream.allowedOrigins entry is not a URL`);
121
+ }
122
+ if (parsed.origin !== o.replace(/\/$/, "")) {
123
+ throw new UpstreamHttpError(
124
+ "INVALID_CONFIG",
125
+ "upstream.allowedOrigins entries must be bare origins (scheme://host[:port]), with no path",
126
+ );
127
+ }
128
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopbackHost(parsed.hostname))) {
129
+ throw new UpstreamHttpError("INSECURE_URL", "upstream.allowedOrigins entries must be https");
130
+ }
131
+ allowedOrigins.add(parsed.origin);
132
+ }
133
+ }
134
+
135
+ const headers = upstream.headers ?? {};
136
+ if (typeof headers !== "object" || Array.isArray(headers) || headers === null) {
137
+ throw new UpstreamHttpError("INVALID_CONFIG", "upstream.headers must be an object");
138
+ }
139
+ for (const [name, spec] of Object.entries(headers)) {
140
+ if (typeof spec === "string") {
141
+ if (SENSITIVE_HEADER.test(name)) {
142
+ throw new UpstreamHttpError(
143
+ "LITERAL_CREDENTIAL",
144
+ `upstream.headers["${name}"] looks like a credential; give it as { "fromEnv": "VAR_NAME" } instead of a literal value`,
145
+ );
146
+ }
147
+ continue;
148
+ }
149
+ if (!spec || typeof spec !== "object" || typeof spec.fromEnv !== "string" || !spec.fromEnv) {
150
+ throw new UpstreamHttpError(
151
+ "INVALID_CONFIG",
152
+ `upstream.headers["${name}"] must be a string or { "fromEnv": "VAR_NAME", "prefix"?: string }`,
153
+ );
154
+ }
155
+ if (spec.prefix !== undefined && typeof spec.prefix !== "string") {
156
+ throw new UpstreamHttpError("INVALID_CONFIG", `upstream.headers["${name}"].prefix must be a string`);
157
+ }
158
+ }
159
+
160
+ const timeoutMs = upstream.timeoutMs ?? DEFAULT_TIMEOUT_MS;
161
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) {
162
+ throw new UpstreamHttpError("INVALID_CONFIG", "upstream.timeoutMs must be a positive integer");
163
+ }
164
+ const maxResponseBytes = upstream.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
165
+ if (!Number.isInteger(maxResponseBytes) || maxResponseBytes <= 0) {
166
+ throw new UpstreamHttpError("INVALID_CONFIG", "upstream.maxResponseBytes must be a positive integer");
167
+ }
168
+ if (upstream.allowPrivateNetwork !== undefined && typeof upstream.allowPrivateNetwork !== "boolean") {
169
+ throw new UpstreamHttpError("INVALID_CONFIG", "upstream.allowPrivateNetwork must be a boolean");
170
+ }
171
+
172
+ return {
173
+ url,
174
+ loopback,
175
+ allowedOrigins,
176
+ headers,
177
+ timeoutMs,
178
+ maxResponseBytes,
179
+ allowPrivateNetwork: upstream.allowPrivateNetwork === true,
180
+ };
181
+ }
182
+
183
+ /**
184
+ * Resolve header values from the environment. Missing variables are a
185
+ * startup error, not a silent empty header.
186
+ *
187
+ * @returns {{ headers: Record<string,string>, secrets: string[] }}
188
+ */
189
+ export function resolveHeaders(headerSpec, env = process.env) {
190
+ const headers = {};
191
+ const secrets = [];
192
+ for (const [name, spec] of Object.entries(headerSpec)) {
193
+ if (typeof spec === "string") {
194
+ headers[name] = spec;
195
+ continue;
196
+ }
197
+ const value = env[spec.fromEnv];
198
+ if (typeof value !== "string" || value === "") {
199
+ throw new UpstreamHttpError(
200
+ "MISSING_CREDENTIAL",
201
+ `upstream.headers["${name}"] reads environment variable ${spec.fromEnv}, which is not set`,
202
+ );
203
+ }
204
+ headers[name] = (spec.prefix ?? "") + value;
205
+ secrets.push(value);
206
+ }
207
+ return { headers, secrets };
208
+ }
209
+
210
+ /** Replace every occurrence of a known secret in `text`. */
211
+ export function redact(text, secrets) {
212
+ let out = String(text ?? "");
213
+ for (const s of secrets) {
214
+ if (s && s.length >= 4) out = out.split(s).join("[REDACTED]");
215
+ }
216
+ return out;
217
+ }
218
+
219
+ /**
220
+ * Classify one IP address. Returns null when it is an ordinary public
221
+ * address, otherwise the reason it is refused.
222
+ *
223
+ * @param {string} address
224
+ * @returns {null | "loopback" | "private" | "link-local" | "metadata" | "unspecified" | "reserved"}
225
+ */
226
+ export function classifyAddress(address) {
227
+ let a = address.toLowerCase();
228
+ if (a.startsWith("[") && a.endsWith("]")) a = a.slice(1, -1);
229
+ const mapped = a.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
230
+ if (mapped) a = mapped[1];
231
+
232
+ if (net.isIPv4(a)) {
233
+ const [p, q] = a.split(".").map(Number);
234
+ if (a === "169.254.169.254" || a === "100.100.100.200") return "metadata";
235
+ if (p === 0) return "unspecified";
236
+ if (p === 127) return "loopback";
237
+ if (p === 10) return "private";
238
+ if (p === 172 && q >= 16 && q <= 31) return "private";
239
+ if (p === 192 && q === 168) return "private";
240
+ if (p === 100 && q >= 64 && q <= 127) return "private"; // CGNAT
241
+ if (p === 169 && q === 254) return "link-local";
242
+ if (p >= 224) return "reserved"; // multicast, reserved, broadcast
243
+ return null;
244
+ }
245
+ if (net.isIPv6(a)) {
246
+ if (a === "::") return "unspecified";
247
+ if (a === "::1") return "loopback";
248
+ if (a === "fd00:ec2::254") return "metadata";
249
+ if (/^fe[89ab]/.test(a)) return "link-local";
250
+ if (/^f[cd]/.test(a)) return "private";
251
+ if (/^ff/.test(a)) return "reserved";
252
+ return null;
253
+ }
254
+ return "reserved";
255
+ }
256
+
257
+ /**
258
+ * Decide whether the addresses a host resolves to may be contacted.
259
+ * Throws UpstreamHttpError(ADDRESS_REFUSED) naming the first bad address.
260
+ */
261
+ export function assertAddressesAllowed(addresses, { loopbackUrl, allowPrivateNetwork }) {
262
+ if (!addresses.length) {
263
+ throw new UpstreamHttpError("ADDRESS_REFUSED", "upstream host resolved to no addresses");
264
+ }
265
+ for (const address of addresses) {
266
+ const kind = classifyAddress(address);
267
+ if (kind === null) continue;
268
+ if (kind === "loopback" && loopbackUrl) continue;
269
+ if (kind === "private" && allowPrivateNetwork) continue;
270
+ throw new UpstreamHttpError(
271
+ "ADDRESS_REFUSED",
272
+ `upstream host resolves to a ${kind} address (${address}); refused`,
273
+ );
274
+ }
275
+ }
276
+
277
+ function isLoopbackHost(hostname) {
278
+ return LOOPBACK_HOSTS.has(hostname.toLowerCase());
279
+ }
280
+
281
+ /**
282
+ * Build the guarded fetch the SDK transport uses for every request.
283
+ *
284
+ * @param {ReturnType<typeof validateHttpUpstream>} cfg
285
+ * @param {{ headers: Record<string,string>, secrets: string[], fetchImpl?: typeof fetch,
286
+ * lookup?: (host: string) => Promise<string[]>, onAudit?: (e: object) => void }} deps
287
+ */
288
+ export function createGuardedFetch(cfg, deps) {
289
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
290
+ const lookup = deps.lookup ?? defaultLookup;
291
+ const secrets = deps.secrets ?? [];
292
+ const audit = (event) => {
293
+ try { deps.onAudit?.(event); } catch { /* audit handlers cannot break requests */ }
294
+ };
295
+
296
+ return async function guardedFetch(input, init = {}) {
297
+ const target = new URL(typeof input === "string" || input instanceof URL ? String(input) : input.url);
298
+ if (!cfg.allowedOrigins.has(target.origin)) {
299
+ audit({ kind: "upstream.http.refused", detail: { code: "ORIGIN_NOT_ALLOWED", origin: target.origin } });
300
+ throw new UpstreamHttpError(
301
+ "ORIGIN_NOT_ALLOWED",
302
+ `request to origin ${target.origin} is not in the upstream allow-list; refused`,
303
+ );
304
+ }
305
+ if (target.username || target.password) {
306
+ throw new UpstreamHttpError("CREDENTIAL_IN_URL", "request URL carries userinfo; refused");
307
+ }
308
+
309
+ const host = target.hostname.replace(/^\[|\]$/g, "");
310
+ const addresses = net.isIP(host) ? [host] : await lookup(host);
311
+ try {
312
+ assertAddressesAllowed(addresses, {
313
+ loopbackUrl: isLoopbackHost(target.hostname),
314
+ allowPrivateNetwork: cfg.allowPrivateNetwork,
315
+ });
316
+ } catch (err) {
317
+ audit({ kind: "upstream.http.refused", detail: { code: err.code, host } });
318
+ throw err;
319
+ }
320
+
321
+ const headers = new Headers(init.headers ?? {});
322
+ for (const [k, v] of Object.entries(deps.headers ?? {})) headers.set(k, v);
323
+
324
+ const method = (init.method ?? "GET").toUpperCase();
325
+ // Only a POST carries a JSON-RPC request that can cause an effect, so
326
+ // only a POST gets the hard timeout. The long-lived GET stream the SDK
327
+ // may open for server-initiated messages must not be killed by it.
328
+ let timeoutController = null;
329
+ let timer = null;
330
+ let signal = init.signal;
331
+ if (method === "POST") {
332
+ timeoutController = new AbortController();
333
+ timer = setTimeout(() => timeoutController.abort(new Error("upstream timeout")), cfg.timeoutMs);
334
+ signal = init.signal ? AbortSignal.any([init.signal, timeoutController.signal]) : timeoutController.signal;
335
+ }
336
+
337
+ let response;
338
+ try {
339
+ response = await fetchImpl(target, { ...init, headers, signal, redirect: "manual" });
340
+ } catch (err) {
341
+ if (timeoutController?.signal.aborted) {
342
+ audit({ kind: "upstream.http.timeout", detail: { code: UPSTREAM_OUTCOME_UNKNOWN, timeoutMs: cfg.timeoutMs } });
343
+ throw new UpstreamHttpError(
344
+ UPSTREAM_OUTCOME_UNKNOWN,
345
+ `upstream did not answer within ${cfg.timeoutMs} ms; the request was sent, so the upstream may have acted. Not retried.`,
346
+ );
347
+ }
348
+ throw new UpstreamHttpError("REQUEST_FAILED", redact(err?.message ?? String(err), secrets));
349
+ } finally {
350
+ if (timer) clearTimeout(timer);
351
+ }
352
+
353
+ if (response.status >= 300 && response.status < 400) {
354
+ audit({ kind: "upstream.http.refused", detail: { code: "REDIRECT_REFUSED", status: response.status } });
355
+ try { await response.body?.cancel(); } catch { /* drained */ }
356
+ throw new UpstreamHttpError(
357
+ "REDIRECT_REFUSED",
358
+ `upstream answered with a ${response.status} redirect; redirects are refused`,
359
+ );
360
+ }
361
+ if (method === "POST") return capResponse(response, cfg.maxResponseBytes, audit);
362
+ return response;
363
+ };
364
+ }
365
+
366
+ /**
367
+ * Bound a POST response body. A declared Content-Length over the cap is
368
+ * refused before reading; otherwise the stream is counted and errors as
369
+ * soon as it passes the cap, so an oversized body is never buffered whole.
370
+ */
371
+ function capResponse(response, maxBytes, audit) {
372
+ const tooLarge = () =>
373
+ new UpstreamHttpError(
374
+ UPSTREAM_RESPONSE_TOO_LARGE,
375
+ `upstream response exceeded ${maxBytes} bytes and was discarded; the upstream may already have acted`,
376
+ );
377
+ const declared = Number(response.headers.get("content-length"));
378
+ if (Number.isFinite(declared) && declared > maxBytes) {
379
+ audit({ kind: "upstream.http.refused", detail: { code: UPSTREAM_RESPONSE_TOO_LARGE, declared } });
380
+ try { response.body?.cancel(); } catch { /* drained */ }
381
+ throw tooLarge();
382
+ }
383
+ if (!response.body) return response;
384
+ let seen = 0;
385
+ const counted = response.body.pipeThrough(
386
+ new TransformStream({
387
+ transform(chunk, controller) {
388
+ seen += chunk.byteLength;
389
+ if (seen > maxBytes) {
390
+ audit({ kind: "upstream.http.refused", detail: { code: UPSTREAM_RESPONSE_TOO_LARGE } });
391
+ controller.error(tooLarge());
392
+ return;
393
+ }
394
+ controller.enqueue(chunk);
395
+ },
396
+ }),
397
+ );
398
+ return new Response(counted, { status: response.status, statusText: response.statusText, headers: response.headers });
399
+ }
400
+
401
+ async function defaultLookup(host) {
402
+ const results = await dns.lookup(host, { all: true, verbatim: true });
403
+ return results.map((r) => r.address);
404
+ }
405
+
406
+ /**
407
+ * Build a connected-ready Streamable HTTP client transport for the
408
+ * configured upstream. The SDK is imported lazily so a stdio-only
409
+ * deployment never loads it.
410
+ */
411
+ export async function createHttpUpstreamTransport(upstream, { env, onAudit, fetchImpl, lookup } = {}) {
412
+ const cfg = validateHttpUpstream(upstream);
413
+ const { headers, secrets } = resolveHeaders(cfg.headers, env ?? process.env);
414
+ const guardedFetch = createGuardedFetch(cfg, { headers, secrets, fetchImpl, lookup, onAudit });
415
+ const { StreamableHTTPClientTransport } = await import(
416
+ "@modelcontextprotocol/sdk/client/streamableHttp.js"
417
+ );
418
+ const transport = new StreamableHTTPClientTransport(cfg.url, {
419
+ fetch: guardedFetch,
420
+ // No stream resumption retries: a reconnect never re-sends a call, but
421
+ // keeping the transport's behaviour to "one attempt" makes the no-retry
422
+ // claim trivially true rather than true-by-analysis.
423
+ reconnectionOptions: {
424
+ initialReconnectionDelay: 1000,
425
+ maxReconnectionDelay: 1000,
426
+ reconnectionDelayGrowFactor: 1,
427
+ maxRetries: 0,
428
+ },
429
+ });
430
+ return { transport, origin: cfg.url.origin, secrets };
431
+ }
package/src/index.mjs CHANGED
@@ -9,14 +9,23 @@
9
9
  * consumers can use it directly to validate a config before
10
10
  * committing it to disk.
11
11
  *
12
- * Mode 3 (Capability-Enforced) is the v0.2.0 upgrade path. The seam
12
+ * Mode 3 (Capability-Enforced) has not shipped and carries no date. The seam
13
13
  * is documented in src/proxy.mjs (`buildUpstreamIface`); the
14
14
  * cryptographic primitive is already shipped at
15
15
  * `@strixgov/mcp-token-validator`.
16
16
  */
17
17
 
18
18
  export { startProxy } from "./proxy.mjs";
19
- export { loadConfig, resolveCapabilities } from "./config.mjs";
19
+ export { loadConfig, resolveCapabilities, describeConfig, unknownConfigKeys } from "./config.mjs";
20
+ export {
21
+ createContentGuard,
22
+ scanValue,
23
+ redactText,
24
+ redactValue,
25
+ SECRET_PATTERNS,
26
+ SECRET_IN_ARGUMENTS,
27
+ ARGUMENT_RULE_VIOLATION,
28
+ } from "./content-guard.mjs";
20
29
  export {
21
30
  createShadowDiscovery,
22
31
  SHADOW_LOG_BASENAME,