@buildanagent/harness 0.1.0-alpha.30 → 0.1.0-alpha.31

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 (58) hide show
  1. package/README.md +69 -3
  2. package/dist/credentials/addresses.d.ts +9 -0
  3. package/dist/credentials/addresses.js +52 -0
  4. package/dist/credentials/addresses.js.map +1 -1
  5. package/dist/credentials/egress-proxy.js +34 -4
  6. package/dist/credentials/egress-proxy.js.map +1 -1
  7. package/dist/extensions/load.js +5 -2
  8. package/dist/extensions/load.js.map +1 -1
  9. package/dist/extensions/lock.d.ts +16 -2
  10. package/dist/extensions/lock.js +155 -21
  11. package/dist/extensions/lock.js.map +1 -1
  12. package/dist/extensions/mcp-pins-node.d.ts +16 -0
  13. package/dist/extensions/mcp-pins-node.js +18 -0
  14. package/dist/extensions/mcp-pins-node.js.map +1 -0
  15. package/dist/extensions/node.d.ts +4 -2
  16. package/dist/extensions/node.js +4 -2
  17. package/dist/extensions/node.js.map +1 -1
  18. package/dist/harness.d.ts +7 -1
  19. package/dist/harness.js.map +1 -1
  20. package/dist/mcp/connection.d.ts +9 -3
  21. package/dist/mcp/connection.js +192 -25
  22. package/dist/mcp/connection.js.map +1 -1
  23. package/dist/mcp/errors.d.ts +5 -2
  24. package/dist/mcp/errors.js.map +1 -1
  25. package/dist/mcp/guarded-fetch.d.ts +33 -0
  26. package/dist/mcp/guarded-fetch.js +391 -0
  27. package/dist/mcp/guarded-fetch.js.map +1 -0
  28. package/dist/mcp/http-node.d.ts +15 -0
  29. package/dist/mcp/http-node.js +179 -0
  30. package/dist/mcp/http-node.js.map +1 -0
  31. package/dist/mcp/index.d.ts +6 -3
  32. package/dist/mcp/index.js +5 -2
  33. package/dist/mcp/index.js.map +1 -1
  34. package/dist/mcp/manager.d.ts +4 -3
  35. package/dist/mcp/manager.js +432 -47
  36. package/dist/mcp/manager.js.map +1 -1
  37. package/dist/mcp/pins.d.ts +9 -0
  38. package/dist/mcp/pins.js +54 -0
  39. package/dist/mcp/pins.js.map +1 -0
  40. package/dist/mcp/record.js +6 -0
  41. package/dist/mcp/record.js.map +1 -1
  42. package/dist/mcp/remote-config.d.ts +20 -0
  43. package/dist/mcp/remote-config.js +208 -0
  44. package/dist/mcp/remote-config.js.map +1 -0
  45. package/dist/mcp/remote.d.ts +20 -0
  46. package/dist/mcp/remote.js +146 -0
  47. package/dist/mcp/remote.js.map +1 -0
  48. package/dist/mcp/types.d.ts +198 -8
  49. package/dist/mcp/types.js.map +1 -1
  50. package/dist/server/protocol.schema.json +6 -3
  51. package/dist/session/runner.js +39 -6
  52. package/dist/session/runner.js.map +1 -1
  53. package/dist/tools/index.d.ts +1 -1
  54. package/dist/tools/index.js.map +1 -1
  55. package/dist/tools/types.d.ts +16 -0
  56. package/dist/tools/types.js.map +1 -1
  57. package/llms.txt +18 -2
  58. package/package.json +7 -6
@@ -0,0 +1,391 @@
1
+ /**
2
+ * The fetch every request to a remote MCP server goes through, whatever reaches the network under it. It sends to the
3
+ * configured origin only, follows no redirect, refuses a `401` with a clear error, checks the server's session id, caps
4
+ * how many responses are open, and hands the client library a body it bounds: by bytes, by time, and for an event
5
+ * stream by line and by event, with the server's `retry` field removed so the server can't set the reconnect delay.
6
+ */
7
+ import { shortText } from "./content.js";
8
+ // What a server's session id may be: visible ASCII, at most 256 characters. It is a token the server chose, so the
9
+ // harness checks its form and trusts nothing else about it.
10
+ const SESSION_ID = /^[\x21-\x7e]{1,256}$/;
11
+ // An event id the client may send back as `Last-Event-ID`: printable ASCII, at most 256 bytes.
12
+ const MAX_EVENT_ID_BYTES = 256;
13
+ const CR = 0x0d;
14
+ const LF = 0x0a;
15
+ const COLON = 0x3a;
16
+ const SPACE = 0x20;
17
+ const encoder = new TextEncoder();
18
+ const RETRY = encoder.encode("retry");
19
+ const ID = encoder.encode("id");
20
+ const BODILESS = [204, 205];
21
+ const BOM = new Uint8Array([0xef, 0xbb, 0xbf]);
22
+ const NEWLINE = new Uint8Array([LF]);
23
+ /** An error from the guard, with a code the connection maps to a clear message. */
24
+ export class RemoteRefusal extends Error {
25
+ /**
26
+ * `too_large` for a body, an event or a line past its bound; `full` for a stream past `maxStreamBytes` in all;
27
+ * `timeout` for a time bound.
28
+ */
29
+ code;
30
+ constructor(code, message) {
31
+ super(message);
32
+ this.code = code;
33
+ }
34
+ }
35
+ const startsWith = (bytes, prefix) => bytes.length >= prefix.length && prefix.every((byte, index) => bytes[index] === byte);
36
+ /** Whether an event-stream line's field is `name`: the bytes before its first colon, or the whole line. */
37
+ function fieldIs(line, name) {
38
+ return startsWith(line, name) && (line.length === name.length || line[name.length] === COLON);
39
+ }
40
+ /** Whether an `id:` line carries an id the client may send back: printable ASCII and short. */
41
+ function usableId(line) {
42
+ let value = line.subarray(Math.min(line.length, ID.length + 1));
43
+ if (value[0] === SPACE)
44
+ value = value.subarray(1);
45
+ return value.length <= MAX_EVENT_ID_BYTES && value.every((byte) => byte >= SPACE && byte <= 0x7e);
46
+ }
47
+ /** Whether a line passes on: every line but `retry:` and an `id:` the client could not send back. */
48
+ const kept = (line) => !(fieldIs(line, RETRY) || (fieldIs(line, ID) && !usableId(line)));
49
+ function concat(parts) {
50
+ const all = new Uint8Array(parts.reduce((size, part) => size + part.length, 0));
51
+ let at = 0;
52
+ for (const part of parts) {
53
+ all.set(part, at);
54
+ at += part.length;
55
+ }
56
+ return all;
57
+ }
58
+ /** The index of the next CR or LF in `chunk` from `from`, or -1. */
59
+ function nextBreak(chunk, from) {
60
+ for (let index = from; index < chunk.length; index += 1) {
61
+ if (chunk[index] === CR || chunk[index] === LF)
62
+ return index;
63
+ }
64
+ return -1;
65
+ }
66
+ /**
67
+ * Splits an event stream into lines, passes each on with an LF after it unless it is dropped, and fails a line or an
68
+ * event over `max` bytes. A line ends at CR, LF or CRLF, as the event-stream format says; each is passed on as LF, so
69
+ * dropping a line between a CR and an LF can't join them into one line end and hide a blank line. It drops every
70
+ * `retry:` line and every `id:` line whose id the client could not send back, so neither can steer the reconnects.
71
+ */
72
+ class EventFilter {
73
+ #max;
74
+ // The start of a line that has no end yet, in one buffer that grows by doubling, so a line sent a byte at a time
75
+ // costs its bytes and not an array of one-byte pieces.
76
+ #pending = new Uint8Array(0);
77
+ #pendingBytes = 0;
78
+ #eventBytes = 0;
79
+ // A chunk that ended in CR may have its LF at the start of the next one, which is part of the same line end.
80
+ #crEnded = false;
81
+ #started = false;
82
+ #head = new Uint8Array(0);
83
+ constructor(max) {
84
+ this.#max = max;
85
+ }
86
+ /** The bytes to pass on for this chunk, or an error message when a bound is broken. */
87
+ push(input) {
88
+ // An empty chunk changes nothing, so it can't end a CRLF that spans two chunks.
89
+ const chunk = input.length === 0 ? undefined : this.#opening(input);
90
+ if (chunk === undefined || chunk.length === 0)
91
+ return new Uint8Array(0);
92
+ const out = [];
93
+ let start = this.#startOf(chunk);
94
+ for (let index = nextBreak(chunk, start); index !== -1; index = nextBreak(chunk, start)) {
95
+ const crlf = chunk[index] === CR && chunk[index + 1] === LF;
96
+ const end = crlf ? index + 2 : index + 1;
97
+ const failure = this.#line(chunk.subarray(start, index), out);
98
+ if (failure !== undefined)
99
+ return failure;
100
+ if (chunk[index] === CR && end === chunk.length)
101
+ this.#crEnded = true;
102
+ start = end;
103
+ }
104
+ return this.#keepRest(chunk.subarray(start)) ?? concat(out);
105
+ }
106
+ /**
107
+ * The stream's first bytes without a byte order mark, which the format ignores, so the first field reads as it is.
108
+ * A mark can arrive split across chunks, so bytes that could still start one are held until the mark is whole or
109
+ * ruled out; `undefined` while they are held.
110
+ */
111
+ #opening(input) {
112
+ if (this.#started)
113
+ return input;
114
+ const joined = this.#head.length === 0 ? input : concat([this.#head, input]);
115
+ if (joined.length < BOM.length && joined.every((byte, index) => byte === BOM[index])) {
116
+ this.#head = joined.slice();
117
+ return undefined;
118
+ }
119
+ this.#started = true;
120
+ this.#head = new Uint8Array(0);
121
+ return startsWith(joined, BOM) ? joined.subarray(BOM.length) : joined;
122
+ }
123
+ /** Where a chunk's lines start: after the LF of a CRLF the last chunk ended. */
124
+ #startOf(chunk) {
125
+ const start = this.#crEnded && chunk[0] === LF ? 1 : 0;
126
+ this.#crEnded = false;
127
+ return start;
128
+ }
129
+ /** Ends one line: checks its size and its event's, and passes it on with an LF unless it is dropped. */
130
+ #line(piece, out) {
131
+ const line = this.#pendingBytes === 0 ? piece : concat([this.#pending.subarray(0, this.#pendingBytes), piece]);
132
+ this.#pending = new Uint8Array(0);
133
+ this.#pendingBytes = 0;
134
+ // An event holds its lines, so the event's bound is also each line's; `#keepRest()` bounds a line still open.
135
+ this.#eventBytes = line.length === 0 ? 0 : this.#eventBytes + line.length;
136
+ if (this.#eventBytes > this.#max)
137
+ return `an event over ${this.#max} bytes`;
138
+ if (kept(line))
139
+ out.push(concat([line, NEWLINE]));
140
+ return undefined;
141
+ }
142
+ #keepRest(rest) {
143
+ if (rest.length === 0)
144
+ return undefined;
145
+ if (this.#pendingBytes + rest.length > this.#max)
146
+ return `an event-stream line over ${this.#max} bytes`;
147
+ const needed = this.#pendingBytes + rest.length;
148
+ if (needed > this.#pending.length) {
149
+ const grown = new Uint8Array(Math.min(this.#max, Math.max(needed, this.#pending.length * 2, 1024)));
150
+ grown.set(this.#pending.subarray(0, this.#pendingBytes));
151
+ this.#pending = grown;
152
+ }
153
+ this.#pending.set(rest, this.#pendingBytes);
154
+ this.#pendingBytes = needed;
155
+ return undefined;
156
+ }
157
+ }
158
+ const unref = (timer) => {
159
+ timer?.unref?.();
160
+ };
161
+ /** A timer that never holds a Node process open. */
162
+ function later(run, ms) {
163
+ const timer = setTimeout(run, ms);
164
+ unref(timer);
165
+ return timer;
166
+ }
167
+ /** One read, or `idle` when nothing came for `ms`; with no `ms`, the read alone. */
168
+ async function readWithin(reader, ms) {
169
+ if (ms === undefined)
170
+ return reader.read();
171
+ let timer;
172
+ const quiet = new Promise((resolve) => {
173
+ timer = later(() => resolve("idle"), ms);
174
+ });
175
+ try {
176
+ return await Promise.race([reader.read(), quiet]);
177
+ }
178
+ finally {
179
+ clearTimeout(timer);
180
+ }
181
+ }
182
+ /**
183
+ * A body that ends with an error once it passes a bound: `maxMessageBytes` for a JSON body, `maxStreamBytes` in all,
184
+ * no byte for `streamIdleMs`, or open longer than `maxStreamMs`. An event stream is filtered as `EventFilter` says.
185
+ * An `endless` stream, a legacy SSE server's one stream, has only the per-event and per-line bounds. `done` runs once,
186
+ * however the body ends.
187
+ */
188
+ function boundedBody(source, settings, body) {
189
+ const { events, endless, done } = body;
190
+ const reader = source.getReader();
191
+ const filter = events ? new EventFilter(settings.maxMessageBytes) : undefined;
192
+ const cap = endless
193
+ ? Number.POSITIVE_INFINITY
194
+ : events
195
+ ? settings.maxStreamBytes
196
+ : Math.min(settings.maxMessageBytes, settings.maxStreamBytes);
197
+ const code = events ? "full" : "too_large";
198
+ const idleMs = endless ? undefined : settings.streamIdleMs;
199
+ let total = 0;
200
+ let finished = false;
201
+ let lifetime;
202
+ const finish = () => {
203
+ if (finished)
204
+ return;
205
+ finished = true;
206
+ clearTimeout(lifetime);
207
+ done();
208
+ };
209
+ const fail = (controller, error) => {
210
+ reader.cancel().catch(() => { });
211
+ if (finished)
212
+ return;
213
+ controller.error(error);
214
+ finish();
215
+ if (error instanceof RemoteRefusal)
216
+ body.broken(error);
217
+ };
218
+ /** The bytes to pass on for one chunk; it throws when the chunk breaks a bound. */
219
+ const pass = (chunk) => {
220
+ total += chunk.length;
221
+ if (total > cap)
222
+ throw new RemoteRefusal(code, `a response passed ${cap} bytes`);
223
+ const passed = filter === undefined ? chunk : filter.push(chunk);
224
+ if (typeof passed === "string")
225
+ throw new RemoteRefusal("too_large", `the server sent ${passed}`);
226
+ return passed;
227
+ };
228
+ return new ReadableStream({
229
+ start(controller) {
230
+ if (endless)
231
+ return;
232
+ lifetime = later(() => fail(controller, new RemoteRefusal("timeout", `a response stayed open past ${settings.maxStreamMs} ms`)), settings.maxStreamMs);
233
+ },
234
+ async pull(controller) {
235
+ try {
236
+ // A pull that enqueues nothing is not called again, so it reads on until a chunk has bytes to pass.
237
+ let passed;
238
+ while (passed === undefined || passed.length === 0) {
239
+ const read = await readWithin(reader, idleMs);
240
+ if (finished)
241
+ return;
242
+ if (read === "idle")
243
+ throw new RemoteRefusal("timeout", `a response sent nothing for ${settings.streamIdleMs} ms`);
244
+ if (read.done) {
245
+ controller.close();
246
+ finish();
247
+ return;
248
+ }
249
+ passed = pass(read.value);
250
+ }
251
+ controller.enqueue(passed);
252
+ }
253
+ catch (error) {
254
+ fail(controller, error);
255
+ }
256
+ },
257
+ cancel(reason) {
258
+ finish();
259
+ return reader.cancel(reason).catch(() => { });
260
+ },
261
+ });
262
+ }
263
+ const isEventStream = (response) => (response.headers.get("content-type") ?? "").split(";")[0]?.trim().toLowerCase() === "text/event-stream";
264
+ /** Cancels a body nobody will read, so its connection closes. */
265
+ const discard = (response) => {
266
+ response.body?.cancel().catch(() => { });
267
+ };
268
+ /** The kind of stream a request opens. */
269
+ function kindOf(method, body, endless) {
270
+ if (method === "GET")
271
+ return endless ? "events" : "get";
272
+ if (typeof body !== "string")
273
+ return "request";
274
+ try {
275
+ return JSON.parse(body).method === "subscriptions/listen" ? "listen" : "request";
276
+ }
277
+ catch {
278
+ return "request";
279
+ }
280
+ }
281
+ /** Refuses a request the client must not send: one that leaves the origin, a `GET` the hooks refuse, one too many. */
282
+ function refusalOf(url, method, settings, hooks, open) {
283
+ // The client may only speak to the configured origin: an `endpoint` event or a redirect can't send it elsewhere.
284
+ if (url.origin !== settings.url.origin || url.username !== "" || url.password !== "") {
285
+ return new RemoteRefusal("refused", "a request left the server's origin, so it was not sent");
286
+ }
287
+ if (method === "GET" && hooks.onGet?.() === false) {
288
+ return new RemoteRefusal("refused", "the server's event stream may not be opened again");
289
+ }
290
+ if (open >= settings.maxStreams) {
291
+ return new RemoteRefusal("refused", `${settings.maxStreams} responses are already open on this connection`);
292
+ }
293
+ return undefined;
294
+ }
295
+ /** The request's headers with the configured ones set over them. */
296
+ function headersOf(init, settings) {
297
+ const headers = new Headers(init.headers);
298
+ for (const [name, value] of Object.entries(settings.headers))
299
+ headers.set(name, value);
300
+ return headers;
301
+ }
302
+ /** Calls `base` with the headers timeout: the response must begin within `headersTimeoutMs`. */
303
+ async function within(base, url, init, settings) {
304
+ const timer = new AbortController();
305
+ const waited = later(() => timer.abort(new RemoteRefusal("timeout", `no response began within ${settings.headersTimeoutMs} ms`)), settings.headersTimeoutMs);
306
+ const signal = init.signal == null ? timer.signal : AbortSignal.any([init.signal, timer.signal]);
307
+ try {
308
+ return await base(url, { ...init, signal, redirect: "manual" });
309
+ }
310
+ catch (error) {
311
+ throw timer.signal.aborted ? timer.signal.reason : error;
312
+ }
313
+ finally {
314
+ clearTimeout(waited);
315
+ }
316
+ }
317
+ /** `base` wrapped in the checks this module describes. */
318
+ export function guardedFetch(base, settings, hooks) {
319
+ let open = 0;
320
+ return async (input, init = {}) => {
321
+ const url = new URL(typeof input === "string" ? input : input.href);
322
+ const method = (init.method ?? "GET").toUpperCase();
323
+ const refusal = refusalOf(url, method, settings, hooks, open);
324
+ if (refusal !== undefined)
325
+ throw refusal;
326
+ open += 1;
327
+ let counted = true;
328
+ const release = () => {
329
+ if (counted)
330
+ open -= 1;
331
+ counted = false;
332
+ };
333
+ let response;
334
+ try {
335
+ response = await within(base, url, { ...init, method, headers: headersOf(init, settings) }, settings);
336
+ }
337
+ catch (error) {
338
+ release();
339
+ throw error;
340
+ }
341
+ try {
342
+ return checked(response, settings, hooks, { release, kind: kindOf(method, init.body, hooks.endless === true) });
343
+ }
344
+ catch (error) {
345
+ release();
346
+ discard(response);
347
+ throw error;
348
+ }
349
+ };
350
+ }
351
+ /** Throws for a response the client must not read: a redirect, a 401 or a session id of the wrong form. */
352
+ function refuseResponse(response) {
353
+ const status = response.status;
354
+ // No MCP request is conditional, so a 304 answers nothing the client asked; it is refused for what it is.
355
+ if (status === 304)
356
+ throw new RemoteRefusal("refused", "the server answered 304 Not Modified to a request that asked for no cache");
357
+ if ((status >= 300 && status < 400) || response.type === "opaqueredirect") {
358
+ throw new RemoteRefusal("redirect", `the server answered with a redirect (HTTP ${status}), which is not followed`);
359
+ }
360
+ if (status === 401) {
361
+ throw new RemoteRefusal("unauthorized", "the server asked for authorization (HTTP 401); this harness runs no authorization flow, so give the credential in the transport's headers");
362
+ }
363
+ const session = response.headers.get("mcp-session-id");
364
+ if (session !== null && !SESSION_ID.test(session)) {
365
+ throw new RemoteRefusal("refused", "the server sent a session id that is not 1 to 256 visible ASCII characters");
366
+ }
367
+ }
368
+ function checked(response, settings, hooks, stream) {
369
+ const { release } = stream;
370
+ refuseResponse(response);
371
+ const { status, statusText, headers } = response;
372
+ if (response.body === null || BODILESS.includes(status)) {
373
+ discard(response);
374
+ release();
375
+ return new Response(null, { status, statusText, headers });
376
+ }
377
+ if (status >= 400)
378
+ hooks.log(`the server answered HTTP ${status} ${shortText(statusText, 64)}`);
379
+ const { kind } = stream;
380
+ const reopens = kind === "get" || kind === "listen";
381
+ const body = boundedBody(response.body, settings, {
382
+ events: isEventStream(response),
383
+ // Only an event stream is the one channel of a legacy SSE server; any other body on that GET, such as an error
384
+ // page, is bounded like any answer.
385
+ endless: kind === "events" && isEventStream(response),
386
+ done: release,
387
+ broken: (error) => hooks.onBroken?.(error, error.code === "too_large" || !reopens, kind),
388
+ });
389
+ return new Response(body, { status, statusText, headers });
390
+ }
391
+ //# sourceMappingURL=guarded-fetch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guarded-fetch.js","sourceRoot":"","sources":["../../src/mcp/guarded-fetch.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAMzC,mHAAmH;AACnH,4DAA4D;AAC5D,MAAM,UAAU,GAAG,sBAAsB,CAAC;AAC1C,+FAA+F;AAC/F,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,EAAE,GAAG,IAAI,CAAC;AAChB,MAAM,EAAE,GAAG,IAAI,CAAC;A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CAAC;KACzF,CAAC,CAAC;IACH,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["/**\n * The fetch every request to a remote MCP server goes through, whatever reaches the network under it. It sends to the\n * configured origin only, follows no redirect, refuses a `401` with a clear error, checks the server's session id, caps\n * how many responses are open, and hands the client library a body it bounds: by bytes, by time, and for an event\n * stream by line and by event, with the server's `retry` field removed so the server can't set the reconnect delay.\n */\nimport { shortText } from \"./content.js\";\nimport type { RemoteSettings } from \"./remote-config.js\";\n\n/** A fetch, as the client library calls it. */\nexport type FetchLike = (input: string | URL, init?: RequestInit) => Promise<Response>;\n\n// What a server's session id may be: visible ASCII, at most 256 characters. It is a token the server chose, so the\n// harness checks its form and trusts nothing else about it.\nconst SESSION_ID = /^[\\x21-\\x7e]{1,256}$/;\n// An event id the client may send back as `Last-Event-ID`: printable ASCII, at most 256 bytes.\nconst MAX_EVENT_ID_BYTES = 256;\nconst CR = 0x0d;\nconst LF = 0x0a;\nconst COLON = 0x3a;\nconst SPACE = 0x20;\nconst encoder = new TextEncoder();\nconst RETRY = encoder.encode(\"retry\");\nconst ID = encoder.encode(\"id\");\nconst BODILESS = [204, 205];\nconst BOM = new Uint8Array([0xef, 0xbb, 0xbf]);\nconst NEWLINE = new Uint8Array([LF]);\n\n/** An error from the guard, with a code the connection maps to a clear message. */\nexport class RemoteRefusal extends Error {\n /**\n * `too_large` for a body, an event or a line past its bound; `full` for a stream past `maxStreamBytes` in all;\n * `timeout` for a time bound.\n */\n readonly code: \"unauthorized\" | \"redirect\" | \"refused\" | \"too_large\" | \"full\" | \"timeout\";\n constructor(code: RemoteRefusal[\"code\"], message: string) {\n super(message);\n this.code = code;\n }\n}\n\nconst startsWith = (bytes: Uint8Array, prefix: Uint8Array): boolean =>\n bytes.length >= prefix.length && prefix.every((byte, index) => bytes[index] === byte);\n\n/** Whether an event-stream line's field is `name`: the bytes before its first colon, or the whole line. */\nfunction fieldIs(line: Uint8Array, name: Uint8Array): boolean {\n return startsWith(line, name) && (line.length === name.length || line[name.length] === COLON);\n}\n\n/** Whether an `id:` line carries an id the client may send back: printable ASCII and short. */\nfunction usableId(line: Uint8Array): boolean {\n let value = line.subarray(Math.min(line.length, ID.length + 1));\n if (value[0] === SPACE) value = value.subarray(1);\n return value.length <= MAX_EVENT_ID_BYTES && value.every((byte) => byte >= SPACE && byte <= 0x7e);\n}\n\n/** Whether a line passes on: every line but `retry:` and an `id:` the client could not send back. */\nconst kept = (line: Uint8Array): boolean => !(fieldIs(line, RETRY) || (fieldIs(line, ID) && !usableId(line)));\n\nfunction concat(parts: readonly Uint8Array[]): Uint8Array {\n const all = new Uint8Array(parts.reduce((size, part) => size + part.length, 0));\n let at = 0;\n for (const part of parts) {\n all.set(part, at);\n at += part.length;\n }\n return all;\n}\n\n/** The index of the next CR or LF in `chunk` from `from`, or -1. */\nfunction nextBreak(chunk: Uint8Array, from: number): number {\n for (let index = from; index < chunk.length; index += 1) {\n if (chunk[index] === CR || chunk[index] === LF) return index;\n }\n return -1;\n}\n\n/**\n * Splits an event stream into lines, passes each on with an LF after it unless it is dropped, and fails a line or an\n * event over `max` bytes. A line ends at CR, LF or CRLF, as the event-stream format says; each is passed on as LF, so\n * dropping a line between a CR and an LF can't join them into one line end and hide a blank line. It drops every\n * `retry:` line and every `id:` line whose id the client could not send back, so neither can steer the reconnects.\n */\nclass EventFilter {\n readonly #max: number;\n // The start of a line that has no end yet, in one buffer that grows by doubling, so a line sent a byte at a time\n // costs its bytes and not an array of one-byte pieces.\n #pending = new Uint8Array(0);\n #pendingBytes = 0;\n #eventBytes = 0;\n // A chunk that ended in CR may have its LF at the start of the next one, which is part of the same line end.\n #crEnded = false;\n #started = false;\n #head = new Uint8Array(0);\n\n constructor(max: number) {\n this.#max = max;\n }\n\n /** The bytes to pass on for this chunk, or an error message when a bound is broken. */\n push(input: Uint8Array): Uint8Array | string {\n // An empty chunk changes nothing, so it can't end a CRLF that spans two chunks.\n const chunk = input.length === 0 ? undefined : this.#opening(input);\n if (chunk === undefined || chunk.length === 0) return new Uint8Array(0);\n const out: Uint8Array[] = [];\n let start = this.#startOf(chunk);\n for (let index = nextBreak(chunk, start); index !== -1; index = nextBreak(chunk, start)) {\n const crlf = chunk[index] === CR && chunk[index + 1] === LF;\n const end = crlf ? index + 2 : index + 1;\n const failure = this.#line(chunk.subarray(start, index), out);\n if (failure !== undefined) return failure;\n if (chunk[index] === CR && end === chunk.length) this.#crEnded = true;\n start = end;\n }\n return this.#keepRest(chunk.subarray(start)) ?? concat(out);\n }\n\n /**\n * The stream's first bytes without a byte order mark, which the format ignores, so the first field reads as it is.\n * A mark can arrive split across chunks, so bytes that could still start one are held until the mark is whole or\n * ruled out; `undefined` while they are held.\n */\n #opening(input: Uint8Array): Uint8Array | undefined {\n if (this.#started) return input;\n const joined = this.#head.length === 0 ? input : concat([this.#head, input]);\n if (joined.length < BOM.length && joined.every((byte, index) => byte === BOM[index])) {\n this.#head = joined.slice();\n return undefined;\n }\n this.#started = true;\n this.#head = new Uint8Array(0);\n return startsWith(joined, BOM) ? joined.subarray(BOM.length) : joined;\n }\n\n /** Where a chunk's lines start: after the LF of a CRLF the last chunk ended. */\n #startOf(chunk: Uint8Array): number {\n const start = this.#crEnded && chunk[0] === LF ? 1 : 0;\n this.#crEnded = false;\n return start;\n }\n\n /** Ends one line: checks its size and its event's, and passes it on with an LF unless it is dropped. */\n #line(piece: Uint8Array, out: Uint8Array[]): string | undefined {\n const line = this.#pendingBytes === 0 ? piece : concat([this.#pending.subarray(0, this.#pendingBytes), piece]);\n this.#pending = new Uint8Array(0);\n this.#pendingBytes = 0;\n // An event holds its lines, so the event's bound is also each line's; `#keepRest()` bounds a line still open.\n this.#eventBytes = line.length === 0 ? 0 : this.#eventBytes + line.length;\n if (this.#eventBytes > this.#max) return `an event over ${this.#max} bytes`;\n if (kept(line)) out.push(concat([line, NEWLINE]));\n return undefined;\n }\n\n #keepRest(rest: Uint8Array): string | undefined {\n if (rest.length === 0) return undefined;\n if (this.#pendingBytes + rest.length > this.#max) return `an event-stream line over ${this.#max} bytes`;\n const needed = this.#pendingBytes + rest.length;\n if (needed > this.#pending.length) {\n const grown = new Uint8Array(Math.min(this.#max, Math.max(needed, this.#pending.length * 2, 1024)));\n grown.set(this.#pending.subarray(0, this.#pendingBytes));\n this.#pending = grown;\n }\n this.#pending.set(rest, this.#pendingBytes);\n this.#pendingBytes = needed;\n return undefined;\n }\n}\n\nconst unref = (timer: unknown): void => {\n (timer as { unref?: () => void } | undefined)?.unref?.();\n};\n\n/** A timer that never holds a Node process open. */\nfunction later(run: () => void, ms: number): ReturnType<typeof setTimeout> {\n const timer = setTimeout(run, ms);\n unref(timer);\n return timer;\n}\n\n/** One read, or `idle` when nothing came for `ms`; with no `ms`, the read alone. */\nasync function readWithin(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n ms: number | undefined,\n): Promise<Awaited<ReturnType<ReadableStreamDefaultReader<Uint8Array>[\"read\"]>> | \"idle\"> {\n if (ms === undefined) return reader.read();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const quiet = new Promise<\"idle\">((resolve) => {\n timer = later(() => resolve(\"idle\"), ms);\n });\n try {\n return await Promise.race([reader.read(), quiet]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * A body that ends with an error once it passes a bound: `maxMessageBytes` for a JSON body, `maxStreamBytes` in all,\n * no byte for `streamIdleMs`, or open longer than `maxStreamMs`. An event stream is filtered as `EventFilter` says.\n * An `endless` stream, a legacy SSE server's one stream, has only the per-event and per-line bounds. `done` runs once,\n * however the body ends.\n */\nfunction boundedBody(\n source: ReadableStream<Uint8Array>,\n settings: RemoteSettings,\n body: {\n readonly events: boolean;\n readonly endless: boolean;\n readonly done: () => void;\n readonly broken: (error: RemoteRefusal) => void;\n },\n): ReadableStream<Uint8Array> {\n const { events, endless, done } = body;\n const reader = source.getReader();\n const filter = events ? new EventFilter(settings.maxMessageBytes) : undefined;\n const cap = endless\n ? Number.POSITIVE_INFINITY\n : events\n ? settings.maxStreamBytes\n : Math.min(settings.maxMessageBytes, settings.maxStreamBytes);\n const code = events ? \"full\" : \"too_large\";\n const idleMs = endless ? undefined : settings.streamIdleMs;\n let total = 0;\n let finished = false;\n let lifetime: ReturnType<typeof setTimeout> | undefined;\n const finish = () => {\n if (finished) return;\n finished = true;\n clearTimeout(lifetime);\n done();\n };\n const fail = (controller: ReadableStreamDefaultController<Uint8Array>, error: unknown) => {\n reader.cancel().catch(() => {});\n if (finished) return;\n controller.error(error);\n finish();\n if (error instanceof RemoteRefusal) body.broken(error);\n };\n /** The bytes to pass on for one chunk; it throws when the chunk breaks a bound. */\n const pass = (chunk: Uint8Array): Uint8Array => {\n total += chunk.length;\n if (total > cap) throw new RemoteRefusal(code, `a response passed ${cap} bytes`);\n const passed = filter === undefined ? chunk : filter.push(chunk);\n if (typeof passed === \"string\") throw new RemoteRefusal(\"too_large\", `the server sent ${passed}`);\n return passed;\n };\n return new ReadableStream<Uint8Array>({\n start(controller) {\n if (endless) return;\n lifetime = later(\n () => fail(controller, new RemoteRefusal(\"timeout\", `a response stayed open past ${settings.maxStreamMs} ms`)),\n settings.maxStreamMs,\n );\n },\n async pull(controller) {\n try {\n // A pull that enqueues nothing is not called again, so it reads on until a chunk has bytes to pass.\n let passed: Uint8Array | undefined;\n while (passed === undefined || passed.length === 0) {\n const read = await readWithin(reader, idleMs);\n if (finished) return;\n if (read === \"idle\")\n throw new RemoteRefusal(\"timeout\", `a response sent nothing for ${settings.streamIdleMs} ms`);\n if (read.done) {\n controller.close();\n finish();\n return;\n }\n passed = pass(read.value);\n }\n controller.enqueue(passed);\n } catch (error) {\n fail(controller, error);\n }\n },\n cancel(reason) {\n finish();\n return reader.cancel(reason).catch(() => {});\n },\n });\n}\n\nconst isEventStream = (response: Response): boolean =>\n (response.headers.get(\"content-type\") ?? \"\").split(\";\")[0]?.trim().toLowerCase() === \"text/event-stream\";\n\n/** Cancels a body nobody will read, so its connection closes. */\nconst discard = (response: Response): void => {\n response.body?.cancel().catch(() => {});\n};\n\n/**\n * What a response is for: `request` answers one request; `get` is a streamable HTTP server's `GET` stream and\n * `listen` a `subscriptions/listen` stream, both meant to stay open and both opened again when they end; `events` is\n * a legacy SSE server's one stream, which nothing can open again.\n */\nexport type StreamKind = \"request\" | \"get\" | \"listen\" | \"events\";\n\n/**\n * The checks a remote server's fetch adds. `onGet` decides whether a `GET` may go out; false refuses it. `endless`\n * marks a `GET` as a legacy SSE server's one stream, which has no time or total-byte bound. `onBroken` hears of a body\n * cut for a bound: `fatal` for an event, a line or a body past its size, or any bound on the answer to one request,\n * since the server is then broken or hostile. A time or total-byte cut of a `get` or `listen` stream is planned, not\n * fatal: the stream ends and is opened again.\n */\nexport interface GuardHooks {\n readonly onGet?: () => boolean;\n readonly endless?: boolean;\n readonly onBroken?: (error: RemoteRefusal, fatal: boolean, kind: StreamKind) => void;\n readonly log: (line: string) => void;\n}\n\n/** The kind of stream a request opens. */\nfunction kindOf(method: string, body: RequestInit[\"body\"], endless: boolean): StreamKind {\n if (method === \"GET\") return endless ? \"events\" : \"get\";\n if (typeof body !== \"string\") return \"request\";\n try {\n return (JSON.parse(body) as { method?: unknown }).method === \"subscriptions/listen\" ? \"listen\" : \"request\";\n } catch {\n return \"request\";\n }\n}\n\n/** Refuses a request the client must not send: one that leaves the origin, a `GET` the hooks refuse, one too many. */\nfunction refusalOf(\n url: URL,\n method: string,\n settings: RemoteSettings,\n hooks: GuardHooks,\n open: number,\n): RemoteRefusal | undefined {\n // The client may only speak to the configured origin: an `endpoint` event or a redirect can't send it elsewhere.\n if (url.origin !== settings.url.origin || url.username !== \"\" || url.password !== \"\") {\n return new RemoteRefusal(\"refused\", \"a request left the server's origin, so it was not sent\");\n }\n if (method === \"GET\" && hooks.onGet?.() === false) {\n return new RemoteRefusal(\"refused\", \"the server's event stream may not be opened again\");\n }\n if (open >= settings.maxStreams) {\n return new RemoteRefusal(\"refused\", `${settings.maxStreams} responses are already open on this connection`);\n }\n return undefined;\n}\n\n/** The request's headers with the configured ones set over them. */\nfunction headersOf(init: RequestInit, settings: RemoteSettings): Headers {\n const headers = new Headers(init.headers);\n for (const [name, value] of Object.entries(settings.headers)) headers.set(name, value);\n return headers;\n}\n\n/** Calls `base` with the headers timeout: the response must begin within `headersTimeoutMs`. */\nasync function within(base: FetchLike, url: URL, init: RequestInit, settings: RemoteSettings): Promise<Response> {\n const timer = new AbortController();\n const waited = later(\n () => timer.abort(new RemoteRefusal(\"timeout\", `no response began within ${settings.headersTimeoutMs} ms`)),\n settings.headersTimeoutMs,\n );\n const signal = init.signal == null ? timer.signal : AbortSignal.any([init.signal, timer.signal]);\n try {\n return await base(url, { ...init, signal, redirect: \"manual\" });\n } catch (error) {\n throw timer.signal.aborted ? timer.signal.reason : error;\n } finally {\n clearTimeout(waited);\n }\n}\n\n/** `base` wrapped in the checks this module describes. */\nexport function guardedFetch(base: FetchLike, settings: RemoteSettings, hooks: GuardHooks): FetchLike {\n let open = 0;\n return async (input, init = {}) => {\n const url = new URL(typeof input === \"string\" ? input : input.href);\n const method = (init.method ?? \"GET\").toUpperCase();\n const refusal = refusalOf(url, method, settings, hooks, open);\n if (refusal !== undefined) throw refusal;\n open += 1;\n let counted = true;\n const release = () => {\n if (counted) open -= 1;\n counted = false;\n };\n let response: Response;\n try {\n response = await within(base, url, { ...init, method, headers: headersOf(init, settings) }, settings);\n } catch (error) {\n release();\n throw error;\n }\n try {\n return checked(response, settings, hooks, { release, kind: kindOf(method, init.body, hooks.endless === true) });\n } catch (error) {\n release();\n discard(response);\n throw error;\n }\n };\n}\n\n/** Throws for a response the client must not read: a redirect, a 401 or a session id of the wrong form. */\nfunction refuseResponse(response: Response): void {\n const status = response.status;\n // No MCP request is conditional, so a 304 answers nothing the client asked; it is refused for what it is.\n if (status === 304)\n throw new RemoteRefusal(\"refused\", \"the server answered 304 Not Modified to a request that asked for no cache\");\n if ((status >= 300 && status < 400) || response.type === \"opaqueredirect\") {\n throw new RemoteRefusal(\"redirect\", `the server answered with a redirect (HTTP ${status}), which is not followed`);\n }\n if (status === 401) {\n throw new RemoteRefusal(\n \"unauthorized\",\n \"the server asked for authorization (HTTP 401); this harness runs no authorization flow, so give the credential in the transport's headers\",\n );\n }\n const session = response.headers.get(\"mcp-session-id\");\n if (session !== null && !SESSION_ID.test(session)) {\n throw new RemoteRefusal(\"refused\", \"the server sent a session id that is not 1 to 256 visible ASCII characters\");\n }\n}\n\nfunction checked(\n response: Response,\n settings: RemoteSettings,\n hooks: GuardHooks,\n stream: { readonly release: () => void; readonly kind: StreamKind },\n): Response {\n const { release } = stream;\n refuseResponse(response);\n const { status, statusText, headers } = response;\n if (response.body === null || BODILESS.includes(status)) {\n discard(response);\n release();\n return new Response(null, { status, statusText, headers });\n }\n if (status >= 400) hooks.log(`the server answered HTTP ${status} ${shortText(statusText, 64)}`);\n const { kind } = stream;\n const reopens = kind === \"get\" || kind === \"listen\";\n const body = boundedBody(response.body, settings, {\n events: isEventStream(response),\n // Only an event stream is the one channel of a legacy SSE server; any other body on that GET, such as an error\n // page, is bounded like any answer.\n endless: kind === \"events\" && isEventStream(response),\n done: release,\n broken: (error) => hooks.onBroken?.(error, error.code === \"too_large\" || !reopens, kind),\n });\n return new Response(body, { status, statusText, headers });\n}\n"]}
@@ -0,0 +1,15 @@
1
+ import type { FetchLike } from "./guarded-fetch.js";
2
+ import type { RemoteSettings } from "./remote-config.js";
3
+ /**
4
+ * Whether this is Node, whose `node:https` takes the custom `lookup` the pinned connection needs. Cloudflare's workerd
5
+ * also has `process.getBuiltinModule()` and `node:https` under `nodejs_compat`, but refuses a `lookup` option, so it
6
+ * is told apart by its user agent and gets the platform's `fetch` instead.
7
+ */
8
+ export declare function hasNodeNetwork(): boolean;
9
+ type Resolve = (host: string) => Promise<readonly string[]>;
10
+ /** The pinned fetch, for one server's settings. */
11
+ export declare function nodeFetch(settings: RemoteSettings, options: {
12
+ readonly resolve?: Resolve | undefined;
13
+ readonly ca?: string | readonly string[] | undefined;
14
+ }): FetchLike;
15
+ export {};
@@ -0,0 +1,179 @@
1
+ /**
2
+ * The network under a remote server's fetch on Node, when no egress proxy is configured. Each request resolves the
3
+ * server's name once, checks every address it gets against the server's address policy, connects to the first, and
4
+ * checks the address the socket reached once more, so a name whose answer changes between two lookups can't steer a
5
+ * request to the host's own network. It verifies certificates, asks for no compression, follows no redirect and keeps
6
+ * no connection alive between requests. It loads Node's modules by `process.getBuiltinModule()` when a request is made,
7
+ * so the `mcp` entry still loads on a runtime without them.
8
+ */
9
+ import { isAddressLiteral } from "../credentials/addresses.js";
10
+ import { RemoteRefusal } from "./guarded-fetch.js";
11
+ const bare = (host) => (host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host);
12
+ const familyOf = (address) => (address.includes(":") ? 6 : 4);
13
+ /**
14
+ * Whether this is Node, whose `node:https` takes the custom `lookup` the pinned connection needs. Cloudflare's workerd
15
+ * also has `process.getBuiltinModule()` and `node:https` under `nodejs_compat`, but refuses a `lookup` option, so it
16
+ * is told apart by its user agent and gets the platform's `fetch` instead.
17
+ */
18
+ export function hasNodeNetwork() {
19
+ if (typeof process === "undefined" || typeof process.getBuiltinModule !== "function")
20
+ return false;
21
+ const agent = globalThis.navigator?.userAgent;
22
+ return agent !== "Cloudflare-Workers" && typeof process.versions?.node === "string";
23
+ }
24
+ /** The body a request sends: the client library sends JSON text, or nothing. */
25
+ async function bodyOf(init) {
26
+ if (init.body === undefined || init.body === null)
27
+ return undefined;
28
+ return new Uint8Array(await new Response(init.body).arrayBuffer());
29
+ }
30
+ /** A Web `Response` for a Node response. A body nobody can read is drained, so the socket closes. */
31
+ function toResponse(reply) {
32
+ const stream = process.getBuiltinModule("node:stream");
33
+ const headers = new Headers();
34
+ for (const [name, value] of Object.entries(reply.headers)) {
35
+ if (value === undefined)
36
+ continue;
37
+ for (const one of Array.isArray(value) ? value : [value])
38
+ headers.append(name, one);
39
+ }
40
+ const status = reply.statusCode ?? 0;
41
+ // Node parses any three-digit status, and `Response` throws outside 200 to 599, so such an answer is refused here.
42
+ if (status < 200 || status > 599) {
43
+ reply.destroy();
44
+ throw new RemoteRefusal("refused", `the server answered with status ${status}, which HTTP does not define`);
45
+ }
46
+ if ([204, 205, 304].includes(status)) {
47
+ reply.resume();
48
+ return new Response(null, { status, headers });
49
+ }
50
+ return new Response(stream.Readable.toWeb(reply), {
51
+ status,
52
+ statusText: reply.statusMessage ?? "",
53
+ headers,
54
+ });
55
+ }
56
+ /** The system resolver: every address of a name, in the order the system gives them. */
57
+ const systemResolve = async (host) => (await process.getBuiltinModule("node:dns").promises.lookup(host, { all: true, verbatim: true })).map((found) => found.address);
58
+ /**
59
+ * A `lookup` for `node:https`: it resolves the name once, refuses it when any address is one the server may not reach,
60
+ * and hands back the first address alone, so the socket connects to that checked address and no other.
61
+ */
62
+ function checkedLookup(settings, resolve) {
63
+ return (hostname, lookupOptions, callback) => {
64
+ resolve(hostname).then((addresses) => {
65
+ if (addresses.length === 0 || addresses.some((address) => !settings.allows(address))) {
66
+ callback(new RemoteRefusal("refused", "the server's name resolves to an address it may not reach"));
67
+ return;
68
+ }
69
+ const first = addresses[0];
70
+ if (lookupOptions.all === true)
71
+ callback(null, [{ address: first, family: familyOf(first) }]);
72
+ else
73
+ callback(null, first, familyOf(first));
74
+ }, (error) => callback(error instanceof Error ? error : new Error(String(error))));
75
+ };
76
+ }
77
+ /** The request's headers for Node: no compression, a length for the body, and the URL's own `Host`. */
78
+ function nodeHeaders(init, url, body) {
79
+ const headers = {};
80
+ new Headers(init.headers).forEach((value, name) => {
81
+ headers[name] = value;
82
+ });
83
+ headers["accept-encoding"] = "identity";
84
+ if (body !== undefined)
85
+ headers["content-length"] = String(body.length);
86
+ headers.host = url.host;
87
+ return headers;
88
+ }
89
+ /**
90
+ * Checks the address the socket reached once it has connected: the lookup's answer is what it connected to, and this
91
+ * proves it for a literal address and for any path around the lookup.
92
+ */
93
+ function checkReached(request, settings, secure) {
94
+ request.once("socket", (socket) => {
95
+ socket.once(secure ? "secureConnect" : "connect", () => {
96
+ const reached = socket.remoteAddress;
97
+ if (reached === undefined || !settings.allows(reached)) {
98
+ request.destroy(new RemoteRefusal("refused", "the connection reached an address the server may not use"));
99
+ }
100
+ });
101
+ });
102
+ }
103
+ /** Settles with the response, refusing a compressed one, which the request did not ask for. */
104
+ function settle(request, signal) {
105
+ return new Promise((resolve, reject) => {
106
+ const abort = () => request.destroy(signal?.reason instanceof Error ? signal.reason : new Error("aborted"));
107
+ signal?.addEventListener("abort", abort, { once: true });
108
+ request.once("close", () => signal?.removeEventListener("abort", abort));
109
+ request.once("response", (reply) => {
110
+ const encoding = String(reply.headers["content-encoding"] ?? "identity")
111
+ .trim()
112
+ .toLowerCase();
113
+ if (encoding !== "identity" && encoding !== "") {
114
+ reply.destroy();
115
+ reject(new RemoteRefusal("refused", "the server compressed its answer, which the harness did not ask for"));
116
+ return;
117
+ }
118
+ // A throw here would escape the event handler and end the process, so every failure becomes a rejection.
119
+ try {
120
+ resolve(toResponse(reply));
121
+ }
122
+ catch (error) {
123
+ reply.destroy();
124
+ reject(error);
125
+ }
126
+ });
127
+ request.once("error", (error) => reject(signal?.aborted ? signal.reason : error));
128
+ });
129
+ }
130
+ /** The pinned fetch, for one server's settings. */
131
+ export function nodeFetch(settings, options) {
132
+ const lookup = checkedLookup(settings, options.resolve ?? systemResolve);
133
+ return async (input, init = {}) => {
134
+ const url = new URL(typeof input === "string" ? input : input.href);
135
+ const host = bare(url.hostname);
136
+ const literal = isAddressLiteral(host);
137
+ // A literal address is checked as it is, since Node looks nothing up for it; a name is looked up once, in `lookup`.
138
+ if (literal && !settings.allows(host))
139
+ throw new RemoteRefusal("refused", "the server's address is one it may not reach");
140
+ const secure = url.protocol === "https:";
141
+ const body = await bodyOf(init);
142
+ const signal = init.signal ?? undefined;
143
+ signal?.throwIfAborted();
144
+ const request = process
145
+ .getBuiltinModule(secure ? "node:https" : "node:http")
146
+ .request(requestOptions(url, init, body, literal ? undefined : lookup, options.ca));
147
+ checkReached(request, settings, secure);
148
+ const response = settle(request, signal);
149
+ request.end(body);
150
+ return response;
151
+ };
152
+ }
153
+ /** The options of one Node request: no shared agent, the checked lookup for a name, and TLS settings for `https:`. */
154
+ function requestOptions(url, init, body, lookup, ca) {
155
+ const host = bare(url.hostname);
156
+ const secure = url.protocol === "https:";
157
+ const port = url.port !== "" ? Number(url.port) : secure ? 443 : 80;
158
+ return {
159
+ protocol: url.protocol,
160
+ hostname: host,
161
+ port,
162
+ method: init.method ?? "GET",
163
+ path: `${url.pathname}${url.search}`,
164
+ headers: nodeHeaders(init, url, body),
165
+ agent: false,
166
+ ...(lookup === undefined ? {} : { lookup: lookup }),
167
+ ...(secure ? tlsOptions(lookup === undefined ? undefined : host, ca) : {}),
168
+ };
169
+ }
170
+ /** Certificates are always verified, against the system's authorities or the server's own `ca`, over TLS 1.2 or later. */
171
+ function tlsOptions(servername, ca) {
172
+ return {
173
+ ...(servername === undefined ? {} : { servername }),
174
+ rejectUnauthorized: true,
175
+ minVersion: "TLSv1.2",
176
+ ...(ca === undefined ? {} : { ca: ca }),
177
+ };
178
+ }
179
+ //# sourceMappingURL=http-node.js.map