@240xu/dsh-websearch 2.8.7 → 2.8.9
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/README.md +55 -12
- package/lib/backends/anthropic-like.js +11 -7
- package/lib/backends/brave.js +4 -2
- package/lib/backends/ddg.js +27 -11
- package/lib/backends/exa.js +3 -1
- package/lib/backends/firecrawl.js +127 -0
- package/lib/backends/mojeek.js +4 -2
- package/lib/backends/openai.js +12 -7
- package/lib/backends/parallel.js +2 -20
- package/lib/backends/searxng.js +36 -8
- package/lib/backends/serper.js +4 -2
- package/lib/backends/tavily.js +4 -2
- package/lib/backends/tinyfish.js +124 -0
- package/lib/breaker.js +25 -4
- package/lib/cache.js +30 -3
- package/lib/client.js +564 -182
- package/lib/health.js +20 -17
- package/lib/history.js +26 -36
- package/lib/index.js +351 -57
- package/lib/prompting.js +13 -3
- package/lib/provider.js +273 -78
- package/lib/rrf.js +9 -4
- package/lib/settings-api.js +44 -30
- package/lib/trust.js +6 -0
- package/lib/util/base-url.js +56 -0
- package/lib/util/egress-fetch.js +163 -12
- package/lib/util/failure-label.js +73 -12
- package/lib/util/log.js +5 -3
- package/lib/util/mcp-client.js +89 -40
- package/lib/util/namespace.js +28 -0
- package/lib/util/rank.js +6 -2
- package/lib/util/redact.js +49 -0
- package/lib/util/web-error.js +49 -0
- package/package.json +3 -4
- package/lib/config.js +0 -205
package/lib/settings-api.js
CHANGED
|
@@ -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
|
-
|
|
70
|
-
|
|
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,
|
|
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
|
|
126
|
-
*
|
|
127
|
-
*
|
|
128
|
-
*
|
|
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
|
-
|
|
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,20 @@ 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
|
+
const expected = Number.isInteger(body.expectedRevision) ? body.expectedRevision : undefined;
|
|
171
|
+
// Report a stale revision before field validation: otherwise a caller that
|
|
172
|
+
// both lost a race and sent a bad value sees a misleading 400 and retries
|
|
173
|
+
// forever. The host mutate() still performs the authoritative CAS below,
|
|
174
|
+
// so a revision that changes between here and there remains covered.
|
|
175
|
+
if (expected !== undefined && Number.isInteger(view.revision) && expected !== view.revision) {
|
|
176
|
+
sendJson(res, 409, { ok: false, code: "SETTINGS_CONFLICT", error: "settings changed elsewhere; reload and retry" });
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
169
179
|
const ops = [];
|
|
170
180
|
for (const raw of wanted) {
|
|
171
181
|
const parsed = validateOp(raw, fields);
|
|
@@ -175,12 +185,6 @@ async function write(req, res, deps) {
|
|
|
175
185
|
}
|
|
176
186
|
ops.push(parsed);
|
|
177
187
|
}
|
|
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
188
|
try {
|
|
185
189
|
await settings.mutate(view.ns, ops, expected);
|
|
186
190
|
} catch (err) {
|
|
@@ -248,19 +252,29 @@ function readBody(req) {
|
|
|
248
252
|
return new Promise((resolveBody, rejectBody) => {
|
|
249
253
|
const chunks = [];
|
|
250
254
|
let size = 0;
|
|
255
|
+
const onEnd = () => resolveBody(Buffer.concat(chunks).toString("utf8"));
|
|
256
|
+
const onError = rejectBody;
|
|
251
257
|
req.on("data", (chunk) => {
|
|
252
258
|
size += chunk.length;
|
|
253
259
|
if (size > MAX_BODY_BYTES) {
|
|
254
260
|
const oversize = new Error("request body too large");
|
|
255
261
|
oversize.status = 413;
|
|
256
262
|
rejectBody(oversize);
|
|
263
|
+
// Stop consuming and release the stream so a keep-alive connection is
|
|
264
|
+
// not left waiting for an `end` that can still arrive.
|
|
257
265
|
req.removeAllListeners("data");
|
|
266
|
+
req.removeListener("end", onEnd);
|
|
267
|
+
req.removeListener("error", onError);
|
|
268
|
+
// Drain the remaining body instead of destroying the socket: the 413
|
|
269
|
+
// response still has to be written, and destroying here makes the
|
|
270
|
+
// client see ECONNRESET (65 号 N1, a regression of the drain fix).
|
|
271
|
+
req.resume();
|
|
258
272
|
return;
|
|
259
273
|
}
|
|
260
274
|
chunks.push(chunk);
|
|
261
275
|
});
|
|
262
|
-
req.on("end",
|
|
263
|
-
req.on("error",
|
|
276
|
+
req.on("end", onEnd);
|
|
277
|
+
req.on("error", onError);
|
|
264
278
|
});
|
|
265
279
|
}
|
|
266
280
|
|
package/lib/trust.js
CHANGED
|
@@ -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 every 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
|
+
}
|
package/lib/util/egress-fetch.js
CHANGED
|
@@ -21,17 +21,113 @@
|
|
|
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;
|
|
27
31
|
|
|
28
32
|
/** fetch-compatible entry: forwarder first, then HTTPS_PROXY/HTTP_PROXY tunnel. */
|
|
29
|
-
export function egressFetch(url, init = {}) {
|
|
33
|
+
export function egressFetch(url, init = {}, depth = 0) {
|
|
30
34
|
const forwarder = forwarderFor(url);
|
|
31
|
-
if (forwarder !== undefined)
|
|
35
|
+
if (forwarder !== undefined) {
|
|
36
|
+
return forwarderFetch(String(url), init, forwarder).catch((error) => {
|
|
37
|
+
// The sidecar is an OPTIONAL accelerator. A transport-level rejection
|
|
38
|
+
// means the hop itself is unusable (not that the upstream refused us),
|
|
39
|
+
// so retry once over the proxy path before surfacing the failure.
|
|
40
|
+
if (init.signal?.aborted === true || !isForwarderTransportError(error)) throw error;
|
|
41
|
+
forwarderProbes.set(forwarder.endpoint, { ok: false, at: Date.now() });
|
|
42
|
+
const proxy = proxyFor(url);
|
|
43
|
+
if (proxy === undefined) return fetch(url, init);
|
|
44
|
+
return tunneledFetch(String(url), init, proxy, depth);
|
|
45
|
+
});
|
|
46
|
+
}
|
|
32
47
|
const proxy = proxyFor(url);
|
|
33
48
|
if (proxy === undefined) return fetch(url, init);
|
|
34
|
-
return tunneledFetch(String(url), init, proxy,
|
|
49
|
+
return tunneledFetch(String(url), init, proxy, depth);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Distinguish "the sidecar hop failed" from "the upstream answered with an
|
|
54
|
+
* error". Only the former may be retried over the proxy: retrying a 4xx/5xx
|
|
55
|
+
* would double-count rate limits.
|
|
56
|
+
* @param {unknown} error rejection from forwarderFetch
|
|
57
|
+
* @returns {boolean} true when the hop should be treated as unusable
|
|
58
|
+
*/
|
|
59
|
+
function isForwarderTransportError(error) {
|
|
60
|
+
const code = error !== null && typeof error === "object" ? error.code : undefined;
|
|
61
|
+
if (typeof code === "string") {
|
|
62
|
+
// ECONNREFUSED / EHOSTUNREACH / ENETUNREACH mean "nothing is there" — the
|
|
63
|
+
// sidecar is absent and the proxy path is strictly better. Timeouts and
|
|
64
|
+
// resets mean the sidecar IS there but unhealthy, which the caller should
|
|
65
|
+
// see (retrying over the proxy would hide a broken sidecar).
|
|
66
|
+
return ["ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH"].includes(code);
|
|
67
|
+
}
|
|
68
|
+
// Without a machine-readable code, only an explicit "unreachable" verdict
|
|
69
|
+
// counts. "did not respond within Nms" means the sidecar accepted and then
|
|
70
|
+
// stalled — the caller must see that, not have it papered over by a proxy
|
|
71
|
+
// retry.
|
|
72
|
+
const text = String(error instanceof Error ? error.message : error);
|
|
73
|
+
return /forwarder unreachable|ECONNREFUSED/i.test(text);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Probe cache for the optional TLS-egress forwarder. `forwarderFor()` must stay
|
|
79
|
+
* synchronous, so the reachability check runs in the background and the first
|
|
80
|
+
* call for an endpoint deliberately returns "not usable": the proxy path is
|
|
81
|
+
* always correct, whereas a dead sidecar would cost ~20s per request.
|
|
82
|
+
* A failed endpoint is re-probed after REPROBE_MS so a sidecar that starts
|
|
83
|
+
* later is picked up without restarting the process.
|
|
84
|
+
*/
|
|
85
|
+
const FORWARDER_REPROBE_MS = 60_000;
|
|
86
|
+
const forwarderProbes = new Map();
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* @param {string} endpoint forwarder base URL
|
|
90
|
+
* @returns {boolean} true only after a probe confirmed the port accepts
|
|
91
|
+
*/
|
|
92
|
+
function forwarderUsable(endpoint) {
|
|
93
|
+
const probe = forwarderProbes.get(endpoint);
|
|
94
|
+
if (probe !== undefined) {
|
|
95
|
+
// A confirmed-dead endpoint stays retired until the re-probe window
|
|
96
|
+
// expires; a confirmed-live one is used directly.
|
|
97
|
+
if (probe.ok) {
|
|
98
|
+
if (Date.now() - probe.at < FORWARDER_REPROBE_MS) return true;
|
|
99
|
+
} else if (Date.now() - probe.at < FORWARDER_REPROBE_MS) {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
// Unknown, or the verdict is stale: probe again, but do NOT block this
|
|
104
|
+
// request on the result. Optimistically take the forwarder path (upstream
|
|
105
|
+
// behaviour) and let a transport failure fall back to the proxy; a first
|
|
106
|
+
// request must never be denied the JA3 fix merely because the probe has
|
|
107
|
+
// not finished yet.
|
|
108
|
+
probeForwarder(endpoint);
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** @param {string} endpoint forwarder base URL */
|
|
113
|
+
function probeForwarder(endpoint) {
|
|
114
|
+
let host;
|
|
115
|
+
let port;
|
|
116
|
+
try {
|
|
117
|
+
const parsed = new URL(endpoint);
|
|
118
|
+
host = parsed.hostname;
|
|
119
|
+
port = Number(parsed.port) || (parsed.protocol === "https:" ? 443 : 80);
|
|
120
|
+
} catch {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
const socket = net.connect({ host, port });
|
|
124
|
+
const settle = (ok) => {
|
|
125
|
+
socket.destroy();
|
|
126
|
+
forwarderProbes.set(endpoint, { ok, at: Date.now() });
|
|
127
|
+
};
|
|
128
|
+
socket.setTimeout(2000, () => settle(false));
|
|
129
|
+
socket.once("connect", () => settle(true));
|
|
130
|
+
socket.once("error", () => settle(false));
|
|
35
131
|
}
|
|
36
132
|
|
|
37
133
|
/** Resolve the TLS-egress forwarder for a request target (NO_PROXY aware). */
|
|
@@ -47,11 +143,18 @@ function forwarderFor(url) {
|
|
|
47
143
|
const endpoint = env.DSH_EGRESS_FORWARDER;
|
|
48
144
|
if (endpoint === undefined || endpoint === "") return undefined;
|
|
49
145
|
if (inNoProxy(target, env.NO_PROXY || env.no_proxy)) return undefined;
|
|
146
|
+
// The sidecar is an OPTIONAL accelerator. A configured-yet-dead endpoint
|
|
147
|
+
// would otherwise make every request wait ~20s before failing, which is
|
|
148
|
+
// strictly worse than the proxy path. Only take the forwarder when a
|
|
149
|
+
// background probe has actually seen the port accept a connection; an
|
|
150
|
+
// unknown or failed probe keeps us on the proxy (fail-open).
|
|
151
|
+
if (!forwarderUsable(endpoint)) return undefined;
|
|
50
152
|
const proxy = env.DSH_EGRESS_FORWARDER_PROXY
|
|
51
153
|
|| env.HTTPS_PROXY || env.https_proxy || env.HTTP_PROXY || env.http_proxy || "";
|
|
52
154
|
return { endpoint, proxy: proxy === "" ? undefined : proxy };
|
|
53
155
|
}
|
|
54
156
|
|
|
157
|
+
|
|
55
158
|
/** Resolve the proxy URL for a request target (NO_PROXY aware). */
|
|
56
159
|
function proxyFor(url) {
|
|
57
160
|
let target;
|
|
@@ -123,6 +226,12 @@ async function tunneledFetch(url, init, proxy, depth) {
|
|
|
123
226
|
await drain(response);
|
|
124
227
|
throw new TypeError(`fetch failed: redirect mode is set to error (${response.status})`);
|
|
125
228
|
}
|
|
229
|
+
if (init.redirect !== "manual" && depth >= MAX_REDIRECTS) {
|
|
230
|
+
// Returning the final 3xx made a redirect loop look like a normal
|
|
231
|
+
// (ok:false) response; callers only saw an opaque empty body.
|
|
232
|
+
await drain(response);
|
|
233
|
+
throw new TypeError(`fetch failed: too many redirects (max ${MAX_REDIRECTS})`);
|
|
234
|
+
}
|
|
126
235
|
if (init.redirect !== "manual" && depth < MAX_REDIRECTS) {
|
|
127
236
|
const next = new URL(location, target);
|
|
128
237
|
const dropBody = response.status === 303
|
|
@@ -131,7 +240,7 @@ async function tunneledFetch(url, init, proxy, depth) {
|
|
|
131
240
|
? { ...init, method: "GET", body: undefined, headers: withoutBodyHeaders(init.headers) }
|
|
132
241
|
: { ...init };
|
|
133
242
|
await drain(response);
|
|
134
|
-
return egressFetch(next.href, nextInit);
|
|
243
|
+
return egressFetch(next.href, nextInit, depth + 1);
|
|
135
244
|
}
|
|
136
245
|
}
|
|
137
246
|
}
|
|
@@ -295,13 +404,24 @@ function httpsViaConnect(target, proxyUrl, method, headers, body, signal) {
|
|
|
295
404
|
fail(new TypeError(`fetch failed: proxy CONNECT rejected with ${connectRes.statusCode}`));
|
|
296
405
|
return;
|
|
297
406
|
}
|
|
407
|
+
// normalizeHeaders() strips Host
|
|
408
|
+
// (see below). For a request tunnelled through CONNECT, Node's
|
|
409
|
+
// https.request() then synthesises a Host from options.host — which is
|
|
410
|
+
// absent here (we pass an already-connected `socket`), so the value is
|
|
411
|
+
// the bare hostname without the port, not the request-target authority.
|
|
412
|
+
// Cloudflare-fronted MCP endpoints (mcp.exa.ai, search.parallel.ai)
|
|
413
|
+
// reject that with HTTP 403 before any MCP handshake. httpViaProxy()
|
|
414
|
+
// already restores the header with the same expression; mirror it here
|
|
415
|
+
// so both proxy paths send an explicit, port-qualified Host. Node
|
|
416
|
+
// auto-synthesises a non-port-qualified Host under { socket }, which
|
|
417
|
+
// the upstream proxy rejects; target.host carries the authority form.
|
|
298
418
|
const request = https.request({
|
|
299
419
|
socket,
|
|
300
420
|
agent: false,
|
|
301
421
|
servername: target.hostname,
|
|
302
422
|
method,
|
|
303
423
|
path: pathWithQuery(target),
|
|
304
|
-
headers,
|
|
424
|
+
headers: { ...headers, host: headers.host ?? target.host },
|
|
305
425
|
});
|
|
306
426
|
open.push(request);
|
|
307
427
|
request.on("error", (error) => fail(new TypeError(`fetch failed: ${sanitize(error)}`, { cause: error })));
|
|
@@ -362,17 +482,42 @@ function httpViaProxy(target, proxyUrl, method, headers, body, signal) {
|
|
|
362
482
|
function collect(res) {
|
|
363
483
|
return new Promise((resolve, reject) => {
|
|
364
484
|
const chunks = [];
|
|
365
|
-
|
|
485
|
+
let bytes = 0;
|
|
486
|
+
let settled = false;
|
|
487
|
+
res.on("data", (chunk) => {
|
|
488
|
+
if (settled) return;
|
|
489
|
+
bytes += chunk.length;
|
|
490
|
+
if (bytes > MAX_RESPONSE_BYTES) {
|
|
491
|
+
settled = true;
|
|
492
|
+
res.destroy();
|
|
493
|
+
reject(new TypeError(`fetch failed: response body exceeds ${MAX_RESPONSE_BYTES} bytes`));
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
chunks.push(chunk);
|
|
497
|
+
});
|
|
366
498
|
res.on("end", () => {
|
|
499
|
+
if (settled) return;
|
|
500
|
+
settled = true;
|
|
367
501
|
// Null-body statuses (204/304) and empty streams must construct a
|
|
368
502
|
// bodiless Response; an empty Buffer is not null and would throw.
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
503
|
+
// Constructing a Response can throw (invalid status, illegal header
|
|
504
|
+
// name, 204 with a body). This runs inside an event callback, so an
|
|
505
|
+
// uncaught throw here would bypass reject() and crash the process.
|
|
506
|
+
try {
|
|
507
|
+
const payload = chunks.length === 0 ? null : Buffer.concat(chunks);
|
|
508
|
+
resolve(new Response(payload, {
|
|
509
|
+
status: res.statusCode ?? 502,
|
|
510
|
+
headers: headersFromRaw(res),
|
|
511
|
+
}));
|
|
512
|
+
} catch (err) {
|
|
513
|
+
reject(err);
|
|
514
|
+
}
|
|
515
|
+
});
|
|
516
|
+
res.on("error", (err) => {
|
|
517
|
+
if (settled) return;
|
|
518
|
+
settled = true;
|
|
519
|
+
reject(err);
|
|
374
520
|
});
|
|
375
|
-
res.on("error", reject);
|
|
376
521
|
});
|
|
377
522
|
}
|
|
378
523
|
|
|
@@ -401,6 +546,12 @@ function normalizeHeaders(raw) {
|
|
|
401
546
|
if (value !== undefined) headers[String(key).toLowerCase()] = String(value);
|
|
402
547
|
}
|
|
403
548
|
}
|
|
549
|
+
// Host is deliberately removed: a caller-supplied Host must not override
|
|
550
|
+
// the tunnel target. Each transport is therefore responsible for adding it
|
|
551
|
+
// back before the request is sent — httpViaProxy() and httpsViaConnect()
|
|
552
|
+
// both do so via `host: headers.host ?? target.host`. Do not delete those
|
|
553
|
+
// two restorations; doing so reintroduces the Cloudflare 403 described in
|
|
554
|
+
// the comment at httpsViaConnect().
|
|
404
555
|
delete headers["host"];
|
|
405
556
|
return headers;
|
|
406
557
|
}
|
|
@@ -1,12 +1,69 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
1
|
+
// failure-label.js — classify quota/rate-limit failures. Route on the stable
|
|
2
|
+
// `code` / `status` / `rateLimited` fields first (HarnessError JSDoc:
|
|
3
|
+
// "route on this, never by parsing message"). The message regex is a legacy
|
|
4
|
+
// fallback for errors built before webErrorFromResponse() landed.
|
|
5
|
+
|
|
6
|
+
import { RATE_LIMIT_CODE, QUOTA_CODE } from "./web-error.js";
|
|
7
|
+
|
|
8
|
+
/** True when the error indicates a keyless permission refusal (needs a key,
|
|
9
|
+
* not a retry). The Firecrawl hosted MCP returns this as an isError result. */
|
|
10
|
+
export function keylessRejected(err) {
|
|
11
|
+
if (err?.keylessRejected === true) return true;
|
|
12
|
+
const s = String(err?.message ?? err);
|
|
13
|
+
return /Anonymous keyless access is unavailable|keyless access is unavailable/i.test(s);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** True when the error is a rate limit or exhausted quota. */
|
|
17
|
+
export function rateLimited(err) {
|
|
18
|
+
if (err?.code === RATE_LIMIT_CODE || err?.code === QUOTA_CODE) return true;
|
|
19
|
+
if (err?.rateLimited === true || err?.quota === true) return true;
|
|
20
|
+
if (Number(err?.status) === 429) return true;
|
|
21
|
+
if (typeof err?.providerCode === "string"
|
|
22
|
+
&& /^(rate_limit_error|quota_exceeded|insufficient_quota)$/.test(err.providerCode)) return true;
|
|
23
|
+
// Legacy fallback for pre-helper errors. Bare "quota" and generic
|
|
24
|
+
// "anonymous" are deliberately excluded: they produced false positives on
|
|
25
|
+
// HTTP 200/402/503 bodies. Only Firecrawl's exact keyless MCP isError text
|
|
26
|
+
// is matched; it never passes through webErrorFromResponse().
|
|
27
|
+
const s = String(err?.message ?? err);
|
|
28
|
+
return /HTTP 429|429\b|rate.?limit/i.test(s)
|
|
29
|
+
|| /额度/i.test(s)
|
|
30
|
+
|| /Anonymous keyless access is unavailable/i.test(s);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Cap a server-supplied cooldown so a bogus or hostile Retry-After cannot
|
|
34
|
+
// disable a backend for years. Anything beyond a day is treated as unknown.
|
|
35
|
+
const MAX_RETRY_AFTER_MS = 24 * 60 * 60 * 1000;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Best-effort Retry-After extraction, in milliseconds. webErrorFromResponse()
|
|
39
|
+
* stores the raw header on err.retryAfter.
|
|
40
|
+
*
|
|
41
|
+
* Returns `undefined` when the response carried no usable header — including
|
|
42
|
+
* an unparsable value, a past http-date, or a value beyond the one-day cap.
|
|
43
|
+
* The breaker then falls back to the configured `breakerCooldownMs`, so
|
|
44
|
+
* `0 = count only` keeps working for header-less 429s instead of silently
|
|
45
|
+
* becoming 60 seconds.
|
|
46
|
+
*
|
|
47
|
+
* @returns {number|undefined} explicit cooldown in milliseconds, if any
|
|
48
|
+
*/
|
|
49
|
+
export function retryAfterMsFrom(err) {
|
|
50
|
+
const v = err?.retryAfter
|
|
51
|
+
?? err?.cause?.response?.headers?.get?.("retry-after")
|
|
52
|
+
?? err?.cause?.retryAfter;
|
|
53
|
+
if (v == null || String(v).trim() === "") return undefined;
|
|
54
|
+
const secs = Number(v);
|
|
55
|
+
if (Number.isFinite(secs)) {
|
|
56
|
+
if (secs < 0) return undefined;
|
|
57
|
+
const ms = secs * 1000;
|
|
58
|
+
return ms <= MAX_RETRY_AFTER_MS ? ms : undefined;
|
|
59
|
+
}
|
|
60
|
+
const date = Date.parse(v);
|
|
61
|
+
if (!Number.isFinite(date)) return undefined;
|
|
62
|
+
// An http-date in the past (clock skew, already-expired window) must not
|
|
63
|
+
// become a zero-length cooldown; treat it as unknown.
|
|
64
|
+
const ms = date - Date.now();
|
|
65
|
+
return ms > 0 && ms <= MAX_RETRY_AFTER_MS ? ms : undefined;
|
|
66
|
+
}
|
|
10
67
|
|
|
11
68
|
/**
|
|
12
69
|
* @param {string} id backend id (searxng gets a dedicated phrasing)
|
|
@@ -25,9 +82,13 @@ export function failureLabel(id, raw) {
|
|
|
25
82
|
// Proxy/forwarder-path failures get their own class: the route5 incident
|
|
26
83
|
// (harness EnvHttpProxyAgent hijacking the sidecar request) surfaced as a
|
|
27
84
|
// generic "fetch failed", pointing the reader at DNS/TLS when the actual
|
|
28
|
-
// fault was the proxy/egress hop.
|
|
29
|
-
|
|
30
|
-
|
|
85
|
+
// fault was the proxy/egress hop. Match explicit proxy markers first: a bare
|
|
86
|
+
// /CONNECT/i also matched "connect ECONNREFUSED", mislabelling ordinary
|
|
87
|
+
// network failures as proxy failures.
|
|
88
|
+
if (/proxy\s+(response|connect|tunnel)|HTTP Tunneling|CONNECT tunnel|forwarder|sidecar/i.test(m)) {
|
|
89
|
+
return "proxy/forwarder path failed";
|
|
90
|
+
}
|
|
91
|
+
if (/(fetch failed|connection refused|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|ETIMEDOUT|ECONNRESET|EPIPE|socket hang up|certificate|TLS)/i.test(m)) {
|
|
31
92
|
return "network unreachable (DNS/TCP/TLS)";
|
|
32
93
|
}
|
|
33
94
|
if (/HTTP 429|Too Many Requests|rate.?limit/i.test(m)) return "rate-limited (HTTP 429)";
|
package/lib/util/log.js
CHANGED
|
@@ -18,14 +18,16 @@
|
|
|
18
18
|
* search.
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
|
+
import { redact } from "./redact.js";
|
|
22
|
+
|
|
21
23
|
/** One-line summary safe for the host log. */
|
|
22
24
|
function summarize(request) {
|
|
23
25
|
try {
|
|
24
26
|
const body = request && request.body ? JSON.stringify(request.body) : "";
|
|
25
27
|
const trimmed = body.length > 200 ? body.slice(0, 200) + "..." : body;
|
|
26
|
-
return String((request && request.endpoint) || "") +
|
|
28
|
+
return redact(String((request && request.endpoint) || "") +
|
|
27
29
|
(request && request.toolName ? " tool=" + request.toolName : "") +
|
|
28
|
-
(trimmed ? " body=" + trimmed : "");
|
|
30
|
+
(trimmed ? " body=" + trimmed : ""));
|
|
29
31
|
} catch {
|
|
30
32
|
return String(request && request.endpoint);
|
|
31
33
|
}
|
|
@@ -56,7 +58,7 @@ export function recordBackendOutcome(ctx, backendId, outcome) {
|
|
|
56
58
|
const logger = ctx && ctx.logger;
|
|
57
59
|
if (!logger) return;
|
|
58
60
|
const status = outcome && typeof outcome.status === "string" ? outcome.status : "";
|
|
59
|
-
const line = "[websearch:" + backendId + "] outcome " + JSON.stringify(outcome ?? {}).slice(0, 500);
|
|
61
|
+
const line = redact("[websearch:" + backendId + "] outcome " + JSON.stringify(outcome ?? {}).slice(0, 500));
|
|
60
62
|
if (status === "error" && typeof logger.warn === "function") logger.warn(line);
|
|
61
63
|
else if (typeof logger.debug === "function") logger.debug(line);
|
|
62
64
|
} catch {
|