@him666233/dsh-inline-diff 1.3.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.
Files changed (5) hide show
  1. package/README.en.md +28 -9
  2. package/README.md +28 -9
  3. package/client.js +2665 -337
  4. package/index.js +1509 -740
  5. package/package.json +1 -1
package/index.js CHANGED
@@ -1,740 +1,1509 @@
1
- /**
2
- /**
3
- * dsh-inline-diff —— Host 半侧(Node 侧,纯 ESM,无需构建)。
4
- *
5
- * 职责只有两件事,都刻意保持小:
6
- *
7
- * 1. 快照捕获:监听 `tools/result` 事件,为每次**成功**的 `edit` / `write`
8
- * Tool 调用保存精确的修改前/后全文。fs 工具本身就在结果 value 里返回
9
- * `{ path, before, after }`,Host 半侧只需原样留存;浏览器半侧据此渲染
10
- * 精确的全文对照(真实行号、移动块提示、被动行号位移),无需重读/重建文件。
11
- * 快照保存在有界的内存 LRU 中:实时会话是主要消费者,历史回放则回退到
12
- * 下面的文件读取路由。
13
- *
14
- * 2. 同源只读 API:在本插件自己的前缀路由下提供
15
- *
16
- * POST /dsh-inline-diff/api/snapshot { sessionId, callId }
17
- * POST /dsh-inline-diff/api/read { cwd, path }
18
- * GET /dsh-inline-diff/api/ping
19
- *
20
- * 读取路由永远不离开会话工作区(请求路径与解析后路径都做 realpath 包含
21
- * 校验),且只返回上限内的展示文本。它只服务两个展示用途:历史回放中
22
- * 实时快照已丢失时的行号定位,以及全文对照。
23
- *
24
- * 安全模型(1.3.0 加固):
25
- *
26
- * - 前缀路由不在 DSH 已认证的 `/api` 传输层下,因此本模块自己执行同样的浏览器
27
- * 信任边界,且在任何 body 读取之前:当 `connection` 服务已挂载(所有
28
- * Web/桌面 profile)时,用其文档化的 `admit(request)` 判定 Host/Origin/DNS
29
- * rebinding 信任并要求有效浏览器会话 cookie(否则 401/403);没有
30
- * `connection` 的 profile 回退本地围栏——Host 头必须是 loopback 或本监听器
31
- * 的绑定地址、跨站 Origin / `sec-fetch-site: cross-site` 一律拒绝、带 Origin
32
- * 时必须是同一 authority。调用方无法跳过这道检查。
33
- * - 请求体在缓冲前就限长(Content-Length + 流式累计大小),带读取超时,且必须
34
- * 是 `application/json` 对象,因此跨站“简单请求”与 slow-loris 流都会被拒绝,
35
- * 且不会无界分配内存。
36
- * - 文件读取是展示专用的:根与目标都 realpath 包含校验、regular-file 检查、
37
- * 符号链接目标必须仍在工作区内、2 MiB 上限、二进制拒绝、读取超时、并发上限。
38
- * - 快照内存有单条与总量双预算(按字节计账),一波巨大编辑不会让 Host 内存
39
- * 无限增长。
40
- * - 响应统一 JSON + `nosniff` / `no-store`;错误信息映射为稳定码,绝不回显原始
41
- * 文件系统错误(其中含路径与 errno)。
42
- *
43
- * 失败与回退(README「Host API 准入」行):
44
- * - 准入失败 → 401/403 固定文案;客户端 api.js 收到非 2xx 返回 null,卡片继续
45
- * 降级展示(元数据差异块 → 参数预览 → “没有可展示的差异”);
46
- * - 读取结果超大/二进制/超时/并发超限 → 明确 kind 或错误码,浏览器按 kind
47
- * 降级,不猜测;
48
- * - 捕获失败(结果畸形、事件被冻结、内存预算淘汰)→ 完全吞掉,绝不影响 Tool
49
- * 调用本身;快照缺失时历史回放会自动回退到文件读取/差异块。
50
- */
51
- import { readFile, realpath, stat } from 'node:fs/promises'
52
- import { isAbsolute, relative, resolve } from 'node:path'
53
-
54
- /** webServer 服务承载本插件的前缀路由(通过 inject 注入)。 */
55
- export const inject = ['webServer']
56
-
57
- /** 本插件自己的 API 前缀(用包名,URL 路径安全)。 */
58
- const API_PREFIX = '/dsh-inline-diff/api'
59
- /** 展示读取上限:更大的文件返回 `oversized`,浏览器降级为差异块视图。 */
60
- const READ_CAP = 2 * 1024 * 1024
61
- /** 请求体大小上限。 */
62
- const BODY_CAP = 1024 * 1024
63
- /** 所有会话合计保留的快照条目数(有界内存 LRU)。 */
64
- const SNAPSHOT_CAP = 240
65
- /** 单侧快照文本上限:巨大写入不值得为“展示”常驻这么多内存。 */
66
- const SNAPSHOT_TEXT_CAP = 4 * 1024 * 1024
67
- /**
68
- * Total snapshot memory budget across all sessions. 逐条上限仍可能被大量
69
- * "4 MiB 大文件编辑"叠加成近 2 GiB 的常驻内存(240 × 2 × 4 MiB),因此再加
70
- * 一道总量上限:按 UTF-16 字符数 × 2 字节保守估算,超出后从最旧条目开始淘汰。
71
- * 该预算只影响历史回放时较旧快照的可用性(读路由会回退为文件读取/差异块),
72
- * 不影响当前会话的实时快照。
73
- */
74
- const SNAPSHOT_TOTAL_CAP = 64 * 1024 * 1024
75
- /** 请求体必须在此时间窗内全部接收(slow-loris 防护)。 */
76
- const BODY_TIMEOUT_MS = 10_000
77
- /** 单次展示读取必须在此时间窗内完成(磁盘不可达/过慢时放弃)。 */
78
- const READ_TIMEOUT_MS = 15_000
79
- /** 所有卡片合计的并发展示读取上限:防止卡住的页面把磁盘 I/O 打满。 */
80
- const MAX_CONCURRENT_READS = 8
81
- /** 快照 key 来自客户端;限制长度让 key 保持小而可比较。 */
82
- const MAX_ID_LENGTH = 512
83
-
84
- /**
85
- * 只读边界常量。导出仅供 `tests/security.test.mjs` 断言真实生产值(避免测试里
86
- * 复制一份数字而漂移);插件加载器会忽略多余的命名导出。
87
- */
88
- export const LIMITS = Object.freeze({
89
- body: BODY_CAP,
90
- read: READ_CAP,
91
- snapshotEntries: SNAPSHOT_CAP,
92
- snapshotText: SNAPSHOT_TEXT_CAP,
93
- snapshotTotal: SNAPSHOT_TOTAL_CAP,
94
- bodyTimeoutMs: BODY_TIMEOUT_MS,
95
- readTimeoutMs: READ_TIMEOUT_MS,
96
- maxConcurrentReads: MAX_CONCURRENT_READS,
97
- maxIdLength: MAX_ID_LENGTH,
98
- })
99
-
100
- /** 一个带类型的请求失败:`status` 是应答用的 HTTP 状态码。 */
101
- class RequestError extends Error {
102
- /**
103
- * @param {number} status
104
- * @param {string} message - 稳定、不敏感的客户端可读消息(不回显 fs 细节)
105
- */
106
- constructor(status, message) {
107
- super(message)
108
- this.name = 'RequestError'
109
- this.status = status
110
- }
111
- }
112
-
113
- // ---------------------------------------------------------------------------
114
- // 快照存储(有界 LRU:条目数 + 总字节双预算)
115
- // ---------------------------------------------------------------------------
116
-
117
- /** sessionId + callId → `{ snapshot, bytes }`;Map 插入序即 LRU 淘汰序。 */
118
- const snapshots = new Map()
119
- /** 所有已存快照的近似常驻字节数(见 approximateSnapshotBytes 的保守估算)。 */
120
- let snapshotBytes = 0
121
-
122
- /** 拼出快照 Map 的 key(`sessionId\0callId`)。 */
123
- function snapshotKey(sessionId, callId) {
124
- return String(sessionId) + '\0' + String(callId)
125
- }
126
-
127
- /**
128
- * 估算单条快照的保守字节占用,用于内存预算。
129
- *
130
- * V8 对短/拉丁字符串按每字符 1 字节存储,其它字符串 2 字节;这里统一按
131
- * `2 × 字符数` 估算,宁高估不低估,保证预算不会失守。
132
- */
133
- function approximateSnapshotBytes(snapshot) {
134
- const before = typeof snapshot?.before === 'string' ? snapshot.before.length : 0
135
- const after = typeof snapshot?.after === 'string' ? snapshot.after.length : 0
136
- const path = typeof snapshot?.path === 'string' ? snapshot.path.length : 0
137
- return 2 * (before + after + path)
138
- }
139
-
140
- /** 删除一条快照并同步扣减字节计数(计数下限钳到 0,防止浮点/重复删除漂移)。 */
141
- function deleteSnapshot(key) {
142
- const entry = snapshots.get(key)
143
- if (entry === undefined) return
144
- snapshots.delete(key)
145
- snapshotBytes -= entry.bytes
146
- if (snapshotBytes < 0) snapshotBytes = 0
147
- }
148
-
149
- /**
150
- * 存入一条快照:覆盖写(先删旧条目再插新条目,位移到 LRU 末端),随后当
151
- * 条目数或总字节任一超预算时,从最旧条目开始淘汰,直到两个预算都满足。
152
- */
153
- function putSnapshot(key, snapshot) {
154
- deleteSnapshot(key)
155
- const bytes = approximateSnapshotBytes(snapshot)
156
- snapshots.set(key, { snapshot, bytes })
157
- snapshotBytes += bytes
158
- while (snapshots.size > SNAPSHOT_CAP || snapshotBytes > SNAPSHOT_TOTAL_CAP) {
159
- const oldest = snapshots.keys().next().value
160
- if (oldest === undefined) break
161
- deleteSnapshot(oldest)
162
- }
163
- }
164
-
165
- /** 读取一条快照;从未捕获或被淘汰时返回 null(浏览器据此走下一级回退)。 */
166
- function getSnapshot(key) {
167
- const entry = snapshots.get(key)
168
- return entry === undefined ? null : entry.snapshot
169
- }
170
-
171
- /**
172
- * @internal 仅供测试的状态探针;调用方无法通过它修改存储。
173
- * @returns {{ count: number, bytes: number }}
174
- */
175
- export function snapshotStats() {
176
- return { count: snapshots.size, bytes: snapshotBytes }
177
- }
178
-
179
- /**
180
- * @internal 仅供测试:清空快照存储,让每个测试套件从空状态开始。
181
- */
182
- export function clearSnapshots() {
183
- snapshots.clear()
184
- snapshotBytes = 0
185
- }
186
-
187
- // ---------------------------------------------------------------------------
188
- // 工作区路径围栏
189
- // ---------------------------------------------------------------------------
190
-
191
- /** 判断候选路径是根本身还是位于根之下(不允许 `..` 逃逸,`relative` 为空表示根)。 */
192
- export function inside(root, candidate) {
193
- const child = relative(root, candidate)
194
- return child === '' || (!child.startsWith('..') && !isAbsolute(child))
195
- }
196
-
197
- /**
198
- * 在“展示围栏”内解析一个请求路径:根 realpath → 候选包含校验 → 候选 realpath
199
- * → 结果再包含校验。符号链接只有目标仍在根内才放行(指向工作区外的链接或
200
- * Windows junction 读不到根外内容)。
201
- *
202
- * 失败一律抛带状态码的 RequestError,且消息固定:绝不把原始 fs 错误
203
- * (含用户请求的绝对路径与 errno)回给调用方。
204
- *
205
- * @returns {Promise<{ filename: string, size: number }>} 解析后的真实文件名与大小。
206
- */
207
- export async function resolveReadTarget(cwd, requestedPath) {
208
- if (typeof cwd !== 'string' || cwd === '') throw new RequestError(400, 'cwd is required')
209
- if (typeof requestedPath !== 'string' || requestedPath === '') throw new RequestError(400, 'path is required')
210
- // NUL 会截断底层系统调用,属于非法路径而不是普通“不存在”。
211
- if (cwd.includes('\0') || requestedPath.includes('\0')) throw new RequestError(400, 'path is invalid')
212
- let root
213
- try {
214
- root = await realpath(cwd)
215
- } catch {
216
- throw new RequestError(404, 'workspace is not readable')
217
- }
218
- const candidate = resolve(root, requestedPath)
219
- if (!inside(root, candidate)) throw new RequestError(403, 'path is outside the session workspace')
220
- let filename
221
- try {
222
- // 符号链接在这里解析:只有 realpath 之后仍在根内才放行,因此一个指向
223
- // 工作区外的链接(或 Windows junction)无法读出根外内容。
224
- filename = await realpath(candidate)
225
- } catch {
226
- throw new RequestError(404, 'file is not readable')
227
- }
228
- if (!inside(root, filename)) throw new RequestError(403, 'resolved path is outside the session workspace')
229
- let info
230
- try {
231
- info = await stat(filename)
232
- } catch {
233
- throw new RequestError(404, 'file is not readable')
234
- }
235
- if (!info.isFile()) throw new RequestError(400, 'path is not a regular file')
236
- return { filename, size: info.size }
237
- }
238
-
239
- /**
240
- * 读取一个展示目标;用 `kind` 显式告诉浏览器如何降级。
241
- *
242
- * 读取带独立超时,并在读取后再次检查大小:文件在 stat 与 readFile 之间变大时,
243
- * 仍然不会超过展示上限。
244
- *
245
- * @returns {Promise<{kind:'text', text:string, size:number} |
246
- * {kind:'binary'|'oversized', size:number}>}
247
- */
248
- async function readDisplayTarget(cwd, requestedPath) {
249
- const target = await resolveReadTarget(cwd, requestedPath)
250
- if (target.size > READ_CAP) return { kind: 'oversized', size: target.size }
251
- const controller = new AbortController()
252
- const timer = setTimeout(() => controller.abort(), READ_TIMEOUT_MS)
253
- let bytes
254
- try {
255
- bytes = await readFile(target.filename, { signal: controller.signal })
256
- } catch (error) {
257
- if (controller.signal.aborted || error?.name === 'AbortError') {
258
- throw new RequestError(504, 'file read timed out')
259
- }
260
- throw new RequestError(404, 'file is not readable')
261
- } finally {
262
- clearTimeout(timer)
263
- }
264
- if (bytes.length > READ_CAP) return { kind: 'oversized', size: bytes.length }
265
- if (bytes.includes(0)) return { kind: 'binary', size: target.size }
266
- let text = bytes.toString('utf8')
267
- // 开头的 BOM 属于展示噪声;差异基准本身也是纯文本,去掉不留痕。
268
- if (text.charCodeAt(0) === 0xfeff) text = text.slice(1)
269
- return { kind: 'text', text, size: target.size }
270
- }
271
-
272
- // ---------------------------------------------------------------------------
273
- // 浏览器信任围栏(`connection` 服务未挂载时的回退)
274
- // ---------------------------------------------------------------------------
275
-
276
- /** 判断一个归一化 URL hostname 是否为本机 loopback(localhost / [::1] / 127.0.0.0-127.255.255.255)。 */
277
- export function isLoopbackHostname(hostname) {
278
- if (typeof hostname !== 'string' || hostname === '') return false
279
- if (hostname === 'localhost' || hostname === '[::1]') return true
280
- const parts = hostname.split('.')
281
- return parts.length === 4 && parts[0] === '127' && parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255)
282
- }
283
-
284
- /**
285
- * 把裸 authority(`host` 或 `host:port`)解析成 URL;不可解析时返回 undefined。
286
- *
287
- * 之后还会要求 pathname/search/hash 为空,因此夹带 `user@host` 或 `host/path`
288
- * 的 Host 头无法通过包含校验。
289
- */
290
- function parseAuthority(authority, scheme = 'http:') {
291
- try {
292
- return new URL(`${scheme}//${authority}`)
293
- } catch {
294
- return undefined
295
- }
296
- }
297
-
298
- /**
299
- * 本监听器绑定 literal 对应的 URL hostname(IPv6 自动加方括号,去掉 zone id),
300
- * 无法解析时返回 undefined。
301
- */
302
- export function bindHostname(bindHost) {
303
- if (typeof bindHost !== 'string' || bindHost === '') return undefined
304
- const zoneAt = bindHost.indexOf('%')
305
- const address = zoneAt === -1 ? bindHost : bindHost.slice(0, zoneAt)
306
- if (address === '') return undefined
307
- const parsed = parseAuthority(address.includes(':') ? `[${address}]` : address)
308
- return parsed?.hostname
309
- }
310
-
311
- /**
312
- * 判断附带的 `Origin` 头与 `Host` 是否同一 authority。
313
- *
314
- * Host 按 Origin 自己的 HTTP(S) 协议解析,保证默认端口归一一致(HTTPS 反向代理
315
- * 后面可能是一个 HTTP 监听器)。
316
- */
317
- export function isSameAuthorityOrigin(origin, host) {
318
- if (typeof origin !== 'string' || typeof host !== 'string') return false
319
- let originUrl
320
- try {
321
- originUrl = new URL(origin)
322
- } catch {
323
- return false
324
- }
325
- const scheme = originUrl.protocol === 'https:' ? 'https:' : originUrl.protocol === 'http:' ? 'http:' : undefined
326
- if (scheme === undefined) return false
327
- const hostUrl = parseAuthority(host, scheme)
328
- return hostUrl !== undefined && originUrl.host === hostUrl.host
329
- }
330
-
331
- /**
332
- * 没有 `connection` 服务的 profile 使用的本地回退围栏。
333
- *
334
- * 防御 DNS rebinding(Host 写成攻击者域名、socket 却落到本机)与来自恶意页面
335
- * 的跨站请求。HTTP 页面里的读取型请求不携带 Origin,所以 Host 是唯一可靠依据:
336
- * 只接受 loopback 或监听器自己的绑定 IP literal;带 Origin 时必须是同一
337
- * authority;`sec-fetch-site: cross-site` 一律拒绝。
338
- *
339
- * @param {object} req - Node HTTP 请求(只读 headers)。
340
- * @param {string | undefined} bindHost - 本监听器的绑定地址 literal。
341
- * @param {'http:' | 'https:'} protocol - 本监听器的协议。
342
- * @returns {boolean} true 表示允许访问展示 API。
343
- */
344
- export function isTrustedHostRequest(req, bindHost, protocol = 'http:') {
345
- const headers = req !== null && typeof req === 'object' ? req.headers : undefined
346
- const host = headerOf(headers, 'host')
347
- if (host === undefined) return false
348
- const hostUrl = parseAuthority(host, protocol)
349
- if (hostUrl === undefined) return false
350
- // Host 必须是裸 authority:不能带凭据、路径、query 或 fragment。
351
- if (hostUrl.username !== '' || hostUrl.password !== '' || hostUrl.pathname !== '/' || hostUrl.search !== '' || hostUrl.hash !== '') return false
352
- const loopback = isLoopbackHostname(hostUrl.hostname)
353
- const ownBind = hostUrl.hostname === bindHostname(bindHost)
354
- if (!loopback && !ownBind) return false
355
- if (headerOf(headers, 'sec-fetch-site') === 'cross-site') return false
356
- const origin = headerOf(headers, 'origin')
357
- if (origin === undefined) return true
358
- return isSameAuthorityOrigin(origin, host)
359
- }
360
-
361
- /** 读取一个 header 值(Node 已把名字转小写;单值字符串与数组首项都接受)。 */
362
- function headerOf(headers, name) {
363
- if (headers === null || typeof headers !== 'object') return undefined
364
- const value = headers[name]
365
- if (typeof value === 'string') return value
366
- if (Array.isArray(value) && typeof value[0] === 'string') return value[0]
367
- return undefined
368
- }
369
-
370
- /** 回退围栏需要的 webServer 事实(绑定地址与协议);服务缺失/形状异常时返回安全默认。 */
371
- function webServerFacts(ctx) {
372
- const fallback = { bindHost: undefined, protocol: 'http:' }
373
- try {
374
- let web = undefined
375
- if (ctx !== null && typeof ctx === 'object') {
376
- web = typeof ctx.webServer === 'object' && ctx.webServer !== null ? ctx.webServer : undefined
377
- if (web === undefined && typeof ctx.get === 'function') web = ctx.get('webServer')
378
- }
379
- if (web === null || typeof web !== 'object') return fallback
380
- return {
381
- bindHost: typeof web.host === 'string' ? web.host : undefined,
382
- protocol: web.protocol === 'https:' ? 'https:' : 'http:',
383
- }
384
- } catch {
385
- return fallback
386
- }
387
- }
388
-
389
- /**
390
- * 单个路由请求的准入判定。
391
- *
392
- * 优先复用 DSH 官方 connection 服务的准入(Host/Origin/跨站 + 浏览器 Cookie
393
- * 认证),这样本插件不会成为绕过平台认证的旁路;只有该服务未挂载的 profile 才
394
- * 退回本地围栏。任何异常都走围栏而不是直接放行(fail-closed)。
395
- *
396
- * @returns {number | undefined} 拒绝时返回 HTTP 状态码;undefined 表示放行。
397
- */
398
- function admissionRejection(ctx, req) {
399
- let connection
400
- try {
401
- if (ctx !== null && typeof ctx === 'object' && typeof ctx.get === 'function') connection = ctx.get('connection')
402
- } catch {
403
- connection = undefined
404
- }
405
- if (connection !== null && typeof connection === 'object' && typeof connection.admit === 'function') {
406
- try {
407
- const admission = connection.admit(req)
408
- if (admission !== null && typeof admission === 'object' && 'rejection' in admission) {
409
- const status = admission.rejection
410
- return status === 401 ? 401 : 403
411
- }
412
- return undefined
413
- } catch {
414
- // 服务形态与预期不符(版本漂移):退回本地围栏继续判定。
415
- }
416
- }
417
- const facts = webServerFacts(ctx)
418
- return isTrustedHostRequest(req, facts.bindHost, facts.protocol) ? undefined : 403
419
- }
420
-
421
- // ---------------------------------------------------------------------------
422
- // HTTP 辅助函数
423
- // ---------------------------------------------------------------------------
424
-
425
- /**
426
- * 固定响应头:只回 JSON、禁止 MIME 嗅探、禁止缓存、不泄露 referrer、
427
- * 禁止跨源读取(display-only API 不需要被其它源嵌入)。
428
- */
429
- const JSON_HEADERS = Object.freeze({
430
- 'content-type': 'application/json; charset=utf-8',
431
- 'x-content-type-options': 'nosniff',
432
- 'cache-control': 'no-store',
433
- 'referrer-policy': 'no-referrer',
434
- 'cross-origin-resource-policy': 'same-origin',
435
- })
436
-
437
- /** 发送一个 JSON 响应;连接已断开时安全 no-op(display-only API 没有需要保护的状态)。 */
438
- function respond(res, status, payload) {
439
- if (res === null || typeof res !== 'object') return
440
- if (res.headersSent === true || res.writableEnded === true) return
441
- let body
442
- try {
443
- body = JSON.stringify(payload)
444
- } catch {
445
- body = '{"ok":false,"error":"response failed"}'
446
- }
447
- try {
448
- res.writeHead(status, JSON_HEADERS)
449
- res.end(body)
450
- } catch {
451
- // 客户端已断开:没有需要保护的状态,忽略。
452
- }
453
- }
454
-
455
- /** 发送一个带类型的失败响应(稳定错误码,不含文件系统细节)。 */
456
- function fail(res, status, error) {
457
- respond(res, status, { ok: false, error })
458
- }
459
-
460
- /**
461
- * 拒绝一个“body 可能还在传输”的请求:先写响应,等响应刷出后再销毁 socket。
462
- * (先销毁会丢掉客户端需要看到的 413/408。)
463
- */
464
- function rejectBody(req, res, status, error) {
465
- if (res !== null && typeof res === 'object' && res.headersSent !== true && res.writableEnded !== true) {
466
- try {
467
- res.writeHead(status, JSON_HEADERS)
468
- res.end(JSON.stringify({ ok: false, error }), () => {
469
- try {
470
- req.destroy()
471
- } catch {
472
- // 忽略:连接已断开,无需处理。
473
- }
474
- })
475
- return
476
- } catch {
477
- // 写响应失败则直接走销毁。
478
- }
479
- }
480
- try {
481
- req.destroy()
482
- } catch {
483
- // 忽略:socket 已不可用。
484
- }
485
- }
486
-
487
- /** 请求是否声明了 `application/json` body(忽略参数部分、大小写不敏感)。 */
488
- function isJsonRequest(req) {
489
- const type = headerOf(req?.headers, 'content-type')
490
- if (typeof type !== 'string') return false
491
- const media = type.split(';', 1)[0].trim().toLowerCase()
492
- return media === 'application/json'
493
- }
494
-
495
- /**
496
- * 读取一个 JSON 请求体:硬上限 + 读取超时 + 提前 Content-Length 拒绝。
497
- *
498
- * 解析结果在 Promise 外先按对象校验:数组、null、标量都拒绝,避免下游把
499
- * `body.cwd` 之类的字段访问变成奇怪的类型强制转换。
500
- *
501
- * @param {object} req - Node IncomingMessage(只读取 headers)。
502
- * @param {object} res - Node ServerResponse(用于提前拒绝时先回响应)。
503
- * @returns {Promise<object>} 解析后的对象。
504
- */
505
- function readJsonBody(req, res) {
506
- return new Promise((resolvePromise, rejectPromise) => {
507
- let settled = false
508
- let size = 0
509
- const chunks = []
510
- let timer
511
- /** 让 Promise 恰好 settle 一次并释放超时定时器(重复 settle 直接忽略)。 */
512
- const settle = (settleWith, value) => {
513
- if (settled) return
514
- settled = true
515
- if (timer !== undefined) clearTimeout(timer)
516
- settleWith(value)
517
- }
518
- const abort = (status, error) => {
519
- rejectBody(req, res, status, error)
520
- settle(rejectPromise, new RequestError(status, error))
521
- }
522
- // 快速失败:声明的 Content-Length 已超限时不必读取任何字节。
523
- const declared = headerOf(req?.headers, 'content-length')
524
- if (declared !== undefined && /^\d+$/.test(declared) && Number(declared) > BODY_CAP) {
525
- abort(413, 'request body too large')
526
- return
527
- }
528
- timer = setTimeout(() => {
529
- abort(408, 'request body read timeout')
530
- }, BODY_TIMEOUT_MS)
531
- req.on('data', chunk => {
532
- if (settled) return
533
- // 防御性:Node 正常给 Buffer;非 Buffer 只接受字符串,其余忽略。
534
- const buffer = Buffer.isBuffer(chunk) ? chunk : typeof chunk === 'string' ? Buffer.from(chunk) : null
535
- if (buffer === null) return
536
- size += buffer.length
537
- if (size > BODY_CAP) {
538
- abort(413, 'request body too large')
539
- return
540
- }
541
- chunks.push(buffer)
542
- })
543
- req.on('end', () => {
544
- if (settled) return
545
- let parsed
546
- try {
547
- parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'))
548
- } catch {
549
- settle(rejectPromise, new RequestError(400, 'invalid JSON body'))
550
- return
551
- }
552
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
553
- settle(rejectPromise, new RequestError(400, 'body must be a JSON object'))
554
- return
555
- }
556
- settle(resolvePromise, parsed)
557
- })
558
- req.on('error', () => {
559
- if (settled) return
560
- settle(rejectPromise, new RequestError(400, 'request aborted'))
561
- })
562
- // `close` 在上传中途中止与正常结束后都会触发;正常路径此时 Promise 已经
563
- // settle,因此这里只在尚未 settle 时按中止处理。
564
- req.on('close', () => {
565
- if (settled) return
566
- settle(rejectPromise, new RequestError(400, 'request aborted'))
567
- })
568
- })
569
- }
570
-
571
- /** 提取请求 URL 的 pathname(忽略 query string)。 */
572
- function routeOf(rawUrl) {
573
- if (typeof rawUrl !== 'string' || rawUrl === '') return '/'
574
- const question = rawUrl.indexOf('?')
575
- return question === -1 ? rawUrl : rawUrl.slice(0, question)
576
- }
577
-
578
- /** 把匹配到的路由映射成 action 名;未知路由返回原文(由调用方回 404)。 */
579
- function actionOf(route) {
580
- if (route.startsWith(API_PREFIX + '/')) return route.slice(API_PREFIX.length + 1)
581
- if (route.startsWith('/')) return route.slice(1)
582
- return route
583
- }
584
-
585
- // ---------------------------------------------------------------------------
586
- // 快照捕获
587
- // ---------------------------------------------------------------------------
588
-
589
- /**
590
- * 从一次 `tools/result` 事件捕获成功的文件修改快照。
591
- *
592
- * 只处理成功、且工具名是 `edit`/`write` 的结果(`str_replace_editor` 不产生
593
- * 执行快照,卡片走元数据差异块路径)。展示专用:畸形/冻结/异常形状的事件都
594
- * 在这里吞掉,绝不影响 Tool 调用本身。
595
- *
596
- * 边界:after 必须是非空字符串且不超过单条文本上限;before 可为 null(新建);
597
- * callId/sessionId 缺失或超长时放弃捕获(防止异常 key 撑爆存储)。
598
- */
599
- function captureSnapshot(exec, result) {
600
- try {
601
- if (result === undefined || result === null || result.isError === true) return
602
- const name = exec?.name
603
- if (name !== 'edit' && name !== 'write') return
604
- const value = result.value
605
- if (value === null || typeof value !== 'object') return
606
- const after = value.after
607
- if (typeof after !== 'string') return
608
- if (after.length > SNAPSHOT_TEXT_CAP) return
609
- const before = typeof value.before === 'string' ? value.before : null
610
- if (before !== null && before.length > SNAPSHOT_TEXT_CAP) return
611
- const callId = exec.callId === undefined || exec.callId === null ? '' : String(exec.callId)
612
- if (callId === '' || callId.length > MAX_ID_LENGTH) return
613
- const sessionId = exec.agent?.id === undefined || exec.agent?.id === null ? '' : String(exec.agent.id)
614
- if (sessionId.length > MAX_ID_LENGTH) return
615
- const path = typeof value.path === 'string' ? value.path : (typeof exec.arguments?.file_path === 'string' ? exec.arguments.file_path : '')
616
- putSnapshot(snapshotKey(sessionId, callId), {
617
- path,
618
- before,
619
- after,
620
- operation: typeof value.operation === 'string'
621
- ? value.operation
622
- : before === null ? 'create' : 'update',
623
- at: Date.now(),
624
- })
625
- } catch {
626
- // 展示专用捕获:绝不影响 Tool 调用本身。
627
- }
628
- }
629
-
630
- // ---------------------------------------------------------------------------
631
- // 路由处理
632
- // ---------------------------------------------------------------------------
633
-
634
- /** 当前并发的展示读取计数(进程级全局上限,见 MAX_CONCURRENT_READS)。 */
635
- let activeReads = 0
636
-
637
- /** 准入之后分发一个请求;所有失败路径都回 JSON(稳定码,不泄漏内部细节)。 */
638
- async function handleRequest(ctx, req, res) {
639
- const route = routeOf(req?.url)
640
- // 1. 浏览器信任边界(平台准入优先,回退本地围栏):必须在读取任何 body 之前。
641
- const rejection = admissionRejection(ctx, req)
642
- if (rejection !== undefined) {
643
- fail(res, rejection, rejection === 401 ? 'unauthorized' : 'forbidden')
644
- return
645
- }
646
- try {
647
- if (req.method === 'GET' && (route === '/ping' || route === API_PREFIX + '/ping')) {
648
- respond(res, 200, { ok: true, snapshots: snapshots.size })
649
- return
650
- }
651
- if (req.method !== 'POST') {
652
- fail(res, 405, 'POST only')
653
- return
654
- }
655
- // 2. 先认 action 再读 body:未知路径不消耗解析预算。
656
- const action = actionOf(route)
657
- if (action !== 'snapshot' && action !== 'read') {
658
- fail(res, 404, 'unknown action')
659
- return
660
- }
661
- // 3. 只接受 application/json:浏览器的跨站“简单请求”无法携带该类型,
662
- // 因此这一道同时挡住 text/plain 形式的 CSRF 探测。
663
- if (!isJsonRequest(req)) {
664
- fail(res, 415, 'content type must be application/json')
665
- return
666
- }
667
- const body = await readJsonBody(req, res)
668
- if (action === 'snapshot') {
669
- const sessionId = body.sessionId
670
- const rawCallId = body.callId
671
- if (sessionId !== undefined && typeof sessionId !== 'string') {
672
- fail(res, 400, 'invalid sessionId')
673
- return
674
- }
675
- if (rawCallId !== undefined && typeof rawCallId !== 'string' && typeof rawCallId !== 'number') {
676
- fail(res, 400, 'invalid callId')
677
- return
678
- }
679
- const key = snapshotKey(sessionId ?? '', rawCallId === undefined || rawCallId === null ? '' : String(rawCallId))
680
- if (key.length > MAX_ID_LENGTH * 2 + 1) {
681
- fail(res, 400, 'invalid snapshot key')
682
- return
683
- }
684
- respond(res, 200, { ok: true, snapshot: getSnapshot(key) })
685
- return
686
- }
687
- if (body.cwd !== undefined && typeof body.cwd !== 'string') {
688
- fail(res, 400, 'cwd is required')
689
- return
690
- }
691
- if (body.path !== undefined && typeof body.path !== 'string') {
692
- fail(res, 400, 'path is required')
693
- return
694
- }
695
- if (activeReads >= MAX_CONCURRENT_READS) {
696
- // 429 而不是排队:显示型读取失败时浏览器本来就会回退为差异块展示。
697
- fail(res, 429, 'too many concurrent reads')
698
- return
699
- }
700
- activeReads++
701
- try {
702
- const result = await readDisplayTarget(body.cwd, body.path)
703
- respond(res, 200, { ok: true, ...result })
704
- } finally {
705
- activeReads--
706
- }
707
- } catch (error) {
708
- // 底层在流式拒绝时已经写过响应(413/408):不能二次写头。
709
- if (res?.headersSent === true || res?.writableEnded === true) return
710
- const status = Number.isInteger(error?.status) ? error.status : 500
711
- // 内部异常只回稳定文案,不泄漏 errno / 绝对路径 / 堆栈。
712
- const message = error instanceof RequestError ? error.message : 'request failed'
713
- fail(res, status, message)
714
- }
715
- }
716
-
717
- // ---------------------------------------------------------------------------
718
- // 插件入口
719
- // ---------------------------------------------------------------------------
720
-
721
- /**
722
- * 安装 Host 半侧的捕获与只读 API。
723
- * @param ctx - 插件 context;`webServer` 服务通过 `inject` 注入。
724
- */
725
- export function apply(ctx) {
726
- // 工具结果捕获:edit/write 工具在 result value 里返回修改前/后全文,这正是
727
- // Host 自己做 diff 时所依据的精确文本。
728
- ctx.effect(() => ctx.on('tools/result', (exec, result) => {
729
- captureSnapshot(exec, result)
730
- }), 'dsh-inline-diff: capture mutation snapshots')
731
-
732
- // 同源展示 API。每个路由条目都是 effect 持有的资源(dispose 时自动注销)。
733
- ctx.effect(() => ctx.webServer.register({
734
- kind: 'prefix',
735
- path: API_PREFIX,
736
- handler: async (req, res) => {
737
- await handleRequest(ctx, req, res)
738
- },
739
- }), 'dsh-inline-diff: display api')
740
- }
1
+ /**
2
+ /**
3
+ * dsh-inline-diff —— Host 半侧(Node 侧,纯 ESM,无需构建)。
4
+ *
5
+ * 职责只有两件事,都刻意保持小:
6
+ *
7
+ * 1. 快照捕获:监听 `tools/result` 事件,为每次**成功**的 `edit` / `write`
8
+ * Tool 调用保存精确的修改前/后全文。fs 工具本身就在结果 value 里返回
9
+ * `{ path, before, after }`,Host 半侧只需原样留存;浏览器半侧据此渲染
10
+ * 精确的全文对照(真实行号、移动块提示、被动行号位移),无需重读/重建文件。
11
+ * 快照保存在有界的内存 LRU 中:实时会话是主要消费者,历史回放则回退到
12
+ * 下面的文件读取路由。
13
+ *
14
+ * 2. 同源只读 API:在本插件自己的前缀路由下提供
15
+ *
16
+ * POST /dsh-inline-diff/api/snapshot { sessionId, callId }
17
+ * POST /dsh-inline-diff/api/read { cwd, path }
18
+ * GET /dsh-inline-diff/api/update/versions 版本列表/当前版本/安装方式
19
+ * POST /dsh-inline-diff/api/update/install { version } 安装/回退
20
+ * GET /dsh-inline-diff/api/tools 当前可见工具名(第三方工具兼容)
21
+ * GET /dsh-inline-diff/api/ping
22
+ *
23
+ * 读取路由永远不离开会话工作区(请求路径与解析后路径都做 realpath 包含
24
+ * 校验),且只返回上限内的展示文本。它只服务两个展示用途:历史回放中
25
+ * 实时快照已丢失时的行号定位,以及全文对照。
26
+ *
27
+ * 安全模型(1.3.0 加固):
28
+ *
29
+ * - 前缀路由不在 DSH 已认证的 `/api` 传输层下,因此本模块自己执行同样的浏览器
30
+ * 信任边界,且在任何 body 读取之前:当 `connection` 服务已挂载(所有
31
+ * Web/桌面 profile)时,用其文档化的 `admit(request)` 判定 Host/Origin/DNS
32
+ * rebinding 信任并要求有效浏览器会话 cookie(否则 401/403);没有
33
+ * `connection` 的 profile 回退本地围栏——Host 头必须是 loopback 或本监听器
34
+ * 的绑定地址、跨站 Origin / `sec-fetch-site: cross-site` 一律拒绝、带 Origin
35
+ * 时必须是同一 authority。调用方无法跳过这道检查。
36
+ * - 请求体在缓冲前就限长(Content-Length + 流式累计大小),带读取超时,且必须
37
+ * 是 `application/json` 对象,因此跨站“简单请求”与 slow-loris 流都会被拒绝,
38
+ * 且不会无界分配内存。
39
+ * - 文件读取是展示专用的:根与目标都 realpath 包含校验、regular-file 检查、
40
+ * 符号链接目标必须仍在工作区内、2 MiB 上限、二进制拒绝、读取超时、并发上限。
41
+ * - 快照内存有单条与总量双预算(按字节计账),一波巨大编辑不会让 Host 内存
42
+ * 无限增长。
43
+ * - 响应统一 JSON + `nosniff` / `no-store`;错误信息映射为稳定码,绝不回显原始
44
+ * 文件系统错误(其中含路径与 errno)。
45
+ *
46
+ * 失败与回退(README「Host API 准入」行):
47
+ * - 准入失败 → 401/403 固定文案;客户端 api.js 收到非 2xx 返回 null,卡片继续
48
+ * 降级展示(元数据差异块 → 参数预览 → “没有可展示的差异”);
49
+ * - 读取结果超大/二进制/超时/并发超限 → 明确 kind 或错误码,浏览器按 kind
50
+ * 降级,不猜测;
51
+ * - 捕获失败(结果畸形、事件被冻结、内存预算淘汰)→ 完全吞掉,绝不影响 Tool
52
+ * 调用本身;快照缺失时历史回放会自动回退到文件读取/差异块。
53
+ */
54
+ import { spawn } from 'node:child_process'
55
+ import { existsSync, readFileSync } from 'node:fs'
56
+ import { mkdir, readFile, realpath, rename, stat, writeFile } from 'node:fs/promises'
57
+ import { homedir } from 'node:os'
58
+ import { dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path'
59
+ import { fileURLToPath } from 'node:url'
60
+
61
+ /** webServer 服务承载本插件的前缀路由(通过 inject 注入)。 */
62
+ export const inject = ['webServer']
63
+
64
+ /** 本插件自己的 API 前缀(用包名,URL 路径安全)。 */
65
+ const API_PREFIX = '/dsh-inline-diff/api'
66
+ /** 展示读取上限:更大的文件返回 `oversized`,浏览器降级为差异块视图。 */
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
74
+ /** 请求体大小上限。 */
75
+ const BODY_CAP = 1024 * 1024
76
+ /** 所有会话合计保留的快照条目数(有界内存 LRU)。 */
77
+ const SNAPSHOT_CAP = 240
78
+ /** 单侧快照文本上限:巨大写入不值得为“展示”常驻这么多内存。 */
79
+ const SNAPSHOT_TEXT_CAP = 4 * 1024 * 1024
80
+ /**
81
+ * Total snapshot memory budget across all sessions. 逐条上限仍可能被大量
82
+ * "4 MiB 大文件编辑"叠加成近 2 GiB 的常驻内存(240 × 2 × 4 MiB),因此再加
83
+ * 一道总量上限:按 UTF-16 字符数 × 2 字节保守估算,超出后从最旧条目开始淘汰。
84
+ * 该预算只影响历史回放时较旧快照的可用性(读路由会回退为文件读取/差异块),
85
+ * 不影响当前会话的实时快照。
86
+ */
87
+ const SNAPSHOT_TOTAL_CAP = 64 * 1024 * 1024
88
+ /** 请求体必须在此时间窗内全部接收(slow-loris 防护)。 */
89
+ const BODY_TIMEOUT_MS = 10_000
90
+ /** 单次展示读取必须在此时间窗内完成(磁盘不可达/过慢时放弃)。 */
91
+ const READ_TIMEOUT_MS = 15_000
92
+ /** 所有卡片合计的并发展示读取上限:防止卡住的页面把磁盘 I/O 打满。 */
93
+ const MAX_CONCURRENT_READS = 8
94
+ /** 快照 key 来自客户端;限制长度让 key 保持小而可比较。 */
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
100
+
101
+ /**
102
+ * 只读边界常量。导出仅供 `tests/security.test.mjs` 断言真实生产值(避免测试里
103
+ * 复制一份数字而漂移);插件加载器会忽略多余的命名导出。
104
+ */
105
+ export const LIMITS = Object.freeze({
106
+ body: BODY_CAP,
107
+ read: READ_CAP,
108
+ snapshotEntries: SNAPSHOT_CAP,
109
+ snapshotText: SNAPSHOT_TEXT_CAP,
110
+ snapshotTotal: SNAPSHOT_TOTAL_CAP,
111
+ bodyTimeoutMs: BODY_TIMEOUT_MS,
112
+ readTimeoutMs: READ_TIMEOUT_MS,
113
+ maxConcurrentReads: MAX_CONCURRENT_READS,
114
+ maxIdLength: MAX_ID_LENGTH,
115
+ maxToolNameLength: MAX_TOOL_NAME_LENGTH,
116
+ maxToolNames: MAX_TOOL_NAMES,
117
+ })
118
+
119
+ /** 一个带类型的请求失败:`status` 是应答用的 HTTP 状态码。 */
120
+ class RequestError extends Error {
121
+ /**
122
+ * @param {number} status
123
+ * @param {string} message - 稳定、不敏感的客户端可读消息(不回显 fs 细节)
124
+ * @param {string} [code] - 稳定错误码(设置页等需要按码显示文案时使用)
125
+ */
126
+ constructor(status, message, code) {
127
+ super(message)
128
+ this.name = 'RequestError'
129
+ this.status = status
130
+ if (typeof code === 'string') this.code = code
131
+ }
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // 快照存储(有界 LRU:条目数 + 总字节双预算)
136
+ // ---------------------------------------------------------------------------
137
+
138
+ /** sessionId + callId → `{ snapshot, bytes }`;Map 插入序即 LRU 淘汰序。 */
139
+ const snapshots = new Map()
140
+ /** 所有已存快照的近似常驻字节数(见 approximateSnapshotBytes 的保守估算)。 */
141
+ let snapshotBytes = 0
142
+
143
+ /** 拼出快照 Map 的 key(`sessionId\0callId`)。 */
144
+ function snapshotKey(sessionId, callId) {
145
+ return String(sessionId) + '\0' + String(callId)
146
+ }
147
+
148
+ /**
149
+ * 估算单条快照的保守字节占用,用于内存预算。
150
+ *
151
+ * V8 对短/拉丁字符串按每字符 1 字节存储,其它字符串 2 字节;这里统一按
152
+ * `2 × 字符数` 估算,宁高估不低估,保证预算不会失守。
153
+ */
154
+ function approximateSnapshotBytes(snapshot) {
155
+ const before = typeof snapshot?.before === 'string' ? snapshot.before.length : 0
156
+ const after = typeof snapshot?.after === 'string' ? snapshot.after.length : 0
157
+ const path = typeof snapshot?.path === 'string' ? snapshot.path.length : 0
158
+ return 2 * (before + after + path)
159
+ }
160
+
161
+ /** 删除一条快照并同步扣减字节计数(计数下限钳到 0,防止浮点/重复删除漂移)。 */
162
+ function deleteSnapshot(key) {
163
+ const entry = snapshots.get(key)
164
+ if (entry === undefined) return
165
+ snapshots.delete(key)
166
+ snapshotBytes -= entry.bytes
167
+ if (snapshotBytes < 0) snapshotBytes = 0
168
+ }
169
+
170
+ /**
171
+ * 存入一条快照:覆盖写(先删旧条目再插新条目,位移到 LRU 末端),随后当
172
+ * 条目数或总字节任一超预算时,从最旧条目开始淘汰,直到两个预算都满足。
173
+ */
174
+ function putSnapshot(key, snapshot) {
175
+ deleteSnapshot(key)
176
+ const bytes = approximateSnapshotBytes(snapshot)
177
+ snapshots.set(key, { snapshot, bytes })
178
+ snapshotBytes += bytes
179
+ while (snapshots.size > SNAPSHOT_CAP || snapshotBytes > SNAPSHOT_TOTAL_CAP) {
180
+ const oldest = snapshots.keys().next().value
181
+ if (oldest === undefined) break
182
+ deleteSnapshot(oldest)
183
+ }
184
+ }
185
+
186
+ /** 读取一条快照;从未捕获或被淘汰时返回 null(浏览器据此走下一级回退)。 */
187
+ function getSnapshot(key) {
188
+ const entry = snapshots.get(key)
189
+ return entry === undefined ? null : entry.snapshot
190
+ }
191
+
192
+ /**
193
+ * @internal 仅供测试的状态探针;调用方无法通过它修改存储。
194
+ * @returns {{ count: number, bytes: number }}
195
+ */
196
+ export function snapshotStats() {
197
+ return { count: snapshots.size, bytes: snapshotBytes }
198
+ }
199
+
200
+ /**
201
+ * @internal 仅供测试:清空快照存储,让每个测试套件从空状态开始。
202
+ */
203
+ export function clearSnapshots() {
204
+ snapshots.clear()
205
+ snapshotBytes = 0
206
+ }
207
+
208
+ // ---------------------------------------------------------------------------
209
+ // 工作区路径围栏
210
+ // ---------------------------------------------------------------------------
211
+
212
+ /** 判断候选路径是根本身还是位于根之下(不允许 `..` 逃逸,`relative` 为空表示根)。 */
213
+ export function inside(root, candidate) {
214
+ const child = relative(root, candidate)
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)
231
+ }
232
+
233
+ /**
234
+ * 在“展示围栏”内解析一个请求路径:根 realpath → 候选包含校验 → 候选 realpath
235
+ * → 结果再包含校验。符号链接只有目标仍在根内才放行(指向工作区外的链接或
236
+ * Windows junction 读不到根外内容)。
237
+ *
238
+ * `extraRoots` 是用户显式授权的额外可读目录(设置页维护):候选路径或 realpath
239
+ * 之后的目标只要落在其中任一目录下也放行。这样工作区外文件的历史回放/全文对照
240
+ * 可以按用户授权读取,而不是放开任意根。
241
+ *
242
+ * 失败一律抛带状态码的 RequestError,且消息固定:绝不把原始 fs 错误
243
+ * (含用户请求的绝对路径与 errno)回给调用方。
244
+ *
245
+ * @param {string} cwd - 会话工作区根。
246
+ * @param {string} requestedPath - 请求路径(绝对或相对 cwd)。
247
+ * @param {string[]} [extraRoots] - 已规范化的额外可读目录。
248
+ * @returns {Promise<{ filename: string, size: number }>} 解析后的真实文件名与大小。
249
+ */
250
+ export async function resolveReadTarget(cwd, requestedPath, extraRoots = []) {
251
+ if (typeof cwd !== 'string' || cwd === '') throw new RequestError(400, 'cwd is required')
252
+ if (typeof requestedPath !== 'string' || requestedPath === '') throw new RequestError(400, 'path is required')
253
+ // NUL 会截断底层系统调用,属于非法路径而不是普通“不存在”。
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 !== '') : []
256
+ let root
257
+ try {
258
+ root = await realpath(cwd)
259
+ } catch {
260
+ throw new RequestError(404, 'workspace is not readable')
261
+ }
262
+ const candidate = resolve(root, requestedPath)
263
+ if (!inside(root, candidate) && !roots.some(extra => isSameOrInside(extra, candidate))) {
264
+ throw new RequestError(403, 'path is outside the session workspace')
265
+ }
266
+ let filename
267
+ try {
268
+ // 符号链接在这里解析:只有 realpath 之后仍在根内(或授权的额外目录内)才
269
+ // 放行,因此一个指向其它位置的链接无法绕过围栏。
270
+ filename = await realpath(candidate)
271
+ } catch {
272
+ throw new RequestError(404, 'file is not readable')
273
+ }
274
+ if (!inside(root, filename) && !roots.some(extra => isSameOrInside(extra, filename))) {
275
+ throw new RequestError(403, 'resolved path is outside the session workspace')
276
+ }
277
+ let info
278
+ try {
279
+ info = await stat(filename)
280
+ } catch {
281
+ throw new RequestError(404, 'file is not readable')
282
+ }
283
+ if (!info.isFile()) throw new RequestError(400, 'path is not a regular file')
284
+ return { filename, size: info.size }
285
+ }
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
+
502
+ /**
503
+ * 读取一个展示目标;用 `kind` 显式告诉浏览器如何降级。
504
+ *
505
+ * 读取带独立超时,并在读取后再次检查大小:文件在 stat 与 readFile 之间变大时,
506
+ * 仍然不会超过展示上限。
507
+ *
508
+ * @returns {Promise<{kind:'text', text:string, size:number} |
509
+ * {kind:'binary'|'oversized', size:number}>}
510
+ */
511
+ async function readDisplayTarget(cwd, requestedPath, extraRoots = []) {
512
+ const target = await resolveReadTarget(cwd, requestedPath, extraRoots)
513
+ if (target.size > READ_CAP) return { kind: 'oversized', size: target.size }
514
+ const controller = new AbortController()
515
+ const timer = setTimeout(() => controller.abort(), READ_TIMEOUT_MS)
516
+ let bytes
517
+ try {
518
+ bytes = await readFile(target.filename, { signal: controller.signal })
519
+ } catch (error) {
520
+ if (controller.signal.aborted || error?.name === 'AbortError') {
521
+ throw new RequestError(504, 'file read timed out')
522
+ }
523
+ throw new RequestError(404, 'file is not readable')
524
+ } finally {
525
+ clearTimeout(timer)
526
+ }
527
+ if (bytes.length > READ_CAP) return { kind: 'oversized', size: bytes.length }
528
+ const text = decodeDisplayText(bytes)
529
+ if (text === null) return { kind: 'binary', size: target.size }
530
+ return { kind: 'text', text, size: target.size }
531
+ }
532
+
533
+ // ---------------------------------------------------------------------------
534
+ // 浏览器信任围栏(`connection` 服务未挂载时的回退)
535
+ // ---------------------------------------------------------------------------
536
+
537
+ /** 判断一个归一化 URL hostname 是否为本机 loopback(localhost / [::1] / 127.0.0.0-127.255.255.255)。 */
538
+ export function isLoopbackHostname(hostname) {
539
+ if (typeof hostname !== 'string' || hostname === '') return false
540
+ if (hostname === 'localhost' || hostname === '[::1]') return true
541
+ const parts = hostname.split('.')
542
+ return parts.length === 4 && parts[0] === '127' && parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255)
543
+ }
544
+
545
+ /**
546
+ * 把裸 authority(`host` 或 `host:port`)解析成 URL;不可解析时返回 undefined。
547
+ *
548
+ * 之后还会要求 pathname/search/hash 为空,因此夹带 `user@host` 或 `host/path`
549
+ * 的 Host 头无法通过包含校验。
550
+ */
551
+ function parseAuthority(authority, scheme = 'http:') {
552
+ try {
553
+ return new URL(`${scheme}//${authority}`)
554
+ } catch {
555
+ return undefined
556
+ }
557
+ }
558
+
559
+ /**
560
+ * 本监听器绑定 literal 对应的 URL hostname(IPv6 自动加方括号,去掉 zone id),
561
+ * 无法解析时返回 undefined。
562
+ */
563
+ export function bindHostname(bindHost) {
564
+ if (typeof bindHost !== 'string' || bindHost === '') return undefined
565
+ const zoneAt = bindHost.indexOf('%')
566
+ const address = zoneAt === -1 ? bindHost : bindHost.slice(0, zoneAt)
567
+ if (address === '') return undefined
568
+ const parsed = parseAuthority(address.includes(':') ? `[${address}]` : address)
569
+ return parsed?.hostname
570
+ }
571
+
572
+ /**
573
+ * 判断附带的 `Origin` 头与 `Host` 是否同一 authority。
574
+ *
575
+ * Host 按 Origin 自己的 HTTP(S) 协议解析,保证默认端口归一一致(HTTPS 反向代理
576
+ * 后面可能是一个 HTTP 监听器)。
577
+ */
578
+ export function isSameAuthorityOrigin(origin, host) {
579
+ if (typeof origin !== 'string' || typeof host !== 'string') return false
580
+ let originUrl
581
+ try {
582
+ originUrl = new URL(origin)
583
+ } catch {
584
+ return false
585
+ }
586
+ const scheme = originUrl.protocol === 'https:' ? 'https:' : originUrl.protocol === 'http:' ? 'http:' : undefined
587
+ if (scheme === undefined) return false
588
+ const hostUrl = parseAuthority(host, scheme)
589
+ return hostUrl !== undefined && originUrl.host === hostUrl.host
590
+ }
591
+
592
+ /**
593
+ * 没有 `connection` 服务的 profile 使用的本地回退围栏。
594
+ *
595
+ * 防御 DNS rebinding(Host 写成攻击者域名、socket 却落到本机)与来自恶意页面
596
+ * 的跨站请求。HTTP 页面里的读取型请求不携带 Origin,所以 Host 是唯一可靠依据:
597
+ * 只接受 loopback 或监听器自己的绑定 IP literal;带 Origin 时必须是同一
598
+ * authority;`sec-fetch-site: cross-site` 一律拒绝。
599
+ *
600
+ * @param {object} req - Node HTTP 请求(只读 headers)。
601
+ * @param {string | undefined} bindHost - 本监听器的绑定地址 literal。
602
+ * @param {'http:' | 'https:'} protocol - 本监听器的协议。
603
+ * @returns {boolean} true 表示允许访问展示 API。
604
+ */
605
+ export function isTrustedHostRequest(req, bindHost, protocol = 'http:') {
606
+ const headers = req !== null && typeof req === 'object' ? req.headers : undefined
607
+ const host = headerOf(headers, 'host')
608
+ if (host === undefined) return false
609
+ const hostUrl = parseAuthority(host, protocol)
610
+ if (hostUrl === undefined) return false
611
+ // Host 必须是裸 authority:不能带凭据、路径、query 或 fragment。
612
+ if (hostUrl.username !== '' || hostUrl.password !== '' || hostUrl.pathname !== '/' || hostUrl.search !== '' || hostUrl.hash !== '') return false
613
+ const loopback = isLoopbackHostname(hostUrl.hostname)
614
+ const ownBind = hostUrl.hostname === bindHostname(bindHost)
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
+ }
622
+ if (headerOf(headers, 'sec-fetch-site') === 'cross-site') return false
623
+ const origin = headerOf(headers, 'origin')
624
+ if (origin === undefined) return true
625
+ return isSameAuthorityOrigin(origin, host)
626
+ }
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
+
641
+ /** 读取一个 header 值(Node 已把名字转小写;单值字符串与数组首项都接受)。 */
642
+ function headerOf(headers, name) {
643
+ if (headers === null || typeof headers !== 'object') return undefined
644
+ const value = headers[name]
645
+ if (typeof value === 'string') return value
646
+ if (Array.isArray(value) && typeof value[0] === 'string') return value[0]
647
+ return undefined
648
+ }
649
+
650
+ /** 回退围栏需要的 webServer 事实(绑定地址与协议);服务缺失/形状异常时返回安全默认。 */
651
+ function webServerFacts(ctx) {
652
+ const fallback = { bindHost: undefined, protocol: 'http:' }
653
+ try {
654
+ let web = undefined
655
+ if (ctx !== null && typeof ctx === 'object') {
656
+ web = typeof ctx.webServer === 'object' && ctx.webServer !== null ? ctx.webServer : undefined
657
+ if (web === undefined && typeof ctx.get === 'function') web = ctx.get('webServer')
658
+ }
659
+ if (web === null || typeof web !== 'object') return fallback
660
+ return {
661
+ bindHost: typeof web.host === 'string' ? web.host : undefined,
662
+ protocol: web.protocol === 'https:' ? 'https:' : 'http:',
663
+ }
664
+ } catch {
665
+ return fallback
666
+ }
667
+ }
668
+
669
+ /**
670
+ * 单个路由请求的准入判定。
671
+ *
672
+ * 优先复用 DSH 官方 connection 服务的准入(Host/Origin/跨站 + 浏览器 Cookie
673
+ * 认证),这样本插件不会成为绕过平台认证的旁路;只有该服务未挂载的 profile 才
674
+ * 退回本地围栏。任何异常都走围栏而不是直接放行(fail-closed)。
675
+ *
676
+ * @returns {number | undefined} 拒绝时返回 HTTP 状态码;undefined 表示放行。
677
+ */
678
+ function admissionRejection(ctx, req) {
679
+ let connection
680
+ try {
681
+ if (ctx !== null && typeof ctx === 'object' && typeof ctx.get === 'function') connection = ctx.get('connection')
682
+ } catch {
683
+ connection = undefined
684
+ }
685
+ if (connection !== null && typeof connection === 'object' && typeof connection.admit === 'function') {
686
+ try {
687
+ const admission = connection.admit(req)
688
+ if (admission !== null && typeof admission === 'object' && 'rejection' in admission) {
689
+ const status = admission.rejection
690
+ return status === 401 ? 401 : 403
691
+ }
692
+ return undefined
693
+ } catch {
694
+ // 服务形态与预期不符(版本漂移):退回本地围栏继续判定。
695
+ }
696
+ }
697
+ const facts = webServerFacts(ctx)
698
+ return isTrustedHostRequest(req, facts.bindHost, facts.protocol) ? undefined : 403
699
+ }
700
+
701
+ // ---------------------------------------------------------------------------
702
+ // HTTP 辅助函数
703
+ // ---------------------------------------------------------------------------
704
+
705
+ /**
706
+ * 固定响应头:只回 JSON、禁止 MIME 嗅探、禁止缓存、不泄露 referrer、
707
+ * 禁止跨源读取(display-only API 不需要被其它源嵌入)。
708
+ */
709
+ const JSON_HEADERS = Object.freeze({
710
+ 'content-type': 'application/json; charset=utf-8',
711
+ 'x-content-type-options': 'nosniff',
712
+ 'cache-control': 'no-store',
713
+ 'referrer-policy': 'no-referrer',
714
+ 'cross-origin-resource-policy': 'same-origin',
715
+ })
716
+
717
+ /** 发送一个 JSON 响应;连接已断开时安全 no-op(display-only API 没有需要保护的状态)。 */
718
+ function respond(res, status, payload) {
719
+ if (res === null || typeof res !== 'object') return
720
+ if (res.headersSent === true || res.writableEnded === true) return
721
+ let body
722
+ try {
723
+ body = JSON.stringify(payload)
724
+ } catch {
725
+ body = '{"ok":false,"error":"response failed"}'
726
+ }
727
+ try {
728
+ res.writeHead(status, JSON_HEADERS)
729
+ res.end(body)
730
+ } catch {
731
+ // 客户端已断开:没有需要保护的状态,忽略。
732
+ }
733
+ }
734
+
735
+ /** 发送一个带类型的失败响应(稳定错误码,不含文件系统细节)。 */
736
+ function fail(res, status, error) {
737
+ respond(res, status, { ok: false, error })
738
+ }
739
+
740
+ /**
741
+ * 拒绝一个“body 可能还在传输”的请求:先写响应,等响应刷出后再销毁 socket。
742
+ * (先销毁会丢掉客户端需要看到的 413/408。)
743
+ */
744
+ function rejectBody(req, res, status, error) {
745
+ if (res !== null && typeof res === 'object' && res.headersSent !== true && res.writableEnded !== true) {
746
+ try {
747
+ res.writeHead(status, JSON_HEADERS)
748
+ res.end(JSON.stringify({ ok: false, error }), () => {
749
+ try {
750
+ req.destroy()
751
+ } catch {
752
+ // 忽略:连接已断开,无需处理。
753
+ }
754
+ })
755
+ return
756
+ } catch {
757
+ // 写响应失败则直接走销毁。
758
+ }
759
+ }
760
+ try {
761
+ req.destroy()
762
+ } catch {
763
+ // 忽略:socket 已不可用。
764
+ }
765
+ }
766
+
767
+ /** 请求是否声明了 `application/json` body(忽略参数部分、大小写不敏感)。 */
768
+ function isJsonRequest(req) {
769
+ const type = headerOf(req?.headers, 'content-type')
770
+ if (typeof type !== 'string') return false
771
+ const media = type.split(';', 1)[0].trim().toLowerCase()
772
+ return media === 'application/json'
773
+ }
774
+
775
+ /**
776
+ * 读取一个 JSON 请求体:硬上限 + 读取超时 + 提前 Content-Length 拒绝。
777
+ *
778
+ * 解析结果在 Promise 外先按对象校验:数组、null、标量都拒绝,避免下游把
779
+ * `body.cwd` 之类的字段访问变成奇怪的类型强制转换。
780
+ *
781
+ * @param {object} req - Node IncomingMessage(只读取 headers)。
782
+ * @param {object} res - Node ServerResponse(用于提前拒绝时先回响应)。
783
+ * @returns {Promise<object>} 解析后的对象。
784
+ */
785
+ function readJsonBody(req, res) {
786
+ return new Promise((resolvePromise, rejectPromise) => {
787
+ let settled = false
788
+ let size = 0
789
+ const chunks = []
790
+ let timer
791
+ /** 让 Promise 恰好 settle 一次并释放超时定时器(重复 settle 直接忽略)。 */
792
+ const settle = (settleWith, value) => {
793
+ if (settled) return
794
+ settled = true
795
+ if (timer !== undefined) clearTimeout(timer)
796
+ settleWith(value)
797
+ }
798
+ const abort = (status, error) => {
799
+ rejectBody(req, res, status, error)
800
+ settle(rejectPromise, new RequestError(status, error))
801
+ }
802
+ // 快速失败:声明的 Content-Length 已超限时不必读取任何字节。
803
+ const declared = headerOf(req?.headers, 'content-length')
804
+ if (declared !== undefined && /^\d+$/.test(declared) && Number(declared) > BODY_CAP) {
805
+ abort(413, 'request body too large')
806
+ return
807
+ }
808
+ timer = setTimeout(() => {
809
+ abort(408, 'request body read timeout')
810
+ }, BODY_TIMEOUT_MS)
811
+ req.on('data', chunk => {
812
+ if (settled) return
813
+ // 防御性:Node 正常给 Buffer;非 Buffer 只接受字符串,其余忽略。
814
+ const buffer = Buffer.isBuffer(chunk) ? chunk : typeof chunk === 'string' ? Buffer.from(chunk) : null
815
+ if (buffer === null) return
816
+ size += buffer.length
817
+ if (size > BODY_CAP) {
818
+ abort(413, 'request body too large')
819
+ return
820
+ }
821
+ chunks.push(buffer)
822
+ })
823
+ req.on('end', () => {
824
+ if (settled) return
825
+ let parsed
826
+ try {
827
+ parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'))
828
+ } catch {
829
+ settle(rejectPromise, new RequestError(400, 'invalid JSON body'))
830
+ return
831
+ }
832
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
833
+ settle(rejectPromise, new RequestError(400, 'body must be a JSON object'))
834
+ return
835
+ }
836
+ settle(resolvePromise, parsed)
837
+ })
838
+ req.on('error', () => {
839
+ if (settled) return
840
+ settle(rejectPromise, new RequestError(400, 'request aborted'))
841
+ })
842
+ // `close` 在上传中途中止与正常结束后都会触发;正常路径此时 Promise 已经
843
+ // settle,因此这里只在尚未 settle 时按中止处理。
844
+ req.on('close', () => {
845
+ if (settled) return
846
+ settle(rejectPromise, new RequestError(400, 'request aborted'))
847
+ })
848
+ })
849
+ }
850
+
851
+ /** 提取请求 URL 的 pathname(忽略 query string)。 */
852
+ function routeOf(rawUrl) {
853
+ if (typeof rawUrl !== 'string' || rawUrl === '') return '/'
854
+ const question = rawUrl.indexOf('?')
855
+ return question === -1 ? rawUrl : rawUrl.slice(0, question)
856
+ }
857
+
858
+ /** 把匹配到的路由映射成 action 名;未知路由返回原文(由调用方回 404)。 */
859
+ function actionOf(route) {
860
+ if (route.startsWith(API_PREFIX + '/')) return route.slice(API_PREFIX.length + 1)
861
+ if (route.startsWith('/')) return route.slice(1)
862
+ return route
863
+ }
864
+
865
+ // ---------------------------------------------------------------------------
866
+ // 快照捕获
867
+ // ---------------------------------------------------------------------------
868
+
869
+ /**
870
+ * 从一次 `tools/result` 事件捕获成功的文件修改快照。
871
+ *
872
+ * 只处理成功、且工具名是 `edit`/`write` 的结果(`str_replace_editor` 不产生
873
+ * 执行快照,卡片走元数据差异块路径)。展示专用:畸形/冻结/异常形状的事件都
874
+ * 在这里吞掉,绝不影响 Tool 调用本身。
875
+ *
876
+ * 边界:after 必须是非空字符串且不超过单条文本上限;before 可为 null(新建);
877
+ * callId/sessionId 缺失或超长时放弃捕获(防止异常 key 撑爆存储)。
878
+ */
879
+ function captureSnapshot(exec, result) {
880
+ try {
881
+ if (result === undefined || result === null || result.isError === true) return
882
+ const name = exec?.name
883
+ if (name !== 'edit' && name !== 'write') return
884
+ const value = result.value
885
+ if (value === null || typeof value !== 'object') return
886
+ const after = value.after
887
+ if (typeof after !== 'string') return
888
+ if (after.length > SNAPSHOT_TEXT_CAP) return
889
+ const before = typeof value.before === 'string' ? value.before : null
890
+ if (before !== null && before.length > SNAPSHOT_TEXT_CAP) return
891
+ const callId = exec.callId === undefined || exec.callId === null ? '' : String(exec.callId)
892
+ if (callId === '' || callId.length > MAX_ID_LENGTH) return
893
+ const sessionId = exec.agent?.id === undefined || exec.agent?.id === null ? '' : String(exec.agent.id)
894
+ if (sessionId.length > MAX_ID_LENGTH) return
895
+ const path = typeof value.path === 'string' ? value.path : (typeof exec.arguments?.file_path === 'string' ? exec.arguments.file_path : '')
896
+ putSnapshot(snapshotKey(sessionId, callId), {
897
+ path,
898
+ before,
899
+ after,
900
+ operation: typeof value.operation === 'string'
901
+ ? value.operation
902
+ : before === null ? 'create' : 'update',
903
+ at: Date.now(),
904
+ })
905
+ } catch {
906
+ // 展示专用捕获:绝不影响 Tool 调用本身。
907
+ }
908
+ }
909
+
910
+ // ---------------------------------------------------------------------------
911
+ // 版本与更新(设置页自带的检查更新 / 更新 / 回退)
912
+ // ---------------------------------------------------------------------------
913
+
914
+ /** npm 包名兜底值:正常情况下从本目录的 package.json 读取,改名后无需改 Host 代码。 */
915
+ const UPDATE_PACKAGE_FALLBACK = '@him666233/dsh-inline-diff'
916
+ const UPDATE_FETCH_TIMEOUT_MS = 12_000
917
+ const UPDATE_CACHE_TTL_MS = 60_000
918
+ const UPDATE_INSTALL_TIMEOUT_MS = 240_000
919
+ const UPDATE_LOG_CAP = 16 * 1024
920
+ const UPDATE_ERROR_TAIL_CAP = 4_000
921
+ /** registry packument 响应上限:正常只有 ~10KB,2MB 足以覆盖且防止恶意超大响应撑内存。 */
922
+ const REGISTRY_MAX_CHARS = 2 * 1024 * 1024
923
+ /** 版本列表最多保留多少条(防止异常 packument 生成超大数组)。 */
924
+ const REGISTRY_MAX_VERSIONS = 200
925
+ /** profile 名白名单:只允许常见字符,防止被当成 CLI 选项或路径片段。 */
926
+ const PROFILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
927
+
928
+ /** registry 列表缓存(Host 进程级)。 */
929
+ let updateCache = { at: 0, data: null }
930
+ /** 同一进程内只允许一个安装任务(CLI 自身还有跨进程文件锁)。 */
931
+ let updateBusy = false
932
+
933
+ /** 本插件 Host 半区所在目录(读自己的 package.json 取当前版本)。 */
934
+ function selfDir() {
935
+ return dirname(fileURLToPath(import.meta.url))
936
+ }
937
+
938
+ /** 安全读 JSON;缺失/损坏返回 null。 */
939
+ async function readJsonSafe(file) {
940
+ try {
941
+ return JSON.parse(await readFile(file, 'utf8'))
942
+ } catch {
943
+ return null
944
+ }
945
+ }
946
+
947
+ /** 当前已加载的插件版本(来自安装目录的 package.json)。 */
948
+ async function currentPluginVersion() {
949
+ const manifest = await readJsonSafe(join(selfDir(), 'package.json'))
950
+ return typeof manifest?.version === 'string' ? manifest.version : null
951
+ }
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
+
985
+ /**
986
+ * 当前 profile 的上下文。优先用 DSH 文档化的 profileContext 服务;取不到时
987
+ * 回退解析 `--profile <name>` / DSH_PROFILE 环境变量(Web CLI 启动场景)。
988
+ */
989
+ function profileContextOf(ctx) {
990
+ try {
991
+ const pc = typeof ctx?.get === 'function' ? ctx.get('profileContext') : undefined
992
+ if (pc !== null && typeof pc === 'object' && typeof pc.name === 'string' && PROFILE_NAME_PATTERN.test(pc.name)) return pc
993
+ } catch {
994
+ // 服务不可用:继续回退。
995
+ }
996
+ const argv = Array.isArray(process.argv) ? process.argv : []
997
+ let name = typeof process.env.DSH_PROFILE === 'string' ? process.env.DSH_PROFILE : null
998
+ for (let index = 0; index < argv.length - 1; index += 1) {
999
+ if (argv[index] === '--profile' && typeof argv[index + 1] === 'string') name = argv[index + 1]
1000
+ }
1001
+ if (name === null || name === '' || !PROFILE_NAME_PATTERN.test(name)) return null
1002
+ const home = typeof process.env.DSH_HOME === 'string' && process.env.DSH_HOME !== ''
1003
+ ? process.env.DSH_HOME
1004
+ : join(homedir(), '.dsh')
1005
+ return { name, dir: join(home, 'profiles', name) }
1006
+ }
1007
+
1008
+ /** 是否运行在桌面 Electron 宿主里(桌面端 v1 只读展示 + 手动命令)。 */
1009
+ function isDesktopHost() {
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)))
1014
+ }
1015
+
1016
+ /** semver 解析;非 semver 返回 null。 */
1017
+ function parseSemver(text) {
1018
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(String(text).trim())
1019
+ if (match === null) return null
1020
+ return {
1021
+ major: Number(match[1]),
1022
+ minor: Number(match[2]),
1023
+ patch: Number(match[3]),
1024
+ pre: match[4] === undefined ? [] : match[4].split('.'),
1025
+ }
1026
+ }
1027
+
1028
+ /** semver 比较:a<b 返回负数,a==b 返回 0,a>b 返回正数(含 prerelease 规则)。 */
1029
+ function compareSemver(left, right) {
1030
+ const a = parseSemver(left)
1031
+ const b = parseSemver(right)
1032
+ if (a === null || b === null) return 0
1033
+ for (const key of ['major', 'minor', 'patch']) {
1034
+ if (a[key] !== b[key]) return a[key] - b[key]
1035
+ }
1036
+ if (a.pre.length === 0 && b.pre.length === 0) return 0
1037
+ if (a.pre.length === 0) return 1
1038
+ if (b.pre.length === 0) return -1
1039
+ const length = Math.max(a.pre.length, b.pre.length)
1040
+ for (let index = 0; index < length; index += 1) {
1041
+ const x = a.pre[index]
1042
+ const y = b.pre[index]
1043
+ if (x === undefined) return -1
1044
+ if (y === undefined) return 1
1045
+ const xn = /^\d+$/.test(x) ? Number(x) : null
1046
+ const yn = /^\d+$/.test(y) ? Number(y) : null
1047
+ if (xn !== null && yn !== null) {
1048
+ if (xn !== yn) return xn - yn
1049
+ continue
1050
+ }
1051
+ if (xn !== null) return -1
1052
+ if (yn !== null) return 1
1053
+ if (x !== y) return x < y ? -1 : 1
1054
+ }
1055
+ return 0
1056
+ }
1057
+
1058
+ /** 把 registry packument 收窄成设置页可用的版本列表。 */
1059
+ function normalizeRegistry(document) {
1060
+ const latest = typeof document?.['dist-tags']?.latest === 'string' ? document['dist-tags'].latest : null
1061
+ const time = document?.time !== null && typeof document?.time === 'object' ? document.time : {}
1062
+ const versions = []
1063
+ for (const [version, meta] of Object.entries(document?.versions ?? {})) {
1064
+ if (parseSemver(version) === null) continue
1065
+ const hasBundle = meta?.dsh !== null && typeof meta?.dsh === 'object' && meta.dsh.bundle !== undefined && meta.dsh.bundle !== null
1066
+ // 占位/坏包(例如 0.0.0-stage)没有 dsh.bundle 且 tarball 元数据损坏,安装会
1067
+ // 在 pnpm 重试数分钟后失败:直接标记为不可安装,避免用户踩坑。
1068
+ const stub = meta?.stub === true || !hasBundle
1069
+ versions.push({
1070
+ version,
1071
+ publishedAt: typeof time[version] === 'string' ? time[version] : null,
1072
+ latest: latest === version,
1073
+ deprecated: typeof meta?.deprecated === 'string' ? meta.deprecated : null,
1074
+ enginesDsh: typeof meta?.engines?.dsh === 'string' ? meta.engines.dsh : null,
1075
+ bundleMissing: !hasBundle,
1076
+ installable: !stub,
1077
+ })
1078
+ }
1079
+ versions.sort((a, b) => compareSemver(b.version, a.version))
1080
+ return { latest, versions: versions.slice(0, REGISTRY_MAX_VERSIONS) }
1081
+ }
1082
+
1083
+ /** 拉取 npm registry 版本列表(带超时与 60s 缓存)。 */
1084
+ async function fetchRegistryVersions(force) {
1085
+ if (force !== true && updateCache.data !== null && Date.now() - updateCache.at < UPDATE_CACHE_TTL_MS) {
1086
+ return updateCache.data
1087
+ }
1088
+ const controller = new AbortController()
1089
+ const timer = setTimeout(() => controller.abort(), UPDATE_FETCH_TIMEOUT_MS)
1090
+ try {
1091
+ const response = await fetch(registryUrlOf(updatePackageName()), {
1092
+ headers: { accept: 'application/json' },
1093
+ signal: controller.signal,
1094
+ })
1095
+ if (!response.ok) throw new Error(`registry responded ${response.status}`)
1096
+ // 先按 Content-Length 与正文长度双重限制,再 JSON.parse:即使 registry/代理
1097
+ // 返回异常超大响应,也不会在 Host 进程里分配无界内存。
1098
+ const declared = Number(response.headers.get('content-length') ?? '0')
1099
+ if (Number.isFinite(declared) && declared > REGISTRY_MAX_CHARS) throw new Error('registry response too large')
1100
+ const bodyText = await response.text()
1101
+ if (bodyText.length > REGISTRY_MAX_CHARS) throw new Error('registry response too large')
1102
+ let document
1103
+ try {
1104
+ document = JSON.parse(bodyText)
1105
+ } catch {
1106
+ throw new Error('registry response is not valid JSON')
1107
+ }
1108
+ if (document === null || typeof document !== 'object' || Array.isArray(document)) {
1109
+ throw new Error('registry response has unexpected shape')
1110
+ }
1111
+ const data = normalizeRegistry(document)
1112
+ updateCache = { at: Date.now(), data }
1113
+ return data
1114
+ } finally {
1115
+ clearTimeout(timer)
1116
+ }
1117
+ }
1118
+
1119
+ /** 当前 profile 的安装方式:Web 可一键调用官方 CLI;桌面端降级为手动命令。 */
1120
+ function installerInfo(pc) {
1121
+ const name = pc?.name ?? 'web'
1122
+ const anchor = typeof pc?.installAnchor === 'string' ? pc.installAnchor : null
1123
+ // installAnchor 必须是当前安装锚点里的 @deepseek-ai/dsh/package.json;否则视为
1124
+ // 不可用(宁可降级为手动命令,也不从任意路径 spawn)。
1125
+ const anchorLooksExpected = anchor !== null
1126
+ && /[\\/]node_modules[\\/]@deepseek-ai[\\/]dsh[\\/]package\.json$/.test(anchor)
1127
+ const cliRoot = anchorLooksExpected ? dirname(anchor) : null
1128
+ const cliBin = cliRoot === null ? null : join(cliRoot, 'lib', 'bin.js')
1129
+ const command = `dsh plugin --profile ${name} add ${updatePackageName()}@<version>`
1130
+ if (isDesktopHost()) {
1131
+ return { mode: 'manual', platform: 'desktop', command, cliBin: null, reason: 'desktop-requires-exit' }
1132
+ }
1133
+ if (cliBin === null || !isAbsolute(cliBin) || !existsSync(cliBin)) {
1134
+ return { mode: 'manual', platform: 'web', command, cliBin: null, reason: 'cli-not-found' }
1135
+ }
1136
+ return { mode: 'cli', platform: 'web', command, cliBin, reason: null }
1137
+ }
1138
+
1139
+ /** 读取 profile 里已安装的插件版本;读不到返回 null。 */
1140
+ async function installedVersionAt(pc) {
1141
+ if (pc === null || typeof pc.dir !== 'string') return null
1142
+ const manifest = await readJsonSafe(join(pc.dir, 'node_modules', updatePackageName(), 'package.json'))
1143
+ return typeof manifest?.version === 'string' ? manifest.version : null
1144
+ }
1145
+
1146
+ /** 读取 profile 绑定的 DSH 版本(installAnchor 指向 @deepseek-ai/dsh/package.json)。 */
1147
+ async function dshVersionAt(pc) {
1148
+ if (pc === null || typeof pc.installAnchor !== 'string') return null
1149
+ const manifest = await readJsonSafe(pc.installAnchor)
1150
+ return typeof manifest?.version === 'string' ? manifest.version : null
1151
+ }
1152
+
1153
+ /** 在子进程里跑官方 CLI 的 plugin add;返回结构化结果(含日志尾部)。 */
1154
+ function runPluginInstall(pc, version, installer) {
1155
+ return new Promise((resolveResult) => {
1156
+ const spec = `${updatePackageName()}@${version}`
1157
+ const command = `dsh plugin --profile ${pc.name} add ${spec}`
1158
+ const args = [installer.cliBin, 'plugin', '--profile', pc.name, 'add', spec]
1159
+ if (typeof installer.cliBin !== 'string' || !isAbsolute(installer.cliBin) || !PROFILE_NAME_PATTERN.test(pc.name)) {
1160
+ resolveResult({ ok: false, code: 'installer-unavailable', command })
1161
+ return
1162
+ }
1163
+ let child
1164
+ try {
1165
+ child = spawn(process.execPath, args, {
1166
+ cwd: typeof pc.dir === 'string' && isAbsolute(pc.dir) ? pc.dir : process.cwd(),
1167
+ windowsHide: true,
1168
+ env: { ...process.env },
1169
+ stdio: ['ignore', 'pipe', 'pipe'],
1170
+ // POSIX:让 CLI 自成一个进程组,超时时可以整组 SIGKILL;否则 pnpm 的
1171
+ // 孙进程会留在机器上(Windows 走 taskkill /T,见下面的超时分支)。
1172
+ detached: process.platform !== 'win32',
1173
+ })
1174
+ } catch (error) {
1175
+ resolveResult({ ok: false, code: 'spawn-failed', command, logTail: String(error?.message ?? '') })
1176
+ return
1177
+ }
1178
+ let stdout = ''
1179
+ let stderr = ''
1180
+ let settled = false
1181
+ const finish = (result) => {
1182
+ if (settled) return
1183
+ settled = true
1184
+ clearTimeout(timer)
1185
+ resolveResult({ ...result, command })
1186
+ }
1187
+ child.stdout?.on('data', (chunk) => { stdout = (stdout + String(chunk)).slice(-UPDATE_LOG_CAP) })
1188
+ child.stderr?.on('data', (chunk) => { stderr = (stderr + String(chunk)).slice(-UPDATE_LOG_CAP) })
1189
+ child.on('error', (error) => finish({ ok: false, code: 'spawn-failed', logTail: String(error?.message ?? '') }))
1190
+ child.on('close', (code) => {
1191
+ const logTail = (stderr + stdout).slice(-UPDATE_ERROR_TAIL_CAP)
1192
+ finish({ ok: code === 0, code: code === 0 ? 'ok' : `exit-${code}`, exitCode: code, logTail })
1193
+ })
1194
+ const timer = setTimeout(() => {
1195
+ try {
1196
+ if (process.platform === 'win32') {
1197
+ // npm/pnpm 会拉起子进程树:只 kill 父进程会留下孤儿,因此用 taskkill /T。
1198
+ // spawn 失败时 pid 可能缺失,不能把 "undefined" 传给 taskkill。
1199
+ if (Number.isInteger(child.pid)) spawn('taskkill', ['/pid', String(child.pid), '/t', '/f'], { windowsHide: true }).on('error', () => {})
1200
+ } else {
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
+ }
1208
+ }
1209
+ } catch {
1210
+ // 尽力而为:超时返回状态仍然明确。
1211
+ }
1212
+ finish({ ok: false, code: 'timeout', logTail: (stderr + stdout).slice(-UPDATE_ERROR_TAIL_CAP) })
1213
+ }, UPDATE_INSTALL_TIMEOUT_MS)
1214
+ })
1215
+ }
1216
+
1217
+ /** GET /update/versions 的响应体。 */
1218
+ async function updateVersionsPayload(ctx, force) {
1219
+ const pc = profileContextOf(ctx)
1220
+ const [current, registry, dshVersion] = await Promise.all([
1221
+ currentPluginVersion(),
1222
+ fetchRegistryVersions(force),
1223
+ dshVersionAt(pc),
1224
+ ])
1225
+ const installed = await installedVersionAt(pc)
1226
+ const installer = installerInfo(pc)
1227
+ return {
1228
+ ok: true,
1229
+ current: installed ?? current,
1230
+ loaded: current,
1231
+ dshVersion,
1232
+ latest: registry.latest,
1233
+ // 只回传 profile 名称:绝对路径属于本机信息,UI 也不需要,避免不必要地暴露。
1234
+ profile: pc === null ? null : { name: pc.name },
1235
+ installer,
1236
+ versions: registry.versions,
1237
+ }
1238
+ }
1239
+
1240
+ /** POST /update/install 的核心:校验版本 → 跑 CLI → 复核安装结果。 */
1241
+ async function performUpdate(ctx, body) {
1242
+ const version = body?.version
1243
+ if (typeof version !== 'string' || version.length > 100 || parseSemver(version) === null) {
1244
+ return { status: 400, payload: { ok: false, code: 'invalid-version' } }
1245
+ }
1246
+ const pc = profileContextOf(ctx)
1247
+ if (pc === null) return { status: 400, payload: { ok: false, code: 'profile-unknown' } }
1248
+ const installer = installerInfo(pc)
1249
+ if (installer.mode !== 'cli') {
1250
+ return {
1251
+ status: 400,
1252
+ payload: {
1253
+ ok: false,
1254
+ code: installer.reason ?? 'manual-required',
1255
+ command: `${installer.command.replace('@<version>', `@${version}`)}`,
1256
+ },
1257
+ }
1258
+ }
1259
+ const registry = await fetchRegistryVersions(false)
1260
+ const entry = registry.versions.find(item => item.version === version)
1261
+ if (entry === undefined) return { status: 400, payload: { ok: false, code: 'version-not-found' } }
1262
+ if (entry.installable !== true) return { status: 400, payload: { ok: false, code: 'version-not-installable' } }
1263
+ if (updateBusy) return { status: 409, payload: { ok: false, code: 'busy' } }
1264
+ updateBusy = true
1265
+ try {
1266
+ const result = await runPluginInstall(pc, version, installer)
1267
+ if (!result.ok) return { status: 200, payload: { ok: false, code: result.code, logTail: result.logTail, command: result.command } }
1268
+ const installed = await installedVersionAt(pc)
1269
+ if (installed !== version) {
1270
+ return { status: 200, payload: { ok: false, code: 'verify-failed', installedVersion: installed, logTail: result.logTail, command: result.command } }
1271
+ }
1272
+ // 安装成功:下次进程启动才加载新代码,因此必须提示重启(页面刷新不够)。
1273
+ updateCache = { at: 0, data: null }
1274
+ return {
1275
+ status: 200,
1276
+ payload: { ok: true, installedVersion: installed, restartRequired: true, logTail: result.logTail, command: result.command },
1277
+ }
1278
+ } finally {
1279
+ updateBusy = false
1280
+ }
1281
+ }
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
+
1349
+ // ---------------------------------------------------------------------------
1350
+ // 路由处理
1351
+ // ---------------------------------------------------------------------------
1352
+
1353
+ /** 当前并发的展示读取计数(进程级全局上限,见 MAX_CONCURRENT_READS)。 */
1354
+ let activeReads = 0
1355
+
1356
+ /** 准入之后分发一个请求;所有失败路径都回 JSON(稳定码,不泄漏内部细节)。 */
1357
+ async function handleRequest(ctx, req, res) {
1358
+ const route = routeOf(req?.url)
1359
+ // 1. 浏览器信任边界(平台准入优先,回退本地围栏):必须在读取任何 body 之前。
1360
+ const rejection = admissionRejection(ctx, req)
1361
+ if (rejection !== undefined) {
1362
+ fail(res, rejection, rejection === 401 ? 'unauthorized' : 'forbidden')
1363
+ return
1364
+ }
1365
+ try {
1366
+ if (req.method === 'GET' && (route === '/ping' || route === API_PREFIX + '/ping')) {
1367
+ respond(res, 200, { ok: true, snapshots: snapshots.size })
1368
+ return
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
+ }
1381
+ if (req.method === 'GET' && route === API_PREFIX + '/update/versions') {
1382
+ const refresh = /[?&]refresh=1(?:&|$)/.test(String(req?.url ?? ''))
1383
+ try {
1384
+ respond(res, 200, await updateVersionsPayload(ctx, refresh))
1385
+ } catch {
1386
+ respond(res, 200, { ok: false, code: 'registry-unreachable' })
1387
+ }
1388
+ return
1389
+ }
1390
+ if (req.method !== 'POST') {
1391
+ fail(res, 405, 'POST only')
1392
+ return
1393
+ }
1394
+ // 2. 先认 action 再读 body:未知路径不消耗解析预算。
1395
+ const action = actionOf(route)
1396
+ if (action !== 'snapshot' && action !== 'read' && action !== 'update/install' && action !== 'read-roots') {
1397
+ fail(res, 404, 'unknown action')
1398
+ return
1399
+ }
1400
+ // 3. 只接受 application/json:浏览器的跨站“简单请求”无法携带该类型,
1401
+ // 因此这一道同时挡住 text/plain 形式的 CSRF 探测。
1402
+ if (!isJsonRequest(req)) {
1403
+ fail(res, 415, 'content type must be application/json')
1404
+ return
1405
+ }
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
+ }
1419
+ if (action === 'update/install') {
1420
+ const result = await performUpdate(ctx, body)
1421
+ respond(res, result.status, result.payload)
1422
+ return
1423
+ }
1424
+ if (action === 'snapshot') {
1425
+ const sessionId = body.sessionId
1426
+ const rawCallId = body.callId
1427
+ if (sessionId !== undefined && typeof sessionId !== 'string') {
1428
+ fail(res, 400, 'invalid sessionId')
1429
+ return
1430
+ }
1431
+ if (rawCallId !== undefined && typeof rawCallId !== 'string' && typeof rawCallId !== 'number') {
1432
+ fail(res, 400, 'invalid callId')
1433
+ return
1434
+ }
1435
+ const key = snapshotKey(sessionId ?? '', rawCallId === undefined || rawCallId === null ? '' : String(rawCallId))
1436
+ if (key.length > MAX_ID_LENGTH * 2 + 1) {
1437
+ fail(res, 400, 'invalid snapshot key')
1438
+ return
1439
+ }
1440
+ respond(res, 200, { ok: true, snapshot: getSnapshot(key) })
1441
+ return
1442
+ }
1443
+ if (typeof body.cwd !== 'string' || body.cwd === '') {
1444
+ fail(res, 400, 'cwd is required')
1445
+ return
1446
+ }
1447
+ if (typeof body.path !== 'string' || body.path === '') {
1448
+ fail(res, 400, 'path is required')
1449
+ return
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
+ }
1458
+ if (activeReads >= MAX_CONCURRENT_READS) {
1459
+ // 429 而不是排队:显示型读取失败时浏览器本来就会回退为差异块展示。
1460
+ fail(res, 429, 'too many concurrent reads')
1461
+ return
1462
+ }
1463
+ activeReads++
1464
+ try {
1465
+ const result = await readDisplayTarget(body.cwd, body.path, extraRoots)
1466
+ respond(res, 200, { ok: true, ...result })
1467
+ } finally {
1468
+ activeReads--
1469
+ }
1470
+ } catch (error) {
1471
+ // 底层在流式拒绝时已经写过响应(413/408):不能二次写头。
1472
+ if (res?.headersSent === true || res?.writableEnded === true) return
1473
+ const status = Number.isInteger(error?.status) ? error.status : 500
1474
+ // 内部异常只回稳定文案,不泄漏 errno / 绝对路径 / 堆栈。
1475
+ const message = error instanceof RequestError ? error.message : 'request failed'
1476
+ fail(res, status, message)
1477
+ }
1478
+ }
1479
+
1480
+ // ---------------------------------------------------------------------------
1481
+ // 插件入口
1482
+ // ---------------------------------------------------------------------------
1483
+
1484
+ /**
1485
+ * 安装 Host 半侧的捕获与只读 API。
1486
+ * @param ctx - 插件 context;`webServer` 服务通过 `inject` 注入。
1487
+ */
1488
+ export function apply(ctx) {
1489
+ // 工具结果捕获:edit/write 工具在 result value 里返回修改前/后全文,这正是
1490
+ // Host 自己做 diff 时所依据的精确文本。
1491
+ ctx.effect(() => ctx.on('tools/result', (exec, result) => {
1492
+ captureSnapshot(exec, result)
1493
+ }), 'dsh-inline-diff: capture mutation snapshots')
1494
+
1495
+ // 工具注册表变化(插件挂载/卸载、MCP 工具刷新)→ 丢弃 `/tools` 缓存,
1496
+ // 下一次请求即可看到新工具。事件没有负载,只用来失效。
1497
+ ctx.effect(() => ctx.on('tools/change', () => {
1498
+ invalidateToolNames(ctx)
1499
+ }), 'dsh-inline-diff: tool list cache')
1500
+
1501
+ // 同源展示 API。每个路由条目都是 effect 持有的资源(dispose 时自动注销)。
1502
+ ctx.effect(() => ctx.webServer.register({
1503
+ kind: 'prefix',
1504
+ path: API_PREFIX,
1505
+ handler: async (req, res) => {
1506
+ await handleRequest(ctx, req, res)
1507
+ },
1508
+ }), 'dsh-inline-diff: display api')
1509
+ }