dsh-union-search 0.11.4 → 0.11.5

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/index.js CHANGED
@@ -5,6 +5,9 @@ import fs from "node:fs";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
7
  import dnsPromises from "node:dns";
8
+ import https from "node:https";
9
+ import http from "node:http";
10
+ import zlib from "node:zlib";
8
11
  import { exec } from "node:child_process";
9
12
  import { mcpCall, mcpContentText } from "./mcp_adapter.js";
10
13
  import TurndownService from "turndown";
@@ -475,31 +478,105 @@ function uniqueSources(sources, limit) {
475
478
  return out;
476
479
  }
477
480
 
481
+ // ALPN 抓取通道(0.11.5,上游 #162 / ec6c1bd 教训):部分站点/中间盒会 RST 不带 ALPN 扩展的
482
+ // TLS 握手,undici fetch 无法声明 ALPNProtocols,只能表现为 "socket hang up";浏览器能开这些站。
483
+ // 这里用 node:https + ALPN ["http/1.1"] 自建 fetch-like 基元:不跟重定向(advanceFetch 自带
484
+ // 逐跳 SSRF 复检环);解压 gzip/deflate/br;字符解码复用 decodeResponseBody(GBK 老站矩阵)。
485
+ const alpnHttpsAgent = new https.Agent({ ALPNProtocols: ["http/1.1"], keepAlive: true });
486
+ const alpnHttpAgent = new http.Agent({ keepAlive: true });
487
+
488
+ function httpsLikeFetch(target, { headers = {}, signal, timeoutMs = 12000 } = {}) {
489
+ return new Promise((resolve, reject) => {
490
+ const urlObj = target instanceof URL ? target : new URL(String(target));
491
+ const transport = urlObj.protocol === "http:" ? http : https;
492
+ const agent = urlObj.protocol === "http:" ? alpnHttpAgent : alpnHttpsAgent;
493
+ const onAbort = () => req.destroy(new Error("aborted"));
494
+ const req = transport.request(urlObj, {
495
+ method: "GET",
496
+ agent,
497
+ headers: { "accept-encoding": "gzip, deflate, br", ...headers },
498
+ timeout: timeoutMs,
499
+ }, (res) => {
500
+ const chunks = [];
501
+ res.on("data", (c) => chunks.push(c));
502
+ res.on("end", () => {
503
+ signal?.removeEventListener("abort", onAbort);
504
+ let body = Buffer.concat(chunks);
505
+ const enc = String(res.headers["content-encoding"] ?? "").toLowerCase();
506
+ try {
507
+ if (enc.includes("gzip")) body = zlib.gunzipSync(body);
508
+ else if (enc.includes("br")) body = zlib.brotliDecompressSync(body);
509
+ else if (enc.includes("deflate")) {
510
+ try { body = zlib.inflateSync(body); } catch { body = zlib.inflateRawSync(body); }
511
+ }
512
+ } catch { /* 解压失败保留原字节,交给解码层兜底(与旧行为一致) */ }
513
+ const headersMap = new Map();
514
+ for (const [k, v] of Object.entries(res.headers)) headersMap.set(k, Array.isArray(v) ? v.join(", ") : String(v));
515
+ const status = res.statusCode ?? 0;
516
+ resolve({
517
+ status,
518
+ ok: status >= 200 && status < 300,
519
+ headers: { get: (k) => headersMap.get(String(k).toLowerCase()) ?? null },
520
+ arrayBuffer: async () => body,
521
+ url: res.responseUrl ?? urlObj.toString(),
522
+ });
523
+ });
524
+ res.on("aborted", () => reject(new Error("socket hang up (response aborted)")));
525
+ });
526
+ req.setTimeout(timeoutMs, () => req.destroy(new Error(`timed out after ${timeoutMs}ms`)));
527
+ signal?.addEventListener("abort", onAbort, { once: true });
528
+ req.on("error", (error) => {
529
+ signal?.removeEventListener("abort", onAbort);
530
+ reject(error);
531
+ });
532
+ req.end();
533
+ });
534
+ }
535
+
536
+ // 跟随机重定向(≤5 跳,浏览器语义 GET 延续)+ 文本解码;fetchHtml / fetchVideoHtml 共用。
537
+ async function httpsFetchText(url, { headers = {}, signal, timeoutMs = 12000 } = {}) {
538
+ let current = url instanceof URL ? url : new URL(String(url));
539
+ let res;
540
+ for (let hops = 0; ; hops++) {
541
+ res = await httpsLikeFetch(current, { headers, signal, timeoutMs });
542
+ if (![301, 302, 303, 307, 308].includes(res.status)) break;
543
+ const location = res.headers.get("location");
544
+ if (!location) break;
545
+ if (hops >= 5) throw new Error("too many redirects (max 5 hops)");
546
+ current = new URL(location, current);
547
+ }
548
+ const text = decodeResponseBody(await res.arrayBuffer(), res.headers.get("content-type"));
549
+ return { status: res.status, ok: res.ok, text };
550
+ }
551
+
478
552
  async function fetchHtml(url, signal, acceptLang) {
479
- // 单次请求超时 12s,避免挂起被当成 Connection error
480
- let response;
553
+ // 单次请求超时 12s,避免挂起被当成 Connection error(0.11.5 起走 ALPN https 基元)
554
+ let result;
481
555
  try {
482
- const controller = new AbortController();
483
- const timer = setTimeout(() => controller.abort(), 12000);
484
- const onAbort = () => controller.abort();
556
+ const ctrl = new AbortController();
557
+ const timer = setTimeout(() => ctrl.abort(), 12000);
558
+ const onAbort = () => ctrl.abort();
485
559
  signal?.addEventListener("abort", onAbort);
486
- response = await fetch(url, {
487
- headers: { "user-agent": USER_AGENT, "accept-language": acceptLang ?? ACCEPT_LANG },
488
- signal: controller.signal,
489
- redirect: "follow",
490
- });
491
- clearTimeout(timer);
492
- signal?.removeEventListener("abort", onAbort);
560
+ try {
561
+ result = await httpsFetchText(url, {
562
+ headers: { "user-agent": USER_AGENT, "accept-language": acceptLang ?? ACCEPT_LANG },
563
+ signal: ctrl.signal,
564
+ timeoutMs: 14000,
565
+ });
566
+ } finally {
567
+ clearTimeout(timer);
568
+ signal?.removeEventListener("abort", onAbort);
569
+ }
493
570
  } catch (error) {
494
571
  if (signal?.aborted) throw error;
495
572
  throw new Error(`connection error: ${error?.message ?? String(error)}`);
496
573
  }
497
- if (!response.ok) {
498
- throw new Error(`HTTP ${response.status} from ${url.split("?")[0]}`);
574
+ const { status, ok, text: html } = result;
575
+ if (!ok) {
576
+ throw new Error(`HTTP ${status} from ${url.split("?")[0]}`);
499
577
  }
500
- const html = await response.text();
501
578
  // DuckDuckGo 反爬验证页检测(HTTP 202 或验证关键字)
502
- if (response.status === 202 || /anomaly|captcha|unusual traffic|robot check/i.test(html.slice(0, 4000))) {
579
+ if (status === 202 || /anomaly|captcha|unusual traffic|robot check/i.test(html.slice(0, 4000))) {
503
580
  throw new Error("DuckDuckGo is rate-limited right now (anti-bot challenge, usually temporary) - Bing works");
504
581
  }
505
582
  return html;
@@ -1428,7 +1505,8 @@ async function advanceFetch(url, { selector, fields, mode, maxChars, allowPrivat
1428
1505
  const onAbort = () => ctrl.abort();
1429
1506
  signal?.addEventListener("abort", onAbort);
1430
1507
  try {
1431
- response = await fetch(current, {
1508
+ // 0.11.5:ALPN https 基元,不自动跟重定向——下面的逐跳 SSRF 复检环保留原语义
1509
+ response = await httpsLikeFetch(current, {
1432
1510
  headers: {
1433
1511
  "user-agent": userAgent || USER_AGENT,
1434
1512
  "accept-language": ACCEPT_LANG,
@@ -1436,8 +1514,8 @@ async function advanceFetch(url, { selector, fields, mode, maxChars, allowPrivat
1436
1514
  ...(referer ? { referer } : {}),
1437
1515
  ...(cookieHeader ? { cookie: cookieHeader } : {}),
1438
1516
  },
1439
- redirect: "manual",
1440
1517
  signal: ctrl.signal,
1518
+ timeoutMs: ADVANCE_FETCH_TIMEOUT_MS,
1441
1519
  });
1442
1520
  } catch (error) {
1443
1521
  if (signal?.aborted) throw error;
@@ -1865,31 +1943,35 @@ const YOUTUBE_SEARCH_URL = "https://www.youtube.com/results";
1865
1943
  const VIMEO_SEARCH_URL = "https://vimeo.com/search";
1866
1944
 
1867
1945
  // 通用 HTML 抓取(视频源用;跟随重定向,桌面 UA)。失败信息通用,不套 DDG 文案。
1946
+ // 0.11.5:走 ALPN https 基元(同 fetchHtml),重定向由 httpsFetchText 内部跟 ≤5 跳。
1868
1947
  async function fetchVideoHtml(url, signal, extraHeaders) {
1869
- let response;
1948
+ let result;
1870
1949
  try {
1871
- const controller = new AbortController();
1872
- const timer = setTimeout(() => controller.abort(), 15000);
1873
- const onAbort = () => controller.abort();
1950
+ const ctrl = new AbortController();
1951
+ const timer = setTimeout(() => ctrl.abort(), 15000);
1952
+ const onAbort = () => ctrl.abort();
1874
1953
  signal?.addEventListener("abort", onAbort);
1875
- response = await fetch(url, {
1876
- headers: {
1877
- "user-agent": USER_AGENT,
1878
- "accept-language": ACCEPT_LANG,
1879
- accept: "text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8",
1880
- ...(extraHeaders ?? {}),
1881
- },
1882
- signal: controller.signal,
1883
- redirect: "follow",
1884
- });
1885
- clearTimeout(timer);
1886
- signal?.removeEventListener("abort", onAbort);
1954
+ try {
1955
+ result = await httpsFetchText(url, {
1956
+ headers: {
1957
+ "user-agent": USER_AGENT,
1958
+ "accept-language": ACCEPT_LANG,
1959
+ accept: "text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8",
1960
+ ...(extraHeaders ?? {}),
1961
+ },
1962
+ signal: ctrl.signal,
1963
+ timeoutMs: 17000,
1964
+ });
1965
+ } finally {
1966
+ clearTimeout(timer);
1967
+ signal?.removeEventListener("abort", onAbort);
1968
+ }
1887
1969
  } catch (error) {
1888
1970
  if (signal?.aborted) throw error;
1889
1971
  throw new Error(`connection error: ${error?.message ?? String(error)}`);
1890
1972
  }
1891
- if (!response.ok) throw new Error(`HTTP ${response.status} from ${url.split("?")[0]}`);
1892
- return response.text();
1973
+ if (!result.ok) throw new Error(`HTTP ${result.status} from ${url.split("?")[0]}`);
1974
+ return result.text;
1893
1975
  }
1894
1976
 
1895
1977
  // 递归收集对象图里所有 key === searchKey 的值(YouTube ytInitialData 层级常变)
@@ -6148,4 +6230,7 @@ export {
6148
6230
  guardRelevance,
6149
6231
  queryOverlapTokens,
6150
6232
  verifyInstalledVersion,
6233
+ httpsLikeFetch,
6234
+ httpsFetchText,
6235
+ alpnHttpsAgent,
6151
6236
  };
@@ -15,6 +15,18 @@
15
15
  import https from "node:https";
16
16
  import http from "node:http";
17
17
 
18
+ // ALPN http/1.1(0.11.5 同源,上游 #162 教训):部分网关/站点会 RST 不带 ALPN 扩展的握手;
19
+ // 真实引擎端点走 https 时显式声明 http/1.1,本地单测的 http 端点用普通 keepAlive agent。
20
+ const ALPN_HTTPS_AGENT = new https.Agent({ ALPNProtocols: ["http/1.1"], keepAlive: true });
21
+ const PLAIN_HTTP_AGENT = new http.Agent({ keepAlive: true });
22
+ function agentFor(endpoint) {
23
+ try {
24
+ return new URL(endpoint).protocol === "http:" ? PLAIN_HTTP_AGENT : ALPN_HTTPS_AGENT;
25
+ } catch {
26
+ return ALPN_HTTPS_AGENT;
27
+ }
28
+ }
29
+
18
30
  /**
19
31
  * 解析 MCP 响应体:先按纯 JSON 解析,失败再按 SSE 帧提取。
20
32
  * SSE 帧:多个 `data:` 行(同一事件内按规范以 \n 拼接);这里同时兼容
@@ -144,6 +156,7 @@ function httpsPost(endpoint, body, headers, { timeoutMs, signal, label }) {
144
156
  };
145
157
  const req = transportFor(endpoint).request(endpoint, {
146
158
  method: "POST",
159
+ agent: agentFor(endpoint),
147
160
  headers: { ...headers, "content-length": Buffer.byteLength(body) },
148
161
  }, (res) => {
149
162
  const chunks = [];
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "dsh-union-search",
3
- "version": "0.11.4",
3
+ "version": "0.11.5",
4
4
  "description": "Union web search for DeepSeek Harness (renamed from dsh-free-search): free keyless engines + many professional paid search APIs — 28 engines (Bing/DuckDuckGo/AnySearch/SearXNG multi-instance union/Exa/Tavily/Keenable/Firecrawl/Parallel keyless; Zhihu global/site via MCP and Perplexity/SerpBase/Serply/DeepSeek official/You.com/Baidu/Kimi/Aliyun/Doubao/Zhipu/Bocha/Metaso with key; OpenAI/Gemini/Claude/Grok model built-in search, explicit-only) + auto smart routing + global engine enable/disable & fallback priority + multi mode (parallel top-3 merge) + multi_search cross-source tool + failure-aware fallback + block system built-in search toggle + experimental free advance_fetch (no API key, no billing; host-twin GitHub-Flavored Markdown conversion + CSS selector/fields structured extraction) + time filtering + platform search + web_fetch, with web settings UI.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "scripts": {
8
- "test": "node --test test/md.test.mjs test/egress.test.mjs test/relevance.test.mjs test/upgrade.test.mjs test/credentials.test.mjs test/tool-face.test.mjs test/notes-channel.test.mjs"
8
+ "test": "node --test test/md.test.mjs test/egress.test.mjs test/relevance.test.mjs test/upgrade.test.mjs test/alpn.test.mjs test/credentials.test.mjs test/tool-face.test.mjs test/notes-channel.test.mjs"
9
9
  },
10
10
  "exports": {
11
11
  ".": "./lib/index.js",