dsh-free-search 0.9.55 → 0.9.57

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 CHANGED
@@ -631,7 +631,7 @@ npx -y -p dsh-free-search dsh-free-search-mcp
631
631
 
632
632
  #### 离线自检断言(tools/)
633
633
 
634
- 仓库自带 **70 个**零依赖断言脚本(合计 **1032 项**),**不需要 API key、不联网、不需要测试框架**,Node ≥ 20 即可跑。一次跑全部:`npm test`。
634
+ 仓库自带 **71 个**零依赖断言脚本(合计 **1044 项**),**不需要 API key、不联网、不需要测试框架**,Node ≥ 20 即可跑。一次跑全部:`npm test`。
635
635
 
636
636
  | 脚本 | 覆盖 | 运行(项数) |
637
637
  |---|---|---|
@@ -703,6 +703,7 @@ npx -y -p dsh-free-search dsh-free-search-mcp
703
703
  | `assert-firecrawl-keyless.mjs` | Firecrawl keyless 出口判定:403 + VPN/proxy 文案才算拒绝、普通 403 与 401/429/500 不算、冷却初始未触发 | `node tools/assert-firecrawl-keyless.mjs`(5) |
704
704
  | `assert-fetch-charset.mjs` | 抓取编码(#88):`charset=gbk` / `gb2312` 按声明解码、无声明时嗅探 `<meta charset>` 与 http-equiv 形式、默认 UTF-8、未知 label 兜底 UTF-8 不抛错 | `node tools/assert-fetch-charset.mjs`(6) |
705
705
  | `assert-fetch-abort.mjs` | 抓取中断(#87):压缩响应中途断连必须 reject(不再永久 pending)、明文断连同样 reject、abort 能打断停滞的 gzip 流、complete 响应与重定向仍正常 | `node tools/assert-fetch-abort.mjs`(6) |
706
+ | `assert-fetch-proxy.mjs` | 抓取层代理:`http_proxy` / `https_proxy` / `all_proxy` / `no_proxy` 解析(大小写与小写优先、空值视为未设置)、`NO_PROXY` 的域名 / `host:port` / `*` 匹配、loopback 恒直连、`socks5://` 忽略、`CONNECT` 隧道握手与 `Proxy-Authorization`、代理拒绝与提前断连不挂起、有 agent 时重定向每一跳仍过 SSRF 校验、浏览器 tier 的 `--proxy-server` | `node tools/assert-fetch-proxy.mjs`(12) |
706
707
  | `assert-bridge-access.mjs` | 桥接 Host 围栏(#84):loopback 放行、remote peer 打 loopback Host 拒绝、`--trusted-host`(无端口匹配任意端口 / 带端口精确匹配)、`--public-url`、绑定地址、跨站与异源拒绝、connection 鉴权委托与 fail-closed、设置客户端按 `document.baseURI` 解析子路径 | `node tools/assert-bridge-access.mjs`(14) |
707
708
  | `assert-provider-takeover.mjs` | provider 接管:旧属性 API 与 rc.2 的 `config.*` ref 两套兼容、`settings.mutate(web)` 单批写入、显式指定的 provider 不被抢占、`fetchProviderTakeover: false` 时保留显式 `http`、describe 噪声不误报、嵌套 config 变化与 web 重建分别成行、关闭 DSH 搜索开关后重新接管(`deepseek-search-api` / `deepseek-official` 均视为官方默认)、打开 DeepSeek 开关(`deepseek-fetch-api`)时让路、apply 重入/重复注册不再中断、重复日志去重 | `node tools/assert-provider-takeover.mjs`(20) |
708
709
 
@@ -712,15 +713,27 @@ npx -y -p dsh-free-search dsh-free-search-mcp
712
713
 
713
714
  ### 代理说明(国内用户)
714
715
 
715
- DuckDuckGo 等引擎可能需要代理才能访问,而 Node.js 的 `fetch` 默认不走系统代理。需要给 dsh 进程设置(Node 24+):
716
+ 本插件有两条独立的出网路径,代理对两条都要配:
717
+
718
+ 1. **搜索**(`web_search` / `multi_search` / `advanced_search` / `platform_search` / `video_search` 等)走 `globalThis.fetch`(undici),是否代理由 undici 的全局 dispatcher 决定。
719
+ 2. **抓取正文**(`web_fetch` 与 `research` 的 T1 直连、T1.5 无头浏览器,以及 exa / firecrawl / crawl4ai 的云端调用)历史上直接用 `node:https` 与子进程,**既不读代理环境变量,也不受 undici dispatcher 影响**。所以会出现「搜索能通、抓取一直超时」——设置里的代理插件对第二层无效。现在这一层自己读代理环境变量,并为每一跳建立 HTTP `CONNECT` 隧道(浏览器 tier 则传 `--proxy-server`)。
720
+
721
+ 配置方式(`http_proxy` / `https_proxy` / `all_proxy` / `no_proxy`,大小写均可,小写优先,空值视为未设置):
716
722
 
717
723
  ```sh
718
- export NODE_USE_ENV_PROXY=1
719
724
  export HTTPS_PROXY=http://127.0.0.1:7897 # 你的代理地址
720
725
  export HTTP_PROXY=http://127.0.0.1:7897
726
+ export NO_PROXY=localhost,127.0.0.1,::1 # 可选
721
727
  ```
722
728
 
723
- Windows 用户:桌面快捷方式已内置此配置(`set NODE_USE_ENV_PROXY=1&& set HTTPS_PROXY=...`)。
729
+ - 只支持 `http://` / `https://` 代理(可带 Basic 认证);`socks5://` 会被忽略并直连。
730
+ - loopback 地址(`localhost`、`127.0.0.1`、`::1`、`127.0.0.0/8`)恒直连。
731
+ - `NO_PROXY` 支持逗号分隔的域名、`host:port` 与 `*`。
732
+ - 走代理时域名由代理端解析,`lookup` 钩子失效;因此重定向的每一跳都会先显式过一遍 SSRF 校验,`allowFakeIpCidrs` 等设置继续生效。
733
+ - 代理不可达时按原有逻辑降级到云端 tier,错误信息里会带 `proxy <host> refused CONNECT ...` 之类的具体原因。
734
+ - 不依赖 Node 24 的 `NODE_USE_ENV_PROXY`,Node ≥ 20 即可;该变量只影响 undici 那条路径。
735
+
736
+ Windows 用户:桌面快捷方式已内置 `NODE_USE_ENV_PROXY=1` + `HTTPS_PROXY`(`set NODE_USE_ENV_PROXY=1&& set HTTPS_PROXY=...`)。
724
737
 
725
738
  ### 工作原理
726
739
 
@@ -1355,7 +1368,7 @@ Restart `dsh web` after switching to apply changes.
1355
1368
 
1356
1369
  #### Offline self-check assertions (`tools/`)
1357
1370
 
1358
- **Seventy** zero-dependency assertion scripts ship with the repo (**1032 assertions** total): **no API keys, no network, no test framework**, Node ≥ 20. Run everything with `npm test`.
1371
+ **Seventy-one** zero-dependency assertion scripts ship with the repo (**1044 assertions** total): **no API keys, no network, no test framework**, Node ≥ 20. Run everything with `npm test`.
1359
1372
 
1360
1373
  | Script | Covers | Run (count) |
1361
1374
  |---|---|---|
@@ -1425,6 +1438,7 @@ Restart `dsh web` after switching to apply changes.
1425
1438
  | `assert-firecrawl-keyless.mjs` | Firecrawl keyless egress refusal: only a 403 with the VPN/proxy wording counts, plain 403 and 401/429/500 do not, and the cooldown starts inactive | `node tools/assert-firecrawl-keyless.mjs` (5) |
1426
1439
  | `assert-fetch-charset.mjs` | fetch encoding (#88): `charset=gbk` / `gb2312` decoded as declared, `<meta charset>` and the http-equiv form sniffed when the header omits it, UTF-8 by default, and an unknown label falls back to UTF-8 instead of throwing | `node tools/assert-fetch-charset.mjs` (6) |
1427
1440
  | `assert-fetch-abort.mjs` | fetch interruption (#87): a compressed response cut mid-body rejects instead of hanging forever, identity truncation rejects too, abort breaks a stalled gzip stream, and complete responses plus redirects still work | `node tools/assert-fetch-abort.mjs` (6) |
1441
+ | `assert-fetch-proxy.mjs` | proxy support for the fetch tiers: `http_proxy` / `https_proxy` / `all_proxy` / `no_proxy` parsing (either case, lowercase wins, empty means unset), `NO_PROXY` domain / `host:port` / `*` matching, loopback always direct, `socks5://` ignored, the `CONNECT` tunnel handshake and `Proxy-Authorization`, a refusing proxy and an early disconnect never hanging, the SSRF guard still applied to every redirect hop when an agent is in use, and `--proxy-server` for the browser tier | `node tools/assert-fetch-proxy.mjs` (12) |
1428
1442
  | `assert-bridge-access.mjs` | bridge Host fence (#84): loopback allowed, a remote peer behind a loopback Host refused, `--trusted-host` (port-less matches any port, explicit port matches exactly), `--public-url`, the bind address, cross-site and foreign-Origin refused, connection-auth delegation, fail-closed behavior, and settings-client subpath resolution via `document.baseURI` | `node tools/assert-bridge-access.mjs` (14) |
1429
1443
  | `assert-provider-takeover.mjs` | provider takeover: both the legacy property API and the rc.2 `config.*` refs, a single batched `settings.mutate(web)`, explicit foreign providers left untouched, an explicit `http` kept when `fetchProviderTakeover` is off, describe()-triggered events ignored when nothing changed, nested config changes and web rebuilds reported separately, re-takeover after DSH's search switch is turned off (both `deepseek-search-api` and `deepseek-official` count as the factory default), stepping aside for the explicit `deepseek-fetch-api` switch, apply re-entry / duplicate registrations tolerated, and repeated logs deduplicated | `node tools/assert-provider-takeover.mjs` (20) |
1430
1444
 
@@ -1434,15 +1448,27 @@ Any failure exits non-zero with the failing items listed. Passing the path of an
1434
1448
 
1435
1449
  ### Proxy Note (for Users in Mainland China)
1436
1450
 
1437
- Engines like DuckDuckGo may require a proxy. Since Node.js `fetch` does not use the system proxy by default, set the following environment variables for the dsh process (Node 24+):
1451
+ This plugin has two independent outbound paths, and both need the proxy configured:
1452
+
1453
+ 1. **Search** (`web_search` / `multi_search` / `advanced_search` / `platform_search` / `video_search`, …) goes through `globalThis.fetch` (undici), so whether it is proxied depends on undici's global dispatcher.
1454
+ 2. **Body fetching** (`web_fetch`, plus the T1 direct fetch and T1.5 headless-browser tiers of `research`, and the exa / firecrawl / crawl4ai cloud calls) used plain `node:https` and child processes. That layer **never read the proxy environment variables and never saw the undici dispatcher**, which is why search works while fetching keeps timing out — a proxy plugin installed for undici cannot reach it. It now reads the proxy environment itself and opens an HTTP `CONNECT` tunnel per hop (the browser tier gets `--proxy-server` instead).
1455
+
1456
+ Configure (`http_proxy` / `https_proxy` / `all_proxy` / `no_proxy`, either case, lowercase wins, empty means unset):
1438
1457
 
1439
1458
  ```sh
1440
- export NODE_USE_ENV_PROXY=1
1441
1459
  export HTTPS_PROXY=http://127.0.0.1:7897 # Your proxy address
1442
1460
  export HTTP_PROXY=http://127.0.0.1:7897
1461
+ export NO_PROXY=localhost,127.0.0.1,::1 # Optional
1443
1462
  ```
1444
1463
 
1445
- Windows users: The desktop shortcut already includes this configuration (`set NODE_USE_ENV_PROXY=1&& set HTTPS_PROXY=...`).
1464
+ - Only `http://` / `https://` proxies are supported (Basic auth allowed); `socks5://` is ignored and the request goes direct.
1465
+ - Loopback addresses (`localhost`, `127.0.0.1`, `::1`, `127.0.0.0/8`) always go direct.
1466
+ - `NO_PROXY` accepts comma-separated domains, `host:port`, and `*`.
1467
+ - When proxied, the proxy resolves the hostname so the `lookup` hook no longer applies; every redirect hop is therefore re-checked by the SSRF guard explicitly, and settings such as `allowFakeIpCidrs` keep working.
1468
+ - If the proxy is unreachable the usual degradation to the cloud tiers still happens, and the error message names the reason (`proxy <host> refused CONNECT ...`).
1469
+ - This does not depend on Node 24's `NODE_USE_ENV_PROXY`; Node ≥ 20 is enough. That variable only affects the undici path.
1470
+
1471
+ Windows users: The desktop shortcut already includes `NODE_USE_ENV_PROXY=1` + `HTTPS_PROXY` (`set NODE_USE_ENV_PROXY=1&& set HTTPS_PROXY=...`).
1446
1472
 
1447
1473
  ### How It Works
1448
1474
 
package/lib/client.js CHANGED
@@ -769,7 +769,7 @@ window.__ModuleLoader__.load({
769
769
  "cache_search",
770
770
  "domain_search",
771
771
  ];
772
- const PLUGIN_VERSION = "0.9.55";
772
+ const PLUGIN_VERSION = "0.9.57";
773
773
  const PLUGIN_REPO_URL = "https://github.com/DDDMUC/dsh-free-search";
774
774
  // 右侧浮动目录(#85):条目顺序即页面顺序,anchor 是页面里对应 field 的 id。
775
775
  const NAV_ITEMS = [
@@ -14,6 +14,7 @@ import { join } from "node:path";
14
14
  import { callExa, callFirecrawl, callCrawl4ai } from "./fetch_upstream.js";
15
15
  import { stripLoneSurrogates } from "./safe_text.js";
16
16
  import { assertPublicUrl, makeSafeLookup } from "./ssrf.js";
17
+ import { agentForUrl, proxyForTarget, readProxyEnv } from "./proxy.js";
17
18
 
18
19
  const T1_MIN_CHARS = 300;
19
20
  const TEXTUAL = /text\/|json|xml|javascript|application\/json/i;
@@ -52,7 +53,7 @@ function findSystemBrowser() {
52
53
  return cachedBrowserPath;
53
54
  }
54
55
 
55
- function browserDumpDom(browserPath, url, { timeoutMs = 25000, signal } = {}) {
56
+ function browserDumpDom(browserPath, url, { timeoutMs = 25000, signal, proxy = "" } = {}) {
56
57
  return new Promise((resolve) => {
57
58
  // 独立 user-data-dir:避免与用户正在运行的浏览器实例抢同一 profile(共享 profile 时无输出/立即退出)
58
59
  let tmpDir;
@@ -71,6 +72,8 @@ function browserDumpDom(browserPath, url, { timeoutMs = 25000, signal } = {}) {
71
72
  "--disable-component-update",
72
73
  "--disable-sync",
73
74
  `--user-data-dir=${tmpDir}`,
75
+ // 直连拿不到的站往往也正需要代理:把同一个代理交给浏览器,否则这一层照样白跑。
76
+ ...(proxy ? [`--proxy-server=${proxy}`] : []),
74
77
  "--dump-dom",
75
78
  "--virtual-time-budget=10000",
76
79
  url,
@@ -160,7 +163,7 @@ function decodeBody(buffer, contentType) {
160
163
  }
161
164
 
162
165
  /** GET 跟随重定向(≤5 跳),返回最终 URL / 状态 / 正文 / 内容类型;支持 gzip/br/deflate 解压。 */
163
- export function httpsGetFollow(url, { headers = {}, timeoutMs = 20000, signal, lookup } = {}, transport = https) {
166
+ export function httpsGetFollow(url, { headers = {}, timeoutMs = 20000, signal, lookup, agent = null } = {}, transport = https) {
164
167
  return new Promise((resolve, reject) => {
165
168
  let settled = false;
166
169
  let activeReq = null;
@@ -199,7 +202,7 @@ export function httpsGetFollow(url, { headers = {}, timeoutMs = 20000, signal, l
199
202
  signal.addEventListener("abort", onAbort, { once: true });
200
203
  }
201
204
 
202
- const hop = (current, left) => {
205
+ const hop = async (current, left) => {
203
206
  if (settled) return;
204
207
  let target;
205
208
  try {
@@ -208,6 +211,17 @@ export function httpsGetFollow(url, { headers = {}, timeoutMs = 20000, signal, l
208
211
  settle(false, error);
209
212
  return;
210
213
  }
214
+ // 走代理时主机名由代理解析,transport 的 lookup 钩子不再生效;重定向的每一跳
215
+ // 因此在这里显式过一遍 SSRF 校验,避免代理成为绕过守卫的通道。
216
+ if (agent && lookup) {
217
+ try {
218
+ await new Promise((resolve, reject) => lookup(target.hostname, { all: true }, (error) => (error ? reject(error) : resolve(undefined))));
219
+ } catch (error) {
220
+ settle(false, error);
221
+ return;
222
+ }
223
+ if (settled) return;
224
+ }
211
225
  const req = transport.request(
212
226
  {
213
227
  hostname: target.hostname,
@@ -216,13 +230,14 @@ export function httpsGetFollow(url, { headers = {}, timeoutMs = 20000, signal, l
216
230
  method: "GET",
217
231
  headers,
218
232
  timeout: timeoutMs,
219
- ...(lookup ? { lookup } : {}),
233
+ ...(lookup && !agent ? { lookup } : {}),
234
+ ...(agent ? { agent } : {}),
220
235
  },
221
236
  (res) => {
222
237
  activeRes = res;
223
238
  if ([301, 302, 303, 307, 308].includes(res.statusCode) && res.headers.location && left > 0) {
224
239
  res.resume();
225
- return hop(new URL(res.headers.location, current).toString(), left - 1);
240
+ return void hop(new URL(res.headers.location, current).toString(), left - 1).catch((error) => settle(false, error));
226
241
  }
227
242
 
228
243
  const enc = String(res.headers["content-encoding"] || "").toLowerCase();
@@ -277,7 +292,7 @@ export function httpsGetFollow(url, { headers = {}, timeoutMs = 20000, signal, l
277
292
  };
278
293
 
279
294
  try {
280
- hop(url, 5);
295
+ void hop(url, 5).catch((error) => settle(false, error));
281
296
  } catch (error) {
282
297
  settle(false, error);
283
298
  }
@@ -339,6 +354,8 @@ export function createFetchProvider({
339
354
  allowedCidrs = () => [],
340
355
  validateUrl = assertPublicUrl,
341
356
  }) {
357
+ // 每个 provider 实例按 proxy URL 复用同一条隧道 agent。
358
+ const proxyAgents = new Map();
342
359
  return {
343
360
  id: "fs-quality-fetch",
344
361
  /** 廉价本地可用性检查(seam 契约要求,禁止网络调用)。 */
@@ -355,7 +372,13 @@ export function createFetchProvider({
355
372
 
356
373
  // T1:直连(文本类内容;二进制交给后层——exa 取正文,PDF 等仍由 firecrawl 处理)
357
374
  try {
358
- const r = await httpsGetFollow(url, { headers: browserishHeaders(acceptLanguage()), signal, lookup: makeSafeLookup(allowed) });
375
+ // 沿用宿主/环境里的代理配置:T1 用 node:https,看不到 undici 的全局 dispatcher。
376
+ const r = await httpsGetFollow(url, {
377
+ headers: browserishHeaders(acceptLanguage()),
378
+ signal,
379
+ lookup: makeSafeLookup(allowed),
380
+ agent: agentForUrl(url, { settings: readProxyEnv(), cache: proxyAgents }),
381
+ });
359
382
  if (r.status < 400 && TEXTUAL.test(r.contentType) && r.text.length >= T1_MIN_CHARS) {
360
383
  return { url: r.url, statusCode: r.status, body: { kind: "html", content: stripLoneSurrogates(r.text) }, truncated: false };
361
384
  }
@@ -367,7 +390,10 @@ export function createFetchProvider({
367
390
  const browserPath = findSystemBrowser();
368
391
  if (browserEnabled() && browserPath) {
369
392
  try {
370
- const html = await browserDumpDom(browserPath, url, { signal });
393
+ const html = await browserDumpDom(browserPath, url, {
394
+ signal,
395
+ proxy: proxyForTarget(url, readProxyEnv()).replace(/\/$/, ""),
396
+ });
371
397
  if (html && html.length >= T1_MIN_CHARS && !/403 Forbidden|\bcaptcha\b/i.test(html.slice(0, 3000))) {
372
398
  return { url, statusCode: 200, body: { kind: "html", content: stripLoneSurrogates(html) }, truncated: false };
373
399
  }
@@ -3,6 +3,7 @@
3
3
  // 注意:不用全局 fetch(undici) 访问 api.crawl4ai.com——其 Pingora 网关会空 401 拦截 undici 特征。
4
4
 
5
5
  import https from "node:https";
6
+ import { agentForUrl } from "./proxy.js";
6
7
 
7
8
  // ---------- 受控替身注入点(测试基建;默认全 null = 生产直连真实服务,行为不变) ----------
8
9
  export const CONTROLLED_STUBS = { exa: null, firecrawl: null, crawl4ai: null };
@@ -30,8 +31,10 @@ export function htmlToText(html) {
30
31
  export function httpsJson(method, url, { headers = {}, body, timeoutMs = 30000, signal } = {}) {
31
32
  return new Promise((resolve, reject) => {
32
33
  const u = new URL(url);
34
+ // 云端服务同样可能只能经代理到达(企业出网/受限网络):沿用环境里的代理配置。
35
+ const agent = agentForUrl(url);
33
36
  const req = https.request(
34
- { hostname: u.hostname, port: u.port || 443, path: u.pathname + u.search, method, headers, timeout: timeoutMs },
37
+ { hostname: u.hostname, port: u.port || 443, path: u.pathname + u.search, method, headers, timeout: timeoutMs, ...(agent ? { agent } : {}) },
35
38
  (res) => {
36
39
  const chunks = [];
37
40
  res.on("data", (c) => chunks.push(c));
package/lib/index.js CHANGED
@@ -3028,6 +3028,16 @@ function apply(ctx, config) {
3028
3028
  });
3029
3029
 
3030
3030
  ctx.inject(["webServer", "settings"], (sctx) => {
3031
+ // DSH >= #8266 calls connection.authentication inside admit(); the bridge
3032
+ // handler must run in a context that injected that service, while older
3033
+ // DSH (no authentication service) keeps using the webServer/settings context.
3034
+ let connectionContext = sctx;
3035
+ ctx.inject(["connection.authentication"], (actx) => {
3036
+ connectionContext = actx;
3037
+ actx.effect(() => () => {
3038
+ if (connectionContext === actx) connectionContext = sctx;
3039
+ }, "free-search: bridge auth context");
3040
+ });
3031
3041
  sctx.effect(() => {
3032
3042
  const disposers = makeBridgeRoutes(
3033
3043
  sctx.settings,
@@ -3043,7 +3053,7 @@ function apply(ctx, config) {
3043
3053
  doctorReport,
3044
3054
  () => {
3045
3055
  try {
3046
- return sctx.get("connection");
3056
+ return connectionContext.get("connection");
3047
3057
  } catch {
3048
3058
  return undefined;
3049
3059
  }
package/lib/proxy.js ADDED
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Proxy support for the local fetch layers.
3
+ *
4
+ * `fetch_provider.js` (T1 direct) and `fetch_upstream.js` (T2-T4) talk to the
5
+ * network with plain `node:https`, deliberately: the crawl4ai gateway rejects
6
+ * undici's fingerprint with an empty 401. That also means they never see the
7
+ * undici global dispatcher, so a proxy installed by a DSH plugin that owns that
8
+ * dispatcher (e.g. @tr1v3r/dsh-proxy) cannot reach them.
9
+ *
10
+ * This module reads the conventional proxy environment variables and hands the
11
+ * transports a standard CONNECT tunnel agent, so those layers follow the same
12
+ * proxy configuration as everything else. No dependencies: node:http/https/tls
13
+ * only, and it degrades to "no proxy" when nothing is configured.
14
+ *
15
+ * Security note: when a request goes through a tunnel the proxy resolves the
16
+ * hostname, so the SSRF `lookup` hook is bypassed. `httpsGetFollow` therefore
17
+ * keeps validating every hop itself before the tunnel is opened.
18
+ */
19
+ import http from "node:http";
20
+ import https from "node:https";
21
+ import tls from "node:tls";
22
+
23
+ const HTTPS_KEYS = ["https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY"];
24
+ const HTTP_KEYS = ["http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"];
25
+ const NO_PROXY_KEYS = ["no_proxy", "NO_PROXY"];
26
+
27
+ function firstEnv(env, keys) {
28
+ for (const key of keys) {
29
+ const value = env?.[key];
30
+ if (typeof value === "string" && value.trim() !== "") return value.trim();
31
+ }
32
+ return "";
33
+ }
34
+
35
+ function bareHost(hostname) {
36
+ return String(hostname ?? "")
37
+ .toLowerCase()
38
+ .replace(/^\[/, "")
39
+ .replace(/\]$/, "")
40
+ .replace(/\.$/, "");
41
+ }
42
+
43
+ /**
44
+ * Read proxy settings from the environment (lowercase wins, uppercase falls
45
+ * back, empty string counts as unset).
46
+ */
47
+ export function readProxyEnv(env = process.env) {
48
+ return {
49
+ http: firstEnv(env, HTTP_KEYS),
50
+ https: firstEnv(env, HTTPS_KEYS),
51
+ noProxy: firstEnv(env, NO_PROXY_KEYS),
52
+ };
53
+ }
54
+
55
+ /**
56
+ * `no_proxy` matcher: comma separated rules, optional leading dot, optional
57
+ * port, `*` for everything. A rule matches the host itself and any subdomain.
58
+ */
59
+ export function matchesNoProxy(hostname, noProxy, port = "") {
60
+ const host = bareHost(hostname);
61
+ if (!host) return false;
62
+ for (const raw of String(noProxy ?? "").split(",")) {
63
+ let rule = raw.trim().toLowerCase();
64
+ if (!rule) continue;
65
+ if (rule === "*") return true;
66
+ const withPort = rule.match(/^(.*):(\d+)$/);
67
+ if (withPort && !withPort[1].endsWith("]")) {
68
+ rule = withPort[1];
69
+ if (port && String(port) !== withPort[2]) continue;
70
+ }
71
+ rule = rule.replace(/^\[/, "").replace(/\]$/, "").replace(/^\./, "");
72
+ if (!rule) continue;
73
+ if (host === rule || host.endsWith("." + rule)) return true;
74
+ }
75
+ return false;
76
+ }
77
+
78
+ function isLoopback(hostname) {
79
+ const host = bareHost(hostname);
80
+ if (host === "localhost" || host.endsWith(".localhost")) return true;
81
+ if (host === "::1" || host === "0.0.0.0") return true;
82
+ return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host);
83
+ }
84
+
85
+ /**
86
+ * Pick the proxy URL that applies to one target, or "" when the request must go
87
+ * direct (loopback always bypasses; SOCKS URLs are not supported here).
88
+ */
89
+ export function proxyForTarget(rawUrl, settings = readProxyEnv()) {
90
+ const target = new URL(String(rawUrl));
91
+ const hostname = bareHost(target.hostname);
92
+ const port = target.port || (target.protocol === "https:" ? "443" : "80");
93
+ if (isLoopback(hostname) || matchesNoProxy(hostname, settings.noProxy, port)) return "";
94
+ const candidate = target.protocol === "https:" ? settings.https : settings.http;
95
+ if (!candidate) return "";
96
+ let proxy;
97
+ try {
98
+ proxy = new URL(candidate.includes("://") ? candidate : "http://" + candidate);
99
+ } catch {
100
+ return "";
101
+ }
102
+ return proxy.protocol === "http:" || proxy.protocol === "https:" ? proxy.toString() : "";
103
+ }
104
+
105
+ /**
106
+ * `https.Agent` that opens every connection through a CONNECT tunnel on the
107
+ * given proxy. Sockets are not kept alive: a tunnel is bound to one target.
108
+ */
109
+ export class TunnelAgent extends https.Agent {
110
+ #proxy;
111
+
112
+ constructor(proxyUrl, options = {}) {
113
+ super({ keepAlive: false, maxSockets: 16, ...options });
114
+ this.#proxy = new URL(String(proxyUrl));
115
+ this.proxyUrl = this.#proxy.toString();
116
+ this.tunnelTimeoutMs = options.tunnelTimeoutMs ?? 15000;
117
+ }
118
+
119
+ createConnection(options, callback) {
120
+ const proxy = this.#proxy;
121
+ const host = options.host;
122
+ const port = options.port || 443;
123
+ const headers = { host: host + ":" + port };
124
+ if (proxy.username || proxy.password) {
125
+ const raw = decodeURIComponent(proxy.username) + ":" + decodeURIComponent(proxy.password);
126
+ headers["proxy-authorization"] = "Basic " + Buffer.from(raw).toString("base64");
127
+ }
128
+ const transport = proxy.protocol === "https:" ? https : http;
129
+ const connect = transport.request({
130
+ host: proxy.hostname,
131
+ port: proxy.port || (proxy.protocol === "https:" ? 443 : 80),
132
+ method: "CONNECT",
133
+ path: host + ":" + port,
134
+ headers,
135
+ agent: false,
136
+ setHost: false,
137
+ });
138
+ let settled = false;
139
+ // 失败时连同底层 socket 一起销毁:半开的隧道 socket 会一直占着代理连接。
140
+ let tunnelSocket = null;
141
+ const fail = (error) => {
142
+ if (settled) return;
143
+ settled = true;
144
+ clearTimeout(timer);
145
+ try { tunnelSocket?.destroy(); } catch { /* 忽略 */ }
146
+ try { connect.destroy(); } catch { /* 忽略 */ }
147
+ callback(error);
148
+ };
149
+ // 代理收下 CONNECT 却既不隧道也不关闭时,https.Agent 不会自己超时:必须显式兜底,
150
+ // 否则请求永远停在建连阶段(web_fetch 的工具级超时才把它收走)。
151
+ const timer = setTimeout(
152
+ () => fail(new Error("proxy " + proxy.host + " did not complete CONNECT " + host + ":" + port + " in " + this.tunnelTimeoutMs + "ms")),
153
+ this.tunnelTimeoutMs
154
+ );
155
+ timer.unref?.();
156
+ connect.once("error", (error) => fail(new Error("proxy " + proxy.host + ": " + error.message)));
157
+ connect.once("response", (res) => {
158
+ res.resume();
159
+ fail(new Error("proxy " + proxy.host + " refused CONNECT " + host + ":" + port + ": HTTP " + res.statusCode));
160
+ });
161
+ connect.once("connect", (res, socket) => {
162
+ tunnelSocket = socket;
163
+ if (res.statusCode !== 200) {
164
+ fail(new Error("proxy " + proxy.host + " refused CONNECT " + host + ":" + port + ": HTTP " + res.statusCode));
165
+ return;
166
+ }
167
+ // 隧道在 TLS 之前被对端关掉:tls.connect 可能只给出 close,这里直接兜住。
168
+ socket.once("close", () => fail(new Error("proxy " + proxy.host + " closed the tunnel to " + host + ":" + port + " before TLS completed")));
169
+ socket.once("error", (error) => fail(error));
170
+ const secure = tls.connect({
171
+ socket,
172
+ servername: options.servername || options.host,
173
+ ALPNProtocols: options.ALPNProtocols,
174
+ rejectUnauthorized: options.rejectUnauthorized !== false,
175
+ });
176
+ secure.once("secureConnect", () => {
177
+ if (settled) return;
178
+ settled = true;
179
+ clearTimeout(timer);
180
+ callback(null, secure);
181
+ });
182
+ secure.once("error", (error) => fail(error));
183
+ // 隧道在握手完成前被对端关掉时只有 close,没有 error。
184
+ secure.once("close", () => fail(new Error("proxy " + proxy.host + " closed the tunnel to " + host + ":" + port + " before TLS completed")));
185
+ });
186
+ connect.end();
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Build the agent a layer should use for one request, or `null` to go direct.
192
+ * `cache` keys agents by proxy URL so repeated fetches reuse the same instance.
193
+ */
194
+ export function agentForUrl(rawUrl, { settings = readProxyEnv(), cache = new Map() } = {}) {
195
+ const proxyUrl = proxyForTarget(rawUrl, settings);
196
+ if (!proxyUrl) return null;
197
+ const existing = cache.get(proxyUrl);
198
+ if (existing) return existing;
199
+ const agent = new TunnelAgent(proxyUrl);
200
+ cache.set(proxyUrl, agent);
201
+ return agent;
202
+ }
203
+
204
+ /** Human readable one-liner for logs/tests. */
205
+ export function describeProxyEnv(env = process.env) {
206
+ const settings = readProxyEnv(env);
207
+ const parts = [];
208
+ if (settings.https) parts.push("https=" + settings.https);
209
+ if (settings.http && settings.http !== settings.https) parts.push("http=" + settings.http);
210
+ if (settings.noProxy) parts.push("no_proxy=" + settings.noProxy);
211
+ return parts.length ? parts.join(" ") : "direct";
212
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-free-search",
3
- "version": "0.9.55",
3
+ "version": "0.9.57",
4
4
  "description": "Free web search for DeepSeek Harness: 42 engines (Bing/DuckDuckGo/AnySearch/SearXNG/Exa/Tavily/Keenable/Firecrawl/Parallel/Brave/Zhipu/You.com keyless; Zhihu global/site via MCP and Perplexity/SerpBase/DeepSeek (official + native tools/search)/Baidu/Kimi/Aliyun/Doubao/Google CSE/Metaso/Yandex/Yuanbao/SpecStream with key; OpenAI/Gemini/Claude model built-in search, explicit-only) + auto smart routing + global engine enable/disable & fallback priority + editable zh/en language pools + multi mode (parallel full language-pool merge) + multi_search cross-source tool + failure-aware fallback (quota/auth cooldown, transient retry, fallbackOn) + time filtering + platform search + domain blocklist (blockedDomains) + web_fetch, with web settings UI, plus a standalone stdio MCP server.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",