@deepseek-ai/dsh-web-fetch-http 0.2.1-rc.4 → 0.2.2-alpha.2

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.i18n.yaml CHANGED
@@ -3,14 +3,14 @@
3
3
  # After editing either side, bring the other along and re-record with:
4
4
  # pnpm run verify-translation-pairing --write packages/web/web-fetch-http/README.md
5
5
  /:
6
- en: a55f23f2363fdbd6
7
- zh: b1fd7328e041ec52
6
+ en: dba7f5089d194048
7
+ zh: 956905ee19f6f362
8
8
  /deepseek-ai-dsh-web-fetch-http:
9
9
  en: 2e839bfc4c365701
10
10
  zh: 62dd5239ae93471c
11
11
  /deepseek-ai-dsh-web-fetch-http/summary:
12
- en: 88157c32f36635d5
13
- zh: a149d576df0349bc
12
+ en: afb0ecfdd563bced
13
+ zh: 734f74bf506e34e2
14
14
  /deepseek-ai-dsh-web-fetch-http/table-of-contents:
15
15
  en: d152484eb41ac6b4
16
16
  zh: 09388d293f9be9cb
@@ -18,8 +18,8 @@
18
18
  en: 630b12516d53e905
19
19
  zh: eed124cfe9c8dc1f
20
20
  /deepseek-ai-dsh-web-fetch-http/use-this-package/when-to-choose-it:
21
- en: eb52e77279c21d6f
22
- zh: 0560e89caa377bfc
21
+ en: acb7517f571c38b8
22
+ zh: 8ee9da18953ab65e
23
23
  /deepseek-ai-dsh-web-fetch-http/use-this-package/minimal-configuration:
24
24
  en: e4534189d5230861
25
25
  zh: 5905731d7b5d9c60
@@ -27,23 +27,23 @@
27
27
  en: 2d18cdcc9b53dd0f
28
28
  zh: 3bc6ca7c5933ee5d
29
29
  /deepseek-ai-dsh-web-fetch-http/use-this-package/transport-behavior:
30
- en: c432147daf2877cf
31
- zh: c14d507dd66e124a
30
+ en: 4c5618124337446e
31
+ zh: 45c7378c8b0bba45
32
32
  /deepseek-ai-dsh-web-fetch-http/use-this-package/failures-and-recovery:
33
- en: 35407f106dc65deb
34
- zh: 02118072fba68b8f
33
+ en: 34095d9d4231d73a
34
+ zh: be0ed903adbb124f
35
35
  /deepseek-ai-dsh-web-fetch-http/understand-the-implementation:
36
36
  en: 9842c69ad3636bb3
37
37
  zh: 3cdc3f816cbdd0cb
38
38
  /deepseek-ai-dsh-web-fetch-http/understand-the-implementation/design-philosophy:
39
- en: a8d806f0706f02e2
40
- zh: d922732a5b7e88bd
39
+ en: 422128dac5eebdde
40
+ zh: 25ba5f49b305a056
41
41
  /deepseek-ai-dsh-web-fetch-http/understand-the-implementation/source-map:
42
- en: 023ca0c9a9ef4968
43
- zh: 74a5785a493f5111
42
+ en: 1f355ec2726ff61b
43
+ zh: 076a0c259c94f22a
44
44
  /deepseek-ai-dsh-web-fetch-http/understand-the-implementation/read-path:
45
- en: 749c0ffeac145807
46
- zh: 1468821a33a9518a
45
+ en: 4836d06bc065477d
46
+ zh: 5a7ddc805a7c67d8
47
47
  /deepseek-ai-dsh-web-fetch-http/further-exploration:
48
48
  en: eeaaf0b455673a1c
49
49
  zh: 0874f9f44ff9a220
@@ -54,8 +54,8 @@
54
54
  en: 40294c1c31b74824
55
55
  zh: d75d48f485447a74
56
56
  /deepseek-ai-dsh-web-fetch-http/known-limitations-and-deferred-work:
57
- en: 4d935fd8f466a234
58
- zh: c398eb7aa737f5ea
57
+ en: 74d63a0c0e7649e1
58
+ zh: 73a59fcca72daba5
59
59
  /deepseek-ai-dsh-web-fetch-http/known-limitations-and-deferred-work/dev-note:
60
60
  en: e67f633dc6fe7773
61
61
  zh: 3bb0c20c93f16f98
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  ---
2
- description: "The anonymous public HTTP(S) fetch backend for ctx.web: how deployments mount bounded, safe URL retrieval with same-origin redirects and text-only decoding."
2
+ description: "The anonymous HTTP(S) fetch backend for ctx.web: how deployments mount bounded URL retrieval with same-origin redirects and text-only decoding."
3
3
  kind: "package-reference"
4
4
  ---
5
5
 
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
9
9
 
10
10
  ## Summary
11
11
 
12
- With `dsh-web-fetch-http`, the harness can fetch public HTTP(S) pages through the web service (`ctx.web`) and get their status code plus bounded, decoded content without sending credentials. Choose it when a composition needs safe retrieval with URL validation, public-address resolution, connection pinning, same-origin redirects, byte and character caps, and an explicit product `User-Agent`. It returns non-2xx responses as results rather than errors, and rejects non-public destinations, binary data, and unsupported content types. The model-facing `web_fetch` tool lives in `dsh-tool-web`, which renders this provider's bodies.
12
+ With `dsh-web-fetch-http`, the harness can fetch HTTP(S) pages through the web service (`ctx.web`) and get their status code plus bounded, decoded content without sending credentials. Choose it when a composition needs retrieval with URL validation, same-origin redirects, byte and character caps, and an explicit product `User-Agent`. It returns non-2xx responses as results rather than errors, and rejects binary data and unsupported content types. It does not restrict destination addresses, so it reaches loopback and private-network hosts. The model-facing `web_fetch` tool lives in `dsh-tool-web`, which renders this provider's bodies.
13
13
 
14
14
  ## Table of Contents
15
15
 
@@ -29,7 +29,7 @@ Mount the provider in a composition that already loads the web service; it regis
29
29
 
30
30
  ### When to choose it
31
31
 
32
- Choose this backend when a deployment must fetch public pages with bounded output and safe transport: no credentials are sent, every resolved address must be public, each connection is pinned to the validated answer set, redirects cannot escape the origin, and every response is capped.
32
+ Choose this backend when a deployment must fetch pages with bounded output: no credentials are sent, redirects cannot escape the origin, and every response is capped.
33
33
 
34
34
  ### Minimal configuration
35
35
 
@@ -61,11 +61,13 @@ const page = await ctx.web.fetch({ url: 'https://example.com' })
61
61
 
62
62
  ### Transport behavior
63
63
 
64
- The provider keeps requests anonymous and bounded: it accepts only `http:` and `https:` URLs without embedded credentials and rejects URLs over 2,048 characters. It resolves each hostname once, rejects the complete result if any IPv4 or IPv6 address is not public unicast, and pins the connection to that validated set. IPv6 checks discover the active DNS64 prefix and reject translations to non-public IPv4. Each same-origin redirect repeats resolution and pinning; cross-origin redirects fail and require a fresh call. The provider also enforces byte, character, hop, and time caps, rejects unsupported content types, and sends an explicit product `User-Agent`.
64
+ The provider keeps requests anonymous and bounded: it accepts only `http:` and `https:` URLs without embedded credentials and rejects URLs over 2,048 characters. Requests go through the process-wide dispatcher, so the installed proxy policy applies and the system resolver chooses the address; any destination address is allowed. Same-origin redirects are followed; cross-origin redirects fail and require a fresh call. The provider also enforces byte, character, hop, and time caps, rejects unsupported content types, and sends an explicit product `User-Agent`.
65
+
66
+ A malformed comma- or whitespace-joined charset declaration containing a UTF-8 label (such as `charset=utf-8,gbk`) is decoded strictly as UTF-8. Recovery rejects invalid UTF-8 without trying another encoding. When the byte cap cuts a character, recovery omits the incomplete suffix and returns `truncated: true`; a complete response using recovery must pass the EOF check. Valid single-label declarations retain ordinary replacement decoding.
65
67
 
66
68
  ### Failures and recovery
67
69
 
68
- Failures throw `WebError` with a machine-routable code: `WEB_INVALID_URL`, `WEB_BLOCKED_URL`, `WEB_FETCH_TOO_LARGE`, `WEB_FETCH_TIMEOUT`, `WEB_REDIRECT_BLOCKED`, `WEB_UNSUPPORTED_CONTENT_TYPE`, `WEB_ABORTED`, or `WEB_PROVIDER_ERROR`. Direct callers can route on the code; the model-facing `web_fetch` tool surfaces the failure text to the model under its own error wrapper.
70
+ Failures throw `WebError` with a machine-routable code: `WEB_INVALID_URL`, `WEB_BLOCKED_URL`, `WEB_FETCH_TOO_LARGE`, `WEB_FETCH_TIMEOUT`, `WEB_REDIRECT_BLOCKED`, `WEB_UNSUPPORTED_CONTENT_TYPE`, `WEB_ABORTED`, or `WEB_PROVIDER_ERROR`. `WEB_UNSUPPORTED_CONTENT_TYPE` covers unsupported media types, unsupported charset declarations, and invalid UTF-8 during malformed-declaration recovery. Direct callers can route on the code; the model-facing `web_fetch` tool surfaces the failure text to the model under its own error wrapper.
69
71
 
70
72
  -----
71
73
 
@@ -81,7 +83,7 @@ This section explains the design decisions behind the provider; the observable b
81
83
 
82
84
  The package is built on one separation and one layered timeout:
83
85
 
84
- - **Safe retrieval vs. presentation.** This provider owns URL validation, public-address enforcement, connection pinning, HTTP transport, redirect policy, caps, charset decoding, and binary rejection; `dsh-tool-web` owns HTML→markdown and truncation formatting. A non-2xx response is data, not failure.
86
+ - **Retrieval vs. presentation.** This provider owns URL validation, HTTP transport, redirect policy, caps, charset decoding, and binary rejection; `dsh-tool-web` owns HTML→markdown and truncation formatting. A non-2xx response is data, not failure.
85
87
  - **Two timeout layers.** The provider's `timeoutMs` is a resource backstop for direct `ctx.web.fetch()` callers; the model-facing tool-call budget belongs to `dsh-tool-call-timeout-policy`, which arms `exec.signal`. When the outer deadline fires first the provider reports `WEB_ABORTED` and the policy replaces it with `TOOL_TIMEOUT`; `WEB_FETCH_TIMEOUT` therefore identifies a direct service caller whose provider budget elapsed.
86
88
 
87
89
  ### Source map
@@ -89,13 +91,12 @@ The package is built on one separation and one layered timeout:
89
91
  | File | Role |
90
92
  |---|---|
91
93
  | [`src/index.ts`](src/index.ts) | Plugin entry: config schema, limit validation, provider registration |
92
- | [`src/provider.ts`](src/provider.ts) | The `HttpFetchProvider`: pinned transport, redirect following, capped reads, charset decoding |
93
- | [`src/network.ts`](src/network.ts) | Public-address resolution, DNS64 discovery, and connection pinning |
94
+ | [`src/provider.ts`](src/provider.ts) | The `HttpFetchProvider`: transport, redirect following, capped reads, charset decoding |
94
95
  | [`src/policy.ts`](src/policy.ts) | URL validation, same-origin checks, content-type classification, charset parsing |
95
96
 
96
97
  ### Read path
97
98
 
98
- A fetch validates the URL, resolves the hostname once, rejects the complete answer set when any address is not public, and pins the connection to the accepted addresses. It repeats that check for each same-origin redirect; a cross-origin redirect or non-public target fails before response bytes are accepted. The final response is classified by `Content-Type`, decoded from its declared charset, and read under the byte cap; the decoded text is then truncated to the character cap.
99
+ A fetch validates the URL and sends the request. It repeats URL validation for each same-origin redirect; a cross-origin redirect fails before response bytes are accepted. The final response is classified by `Content-Type`, decoded from its declared charset (malformed declarations containing UTF-8 use strict UTF-8 recovery), and read under the byte cap; the decoded text is then truncated to the character cap.
99
100
 
100
101
  </details>
101
102
 
@@ -131,8 +132,10 @@ No direct invalidation; the named consumer owns any request-prefix changes.
131
132
 
132
133
  These limits define when the provider is unsafe or a poor fit. They are current package constraints.
133
134
 
135
+ - **Private destinations are reachable** — loopback, private-network, and cloud metadata addresses are fetched like any other host. A deployment that must keep the model away from them needs a `tools/pre-execute` policy, network confinement, or no fetch tool.
134
136
  - **Only textual content decodes** — html/xhtml and `text/*` plus JSON/XML families; a missing `Content-Type` or any binary type throws `WEB_UNSUPPORTED_CONTENT_TYPE`, and text-extractable PDF decoding is named deferred work.
135
- - **Charset comes only from the `Content-Type` header** (UTF-8 default) — an HTML `<meta charset>` declaration is ignored, and a declared-but-unrecognized charset label throws rather than falling back.
137
+ - **Charset comes only from the `Content-Type` header** (UTF-8 default) — an HTML `<meta charset>` declaration is ignored, and unsupported declarations without a UTF-8 label throw.
138
+ - **UTF-8 recovery is a preference, not encoding detection** — bytes can be valid as both UTF-8 and another encoding, even in a long response. Recovery chooses UTF-8 in that case; malformed declarations without a UTF-8 label remain unsupported.
136
139
 
137
140
  <a id="dev-note"></a>
138
141
  ### Dev Note
package/README.zh.md CHANGED
@@ -1,5 +1,5 @@
1
1
  ---
2
- description: "ctx.web 的匿名公共 HTTP(S) 抓取后端:部署方如何挂载有界、安全的 URL 抓取,含同源重定向与仅文本解码。"
2
+ description: "ctx.web 的匿名 HTTP(S) 抓取后端:部署方如何挂载有界的 URL 抓取,含同源重定向与仅文本解码。"
3
3
  kind: "package-reference"
4
4
  ---
5
5
 
@@ -9,7 +9,7 @@ kind: "package-reference"
9
9
 
10
10
  ## 概述
11
11
 
12
- 有了 `dsh-web-fetch-http`,harness 可以通过 web 服务(`ctx.web`)抓取公共 HTTP(S) 页面,并在不发送凭据的情况下获得状态码与有界、解码后的内容。当组合需要 URL 校验、公开地址解析、连接固定、仅同源重定向、字节和字符上限及显式产品 `User-Agent` 时选择它。它把非 2xx 响应作为结果而非错误返回,并拒绝非公开目标、二进制数据与不受支持的内容类型。面向模型的 `web_fetch` 工具位于 `dsh-tool-web`,由它渲染本提供方的正文。
12
+ 有了 `dsh-web-fetch-http`,harness 可以通过 web 服务(`ctx.web`)抓取 HTTP(S) 页面,并在不发送凭据的情况下获得状态码与有界、解码后的内容。当组合需要 URL 校验、仅同源重定向、字节和字符上限及显式产品 `User-Agent` 时选择它。它把非 2xx 响应作为结果而非错误返回,并拒绝二进制数据与不受支持的内容类型。它不限制目标地址,因此可以访问 loopback 与内网主机。面向模型的 `web_fetch` 工具位于 `dsh-tool-web`,由它渲染本提供方的正文。
13
13
 
14
14
  ## 目录
15
15
 
@@ -29,7 +29,7 @@ kind: "package-reference"
29
29
 
30
30
  ### 何时选择
31
31
 
32
- 当部署必须以有界输出和安全传输抓取公共页面时选择此后端:不发送凭据,每个已解析地址必须是公共地址,每次连接都固定到已校验的地址集合,重定向无法逃出源站,每个响应都有上限。
32
+ 当部署必须以有界输出抓取页面时选择此后端:不发送凭据,重定向无法逃出源站,每个响应都有上限。
33
33
 
34
34
  ### 最小配置
35
35
 
@@ -61,11 +61,13 @@ const page = await ctx.web.fetch({ url: 'https://example.com' })
61
61
 
62
62
  ### 传输行为
63
63
 
64
- 提供方保持请求匿名且有界:只接受不含内嵌凭据且不超过 2,048 个字符的 `http:` 与 `https:` URL。它只解析一次主机名;只要结果中有任何 IPv4 或 IPv6 地址不是公共单播地址,就拒绝整个结果,并把连接固定到已校验的地址集合。IPv6 检查会发现活动 DNS64 前缀,并拒绝指向非公开 IPv4 的转换地址。每次同源重定向都会重复解析与固定;跨源重定向会失败并要求重新调用。提供方还强制执行字节、字符、跳数和时间上限,拒绝不支持的内容类型,并发送显式产品 `User-Agent`。
64
+ 提供方保持请求匿名且有界:只接受不含内嵌凭据且不超过 2,048 个字符的 `http:` 与 `https:` URL。请求经过进程级 dispatcher,因此已安装的代理策略生效,目标地址由系统解析器选择;任何目标地址都被允许。同源重定向会被跟随;跨源重定向会失败并要求重新调用。提供方还强制执行字节、字符、跳数和时间上限,拒绝不支持的内容类型,并发送显式产品 `User-Agent`。
65
+
66
+ 对于以逗号或空白拼接、且含有 UTF-8 标签的畸形 charset 声明(例如 `charset=utf-8,gbk`),提供方严格按 UTF-8 解码。恢复路径拒绝非法 UTF-8,不会尝试其他编码。字节上限在字符内部截断时,恢复路径省略不完整的末尾序列并返回 `truncated: true`;使用恢复路径的完整响应必须通过 EOF 检查。合法的单标签声明仍在遇到非法字节时使用替换字符。
65
67
 
66
68
  ### 失败与恢复
67
69
 
68
- 失败会抛出 `WebError`,其中包含可供程序路由的错误码:`WEB_INVALID_URL`、`WEB_BLOCKED_URL`、`WEB_FETCH_TOO_LARGE`、`WEB_FETCH_TIMEOUT`、`WEB_REDIRECT_BLOCKED`、`WEB_UNSUPPORTED_CONTENT_TYPE`、`WEB_ABORTED` 或 `WEB_PROVIDER_ERROR`。直接调用方可以按错误码路由;面向模型的 `web_fetch` 工具会在自己的错误包装层内把失败文本呈现给模型。
70
+ 失败会抛出 `WebError`,其中包含可供程序路由的错误码:`WEB_INVALID_URL`、`WEB_BLOCKED_URL`、`WEB_FETCH_TOO_LARGE`、`WEB_FETCH_TIMEOUT`、`WEB_REDIRECT_BLOCKED`、`WEB_UNSUPPORTED_CONTENT_TYPE`、`WEB_ABORTED` 或 `WEB_PROVIDER_ERROR`。`WEB_UNSUPPORTED_CONTENT_TYPE` 涵盖不支持的媒体类型、不支持的 charset 声明,以及畸形声明恢复过程中遇到的非法 UTF-8。直接调用方可以按错误码路由;面向模型的 `web_fetch` 工具会在自己的错误包装层内把失败文本呈现给模型。
69
71
 
70
72
  -----
71
73
 
@@ -81,7 +83,7 @@ const page = await ctx.web.fetch({ url: 'https://example.com' })
81
83
 
82
84
  本包基于一项职责分离和一套分层超时机制:
83
85
 
84
- - **安全获取与呈现分离。** 本提供方拥有 URL 校验、公开地址强制规则、连接固定、HTTP 传输、重定向策略、上限、charset 解码与二进制拒绝;`dsh-tool-web` 拥有 HTML→markdown 与截断格式化。非 2xx 响应是数据,不是失败。
86
+ - **获取与呈现分离。** 本提供方拥有 URL 校验、HTTP 传输、重定向策略、上限、charset 解码与二进制拒绝;`dsh-tool-web` 拥有 HTML→markdown 与截断格式化。非 2xx 响应是数据,不是失败。
85
87
  - **两层超时。** 提供方的 `timeoutMs` 是直接 `ctx.web.fetch()` 调用方的资源兜底;面向模型的工具调用预算属于 `dsh-tool-call-timeout-policy`,由它触发 `exec.signal`。外层截止期限先到时,提供方报告 `WEB_ABORTED`,策略再以 `TOOL_TIMEOUT` 替换;因此 `WEB_FETCH_TIMEOUT` 标识的是提供方预算耗尽的直接服务调用方。
86
88
 
87
89
  ### 源码地图
@@ -89,13 +91,12 @@ const page = await ctx.web.fetch({ url: 'https://example.com' })
89
91
  | 文件 | 职责 |
90
92
  |---|---|
91
93
  | [`src/index.ts`](src/index.ts) | 插件入口:配置 schema、上限验证、提供方注册 |
92
- | [`src/provider.ts`](src/provider.ts) | `HttpFetchProvider`:固定连接、重定向跟随、有界读取、charset 解码 |
93
- | [`src/network.ts`](src/network.ts) | 公开地址解析、DNS64 发现与连接固定 |
94
+ | [`src/provider.ts`](src/provider.ts) | `HttpFetchProvider`:传输、重定向跟随、有界读取、charset 解码 |
94
95
  | [`src/policy.ts`](src/policy.ts) | URL 校验、同源检查、内容类型分类、charset 解析 |
95
96
 
96
97
  ### 读取路径
97
98
 
98
- 抓取先校验 URL,只解析一次主机名,结果中只要有非公开地址就拒绝,并把连接固定到已接受地址。每次同源重定向都重复该检查;跨源重定向或非公开目标在接收响应字节前失败。最终响应按 `Content-Type` 分类、依声明的 charset 解码,并在字节上限内读取;解码后的文本再截断到字符上限。
99
+ 抓取先校验 URL,再发送请求。每次同源重定向都重复 URL 校验;跨源重定向在接收响应字节前失败。最终响应按 `Content-Type` 分类、依声明的 charset 解码(含有 UTF-8 的畸形声明使用严格 UTF-8 恢复),并在字节上限内读取;解码后的文本再截断到字符上限。
99
100
 
100
101
  </details>
101
102
 
@@ -131,8 +132,10 @@ const page = await ctx.web.fetch({ url: 'https://example.com' })
131
132
 
132
133
  这些限制说明提供方何时不安全或不合适。它们是当前包约束。
133
134
 
135
+ - **可以访问私有目标**——loopback、内网与云元数据地址与其他主机一样会被抓取。需要阻止模型访问这些地址的部署必须添加 `tools/pre-execute` 策略、网络隔离,或不挂载抓取工具。
134
136
  - **只解码文本内容**——包括 html/xhtml 与 `text/*` 加 JSON/XML 家族;缺少 `Content-Type` 或任何二进制类型都会抛出 `WEB_UNSUPPORTED_CONTENT_TYPE`,可提取文本的 PDF 解码属于明确的延期工作。
135
- - **charset 只来自 `Content-Type` 标头**(默认 UTF-8)——HTML `<meta charset>` 声明会被忽略;声明但无法识别的 charset 标签会抛出异常,而非回退。
137
+ - **charset 只来自 `Content-Type` 标头**(默认 UTF-8)——HTML `<meta charset>` 声明会被忽略;不支持且不含 UTF-8 标签的声明会抛出异常。
138
+ - **UTF-8 恢复是一种优先规则,不是编码检测**——同一组字节可能同时是合法的 UTF-8 和其他编码,长响应也不例外。恢复路径在这种情况下选择 UTF-8;不含 UTF-8 标签的畸形声明仍不受支持。
136
139
 
137
140
  <a id="dev-note"></a>
138
141
  ### 开发备注
package/lib/index.js CHANGED
@@ -1,266 +1,16 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
2
  import { WebError } from "@deepseek-ai/dsh-web";
3
3
  import { deadline, timeoutOf } from "@deepseek-ai/dsh-timeout";
4
- import { proxyRouteFor } from "@deepseek-ai/dsh-http-proxy";
5
- import { lookup } from "node:dns/promises";
6
- import { isIP } from "node:net";
7
- import ipaddr from "ipaddr.js";
8
- //#region lib/types/network.js
9
- /**
10
- * Public-network resolution and address-pinned HTTP transport for `web-fetch-http`.
11
- * One DNS answer set is validated before Undici receives it through a custom lookup,
12
- * so the connection cannot resolve the hostname again to a private address.
13
- *
14
- * @module @deepseek-ai/dsh-web-fetch-http/network
15
- */
16
- /** RFC 6052 prefix lengths that may carry an IPv4 destination through NAT64. */
17
- const RFC6052_PREFIX_LENGTHS = [
18
- 32,
19
- 40,
20
- 48,
21
- 56,
22
- 64,
23
- 96
24
- ];
25
- const IPV4ONLY_DISCOVERY_HOST = "ipv4only.arpa";
26
- const IPV4ONLY_SENTINELS = new Set(["192.0.0.170", "192.0.0.171"]);
27
- /**
28
- * Return whether an address is globally reachable unicast. IPv4-mapped IPv6 is
29
- * classified by its embedded IPv4 address; transition and translation prefixes
30
- * remain blocked because their eventual IPv4 destination cannot be pinned here.
31
- *
32
- * @param input - textual IPv4 or IPv6 address.
33
- * @returns true only for a public unicast destination.
34
- */
35
- function isPublicIpAddress(input) {
36
- let parsed;
37
- try {
38
- parsed = ipaddr.parse(stripIpv6Brackets(input));
39
- } catch {
40
- return false;
41
- }
42
- if (parsed instanceof ipaddr.IPv4) return parsed.range() === "unicast";
43
- if (parsed.isIPv4MappedAddress()) return parsed.toIPv4Address().range() === "unicast";
44
- return parsed.range() === "unicast";
45
- }
46
- /**
47
- * Resolve a hostname once and reject the complete answer set if any destination
48
- * is not public. The returned addresses are the only ones the transport may use.
49
- *
50
- * @param hostname - URL hostname, including brackets when it is an IPv6 literal.
51
- * @param signal - aborts the wait for system resolution; an in-flight OS lookup may finish unused.
52
- * @param resolver - lookup implementation, overridden only by focused tests.
53
- * @returns the validated, non-empty address set.
54
- */
55
- async function resolvePublicAddresses(hostname, signal, resolver = lookup) {
56
- const unbracketed = stripIpv6Brackets(hostname);
57
- const literalFamily = isIP(unbracketed);
58
- const resolved = literalFamily === 0 ? await raceWithSignal(resolver(unbracketed, {
59
- all: true,
60
- order: "verbatim"
61
- }), signal) : [{
62
- address: unbracketed,
63
- family: literalFamily
64
- }];
65
- if (resolved.length === 0) throw new WebError(`hostname "${hostname}" resolved to no addresses`, "WEB_PROVIDER_ERROR");
66
- const nat64Prefixes = resolved.some((entry) => entry.family === 6 && isIP(entry.address) === 6) ? await discoverNat64Prefixes(signal, resolver) : [];
67
- const addresses = [];
68
- for (const entry of resolved) {
69
- if (entry.family !== 4 && entry.family !== 6 || isIP(entry.address) !== entry.family) throw new WebError(`hostname "${hostname}" resolved to an invalid IP address`, "WEB_PROVIDER_ERROR");
70
- if (!isPublicIpAddress(entry.address)) throw new WebError(`URL hostname "${hostname}" resolves to a non-public IP address`, "WEB_BLOCKED_URL");
71
- const translatedIpv4 = translatedIpv4Address(entry.address, nat64Prefixes);
72
- if (translatedIpv4 !== void 0 && !isPublicIpAddress(translatedIpv4)) throw new WebError(`URL hostname "${hostname}" resolves through NAT64 to a non-public IPv4 address`, "WEB_BLOCKED_URL");
73
- addresses.push({
74
- address: entry.address,
75
- family: entry.family
76
- });
77
- }
78
- return addresses;
79
- }
80
- /** Discover the active DNS64 prefix set using RFC 7050's reserved hostname. */
81
- async function discoverNat64Prefixes(signal, resolver) {
82
- const discovered = await raceWithSignal(resolver(IPV4ONLY_DISCOVERY_HOST, {
83
- all: true,
84
- order: "verbatim"
85
- }), signal);
86
- const prefixes = [];
87
- const seen = /* @__PURE__ */ new Set();
88
- for (const entry of discovered) {
89
- if (entry.family !== 6 || isIP(entry.address) !== 6) continue;
90
- const bytes = ipaddr.parse(entry.address).toByteArray();
91
- for (const length of RFC6052_PREFIX_LENGTHS) {
92
- const embedded = embeddedIpv4Address(bytes, length);
93
- if (embedded === void 0 || !IPV4ONLY_SENTINELS.has(embedded)) continue;
94
- const prefixBytes = bytes.slice(0, length / 8);
95
- const key = `${String(length)}:${prefixBytes.join(".")}`;
96
- if (seen.has(key)) continue;
97
- seen.add(key);
98
- prefixes.push({
99
- bytes: prefixBytes,
100
- length
101
- });
102
- }
103
- }
104
- return prefixes;
105
- }
106
- /** Return the RFC 6052-embedded IPv4 address when an IPv6 address matches a discovered prefix. */
107
- function translatedIpv4Address(input, prefixes) {
108
- if (isIP(input) !== 6) return void 0;
109
- const bytes = ipaddr.parse(input).toByteArray();
110
- for (const prefix of prefixes) {
111
- if (!prefix.bytes.every((byte, index) => bytes[index] === byte)) continue;
112
- const embedded = embeddedIpv4Address(bytes, prefix.length);
113
- if (embedded !== void 0) return embedded;
114
- }
115
- }
116
- /** Extract one IPv4 address from an RFC 6052 IPv6 layout. */
117
- function embeddedIpv4Address(bytes, prefixLength) {
118
- if (prefixLength === 96) return bytes.slice(12, 16).join(".");
119
- if (bytes[8] !== 0) return void 0;
120
- const prefixBytes = prefixLength / 8;
121
- const beforeReservedOctet = 8 - prefixBytes;
122
- return [...bytes.slice(prefixBytes, prefixBytes + beforeReservedOctet), ...bytes.slice(9, 13 - beforeReservedOctet)].join(".");
123
- }
124
- /**
125
- * Whether a hostname is an IP literal that {@link resolvePublicAddresses} would refuse.
126
- *
127
- * A proxied hop skips those checks because the proxy resolves the origin, but a literal needs no
128
- * resolution: the address is already stated, and handing it to a proxy running on this machine
129
- * would reach exactly the loopback or private service the checks exist to keep out of reach.
130
- *
131
- * @param hostname - a URL's hostname, bracketed or not.
132
- * @returns true when the host is a literal address no request may be sent to.
133
- */
134
- function isNonPublicIpLiteral(hostname) {
135
- const unbracketed = stripIpv6Brackets(hostname);
136
- return isIP(unbracketed) !== 0 && !isPublicIpAddress(unbracketed);
137
- }
138
- /**
139
- * Fetch through an agent whose lookup callback returns only the already validated address set. The
140
- * URL hostname remains intact for HTTP Host and TLS SNI.
141
- *
142
- * The agent is this request's own because the address set is: pinning is how this package refuses a
143
- * DNS answer that changes between validation and connection, and it may not apply process-wide —
144
- * an operator-configured MCP server or model endpoint on loopback is a supported destination, and
145
- * only the URLs this tool fetches are the model's to choose.
146
- *
147
- * @param url - validated HTTP(S) URL the policy does not route through a proxy.
148
- * @param addresses - public addresses returned by {@link resolvePublicAddresses}.
149
- * @param headers - request headers.
150
- * @param signal - request and body-read cancellation signal.
151
- * @returns a response plus the disposer its consumer must call.
152
- */
153
- async function requestPinned(url, addresses, headers, signal) {
154
- const { Agent, fetch } = await import("undici");
155
- const dispatcher = new Agent({
156
- autoSelectFamily: true,
157
- connect: { lookup: createPinnedLookup(addresses) }
158
- });
159
- try {
160
- return {
161
- response: await fetch(url, {
162
- method: "GET",
163
- redirect: "manual",
164
- headers,
165
- signal,
166
- dispatcher
167
- }),
168
- close: async () => {
169
- await dispatcher.close();
170
- }
171
- };
172
- } catch (error) {
173
- await dispatcher.close();
174
- throw error;
175
- }
176
- }
177
- /**
178
- * Fetch through the dispatcher the proxy policy already installed, letting the proxy resolve the
179
- * origin.
180
- *
181
- * No address set is pinned because none exists to pin: the proxy performs the lookup, and a
182
- * connection pinned to a locally resolved address would reach the origin directly and defeat the
183
- * proxy. The dispatcher is the process-wide one, so hops share its connection pool and no caller
184
- * closes it.
185
- *
186
- * @param dispatcher - the route's dispatcher, from `proxyRouteFor`.
187
- * @param url - validated HTTP(S) URL the policy routes through a proxy.
188
- * @param headers - request headers.
189
- * @param signal - request and body-read cancellation signal.
190
- * @returns a response plus a disposer that releases nothing, so both paths close alike.
191
- */
192
- async function requestVia(dispatcher, url, headers, signal) {
193
- const { fetch } = await import("undici");
194
- return {
195
- response: await fetch(url, {
196
- method: "GET",
197
- redirect: "manual",
198
- headers,
199
- signal,
200
- dispatcher
201
- }),
202
- close: () => Promise.resolve()
203
- };
204
- }
205
- /** Production network operations kept as an object so provider tests can replace resolution only. */
206
- const publicHttpNetwork = {
207
- resolve: resolvePublicAddresses,
208
- request: requestPinned,
209
- requestVia
210
- };
211
- /**
212
- * Build the connector lookup that serves a fixed validated answer set.
213
- *
214
- * @param addresses - public addresses retained from the preceding resolution.
215
- * @returns a Node-compatible lookup callback that performs no network resolution.
216
- */
217
- function createPinnedLookup(addresses) {
218
- return (hostname, options, callback) => {
219
- const family = typeof options.family === "number" ? options.family : options.family === "IPv4" ? 4 : options.family === "IPv6" ? 6 : 0;
220
- const eligible = family === 0 ? addresses : addresses.filter((address) => address.family === family);
221
- const selected = eligible[0];
222
- if (selected === void 0) {
223
- callback(Object.assign(/* @__PURE__ */ new Error(`no validated address for ${hostname} in family ${family}`), {
224
- code: "ENOTFOUND",
225
- hostname
226
- }), options.all === true ? [] : "", family);
227
- return;
228
- }
229
- if (options.all === true) {
230
- callback(null, eligible.map((address) => ({ ...address })));
231
- return;
232
- }
233
- callback(null, selected.address, selected.family);
234
- };
235
- }
236
- /** Race a non-cancellable OS lookup without letting it delay tool cancellation. */
237
- function raceWithSignal(promise, signal) {
238
- const abortError = () => new Error("web fetch aborted during hostname resolution", { cause: signal.reason });
239
- if (signal.aborted) return Promise.reject(abortError());
240
- return new Promise((resolve, reject) => {
241
- const abort = () => {
242
- reject(abortError());
243
- };
244
- signal.addEventListener("abort", abort, { once: true });
245
- promise.then(resolve, reject).finally(() => {
246
- signal.removeEventListener("abort", abort);
247
- });
248
- });
249
- }
250
- /** WHATWG URL retains brackets around IPv6 hostnames; IP parsers do not. */
251
- function stripIpv6Brackets(hostname) {
252
- return hostname.startsWith("[") && hostname.endsWith("]") ? hostname.slice(1, -1) : hostname;
253
- }
254
- //#endregion
255
4
  //#region lib/types/policy.js
256
5
  /**
257
- * URL validation and content-type classification for the local HTTP(S) fetch
258
- * provider — the pure, network-free half. The provider's `fetch()` composes
259
- * these with transport (redirect following, byte caps, decoding).
6
+ * URL validation, content-type classification, and charset resolution for the
7
+ * local HTTP(S) fetch provider — the pure, network-free half. The provider's
8
+ * `fetch()` composes these with transport (redirect following, byte caps,
9
+ * decoding).
260
10
  *
261
11
  * @module @deepseek-ai/dsh-web-fetch-http/policy
262
12
  */
263
- /** Maximum accepted request URL length enforced by the public fetch provider. */
13
+ /** Maximum accepted request URL length enforced by the fetch provider. */
264
14
  const WEB_FETCH_MAX_URL_LENGTH = 2048;
265
15
  /**
266
16
  * Parse a request URL and enforce network-independent transport restrictions:
@@ -295,8 +45,7 @@ function validateFetchUrl(input) {
295
45
  }
296
46
  /**
297
47
  * Two URLs are same-origin when scheme, hostname, and port match. A redirect
298
- * that crosses origins is refused so each new origin requires a fresh tool call
299
- * and public-address validation.
48
+ * that crosses origins is refused so each new origin requires a fresh tool call.
300
49
  *
301
50
  * @param a - one of the two URLs to compare.
302
51
  * @param b - the other URL to compare.
@@ -321,42 +70,47 @@ function classifyContentType(contentType) {
321
70
  if (mime === "application/json" || mime === "application/xml" || mime.endsWith("+json") || mime.endsWith("+xml")) return "text";
322
71
  }
323
72
  /**
324
- * Extract the `charset` parameter from a response `Content-Type`, lower-cased,
325
- * or `undefined` when absent. The provider feeds this label to `TextDecoder`
326
- * so a non-UTF-8 response is decoded with its declared encoding rather than
327
- * silently mangled into replacement characters.
73
+ * Extract the lower-cased `charset` parameter from a response `Content-Type`.
328
74
  *
329
- * @param contentType - the raw `Content-Type` header, or `null` when the
330
- * response carries none.
331
- * @returns the lower-cased charset label, or `undefined` when none is declared.
75
+ * @param contentType - the raw header, or `null` when absent.
76
+ * @returns the charset parameter, or `undefined` when none is declared.
332
77
  */
333
78
  function parseCharset(contentType) {
334
79
  return /;\s*charset\s*=\s*"?([^";]+)"?/i.exec(contentType ?? "")?.[1]?.trim().toLowerCase();
335
80
  }
336
81
  /**
337
- * Build a `TextDecoder` for the declared charset, falling back to UTF-8 when
338
- * none is declared. Throws {@link WebError} `WEB_UNSUPPORTED_CONTENT_TYPE` when
339
- * the label is present but not a charset `TextDecoder` recognizes — better to
340
- * fail loudly than return mojibake.
82
+ * Resolve the declared charset, defaulting to UTF-8 when absent. A malformed
83
+ * comma- or whitespace-joined declaration containing a UTF-8 label uses a fatal
84
+ * UTF-8 decoder; other unsupported declarations throw `WEB_UNSUPPORTED_CONTENT_TYPE`.
85
+ * UTF-8 recovery is a preference, not proof of the original encoding.
341
86
  *
342
- * @param charset - the declared charset label (from {@link parseCharset}), or
343
- * `undefined` to default to UTF-8.
344
- * @returns a decoder for the declared (or defaulted) encoding.
87
+ * @param charset - the declared charset parameter, or `undefined` to default.
88
+ * @returns a decoder; callers must report fatal decoding failures and flush at
89
+ * EOF unless they deliberately truncated the bytes.
345
90
  */
346
91
  function decoderForCharset(charset) {
347
- if (charset === void 0) return new TextDecoder("utf-8");
92
+ const declared = charset ?? "utf-8";
348
93
  try {
349
- return new TextDecoder(charset);
94
+ return new TextDecoder(declared);
350
95
  } catch (error) {
351
- throw new WebError(`unsupported charset "${charset}"`, "WEB_UNSUPPORTED_CONTENT_TYPE", { cause: error });
96
+ if (declared.split(/[\s,]+/).some(isUtf8Label)) return new TextDecoder("utf-8", { fatal: true });
97
+ throw new WebError(`unsupported charset "${declared}"`, "WEB_UNSUPPORTED_CONTENT_TYPE", { cause: error });
98
+ }
99
+ }
100
+ /** Whether a label names UTF-8, including its standard aliases. */
101
+ function isUtf8Label(label) {
102
+ try {
103
+ return new TextDecoder(label).encoding === "utf-8";
104
+ } catch (_error) {
105
+ return false;
352
106
  }
353
107
  }
354
108
  //#endregion
355
109
  //#region lib/types/provider.js
356
110
  /**
357
- * Safe HTTP(S) retrieval for `ctx.web`: validates and pins public IP destinations, follows
358
- * only same-origin redirects, enforces time and size limits, classifies and decodes text,
359
- * and leaves presentation to `@deepseek-ai/dsh-tool-web`. Requests carry no browser cookies
111
+ * Bounded HTTP(S) retrieval for `ctx.web`: validates URLs, follows only same-origin redirects,
112
+ * enforces time and size limits, classifies and decodes text, and leaves presentation to
113
+ * `@deepseek-ai/dsh-tool-web`. Requests carry no browser cookies
360
114
  * or ambient credentials.
361
115
  * @module @deepseek-ai/dsh-web-fetch-http/provider
362
116
  */
@@ -420,20 +174,15 @@ var __disposeResources = (function(SuppressedError) {
420
174
  });
421
175
  /** Stable id this provider registers under. */
422
176
  const LOCAL_FETCH_PROVIDER_ID = "http";
423
- /** The anonymous public HTTP(S) fetch provider. */
177
+ /** The anonymous HTTP(S) fetch provider. */
424
178
  var HttpFetchProvider = class {
425
179
  limits;
426
- resolveAddresses;
427
180
  id = LOCAL_FETCH_PROVIDER_ID;
428
- /**
429
- * @param limits - resolved transport and response limits.
430
- * @param resolveAddresses - resolver that rejects non-public destinations before returning.
431
- */
432
- constructor(limits, resolveAddresses = publicHttpNetwork.resolve) {
181
+ /** @param limits - resolved transport and response limits. */
182
+ constructor(limits) {
433
183
  this.limits = limits;
434
- this.resolveAddresses = resolveAddresses;
435
184
  }
436
- /** No credentials to check — an anonymous public fetcher is always usable. */
185
+ /** No credentials to check — an anonymous fetcher is always usable. */
437
186
  available() {
438
187
  return true;
439
188
  }
@@ -459,51 +208,49 @@ var HttpFetchProvider = class {
459
208
  let currentUrl = validateFetchUrl(initialUrl);
460
209
  let redirectsFollowed = 0;
461
210
  for (;;) {
462
- const request = await this.requestOnce(currentUrl, signal);
463
- const { response } = request;
464
- try {
465
- if (isRedirectStatus(response.status)) {
466
- if (redirectsFollowed >= this.limits.maxRedirects) {
467
- await response.body?.cancel();
468
- throw new WebError(`exceeded the maximum of ${this.limits.maxRedirects} redirects`, "WEB_REDIRECT_BLOCKED");
469
- }
470
- const location = response.headers.get("location");
471
- if (location === null) {
472
- await response.body?.cancel();
473
- throw new WebError(`redirect response (HTTP ${response.status}) without a Location header`, "WEB_PROVIDER_ERROR");
474
- }
475
- const target = resolveRedirect(location, currentUrl);
476
- let validatedTarget;
477
- try {
478
- validatedTarget = validateFetchUrl(target.toString());
479
- if (!isSameOrigin(validatedTarget, currentUrl)) throw new WebError(`cross-origin redirect to ${validatedTarget.origin} is not followed automatically; retry against that URL directly`, "WEB_REDIRECT_BLOCKED");
480
- } catch (error) {
481
- await response.body?.cancel();
482
- throw error;
483
- }
211
+ const response = await this.requestOnce(currentUrl, signal);
212
+ if (isRedirectStatus(response.status)) {
213
+ if (redirectsFollowed >= this.limits.maxRedirects) {
214
+ await response.body?.cancel();
215
+ throw new WebError(`exceeded the maximum of ${this.limits.maxRedirects} redirects`, "WEB_REDIRECT_BLOCKED");
216
+ }
217
+ const location = response.headers.get("location");
218
+ if (location === null) {
484
219
  await response.body?.cancel();
485
- currentUrl = validatedTarget;
486
- redirectsFollowed++;
487
- continue;
220
+ throw new WebError(`redirect response (HTTP ${response.status}) without a Location header`, "WEB_PROVIDER_ERROR");
488
221
  }
489
- return await this.readBody(response, currentUrl, signal);
490
- } finally {
491
- await request.close();
222
+ const target = resolveRedirect(location, currentUrl);
223
+ let validatedTarget;
224
+ try {
225
+ validatedTarget = validateFetchUrl(target.toString());
226
+ if (!isSameOrigin(validatedTarget, currentUrl)) throw new WebError(`cross-origin redirect to ${validatedTarget.origin} is not followed automatically; retry against that URL directly`, "WEB_REDIRECT_BLOCKED");
227
+ } catch (error) {
228
+ await response.body?.cancel();
229
+ throw error;
230
+ }
231
+ await response.body?.cancel();
232
+ currentUrl = validatedTarget;
233
+ redirectsFollowed++;
234
+ continue;
492
235
  }
236
+ return await this.readBody(response, currentUrl, signal);
493
237
  }
494
238
  }
239
+ /** Send one GET through the process-wide dispatcher, which applies the installed proxy policy. */
495
240
  async requestOnce(url, signal) {
496
241
  const headers = {
497
242
  "user-agent": this.limits.userAgent,
498
243
  "accept": "text/html,application/xhtml+xml,text/*;q=0.9,application/json;q=0.8"
499
244
  };
500
245
  try {
501
- const route = proxyRouteFor(url);
502
- if (route.proxied && !isNonPublicIpLiteral(url.hostname)) return await publicHttpNetwork.requestVia(route.dispatcher, url, headers, signal);
503
- const addresses = await this.resolveAddresses(url.hostname, signal);
504
- return await publicHttpNetwork.request(url, addresses, headers, signal);
246
+ const { fetch } = await import("undici");
247
+ return await fetch(url, {
248
+ method: "GET",
249
+ redirect: "manual",
250
+ headers,
251
+ signal
252
+ });
505
253
  } catch (error) {
506
- if (error instanceof WebError) throw error;
507
254
  throw translateAbortOrNetwork(error, signal);
508
255
  }
509
256
  }
@@ -523,7 +270,12 @@ var HttpFetchProvider = class {
523
270
  throw error;
524
271
  }
525
272
  const { bytes, truncatedByBytes } = await this.readCapped(response, signal);
526
- const decoded = decoder.decode(bytes);
273
+ let decoded;
274
+ try {
275
+ decoded = decoder.decode(bytes, { stream: decoder.fatal && truncatedByBytes });
276
+ } catch (error) {
277
+ throw new WebError("response body is not valid UTF-8 for the malformed charset declaration", "WEB_UNSUPPORTED_CONTENT_TYPE", { cause: error });
278
+ }
527
279
  const truncatedByChars = decoded.length > this.limits.maxBodyChars;
528
280
  const content = truncatedByChars ? decoded.slice(0, this.limits.maxBodyChars) : decoded;
529
281
  const body = kind === "html" ? {
@@ -629,7 +381,7 @@ function translateAbortOrNetwork(error, signal) {
629
381
  //#endregion
630
382
  //#region lib/types/index.js
631
383
  /**
632
- * Anonymous public HTTP(S) `WebFetchProvider` plugin. It contributes to the
384
+ * Anonymous HTTP(S) `WebFetchProvider` plugin. It contributes to the
633
385
  * `ctx.web` registry without owning the service.
634
386
  *
635
387
  * @module @deepseek-ai/dsh-web-fetch-http
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Anonymous public HTTP(S) `WebFetchProvider` plugin. It contributes to the
2
+ * Anonymous HTTP(S) `WebFetchProvider` plugin. It contributes to the
3
3
  * `ctx.web` registry without owning the service.
4
4
  *
5
5
  * @module @deepseek-ai/dsh-web-fetch-http
@@ -7,7 +7,7 @@
7
7
  import type { Context } from '@deepseek-ai/cordis';
8
8
  import z from '@deepseek-ai/schemastery';
9
9
  export { LOCAL_FETCH_PROVIDER_ID, HttpFetchProvider, } from './provider.ts';
10
- export type { HttpFetchLimits, HttpFetchResolver } from './provider.ts';
10
+ export type { HttpFetchLimits } from './provider.ts';
11
11
  /** Default `User-Agent`: an explicit product agent, never a browser disguise. */
12
12
  export declare const DEFAULT_USER_AGENT = "deepseek-harness/0.0.1 (+https://github.com/deepseek-ai)";
13
13
  /** Cordis plugin name used by loader diagnostics. */
@@ -1,11 +1,12 @@
1
1
  /**
2
- * URL validation and content-type classification for the local HTTP(S) fetch
3
- * provider — the pure, network-free half. The provider's `fetch()` composes
4
- * these with transport (redirect following, byte caps, decoding).
2
+ * URL validation, content-type classification, and charset resolution for the
3
+ * local HTTP(S) fetch provider — the pure, network-free half. The provider's
4
+ * `fetch()` composes these with transport (redirect following, byte caps,
5
+ * decoding).
5
6
  *
6
7
  * @module @deepseek-ai/dsh-web-fetch-http/policy
7
8
  */
8
- /** Maximum accepted request URL length enforced by the public fetch provider. */
9
+ /** Maximum accepted request URL length enforced by the fetch provider. */
9
10
  export declare const WEB_FETCH_MAX_URL_LENGTH = 2048;
10
11
  /** The body kinds this provider decodes. */
11
12
  export type FetchableKind = 'html' | 'text';
@@ -29,8 +30,7 @@ export declare function parseFetchUrl(input: string): URL;
29
30
  export declare function validateFetchUrl(input: string): URL;
30
31
  /**
31
32
  * Two URLs are same-origin when scheme, hostname, and port match. A redirect
32
- * that crosses origins is refused so each new origin requires a fresh tool call
33
- * and public-address validation.
33
+ * that crosses origins is refused so each new origin requires a fresh tool call.
34
34
  *
35
35
  * @param a - one of the two URLs to compare.
36
36
  * @param b - the other URL to compare.
@@ -48,25 +48,21 @@ export declare function isSameOrigin(a: URL, b: URL): boolean;
48
48
  */
49
49
  export declare function classifyContentType(contentType: string | null): FetchableKind | undefined;
50
50
  /**
51
- * Extract the `charset` parameter from a response `Content-Type`, lower-cased,
52
- * or `undefined` when absent. The provider feeds this label to `TextDecoder`
53
- * so a non-UTF-8 response is decoded with its declared encoding rather than
54
- * silently mangled into replacement characters.
51
+ * Extract the lower-cased `charset` parameter from a response `Content-Type`.
55
52
  *
56
- * @param contentType - the raw `Content-Type` header, or `null` when the
57
- * response carries none.
58
- * @returns the lower-cased charset label, or `undefined` when none is declared.
53
+ * @param contentType - the raw header, or `null` when absent.
54
+ * @returns the charset parameter, or `undefined` when none is declared.
59
55
  */
60
56
  export declare function parseCharset(contentType: string | null): string | undefined;
61
57
  /**
62
- * Build a `TextDecoder` for the declared charset, falling back to UTF-8 when
63
- * none is declared. Throws {@link WebError} `WEB_UNSUPPORTED_CONTENT_TYPE` when
64
- * the label is present but not a charset `TextDecoder` recognizes — better to
65
- * fail loudly than return mojibake.
58
+ * Resolve the declared charset, defaulting to UTF-8 when absent. A malformed
59
+ * comma- or whitespace-joined declaration containing a UTF-8 label uses a fatal
60
+ * UTF-8 decoder; other unsupported declarations throw `WEB_UNSUPPORTED_CONTENT_TYPE`.
61
+ * UTF-8 recovery is a preference, not proof of the original encoding.
66
62
  *
67
- * @param charset - the declared charset label (from {@link parseCharset}), or
68
- * `undefined` to default to UTF-8.
69
- * @returns a decoder for the declared (or defaulted) encoding.
63
+ * @param charset - the declared charset parameter, or `undefined` to default.
64
+ * @returns a decoder; callers must report fatal decoding failures and flush at
65
+ * EOF unless they deliberately truncated the bytes.
70
66
  */
71
67
  export declare function decoderForCharset(charset: string | undefined): TextDecoder;
72
68
  //# sourceMappingURL=policy.d.ts.map
@@ -1,12 +1,11 @@
1
1
  /**
2
- * Safe HTTP(S) retrieval for `ctx.web`: validates and pins public IP destinations, follows
3
- * only same-origin redirects, enforces time and size limits, classifies and decodes text,
4
- * and leaves presentation to `@deepseek-ai/dsh-tool-web`. Requests carry no browser cookies
2
+ * Bounded HTTP(S) retrieval for `ctx.web`: validates URLs, follows only same-origin redirects,
3
+ * enforces time and size limits, classifies and decodes text, and leaves presentation to
4
+ * `@deepseek-ai/dsh-tool-web`. Requests carry no browser cookies
5
5
  * or ambient credentials.
6
6
  * @module @deepseek-ai/dsh-web-fetch-http/provider
7
7
  */
8
8
  import type { WebFetchProvider, WebFetchRequest, WebFetchResult } from '@deepseek-ai/dsh-web';
9
- import type { PublicAddress } from './network.ts';
10
9
  /** Resolved provider limits (the plugin's schemastery Config supplies defaults). */
11
10
  export interface HttpFetchLimits {
12
11
  /** Maximum response body size in bytes (read is aborted past this). */
@@ -20,25 +19,20 @@ export interface HttpFetchLimits {
20
19
  /** `User-Agent` header sent on every request. */
21
20
  userAgent: string;
22
21
  }
23
- /** Resolve one hostname to an already policy-validated address set. */
24
- export type HttpFetchResolver = (hostname: string, signal: AbortSignal) => Promise<PublicAddress[]>;
25
22
  /** Stable id this provider registers under. */
26
23
  export declare const LOCAL_FETCH_PROVIDER_ID = "http";
27
- /** The anonymous public HTTP(S) fetch provider. */
24
+ /** The anonymous HTTP(S) fetch provider. */
28
25
  export declare class HttpFetchProvider implements WebFetchProvider {
29
26
  private readonly limits;
30
- private readonly resolveAddresses;
31
27
  readonly id = "http";
32
- /**
33
- * @param limits - resolved transport and response limits.
34
- * @param resolveAddresses - resolver that rejects non-public destinations before returning.
35
- */
36
- constructor(limits: HttpFetchLimits, resolveAddresses?: HttpFetchResolver);
37
- /** No credentials to check — an anonymous public fetcher is always usable. */
28
+ /** @param limits - resolved transport and response limits. */
29
+ constructor(limits: HttpFetchLimits);
30
+ /** No credentials to check — an anonymous fetcher is always usable. */
38
31
  available(): boolean;
39
32
  fetch(request: WebFetchRequest, signal?: AbortSignal): Promise<WebFetchResult>;
40
33
  /** Follow same-origin redirects up to the hop cap, then read the final response. */
41
34
  private followAndRead;
35
+ /** Send one GET through the process-wide dispatcher, which applies the installed proxy policy. */
42
36
  private requestOnce;
43
37
  /** Read, byte-cap, classify, and decode the final response body. */
44
38
  private readBody;
package/locale/de.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Von öffentlichen Webseiten beziehen",
4
+ "description": "Lesen Sie den Inhalt der Webseite HTTP oder HTTPS, ohne dass eine Anmeldung erforderlich ist."
5
+ }
6
+ }
package/locale/es.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Obtener de páginas web públicas",
4
+ "description": "Lea el contenido de la página web HTTP o HTTPS sin necesidad de iniciar sesión."
5
+ }
6
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Obtenir à partir de pages Web publiques",
4
+ "description": "Lisez le contenu de la page Web HTTP ou HTTPS sans nécessiter de connexion."
5
+ }
6
+ }
package/locale/ja.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "公開 Web ページ取得",
4
+ "description": "ログイン不要の HTTP または HTTPS の Web ページを読み取ります。"
5
+ }
6
+ }
package/locale/pt.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Obter de páginas da web públicas",
4
+ "description": "Leia o conteúdo da página da web HTTP ou HTTPS sem precisar fazer login."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Получить с общедоступных веб-страниц",
4
+ "description": "Прочтите содержимое веб-страницы HTTP или HTTPS без необходимости входа в систему."
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/dsh-web-fetch-http",
3
- "description": "Anonymous public HTTP(S) fetch provider for the DeepSeek Harness web capability seam (ctx.web)",
4
- "version": "0.2.1-rc.4",
3
+ "description": "Anonymous HTTP(S) fetch provider for the DeepSeek Harness web capability seam (ctx.web)",
4
+ "version": "0.2.2-alpha.2",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -29,20 +29,18 @@
29
29
  ],
30
30
  "license": "MIT",
31
31
  "peerDependencies": {
32
- "@deepseek-ai/cordis": "~4.0.5",
33
- "@deepseek-ai/dsh-timeout": "0.2.1-rc.4",
34
- "@deepseek-ai/dsh-web": "0.2.1-rc.4",
35
- "@deepseek-ai/dsh-http-proxy": "0.2.1-rc.4"
32
+ "@deepseek-ai/cordis": "~4.0.6-alpha.1",
33
+ "@deepseek-ai/dsh-timeout": "0.2.2-alpha.2",
34
+ "@deepseek-ai/dsh-web": "0.2.2-alpha.2"
36
35
  },
37
36
  "dependencies": {
38
- "@deepseek-ai/schemastery": "~3.18.5",
39
- "ipaddr.js": "^2.5.0",
37
+ "@deepseek-ai/schemastery": "~3.18.6-alpha.1",
40
38
  "undici": "8.11.2"
41
39
  },
42
40
  "devDependencies": {
43
- "@deepseek-ai/cordis": "~4.0.5",
44
- "@deepseek-ai/dsh-timeout": "0.2.1-rc.4",
45
- "@deepseek-ai/dsh-web": "0.2.1-rc.4",
46
- "@deepseek-ai/dsh-http-proxy": "0.2.1-rc.4"
41
+ "@deepseek-ai/cordis": "~4.0.6-alpha.1",
42
+ "@deepseek-ai/dsh-timeout": "0.2.2-alpha.2",
43
+ "@deepseek-ai/dsh-web": "0.2.2-alpha.2",
44
+ "@deepseek-ai/dsh-http-proxy": "0.2.2-alpha.2"
47
45
  }
48
46
  }
@@ -1,106 +0,0 @@
1
- /**
2
- * Public-network resolution and address-pinned HTTP transport for `web-fetch-http`.
3
- * One DNS answer set is validated before Undici receives it through a custom lookup,
4
- * so the connection cannot resolve the hostname again to a private address.
5
- *
6
- * @module @deepseek-ai/dsh-web-fetch-http/network
7
- */
8
- import type { LookupAddress, LookupOptions } from 'node:dns';
9
- import type { Dispatcher, Response } from 'undici';
10
- /** One address resolved and retained for the subsequent pinned connection. */
11
- export interface PublicAddress {
12
- /** Canonical textual IPv4 or IPv6 address. */
13
- readonly address: string;
14
- /** Address family accepted by Node's connection lookup callback. */
15
- readonly family: 4 | 6;
16
- }
17
- /** The result of one address-pinned request; closing releases its private pool. */
18
- export interface PinnedResponse {
19
- /** HTTP response whose body remains readable until `close()` is called. */
20
- readonly response: Response;
21
- /** Release the request's dispatcher after the response body is consumed or cancelled. */
22
- close(): Promise<void>;
23
- }
24
- /** Resolver signature used to test public-address policy without process DNS changes. */
25
- export type AddressResolver = (hostname: string, options: {
26
- all: true;
27
- order: 'verbatim';
28
- }) => Promise<LookupAddress[]>;
29
- /**
30
- * Return whether an address is globally reachable unicast. IPv4-mapped IPv6 is
31
- * classified by its embedded IPv4 address; transition and translation prefixes
32
- * remain blocked because their eventual IPv4 destination cannot be pinned here.
33
- *
34
- * @param input - textual IPv4 or IPv6 address.
35
- * @returns true only for a public unicast destination.
36
- */
37
- export declare function isPublicIpAddress(input: string): boolean;
38
- /**
39
- * Resolve a hostname once and reject the complete answer set if any destination
40
- * is not public. The returned addresses are the only ones the transport may use.
41
- *
42
- * @param hostname - URL hostname, including brackets when it is an IPv6 literal.
43
- * @param signal - aborts the wait for system resolution; an in-flight OS lookup may finish unused.
44
- * @param resolver - lookup implementation, overridden only by focused tests.
45
- * @returns the validated, non-empty address set.
46
- */
47
- export declare function resolvePublicAddresses(hostname: string, signal: AbortSignal, resolver?: AddressResolver): Promise<PublicAddress[]>;
48
- /**
49
- * Whether a hostname is an IP literal that {@link resolvePublicAddresses} would refuse.
50
- *
51
- * A proxied hop skips those checks because the proxy resolves the origin, but a literal needs no
52
- * resolution: the address is already stated, and handing it to a proxy running on this machine
53
- * would reach exactly the loopback or private service the checks exist to keep out of reach.
54
- *
55
- * @param hostname - a URL's hostname, bracketed or not.
56
- * @returns true when the host is a literal address no request may be sent to.
57
- */
58
- export declare function isNonPublicIpLiteral(hostname: string): boolean;
59
- /**
60
- * Fetch through an agent whose lookup callback returns only the already validated address set. The
61
- * URL hostname remains intact for HTTP Host and TLS SNI.
62
- *
63
- * The agent is this request's own because the address set is: pinning is how this package refuses a
64
- * DNS answer that changes between validation and connection, and it may not apply process-wide —
65
- * an operator-configured MCP server or model endpoint on loopback is a supported destination, and
66
- * only the URLs this tool fetches are the model's to choose.
67
- *
68
- * @param url - validated HTTP(S) URL the policy does not route through a proxy.
69
- * @param addresses - public addresses returned by {@link resolvePublicAddresses}.
70
- * @param headers - request headers.
71
- * @param signal - request and body-read cancellation signal.
72
- * @returns a response plus the disposer its consumer must call.
73
- */
74
- export declare function requestPinned(url: URL, addresses: readonly PublicAddress[], headers: Record<string, string>, signal: AbortSignal): Promise<PinnedResponse>;
75
- /**
76
- * Fetch through the dispatcher the proxy policy already installed, letting the proxy resolve the
77
- * origin.
78
- *
79
- * No address set is pinned because none exists to pin: the proxy performs the lookup, and a
80
- * connection pinned to a locally resolved address would reach the origin directly and defeat the
81
- * proxy. The dispatcher is the process-wide one, so hops share its connection pool and no caller
82
- * closes it.
83
- *
84
- * @param dispatcher - the route's dispatcher, from `proxyRouteFor`.
85
- * @param url - validated HTTP(S) URL the policy routes through a proxy.
86
- * @param headers - request headers.
87
- * @param signal - request and body-read cancellation signal.
88
- * @returns a response plus a disposer that releases nothing, so both paths close alike.
89
- */
90
- export declare function requestVia(dispatcher: Dispatcher, url: URL, headers: Record<string, string>, signal: AbortSignal): Promise<PinnedResponse>;
91
- /** Production network operations kept as an object so provider tests can replace resolution only. */
92
- export declare const publicHttpNetwork: {
93
- resolve: typeof resolvePublicAddresses;
94
- request: typeof requestPinned;
95
- requestVia: typeof requestVia;
96
- };
97
- type LookupCallback = (error: NodeJS.ErrnoException | null, address: string | LookupAddress[], family?: number) => void;
98
- /**
99
- * Build the connector lookup that serves a fixed validated answer set.
100
- *
101
- * @param addresses - public addresses retained from the preceding resolution.
102
- * @returns a Node-compatible lookup callback that performs no network resolution.
103
- */
104
- export declare function createPinnedLookup(addresses: readonly PublicAddress[]): (hostname: string, options: LookupOptions, callback: LookupCallback) => void;
105
- export {};
106
- //# sourceMappingURL=network.d.ts.map