@240xu/dsh-websearch 2.8.8 → 2.9.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.
package/lib/rrf.js CHANGED
@@ -24,24 +24,29 @@ function itemKey(item) {
24
24
  * Fuse ranked lists of search sources with Reciprocal Rank Fusion.
25
25
  *
26
26
  * @param {Array<Array<object>>} lists each list is already ranked best-first
27
- * @param {{k?: number}} [opts] k constant (default 60)
27
+ * @param {{k?: number, weights?: number[]}} [opts] k constant (default 60);
28
+ * optional per-list weights (the original query can outweigh derived variants)
28
29
  * @returns {{ fused: object[], scores: Map<string, number> }}
29
30
  * fused: sources sorted by accumulated RRF score desc (ties keep first
30
31
  * appearance order); sources without a usable key are dropped.
31
32
  */
32
- export function rrfFuse(lists, { k = RRF_K } = {}) {
33
+ export function rrfFuse(lists, { k = RRF_K, weights } = {}) {
33
34
  const kk = Number(k) > 0 ? Number(k) : RRF_K;
34
35
  const scores = new Map(); // key -> accumulated score
35
36
  const firstSeen = new Map(); // key -> source object (first metadata wins)
36
37
  const order = []; // keys in first-appearance order (stable ties)
37
38
 
38
- for (const list of Array.isArray(lists) ? lists : []) {
39
+ const allLists = Array.isArray(lists) ? lists : [];
40
+ for (let index = 0; index < allLists.length; index++) {
41
+ const list = allLists[index];
39
42
  if (!Array.isArray(list)) continue;
43
+ const weight = Number(weights?.[index]);
44
+ const w = Number.isFinite(weight) && weight > 0 ? weight : 1;
40
45
  for (let rank = 0; rank < list.length; rank++) {
41
46
  const item = list[rank];
42
47
  const key = itemKey(item);
43
48
  if (!key) continue;
44
- scores.set(key, (scores.get(key) ?? 0) + 1 / (kk + rank));
49
+ scores.set(key, (scores.get(key) ?? 0) + w / (kk + rank));
45
50
  if (!firstSeen.has(key)) {
46
51
  firstSeen.set(key, item);
47
52
  order.push(key);
@@ -32,17 +32,12 @@
32
32
  *
33
33
  * @module lib/settings-api.js
34
34
  */
35
- import { rejectionFor } from "./trust.js";
35
+ import { rejectionFor, rejectionBody } from "./trust.js";
36
+ import { findPluginRow } from "./util/namespace.js";
36
37
 
37
38
  const SETTINGS_PATH = "/api/unified-search/settings";
38
39
  const MAX_BODY_BYTES = 64 * 1024;
39
40
  const MAX_OPS = 64;
40
- /**
41
- * Field names the card owns. Used only to find the profile entry in
42
- * `describe()` output — never as a whitelist; the whitelist is the live
43
- * `Config.dict`, so schema growth is picked up without touching this file.
44
- */
45
- const DISCOVERY_FIELDS = ["numResults", "backendTimeoutMs", "enabledBackends", "enableExa"];
46
41
 
47
42
  /**
48
43
  * Register the (exact) settings route on the late-mounted webServer.
@@ -50,8 +45,8 @@ const DISCOVERY_FIELDS = ["numResults", "backendTimeoutMs", "enabledBackends", "
50
45
  * @param {{ getSettings: () => unknown, getConfig: () => unknown, getConnection?: () => unknown }} deps
51
46
  */
52
47
  export function registerSettingsRoutes(ws, deps) {
53
- if (!ws || typeof ws.register !== "function") return;
54
- ws.register({
48
+ if (!ws || typeof ws.register !== "function") return [];
49
+ const disposer = ws.register({
55
50
  kind: "exact",
56
51
  path: SETTINGS_PATH,
57
52
  handler: guarded(deps, (req, res) => {
@@ -66,13 +61,15 @@ export function registerSettingsRoutes(ws, deps) {
66
61
  return;
67
62
  }
68
63
  if (req.method === "POST") {
69
- void write(req, res, deps);
70
- return;
64
+ // Return the promise so guarded()'s catch handles write() failures
65
+ // instead of leaving an unhandled rejection with no response.
66
+ return write(req, res, deps);
71
67
  }
72
68
  res.setHeader("allow", "GET, POST");
73
69
  sendJson(res, 405, { ok: false, error: "method not allowed (GET/POST)" });
74
70
  }),
75
71
  });
72
+ return typeof disposer === "function" ? [disposer] : [];
76
73
  }
77
74
 
78
75
  /* ------------------------------------------------------------------ */
@@ -83,7 +80,7 @@ function guarded(deps, handler) {
83
80
  return (req, res) => {
84
81
  const rejection = rejectionFor(req, typeof deps.getConnection === "function" ? deps.getConnection() : undefined);
85
82
  if (rejection !== undefined) {
86
- sendJson(res, rejection, { ok: false, error: rejection === 503 ? "admission unavailable" : "untrusted request" });
83
+ sendJson(res, rejection, rejectionBody(rejection));
87
84
  return;
88
85
  }
89
86
  Promise.resolve()
@@ -95,7 +92,10 @@ function guarded(deps, handler) {
95
92
  };
96
93
  }
97
94
 
98
- /** Read the plugin's volatile form snapshot from the host settings service. */
95
+ /** Read the plugin's volatile form snapshot from the host settings service.
96
+ * `revision` counts value changes, not write requests: setting a field to its
97
+ * current value returns 200 without advancing it. Pass the returned revision
98
+ * as expectedRevision on the next write for optimistic-concurrency checks. */
99
99
  function describe(deps) {
100
100
  const settings = typeof deps.getSettings === "function" ? deps.getSettings() : undefined;
101
101
  if (settings === undefined || settings === null || typeof settings.describe !== "function") {
@@ -122,17 +122,13 @@ function describe(deps) {
122
122
  }
123
123
 
124
124
  /**
125
- * Locate this plugin's descriptor: first by shape (the card's own fields
126
- * present in the resolved value), then by the profile entry id this package's
127
- * bundle patch inserts. Shape-first survives a renamed insert id; the literal
128
- * survives a host that reports an empty value.
125
+ * Locate the plugin's settings row. Delegates to the shared resolver so the
126
+ * HTTP bridge and the provider resolve the same namespace in the same way.
127
+ * @param {unknown} descriptors - `settings.describe()` output.
128
+ * @returns {object|undefined} the matching row.
129
129
  */
130
130
  function findNamespace(descriptors) {
131
- if (!Array.isArray(descriptors)) return undefined;
132
- const rows = descriptors.filter((row) => row !== null && typeof row === "object" && typeof row.ns === "string");
133
- return rows.find((row) => row.value !== undefined && row.value !== null
134
- && typeof row.value === "object" && DISCOVERY_FIELDS.some((key) => Object.hasOwn(row.value, key)))
135
- ?? rows.find((row) => row.ns === "dsh-websearch");
131
+ return findPluginRow(descriptors);
136
132
  }
137
133
 
138
134
  async function write(req, res, deps) {
@@ -166,6 +162,24 @@ async function write(req, res, deps) {
166
162
  const fields = config !== undefined && config !== null && config.dict !== undefined && config.dict !== null
167
163
  ? config.dict
168
164
  : {};
165
+ const view = findNamespace(safeDescribe(settings));
166
+ if (view === undefined) {
167
+ sendJson(res, 503, { ok: false, error: "settings namespace unavailable" });
168
+ return;
169
+ }
170
+ if (body.expectedRevision !== undefined && !Number.isInteger(body.expectedRevision)) {
171
+ sendJson(res, 400, { ok: false, error: "expectedRevision must be an integer" });
172
+ return;
173
+ }
174
+ const expected = body.expectedRevision;
175
+ // Report a stale revision before field validation: otherwise a caller that
176
+ // both lost a race and sent a bad value sees a misleading 400 and retries
177
+ // forever. The host mutate() still performs the authoritative CAS below,
178
+ // so a revision that changes between here and there remains covered.
179
+ if (expected !== undefined && Number.isInteger(view.revision) && expected !== view.revision) {
180
+ sendJson(res, 409, { ok: false, code: "SETTINGS_CONFLICT", error: "settings changed elsewhere; reload and retry" });
181
+ return;
182
+ }
169
183
  const ops = [];
170
184
  for (const raw of wanted) {
171
185
  const parsed = validateOp(raw, fields);
@@ -175,12 +189,6 @@ async function write(req, res, deps) {
175
189
  }
176
190
  ops.push(parsed);
177
191
  }
178
- const view = findNamespace(safeDescribe(settings));
179
- if (view === undefined) {
180
- sendJson(res, 503, { ok: false, error: "settings namespace unavailable" });
181
- return;
182
- }
183
- const expected = Number.isInteger(body.expectedRevision) ? body.expectedRevision : undefined;
184
192
  try {
185
193
  await settings.mutate(view.ns, ops, expected);
186
194
  } catch (err) {
@@ -248,19 +256,29 @@ function readBody(req) {
248
256
  return new Promise((resolveBody, rejectBody) => {
249
257
  const chunks = [];
250
258
  let size = 0;
259
+ const onEnd = () => resolveBody(Buffer.concat(chunks).toString("utf8"));
260
+ const onError = rejectBody;
251
261
  req.on("data", (chunk) => {
252
262
  size += chunk.length;
253
263
  if (size > MAX_BODY_BYTES) {
254
264
  const oversize = new Error("request body too large");
255
265
  oversize.status = 413;
256
266
  rejectBody(oversize);
267
+ // Stop consuming and release the stream so a keep-alive connection is
268
+ // not left waiting for an `end` that can still arrive.
257
269
  req.removeAllListeners("data");
270
+ req.removeListener("end", onEnd);
271
+ req.removeListener("error", onError);
272
+ // Drain the remaining body instead of destroying the socket: the 413
273
+ // response still has to be written, and destroying here makes the
274
+ // client see ECONNRESET (65 号 N1, a regression of the drain fix).
275
+ req.resume();
258
276
  return;
259
277
  }
260
278
  chunks.push(chunk);
261
279
  });
262
- req.on("end", () => resolveBody(Buffer.concat(chunks).toString("utf8")));
263
- req.on("error", rejectBody);
280
+ req.on("end", onEnd);
281
+ req.on("error", onError);
264
282
  });
265
283
  }
266
284
 
package/lib/trust.js CHANGED
@@ -16,7 +16,7 @@
16
16
  * matches the `Host` authority whenever the client supplies one, with a
17
17
  * narrow exception for the desktop's dsh-app://app relay Referer.
18
18
  *
19
- * @module src/trust.js
19
+ * @module lib/trust.js
20
20
  */
21
21
 
22
22
  /** Hostnames a same-machine caller can legitimately use. */
@@ -128,6 +128,12 @@ export function structuralRejection(req) {
128
128
  return structuralReason(req) === undefined ? undefined : 403
129
129
  }
130
130
 
131
+ /** The response body every guarded route returns for a rejection. Fixed
132
+ * strings only: the rejection code is a number, never caller-supplied text. */
133
+ export function rejectionBody(code) {
134
+ return { ok: false, error: code === 503 ? 'admission unavailable' : 'untrusted request' }
135
+ }
136
+
131
137
  /** Return a fixed reason without exposing caller-supplied strings. */
132
138
  function structuralReason(req) {
133
139
  const host = authorityOf(req.headers.host, 'http')
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Validation for operator-supplied backend base URLs.
3
+ *
4
+ * A base URL decides where the backend connects AND where its API key is
5
+ * sent, so it is a trust boundary, not a formatting preference: only HTTPS,
6
+ * plus plain HTTP for loopback/RFC1918 self-hosted instances. Embedded
7
+ * credentials are rejected because the caller supplies the key separately.
8
+ * Link-local ranges are rejected regardless of scheme — they host instance
9
+ * metadata, not a search service, and an attacker-controlled settings write
10
+ * must not turn the plugin into a metadata client.
11
+ *
12
+ * @module lib/util/base-url
13
+ */
14
+
15
+ /** Hosts that may be reached over plain HTTP (self-hosted SearXNG etc.). */
16
+ const PRIVATE_HOST_RE = /^(localhost|127(\.\d{1,3}){3}|10(\.\d{1,3}){3}|192\.168(\.\d{1,3}){2}|172\.(1[6-9]|2\d|3[01])(\.\d{1,3}){2})$/;
17
+
18
+ /** Always-off-limits hosts: cloud instance metadata and the unspecified address. */
19
+ const BLOCKED_HOST_RE = /^(0\.0\.0\.0|169\.254\.\d{1,3}\.\d{1,3}|metadata(\.google\.internal)?|instance-data)$/;
20
+
21
+ /**
22
+ * Why a candidate base URL is unusable, or `undefined` when it is allowed.
23
+ *
24
+ * @param {unknown} raw - candidate URL string.
25
+ * @returns {string|undefined} short reason suitable for an error message.
26
+ */
27
+ export function invalidBaseURL(raw) {
28
+ if (typeof raw !== "string" || raw.trim() === "") return "empty URL";
29
+ let url;
30
+ try {
31
+ url = new URL(raw);
32
+ } catch {
33
+ return "not a URL";
34
+ }
35
+ if (url.username !== "" || url.password !== "") return "credentials in URL rejected";
36
+ // URL.hostname keeps brackets on IPv6 literals.
37
+ const host = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
38
+ if (BLOCKED_HOST_RE.test(host)
39
+ || /^fe[89ab][0-9a-f]:/.test(host)
40
+ || host === "fd00:ec2::254"
41
+ || /^::ffff:(a9fe|fe[89ab])/i.test(host)) return "link-local host rejected";
42
+ if (url.protocol === "https:") return undefined;
43
+ if (url.protocol === "http:" && (PRIVATE_HOST_RE.test(host) || host === "::1")) return undefined;
44
+ return "https required (plain http only for private hosts)";
45
+ }
46
+
47
+ /**
48
+ * True when the single candidate is allowed. Convenience wrapper for callers that
49
+ * only need a boolean.
50
+ *
51
+ * @param {unknown} raw - candidate URL string.
52
+ * @returns {boolean} whether the URL passed validation.
53
+ */
54
+ export function isAllowedBaseURL(raw) {
55
+ return invalidBaseURL(raw) === undefined;
56
+ }
@@ -21,17 +21,141 @@
21
21
 
22
22
  import http from "node:http";
23
23
  import https from "node:https";
24
+ import net from "node:net";
24
25
 
25
26
  const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);
26
27
  const MAX_REDIRECTS = 5;
28
+ // Backend responses are search results/HTML, not downloads. Buffer at most
29
+ // 10 MiB so a hostile or broken endpoint cannot exhaust the plugin process.
30
+ const MAX_RESPONSE_BYTES = 10 * 1024 * 1024;
31
+
32
+ /** URL.hostname keeps IPv6 brackets; net/tls/Host compare need the bare address. */
33
+ const bareHost = (host) => String(host).replace(/^\[|\]$/g, "");
27
34
 
28
35
  /** fetch-compatible entry: forwarder first, then HTTPS_PROXY/HTTP_PROXY tunnel. */
29
- export function egressFetch(url, init = {}) {
36
+ export function egressFetch(url, init = {}, depth = 0) {
30
37
  const forwarder = forwarderFor(url);
31
- if (forwarder !== undefined) return forwarderFetch(String(url), init, forwarder);
38
+ if (forwarder !== undefined) {
39
+ return forwarderFetch(String(url), init, forwarder).catch((error) => {
40
+ // The sidecar is an OPTIONAL accelerator. A transport-level rejection
41
+ // means the hop itself is unusable (not that the upstream refused us),
42
+ // so retry once over the proxy path before surfacing the failure.
43
+ if (init.signal?.aborted === true || !isForwarderTransportError(error)) throw error;
44
+ forwarderProbes.set(forwarder.endpoint, { ok: false, at: Date.now() });
45
+ const proxy = proxyFor(url);
46
+ if (proxy === undefined) return cappedNativeFetch(String(url), init);
47
+ return tunneledFetch(String(url), init, proxy, depth);
48
+ });
49
+ }
32
50
  const proxy = proxyFor(url);
33
- if (proxy === undefined) return fetch(url, init);
34
- return tunneledFetch(String(url), init, proxy, 0);
51
+ if (proxy === undefined) return cappedNativeFetch(String(url), init);
52
+ return tunneledFetch(String(url), init, proxy, depth);
53
+ }
54
+
55
+ /**
56
+ * Native fetch path with the same 10 MiB body ceiling as the tunneled path.
57
+ * Without this, the default (no proxy) egress accepted arbitrary bodies and
58
+ * the security cap only held when a proxy was configured.
59
+ * @param {string} url
60
+ * @param {RequestInit} init
61
+ * @returns {Promise<Response>}
62
+ */
63
+ async function cappedNativeFetch(url, init = {}) {
64
+ const res = await fetch(url, init);
65
+ if (res.body === null || String(init.method ?? "GET").toUpperCase() === "HEAD") return res;
66
+ let bytes = 0;
67
+ const stream = res.body.pipeThrough(new TransformStream({
68
+ transform(chunk, controller) {
69
+ bytes += chunk.byteLength;
70
+ if (bytes > MAX_RESPONSE_BYTES) {
71
+ controller.error(new TypeError(`fetch failed: response body exceeds ${MAX_RESPONSE_BYTES} bytes`));
72
+ return;
73
+ }
74
+ controller.enqueue(chunk);
75
+ },
76
+ }));
77
+ return new Response(stream, { status: res.status, statusText: res.statusText, headers: res.headers });
78
+ }
79
+
80
+ /**
81
+ * Distinguish "the sidecar hop failed" from "the upstream answered with an
82
+ * error". Only the former may be retried over the proxy: retrying a 4xx/5xx
83
+ * would double-count rate limits.
84
+ * @param {unknown} error rejection from forwarderFetch
85
+ * @returns {boolean} true when the hop should be treated as unusable
86
+ */
87
+ function isForwarderTransportError(error) {
88
+ const code = error !== null && typeof error === "object" ? error.code : undefined;
89
+ if (typeof code === "string") {
90
+ // ECONNREFUSED / EHOSTUNREACH / ENETUNREACH mean "nothing is there" — the
91
+ // sidecar is absent and the proxy path is strictly better. Timeouts and
92
+ // resets mean the sidecar IS there but unhealthy, which the caller should
93
+ // see (retrying over the proxy would hide a broken sidecar).
94
+ return ["ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH"].includes(code);
95
+ }
96
+ // Without a machine-readable code, only an explicit "unreachable" verdict
97
+ // counts. "did not respond within Nms" means the sidecar accepted and then
98
+ // stalled — the caller must see that, not have it papered over by a proxy
99
+ // retry.
100
+ const text = String(error instanceof Error ? error.message : error);
101
+ return /forwarder unreachable|ECONNREFUSED/i.test(text);
102
+ }
103
+
104
+
105
+ /**
106
+ * Probe cache for the optional TLS-egress forwarder. `forwarderFor()` must stay
107
+ * synchronous, so the reachability check runs in the background and the first
108
+ * call for an endpoint deliberately returns "not usable": the proxy path is
109
+ * always correct, whereas a dead sidecar would cost ~20s per request.
110
+ * A failed endpoint is re-probed after REPROBE_MS so a sidecar that starts
111
+ * later is picked up without restarting the process.
112
+ */
113
+ const FORWARDER_REPROBE_MS = 60_000;
114
+ const forwarderProbes = new Map();
115
+
116
+ /**
117
+ * @param {string} endpoint forwarder base URL
118
+ * @returns {boolean} true only after a probe confirmed the port accepts
119
+ */
120
+ function forwarderUsable(endpoint) {
121
+ const probe = forwarderProbes.get(endpoint);
122
+ if (probe !== undefined) {
123
+ // A confirmed-dead endpoint stays retired until the re-probe window
124
+ // expires; a confirmed-live one is used directly.
125
+ if (probe.ok) {
126
+ if (Date.now() - probe.at < FORWARDER_REPROBE_MS) return true;
127
+ } else if (Date.now() - probe.at < FORWARDER_REPROBE_MS) {
128
+ return false;
129
+ }
130
+ }
131
+ // Unknown, or the verdict is stale: probe again, but do NOT block this
132
+ // request on the result. Optimistically take the forwarder path (upstream
133
+ // behaviour) and let a transport failure fall back to the proxy; a first
134
+ // request must never be denied the JA3 fix merely because the probe has
135
+ // not finished yet.
136
+ probeForwarder(endpoint);
137
+ return true;
138
+ }
139
+
140
+ /** @param {string} endpoint forwarder base URL */
141
+ function probeForwarder(endpoint) {
142
+ let host;
143
+ let port;
144
+ try {
145
+ const parsed = new URL(endpoint);
146
+ host = bareHost(parsed.hostname);
147
+ port = Number(parsed.port) || (parsed.protocol === "https:" ? 443 : 80);
148
+ } catch {
149
+ return;
150
+ }
151
+ const socket = net.connect({ host, port });
152
+ const settle = (ok) => {
153
+ socket.destroy();
154
+ forwarderProbes.set(endpoint, { ok, at: Date.now() });
155
+ };
156
+ socket.setTimeout(2000, () => settle(false));
157
+ socket.once("connect", () => settle(true));
158
+ socket.once("error", () => settle(false));
35
159
  }
36
160
 
37
161
  /** Resolve the TLS-egress forwarder for a request target (NO_PROXY aware). */
@@ -47,11 +171,18 @@ function forwarderFor(url) {
47
171
  const endpoint = env.DSH_EGRESS_FORWARDER;
48
172
  if (endpoint === undefined || endpoint === "") return undefined;
49
173
  if (inNoProxy(target, env.NO_PROXY || env.no_proxy)) return undefined;
174
+ // The sidecar is an OPTIONAL accelerator. A configured-yet-dead endpoint
175
+ // would otherwise make every request wait ~20s before failing, which is
176
+ // strictly worse than the proxy path. Only take the forwarder when a
177
+ // background probe has actually seen the port accept a connection; an
178
+ // unknown or failed probe keeps us on the proxy (fail-open).
179
+ if (!forwarderUsable(endpoint)) return undefined;
50
180
  const proxy = env.DSH_EGRESS_FORWARDER_PROXY
51
181
  || env.HTTPS_PROXY || env.https_proxy || env.HTTP_PROXY || env.http_proxy || "";
52
182
  return { endpoint, proxy: proxy === "" ? undefined : proxy };
53
183
  }
54
184
 
185
+
55
186
  /** Resolve the proxy URL for a request target (NO_PROXY aware). */
56
187
  function proxyFor(url) {
57
188
  let target;
@@ -73,7 +204,7 @@ function proxyFor(url) {
73
204
  /** NO_PROXY matching: "*", bare hosts, leading-dot suffixes, optional :port. */
74
205
  function inNoProxy(target, raw) {
75
206
  if (raw === undefined || raw === "") return false;
76
- const host = target.hostname.toLowerCase();
207
+ const host = bareHost(target.hostname).toLowerCase();
77
208
  const port = target.port !== "" ? target.port : target.protocol === "https:" ? "443" : "80";
78
209
  for (const piece of String(raw).split(",")) {
79
210
  const item = piece.trim().toLowerCase();
@@ -123,6 +254,12 @@ async function tunneledFetch(url, init, proxy, depth) {
123
254
  await drain(response);
124
255
  throw new TypeError(`fetch failed: redirect mode is set to error (${response.status})`);
125
256
  }
257
+ if (init.redirect !== "manual" && depth >= MAX_REDIRECTS) {
258
+ // Returning the final 3xx made a redirect loop look like a normal
259
+ // (ok:false) response; callers only saw an opaque empty body.
260
+ await drain(response);
261
+ throw new TypeError(`fetch failed: too many redirects (max ${MAX_REDIRECTS})`);
262
+ }
126
263
  if (init.redirect !== "manual" && depth < MAX_REDIRECTS) {
127
264
  const next = new URL(location, target);
128
265
  const dropBody = response.status === 303
@@ -131,7 +268,7 @@ async function tunneledFetch(url, init, proxy, depth) {
131
268
  ? { ...init, method: "GET", body: undefined, headers: withoutBodyHeaders(init.headers) }
132
269
  : { ...init };
133
270
  await drain(response);
134
- return egressFetch(next.href, nextInit);
271
+ return egressFetch(next.href, nextInit, depth + 1);
135
272
  }
136
273
  }
137
274
  }
@@ -219,7 +356,7 @@ function forwarderExchange(endpoint, spec, body, signal, callerSignal, timeoutSi
219
356
  reject(new TypeError(`fetch failed: forwarder unreachable (${sanitize(error)})`, { cause: error }));
220
357
  };
221
358
  const request = transport.request({
222
- host: target.hostname,
359
+ host: bareHost(target.hostname),
223
360
  port: target.port !== "" ? Number(target.port) : secure ? 443 : 80,
224
361
  method: "POST",
225
362
  path: target.pathname + target.search,
@@ -276,7 +413,7 @@ function httpsViaConnect(target, proxyUrl, method, headers, body, signal) {
276
413
  const proxyAuth = basicProxyAuth(proxy);
277
414
  if (proxyAuth !== undefined) connectHeaders["proxy-authorization"] = proxyAuth;
278
415
  const connectReq = http.request({
279
- host: proxy.hostname,
416
+ host: bareHost(proxy.hostname),
280
417
  port: proxy.port !== "" ? Number(proxy.port) : 80,
281
418
  method: "CONNECT",
282
419
  path: `${target.hostname}:${port}`,
@@ -295,13 +432,24 @@ function httpsViaConnect(target, proxyUrl, method, headers, body, signal) {
295
432
  fail(new TypeError(`fetch failed: proxy CONNECT rejected with ${connectRes.statusCode}`));
296
433
  return;
297
434
  }
435
+ // normalizeHeaders() strips Host
436
+ // (see below). For a request tunnelled through CONNECT, Node's
437
+ // https.request() then synthesises a Host from options.host — which is
438
+ // absent here (we pass an already-connected `socket`), so the value is
439
+ // the bare hostname without the port, not the request-target authority.
440
+ // Cloudflare-fronted MCP endpoints (mcp.exa.ai, search.parallel.ai)
441
+ // reject that with HTTP 403 before any MCP handshake. httpViaProxy()
442
+ // already restores the header with the same expression; mirror it here
443
+ // so both proxy paths send an explicit, port-qualified Host. Node
444
+ // auto-synthesises a non-port-qualified Host under { socket }, which
445
+ // the upstream proxy rejects; target.host carries the authority form.
298
446
  const request = https.request({
299
447
  socket,
300
448
  agent: false,
301
- servername: target.hostname,
449
+ servername: bareHost(target.hostname),
302
450
  method,
303
451
  path: pathWithQuery(target),
304
- headers,
452
+ headers: { ...headers, host: headers.host ?? target.host },
305
453
  });
306
454
  open.push(request);
307
455
  request.on("error", (error) => fail(new TypeError(`fetch failed: ${sanitize(error)}`, { cause: error })));
@@ -323,7 +471,7 @@ function httpViaProxy(target, proxyUrl, method, headers, body, signal) {
323
471
  const proxy = new URL(proxyUrl);
324
472
  return new Promise((resolve, reject) => {
325
473
  const request = http.request({
326
- host: proxy.hostname,
474
+ host: bareHost(proxy.hostname),
327
475
  port: proxy.port !== "" ? Number(proxy.port) : 80,
328
476
  method,
329
477
  path: target.href,
@@ -362,17 +510,42 @@ function httpViaProxy(target, proxyUrl, method, headers, body, signal) {
362
510
  function collect(res) {
363
511
  return new Promise((resolve, reject) => {
364
512
  const chunks = [];
365
- res.on("data", (chunk) => chunks.push(chunk));
513
+ let bytes = 0;
514
+ let settled = false;
515
+ res.on("data", (chunk) => {
516
+ if (settled) return;
517
+ bytes += chunk.length;
518
+ if (bytes > MAX_RESPONSE_BYTES) {
519
+ settled = true;
520
+ res.destroy();
521
+ reject(new TypeError(`fetch failed: response body exceeds ${MAX_RESPONSE_BYTES} bytes`));
522
+ return;
523
+ }
524
+ chunks.push(chunk);
525
+ });
366
526
  res.on("end", () => {
527
+ if (settled) return;
528
+ settled = true;
367
529
  // Null-body statuses (204/304) and empty streams must construct a
368
530
  // bodiless Response; an empty Buffer is not null and would throw.
369
- const payload = chunks.length === 0 ? null : Buffer.concat(chunks);
370
- resolve(new Response(payload, {
371
- status: res.statusCode ?? 502,
372
- headers: headersFromRaw(res),
373
- }));
531
+ // Constructing a Response can throw (invalid status, illegal header
532
+ // name, 204 with a body). This runs inside an event callback, so an
533
+ // uncaught throw here would bypass reject() and crash the process.
534
+ try {
535
+ const payload = chunks.length === 0 ? null : Buffer.concat(chunks);
536
+ resolve(new Response(payload, {
537
+ status: res.statusCode ?? 502,
538
+ headers: headersFromRaw(res),
539
+ }));
540
+ } catch (err) {
541
+ reject(err);
542
+ }
543
+ });
544
+ res.on("error", (err) => {
545
+ if (settled) return;
546
+ settled = true;
547
+ reject(err);
374
548
  });
375
- res.on("error", reject);
376
549
  });
377
550
  }
378
551
 
@@ -401,6 +574,12 @@ function normalizeHeaders(raw) {
401
574
  if (value !== undefined) headers[String(key).toLowerCase()] = String(value);
402
575
  }
403
576
  }
577
+ // Host is deliberately removed: a caller-supplied Host must not override
578
+ // the tunnel target. Each transport is therefore responsible for adding it
579
+ // back before the request is sent — httpViaProxy() and httpsViaConnect()
580
+ // both do so via `host: headers.host ?? target.host`. Do not delete those
581
+ // two restorations; doing so reintroduces the Cloudflare 403 described in
582
+ // the comment at httpsViaConnect().
404
583
  delete headers["host"];
405
584
  return headers;
406
585
  }