@him666233/dsh-inline-diff 0.0.0-stage → 1.3.0
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/LICENSE +21 -0
- package/README.en.md +125 -0
- package/README.md +124 -2
- package/client.js +24771 -0
- package/cordis.patch.yml +7 -0
- package/icon.svg +16 -0
- package/index.js +740 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +63 -4
package/index.js
ADDED
|
@@ -0,0 +1,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/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
|
+
}
|