hmcp-core 0.0.1 → 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.
Files changed (76) hide show
  1. package/README.md +19 -3
  2. package/dist/approvals.d.ts +508 -0
  3. package/dist/approvals.js +1445 -0
  4. package/dist/argpath.d.ts +75 -0
  5. package/dist/argpath.js +189 -0
  6. package/dist/audit.d.ts +289 -0
  7. package/dist/audit.js +512 -0
  8. package/dist/canonical.d.ts +78 -0
  9. package/dist/canonical.js +146 -0
  10. package/dist/classify-held.d.ts +47 -0
  11. package/dist/classify-held.js +60 -0
  12. package/dist/classify-name.d.ts +55 -0
  13. package/dist/classify-name.js +255 -0
  14. package/dist/decide.d.ts +168 -0
  15. package/dist/decide.js +518 -0
  16. package/dist/egress.d.ts +123 -0
  17. package/dist/egress.js +544 -0
  18. package/dist/enforce.d.ts +78 -0
  19. package/dist/enforce.js +231 -0
  20. package/dist/exposure-apply.d.ts +51 -0
  21. package/dist/exposure-apply.js +69 -0
  22. package/dist/exposure.d.ts +81 -0
  23. package/dist/exposure.js +65 -0
  24. package/dist/file-lock.d.ts +70 -0
  25. package/dist/file-lock.js +165 -0
  26. package/dist/glob.d.ts +11 -0
  27. package/dist/glob.js +55 -0
  28. package/dist/grants.d.ts +204 -0
  29. package/dist/grants.js +372 -0
  30. package/dist/http-util.d.ts +52 -0
  31. package/dist/http-util.js +81 -0
  32. package/dist/index.d.ts +35 -0
  33. package/dist/index.js +36 -0
  34. package/dist/inventory.d.ts +100 -0
  35. package/dist/inventory.js +88 -0
  36. package/dist/ip.d.ts +15 -0
  37. package/dist/ip.js +186 -0
  38. package/dist/jwt.d.ts +57 -0
  39. package/dist/jwt.js +199 -0
  40. package/dist/live-state.d.ts +76 -0
  41. package/dist/live-state.js +57 -0
  42. package/dist/migrate.d.ts +22 -0
  43. package/dist/migrate.js +318 -0
  44. package/dist/pins.d.ts +119 -0
  45. package/dist/pins.js +125 -0
  46. package/dist/policy-batch.d.ts +89 -0
  47. package/dist/policy-batch.js +340 -0
  48. package/dist/policy-source.d.ts +161 -0
  49. package/dist/policy-source.js +299 -0
  50. package/dist/policy-write.d.ts +627 -0
  51. package/dist/policy-write.js +1697 -0
  52. package/dist/policy.d.ts +456 -0
  53. package/dist/policy.js +448 -0
  54. package/dist/redact.d.ts +65 -0
  55. package/dist/redact.js +191 -0
  56. package/dist/registry.d.ts +41 -0
  57. package/dist/registry.js +121 -0
  58. package/dist/remember-defaults.d.ts +9 -0
  59. package/dist/remember-defaults.js +9 -0
  60. package/dist/remember.d.ts +91 -0
  61. package/dist/remember.js +371 -0
  62. package/dist/resolve.d.ts +22 -0
  63. package/dist/resolve.js +34 -0
  64. package/dist/runtime-state.d.ts +65 -0
  65. package/dist/runtime-state.js +35 -0
  66. package/dist/secrets.d.ts +159 -0
  67. package/dist/secrets.js +361 -0
  68. package/dist/tenant.d.ts +83 -0
  69. package/dist/tenant.js +182 -0
  70. package/dist/unicode.d.ts +40 -0
  71. package/dist/unicode.js +103 -0
  72. package/dist/within-host.d.ts +33 -0
  73. package/dist/within-host.js +91 -0
  74. package/dist/within-real.d.ts +7 -0
  75. package/dist/within-real.js +28 -0
  76. package/package.json +33 -4
@@ -0,0 +1,123 @@
1
+ import type { EgressConfig } from "./policy.js";
2
+ export declare class EgressDenied extends Error {
3
+ readonly code: string;
4
+ constructor(message: string, code: string);
5
+ }
6
+ export interface EgressCheck {
7
+ readonly ok: boolean;
8
+ readonly code?: string;
9
+ readonly reason?: string;
10
+ }
11
+ export interface EgressResponse {
12
+ readonly status: number;
13
+ readonly headers: Record<string, string | string[] | undefined>;
14
+ readonly body: Buffer;
15
+ readonly bytes: number;
16
+ readonly url: string;
17
+ readonly truncated: boolean;
18
+ }
19
+ export interface EgressRequestInit {
20
+ readonly method?: string;
21
+ readonly headers?: Record<string, string>;
22
+ readonly body?: string | Buffer | undefined;
23
+ readonly signal?: AbortSignal | undefined;
24
+ }
25
+ export declare class EgressGuard {
26
+ private readonly agentCache;
27
+ private readonly streamingAgentCache;
28
+ /** Dispatchers a reconfigure replaced, closed once the requests they carry have had time to finish. */
29
+ private readonly retired;
30
+ private current;
31
+ constructor(config: EgressConfig);
32
+ /** The rules in force. Read per request, so a `reconfigure` applies to the next one. */
33
+ get config(): EgressConfig;
34
+ /**
35
+ * Adopt new rules without a restart, so a server added from the console can
36
+ * be reached by a gateway that is already running.
37
+ *
38
+ * Every check reads `config` when a request starts, so the allowlist, methods
39
+ * and private-address rules apply from the next request -- and from the next
40
+ * redirect hop of one already under way, since each hop is checked afresh.
41
+ * The pinned dispatchers are dropped too, because they carry the old
42
+ * timeouts and were keyed under the old rules; a new connection gets a new
43
+ * one. Requests already on the wire are left to finish: tearing down a
44
+ * healthy upstream's event stream because an unrelated host was added would
45
+ * turn every console save into an outage. Their dispatchers are closed
46
+ * gracefully a little later, or when the guard is closed.
47
+ */
48
+ reconfigure(next: EgressConfig): void;
49
+ /** Synchronous pre-flight: everything decidable without touching the network. */
50
+ check(rawUrl: string, method?: string): EgressCheck;
51
+ /** Resolves a hostname and refuses the call if any address is in blocked space. */
52
+ resolveVerified(hostname: string): Promise<{
53
+ address: string;
54
+ family: number;
55
+ }[]>;
56
+ private agentFor;
57
+ /**
58
+ * Performs the request with every limit enforced. Redirects are followed
59
+ * manually, re-running the full check against each hop, because undici's
60
+ * redirect interceptor would send us to a host the allowlist never saw.
61
+ */
62
+ /**
63
+ * A guarded request whose response body is *streamed* rather than buffered.
64
+ *
65
+ * `fetch` above reads the whole body so it can cap it, which is right for a
66
+ * REST call and fatal for an MCP transport: a Streamable HTTP server
67
+ * answers with `text/event-stream` and holds it open for the life of the
68
+ * session, so buffering would simply never return. The gateway therefore
69
+ * used a plain global `fetch` for its upstreams and got none of the
70
+ * protections the policy file promised.
71
+ *
72
+ * This is the subset that is sound for a long-lived stream:
73
+ *
74
+ * - the synchronous pre-flight, and DNS resolution with every returned
75
+ * address checked, so a name that also resolves into private space is
76
+ * refused rather than filtered;
77
+ * - the connection pinned to those addresses, which closes the window
78
+ * between checking a name and connecting to it;
79
+ * - a connect and headers timeout, which bound *reaching* the upstream;
80
+ * - redirects refused or counted here rather than followed by the fetch
81
+ * implementation, so an allowlisted host cannot hand the connection to
82
+ * one the allowlist never saw;
83
+ * - the response cap, applied as the bytes arrive.
84
+ *
85
+ * One limit is deliberately not applied: there is no body timeout, because
86
+ * an idle event stream is the normal state of a healthy MCP session rather
87
+ * than a stall. It is stated here because it is a limit a reader of
88
+ * `policy.yaml` could reasonably expect to apply and will not.
89
+ *
90
+ * On `text/event-stream` the response cap is measured per event, not over
91
+ * the connection. A long session has no meaningful total length, so a total
92
+ * cap would end a healthy one at an arbitrary point; one event, though, is
93
+ * a payload in the sense the cap was written for, and leaving it unbounded
94
+ * let a single unterminated event grow the buffer without limit.
95
+ */
96
+ streamingFetch(rawUrl: string, init?: {
97
+ method?: string;
98
+ headers?: Record<string, string>;
99
+ body?: unknown;
100
+ signal?: AbortSignal;
101
+ }): Promise<Response>;
102
+ /**
103
+ * Counts bytes as they arrive and aborts past the cap.
104
+ *
105
+ * An event stream is measured per event rather than over the connection. A
106
+ * long-lived stream has no meaningful total length, so a total cap would end
107
+ * a healthy session at an arbitrary point -- but exempting it outright left
108
+ * no ceiling at all, and an upstream that opens an event and never ends it
109
+ * grows the reader's buffer until the process dies. One event is a payload
110
+ * in the sense the cap was written for, so the same number applies to it.
111
+ */
112
+ private capped;
113
+ /**
114
+ * A pinned agent for a stream.
115
+ *
116
+ * Separate from `agentFor` because that one sets `bodyTimeout`, which would
117
+ * tear down an event stream that is merely quiet.
118
+ */
119
+ private streamingAgentFor;
120
+ fetch(rawUrl: string, init?: EgressRequestInit): Promise<EgressResponse>;
121
+ private fetchOnce;
122
+ close(): Promise<void>;
123
+ }
package/dist/egress.js ADDED
@@ -0,0 +1,544 @@
1
+ import { lookup as dnsLookup } from "node:dns";
2
+ import { Agent, fetch, request as undiciRequest } from "undici";
3
+ import { classifyAddress, isIpLiteral } from "./ip.js";
4
+ export class EgressDenied extends Error {
5
+ code;
6
+ constructor(message, code) {
7
+ super(message);
8
+ this.code = code;
9
+ this.name = "EgressDenied";
10
+ }
11
+ }
12
+ /** Matches an allowlist entry: `api.example.com`, `*.example.com`, or either with `:port`. */
13
+ function matchesEntry(entry, hostname, port) {
14
+ const [pattern, entryPort] = splitHostPort(entry);
15
+ if (entryPort !== undefined && entryPort !== port)
16
+ return false;
17
+ const host = hostname.toLowerCase().replace(/\.$/, "");
18
+ const pat = pattern.toLowerCase().replace(/\.$/, "");
19
+ if (pat.startsWith("*.")) {
20
+ const suffix = pat.slice(1); // ".example.com"
21
+ return host.endsWith(suffix) && host.length > suffix.length;
22
+ }
23
+ return host === pat;
24
+ }
25
+ function splitHostPort(entry) {
26
+ if (entry.startsWith("[")) {
27
+ const end = entry.indexOf("]");
28
+ if (end === -1)
29
+ return [entry, undefined];
30
+ const host = entry.slice(1, end);
31
+ const rest = entry.slice(end + 1);
32
+ return [host, rest.startsWith(":") ? rest.slice(1) : undefined];
33
+ }
34
+ const idx = entry.lastIndexOf(":");
35
+ if (idx > 0 && !entry.slice(idx + 1).includes(".") && /^\d+$/.test(entry.slice(idx + 1))) {
36
+ return [entry.slice(0, idx), entry.slice(idx + 1)];
37
+ }
38
+ return [entry, undefined];
39
+ }
40
+ function defaultPort(protocol) {
41
+ return protocol === "https:" ? "443" : "80";
42
+ }
43
+ /**
44
+ * The only outbound HTTP path in this project. Generated servers use it to
45
+ * reach their REST API and the gateway uses it to reach HTTP upstreams, so one
46
+ * set of limits covers both.
47
+ *
48
+ * Checks, in order: scheme, embedded credentials, method, host allowlist, then
49
+ * DNS resolution with every returned address validated against private space.
50
+ * The verified addresses are pinned for the connection, which closes the DNS
51
+ * rebinding window between the check and the connect.
52
+ */
53
+ /**
54
+ * The index just past the last complete event boundary in `bytes`, or -1.
55
+ *
56
+ * An event ends at a blank line: `\n\n`, or `\r\n\r\n` where the sender uses
57
+ * CRLF. Scanned from the end, because only the most recent boundary matters --
58
+ * everything before it is an event already delivered and already counted.
59
+ */
60
+ function lastEventBoundary(bytes) {
61
+ const LF = 0x0a;
62
+ const CR = 0x0d;
63
+ for (let i = bytes.length - 1; i >= 1; i -= 1) {
64
+ if (bytes[i] !== LF)
65
+ continue;
66
+ if (bytes[i - 1] === LF)
67
+ return i + 1;
68
+ // \r\n\r\n: this LF, a CR before it, and an LF before that.
69
+ if (bytes[i - 1] === CR && i >= 3 && bytes[i - 2] === LF && bytes[i - 3] === CR)
70
+ return i + 1;
71
+ }
72
+ return -1;
73
+ }
74
+ /** How long a dispatcher replaced by `reconfigure` is left to finish what it is doing before it is closed. */
75
+ const RETIRE_AFTER_MS = 30_000;
76
+ export class EgressGuard {
77
+ agentCache = new Map();
78
+ streamingAgentCache = new Map();
79
+ /** Dispatchers a reconfigure replaced, closed once the requests they carry have had time to finish. */
80
+ retired = new Set();
81
+ current;
82
+ constructor(config) {
83
+ this.current = config;
84
+ }
85
+ /** The rules in force. Read per request, so a `reconfigure` applies to the next one. */
86
+ get config() {
87
+ return this.current;
88
+ }
89
+ /**
90
+ * Adopt new rules without a restart, so a server added from the console can
91
+ * be reached by a gateway that is already running.
92
+ *
93
+ * Every check reads `config` when a request starts, so the allowlist, methods
94
+ * and private-address rules apply from the next request -- and from the next
95
+ * redirect hop of one already under way, since each hop is checked afresh.
96
+ * The pinned dispatchers are dropped too, because they carry the old
97
+ * timeouts and were keyed under the old rules; a new connection gets a new
98
+ * one. Requests already on the wire are left to finish: tearing down a
99
+ * healthy upstream's event stream because an unrelated host was added would
100
+ * turn every console save into an outage. Their dispatchers are closed
101
+ * gracefully a little later, or when the guard is closed.
102
+ */
103
+ reconfigure(next) {
104
+ this.current = next;
105
+ const old = [...this.agentCache.values(), ...this.streamingAgentCache.values()];
106
+ this.agentCache.clear();
107
+ this.streamingAgentCache.clear();
108
+ if (old.length === 0)
109
+ return;
110
+ for (const agent of old)
111
+ this.retired.add(agent);
112
+ // Graceful: undici's close waits for requests already dispatched on it.
113
+ const timer = setTimeout(() => {
114
+ for (const agent of old) {
115
+ this.retired.delete(agent);
116
+ agent.close().catch(() => undefined);
117
+ }
118
+ }, RETIRE_AFTER_MS);
119
+ timer.unref?.();
120
+ }
121
+ /** Synchronous pre-flight: everything decidable without touching the network. */
122
+ check(rawUrl, method = "GET") {
123
+ let url;
124
+ try {
125
+ url = new URL(rawUrl);
126
+ }
127
+ catch {
128
+ return { ok: false, code: "invalid-url", reason: `not a valid URL: ${rawUrl}` };
129
+ }
130
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
131
+ return { ok: false, code: "scheme", reason: `scheme ${url.protocol} is not permitted; use https` };
132
+ }
133
+ if (url.protocol === "http:" && !this.config.allow_http) {
134
+ return {
135
+ ok: false,
136
+ code: "plaintext",
137
+ reason: `plaintext HTTP to ${url.host} is refused; set egress.allow_http to permit it`
138
+ };
139
+ }
140
+ if (url.username || url.password) {
141
+ return { ok: false, code: "url-credentials", reason: "credentials embedded in the URL are refused" };
142
+ }
143
+ const upper = method.toUpperCase();
144
+ if (!this.config.methods.map((m) => m.toUpperCase()).includes(upper)) {
145
+ return {
146
+ ok: false,
147
+ code: "method",
148
+ reason: `method ${upper} is not in egress.methods (${this.config.methods.join(", ")})`
149
+ };
150
+ }
151
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
152
+ const port = url.port || defaultPort(url.protocol);
153
+ if (isIpLiteral(hostname) && !this.config.allow_ip_literals) {
154
+ return {
155
+ ok: false,
156
+ code: "ip-literal",
157
+ reason: `bare IP target ${hostname} is refused; set egress.allow_ip_literals to permit it`
158
+ };
159
+ }
160
+ if (this.config.allow.length === 0) {
161
+ return {
162
+ ok: false,
163
+ code: "no-allowlist",
164
+ reason: "egress.allow is empty, so no outbound host is permitted"
165
+ };
166
+ }
167
+ if (!this.config.allow.some((entry) => matchesEntry(entry, hostname, port))) {
168
+ return {
169
+ ok: false,
170
+ code: "host",
171
+ reason: `${url.host} is not in egress.allow (${this.config.allow.join(", ")})`
172
+ };
173
+ }
174
+ if (this.config.block_private_ips && isIpLiteral(hostname)) {
175
+ const verdict = classifyAddress(hostname);
176
+ if (verdict.blocked)
177
+ return { ok: false, code: "private-address", reason: verdict.reason };
178
+ }
179
+ return { ok: true };
180
+ }
181
+ /** Resolves a hostname and refuses the call if any address is in blocked space. */
182
+ async resolveVerified(hostname) {
183
+ if (isIpLiteral(hostname)) {
184
+ const verdict = classifyAddress(hostname);
185
+ if (this.config.block_private_ips && verdict.blocked) {
186
+ throw new EgressDenied(`refusing to connect: ${verdict.reason}`, "private-address");
187
+ }
188
+ return [{ address: hostname, family: hostname.includes(":") ? 6 : 4 }];
189
+ }
190
+ const records = await new Promise((resolve, reject) => {
191
+ dnsLookup(hostname, { all: true, verbatim: true }, (err, addresses) => {
192
+ if (err)
193
+ reject(new EgressDenied(`DNS lookup for ${hostname} failed: ${err.message}`, "dns"));
194
+ else
195
+ resolve(addresses);
196
+ });
197
+ });
198
+ if (records.length === 0) {
199
+ throw new EgressDenied(`DNS lookup for ${hostname} returned no addresses`, "dns");
200
+ }
201
+ if (this.config.block_private_ips) {
202
+ for (const record of records) {
203
+ const verdict = classifyAddress(record.address);
204
+ if (verdict.blocked) {
205
+ // Refuse outright rather than filtering: a public hostname that also
206
+ // resolves into private space is the rebinding attack, not a quirk.
207
+ throw new EgressDenied(`refusing to connect to ${hostname}: it resolves to ${record.address}, ${verdict.reason}`, "private-address");
208
+ }
209
+ }
210
+ }
211
+ return records;
212
+ }
213
+ agentFor(addresses) {
214
+ const key = addresses.map((a) => a.address).join(",");
215
+ const cached = this.agentCache.get(key);
216
+ if (cached)
217
+ return cached;
218
+ const agent = new Agent({
219
+ connect: {
220
+ // Pin the connection to the addresses we validated.
221
+ lookup: (_hostname, _options, callback) => {
222
+ callback(null, addresses);
223
+ }
224
+ },
225
+ headersTimeout: this.config.timeout_ms,
226
+ bodyTimeout: this.config.timeout_ms,
227
+ connectTimeout: this.config.timeout_ms
228
+ });
229
+ this.agentCache.set(key, agent);
230
+ return agent;
231
+ }
232
+ /**
233
+ * Performs the request with every limit enforced. Redirects are followed
234
+ * manually, re-running the full check against each hop, because undici's
235
+ * redirect interceptor would send us to a host the allowlist never saw.
236
+ */
237
+ /**
238
+ * A guarded request whose response body is *streamed* rather than buffered.
239
+ *
240
+ * `fetch` above reads the whole body so it can cap it, which is right for a
241
+ * REST call and fatal for an MCP transport: a Streamable HTTP server
242
+ * answers with `text/event-stream` and holds it open for the life of the
243
+ * session, so buffering would simply never return. The gateway therefore
244
+ * used a plain global `fetch` for its upstreams and got none of the
245
+ * protections the policy file promised.
246
+ *
247
+ * This is the subset that is sound for a long-lived stream:
248
+ *
249
+ * - the synchronous pre-flight, and DNS resolution with every returned
250
+ * address checked, so a name that also resolves into private space is
251
+ * refused rather than filtered;
252
+ * - the connection pinned to those addresses, which closes the window
253
+ * between checking a name and connecting to it;
254
+ * - a connect and headers timeout, which bound *reaching* the upstream;
255
+ * - redirects refused or counted here rather than followed by the fetch
256
+ * implementation, so an allowlisted host cannot hand the connection to
257
+ * one the allowlist never saw;
258
+ * - the response cap, applied as the bytes arrive.
259
+ *
260
+ * One limit is deliberately not applied: there is no body timeout, because
261
+ * an idle event stream is the normal state of a healthy MCP session rather
262
+ * than a stall. It is stated here because it is a limit a reader of
263
+ * `policy.yaml` could reasonably expect to apply and will not.
264
+ *
265
+ * On `text/event-stream` the response cap is measured per event, not over
266
+ * the connection. A long session has no meaningful total length, so a total
267
+ * cap would end a healthy one at an arbitrary point; one event, though, is
268
+ * a payload in the sense the cap was written for, and leaving it unbounded
269
+ * let a single unterminated event grow the buffer without limit.
270
+ */
271
+ async streamingFetch(rawUrl, init = {}) {
272
+ let method = (init.method ?? "GET").toUpperCase();
273
+ let target = rawUrl;
274
+ let headers = init.headers;
275
+ let body = init.body;
276
+ for (let hop = 0;; hop++) {
277
+ const verdict = this.check(target, method);
278
+ if (!verdict.ok)
279
+ throw new EgressDenied(verdict.reason ?? "egress refused", verdict.code ?? "refused");
280
+ const url = new URL(target);
281
+ const addresses = await this.resolveVerified(url.hostname.replace(/^\[|\]$/g, ""));
282
+ const dispatcher = this.streamingAgentFor(addresses);
283
+ const response = await fetch(target, {
284
+ method,
285
+ ...(headers ? { headers } : {}),
286
+ ...(body !== undefined && body !== null ? { body: body } : {}),
287
+ ...(init.signal ? { signal: init.signal } : {}),
288
+ // Never followed by the implementation: a redirect is a request to a
289
+ // URL the allowlist has not seen, so it comes back here to be checked.
290
+ redirect: "manual",
291
+ dispatcher
292
+ });
293
+ const isRedirect = response.status >= 300 && response.status < 400 && response.status !== 304;
294
+ if (!isRedirect)
295
+ return this.capped(response);
296
+ if (hop >= this.config.max_redirects) {
297
+ throw new EgressDenied(this.config.max_redirects === 0
298
+ ? `upstream returned ${response.status} and egress.max_redirects is 0, so the redirect was refused`
299
+ : `upstream exceeded egress.max_redirects (${this.config.max_redirects})`, "redirect");
300
+ }
301
+ const location = response.headers.get("location");
302
+ if (!location) {
303
+ throw new EgressDenied(`upstream returned ${response.status} without a Location header`, "redirect");
304
+ }
305
+ // Nothing reads the redirect's own body; release the connection.
306
+ await response.body?.cancel().catch(() => undefined);
307
+ let next;
308
+ try {
309
+ next = new URL(location, target);
310
+ }
311
+ catch {
312
+ throw new EgressDenied(`upstream redirected to an unparseable location`, "redirect");
313
+ }
314
+ /*
315
+ * The same two rules the buffered `fetch` below applies, and for the
316
+ * same reasons. Passing the allowlist says a host may be *reached*; it
317
+ * does not say it may be handed the credential that was meant for a
318
+ * different one. This path carries the operator's configured upstream
319
+ * headers and, with pass-through on, the caller's own token.
320
+ */
321
+ if (response.status === 303 ||
322
+ ((response.status === 301 || response.status === 302) && method !== "GET" && method !== "HEAD")) {
323
+ method = "GET";
324
+ body = undefined;
325
+ }
326
+ if (url.origin !== next.origin)
327
+ headers = stripAuthHeaders(headers);
328
+ target = next.toString();
329
+ }
330
+ }
331
+ /**
332
+ * Counts bytes as they arrive and aborts past the cap.
333
+ *
334
+ * An event stream is measured per event rather than over the connection. A
335
+ * long-lived stream has no meaningful total length, so a total cap would end
336
+ * a healthy session at an arbitrary point -- but exempting it outright left
337
+ * no ceiling at all, and an upstream that opens an event and never ends it
338
+ * grows the reader's buffer until the process dies. One event is a payload
339
+ * in the sense the cap was written for, so the same number applies to it.
340
+ */
341
+ capped(response) {
342
+ if (!response.body)
343
+ return response;
344
+ const type = response.headers.get("content-type") ?? "";
345
+ const perEvent = type.includes("text/event-stream");
346
+ const limit = this.config.max_body_bytes;
347
+ let seen = 0;
348
+ /*
349
+ * Enough of the previous chunk to recognise a delimiter split across the
350
+ * boundary. An event ends with a blank line, which is three bytes at its
351
+ * longest (`\r\n\r\n` overlapping by one), so three is the whole of it.
352
+ */
353
+ let carry = new Uint8Array(0);
354
+ const body = response.body.pipeThrough(new TransformStream({
355
+ transform(chunk, controller) {
356
+ if (perEvent) {
357
+ const scan = new Uint8Array(carry.length + chunk.byteLength);
358
+ scan.set(carry, 0);
359
+ scan.set(chunk, carry.length);
360
+ const boundary = lastEventBoundary(scan);
361
+ if (boundary === -1) {
362
+ seen += chunk.byteLength;
363
+ }
364
+ else {
365
+ // Bytes after the last complete event start the next one.
366
+ seen = scan.length - boundary;
367
+ }
368
+ carry = scan.subarray(Math.max(0, scan.length - 3));
369
+ }
370
+ else {
371
+ seen += chunk.byteLength;
372
+ }
373
+ if (seen > limit) {
374
+ controller.error(new EgressDenied(perEvent
375
+ ? `a single event exceeded egress.max_body_bytes (${limit}); the stream was aborted`
376
+ : `response body exceeded egress.max_body_bytes (${limit}); the request was aborted`, "response-too-large"));
377
+ return;
378
+ }
379
+ controller.enqueue(chunk);
380
+ }
381
+ }));
382
+ return new Response(body, {
383
+ status: response.status,
384
+ statusText: response.statusText,
385
+ headers: response.headers
386
+ });
387
+ }
388
+ /**
389
+ * A pinned agent for a stream.
390
+ *
391
+ * Separate from `agentFor` because that one sets `bodyTimeout`, which would
392
+ * tear down an event stream that is merely quiet.
393
+ */
394
+ streamingAgentFor(addresses) {
395
+ const key = addresses.map((a) => a.address).join(",");
396
+ const cached = this.streamingAgentCache.get(key);
397
+ if (cached)
398
+ return cached;
399
+ const agent = new Agent({
400
+ connect: {
401
+ lookup: (_hostname, _options, callback) => {
402
+ callback(null, addresses);
403
+ }
404
+ },
405
+ headersTimeout: this.config.timeout_ms,
406
+ bodyTimeout: 0,
407
+ connectTimeout: this.config.timeout_ms
408
+ });
409
+ this.streamingAgentCache.set(key, agent);
410
+ return agent;
411
+ }
412
+ async fetch(rawUrl, init = {}) {
413
+ let method = (init.method ?? "GET").toUpperCase();
414
+ let target = rawUrl;
415
+ let body = init.body;
416
+ let headers = init.headers;
417
+ if (body !== undefined) {
418
+ const size = Buffer.byteLength(body);
419
+ if (size > this.config.max_request_body_bytes) {
420
+ throw new EgressDenied(`request body of ${size} bytes exceeds egress.max_request_body_bytes (${this.config.max_request_body_bytes})`, "request-too-large");
421
+ }
422
+ }
423
+ for (let hop = 0;; hop++) {
424
+ const response = await this.fetchOnce(target, { method, headers, body, signal: init.signal });
425
+ const isRedirect = response.status >= 300 && response.status < 400 && response.status !== 304;
426
+ if (!isRedirect)
427
+ return response;
428
+ const location = headerValue(response.headers, "location");
429
+ if (hop >= this.config.max_redirects) {
430
+ throw new EgressDenied(this.config.max_redirects === 0
431
+ ? `upstream returned ${response.status} and egress.max_redirects is 0, so the redirect was refused`
432
+ : `upstream exceeded egress.max_redirects (${this.config.max_redirects})`, "redirect");
433
+ }
434
+ if (!location) {
435
+ throw new EgressDenied(`upstream returned ${response.status} without a Location header`, "redirect");
436
+ }
437
+ let next;
438
+ try {
439
+ next = new URL(location, target);
440
+ }
441
+ catch {
442
+ throw new EgressDenied(`upstream redirected to an unparseable location`, "redirect");
443
+ }
444
+ // 303, and 301/302 on a non-GET, become GET without a body, per the
445
+ // usual browser rules. The next hop is then checked from scratch.
446
+ if (response.status === 303 || ((response.status === 301 || response.status === 302) && method !== "GET" && method !== "HEAD")) {
447
+ method = "GET";
448
+ body = undefined;
449
+ }
450
+ if (new URL(target).origin !== next.origin) {
451
+ // Never carry credentials across an origin we did not start with.
452
+ headers = stripAuthHeaders(headers);
453
+ }
454
+ target = next.toString();
455
+ }
456
+ }
457
+ async fetchOnce(rawUrl, init) {
458
+ const method = (init.method ?? "GET").toUpperCase();
459
+ const verdict = this.check(rawUrl, method);
460
+ if (!verdict.ok) {
461
+ throw new EgressDenied(verdict.reason ?? "egress refused", verdict.code ?? "refused");
462
+ }
463
+ const url = new URL(rawUrl);
464
+ const addresses = await this.resolveVerified(url.hostname.replace(/^\[|\]$/g, ""));
465
+ const dispatcher = this.agentFor(addresses);
466
+ const controller = new AbortController();
467
+ const timer = setTimeout(() => controller.abort(new Error("egress timeout")), this.config.timeout_ms);
468
+ if (init.signal) {
469
+ init.signal.addEventListener("abort", () => controller.abort(init.signal.reason), { once: true });
470
+ }
471
+ try {
472
+ const response = await undiciRequest(url, {
473
+ method: method,
474
+ headers: init.headers,
475
+ body: init.body,
476
+ dispatcher,
477
+ signal: controller.signal
478
+ });
479
+ const chunks = [];
480
+ let bytes = 0;
481
+ let overflow = false;
482
+ for await (const chunk of response.body) {
483
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
484
+ bytes += buf.length;
485
+ if (bytes > this.config.max_body_bytes) {
486
+ overflow = true;
487
+ controller.abort(new Error("response body limit exceeded"));
488
+ break;
489
+ }
490
+ chunks.push(buf);
491
+ }
492
+ if (overflow) {
493
+ throw new EgressDenied(`response body exceeded egress.max_body_bytes (${this.config.max_body_bytes}); the request was aborted`, "response-too-large");
494
+ }
495
+ return {
496
+ status: response.statusCode,
497
+ headers: response.headers,
498
+ body: Buffer.concat(chunks),
499
+ bytes,
500
+ url: url.toString(),
501
+ truncated: false
502
+ };
503
+ }
504
+ catch (err) {
505
+ if (err instanceof EgressDenied)
506
+ throw err;
507
+ const message = err.message ?? String(err);
508
+ if (controller.signal.aborted) {
509
+ throw new EgressDenied(`request to ${url.host} aborted: ${message}`, "aborted");
510
+ }
511
+ throw new EgressDenied(`request to ${url.host} failed: ${message}`, "network");
512
+ }
513
+ finally {
514
+ clearTimeout(timer);
515
+ }
516
+ }
517
+ async close() {
518
+ const agents = [...this.agentCache.values(), ...this.streamingAgentCache.values(), ...this.retired];
519
+ await Promise.all(agents.map((a) => a.close().catch(() => undefined)));
520
+ this.agentCache.clear();
521
+ this.streamingAgentCache.clear();
522
+ this.retired.clear();
523
+ }
524
+ }
525
+ function headerValue(headers, name) {
526
+ const wanted = name.toLowerCase();
527
+ for (const [key, value] of Object.entries(headers)) {
528
+ if (key.toLowerCase() !== wanted)
529
+ continue;
530
+ return Array.isArray(value) ? value[0] : value;
531
+ }
532
+ return undefined;
533
+ }
534
+ const AUTH_HEADERS = new Set(["authorization", "cookie", "proxy-authorization", "x-api-key", "api-key"]);
535
+ function stripAuthHeaders(headers) {
536
+ if (!headers)
537
+ return headers;
538
+ const out = {};
539
+ for (const [key, value] of Object.entries(headers)) {
540
+ if (!AUTH_HEADERS.has(key.toLowerCase()))
541
+ out[key] = value;
542
+ }
543
+ return out;
544
+ }