dsh-free-search 0.9.39 → 0.9.40

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
@@ -585,7 +585,7 @@ Search engine test:
585
585
 
586
586
  #### 离线自检断言(tools/)
587
587
 
588
- 仓库自带 **50 个**零依赖断言脚本(合计 **796 项**),**不需要 API key、不联网、不需要测试框架**,Node ≥ 20 即可跑:
588
+ 仓库自带 **51 个**零依赖断言脚本(合计 **805 项**),**不需要 API key、不联网、不需要测试框架**,Node ≥ 20 即可跑。一次跑全部:`npm test`。
589
589
 
590
590
  | 脚本 | 覆盖 | 运行(项数) |
591
591
  |---|---|---|
@@ -596,7 +596,8 @@ Search engine test:
596
596
  | `assert-multi-policy.mjs` | multi 执行策略:并发上限是天花板 / 目标成功源非硬下限 / 凭据资格在上限之前分流 / **Fast·Balanced·Deep 档位** | `node tools/assert-multi-policy.mjs`(146) |
597
597
  | `assert-multi-limit.mjs` | multi 结果上限(#109):默认 20 / 硬上限 100 / 配置归一化、单次 maxResults 受上限约束、工具参数与本段提示词写明生效上限、设置页字段与保存 | `node tools/assert-multi-limit.mjs`(6) |
598
598
  | `assert-maintenance.mjs` | 维护面:CI 在 Node 20/22/24 跑全部断言并过打包闸门、发布脚本会 bump / 校验 / 打 tag / 可发布、恢复官方 provider 的桥接与设置页按钮 | `node tools/assert-maintenance.mjs`(4) |
599
- | `assert-engine-modules.mjs` | 引擎分层:实现文件存在且被 index 引用、引擎函数已迁出 index、设置页引擎 id 与服务端清单一致、清单覆盖 36 个引擎且免费/按次标记正确 | `node tools/assert-engine-modules.mjs`(4) |
599
+ | `assert-engine-modules.mjs` | 引擎分层:实现文件存在且被 index 引用、引擎函数已迁出 index、设置页引擎 id 与服务端清单一致、清单覆盖 36 个引擎且免费/按次标记正确、index 不引用引擎私有名 | `node tools/assert-engine-modules.mjs`(6) |
600
+ | `assert-bing-relevance.mjs` | Bing 相关性(#112):单字中文 token 被剔除、无关替代 SERP 被拒、真正相关的结果通过、只命中通用引擎名的整批被拒、单一 token 覆盖一半时放行、单字/纯数字查询的显式行为 | `node tools/assert-bing-relevance.mjs`(6) |
600
601
  | `assert-result-ranking.mjs` | 合并排序:**eTLD+1 同域判定** / 域名轮转 / `seenIn` 降为末位 / 时效仅带时间过滤时生效 | `node tools/assert-result-ranking.mjs`(31) |
601
602
  | `assert-url-norm.mjs` | URL 规范化:只剔已审计的 tracking 参数,保留可能区分资源的参数 | `node tools/assert-url-norm.mjs`(72) |
602
603
  | `assert-prompt-contract.mjs` | 系统提示词契约:**检索≠抓取**、不可信边界、模型内置搜索只在显式选中时运行 | `node tools/assert-prompt-contract.mjs`(9) |
@@ -1243,7 +1244,7 @@ Restart `dsh web` after switching to apply changes.
1243
1244
 
1244
1245
  #### Offline self-check assertions (`tools/`)
1245
1246
 
1246
- **Fifty** zero-dependency assertion scripts ship with the repo (**796 assertions** total): **no API keys, no network, no test framework**, Node ≥ 20:
1247
+ **Fifty-one** zero-dependency assertion scripts ship with the repo (**805 assertions** total): **no API keys, no network, no test framework**, Node ≥ 20. Run everything with `npm test`.
1247
1248
 
1248
1249
  | Script | Covers | Run (count) |
1249
1250
  |---|---|---|
@@ -1254,7 +1255,8 @@ Restart `dsh web` after switching to apply changes.
1254
1255
  | `assert-multi-policy.mjs` | multi execution policy: ceiling semantics / target-is-not-a-hard-minimum / credential eligibility before the ceiling / **Fast·Balanced·Deep presets** | `node tools/assert-multi-policy.mjs` (146) |
1255
1256
  | `assert-multi-limit.mjs` | Multi result ceiling (#109): default 20 / hard max 100 / config normalisation, per-call maxResults clamped to the ceiling, tool copy and prompt state name the effective limit, settings field and save path | `node tools/assert-multi-limit.mjs` (6) |
1256
1257
  | `assert-maintenance.mjs` | Maintenance surface: CI runs every assertion on Node 20/22/24 plus the packaging gate, the release script bumps / verifies / tags / can publish, and the restore-official-provider bridge and settings button are wired | `node tools/assert-maintenance.mjs` (4) |
1257
- | `assert-engine-modules.mjs` | Engine layout: module files exist and are imported, implementations have left index.js, the client engine ids match the server catalog, and the catalog covers 36 engines with the right free/explicit flags | `node tools/assert-engine-modules.mjs` (4) |
1258
+ | `assert-engine-modules.mjs` | Engine layout: module files exist and are imported, implementations have left index.js, the client engine ids match the server catalog, the catalog covers 36 engines with the right free/explicit flags, and index never reads an engine-private name | `node tools/assert-engine-modules.mjs` (6) |
1259
+ | `assert-bing-relevance.mjs` | Bing relevance (#112): single-character CJK tokens removed, an unrelated substituted SERP rejected, genuinely relevant results accepted, a batch matching only a generic engine name rejected, one distinctive token covering half the query accepted, and explicit single-character/numeric behaviour | `node tools/assert-bing-relevance.mjs` (6) |
1258
1260
  | `assert-result-ranking.mjs` | merged ranking: **eTLD+1 same-site detection** / domain round-robin / `seenIn` demoted / freshness only under a time filter | `node tools/assert-result-ranking.mjs` (31) |
1259
1261
  | `assert-url-norm.mjs` | URL normalization: strips only audited tracking params, keeps params that may identify different resources | `node tools/assert-url-norm.mjs` (72) |
1260
1262
  | `assert-prompt-contract.mjs` | system-prompt contract: **search ≠ fetch**, untrusted-data boundary, model engines only when explicitly selected | `node tools/assert-prompt-contract.mjs` (9) |
package/lib/client.js CHANGED
@@ -650,7 +650,7 @@ window.__ModuleLoader__.load({
650
650
  "cache_search",
651
651
  "domain_search",
652
652
  ];
653
- const PLUGIN_VERSION = "0.9.39";
653
+ const PLUGIN_VERSION = "0.9.40";
654
654
  const PLUGIN_REPO_URL = "https://github.com/DDDMUC/dsh-free-search";
655
655
  // 右侧浮动目录(#85):条目顺序即页面顺序,anchor 是页面里对应 field 的 id。
656
656
  const NAV_ITEMS = [
@@ -3,6 +3,11 @@ import { uniqueSources, fetchHtmlWithRetry, stripTags, decodeEntities, approxima
3
3
 
4
4
  let ignoredAnysearchKey = "";
5
5
 
6
+ /** Called from index.js when the user writes a new AnySearch key. */
7
+ export function resetIgnoredAnysearchKey() {
8
+ ignoredAnysearchKey = "";
9
+ }
10
+
6
11
  const ANYSEARCH_KEY_INVALID_NOTE_ZH = "AnySearch key 无效,本次已忽略该 key,改回免费匿名档";
7
12
 
8
13
  const ANYSEARCH_KEY_INVALID_NOTE_EN = "AnySearch key was rejected; ignored it and used the anonymous tier";
@@ -1,81 +1,99 @@
1
- // Bing HTML engine; one fetch, no retry loop (see assert-engines).
2
- import { uniqueSources, fetchHtmlWithRetry, stripTags, decodeEntities, approximateTimeRange, SEARXNG_INSTANCES, SEARXNG_TIME, ANYSEARCH_URL, EXA_MCP_URL, extractDdgUrl, MARKET_TO_LANG, LANG_PROFILES, BING_URL, DDG_HTML_URL, DDG_LITE_URL, activeAcceptLanguage, USER_AGENT, searchLanguage, configLanguage, activeOutputLanguage } from "./shared.js";
3
-
4
- function queryOverlapTokens(query) {
5
- const tokens = new Set();
6
- for (const run of String(query).match(/[\u4e00-\u9fff]+/g) ?? []) {
7
- if (run.length <= 2) tokens.add(run);
8
- for (let i = 0; i + 1 < run.length; i++) tokens.add(run.slice(i, i + 2));
9
- }
10
- for (const word of String(query).toLowerCase().split(/[^a-z0-9]+/)) {
11
- if (word.length >= 2) tokens.add(word);
12
- }
13
- return [...tokens];
14
- }
15
-
16
- function looksRelevant(query, sources) {
17
- const tokens = queryOverlapTokens(query);
18
- if (tokens.length === 0) return true; // 纯符号查询无法判定,不拦截
19
- return sources.some((s) => {
20
- const hay = `${s.title ?? ""} ${s.snippet ?? ""} ${s.url ?? ""}`.toLowerCase();
21
- return tokens.some((t) => hay.includes(t.toLowerCase()));
22
- });
23
- }
24
-
25
- // Bing 会把结果 URL 包成 bing.com/ck/a 跳转链接:真实地址在 u 参数(base64url,a1 前缀)
26
-
27
- function extractBingUrl(href) {
28
- if (!href) return href;
29
- const url = decodeEntities(href); // &amp; -> &
30
- if (!/^https?:\/\/(www\.)?bing\.com\/ck\/a/i.test(url)) return href;
31
- try {
32
- const u = new URL(url).searchParams.get("u");
33
- if (!u) return href;
34
- const b64 = u.startsWith("a1") ? u.slice(2) : u;
35
- const decoded = Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
36
- return /^https?:\/\//i.test(decoded) ? decoded : href;
37
- } catch {
38
- return href;
39
- }
40
- }
41
-
42
- export async function searchBing(query, maxResults, options, signal) {
43
- // mkt:仅显式 bingMarket 才发。默认不发——mkt=zh-CN 在部分地区/线路会返回空 SERP 容器
44
- // (#71:海外 IP + mkt=zh-CN → b_algo=0),Bing 会按 Accept-Language 自行本地化。
45
- const profile = LANG_PROFILES[searchLanguage(configLanguage(options))];
46
- const params = new URLSearchParams({ q: query });
47
- if (options?.bingMarket) params.set("mkt", options.bingMarket);
48
- // Accept-Language:显式 bingMarket 时按 market 反推(避免中文 header 污染),否则用 lang 档案
49
- const acceptLang = options?.bingMarket
50
- ? (MARKET_TO_LANG[options.bingMarket] ?? activeAcceptLanguage)
51
- : (profile.acceptLang ?? activeAcceptLanguage);
52
- const adlt = options?.safeSearch ?? "off";
53
- if (adlt === "off") params.set("adlt", "off");
54
- else if (adlt === "moderate") params.set("adlt", "moderate");
55
- else if (adlt === "strict") params.set("adlt", "strict");
56
- // 注意(2026-10-13 实测):Bing 会对可疑出口 IP 间歇性返回约 91KB 的「空 SERP」(b_algo 块数 0),
57
- // 表现为按请求频率收紧、减少请求后又自行恢复。曾加过「空 SERP 时多试一次」的兜底,但实测
58
- // 请求数翻倍反而更容易被压死,且根因在出口 IP 而非解析,故撤掉——修法应让 bing 不走可疑代理
59
- // (启动脚本的 NO_PROXY 排除 .bing.com 即可恢复)。
60
- const html = await fetchHtmlWithRetry(`${BING_URL}?${params}`, signal, acceptLang);
61
- const blocks = html.match(/<li class="b_algo"[\s\S]*?<\/li>/g) ?? [];
62
- const sources = [];
63
- for (const block of blocks) {
64
- const hrefMatch = block.match(/<a[^>]*href="(https?:\/\/[^"]+)"/);
65
- const titleMatch = block.match(/<h2[^>]*>[\s\S]*?<a[^>]*>(.*?)<\/a>[\s\S]*?<\/h2>/);
66
- const snippetMatch = block.match(/<p[^>]*>([\s\S]*?)<\/p>/);
67
- if (!hrefMatch) continue;
68
- sources.push({
69
- url: extractBingUrl(hrefMatch[1]),
70
- ...(titleMatch ? { title: stripTags(titleMatch[1]) } : {}),
71
- ...(snippetMatch ? { snippet: stripTags(snippetMatch[1]) } : {}),
72
- });
73
- }
74
- // Bing 无结果时会返回无关的缓存页:判为 0 结果,交给统一回退链换下一个引擎
75
- if (sources.length > 0 && !looksRelevant(query, sources)) {
76
- return { sources: [], truncated: false };
77
- }
78
- return { sources: uniqueSources(sources, maxResults ?? 10), truncated: false };
79
- }
80
-
81
- //#region searxng (meta-search, free instances, auto-failover)
1
+ // Bing HTML engine; one fetch, no retry loop (see assert-engines).
2
+ import { uniqueSources, fetchHtmlWithRetry, stripTags, decodeEntities, approximateTimeRange, SEARXNG_INSTANCES, SEARXNG_TIME, ANYSEARCH_URL, EXA_MCP_URL, extractDdgUrl, MARKET_TO_LANG, LANG_PROFILES, BING_URL, DDG_HTML_URL, DDG_LITE_URL, activeAcceptLanguage, USER_AGENT, searchLanguage, configLanguage, activeOutputLanguage } from "./shared.js";
3
+
4
+ export function queryOverlapTokens(query) {
5
+ const tokens = new Set();
6
+ for (const run of String(query).match(/[\u4e00-\u9fff]+/g) ?? []) {
7
+ // 单字(年/月/日)几乎出现在任何默认页里,只保留二元组。
8
+ if (run.length === 2) tokens.add(run);
9
+ for (let i = 0; i + 1 < run.length; i++) tokens.add(run.slice(i, i + 2));
10
+ }
11
+ for (const word of String(query).toLowerCase().split(/[^a-z0-9]+/)) {
12
+ if (word.length >= 2) tokens.add(word);
13
+ }
14
+ return [...tokens];
15
+ }
16
+
17
+ /**
18
+ * Bing 在给出无关的替代结果时,单字 token 或一个泛词(如 "powershell")就足以
19
+ * 让整批通过;这会让模型拿到另一条查询的答案。要求足够多的来源命中,并且
20
+ * 至少命中两个不同 token(或覆盖一半 token),否则按 0 结果处理并回退。
21
+ */
22
+ export function looksRelevant(query, sources) {
23
+ const tokens = queryOverlapTokens(query);
24
+ // 纯符号/单字查询无法可靠判定,保持放行。
25
+ if (tokens.length === 0) return true;
26
+ const strong = tokens.filter((t) => !/^\d+$/.test(t));
27
+ const usable = strong.length > 0 ? strong : tokens;
28
+ const matched = new Set();
29
+ let relevant = 0;
30
+ for (const source of sources) {
31
+ const hay = `${source.title ?? ""} ${source.snippet ?? ""} ${source.url ?? ""}`.toLowerCase();
32
+ const hits = usable.filter((t) => hay.includes(t.toLowerCase()));
33
+ if (hits.length > 0) {
34
+ relevant += 1;
35
+ for (const hit of hits) matched.add(hit);
36
+ }
37
+ }
38
+ const enoughSources = relevant >= Math.max(1, Math.ceil(sources.length / 3));
39
+ const enoughTokens = matched.size >= Math.min(2, usable.length) || matched.size / usable.length >= 0.5;
40
+ return enoughSources && enoughTokens;
41
+ }
42
+
43
+ // Bing 会把结果 URL 包成 bing.com/ck/a 跳转链接:真实地址在 u 参数(base64url,a1 前缀)
44
+
45
+ function extractBingUrl(href) {
46
+ if (!href) return href;
47
+ const url = decodeEntities(href); // &amp; -> &
48
+ if (!/^https?:\/\/(www\.)?bing\.com\/ck\/a/i.test(url)) return href;
49
+ try {
50
+ const u = new URL(url).searchParams.get("u");
51
+ if (!u) return href;
52
+ const b64 = u.startsWith("a1") ? u.slice(2) : u;
53
+ const decoded = Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
54
+ return /^https?:\/\//i.test(decoded) ? decoded : href;
55
+ } catch {
56
+ return href;
57
+ }
58
+ }
59
+
60
+ export async function searchBing(query, maxResults, options, signal) {
61
+ // mkt:仅显式 bingMarket 才发。默认不发——mkt=zh-CN 在部分地区/线路会返回空 SERP 容器
62
+ // (#71:海外 IP + mkt=zh-CN → b_algo=0),Bing 会按 Accept-Language 自行本地化。
63
+ const profile = LANG_PROFILES[searchLanguage(configLanguage(options))];
64
+ const params = new URLSearchParams({ q: query });
65
+ if (options?.bingMarket) params.set("mkt", options.bingMarket);
66
+ // Accept-Language:显式 bingMarket 时按 market 反推(避免中文 header 污染),否则用 lang 档案
67
+ const acceptLang = options?.bingMarket
68
+ ? (MARKET_TO_LANG[options.bingMarket] ?? activeAcceptLanguage)
69
+ : (profile.acceptLang ?? activeAcceptLanguage);
70
+ const adlt = options?.safeSearch ?? "off";
71
+ if (adlt === "off") params.set("adlt", "off");
72
+ else if (adlt === "moderate") params.set("adlt", "moderate");
73
+ else if (adlt === "strict") params.set("adlt", "strict");
74
+ // 注意(2026-10-13 实测):Bing 会对可疑出口 IP 间歇性返回约 91KB 的「空 SERP」(b_algo 块数 0),
75
+ // 表现为按请求频率收紧、减少请求后又自行恢复。曾加过「空 SERP 时多试一次」的兜底,但实测
76
+ // 请求数翻倍反而更容易被压死,且根因在出口 IP 而非解析,故撤掉——修法应让 bing 不走可疑代理
77
+ // (启动脚本的 NO_PROXY 排除 .bing.com 即可恢复)。
78
+ const html = await fetchHtmlWithRetry(`${BING_URL}?${params}`, signal, acceptLang);
79
+ const blocks = html.match(/<li class="b_algo"[\s\S]*?<\/li>/g) ?? [];
80
+ const sources = [];
81
+ for (const block of blocks) {
82
+ const hrefMatch = block.match(/<a[^>]*href="(https?:\/\/[^"]+)"/);
83
+ const titleMatch = block.match(/<h2[^>]*>[\s\S]*?<a[^>]*>(.*?)<\/a>[\s\S]*?<\/h2>/);
84
+ const snippetMatch = block.match(/<p[^>]*>([\s\S]*?)<\/p>/);
85
+ if (!hrefMatch) continue;
86
+ sources.push({
87
+ url: extractBingUrl(hrefMatch[1]),
88
+ ...(titleMatch ? { title: stripTags(titleMatch[1]) } : {}),
89
+ ...(snippetMatch ? { snippet: stripTags(snippetMatch[1]) } : {}),
90
+ });
91
+ }
92
+ // Bing 无结果时会返回无关的缓存页:判为 0 结果,交给统一回退链换下一个引擎
93
+ if (sources.length > 0 && !looksRelevant(query, sources)) {
94
+ return { sources: [], truncated: false };
95
+ }
96
+ return { sources: uniqueSources(sources, maxResults ?? 10), truncated: false };
97
+ }
98
+
99
+ //#region searxng (meta-search, free instances, auto-failover)
package/lib/index.js CHANGED
@@ -27,7 +27,7 @@ import { searchDdgLite } from "./engines/ddg-lite.js";
27
27
  import { searchBing } from "./engines/bing.js";
28
28
  import { searchSearxng } from "./engines/searxng.js";
29
29
  import { searchDegoog } from "./engines/degoog.js";
30
- import { searchAnysearch } from "./engines/anysearch.js";
30
+ import { searchAnysearch, resetIgnoredAnysearchKey } from "./engines/anysearch.js";
31
31
  import { searchExa, searchExaMCP } from "./engines/exa.js";
32
32
  import { searchTavily } from "./engines/tavily.js";
33
33
  import { searchFirecrawl } from "./engines/firecrawl.js";
@@ -1533,7 +1533,7 @@ function makeBridgeRoutes(settings, search, testEngine, getCredentials, getConfi
1533
1533
  await settings.mutate(ns, body.ops, expectedRevision);
1534
1534
  // 设置页保存了 AnySearch key:允许下次再试(不删除存储,仅解除本进程忽略)
1535
1535
  if (body.ops.some((op) => op && op.op === "set" && Array.isArray(op.path) && op.path[0] === "anysearchApiKey")) {
1536
- ignoredAnysearchKey = "";
1536
+ resetIgnoredAnysearchKey();
1537
1537
  }
1538
1538
  } catch (error) {
1539
1539
  if (error instanceof SettingsConflictError) {
@@ -1576,7 +1576,7 @@ function makeBridgeRoutes(settings, search, testEngine, getCredentials, getConfi
1576
1576
  try {
1577
1577
  await credentials.set(ref, value.trim());
1578
1578
  // 用户写入新 AnySearch key:允许下次请求再试(仅忽略同值坏 key,不删除存储)
1579
- if (key === "anysearchApiKey") ignoredAnysearchKey = "";
1579
+ if (key === "anysearchApiKey") resetIgnoredAnysearchKey();
1580
1580
  return { ok: true, value: { ref, set: true } };
1581
1581
  } catch (error) {
1582
1582
  return { ok: false, code: "credentials-write-failed", message: error instanceof Error ? error.message : String(error) };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-free-search",
3
- "version": "0.9.39",
3
+ "version": "0.9.40",
4
4
  "description": "Free web search for DeepSeek Harness: 27 engines (Bing/DuckDuckGo/AnySearch/SearXNG/Exa/Tavily/Keenable/Firecrawl/Parallel/You.com keyless; Zhihu global/site via MCP and Perplexity/SerpBase/DeepSeek (official + native tools/search)/Baidu/Kimi/Aliyun/Doubao 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.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -14,6 +14,7 @@
14
14
  "cordis.patch.yml"
15
15
  ],
16
16
  "scripts": {
17
+ "test": "node tools/run-assertions.mjs",
17
18
  "prepack": "node tools/assert-package-files.mjs"
18
19
  },
19
20
  "keywords": [