@him666233/dsh-inline-diff 1.4.0 → 1.4.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.
package/index.js CHANGED
@@ -17,6 +17,7 @@
17
17
  * POST /dsh-inline-diff/api/read { cwd, path }
18
18
  * GET /dsh-inline-diff/api/update/versions 版本列表/当前版本/安装方式
19
19
  * POST /dsh-inline-diff/api/update/install { version } 安装/回退
20
+ * GET /dsh-inline-diff/api/tools 当前可见工具名(第三方工具兼容)
20
21
  * GET /dsh-inline-diff/api/ping
21
22
  *
22
23
  * 读取路由永远不离开会话工作区(请求路径与解析后路径都做 realpath 包含
@@ -51,9 +52,10 @@
51
52
  * 调用本身;快照缺失时历史回放会自动回退到文件读取/差异块。
52
53
  */
53
54
  import { spawn } from 'node:child_process'
54
- import { readFile, realpath, stat } from 'node:fs/promises'
55
+ import { existsSync, readFileSync } from 'node:fs'
56
+ import { mkdir, readFile, realpath, rename, stat, writeFile } from 'node:fs/promises'
55
57
  import { homedir } from 'node:os'
56
- import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
58
+ import { dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path'
57
59
  import { fileURLToPath } from 'node:url'
58
60
 
59
61
  /** webServer 服务承载本插件的前缀路由(通过 inject 注入)。 */
@@ -63,6 +65,12 @@ export const inject = ['webServer']
63
65
  const API_PREFIX = '/dsh-inline-diff/api'
64
66
  /** 展示读取上限:更大的文件返回 `oversized`,浏览器降级为差异块视图。 */
65
67
  const READ_CAP = 2 * 1024 * 1024
68
+ /** 用户显式授权的工作区外可读目录上限(设置页维护)。 */
69
+ const READ_ROOTS_MAX = 12
70
+ /** 单个授权目录路径长度上限。 */
71
+ const READ_ROOTS_PATH_MAX = 4096
72
+ /** 授权目录清单文件的缓存时间(设置页写入后会主动刷新)。 */
73
+ const READ_ROOTS_CACHE_TTL_MS = 5_000
66
74
  /** 请求体大小上限。 */
67
75
  const BODY_CAP = 1024 * 1024
68
76
  /** 所有会话合计保留的快照条目数(有界内存 LRU)。 */
@@ -85,6 +93,10 @@ const READ_TIMEOUT_MS = 15_000
85
93
  const MAX_CONCURRENT_READS = 8
86
94
  /** 快照 key 来自客户端;限制长度让 key 保持小而可比较。 */
87
95
  const MAX_ID_LENGTH = 512
96
+ /** 工具名上限:Host 注册表的 wire name 不会这么长,超过的一律丢弃。 */
97
+ const MAX_TOOL_NAME_LENGTH = 200
98
+ /** 单次 `/tools` 应答最多列出的工具数(MCP 等可能一次暴露很多工具)。 */
99
+ const MAX_TOOL_NAMES = 500
88
100
 
89
101
  /**
90
102
  * 只读边界常量。导出仅供 `tests/security.test.mjs` 断言真实生产值(避免测试里
@@ -100,6 +112,8 @@ export const LIMITS = Object.freeze({
100
112
  readTimeoutMs: READ_TIMEOUT_MS,
101
113
  maxConcurrentReads: MAX_CONCURRENT_READS,
102
114
  maxIdLength: MAX_ID_LENGTH,
115
+ maxToolNameLength: MAX_TOOL_NAME_LENGTH,
116
+ maxToolNames: MAX_TOOL_NAMES,
103
117
  })
104
118
 
105
119
  /** 一个带类型的请求失败:`status` 是应答用的 HTTP 状态码。 */
@@ -107,11 +121,13 @@ class RequestError extends Error {
107
121
  /**
108
122
  * @param {number} status
109
123
  * @param {string} message - 稳定、不敏感的客户端可读消息(不回显 fs 细节)
124
+ * @param {string} [code] - 稳定错误码(设置页等需要按码显示文案时使用)
110
125
  */
111
- constructor(status, message) {
126
+ constructor(status, message, code) {
112
127
  super(message)
113
128
  this.name = 'RequestError'
114
129
  this.status = status
130
+ if (typeof code === 'string') this.code = code
115
131
  }
116
132
  }
117
133
 
@@ -196,7 +212,22 @@ export function clearSnapshots() {
196
212
  /** 判断候选路径是根本身还是位于根之下(不允许 `..` 逃逸,`relative` 为空表示根)。 */
197
213
  export function inside(root, candidate) {
198
214
  const child = relative(root, candidate)
199
- return child === '' || (!child.startsWith('..') && !isAbsolute(child))
215
+ // 不能只用 startsWith('..'):根下名为 `..notes.txt` 的合法文件也会以 `..`
216
+ // 开头,必须按路径段判断。
217
+ return child === '' || (!isAbsolute(child) && child !== '..' && !child.startsWith('..' + sep))
218
+ }
219
+
220
+ /** Windows 与默认 APFS 大小写不敏感;路径比较按平台归一,避免误拒。 */
221
+ function foldPathForPlatform(value) {
222
+ return process.platform === 'win32' || process.platform === 'darwin' ? value.toLowerCase() : value
223
+ }
224
+
225
+ /** target 是否等于 root 或位于 root 之下(两者都应是规范绝对路径)。 */
226
+ function isSameOrInside(root, target) {
227
+ const rootKey = foldPathForPlatform(root)
228
+ const targetKey = foldPathForPlatform(target)
229
+ if (targetKey === rootKey) return true
230
+ return targetKey.startsWith(rootKey.endsWith(sep) ? rootKey : rootKey + sep)
200
231
  }
201
232
 
202
233
  /**
@@ -204,16 +235,24 @@ export function inside(root, candidate) {
204
235
  * → 结果再包含校验。符号链接只有目标仍在根内才放行(指向工作区外的链接或
205
236
  * Windows junction 读不到根外内容)。
206
237
  *
238
+ * `extraRoots` 是用户显式授权的额外可读目录(设置页维护):候选路径或 realpath
239
+ * 之后的目标只要落在其中任一目录下也放行。这样工作区外文件的历史回放/全文对照
240
+ * 可以按用户授权读取,而不是放开任意根。
241
+ *
207
242
  * 失败一律抛带状态码的 RequestError,且消息固定:绝不把原始 fs 错误
208
243
  * (含用户请求的绝对路径与 errno)回给调用方。
209
244
  *
245
+ * @param {string} cwd - 会话工作区根。
246
+ * @param {string} requestedPath - 请求路径(绝对或相对 cwd)。
247
+ * @param {string[]} [extraRoots] - 已规范化的额外可读目录。
210
248
  * @returns {Promise<{ filename: string, size: number }>} 解析后的真实文件名与大小。
211
249
  */
212
- export async function resolveReadTarget(cwd, requestedPath) {
250
+ export async function resolveReadTarget(cwd, requestedPath, extraRoots = []) {
213
251
  if (typeof cwd !== 'string' || cwd === '') throw new RequestError(400, 'cwd is required')
214
252
  if (typeof requestedPath !== 'string' || requestedPath === '') throw new RequestError(400, 'path is required')
215
253
  // NUL 会截断底层系统调用,属于非法路径而不是普通“不存在”。
216
254
  if (cwd.includes('\0') || requestedPath.includes('\0')) throw new RequestError(400, 'path is invalid')
255
+ const roots = Array.isArray(extraRoots) ? extraRoots.filter(root => typeof root === 'string' && root !== '') : []
217
256
  let root
218
257
  try {
219
258
  root = await realpath(cwd)
@@ -221,16 +260,20 @@ export async function resolveReadTarget(cwd, requestedPath) {
221
260
  throw new RequestError(404, 'workspace is not readable')
222
261
  }
223
262
  const candidate = resolve(root, requestedPath)
224
- if (!inside(root, candidate)) throw new RequestError(403, 'path is outside the session workspace')
263
+ if (!inside(root, candidate) && !roots.some(extra => isSameOrInside(extra, candidate))) {
264
+ throw new RequestError(403, 'path is outside the session workspace')
265
+ }
225
266
  let filename
226
267
  try {
227
- // 符号链接在这里解析:只有 realpath 之后仍在根内才放行,因此一个指向
228
- // 工作区外的链接(或 Windows junction)无法读出根外内容。
268
+ // 符号链接在这里解析:只有 realpath 之后仍在根内(或授权的额外目录内)才
269
+ // 放行,因此一个指向其它位置的链接无法绕过围栏。
229
270
  filename = await realpath(candidate)
230
271
  } catch {
231
272
  throw new RequestError(404, 'file is not readable')
232
273
  }
233
- if (!inside(root, filename)) throw new RequestError(403, 'resolved path is outside the session workspace')
274
+ if (!inside(root, filename) && !roots.some(extra => isSameOrInside(extra, filename))) {
275
+ throw new RequestError(403, 'resolved path is outside the session workspace')
276
+ }
234
277
  let info
235
278
  try {
236
279
  info = await stat(filename)
@@ -241,6 +284,221 @@ export async function resolveReadTarget(cwd, requestedPath) {
241
284
  return { filename, size: info.size }
242
285
  }
243
286
 
287
+ /**
288
+ * 把展示文件字节解码成文本;无法作为文本展示时返回 null。
289
+ *
290
+ * 识别 UTF-8 BOM 与 UTF-16 LE/BE BOM(记事本「Unicode」默认写 UTF-16LE):
291
+ * 直接按字节里有没有 NUL 判二进制会把 UTF-16 文本误判成二进制,导致历史回放
292
+ * 无法展示文件内容。UTF-16 解码后仍含 NUL 的才视为二进制。
293
+ *
294
+ * @param {Buffer} bytes
295
+ * @returns {string|null}
296
+ */
297
+ function decodeDisplayText(bytes) {
298
+ if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe) {
299
+ const text = bytes.subarray(2).toString('utf16le')
300
+ return text.includes('\u0000') ? null : text
301
+ }
302
+ if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) {
303
+ const body = bytes.subarray(2)
304
+ const even = body.length - (body.length % 2)
305
+ const swapped = Buffer.allocUnsafe(even)
306
+ for (let index = 0; index < even; index += 2) {
307
+ swapped[index] = body[index + 1]
308
+ swapped[index + 1] = body[index]
309
+ }
310
+ const text = swapped.toString('utf16le')
311
+ return text.includes('\u0000') ? null : text
312
+ }
313
+ if (bytes.includes(0)) return null
314
+ const text = bytes.toString('utf8')
315
+ // 开头的 BOM 属于展示噪声;差异基准本身也是纯文本,去掉不留痕。
316
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text
317
+ }
318
+
319
+ // ---------------------------------------------------------------------------
320
+ // 用户授权的额外可读目录(工作区外文件的历史回放)
321
+ // ---------------------------------------------------------------------------
322
+
323
+ /** DSH home:与 DSH 的 DSH_HOME 语义一致;测试可临时覆盖环境变量。 */
324
+ function dshHomeDir() {
325
+ return typeof process.env.DSH_HOME === 'string' && process.env.DSH_HOME !== ''
326
+ ? process.env.DSH_HOME
327
+ : join(homedir(), '.dsh')
328
+ }
329
+
330
+ /** 授权目录清单文件(Host 侧持久化,不写 localStorage/不随浏览器清空)。 */
331
+ function readRootsFilePath() {
332
+ return join(dshHomeDir(), 'dsh-inline-diff', 'read-roots.json')
333
+ }
334
+
335
+ /** 每个清单文件一份缓存:DSH_HOME 变化或 TTL 过期时重新读取。 */
336
+ let readRootsCache = { key: '', at: 0, roots: [] }
337
+
338
+ /**
339
+ * 校验并规范化一个用户输入的可读目录。
340
+ *
341
+ * 安全约束:必须是绝对路径、存在、是目录;拒绝文件系统根(`/`、`C:\`、UNC
342
+ * share 根),避免“加一个根 = 恢复任意文件读取”的误操作。符号链接按 realpath
343
+ * 落到真实目录后保存。
344
+ *
345
+ * @param {unknown} value
346
+ * @returns {Promise<string>} 规范绝对路径
347
+ */
348
+ async function canonicalizeReadRoot(value) {
349
+ if (typeof value !== 'string') throw new RequestError(400, 'invalid root', 'invalid-root')
350
+ const trimmed = value.trim()
351
+ if (trimmed === '') throw new RequestError(400, 'invalid root', 'invalid-root')
352
+ if (trimmed.length > READ_ROOTS_PATH_MAX) throw new RequestError(400, 'invalid root', 'invalid-root')
353
+ if (/[\u0000-\u001f]/.test(trimmed)) throw new RequestError(400, 'invalid root', 'invalid-root')
354
+ if (!isAbsolute(trimmed)) throw new RequestError(400, 'root must be absolute', 'root-not-absolute')
355
+ let canonical
356
+ try {
357
+ canonical = await realpath(trimmed)
358
+ } catch {
359
+ throw new RequestError(400, 'root is not readable', 'root-not-readable')
360
+ }
361
+ let info
362
+ try {
363
+ info = await stat(canonical)
364
+ } catch {
365
+ throw new RequestError(400, 'root is not readable', 'root-not-readable')
366
+ }
367
+ if (!info.isDirectory()) throw new RequestError(400, 'root is not a directory', 'root-not-directory')
368
+ if (canonical === parse(canonical).root) {
369
+ throw new RequestError(400, 'filesystem root is not allowed', 'filesystem-root')
370
+ }
371
+ return canonical
372
+ }
373
+
374
+ /**
375
+ * 规范化一份目录清单:去重、最多 READ_ROOTS_MAX 条。
376
+ *
377
+ * @param {unknown} input
378
+ * @param {boolean} strict - true:POST 设置,遇到非法条目直接抛错;
379
+ * false:读取持久化文件,跳过损坏/已不存在的条目,保留其余。
380
+ * @returns {Promise<string[]>}
381
+ */
382
+ async function normalizeReadRoots(input, strict) {
383
+ if (!Array.isArray(input)) {
384
+ if (strict) throw new RequestError(400, 'roots must be an array', 'invalid-roots')
385
+ return []
386
+ }
387
+ if (input.length > READ_ROOTS_MAX && strict) {
388
+ throw new RequestError(400, 'too many roots', 'too-many-roots')
389
+ }
390
+ const roots = []
391
+ const seen = new Set()
392
+ for (const value of input.slice(0, READ_ROOTS_MAX)) {
393
+ let canonical
394
+ try {
395
+ canonical = await canonicalizeReadRoot(value)
396
+ } catch (error) {
397
+ if (strict) throw error
398
+ continue
399
+ }
400
+ const key = foldPathForPlatform(canonical)
401
+ if (seen.has(key)) continue
402
+ seen.add(key)
403
+ roots.push(canonical)
404
+ }
405
+ return roots
406
+ }
407
+
408
+ /** 读取当前授权目录;文件缺失/损坏时返回空数组(读取能力退回工作区围栏)。 */
409
+ async function loadReadRoots() {
410
+ const file = readRootsFilePath()
411
+ if (readRootsCache.key === file && Date.now() - readRootsCache.at < READ_ROOTS_CACHE_TTL_MS) {
412
+ return readRootsCache.roots
413
+ }
414
+ let roots = []
415
+ try {
416
+ const data = JSON.parse(await readFile(file, 'utf8'))
417
+ roots = await normalizeReadRoots(data?.roots, false)
418
+ } catch {
419
+ roots = []
420
+ }
421
+ readRootsCache = { key: file, at: Date.now(), roots }
422
+ return roots
423
+ }
424
+
425
+ /** 原子地写入授权目录清单(先写临时文件再 rename),并刷新缓存。 */
426
+ async function saveReadRoots(roots) {
427
+ const file = readRootsFilePath()
428
+ const temp = `${file}.tmp-${process.pid}-${Date.now()}`
429
+ try {
430
+ await mkdir(dirname(file), { recursive: true })
431
+ await writeFile(temp, `${JSON.stringify({ roots }, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
432
+ await rename(temp, file)
433
+ } catch {
434
+ throw new RequestError(500, 'read roots are not writable', 'read-roots-unwritable')
435
+ }
436
+ readRootsCache = { key: file, at: Date.now(), roots }
437
+ }
438
+
439
+ /**
440
+ * 请求的路径(解析 realpath 后)是否落在某个用户授权目录内。
441
+ * 用于 cwd 不是注册 workspace 时判断这次读取是否有明确授权。
442
+ */
443
+ async function requestedPathInExtraRoots(cwd, requestedPath, roots) {
444
+ if (!Array.isArray(roots) || roots.length === 0) return false
445
+ if (typeof cwd !== 'string' || cwd === '' || typeof requestedPath !== 'string' || requestedPath === '') return false
446
+ let target
447
+ try {
448
+ target = await realpath(isAbsolute(requestedPath) ? requestedPath : resolve(cwd, requestedPath))
449
+ } catch {
450
+ return false
451
+ }
452
+ return roots.some(root => isSameOrInside(root, target))
453
+ }
454
+
455
+ /**
456
+ * 展示读取的根目录是否可信:必须等于某个已注册 workspace 的规范路径,或位于
457
+ * 它之下(会话 cwd 通常就是 workspace 根)。
458
+ *
459
+ * `/read` 的 `cwd` 来自浏览器请求;如果只按“调用方给的根”做 realpath 围栏,
460
+ * 任何同源脚本都能把根设成 `/` 或盘符根读取宿主可读的任意小文件(浏览器信任
461
+ * 边界挡不住同源第三方主题/插件)。这里用 DSH 的 `workspaceRegistry` 把读取
462
+ * 限定在用户真正打开过的工作区;registry 不存在(嵌入式/旧 profile)时保持
463
+ * 既有行为,避免破坏历史回放。
464
+ *
465
+ * @param {object} ctx - Host 插件 context。
466
+ * @param {string} cwd - 请求方给出的读取根。
467
+ * @returns {Promise<boolean>}
468
+ */
469
+ async function readRootAllowed(ctx, cwd) {
470
+ let registry
471
+ try {
472
+ registry = typeof ctx?.get === 'function' ? ctx.get('workspaceRegistry') : undefined
473
+ } catch {
474
+ registry = undefined
475
+ }
476
+ if (registry === null || registry === undefined || typeof registry.list !== 'function') {
477
+ // 没有 workspace 服务:保持 1.4.1 之前的“调用方根 + realpath 围栏”行为。
478
+ return true
479
+ }
480
+ let canonical
481
+ try {
482
+ canonical = await realpath(cwd)
483
+ } catch {
484
+ return false
485
+ }
486
+ let workspaces
487
+ try {
488
+ workspaces = registry.list()
489
+ } catch {
490
+ // 服务存在但不可用:fail-closed,展示读取降级为差异块。
491
+ return false
492
+ }
493
+ if (!Array.isArray(workspaces)) return false
494
+ for (const workspace of workspaces) {
495
+ const root = workspace !== null && typeof workspace === 'object' ? workspace.path : undefined
496
+ if (typeof root !== 'string' || root === '') continue
497
+ if (isSameOrInside(root, canonical)) return true
498
+ }
499
+ return false
500
+ }
501
+
244
502
  /**
245
503
  * 读取一个展示目标;用 `kind` 显式告诉浏览器如何降级。
246
504
  *
@@ -250,8 +508,8 @@ export async function resolveReadTarget(cwd, requestedPath) {
250
508
  * @returns {Promise<{kind:'text', text:string, size:number} |
251
509
  * {kind:'binary'|'oversized', size:number}>}
252
510
  */
253
- async function readDisplayTarget(cwd, requestedPath) {
254
- const target = await resolveReadTarget(cwd, requestedPath)
511
+ async function readDisplayTarget(cwd, requestedPath, extraRoots = []) {
512
+ const target = await resolveReadTarget(cwd, requestedPath, extraRoots)
255
513
  if (target.size > READ_CAP) return { kind: 'oversized', size: target.size }
256
514
  const controller = new AbortController()
257
515
  const timer = setTimeout(() => controller.abort(), READ_TIMEOUT_MS)
@@ -267,10 +525,8 @@ async function readDisplayTarget(cwd, requestedPath) {
267
525
  clearTimeout(timer)
268
526
  }
269
527
  if (bytes.length > READ_CAP) return { kind: 'oversized', size: bytes.length }
270
- if (bytes.includes(0)) return { kind: 'binary', size: target.size }
271
- let text = bytes.toString('utf8')
272
- // 开头的 BOM 属于展示噪声;差异基准本身也是纯文本,去掉不留痕。
273
- if (text.charCodeAt(0) === 0xfeff) text = text.slice(1)
528
+ const text = decodeDisplayText(bytes)
529
+ if (text === null) return { kind: 'binary', size: target.size }
274
530
  return { kind: 'text', text, size: target.size }
275
531
  }
276
532
 
@@ -357,12 +613,31 @@ export function isTrustedHostRequest(req, bindHost, protocol = 'http:') {
357
613
  const loopback = isLoopbackHostname(hostUrl.hostname)
358
614
  const ownBind = hostUrl.hostname === bindHostname(bindHost)
359
615
  if (!loopback && !ownBind) return false
616
+ // DNS rebinding 的第二道:Host 写成 loopback 但 TCP 对端不是本机 → 拒绝。
617
+ // 回退围栏本来就在没有 connection 服务时使用;真实 Node 请求一定有 socket。
618
+ if (loopback) {
619
+ const peer = peerAddressOf(req)
620
+ if (peer !== undefined && !isLoopbackPeer(peer)) return false
621
+ }
360
622
  if (headerOf(headers, 'sec-fetch-site') === 'cross-site') return false
361
623
  const origin = headerOf(headers, 'origin')
362
624
  if (origin === undefined) return true
363
625
  return isSameAuthorityOrigin(origin, host)
364
626
  }
365
627
 
628
+ /** 取 TCP 对端地址;单测的伪请求不一定有 socket。 */
629
+ function peerAddressOf(req) {
630
+ const address = req !== null && typeof req === 'object' ? req.socket?.remoteAddress : undefined
631
+ return typeof address === 'string' && address !== '' ? address : undefined
632
+ }
633
+
634
+ /** 对端地址是否 loopback(兼容 IPv4-mapped IPv6 与带方括号的 ::1)。 */
635
+ function isLoopbackPeer(address) {
636
+ if (typeof address !== 'string') return false
637
+ const value = address.toLowerCase().startsWith('::ffff:') ? address.slice(7) : address
638
+ return value === '::1' || isLoopbackHostname(value)
639
+ }
640
+
366
641
  /** 读取一个 header 值(Node 已把名字转小写;单值字符串与数组首项都接受)。 */
367
642
  function headerOf(headers, name) {
368
643
  if (headers === null || typeof headers !== 'object') return undefined
@@ -636,10 +911,8 @@ function captureSnapshot(exec, result) {
636
911
  // 版本与更新(设置页自带的检查更新 / 更新 / 回退)
637
912
  // ---------------------------------------------------------------------------
638
913
 
639
- /** npm 包名(本插件自身)。 */
640
- const UPDATE_PACKAGE = '@him666233/dsh-inline-diff'
641
- /** npm registry 的 packument 地址(斜杠需编码,@scope 用 %2F)。 */
642
- const REGISTRY_URL = 'https://registry.npmjs.org/@him666233%2Fdsh-inline-diff'
914
+ /** npm 包名兜底值:正常情况下从本目录的 package.json 读取,改名后无需改 Host 代码。 */
915
+ const UPDATE_PACKAGE_FALLBACK = '@him666233/dsh-inline-diff'
643
916
  const UPDATE_FETCH_TIMEOUT_MS = 12_000
644
917
  const UPDATE_CACHE_TTL_MS = 60_000
645
918
  const UPDATE_INSTALL_TIMEOUT_MS = 240_000
@@ -677,6 +950,38 @@ async function currentPluginVersion() {
677
950
  return typeof manifest?.version === 'string' ? manifest.version : null
678
951
  }
679
952
 
953
+ /** 进程级包名缓存;package.json 不可读时回退到发布包名。 */
954
+ let packageNameCache = null
955
+
956
+ /**
957
+ * 本插件自己的 npm 包名(唯一事实来源:本目录的 package.json)。
958
+ *
959
+ * `scripts/set-package-name.mjs` 会同步清单 / patch / client.js / README,但
960
+ * 不会改 Host 代码;如果这里写死旧包名,改名后「检查更新 / 安装」会去查旧包。
961
+ * 读不到清单时回退到发布包名,功能不中断。
962
+ *
963
+ * @returns {string}
964
+ */
965
+ function updatePackageName() {
966
+ if (packageNameCache !== null) return packageNameCache
967
+ try {
968
+ const manifest = JSON.parse(readFileSync(join(selfDir(), 'package.json'), 'utf8'))
969
+ if (typeof manifest?.name === 'string' && /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(manifest.name)) {
970
+ packageNameCache = manifest.name
971
+ return packageNameCache
972
+ }
973
+ } catch {
974
+ // 包清单缺失/损坏:回退兜底值,更新面板仍可显示(安装会失败并回滚)。
975
+ }
976
+ packageNameCache = UPDATE_PACKAGE_FALLBACK
977
+ return packageNameCache
978
+ }
979
+
980
+ /** npm registry 的 packument 地址(作用域斜杠编码为 %2F,@ 保留字面量)。 */
981
+ function registryUrlOf(packageName) {
982
+ return `https://registry.npmjs.org/${packageName.startsWith('@') ? packageName.replace('/', '%2F') : packageName}`
983
+ }
984
+
680
985
  /**
681
986
  * 当前 profile 的上下文。优先用 DSH 文档化的 profileContext 服务;取不到时
682
987
  * 回退解析 `--profile <name>` / DSH_PROFILE 环境变量(Web CLI 启动场景)。
@@ -702,8 +1007,10 @@ function profileContextOf(ctx) {
702
1007
 
703
1008
  /** 是否运行在桌面 Electron 宿主里(桌面端 v1 只读展示 + 手动命令)。 */
704
1009
  function isDesktopHost() {
705
- return process.versions?.electron !== undefined
706
- || (Array.isArray(process.argv) && process.argv.some(value => String(value).includes('dsh-desktop-host')))
1010
+ if (process.versions?.electron !== undefined) return true
1011
+ // 只匹配独立路径段,避免工作区里恰好含 dsh-desktop-host 字样的路径误命中。
1012
+ return Array.isArray(process.argv)
1013
+ && process.argv.some(value => /(^|[\\/])dsh-desktop-host([\\/]|$)/.test(String(value)))
707
1014
  }
708
1015
 
709
1016
  /** semver 解析;非 semver 返回 null。 */
@@ -781,7 +1088,7 @@ async function fetchRegistryVersions(force) {
781
1088
  const controller = new AbortController()
782
1089
  const timer = setTimeout(() => controller.abort(), UPDATE_FETCH_TIMEOUT_MS)
783
1090
  try {
784
- const response = await fetch(REGISTRY_URL, {
1091
+ const response = await fetch(registryUrlOf(updatePackageName()), {
785
1092
  headers: { accept: 'application/json' },
786
1093
  signal: controller.signal,
787
1094
  })
@@ -819,11 +1126,11 @@ function installerInfo(pc) {
819
1126
  && /[\\/]node_modules[\\/]@deepseek-ai[\\/]dsh[\\/]package\.json$/.test(anchor)
820
1127
  const cliRoot = anchorLooksExpected ? dirname(anchor) : null
821
1128
  const cliBin = cliRoot === null ? null : join(cliRoot, 'lib', 'bin.js')
822
- const command = `dsh plugin --profile ${name} add ${UPDATE_PACKAGE}@<version>`
1129
+ const command = `dsh plugin --profile ${name} add ${updatePackageName()}@<version>`
823
1130
  if (isDesktopHost()) {
824
1131
  return { mode: 'manual', platform: 'desktop', command, cliBin: null, reason: 'desktop-requires-exit' }
825
1132
  }
826
- if (cliBin === null || !isAbsolute(cliBin)) {
1133
+ if (cliBin === null || !isAbsolute(cliBin) || !existsSync(cliBin)) {
827
1134
  return { mode: 'manual', platform: 'web', command, cliBin: null, reason: 'cli-not-found' }
828
1135
  }
829
1136
  return { mode: 'cli', platform: 'web', command, cliBin, reason: null }
@@ -832,7 +1139,7 @@ function installerInfo(pc) {
832
1139
  /** 读取 profile 里已安装的插件版本;读不到返回 null。 */
833
1140
  async function installedVersionAt(pc) {
834
1141
  if (pc === null || typeof pc.dir !== 'string') return null
835
- const manifest = await readJsonSafe(join(pc.dir, 'node_modules', UPDATE_PACKAGE, 'package.json'))
1142
+ const manifest = await readJsonSafe(join(pc.dir, 'node_modules', updatePackageName(), 'package.json'))
836
1143
  return typeof manifest?.version === 'string' ? manifest.version : null
837
1144
  }
838
1145
 
@@ -846,7 +1153,7 @@ async function dshVersionAt(pc) {
846
1153
  /** 在子进程里跑官方 CLI 的 plugin add;返回结构化结果(含日志尾部)。 */
847
1154
  function runPluginInstall(pc, version, installer) {
848
1155
  return new Promise((resolveResult) => {
849
- const spec = `${UPDATE_PACKAGE}@${version}`
1156
+ const spec = `${updatePackageName()}@${version}`
850
1157
  const command = `dsh plugin --profile ${pc.name} add ${spec}`
851
1158
  const args = [installer.cliBin, 'plugin', '--profile', pc.name, 'add', spec]
852
1159
  if (typeof installer.cliBin !== 'string' || !isAbsolute(installer.cliBin) || !PROFILE_NAME_PATTERN.test(pc.name)) {
@@ -860,6 +1167,9 @@ function runPluginInstall(pc, version, installer) {
860
1167
  windowsHide: true,
861
1168
  env: { ...process.env },
862
1169
  stdio: ['ignore', 'pipe', 'pipe'],
1170
+ // POSIX:让 CLI 自成一个进程组,超时时可以整组 SIGKILL;否则 pnpm 的
1171
+ // 孙进程会留在机器上(Windows 走 taskkill /T,见下面的超时分支)。
1172
+ detached: process.platform !== 'win32',
863
1173
  })
864
1174
  } catch (error) {
865
1175
  resolveResult({ ok: false, code: 'spawn-failed', command, logTail: String(error?.message ?? '') })
@@ -885,9 +1195,16 @@ function runPluginInstall(pc, version, installer) {
885
1195
  try {
886
1196
  if (process.platform === 'win32') {
887
1197
  // npm/pnpm 会拉起子进程树:只 kill 父进程会留下孤儿,因此用 taskkill /T。
888
- spawn('taskkill', ['/pid', String(child.pid), '/t', '/f'], { windowsHide: true }).on('error', () => {})
1198
+ // spawn 失败时 pid 可能缺失,不能把 "undefined" 传给 taskkill。
1199
+ if (Number.isInteger(child.pid)) spawn('taskkill', ['/pid', String(child.pid), '/t', '/f'], { windowsHide: true }).on('error', () => {})
889
1200
  } else {
890
- child.kill('SIGKILL')
1201
+ // 子进程在独立进程组里(detached),负 pid 杀整组;失败再退回只杀直接子进程。
1202
+ try {
1203
+ if (Number.isInteger(child.pid)) process.kill(-child.pid, 'SIGKILL')
1204
+ else child.kill('SIGKILL')
1205
+ } catch {
1206
+ child.kill('SIGKILL')
1207
+ }
891
1208
  }
892
1209
  } catch {
893
1210
  // 尽力而为:超时返回状态仍然明确。
@@ -963,6 +1280,72 @@ async function performUpdate(ctx, body) {
963
1280
  }
964
1281
  }
965
1282
 
1283
+ // ---------------------------------------------------------------------------
1284
+ // 工具清单(第三方工具兼容)
1285
+ // ---------------------------------------------------------------------------
1286
+
1287
+ /**
1288
+ * 每个插件 ctx 一份 `/tools` 应答缓存:工具注册/卸载(`tools/change`)时失效。
1289
+ *
1290
+ * 为什么要 Host 半侧提供清单:浏览器半侧的 keyed `tool.call.toolview` 只能按
1291
+ * wire 工具名注册视图,DSH 自己只认识内建工具;第三方插件(dsh-ssh、MCP 等)
1292
+ * 注册的工具名客户端无从得知,只能由 Host 从 `tools.definitions()` 导出。
1293
+ * 该路由只读、不落盘、不包含参数或结果。
1294
+ */
1295
+ const toolNamesByContext = new WeakMap()
1296
+
1297
+ /** 取当前进程的 tools 服务;不同 profile/嵌入式宿主缺失时返回 undefined。 */
1298
+ function toolsServiceOf(ctx) {
1299
+ try {
1300
+ if (ctx !== null && typeof ctx === 'object' && typeof ctx.get === 'function') {
1301
+ const service = ctx.get('tools')
1302
+ if (service !== null && typeof service === 'object') return service
1303
+ }
1304
+ } catch {
1305
+ // 版本漂移 / 服务尚未就绪:按“没有工具清单”处理,客户端继续用内建清单。
1306
+ }
1307
+ return undefined
1308
+ }
1309
+
1310
+ /**
1311
+ * 当前可见工具的 wire 名(去重、排序、有界)。任何异常都返回空数组,绝不让
1312
+ * 一个展示型路由把 Host 的 tools 服务拖进错误路径。
1313
+ *
1314
+ * 只读取**全局可见**定义;注册在某个 agent scope 里的工具不在其中(少数实验
1315
+ * 插件会这样做),那些工具仍走官方通用行。
1316
+ */
1317
+ export function visibleToolNames(ctx) {
1318
+ if (ctx !== null && typeof ctx === 'object' && toolNamesByContext.has(ctx)) return toolNamesByContext.get(ctx)
1319
+ const names = []
1320
+ const tools = toolsServiceOf(ctx)
1321
+ // 服务尚未就绪时不缓存空结果:之后挂载 tools 服务的宿主仍能拿到真实清单。
1322
+ if (tools === undefined) return []
1323
+ try {
1324
+ let definitions
1325
+ if (typeof tools.definitions === 'function') definitions = tools.definitions()
1326
+ else if (typeof tools.schemas === 'function') definitions = tools.schemas()
1327
+ if (Array.isArray(definitions)) {
1328
+ for (const definition of definitions) {
1329
+ const name = definition !== null && typeof definition === 'object' ? definition.name : undefined
1330
+ if (typeof name !== 'string' || name === '' || name.length > MAX_TOOL_NAME_LENGTH) continue
1331
+ names.push(name)
1332
+ if (names.length >= MAX_TOOL_NAMES) break
1333
+ }
1334
+ }
1335
+ } catch {
1336
+ return []
1337
+ }
1338
+ names.sort()
1339
+ const unique = [...new Set(names)]
1340
+ if (ctx !== null && typeof ctx === 'object') toolNamesByContext.set(ctx, unique)
1341
+ return unique
1342
+ }
1343
+
1344
+ /** 工具注册表变化时丢弃缓存,下一次 `/tools` 重新读取。 */
1345
+ export function invalidateToolNames(ctx) {
1346
+ if (ctx !== null && typeof ctx === 'object') toolNamesByContext.delete(ctx)
1347
+ }
1348
+
966
1349
  // ---------------------------------------------------------------------------
967
1350
  // 路由处理
968
1351
  // ---------------------------------------------------------------------------
@@ -984,6 +1367,17 @@ async function handleRequest(ctx, req, res) {
984
1367
  respond(res, 200, { ok: true, snapshots: snapshots.size })
985
1368
  return
986
1369
  }
1370
+ if (req.method === 'GET' && route === API_PREFIX + '/tools') {
1371
+ // 第三方工具兼容:浏览器半侧按这份清单为“官方没有视图”的工具名注册
1372
+ // 展开风格行。只回工具名,不回 schema、参数或结果。
1373
+ respond(res, 200, { ok: true, tools: visibleToolNames(ctx) })
1374
+ return
1375
+ }
1376
+ if (req.method === 'GET' && route === API_PREFIX + '/read-roots') {
1377
+ // 用户显式授权的工作区外可读目录;设置页读取当前清单。
1378
+ respond(res, 200, { ok: true, roots: await loadReadRoots(), max: READ_ROOTS_MAX })
1379
+ return
1380
+ }
987
1381
  if (req.method === 'GET' && route === API_PREFIX + '/update/versions') {
988
1382
  const refresh = /[?&]refresh=1(?:&|$)/.test(String(req?.url ?? ''))
989
1383
  try {
@@ -999,7 +1393,7 @@ async function handleRequest(ctx, req, res) {
999
1393
  }
1000
1394
  // 2. 先认 action 再读 body:未知路径不消耗解析预算。
1001
1395
  const action = actionOf(route)
1002
- if (action !== 'snapshot' && action !== 'read' && action !== 'update/install') {
1396
+ if (action !== 'snapshot' && action !== 'read' && action !== 'update/install' && action !== 'read-roots') {
1003
1397
  fail(res, 404, 'unknown action')
1004
1398
  return
1005
1399
  }
@@ -1010,6 +1404,18 @@ async function handleRequest(ctx, req, res) {
1010
1404
  return
1011
1405
  }
1012
1406
  const body = await readJsonBody(req, res)
1407
+ if (action === 'read-roots') {
1408
+ try {
1409
+ const roots = await normalizeReadRoots(body.roots, true)
1410
+ await saveReadRoots(roots)
1411
+ respond(res, 200, { ok: true, roots })
1412
+ } catch (error) {
1413
+ const code = error instanceof RequestError && typeof error.code === 'string' ? error.code : 'invalid-roots'
1414
+ // 设置页按稳定 code 显示本地化文案;不把 fs 错误/绝对路径回给浏览器。
1415
+ respond(res, error instanceof RequestError && error.status === 500 ? 500 : 400, { ok: false, code })
1416
+ }
1417
+ return
1418
+ }
1013
1419
  if (action === 'update/install') {
1014
1420
  const result = await performUpdate(ctx, body)
1015
1421
  respond(res, result.status, result.payload)
@@ -1034,14 +1440,21 @@ async function handleRequest(ctx, req, res) {
1034
1440
  respond(res, 200, { ok: true, snapshot: getSnapshot(key) })
1035
1441
  return
1036
1442
  }
1037
- if (body.cwd !== undefined && typeof body.cwd !== 'string') {
1443
+ if (typeof body.cwd !== 'string' || body.cwd === '') {
1038
1444
  fail(res, 400, 'cwd is required')
1039
1445
  return
1040
1446
  }
1041
- if (body.path !== undefined && typeof body.path !== 'string') {
1447
+ if (typeof body.path !== 'string' || body.path === '') {
1042
1448
  fail(res, 400, 'path is required')
1043
1449
  return
1044
1450
  }
1451
+ // 只允许读用户真正打开过的工作区(或其子目录),或用户显式授权的额外目录;
1452
+ // 同源脚本不能把根设成盘符根/`/` 来读取宿主任意文件。
1453
+ const extraRoots = await loadReadRoots()
1454
+ if (!(await readRootAllowed(ctx, body.cwd)) && !(await requestedPathInExtraRoots(body.cwd, body.path, extraRoots))) {
1455
+ fail(res, 403, 'workspace is not registered')
1456
+ return
1457
+ }
1045
1458
  if (activeReads >= MAX_CONCURRENT_READS) {
1046
1459
  // 429 而不是排队:显示型读取失败时浏览器本来就会回退为差异块展示。
1047
1460
  fail(res, 429, 'too many concurrent reads')
@@ -1049,7 +1462,7 @@ async function handleRequest(ctx, req, res) {
1049
1462
  }
1050
1463
  activeReads++
1051
1464
  try {
1052
- const result = await readDisplayTarget(body.cwd, body.path)
1465
+ const result = await readDisplayTarget(body.cwd, body.path, extraRoots)
1053
1466
  respond(res, 200, { ok: true, ...result })
1054
1467
  } finally {
1055
1468
  activeReads--
@@ -1079,6 +1492,12 @@ export function apply(ctx) {
1079
1492
  captureSnapshot(exec, result)
1080
1493
  }), 'dsh-inline-diff: capture mutation snapshots')
1081
1494
 
1495
+ // 工具注册表变化(插件挂载/卸载、MCP 工具刷新)→ 丢弃 `/tools` 缓存,
1496
+ // 下一次请求即可看到新工具。事件没有负载,只用来失效。
1497
+ ctx.effect(() => ctx.on('tools/change', () => {
1498
+ invalidateToolNames(ctx)
1499
+ }), 'dsh-inline-diff: tool list cache')
1500
+
1082
1501
  // 同源展示 API。每个路由条目都是 effect 持有的资源(dispose 时自动注销)。
1083
1502
  ctx.effect(() => ctx.webServer.register({
1084
1503
  kind: 'prefix',