pi-web-ui 0.103.3 → 0.104.1

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.
Files changed (40) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/dist/server/agent-formatters.js +9 -1
  3. package/dist/server/agent-service-daemon.js +4 -3
  4. package/dist/server/agent-service.js +586 -44
  5. package/dist/server/compaction-markers.js +111 -3
  6. package/dist/server/delegate-mode.js +2 -0
  7. package/dist/server/dispatch-domain-handlers.js +25 -0
  8. package/dist/server/dsh/dsh-agent-service.js +265 -11
  9. package/dist/server/goal-review-gate.js +2 -0
  10. package/dist/server/index.js +1 -0
  11. package/dist/server/market-service.js +36 -9
  12. package/dist/server/mcp-agent-tool.js +164 -0
  13. package/dist/server/mcp-manager.js +182 -0
  14. package/dist/server/net-guard.js +277 -0
  15. package/dist/server/plan-mode.js +3 -0
  16. package/dist/server/plugin-api-catalog.js +24 -0
  17. package/dist/server/plugins.js +113 -0
  18. package/dist/server/preset-share.js +90 -42
  19. package/dist/server/remote-ssh-service.js +90 -25
  20. package/dist/server/sandbox-service.js +705 -0
  21. package/dist/server/sandbox-tool.js +365 -0
  22. package/dist/server/session-branch.js +32 -11
  23. package/dist/server/session-parser.js +48 -21
  24. package/dist/server/terminals.js +210 -10
  25. package/dist/server/tool-manager.js +24 -0
  26. package/dist/server/webui-context.js +6 -0
  27. package/dist/server/workspace-snapshot.js +51 -13
  28. package/package.json +1 -1
  29. package/plugin-sdk/index.d.ts +39 -0
  30. package/plugin-sdk/index.mjs +14 -0
  31. package/plugins/catalog.json +101 -2
  32. package/themes/zhujian-dark.css +711 -0
  33. package/themes/zhujian.css +760 -0
  34. package/web/dist/assets/{TerminalPanel-CAqMqC49.js → TerminalPanel-CpfPFx32.js} +1 -1
  35. package/web/dist/assets/index-D85H75iu.js +680 -0
  36. package/web/dist/assets/index-RqIdFOsh.css +1 -0
  37. package/web/dist/index.html +2 -2
  38. package/web/dist/sw.js +1 -1
  39. package/web/dist/assets/index-CYQdZEbx.css +0 -1
  40. package/web/dist/assets/index-Dt7CQ_Z6.js +0 -680
@@ -0,0 +1,277 @@
1
+ /**
2
+ * server/net-guard.ts —— 服务端外发 HTTP(S) 请求的统一 SSRF 防护与安全抓取工具 (#602)。
3
+ *
4
+ * 防护分层:
5
+ * 1. URL 语法与协议白名单:仅允许 http: / https:;
6
+ * 2. 主机名与字面量 IP 校验(isBlockedHost):
7
+ * - 拦截 localhost / *.localhost / *.local / *.internal;
8
+ * - 将 IPv6 完整展开为 8×16-bit 组,统一还原 IPv4-mapped (::ffff:0:0/96)、
9
+ * IPv4-translated (::ffff:0:0:0/96)、IPv4-compatible (::/96)、NAT64 (64:ff9b::/96)
10
+ * 内嵌的 32-bit IPv4,彻底杜绝 ::ffff:7f00:1 / ::ffff:0:7f00:1 / 0:0:0:0:0:ffff:... 绕过;
11
+ * - 拦截回环、未指定、RFC1918 私网、CGNAT (100.64/10)、链路本地与云元数据 (169.254/16, fe80::/10)、
12
+ * ULA (fc00::/7)、组播与保留段;
13
+ * 3. DNS 解析后 IP 校验(resolveAndValidateUrl):
14
+ * - 对域名调用 dns.promises.lookup(host, { all: true }),任一 A/AAAA 记录命中内网/元数据 IP 即拒绝,
15
+ * 防御域名解析到 127.0.0.1 / 169.254.169.254 的 DNS rebinding;
16
+ * 4. 重定向逐跳校验(safeFetch):
17
+ * - 强制 redirect: "manual",对每一跳 Location 重新执行 URL + DNS 校验(最多 5 跳),
18
+ * 防止公网 URL 302 跳转到内网/云元数据端点。
19
+ */
20
+ import { lookup as dnsLookup } from "node:dns/promises";
21
+ import { isIP } from "node:net";
22
+ const initialGlobalFetch = globalThis.fetch;
23
+ /** 判断全局 fetch 是否仍为进程启动时的原生 fetch(未被 vi.stubGlobal 替换)。 */
24
+ export function isNativeGlobalFetch() {
25
+ return globalThis.fetch === initialGlobalFetch;
26
+ }
27
+ const defaultLookupAll = async (hostname) => {
28
+ return await dnsLookup(hostname, { all: true, verbatim: true });
29
+ };
30
+ /** 解析点分十进制 IPv4 为 4 个 0..255 字节;非法返回 null。 */
31
+ function parseIpv4Octets(input) {
32
+ const m = input.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
33
+ if (!m)
34
+ return null;
35
+ const a = Number(m[1]);
36
+ const b = Number(m[2]);
37
+ const c = Number(m[3]);
38
+ const d = Number(m[4]);
39
+ if (a > 255 || b > 255 || c > 255 || d > 255)
40
+ return null;
41
+ return [a, b, c, d];
42
+ }
43
+ /** 判定 4 字节 IPv4 是否属于内网/回环/链路本地/云元数据/保留段。 */
44
+ function isBlockedIpv4Octets([a, b]) {
45
+ // 注意:不拦截 198.18.0.0/15,因 Clash / Surge / sing-box 等 TUN Fake-IP 模式会将公网域名解析至该段。
46
+ return (a === 0 || // 0.0.0.0/8 (this network)
47
+ a === 10 || // 10.0.0.0/8 (RFC1918)
48
+ (a === 100 && b >= 64 && b <= 127) || // 100.64.0.0/10 (CGNAT RFC6598)
49
+ a === 127 || // 127.0.0.0/8 (loopback)
50
+ (a === 169 && b === 254) || // 169.254.0.0/16 (link-local / cloud metadata)
51
+ (a === 172 && b >= 16 && b <= 31) || // 172.16.0.0/12 (RFC1918)
52
+ (a === 192 && b === 168) || // 192.168.0.0/16 (RFC1918)
53
+ a >= 224 // 224.0.0.0/4 (multicast) & 240.0.0.0/4 (reserved/broadcast)
54
+ );
55
+ }
56
+ /**
57
+ * 将任意合法 IPv6 字符串(含 :: 压缩及末尾 점分 IPv4)展开为 8 个 16-bit 整数(0..0xffff)。
58
+ * 解析失败返回 null。
59
+ */
60
+ function expandIpv6Words(rawInput) {
61
+ // 去掉 zone index(如 fe80::1%eth0 或 %25eth0)
62
+ const input = rawInput.split("%")[0].toLowerCase();
63
+ if (!input.includes(":"))
64
+ return null;
65
+ let working = input;
66
+ // 若末尾带点分 IPv4(如 ::ffff:127.0.0.1 或 ::ffff:0:127.0.0.1),先转成两个 16-bit hex 段
67
+ const lastColon = working.lastIndexOf(":");
68
+ const tail = working.slice(lastColon + 1);
69
+ if (tail.includes(".")) {
70
+ const octets = parseIpv4Octets(tail);
71
+ if (!octets)
72
+ return null;
73
+ const hi = ((octets[0] << 8) | octets[1]).toString(16);
74
+ const lo = ((octets[2] << 8) | octets[3]).toString(16);
75
+ working = `${working.slice(0, lastColon + 1)}${hi}:${lo}`;
76
+ }
77
+ const doubleColonParts = working.split("::");
78
+ if (doubleColonParts.length > 2)
79
+ return null;
80
+ const parseSide = (side) => {
81
+ if (!side)
82
+ return [];
83
+ const parts = side.split(":");
84
+ const words = [];
85
+ for (const p of parts) {
86
+ if (!/^[0-9a-f]{1,4}$/.test(p))
87
+ return null;
88
+ words.push(parseInt(p, 16));
89
+ }
90
+ return words;
91
+ };
92
+ if (doubleColonParts.length === 2) {
93
+ const left = parseSide(doubleColonParts[0]);
94
+ const right = parseSide(doubleColonParts[1]);
95
+ if (!left || !right)
96
+ return null;
97
+ const missing = 8 - (left.length + right.length);
98
+ if (missing < 1)
99
+ return null;
100
+ return [...left, ...new Array(missing).fill(0), ...right];
101
+ }
102
+ const full = parseSide(working);
103
+ if (!full || full.length !== 8)
104
+ return null;
105
+ return full;
106
+ }
107
+ /**
108
+ * 判断 8×16-bit IPv6 地址是否内嵌了 IPv4:
109
+ * - IPv4-mapped: 0:0:0:0:0:ffff:w6:w7
110
+ * - IPv4-translated: 0:0:0:0:ffff:0:w6:w7 (RFC 2765 SIIT)
111
+ * - IPv4-compatible: 0:0:0:0:0:0:w6:w7 (排除 ::0 与 ::1)
112
+ * - NAT64 well-known prefix: 64:ff9b:0:0:0:0:w6:w7 或 64:ff9b:1::/48
113
+ */
114
+ function extractEmbeddedIpv4(w) {
115
+ const isMapped = w[0] === 0 && w[1] === 0 && w[2] === 0 && w[3] === 0 && w[4] === 0 && w[5] === 0xffff;
116
+ const isTranslated = w[0] === 0 && w[1] === 0 && w[2] === 0 && w[3] === 0 && w[4] === 0xffff && w[5] === 0;
117
+ const isCompatible = w[0] === 0 &&
118
+ w[1] === 0 &&
119
+ w[2] === 0 &&
120
+ w[3] === 0 &&
121
+ w[4] === 0 &&
122
+ w[5] === 0 &&
123
+ !(w[6] === 0 && (w[7] === 0 || w[7] === 1));
124
+ const isNat64 = w[0] === 0x0064 && w[1] === 0xff9b && w[3] === 0 && w[4] === 0 && w[5] === 0;
125
+ if (isMapped || isTranslated || isCompatible || isNat64) {
126
+ return [(w[6] >> 8) & 0xff, w[6] & 0xff, (w[7] >> 8) & 0xff, w[7] & 0xff];
127
+ }
128
+ return null;
129
+ }
130
+ /** SSRF 收口:内网/回环/链路本地/云元数据地址一律拒绝。 */
131
+ export function isBlockedHost(hostname) {
132
+ const host = hostname
133
+ .trim()
134
+ .toLowerCase()
135
+ .replace(/^\[|\]$/g, "")
136
+ .replace(/\.+$/, "");
137
+ if (!host)
138
+ return true;
139
+ if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) {
140
+ return true;
141
+ }
142
+ // 1. IPv6 字面量(含 ::ffff:7f00:1 / ::ffff:0:7f00:1 / 0:0:0:0:0:ffff:... 等所有展开或压缩变体)
143
+ if (host.includes(":")) {
144
+ const words = expandIpv6Words(host);
145
+ if (!words)
146
+ return true; // 非法 IPv6 字面量一律拒绝
147
+ const embeddedV4 = extractEmbeddedIpv4(words);
148
+ if (embeddedV4) {
149
+ return isBlockedIpv4Octets(embeddedV4);
150
+ }
151
+ const allZeroPrefix = words[0] === 0 &&
152
+ words[1] === 0 &&
153
+ words[2] === 0 &&
154
+ words[3] === 0 &&
155
+ words[4] === 0 &&
156
+ words[5] === 0 &&
157
+ words[6] === 0;
158
+ // :: (unspecified) 或 ::1 (loopback)
159
+ if (allZeroPrefix && (words[7] === 0 || words[7] === 1))
160
+ return true;
161
+ // fe80::/10 (link-local)
162
+ if ((words[0] & 0xffc0) === 0xfe80)
163
+ return true;
164
+ // fc00::/7 (ULA unique local fc00::..fdff::)
165
+ if ((words[0] & 0xfe00) === 0xfc00)
166
+ return true;
167
+ // ff00::/8 (multicast)
168
+ if ((words[0] & 0xff00) === 0xff00)
169
+ return true;
170
+ // 2001:db8::/32 (documentation)
171
+ if (words[0] === 0x2001 && words[1] === 0x0db8)
172
+ return true;
173
+ return false;
174
+ }
175
+ // 2. 标准点分 IPv4
176
+ const v4 = parseIpv4Octets(host);
177
+ if (v4) {
178
+ return isBlockedIpv4Octets(v4);
179
+ }
180
+ // 3. 非常规纯数字/十六进制/八进制单段或多段 IPv4 变形(如 2130706433、0x7f000001、127.1)
181
+ // URL 构造器通常会规范化,若仍有纯数字结尾段则拒绝
182
+ if (/^(?:0x[0-9a-f]+|\d+)(?:\.(?:0x[0-9a-f]+|\d+))*$/i.test(host)) {
183
+ return true;
184
+ }
185
+ return false;
186
+ }
187
+ /** 同步校验一个可抓取地址:只允许 http/https 且 hostname 非内网/回环。 */
188
+ export function validateFetchUrl(raw) {
189
+ let u;
190
+ try {
191
+ u = new URL(String(raw ?? "").trim());
192
+ }
193
+ catch {
194
+ return { ok: false, reason: "scheme" };
195
+ }
196
+ if (u.protocol !== "http:" && u.protocol !== "https:")
197
+ return { ok: false, reason: "scheme" };
198
+ if (isBlockedHost(u.hostname))
199
+ return { ok: false, reason: "host" };
200
+ return { ok: true, url: u.toString() };
201
+ }
202
+ /**
203
+ * 异步校验 URL + 解析后 IP(防 DNS rebinding 指向 127.0.0.1 / 169.254.169.254 等内网地址)。
204
+ *
205
+ * - 先执行 validateFetchUrl;
206
+ * - 若 hostname 是域名(非 IP 字面量),调用 lookup 解析全部 A/AAAA 记录;
207
+ * - 任一解析出的 IP 命中 isBlockedHost,或解析无结果/报错,均判定为 reason: "host"。
208
+ */
209
+ export async function resolveAndValidateUrl(raw, opts = {}) {
210
+ const sync = validateFetchUrl(raw);
211
+ if (!sync.ok)
212
+ return sync;
213
+ const u = new URL(sync.url);
214
+ const bareHost = u.hostname.replace(/^\[|\]$/g, "");
215
+ if (isIP(bareHost) !== 0) {
216
+ return { ok: true, url: sync.url, addresses: [bareHost] };
217
+ }
218
+ const lookupFn = opts.lookup ?? defaultLookupAll;
219
+ try {
220
+ const records = await lookupFn(bareHost);
221
+ if (!Array.isArray(records) || records.length === 0) {
222
+ return { ok: false, reason: "host" };
223
+ }
224
+ const addresses = [];
225
+ for (const rec of records) {
226
+ const addr = typeof rec?.address === "string" ? rec.address.trim() : "";
227
+ if (!addr || isBlockedHost(addr)) {
228
+ return { ok: false, reason: "host" };
229
+ }
230
+ addresses.push(addr);
231
+ }
232
+ return { ok: true, url: sync.url, addresses };
233
+ }
234
+ catch {
235
+ return { ok: false, reason: "host" };
236
+ }
237
+ }
238
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
239
+ /**
240
+ * 带 SSRF 收口(URL 校验 + DNS 解析后 IP 校验 + 重定向逐跳校验)的安全 fetch 封装。
241
+ */
242
+ export async function safeFetch(url, init = {}, opts = {}) {
243
+ const fetcher = opts.fetcher ?? ((u, i) => fetch(u, i));
244
+ const useDns = opts.skipDnsLookup !== undefined ? !opts.skipDnsLookup : !!opts.lookup || (!opts.fetcher && isNativeGlobalFetch());
245
+ const maxRedirects = opts.maxRedirects ?? 5;
246
+ let currentUrl = url;
247
+ let currentInit = { ...init, redirect: "manual" };
248
+ for (let hop = 0; hop <= maxRedirects; hop++) {
249
+ const check = useDns
250
+ ? await resolveAndValidateUrl(currentUrl, { lookup: opts.lookup })
251
+ : validateFetchUrl(currentUrl);
252
+ if (!check.ok) {
253
+ throw new Error(check.reason === "scheme"
254
+ ? `Blocked URL scheme: ${currentUrl}`
255
+ : `Blocked private or internal host: ${currentUrl}`);
256
+ }
257
+ currentUrl = check.url;
258
+ const res = await fetcher(currentUrl, currentInit);
259
+ if (!REDIRECT_STATUSES.has(res.status)) {
260
+ return res;
261
+ }
262
+ const location = res.headers?.get?.("location");
263
+ if (!location) {
264
+ return res;
265
+ }
266
+ if (hop === maxRedirects) {
267
+ throw new Error(`Too many redirects (> ${maxRedirects})`);
268
+ }
269
+ const nextUrl = new URL(location, currentUrl).toString();
270
+ // 303 或 301/302 POST 重定向按规范退化为 GET
271
+ if (res.status === 303 || ((res.status === 301 || res.status === 302) && currentInit.method === "POST")) {
272
+ currentInit = { ...currentInit, method: "GET", body: undefined };
273
+ }
274
+ currentUrl = nextUrl;
275
+ }
276
+ throw new Error(`Too many redirects (> ${maxRedirects})`);
277
+ }
@@ -51,6 +51,9 @@ const BLOCKED_TOOLS = new Set([
51
51
  "eval",
52
52
  // QuickJS 沙箱代码执行(可嵌套调用写工具/命令,计划模式禁止任意代码执行)
53
53
  "codemode",
54
+ // MCP 服务器配置管理(install/remove 会修改 mcp.json 并拉起新子进程)
55
+ "mcp_manage",
56
+ "sandbox",
54
57
  // 形态变换(会重写整个文件树)
55
58
  "format",
56
59
  "prettier",
@@ -264,6 +264,30 @@ export const HOST_METHODS = [
264
264
  example: `host.events.on("notes:changed", () => {})`,
265
265
  },
266
266
  { name: "models.list", needs: "-", summary: "列出已配置鉴权的模型(provider/id)", example: `host.models.list()` },
267
+ {
268
+ name: "mcp.list",
269
+ needs: "-",
270
+ summary: "列出已配置的全局与项目级 MCP 服务器及运行态/工具列表",
271
+ example: `await host.mcp.list()`,
272
+ },
273
+ {
274
+ name: "mcp.check",
275
+ needs: "-",
276
+ summary: "按名称、npm 包名、命令或 URL 检查指定 MCP 是否已安装/运行中",
277
+ example: `await host.mcp.check("filesystem")`,
278
+ },
279
+ {
280
+ name: "mcp.install",
281
+ needs: "tools",
282
+ summary: "安装/配置 MCP 服务器(支持 package 快捷方式)并立即触发热加载",
283
+ example: `await host.mcp.install({ package: "@modelcontextprotocol/server-memory" })`,
284
+ },
285
+ {
286
+ name: "mcp.promptInstall",
287
+ needs: "chat",
288
+ summary: "向当前对话发送指令,让 AI 检查并安装指定的 MCP 服务器",
289
+ example: `await host.mcp.promptInstall("@modelcontextprotocol/server-filesystem")`,
290
+ },
267
291
  {
268
292
  name: "scm",
269
293
  needs: "-",
@@ -39,6 +39,7 @@ import { applyPostEdit, denialText, freezeParams, isBlockingDecision, normalizeP
39
39
  import { normalizeWorkspaceRoots } from "./client-state.js";
40
40
  import { compareVersions, ensureBackup } from "./plugin-updater.js";
41
41
  import { createProject, isInsideRoot, realPathOfNearest, } from "./plugin-project.js";
42
+ import { listAllMcpServers, checkMcpServer, installMcpServer, } from "./mcp-manager.js";
42
43
  import { createHash } from "node:crypto";
43
44
  import { execFile } from "node:child_process";
44
45
  import { promisify } from "node:util";
@@ -1580,6 +1581,8 @@ export class PluginManager {
1580
1581
  runAborter = undefined;
1581
1582
  /** 由 index.ts 接入 agent-service:模型列表(host.models.list 的底层)。无注入回 []。 */
1582
1583
  modelLister = undefined;
1584
+ /** 由 index.ts 接入 McpBridge:供 host.mcp 读取实时运行状态与热重载。 */
1585
+ mcpBridge = undefined;
1583
1586
  /** 插件能力动态授权表(host.requestPermission 的底层,见 server/plugin-permissions.ts)。 */
1584
1587
  permGrants;
1585
1588
  /** 由 index.ts 注入:向浏览器请求能力授权的用户确认({ok, remember})。
@@ -3757,6 +3760,116 @@ export class PluginManager {
3757
3760
  }
3758
3761
  },
3759
3762
  },
3763
+ mcp: {
3764
+ list: async () => {
3765
+ try {
3766
+ const res = listAllMcpServers({
3767
+ agentDir: self.mcpBridge?.getAgentDir(),
3768
+ cwd: self.cwdValue,
3769
+ dataDir: self.dataDir,
3770
+ bridge: self.mcpBridge,
3771
+ });
3772
+ return res.servers;
3773
+ }
3774
+ catch (err) {
3775
+ console.error(`[plugin:${info.id}] mcp.list failed:`, err);
3776
+ return [];
3777
+ }
3778
+ },
3779
+ check: async (query) => {
3780
+ try {
3781
+ return checkMcpServer({
3782
+ agentDir: self.mcpBridge?.getAgentDir(),
3783
+ cwd: self.cwdValue,
3784
+ dataDir: self.dataDir,
3785
+ bridge: self.mcpBridge,
3786
+ query: String(query ?? ""),
3787
+ });
3788
+ }
3789
+ catch (err) {
3790
+ console.error(`[plugin:${info.id}] mcp.check failed:`, err);
3791
+ return { installed: false, running: false, enabled: false, server: null, matches: [], tools: [] };
3792
+ }
3793
+ },
3794
+ install: async (spec) => {
3795
+ if (!can("tools")) {
3796
+ return { ok: false, error: '插件未声明能力 "tools"(manifest.permissions)——请求被拒' };
3797
+ }
3798
+ try {
3799
+ const res = await installMcpServer({
3800
+ agentDir: self.mcpBridge?.getAgentDir(),
3801
+ cwd: self.cwdValue,
3802
+ dataDir: self.dataDir,
3803
+ bridge: self.mcpBridge,
3804
+ spec: spec ?? {},
3805
+ });
3806
+ if (res.ok) {
3807
+ try {
3808
+ self.onAgentToolsChanged?.();
3809
+ }
3810
+ catch {
3811
+ /* ignore */
3812
+ }
3813
+ }
3814
+ return res;
3815
+ }
3816
+ catch (err) {
3817
+ return { ok: false, error: err.message };
3818
+ }
3819
+ },
3820
+ promptInstall: async (target, opts) => {
3821
+ if (!can("chat") && !can("tools")) {
3822
+ return { ok: false, error: '插件未声明能力 "chat" 或 "tools"(manifest.permissions)——请求被拒' };
3823
+ }
3824
+ const scope = opts?.scope === "global" ? "global" : "project";
3825
+ let desc = "";
3826
+ if (typeof target === "string") {
3827
+ desc = target.trim();
3828
+ }
3829
+ else if (target && typeof target === "object") {
3830
+ const parts = [];
3831
+ if (target.name)
3832
+ parts.push(`name="${target.name}"`);
3833
+ if (target.package)
3834
+ parts.push(`package="${target.package}"`);
3835
+ if (target.command)
3836
+ parts.push(`command="${target.command}"`);
3837
+ if (target.args?.length)
3838
+ parts.push(`args=${JSON.stringify(target.args)}`);
3839
+ if (target.url)
3840
+ parts.push(`url="${target.url}"`);
3841
+ desc = parts.join(", ");
3842
+ }
3843
+ if (!desc) {
3844
+ return { ok: false, error: "mcp.promptInstall: target 不能为空" };
3845
+ }
3846
+ const cfgFile = scope === "global" ? "~/.pi/agent/mcp.json" : ".pi/mcp.json";
3847
+ const promptText = `请检查并安装以下 MCP 服务器(作用域:${scope},配置文件:\`${cfgFile}\`):${desc}。\n` +
3848
+ `- 若当前会话已启用 \`mcp_manage\` 工具,请先调用 \`mcp_manage({ action: "check", query: ... })\` 确认是否已安装,未安装则调用 \`mcp_manage({ action: "install", scope: "${scope}", ... })\` 完成安装并验证状态;\n` +
3849
+ `- 若未启用 \`mcp_manage\` 工具,请用 \`read\` 检查 \`${cfgFile}\`,并在 \`mcpServers\` 字段下写入对应的服务器配置(例如 \`{ "command": "npx", "args": ["-y", "<package>"] }\`),保存后系统会自动热加载该 MCP 服务器。`;
3850
+ const targetConvId = (typeof opts?.conversationId === "string" && opts.conversationId.trim()) ||
3851
+ self.conversationProvider?.()?.conversationId;
3852
+ if (targetConvId && self.conversationWriter) {
3853
+ try {
3854
+ const r = await self.conversationWriter(targetConvId, promptText);
3855
+ return { ok: r.ok, conversationId: targetConvId, ...(r.error ? { error: r.error } : {}) };
3856
+ }
3857
+ catch (err) {
3858
+ return { ok: false, error: err.message };
3859
+ }
3860
+ }
3861
+ if (self.chatProvider) {
3862
+ try {
3863
+ const r = await self.chatProvider(info.id, { text: promptText });
3864
+ return { ok: true, conversationId: r.conversationId };
3865
+ }
3866
+ catch (err) {
3867
+ return { ok: false, error: err.message };
3868
+ }
3869
+ }
3870
+ return { ok: false, error: "无可用对话通道(conversationWriter / chatProvider 未接入)" };
3871
+ },
3872
+ },
3760
3873
  onStats: (h) => {
3761
3874
  self.statsHandlers.add(h);
3762
3875
  return effects.add("onStats", () => {
@@ -31,8 +31,10 @@ import { pick } from "./i18n.js";
31
31
  import { normalizeSoftCapByModel, normalizeSoftCapTokens } from "./soft-cap.js";
32
32
  import { ALL_KNOWN_AGENT_TOOL_NAMES, isConfigurableAgentTool, normalizeDisabledAgentTools, resolveDisabledAgentToolsFromEnabled, resolveEnabledAgentTools, } from "./tool-manager.js";
33
33
  import { normalizeToolPromptOverrides } from "./tool-prompt-overrides.js";
34
+ import { isBlockedHost, isNativeGlobalFetch, resolveAndValidateUrl, validateFetchUrl, } from "./net-guard.js";
34
35
  import { PRESET_FIELD_NAMES, normalizePresetFieldSelection } from "./preset-fields.js";
35
36
  import { defaultFetcher } from "./update-check.js";
37
+ export { isBlockedHost, resolveAndValidateUrl, validateFetchUrl };
36
38
  const execFileAsync = promisify(execFile);
37
39
  /** 预览文本的截断长度(设置面板展示用)。 */
38
40
  const PREVIEW_TEXT_MAX = 400;
@@ -559,52 +561,60 @@ export function presetSummary(settings) {
559
561
  /* ------------------------------------------------------------------ */
560
562
  /* 抓取(目录 / 网址导入) */
561
563
  /* ------------------------------------------------------------------ */
562
- /** SSRF 收口:内网/回环/链路本地地址一律拒绝(预设来源只该是公网)。 */
563
- export function isBlockedHost(hostname) {
564
- const host = hostname
565
- .trim()
566
- .toLowerCase()
567
- .replace(/^\[|\]$/g, "");
568
- if (!host)
569
- return true;
570
- if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) {
571
- return true;
572
- }
573
- if (host === "::1" || host === "::" || host.startsWith("fe80:") || /^f[cd][0-9a-f]{2}:/.test(host))
574
- return true;
575
- const m = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
576
- if (!m)
577
- return false;
578
- const [a, b] = [Number(m[1]), Number(m[2])];
579
- return (a === 0 ||
580
- a === 10 ||
581
- a === 127 ||
582
- (a === 169 && b === 254) ||
583
- (a === 172 && b >= 16 && b <= 31) ||
584
- (a === 192 && b === 168) ||
585
- a >= 224);
586
- }
587
- /** 校验一个可抓取地址:只允许 http/https 且非内网。 */
588
- export function validateFetchUrl(raw) {
589
- let u;
590
- try {
591
- u = new URL(String(raw ?? "").trim());
592
- }
593
- catch {
594
- return { ok: false, reason: "scheme" };
595
- }
596
- if (u.protocol !== "http:" && u.protocol !== "https:")
597
- return { ok: false, reason: "scheme" };
598
- if (isBlockedHost(u.hostname))
599
- return { ok: false, reason: "host" };
600
- return { ok: true, url: u.toString() };
601
- }
602
- /** 带超时与大小上限的抓取(只走注入的 Fetcher)。 */
564
+ /** 带超时、大小上限、DNS 解析后 IP 校验与重定向逐跳校验的抓取(#602)。 */
603
565
  export async function fetchText(url, opts = {}) {
604
566
  const fetcher = opts.fetcher ?? defaultTextFetcher;
605
567
  const timeoutMs = opts.timeoutMs ?? FETCH_TIMEOUT_MS;
606
568
  const maxBytes = opts.maxBytes ?? PRESET_JSON_MAX_BYTES;
607
- const res = await fetcher(url, { signal: AbortSignal.timeout(timeoutMs) });
569
+ const maxRedirects = opts.maxRedirects ?? 5;
570
+ // 真实抓取或显式注入 lookup 时执行 DNS 解析后内网 IP 校验(防 DNS rebinding);
571
+ // 纯内存 mock fetcher(未传 lookup)仅执行 URL 校验与重定向逐跳校验。
572
+ const useDns = !!opts.lookup || (!opts.fetcher && isNativeGlobalFetch());
573
+ let currentUrl = url;
574
+ let res = null;
575
+ for (let hop = 0; hop <= maxRedirects; hop++) {
576
+ const check = useDns
577
+ ? await resolveAndValidateUrl(currentUrl, { lookup: opts.lookup })
578
+ : validateFetchUrl(currentUrl);
579
+ if (!check.ok) {
580
+ return {
581
+ ok: false,
582
+ errorKey: check.reason === "scheme" ? "presets.url.scheme" : "presets.url.host",
583
+ error: check.reason === "scheme"
584
+ ? "Only http:// and https:// URLs are supported"
585
+ : "Private, loopback, or internal addresses are blocked",
586
+ };
587
+ }
588
+ currentUrl = check.url;
589
+ res = await fetcher(currentUrl, { signal: AbortSignal.timeout(timeoutMs), redirect: "manual" });
590
+ if (res.status === 301 || res.status === 302 || res.status === 303 || res.status === 307 || res.status === 308) {
591
+ const location = res.headers?.get?.("location");
592
+ if (!location)
593
+ break;
594
+ if (hop === maxRedirects) {
595
+ return {
596
+ ok: false,
597
+ errorKey: "presets.fetch.status",
598
+ error: `Too many redirects (> ${maxRedirects})`,
599
+ };
600
+ }
601
+ try {
602
+ currentUrl = new URL(location, currentUrl).toString();
603
+ }
604
+ catch {
605
+ return {
606
+ ok: false,
607
+ errorKey: "presets.url.scheme",
608
+ error: "Invalid redirect URL",
609
+ };
610
+ }
611
+ continue;
612
+ }
613
+ break;
614
+ }
615
+ if (!res) {
616
+ return { ok: false, errorKey: "presets.fetch.status", error: "Empty response" };
617
+ }
608
618
  if (!res.ok) {
609
619
  return {
610
620
  ok: false,
@@ -612,6 +622,44 @@ export async function fetchText(url, opts = {}) {
612
622
  error: `HTTP ${res.status}${res.statusText ? ` ${res.statusText}` : ""}`,
613
623
  };
614
624
  }
625
+ // 流式累计到上限即取消:先整读进内存再查上限,一个几百 MB 的响应照样
626
+ // 在超时窗口内把缓冲打爆(AbortSignal 只断超时,不限字节)
627
+ const body = res.body;
628
+ if (body) {
629
+ const reader = body.getReader();
630
+ const decoder = new TextDecoder();
631
+ let received = 0;
632
+ const chunks = [];
633
+ for (;;) {
634
+ const { done, value } = await reader.read();
635
+ if (done)
636
+ break;
637
+ if (!value)
638
+ continue;
639
+ received += value.byteLength;
640
+ if (received > maxBytes) {
641
+ try {
642
+ await reader.cancel();
643
+ }
644
+ catch {
645
+ /* body already consumed/closed */
646
+ }
647
+ return {
648
+ ok: false,
649
+ errorKey: "presets.fetch.tooLarge",
650
+ error: `Content too large (> ${Math.round(maxBytes / 1024)} KB)`,
651
+ };
652
+ }
653
+ chunks.push(value);
654
+ }
655
+ const merged = new Uint8Array(received);
656
+ let offset = 0;
657
+ for (const chunk of chunks) {
658
+ merged.set(chunk, offset);
659
+ offset += chunk.byteLength;
660
+ }
661
+ return { ok: true, text: decoder.decode(merged) };
662
+ }
615
663
  const text = await res.text();
616
664
  if (Buffer.byteLength(text, "utf8") > maxBytes) {
617
665
  return {