dsh-free-search 0.9.37 → 0.9.38

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
@@ -76,7 +76,7 @@
76
76
 
77
77
  #### 抓取与工具
78
78
 
79
- - **网页抓取(web_fetch)** —— 让 agent 抓取网页内容(官方 `dsh-web-fetch-http` provider,纯 JS,零额外依赖),可自动接管 `web.fetchProvider` 为插件的直连 → exa → firecrawl → crawl4ai 质量链。
79
+ - **网页抓取(web_fetch)** —— 让 agent 抓取网页内容(官方 `dsh-web-fetch-http` provider,纯 JS,零额外依赖),可自动接管 `web.fetchProvider` 为插件的直连 → 浏览器渲染 → exa / firecrawl → crawl4ai 质量链。T1.5 浏览器渲染可在设置页关闭,exa 与 firecrawl 的先后顺序也可切换;私网、回环和云元数据地址一律拒绝(SSRF 防护)。
80
80
 
81
81
  <img src="https://raw.githubusercontent.com/DDDMUC/dsh-free-search/master/assets/ui-fetch.png" alt="抓取与平台:web_fetch 接管、Key 存储位置与平台搜索开关" width="100%" />
82
82
  <sub>▲ 抓取:自动接管 web_fetch、Key 存储位置与平台搜索开关</sub>
@@ -93,7 +93,7 @@
93
93
 
94
94
  #### 设置页与目录
95
95
 
96
- - **网页设置页** —— 引擎切换 + API key 配置(UI 中 key 脱敏显示「已配置」)+ 中英文切换;入口在左侧「插件」页的组件行配置(`plugins.row.config`,DSH 0.1.7-rc.1+)。远程访问(VPS / 反向代理 / 自定义域名)下也能用:桥接接口沿用宿主的 Host 围栏,`--trusted-host` 与 `--public-url` 声明的地址会放行(#84)。
96
+ - **网页设置页** —— 引擎切换 + API key 配置(UI 中 key 脱敏显示「已配置」)+ 中英文切换;入口在左侧「插件」页的组件行配置(`plugins.row.config`,DSH 0.2.1-rc.2+)。远程访问(VPS / 反向代理 / 自定义域名)下也能用:桥接接口沿用宿主的 Host 围栏,`--trusted-host` 与 `--public-url` 声明的地址会放行(#84)。
97
97
 
98
98
  <img src="https://raw.githubusercontent.com/DDDMUC/dsh-free-search/master/assets/ui-apikeys.png" alt="全局回退优先级与每引擎 API key" width="100%" />
99
99
  <sub>▲ 全局回退优先级:每行一个引擎,右侧填该引擎的 API key(已配置会脱敏显示)</sub>
@@ -207,6 +207,8 @@
207
207
 
208
208
  ### 安装
209
209
 
210
+ 需要 **DSH 0.2.1-rc.2 或更新的 0.2.x**;更早的 0.1.x 宿主不满足 `engines.dsh`,插件管理器会拒绝安装。
211
+
210
212
  ```sh
211
213
  git clone https://github.com/DDDMUC/dsh-free-search.git
212
214
  dsh plugin --profile web add /path/to/dsh-free-search
@@ -268,7 +270,7 @@ DSH 0.2.1 设置 → 网页搜索 → **DeepSeek 搜索 API** 开关会和本插
268
270
 
269
271
  #### 网页设置(推荐)
270
272
 
271
- 安装后打开配置页(DSH 0.1.7-rc.1+):
273
+ 安装后打开配置页(DSH 0.2.1-rc.2+):
272
274
 
273
275
  - 左侧 **插件** 页 → **已安装** 分组 → `free-search` → 点击组件行 `web-search-free`(行内"配置"入口)
274
276
 
@@ -367,7 +369,7 @@ DSH 0.2.1 设置 → 网页搜索 → **DeepSeek 搜索 API** 开关会和本插
367
369
 
368
370
  #### 配置文件
369
371
 
370
- DSH 0.1.7-rc.1 起,配置跟随 profile 的插件条目保存:设置页与 `/free-search-engine` 都会写入当前 profile 的 `cordis.patch.yml` 中 `web-search-free`(`dsh-free-search`)条目的 `config`。
372
+ 从 DSH 0.1.7-rc.1 起(当前版本要求 0.2.1-rc.2+),配置跟随 profile 的插件条目保存:设置页与 `/free-search-engine` 都会写入当前 profile 的 `cordis.patch.yml` 中 `web-search-free`(`dsh-free-search`)条目的 `config`。
371
373
 
372
374
  旧版 `~/.dsh/settings.yaml` 的 `free-search:` 段**不会被 DSH 核心自动导入**(核心的 `importLegacyDocument` 只为 `ui-developer-tools` / `ui-onboarding` / `shell` 三个段提供了映射),原文件在导入其它段后会被改名为 `settings.yaml.imported`,该段的值只留在那里。插件会在启动时检测 `settings.yaml.imported`(或仍存在的 `settings.yaml`)中的 `free-search:` 段,把可识别的字段**一次性补种**进当前 profile 的条目 `config`(写一次后不再重复,可在启动日志看到 `free-search: migrated N field(s)…`)。如果你想手动处理,也可以照着 `settings.yaml.imported` 里的值在插件页行配置中填一遍。
373
375
 
@@ -394,6 +396,8 @@ promptToolsLang: "" # 工具段那句话的语言,zh 或 en;留空
394
396
  disabledTools: [] # 关掉的工具不再注册(例如 [domain_search]),schema 一并从上下文消失
395
397
  bingMarket: zh-CN # Bing 市场;留空 = 自动(不发送 mkt)
396
398
  fetchProviderTakeover: true # false = 保留你显式 pin 的 fetchProvider: http
399
+ browserFetch: true # 直连失败时用系统浏览器无头渲染
400
+ fetchPrefer: exa # exa | firecrawl —— 两者都失败后先试哪个 keyed 抓取层
397
401
  region: cn-zh # DuckDuckGo 区域(可选)
398
402
  searxngInstances: # 自定义 SearXNG 实例(可选)
399
403
  - https://your-instance.example
@@ -578,7 +582,7 @@ Search engine test:
578
582
 
579
583
  #### 离线自检断言(tools/)
580
584
 
581
- 仓库自带 **47 个**零依赖断言脚本(合计 **776 项**),**不需要 API key、不联网、不需要测试框架**,Node ≥ 20 即可跑:
585
+ 仓库自带 **48 个**零依赖断言脚本(合计 **782 项**),**不需要 API key、不联网、不需要测试框架**,Node ≥ 20 即可跑:
582
586
 
583
587
  | 脚本 | 覆盖 | 运行(项数) |
584
588
  |---|---|---|
@@ -596,6 +600,7 @@ Search engine test:
596
600
  | `assert-research-degradation.mjs` | research 无 key 全降级、`node:sqlite` no-op、90s 预算隔离、缓存目录可配置、`budget.exhausted` 契约名 | `node tools/assert-research-degradation.mjs`(19) |
597
601
  | `assert-research-call-wrappers.mjs` | research 四个 `call*` 包装层的替身/底层透传(#75 回归) | `node tools/assert-research-call-wrappers.mjs`(23) |
598
602
  | `assert-fetch-chain.mjs` | `fs-quality-fetch` 四层链序、任一层命中即停、exa 失败静默降级 firecrawl、全层失败聚合报错 | `node tools/assert-fetch-chain.mjs`(8) |
603
+ | `assert-fetch-ssrf.mjs` | 抓取 SSRF 防护:公网/私网/保留地址判定、DNS 解析到私网拒绝、localhost 与 IP 字面量拒绝、非 HTTPS 与带凭据 URL 拒绝、provider 接线与设置项 | `node tools/assert-fetch-ssrf.mjs`(6) |
599
604
  | `assert-single-fetch-layer.mjs` | 抓取层全库只有一份实现、依赖单向、替身键不串层 | `node tools/assert-single-fetch-layer.mjs`(22) |
600
605
  | `assert-vertical.mjs` | `domain_search` 41 引擎注册表、每引擎 desc、未知引擎报错、不依赖 research | `node tools/assert-vertical.mjs`(8) |
601
606
  | `assert-free-search-test-schema.mjs` | `free_search_test` 输出 schema 与真实产出一致(含 auto/multi 虚拟模式) | `node tools/assert-free-search-test-schema.mjs`(8) |
@@ -722,7 +727,7 @@ This plugin solves exactly that: multiple free engines plus automatic fallback,
722
727
 
723
728
  #### Fetch and tools
724
729
 
725
- - **Webpage Fetching (`web_fetch`)** — Allows the agent to read full webpage contents (official `dsh-web-fetch-http` provider, pure JS, zero extra dependencies); it can take over `web.fetchProvider` with the plugin's direct → exa → firecrawl → crawl4ai quality chain.
730
+ - **Webpage Fetching (`web_fetch`)** — Allows the agent to read full webpage contents (official `dsh-web-fetch-http` provider, pure JS, zero extra dependencies); it can take over `web.fetchProvider` with the plugin's direct → browser render → exa / firecrawl → crawl4ai quality chain. The headless browser tier can be switched off in Settings and the exa/firecrawl order is configurable; loopback, private-network and cloud-metadata addresses are rejected (SSRF guard).
726
731
 
727
732
  <img src="https://raw.githubusercontent.com/DDDMUC/dsh-free-search/master/assets/ui-fetch.png" alt="Fetch and platforms: web_fetch takeover, key storage and platform switches" width="100%" />
728
733
  <sub>▲ Fetch: web_fetch takeover, key storage location and platform search switches</sub>
@@ -739,7 +744,7 @@ This plugin solves exactly that: multiple free engines plus automatic fallback,
739
744
 
740
745
  #### Settings and rail
741
746
 
742
- - **Web Settings UI** — Engine switching, API key configuration (keys masked as "configured" in the UI), and a Chinese/English toggle; the entry is the component-row config (`plugins.row.config`) on the sidebar Plugins page (DSH 0.1.7-rc.1+). Remote access (VPS, reverse proxy, custom domain) works too: the bridge reuses the host's own Host fence, so addresses declared with `--trusted-host` or `--public-url` are accepted (#84).
747
+ - **Web Settings UI** — Engine switching, API key configuration (keys masked as "configured" in the UI), and a Chinese/English toggle; the entry is the component-row config (`plugins.row.config`) on the sidebar Plugins page (DSH 0.2.1-rc.2+). Remote access (VPS, reverse proxy, custom domain) works too: the bridge reuses the host's own Host fence, so addresses declared with `--trusted-host` or `--public-url` are accepted (#84).
743
748
 
744
749
  <img src="https://raw.githubusercontent.com/DDDMUC/dsh-free-search/master/assets/ui-apikeys.png" alt="Global fallback priority and per-engine API keys" width="100%" />
745
750
  <sub>▲ Global fallback priority: one engine per row, its API key on the right (configured keys are masked)</sub>
@@ -855,6 +860,8 @@ Rule of thumb for a default pool: **① as the floor + ③ as the workhorse**;
855
860
 
856
861
  ### Installation
857
862
 
863
+ Requires **DSH 0.2.1-rc.2 or a newer 0.2.x**; older 0.1.x hosts do not satisfy `engines.dsh` and the plugin manager will refuse the install.
864
+
858
865
  ```sh
859
866
  git clone https://github.com/DDDMUC/dsh-free-search.git
860
867
  dsh plugin --profile web add /path/to/dsh-free-search
@@ -916,7 +923,7 @@ This plugin intentionally specifies `@deepseek-ai/dsh-settings` and `@deepseek-a
916
923
 
917
924
  #### Web Settings (Recommended)
918
925
 
919
- After installation, open the config page (DSH 0.1.7-rc.1+):
926
+ After installation, open the config page (DSH 0.2.1-rc.2+):
920
927
 
921
928
  - Sidebar **Plugins** page → **Installed** group → `free-search` → click the `web-search-free` component row (the row's "configure" entry)
922
929
 
@@ -1015,7 +1022,7 @@ If you deliberately pinned `fetchProvider: http` (you only want the built-in fet
1015
1022
 
1016
1023
  #### Configuration File
1017
1024
 
1018
- Since DSH 0.1.7-rc.1 the configuration is stored with the profile's plugin entry: the settings page and `/free-search-engine` both write the `config` of the `web-search-free` (`dsh-free-search`) entry in the active profile's `cordis.patch.yml`.
1025
+ Since DSH 0.1.7-rc.1 (the current release line requires 0.2.1-rc.2+) the configuration is stored with the profile's plugin entry: the settings page and `/free-search-engine` both write the `config` of the `web-search-free` (`dsh-free-search`) entry in the active profile's `cordis.patch.yml`.
1019
1026
 
1020
1027
  The old `free-search:` section of `~/.dsh/settings.yaml` is **not** imported by the DSH core (`importLegacyDocument` only maps `ui-developer-tools` / `ui-onboarding` / `shell`); the file is renamed to `settings.yaml.imported` after the other sections are imported, and the section's values stay there. The plugin detects that section in `settings.yaml.imported` (or in a still-present `settings.yaml`) at startup and seeds the recognized fields into this entry's `config` **once** (watch for `free-search: migrated N field(s)…` in the startup log). You can also migrate manually by copying the values from `settings.yaml.imported` into the plugin row config.
1021
1028
 
@@ -1042,6 +1049,8 @@ promptConstraintsIndex: 0
1042
1049
  disabledTools: [] # tools that are not registered at all (e.g. [domain_search]); their schemas leave the context too
1043
1050
  bingMarket: zh-CN # Bing market; empty = automatic (no mkt sent)
1044
1051
  fetchProviderTakeover: true # false = keep the fetchProvider: http you pinned yourself
1052
+ browserFetch: true # use the system browser headless renderer when direct fetch fails
1053
+ fetchPrefer: exa # exa | firecrawl — which keyed fetch tier to try first
1045
1054
  region: cn-zh # DuckDuckGo region (optional)
1046
1055
  searxngInstances: # Custom SearXNG instances (optional)
1047
1056
  - https://your-instance.example
@@ -1226,7 +1235,7 @@ Restart `dsh web` after switching to apply changes.
1226
1235
 
1227
1236
  #### Offline self-check assertions (`tools/`)
1228
1237
 
1229
- **Forty-seven** zero-dependency assertion scripts ship with the repo (**776 assertions** total): **no API keys, no network, no test framework**, Node ≥ 20:
1238
+ **Forty-eight** zero-dependency assertion scripts ship with the repo (**782 assertions** total): **no API keys, no network, no test framework**, Node ≥ 20:
1230
1239
 
1231
1240
  | Script | Covers | Run (count) |
1232
1241
  |---|---|---|
@@ -1244,6 +1253,7 @@ Restart `dsh web` after switching to apply changes.
1244
1253
  | `assert-research-degradation.mjs` | research degrades fully without keys, `node:sqlite` no-op, 90s budget isolation, configurable cache dir, `budget.exhausted` contract names | `node tools/assert-research-degradation.mjs` (19) |
1245
1254
  | `assert-research-call-wrappers.mjs` | the four research `call*` wrappers proxy to stubs / the real layer (#75 regression) | `node tools/assert-research-call-wrappers.mjs` (23) |
1246
1255
  | `assert-fetch-chain.mjs` | `fs-quality-fetch` tier ordering, stop-on-first-success, silent firecrawl degradation, aggregated all-tiers failure | `node tools/assert-fetch-chain.mjs` (8) |
1256
+ | `assert-fetch-ssrf.mjs` | Fetch SSRF guard: public/private/reserved address classification, DNS resolving to a private address rejected, localhost and IP literals rejected, non-HTTPS and credential URLs rejected, provider wiring and settings | `node tools/assert-fetch-ssrf.mjs` (6) |
1247
1257
  | `assert-single-fetch-layer.mjs` | exactly one fetch implementation repo-wide, one-way deps, seams owned by the right layer | `node tools/assert-single-fetch-layer.mjs` (22) |
1248
1258
  | `assert-vertical.mjs` | `domain_search` registry of 41 engines, per-engine descriptions, unknown-engine errors, no research dependency | `node tools/assert-vertical.mjs` (8) |
1249
1259
  | `assert-free-search-test-schema.mjs` | `free_search_test` output schema matches real output (incl. auto/multi virtual modes) | `node tools/assert-free-search-test-schema.mjs` (8) |
package/lib/client.js CHANGED
@@ -429,6 +429,12 @@ window.__ModuleLoader__.load({
429
429
  marketAuto: "自动 —— 不发送 mkt(推荐用于非上列地区)",
430
430
  fetchTakeoverLabel: "自动接管 web_fetch",
431
431
  fetchTakeoverHint: "开启时:web.fetchProvider 未设置或仍是出厂默认 http 会接管为 fs-quality-fetch。如果你刻意 pin 了 http(例如只想用内置抓取),关掉此项。",
432
+ browserFetchLabel: "用本机浏览器渲染",
433
+ browserFetchHint: "直连失败时用系统 Chrome/Edge 无头加载页面,能过 JS 挑战;没有浏览器时自动跳过。",
434
+ fetchPreferLabel: "抓取质量链顺序",
435
+ fetchPreferExa: "Exa 优先",
436
+ fetchPreferFirecrawl: "Firecrawl 优先",
437
+ fetchPreferHint: "直连和浏览器都失败后先试哪个;只有两个都配了 key 时才有区别。",
432
438
  restoreOfficial: "恢复官方搜索",
433
439
  restoreOfficialHint: "把 web.searchProvider 改回 deepseek-official、web.fetchProvider 改回 http。停用或卸载本插件前建议先点一次,避免宿主报 configured web provider \"ddg\" is not registered。",
434
440
  restoringOfficial: "恢复中…",
@@ -585,6 +591,12 @@ window.__ModuleLoader__.load({
585
591
  marketAuto: "Automatic — send no mkt (recommended outside the listed regions)",
586
592
  fetchTakeoverLabel: "Take over web_fetch automatically",
587
593
  fetchTakeoverHint: "On: when web.fetchProvider is unset or still the factory default http, it is taken over as fs-quality-fetch. Turn this off if you deliberately pinned http (e.g. you only want the built-in fetcher).",
594
+ browserFetchLabel: "Render with the local browser",
595
+ browserFetchHint: "When direct fetch fails, load the page in headless Chrome/Edge to pass JS challenges; skipped when no browser is installed.",
596
+ fetchPreferLabel: "Fetch quality-chain order",
597
+ fetchPreferExa: "Exa first",
598
+ fetchPreferFirecrawl: "Firecrawl first",
599
+ fetchPreferHint: "Which keyed tier to try first after direct and browser both fail; only matters when both keys are configured.",
588
600
  restoreOfficial: "Restore official search",
589
601
  restoreOfficialHint: "Sets web.searchProvider back to deepseek-official and web.fetchProvider back to http. Run this before disabling or uninstalling the plugin, otherwise the host reports configured web provider \"ddg\" is not registered.",
590
602
  restoringOfficial: "Restoring…",
@@ -634,7 +646,7 @@ window.__ModuleLoader__.load({
634
646
  "cache_search",
635
647
  "domain_search",
636
648
  ];
637
- const PLUGIN_VERSION = "0.9.37";
649
+ const PLUGIN_VERSION = "0.9.38";
638
650
  const PLUGIN_REPO_URL = "https://github.com/DDDMUC/dsh-free-search";
639
651
  // 右侧浮动目录(#85):条目顺序即页面顺序,anchor 是页面里对应 field 的 id。
640
652
  const NAV_ITEMS = [
@@ -898,6 +910,8 @@ window.__ModuleLoader__.load({
898
910
  const [safeSearch, setSafeSearch] = react.useState("off");
899
911
  const [bingMarket, setBingMarket] = react.useState("zh-CN");
900
912
  const [fetchProviderTakeover, setFetchProviderTakeover] = react.useState(true);
913
+ const [browserFetch, setBrowserFetch] = react.useState(true);
914
+ const [fetchPrefer, setFetchPrefer] = react.useState("exa");
901
915
  const [anysearchKey, setAnysearchKey] = react.useState("");
902
916
  const [exaKey, setExaKey] = react.useState("");
903
917
  const [tavilyKey, setTavilyKey] = react.useState("");
@@ -1059,6 +1073,8 @@ window.__ModuleLoader__.load({
1059
1073
  setSafeSearch(v.safeSearch === "strict" || v.safeSearch === "moderate" ? v.safeSearch : "off");
1060
1074
  setBingMarket(v.bingMarket === undefined ? "zh-CN" : v.bingMarket);
1061
1075
  setFetchProviderTakeover(v.fetchProviderTakeover !== false);
1076
+ setBrowserFetch(v.browserFetch !== false);
1077
+ setFetchPrefer(v.fetchPrefer === "firecrawl" ? "firecrawl" : "exa");
1062
1078
  setLang(v.lang ?? "zh");
1063
1079
  setUiLang(typeof v.uiLang === "string" ? v.uiLang : "");
1064
1080
  setPromptLanguage(v.promptLanguage === "zh" ? "zh" : "en");
@@ -1231,6 +1247,8 @@ window.__ModuleLoader__.load({
1231
1247
  ops.push({ op: "set", path: ["safeSearch"], value: safeSearch });
1232
1248
  ops.push({ op: "set", path: ["bingMarket"], value: bingMarket });
1233
1249
  ops.push({ op: "set", path: ["fetchProviderTakeover"], value: fetchProviderTakeover });
1250
+ ops.push({ op: "set", path: ["browserFetch"], value: browserFetch });
1251
+ ops.push({ op: "set", path: ["fetchPrefer"], value: fetchPrefer === "firecrawl" ? "firecrawl" : "exa" });
1234
1252
  if (keyStorage !== "credentials") {
1235
1253
  // settings 模式:key 写入当前 profile 的插件条目 config(cordis.patch.yml)
1236
1254
  for (const [field, value] of keyFields) {
@@ -2304,6 +2322,61 @@ react_jsx_runtime.jsx("div", {
2304
2322
  }),
2305
2323
  ],
2306
2324
  }),
2325
+ react_jsx_runtime.jsx("div", {
2326
+ className: "dshfs-field",
2327
+ children: [
2328
+ react_jsx_runtime.jsx("label", {
2329
+ className: "dshfs-platform",
2330
+ children: [
2331
+ react_jsx_runtime.jsx("input", {
2332
+ type: "checkbox",
2333
+ checked: browserFetch,
2334
+ disabled: !ready || saving,
2335
+ onChange: (e) => {
2336
+ setBrowserFetch(e.target.checked);
2337
+ setDirty(true);
2338
+ setFailed(false);
2339
+ setSaveError("");
2340
+ },
2341
+ }),
2342
+ t.browserFetchLabel,
2343
+ ],
2344
+ }),
2345
+ react_jsx_runtime.jsx("p", {
2346
+ className: "dshfs-hint",
2347
+ children: t.browserFetchHint,
2348
+ }),
2349
+ ],
2350
+ }),
2351
+ react_jsx_runtime.jsx("div", {
2352
+ className: "dshfs-field",
2353
+ children: [
2354
+ react_jsx_runtime.jsx("div", {
2355
+ className: "dshfs-label",
2356
+ children: t.fetchPreferLabel,
2357
+ }),
2358
+ react_jsx_runtime.jsx("select", {
2359
+ className: "dshfs-select",
2360
+ value: fetchPrefer,
2361
+ style: { colorScheme: selectColorScheme },
2362
+ disabled: !ready || saving,
2363
+ onChange: (e) => {
2364
+ setFetchPrefer(e.target.value === "firecrawl" ? "firecrawl" : "exa");
2365
+ setDirty(true);
2366
+ setFailed(false);
2367
+ setSaveError("");
2368
+ },
2369
+ children: [
2370
+ react_jsx_runtime.jsx("option", { value: "exa", children: t.fetchPreferExa }),
2371
+ react_jsx_runtime.jsx("option", { value: "firecrawl", children: t.fetchPreferFirecrawl }),
2372
+ ],
2373
+ }),
2374
+ react_jsx_runtime.jsx("p", {
2375
+ className: "dshfs-hint",
2376
+ children: t.fetchPreferHint,
2377
+ }),
2378
+ ],
2379
+ }),
2307
2380
  react_jsx_runtime.jsx("div", {
2308
2381
  className: "dshfs-field",
2309
2382
  children: [
@@ -13,6 +13,7 @@ import { tmpdir } from "node:os";
13
13
  import { join } from "node:path";
14
14
  import { callExa, callFirecrawl, callCrawl4ai } from "./fetch_upstream.js";
15
15
  import { stripLoneSurrogates } from "./safe_text.js";
16
+ import { assertPublicUrl, safeLookup } from "./ssrf.js";
16
17
 
17
18
  const T1_MIN_CHARS = 300;
18
19
  const TEXTUAL = /text\/|json|xml|javascript|application\/json/i;
@@ -151,7 +152,7 @@ function decodeBody(buffer, contentType) {
151
152
  }
152
153
 
153
154
  /** GET 跟随重定向(≤5 跳),返回最终 URL / 状态 / 正文 / 内容类型;支持 gzip/br/deflate 解压。 */
154
- export function httpsGetFollow(url, { headers = {}, timeoutMs = 20000, signal } = {}, transport = https) {
155
+ export function httpsGetFollow(url, { headers = {}, timeoutMs = 20000, signal, lookup } = {}, transport = https) {
155
156
  return new Promise((resolve, reject) => {
156
157
  let settled = false;
157
158
  let activeReq = null;
@@ -207,6 +208,7 @@ export function httpsGetFollow(url, { headers = {}, timeoutMs = 20000, signal }
207
208
  method: "GET",
208
209
  headers,
209
210
  timeout: timeoutMs,
211
+ ...(lookup ? { lookup } : {}),
210
212
  },
211
213
  (res) => {
212
214
  activeRes = res;
@@ -295,7 +297,14 @@ const BROWSERISH = {
295
297
  export function browserishHeaders(acceptLanguage = "en-US,en;q=0.9") {
296
298
  return { ...BROWSERISH, "Accept-Language": String(acceptLanguage ?? "").trim() || "en-US,en;q=0.9" };
297
299
  }
298
- export function createFetchProvider({ resolveApiKey, logger, acceptLanguage = () => "en-US,en;q=0.9" }) {
300
+ export function createFetchProvider({
301
+ resolveApiKey,
302
+ logger,
303
+ acceptLanguage = () => "en-US,en;q=0.9",
304
+ browserEnabled = () => true,
305
+ prefer = () => "exa",
306
+ validateUrl = assertPublicUrl,
307
+ }) {
299
308
  return {
300
309
  id: "fs-quality-fetch",
301
310
  /** 廉价本地可用性检查(seam 契约要求,禁止网络调用)。 */
@@ -303,11 +312,14 @@ export function createFetchProvider({ resolveApiKey, logger, acceptLanguage = ()
303
312
  async fetch(request, signal) {
304
313
  const url = String(request?.url || "");
305
314
  if (!/^https:\/\//i.test(url)) throw new Error(`fs-quality-fetch: only https URLs are supported (got "${url.slice(0, 60)}")`);
315
+ // SSRF guard: never fetch loopback / private / metadata addresses, and use a
316
+ // lookup that re-checks every redirect hop.
317
+ await validateUrl(url);
306
318
  const errors = [];
307
319
 
308
320
  // T1:直连(文本类内容;二进制交给后层——exa 取正文,PDF 等仍由 firecrawl 处理)
309
321
  try {
310
- const r = await httpsGetFollow(url, { headers: browserishHeaders(acceptLanguage()), signal });
322
+ const r = await httpsGetFollow(url, { headers: browserishHeaders(acceptLanguage()), signal, lookup: safeLookup });
311
323
  if (r.status < 400 && TEXTUAL.test(r.contentType) && r.text.length >= T1_MIN_CHARS) {
312
324
  return { url: r.url, statusCode: r.status, body: { kind: "html", content: stripLoneSurrogates(r.text) }, truncated: false };
313
325
  }
@@ -315,9 +327,9 @@ export function createFetchProvider({ resolveApiKey, logger, acceptLanguage = ()
315
327
  else errors.push(`direct: ${r.contentType || "unknown type"} ${r.text.length}B`);
316
328
  } catch (e) { errors.push(`direct: ${e.message}`); }
317
329
 
318
- // T1.5:系统浏览器无头渲染(执行 JS 过挑战,抓直连拿不到的页面;无浏览器自动跳过)
330
+ // T1.5:系统浏览器无头渲染(执行 JS 过挑战,抓直连拿不到的页面;无浏览器或设置里关掉时跳过)
319
331
  const browserPath = findSystemBrowser();
320
- if (browserPath) {
332
+ if (browserEnabled() && browserPath) {
321
333
  try {
322
334
  const html = await browserDumpDom(browserPath, url, { signal });
323
335
  if (html && html.length >= T1_MIN_CHARS && !/403 Forbidden|\bcaptcha\b/i.test(html.slice(0, 3000))) {
@@ -329,23 +341,31 @@ export function createFetchProvider({ resolveApiKey, logger, acceptLanguage = ()
329
341
  }
330
342
  }
331
343
 
332
- // T2:exa contents($1/1000 页)——直连失败(反爬/JS/过短)时承接;firecrawl 额度保护:仅在本层失败后才走 T3
333
- const exaKey = await resolveApiKey("EXA_API_KEY", "exaApiKey").catch(() => undefined);
334
- if (exaKey) {
344
+ // T2/T3:exa 与 firecrawl 的先后顺序可在设置页切换;crawl4ai 固定最后。
345
+ const exaTier = async () => {
346
+ const exaKey = await resolveApiKey("EXA_API_KEY", "exaApiKey").catch(() => undefined);
347
+ if (!exaKey) return null;
335
348
  try {
336
349
  const text = await callExa(url, exaKey, signal);
337
350
  if (text.trim().length >= T1_MIN_CHARS) return { url, statusCode: 200, body: { kind: "text", content: stripLoneSurrogates(text) }, truncated: false };
338
351
  errors.push("exa: short content");
339
352
  } catch (e) { errors.push(`exa: ${e.message}`); }
340
- }
341
-
342
- const firecrawlKey = await resolveApiKey("FIRECRAWL_API_KEY", "firecrawlApiKey").catch(() => undefined);
343
- if (firecrawlKey) {
353
+ return null;
354
+ };
355
+ const firecrawlTier = async () => {
356
+ const firecrawlKey = await resolveApiKey("FIRECRAWL_API_KEY", "firecrawlApiKey").catch(() => undefined);
357
+ if (!firecrawlKey) return null;
344
358
  try {
345
359
  const md = await callFirecrawl(url, firecrawlKey, signal);
346
360
  if (md.trim().length >= T1_MIN_CHARS) return { url, statusCode: 200, body: { kind: "text", content: stripLoneSurrogates(md) }, truncated: false };
347
361
  errors.push("firecrawl: short content");
348
362
  } catch (e) { errors.push(`firecrawl: ${e.message}`); }
363
+ return null;
364
+ };
365
+ const order = prefer() === "firecrawl" ? [firecrawlTier, exaTier] : [exaTier, firecrawlTier];
366
+ for (const tier of order) {
367
+ const hit = await tier();
368
+ if (hit) return hit;
349
369
  }
350
370
 
351
371
  const crawl4aiKey = await resolveApiKey("CRAWL4AI_API_KEY", undefined).catch(() => undefined);
package/lib/index.js CHANGED
@@ -1863,6 +1863,10 @@ const Config = z.object({
1863
1863
  bingMarket: z.string().default("zh-CN").volatile(),
1864
1864
  // 是否在 web.fetchProvider 为空/出厂默认 http 时接管 fetch(#83:显式 pin http 的用户可关掉)。
1865
1865
  fetchProviderTakeover: z.boolean().default(true).volatile(),
1866
+ // T1.5 headless browser rendering (default on, matching 0.9.x behaviour).
1867
+ browserFetch: z.boolean().default(true).volatile(),
1868
+ // Which keyed tier runs first after direct/browser: "exa" (default) or "firecrawl".
1869
+ fetchPrefer: z.string().default("exa").volatile(),
1866
1870
  safeSearch: z.string().default("off").volatile(),
1867
1871
  searxngInstances: z.array(z.string()).volatile(),
1868
1872
  // degoog(自建搜索聚合器,见 https://github.com/degoog-org/degoog):需要自己的实例,默认不启用。
@@ -2845,6 +2849,8 @@ function apply(ctx, config) {
2845
2849
  logger,
2846
2850
  // #92:web_fetch 不经过 searchOnce,所以这里按当前配置现算,而不是复用上次搜索留下的值。
2847
2851
  acceptLanguage: () => acceptLanguageFor(current()),
2852
+ browserEnabled: () => current().browserFetch !== false,
2853
+ prefer: () => (current().fetchPrefer === "firecrawl" ? "firecrawl" : "exa"),
2848
2854
  });
2849
2855
  registerOnce(() => ctx.web.registerFetchProvider(fetchProvider), fetchProvider, "fetch provider");
2850
2856
 
package/lib/ssrf.js ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * SSRF guard for web_fetch. The agent can ask the plugin to fetch any HTTPS URL;
3
+ * without this a page could point at loopback, private networks or cloud metadata
4
+ * endpoints and have their content returned as "web" text.
5
+ */
6
+ import dns from "node:dns";
7
+ import net from "node:net";
8
+
9
+ function ipv4Parts(address) {
10
+ const parts = address.split(".").map((part) => Number(part));
11
+ return parts.length === 4 && parts.every((part) => Number.isInteger(part) && part >= 0 && part <= 255) ? parts : null;
12
+ }
13
+
14
+ function isPublicIPv4(address) {
15
+ const parts = ipv4Parts(address);
16
+ if (parts === null) return false;
17
+ const [a, b, c] = parts;
18
+ if (a === 0 || a === 10 || a === 127) return false;
19
+ if (a === 169 && b === 254) return false;
20
+ if (a === 172 && b >= 16 && b <= 31) return false;
21
+ if (a === 192 && b === 168) return false;
22
+ if (a === 100 && b >= 64 && b <= 127) return false;
23
+ if (a === 192 && b === 0 && (c === 0 || c === 2)) return false;
24
+ if (a === 198 && (b === 18 || b === 19)) return false;
25
+ if (a === 198 && b === 51 && c === 100) return false;
26
+ if (a === 203 && b === 0 && c === 113) return false;
27
+ if (a >= 224) return false;
28
+ return true;
29
+ }
30
+
31
+ function isPublicIPv6(address) {
32
+ const value = address.toLowerCase();
33
+ if (value === "::" || value === "::1") return false;
34
+ if (value.startsWith("::ffff:")) return isPublicIPv4(value.slice(7));
35
+ if (value.startsWith("fc") || value.startsWith("fd")) return false;
36
+ if (/^fe[89ab]/.test(value)) return false;
37
+ if (value.startsWith("ff")) return false;
38
+ if (value.startsWith("2001:db8")) return false;
39
+ return true;
40
+ }
41
+
42
+ /** True only for globally routable addresses; unknown input is treated as unsafe. */
43
+ export function isPublicAddress(address) {
44
+ const family = net.isIP(String(address));
45
+ if (family === 4) return isPublicIPv4(String(address));
46
+ if (family === 6) return isPublicIPv6(String(address));
47
+ return false;
48
+ }
49
+
50
+ function bareHost(hostname) {
51
+ return String(hostname).replace(/^\[/, "").replace(/\]$/, "");
52
+ }
53
+
54
+ /** dns.lookup replacement that refuses to connect to private addresses (redirects included). */
55
+ export function safeLookup(hostname, options, callback) {
56
+ const host = bareHost(hostname);
57
+ dns.lookup(host, { ...options, all: true }, (error, addresses) => {
58
+ if (error) {
59
+ callback(error);
60
+ return;
61
+ }
62
+ const list = Array.isArray(addresses) ? addresses : [];
63
+ const blocked = list.find((entry) => !isPublicAddress(entry.address));
64
+ if (blocked) {
65
+ callback(new Error(`SSRF blocked: ${host} resolves to private address ${blocked.address}`));
66
+ return;
67
+ }
68
+ if (options?.all) {
69
+ callback(null, list);
70
+ return;
71
+ }
72
+ callback(null, list[0]?.address, list[0]?.family);
73
+ });
74
+ }
75
+
76
+ /**
77
+ * Reject non-HTTPS URLs and hosts that resolve (or literally point) to a private
78
+ * address. A custom lookup is allowed for tests.
79
+ */
80
+ export async function assertPublicUrl(rawUrl, { lookup = dns.promises.lookup } = {}) {
81
+ let target;
82
+ try {
83
+ target = new URL(String(rawUrl ?? ""));
84
+ } catch {
85
+ throw new Error("invalid URL");
86
+ }
87
+ if (target.protocol !== "https:") throw new Error(`only https URLs are supported (got "${target.protocol}")`);
88
+ if (target.username || target.password) throw new Error("URLs with embedded credentials are not allowed");
89
+ const host = bareHost(target.hostname);
90
+ if (host === "") throw new Error("URL has no host");
91
+ if (net.isIP(host)) {
92
+ if (!isPublicAddress(host)) throw new Error(`SSRF blocked: ${host} is a private address`);
93
+ return target;
94
+ }
95
+ let addresses;
96
+ try {
97
+ addresses = await lookup(host, { all: true });
98
+ } catch {
99
+ throw new Error(`cannot resolve host "${host}"`);
100
+ }
101
+ const list = Array.isArray(addresses) ? addresses : [addresses];
102
+ const blocked = list.find((entry) => !isPublicAddress(entry?.address ?? entry));
103
+ if (blocked) {
104
+ throw new Error(`SSRF blocked: ${host} resolves to private address ${blocked.address ?? blocked}`);
105
+ }
106
+ if (list.length === 0) throw new Error(`cannot resolve host "${host}"`);
107
+ return target;
108
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-free-search",
3
- "version": "0.9.37",
3
+ "version": "0.9.38",
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",