dsh-remote-agent 0.0.0-stage → 0.4.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.
Files changed (70) hide show
  1. package/CHANGELOG.md +700 -0
  2. package/CONTRIBUTING.md +358 -0
  3. package/KNOWN-ISSUES.md +601 -0
  4. package/LICENSE +21 -0
  5. package/README.en.md +353 -0
  6. package/README.md +317 -2
  7. package/SECURITY.md +348 -0
  8. package/bin/dsh-remote-relay.js +257 -0
  9. package/bin/dsh-remote-setup.js +440 -0
  10. package/bin//345/217/214/345/207/273/350/277/220/350/241/214-/351/205/215/347/275/256/345/220/221/345/257/274.cmd +28 -0
  11. package/cordis.patch.yml +87 -0
  12. package/deploy/relay-vps/Caddyfile +24 -0
  13. package/deploy/relay-vps/README.md +132 -0
  14. package/deploy/relay-vps/dsh-remote-relay.service +47 -0
  15. package/deploy/relay-vps/nginx.conf +49 -0
  16. package/deploy/relay-vps/relay.env.example +20 -0
  17. package/docs/dispatch-automation-eval.md +140 -0
  18. package/docs/screenshots/panel-main.png +0 -0
  19. package/docs/screenshots/panel-task-detail.png +0 -0
  20. package/docs/verification-agent-e2e.md +425 -0
  21. package/docs/verification-repos-routing-real.md +521 -0
  22. package/docs/verification-resume-real.md +254 -0
  23. package/docs/worker-setup-pitfalls.md +266 -0
  24. package/lib/artifacts.js +451 -0
  25. package/lib/client.js +1752 -0
  26. package/lib/e2e.js +304 -0
  27. package/lib/glob.js +225 -0
  28. package/lib/hub/audit-log.js +161 -0
  29. package/lib/hub/hub-util.js +114 -0
  30. package/lib/hub/index.js +500 -0
  31. package/lib/hub/node-registry.js +943 -0
  32. package/lib/hub/pull-manager.js +781 -0
  33. package/lib/hub/registry-handshake.js +403 -0
  34. package/lib/hub/registry-ingest.js +346 -0
  35. package/lib/hub/relay-link.js +228 -0
  36. package/lib/hub/subagent-provider.js +424 -0
  37. package/lib/hub/templates.js +693 -0
  38. package/lib/hub/tools.js +1059 -0
  39. package/lib/hub/ui-routes.js +856 -0
  40. package/lib/hub/views.js +351 -0
  41. package/lib/identity.js +271 -0
  42. package/lib/index.js +272 -0
  43. package/lib/node/artifact-service.js +231 -0
  44. package/lib/node/diff.js +124 -0
  45. package/lib/node/exec.js +536 -0
  46. package/lib/node/hub-pin.js +71 -0
  47. package/lib/node/index.js +1022 -0
  48. package/lib/node/repos.js +134 -0
  49. package/lib/node/resource.js +63 -0
  50. package/lib/node/runner.js +792 -0
  51. package/lib/node/task-engine.js +712 -0
  52. package/lib/node/task-store.js +273 -0
  53. package/lib/node/transport.js +763 -0
  54. package/lib/pairing.js +186 -0
  55. package/lib/protocol.js +414 -0
  56. package/lib/relay-config.js +317 -0
  57. package/lib/relay.js +732 -0
  58. package/lib/setup-routes.js +313 -0
  59. package/lib/setup.js +522 -0
  60. package/lib/ws.js +466 -0
  61. package/package.json +103 -4
  62. package/profiles/README.md +573 -0
  63. package/profiles/hub.cordis.yml +84 -0
  64. package/profiles/worker.cordis.yml +60 -0
  65. package/scripts/check-doc-drift.mjs +785 -0
  66. package/scripts/check-packaging.mjs +130 -0
  67. package/scripts/diag-inject.mjs +243 -0
  68. package/scripts/e2e-live-check.mjs +181 -0
  69. package/scripts/relay-init.ps1 +286 -0
  70. package/scripts/relay-init.sh +199 -0
@@ -0,0 +1,536 @@
1
+ /**
2
+ * 命令执行后端。
3
+ *
4
+ * v0.1 目标平台是 Windows 副机,所以:
5
+ * - 默认 shell 是 PowerShell(pwsh 优先,退回 powershell.exe)
6
+ * - 用 `-NoProfile -NonInteractive -Command` 避免用户 profile 干扰与卡在交互提示
7
+ * - 退出码:`$LASTEXITCODE` 在 native 命令后才有意义,所以脚本尾部显式 `exit`
8
+ * - 编码:强制 UTF-8 输出,否则中文路径/输出在 cp936 下会乱码
9
+ * - 进程树:Windows 用 `taskkill /T /F`,POSIX 用进程组 kill
10
+ *
11
+ * posix 分支保留并同样可用(Linux/macOS 副机后续直接跑),不是占位代码。
12
+ */
13
+ import { spawn } from 'node:child_process'
14
+ import fs from 'node:fs'
15
+ import os from 'node:os'
16
+ import path from 'node:path'
17
+ import { RemoteAgentError, ERROR_CODE } from '../protocol.js'
18
+ import { isAbsolutePath, normalizePath } from '../glob.js'
19
+
20
+ export const PLATFORM = Object.freeze({ WINDOWS: 'windows', POSIX: 'posix' })
21
+
22
+ export function detectPlatform() {
23
+ return process.platform === 'win32' ? PLATFORM.WINDOWS : PLATFORM.POSIX
24
+ }
25
+
26
+ /**
27
+ * 在 PATH 里解析一个可执行文件名。
28
+ *
29
+ * 为什么必须自己做:早期版本对非绝对路径候选直接 `return c`("交给 PATH 解析"),
30
+ * 结果在一台只有 Windows PowerShell 5.1 的机器上返回了不存在的 'pwsh.exe',
31
+ * 每一条 exec 任务都以 ENOENT 失败。判断"这个可执行文件到底存不存在"
32
+ * 是这里唯一的职责,不能推给 spawn 事后暴露。
33
+ *
34
+ * "存在"必须按 spawn 的判据来算,不能只用 existsSync:
35
+ * Windows 的**应用执行别名**(App Execution Alias,如
36
+ * `%LOCALAPPDATA%\Microsoft\WindowsApps\pwsh.exe`)是一个 **0 字节**的
37
+ * 重解析点文件。existsSync 返回 true,但 spawn 打开它时抛
38
+ * `EFTYPE`(实测:0 字节 .exe → Error: spawn EFTYPE,errno -4028)。
39
+ * 于是 resolveOnPath 会"成功"解析出一个 spawn 用不了的文件 ——
40
+ * 正是它当初要消灭的那类失败,只是错误码从 ENOENT 变成了 EFTYPE。
41
+ * 真实的 PE 文件不可能 0 字节,所以在 Windows 上把 0 字节候选视为不存在。
42
+ * (别名是目录形式的占位,正确解析需要解析 reparse point;这里选择
43
+ * 继续往下找下一个候选 —— 与"不存在就回退"的语义一致。)
44
+ */
45
+ /**
46
+ * 一个候选路径是否**可执行**(存在 + 非 0 字节)。
47
+ *
48
+ * 为什么需要 0 字节守卫:Windows 上 App Execution Alias(`WindowsApps\*.exe`)
49
+ * 常见形态是 0 字节 reparse point —— `existsSync()` 说"有",但 spawn 打开时抛
50
+ * `EFTYPE`(errno -4028)。也就是说,光看"存在"会把一个必然失败的解释器当成可用的。
51
+ *
52
+ * 判据必须**单一来源**:这个函数被 `resolveOnPath` 与 `resolvePowerShell` 的
53
+ * 绝对路径分支共同调用。历史上后者只有 `existsSync`、没有 0 字节守卫,于是同一个
54
+ * 0 字节 pwsh.exe 在 PATH 分支被跳过、在绝对路径分支被采用,行为自相矛盾
55
+ * (describePowerShell 报 exists:true/family:'pwsh-7',spawn 却抛 EFTYPE)。
56
+ *
57
+ * 读不了(EACCES 等)一律视为不可用 —— 与"不存在就继续找下一个候选"同义。
58
+ */
59
+ export function isUsableExecutable(full) {
60
+ try {
61
+ if (!fs.existsSync(full)) return false
62
+ if (process.platform === 'win32' && fs.statSync(full).size === 0) return false
63
+ return true
64
+ } catch {
65
+ return false
66
+ }
67
+ }
68
+
69
+ export function resolveOnPath(name) {
70
+ if (typeof name !== 'string' || name === '') return ''
71
+ const isWindows = process.platform === 'win32'
72
+ const exts = isWindows
73
+ ? (process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)
74
+ : ['']
75
+ const dirs = (process.env.PATH ?? '').split(path.delimiter).filter(Boolean)
76
+ const hasExt = /\.[A-Za-z0-9]+$/.test(name)
77
+ const names = hasExt ? [name] : [name, ...exts.map((e) => name + e)]
78
+ for (const dir of dirs) {
79
+ for (const n of names) {
80
+ const full = path.join(dir, n)
81
+ if (isUsableExecutable(full)) return full
82
+ }
83
+ }
84
+ return ''
85
+ }
86
+
87
+ /**
88
+ * 找出可用的 PowerShell。
89
+ *
90
+ * 顺序:显式覆盖 → PowerShell 7 常见安装位置 → PATH 上的 pwsh →
91
+ * Windows PowerShell 5.1(几乎每台 Windows 都有,作为兜底)。
92
+ *
93
+ * 显式设置的 DSH_REMOTE_PWSH 一律原样采用(即使是错的)—— 用户明确指定了就用它,
94
+ * 失败了要给出清晰错误,而不是被静默换成别的 shell 掩盖掉配置问题。
95
+ */
96
+ export function resolvePowerShell() {
97
+ const explicit = process.env.DSH_REMOTE_PWSH
98
+ if (explicit && explicit.trim() !== '') return explicit.trim()
99
+
100
+ const programFiles = process.env.ProgramFiles ?? 'C:\\Program Files'
101
+ const programFilesX86 = process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)'
102
+ const localAppData = process.env.LOCALAPPDATA ?? ''
103
+
104
+ const ordered = [
105
+ path.join(programFiles, 'PowerShell', '7', 'pwsh.exe'),
106
+ path.join(programFilesX86, 'PowerShell', '7', 'pwsh.exe'),
107
+ localAppData ? path.join(localAppData, 'Microsoft', 'WindowsApps', 'pwsh.exe') : '',
108
+ 'pwsh.exe',
109
+ 'pwsh',
110
+ // 兜底:Windows PowerShell 5.1
111
+ 'powershell.exe',
112
+ 'powershell',
113
+ path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
114
+ ].filter(Boolean)
115
+
116
+ for (const c of ordered) {
117
+ if (isAbsolutePath(c)) {
118
+ // 必须用与 resolveOnPath 相同的判据(含 0 字节守卫),不能只 existsSync。
119
+ // 历史不一致:绝对安装位置分支只有 existsSync,而 PATH 分支有 0 字节守卫 ——
120
+ // 于是 WindowsApps 下的 0 字节 pwsh.exe(App Execution Alias 的常见形态)
121
+ // 会被这里采用,describePowerShell() 报 exists:true / family:'pwsh-7',
122
+ // 但真正 spawn 时抛 EFTYPE(errno -4028)。同一条规则在两处必须一致。
123
+ if (isUsableExecutable(c)) return c
124
+ continue
125
+ }
126
+ const hit = resolveOnPath(c)
127
+ if (hit) return hit
128
+ }
129
+ return 'powershell.exe'
130
+ }
131
+
132
+ /** 当前解析结果,供诊断/状态接口展示(不缓存,环境变了要能立刻反映)。 */
133
+ export function describePowerShell() {
134
+ const resolved = resolvePowerShell()
135
+ const isPwsh = /pwsh(\.exe)?$/i.test(resolved)
136
+ return {
137
+ resolved,
138
+ family: isPwsh ? 'pwsh-7' : 'windows-powershell-5.1',
139
+ fromEnv: Boolean(process.env.DSH_REMOTE_PWSH),
140
+ exists: isAbsolutePath(resolved) ? fs.existsSync(resolved) : Boolean(resolveOnPath(resolved)),
141
+ }
142
+ }
143
+
144
+ /**
145
+ * 把一段用户命令包成"退出码可靠 + 输出 UTF-8"的 PowerShell 脚本。
146
+ *
147
+ * 关键点:
148
+ * - `$ProgressPreference='SilentlyContinue'` 去掉进度条噪声
149
+ * - `[Console]::OutputEncoding` + `$OutputEncoding` 强制 UTF-8
150
+ * - 结尾把 `$LASTEXITCODE`(native)或 `$?`(cmdlet)折成 0/1 退出码
151
+ */
152
+ export function wrapPowerShell(command, { cwd } = {}) {
153
+ const lines = [
154
+ "$ErrorActionPreference = 'Continue'",
155
+ "$ProgressPreference = 'SilentlyContinue'",
156
+ 'try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {}',
157
+ 'try { $OutputEncoding = [System.Text.Encoding]::UTF8 } catch {}',
158
+ `if ('${escapePsSingle(cwd ?? '')}' -ne '' -and (Test-Path -LiteralPath '${escapePsSingle(cwd ?? '')}')) { Set-Location -LiteralPath '${escapePsSingle(cwd ?? '')}' }`,
159
+ // 用户命令不加 & {} 包装 —— $? 必须反映最后一条真实语句的状态。
160
+ // 早期版本写成 `& { <command> }`,块调用本身成功会让 $? 恒为 true,
161
+ // 于是 cmdlet 失败被静默折成 exit 0(实测 Get-Item 不存在的路径 → 退出码 0,
162
+ // 这会让所有失败的 exec 任务被上报成 completed)。
163
+ command,
164
+ // 判定顺序:只看最后一条语句的成败,与 shell 的 $? 语义一致。
165
+ // 先查 $LASTEXITCODE 是错的 —— 一条先前成功的 native 命令会留下 0,
166
+ // 把后续 cmdlet 的失败掩盖成成功。
167
+ '$__dsh_ok = $?',
168
+ 'if ($__dsh_ok) { exit 0 }',
169
+ 'if ($LASTEXITCODE -ne $null -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE }',
170
+ 'exit 1',
171
+ ]
172
+ return lines.join('\n')
173
+ }
174
+
175
+ function escapePsSingle(s) {
176
+ return String(s).replace(/'/g, "''")
177
+ }
178
+
179
+ /** POSIX 包装:保证 set -o pipefail 语义与退出码直传。 */
180
+ export function wrapPosix(command, { cwd } = {}) {
181
+ const cd = cwd ? `cd ${shellQuote(cwd)} || exit 127\n` : ''
182
+ return `${cd}set -o pipefail 2>/dev/null || true\n${command}\n__dsh_rc=$?\nexit $__dsh_rc\n`
183
+ }
184
+
185
+ export function shellQuote(s) {
186
+ return `'${String(s).replace(/'/g, `'\\''`)}'`
187
+ }
188
+
189
+ /**
190
+ * 决定最终 spawn 的 argv。
191
+ *
192
+ * Windows 侧调用形式经过 2×2 因子实测(PS 5.1),结论与直觉相反,必须按数据来:
193
+ *
194
+ * OutputEncoding 行 BOM 形式 结果
195
+ * ----------------- ---- --------------- --------------------------
196
+ * 无 无 -File "通过" —— 但这是假通过
197
+ * 无 有 -File 乱码
198
+ * 有 无 -File 乱码
199
+ * 有 有 -File ✓ 正确
200
+ * 有 n/a -EncodedCommand ✓ 正确(但 stderr 被包成 CLIXML)
201
+ *
202
+ * 两个反直觉点:
203
+ * 1. **BOM 是必需的。** PS 5.1 对无 BOM 的 .ps1 按 ANSI(GBK) 读,中文字面量当场乱码。
204
+ * 2. **"无编码行 + 无 BOM"会假通过** —— 按 GBK 读进来、又按 GBK 写出去,
205
+ * 字节绕一圈变回原样。这依赖控制台码页,换台机器或换个 locale 就崩,
206
+ * 是最危险的一种"能跑",绝不能依赖。
207
+ *
208
+ * 为什么不选 `-EncodedCommand`(它也正确):它会把子进程 stderr 整体包成
209
+ * `#< CLIXML` XML,错误信息变成不可读的 XML 噪声,副机 agent 无法据此判断失败原因。
210
+ * `-File` + BOM 的 stderr 是干净纯文本(实测 `Get-Item : 找不到路径"..."`)。
211
+ */
212
+ export function buildSpawn(command, { platform, cwd }) {
213
+ if (platform === PLATFORM.WINDOWS) {
214
+ const ps = resolvePowerShell()
215
+ const script = wrapPowerShell(command, { cwd })
216
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-exec-'))
217
+ const file = path.join(dir, 'run.ps1')
218
+ // 必须带 BOM:PS 5.1 靠它判定 UTF-8,否则按 GBK 读、中文字面量乱码
219
+ fs.writeFileSync(file, '\uFEFF' + script, 'utf8')
220
+ return {
221
+ file: ps,
222
+ args: ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', file],
223
+ cleanup: () => {
224
+ try {
225
+ fs.rmSync(dir, { recursive: true, force: true })
226
+ } catch {
227
+ // 临时目录清理失败不该影响任务结果
228
+ }
229
+ },
230
+ }
231
+ }
232
+ return {
233
+ file: process.env.SHELL || '/bin/sh',
234
+ args: ['-c', wrapPosix(command, { cwd })],
235
+ }
236
+ }
237
+
238
+ /** 校验工作区:必须在允许根内,且真实存在。 */
239
+ export function resolveWorkspace(requested, { roots, caseInsensitive, defaultDir }) {
240
+ const target = requested && requested !== '' ? requested : defaultDir
241
+ if (!target) {
242
+ throw new RemoteAgentError('no workspace given and no default configured', ERROR_CODE.WORKSPACE_DENIED)
243
+ }
244
+ if (!isAbsolutePath(target)) {
245
+ throw new RemoteAgentError(`workspace must be absolute: ${target}`, ERROR_CODE.WORKSPACE_DENIED)
246
+ }
247
+ let resolved
248
+ try {
249
+ resolved = fs.realpathSync.native ? fs.realpathSync.native(target) : fs.realpathSync(target)
250
+ } catch {
251
+ // 允许"尚不存在但父目录合法"的工作区:任务本身可能要创建它
252
+ const parent = path.dirname(target)
253
+ try {
254
+ const parentReal = fs.realpathSync.native ? fs.realpathSync.native(parent) : fs.realpathSync(parent)
255
+ resolved = path.join(parentReal, path.basename(target))
256
+ } catch {
257
+ throw new RemoteAgentError(`workspace not reachable: ${target}`, ERROR_CODE.WORKSPACE_DENIED)
258
+ }
259
+ }
260
+
261
+ /**
262
+ * 已存在但不是目录 → 绝不是合法工作区。
263
+ *
264
+ * 不拦的后果是**错误码错位**:task-engine.accept() 紧接着会执行
265
+ * `fs.mkdirSync(workspace, { recursive: true })`,而 mkdir 对已存在的普通文件
266
+ * 抛 EEXIST(recursive 只吞掉 EEXIST 的**目录**情形)—— 这个异常会穿过
267
+ * accept(),在 node/index.js 里被折成 ERROR_CODE.INTERNAL。
268
+ * 于是一个"workspace 参数写成了文件"的输入被上报成"副机内部错误",
269
+ * 调用方的排查方向完全跑偏,而正确答案本该是 workspace-denied。
270
+ *
271
+ * 放在 roots 校验之前:这是"输入根本不是目录"的事实判断,与白名单无关。
272
+ */
273
+ let st
274
+ try {
275
+ st = fs.statSync(resolved)
276
+ } catch {
277
+ // stat 失败(权限 / 竞态)不在这里判死,交给后续步骤报更具体的错
278
+ st = null
279
+ }
280
+ if (st && !st.isDirectory()) {
281
+ throw new RemoteAgentError(`workspace is not a directory: ${resolved}`, ERROR_CODE.WORKSPACE_DENIED)
282
+ }
283
+
284
+ // roots 与 target 必须走**同一套归一**:target 上面已经 realpath 过
285
+ // (展开 8.3 短名与符号链接),roots 不 realpath 的话两边形态不同 →
286
+ // 前缀比对假阳性拒绝。真实触发场景:GH Actions 的 Windows runner TEMP 是
287
+ // `C:\Users\RUNNER~1\AppData\Local\Temp`(8.3 短名),`os.tmpdir()` 派生的
288
+ // 默认 roots 保持短名,而任务里引用的子路径被 realpath 展开成长名 ——
289
+ // 明明在根内却被判 workspace-denied。用户配 8.3 形态或符号链接目录同理。
290
+ const allowed = (roots ?? []).map((r) => {
291
+ let base = r
292
+ try {
293
+ base = fs.realpathSync.native ? fs.realpathSync.native(r) : fs.realpathSync(r)
294
+ } catch {
295
+ // 根不存在 / 不可达:保持原样交给你 normalizePath ——
296
+ // 不存在的根后面照样拒绝一切子路径,不影响安全语义。
297
+ }
298
+ return normalizePath(base, { caseInsensitive })
299
+ })
300
+ if (allowed.length === 0) {
301
+ throw new RemoteAgentError('no allowed roots configured; refusing every workspace', ERROR_CODE.WORKSPACE_DENIED)
302
+ }
303
+ const norm = normalizePath(resolved, { caseInsensitive })
304
+ const ok = allowed.some((r) => norm === r || norm.startsWith(`${r}/`))
305
+ if (!ok) {
306
+ throw new RemoteAgentError(
307
+ `workspace outside allowed roots: ${resolved} (allowed: ${allowed.join(', ')})`,
308
+ ERROR_CODE.WORKSPACE_DENIED,
309
+ )
310
+ }
311
+ return resolved
312
+ }
313
+
314
+ /**
315
+ * 判断路径是否被 denyPaths 拦下。
316
+ *
317
+ * 两种写法都必须生效(与 artifacts.js 的 walk 同一条规则):
318
+ * - 绝对条目:直接与 absPath 比前缀
319
+ * - 相对条目:在 absPath 的**任意段边界**上做连续段匹配
320
+ *
321
+ * 为什么相对条目要单独处理:本函数的真实调用方(task-engine.snapshotWorkspace)
322
+ * 传进来的 absPath 是绝对路径,而 cfg.denyPaths / 任务 constraints.denyPaths 都是
323
+ * 任意字符串。相对条目与绝对路径永不相等 → 相对 denyPaths 被**静默忽略** ——
324
+ * 与 artifacts.js 修过的 D1 完全同类("有时管用"最危险)。方向取保守:
325
+ * 宁可多拒一条变更记录,也不能让被禁路径的内容照常上报给 hub。
326
+ */
327
+ export function isDenied(absPath, denyPaths, { caseInsensitive = false } = {}) {
328
+ const p = normalizePath(absPath, { caseInsensitive })
329
+ if (p === '') return false
330
+ for (const raw of denyPaths ?? []) {
331
+ // 非字符串 / 空串条目必须**显式跳过**,不能交给 normalizePath 兜。
332
+ // 历史缺陷:normalizePath('') / (null) / (42) 都返回 '',而空条目的比对是
333
+ // `p === '' || p.startsWith('/')` ——
334
+ // POSIX:归一化结果是 '/etc/passwd',startsWith('/') 恒真 → 一个空条目
335
+ // 把整张 deny 表变成"全部拒绝"(变更报告静默变空)
336
+ // Windows:归一化结果是 'c:/work/a',不以 '/' 开头 → 同一个空条目变成
337
+ // "什么都不拒"(禁路径静默失效)
338
+ // 同一个非法输入在两种平台上给出相反的极端行为,且两边都是静默的。
339
+ if (typeof raw !== 'string') continue
340
+ if (raw.trim() === '') continue
341
+ const nd = normalizePath(raw, { caseInsensitive })
342
+ // ⚠ 这一行(L3)是**行为不可观测**的纵深防御,不是可被测试证明的守卫。
343
+ //
344
+ // 穷举 928 组输入逐层移除的实测结论(captain + verifier 各自独立得出):
345
+ // L1 `typeof` 守卫 → 可观测(移除后 180 处行为差异)
346
+ // L2 `trim()` 守卫 → 可观测(移除后 6 处差异;`' '` 是唯一只有它能拦的形态,
347
+ // 因为 normalizePath **不做 trim**)
348
+ // L3 本行 → **不可观测**:所有能让 nd === '' 的输入,要么已被 L1 拦下,
349
+ // 要么会在紧接着的 `if (segs.length === 0) continue` 被拦。
350
+ //
351
+ // 所以:**任何测试都无法证明本行存在**(删掉它测试仍全绿)。保留它是为了在
352
+ // "normalizePath 将来改了行为"或"上面几层被调整"时仍有兜底。请勿以"测试全过"
353
+ // 当作它有效的证据 —— 也不要因为它删掉不掉测试而误判它是死代码就移除。
354
+ if (nd === '') continue
355
+
356
+ if (isAbsolutePath(raw)) {
357
+ // 根路径:deny '/' 就该拒掉一切,否则 '/etc/passwd' 因 '//' 前缀比不中而漏过
358
+ if (nd === '/') return true
359
+ if (p === nd || p.startsWith(`${nd}/`)) return true
360
+ continue
361
+ }
362
+
363
+ const segs = nd.split('/').filter(Boolean)
364
+ if (segs.length === 0) continue
365
+ const pSegs = p.split('/').filter(Boolean)
366
+ for (let start = 0; start + segs.length <= pSegs.length; start += 1) {
367
+ let same = true
368
+ for (let i = 0; i < segs.length; i += 1) {
369
+ if (pSegs[start + i] !== segs[i]) {
370
+ same = false
371
+ break
372
+ }
373
+ }
374
+ if (same) return true
375
+ }
376
+ }
377
+ return false
378
+ }
379
+
380
+ /**
381
+ * 跑一条命令,收集输出,返回结构化结果。
382
+ * 不做超时软处理:超时就是杀进程树,然后如实报 timedOut。
383
+ */
384
+ export function runCommand(command, {
385
+ platform = detectPlatform(),
386
+ cwd,
387
+ timeoutMs = 60 * 60 * 1000,
388
+ env = {},
389
+ signal,
390
+ onData,
391
+ maxOutputBytes = 4 * 1024 * 1024,
392
+ } = {}) {
393
+ const { file, args, cleanup } = buildSpawn(command, { platform, cwd })
394
+ const startedAt = Date.now()
395
+
396
+ return new Promise((resolve) => {
397
+ let child
398
+ try {
399
+ child = spawn(file, args, {
400
+ cwd: cwd && fs.existsSync(cwd) ? cwd : undefined,
401
+ env: { ...process.env, ...env },
402
+ windowsHide: true,
403
+ stdio: ['ignore', 'pipe', 'pipe'],
404
+ // POSIX 下独立进程组,便于整组 kill
405
+ detached: platform === PLATFORM.POSIX,
406
+ })
407
+ } catch (err) {
408
+ // spawn 失败也要清临时脚本目录,否则每次失败漏一个目录
409
+ try {
410
+ cleanup?.()
411
+ } catch {
412
+ /* 清理失败不掩盖原始错误 */
413
+ }
414
+ resolve({
415
+ ok: false,
416
+ exitCode: null,
417
+ timedOut: false,
418
+ aborted: false,
419
+ stdout: '',
420
+ stderr: String(err?.message ?? err),
421
+ durationMs: Date.now() - startedAt,
422
+ spawnError: true,
423
+ })
424
+ return
425
+ }
426
+
427
+ const out = []
428
+ const errOut = []
429
+ let outBytes = 0
430
+ let errBytes = 0
431
+ let truncated = false
432
+ let timedOut = false
433
+ let aborted = false
434
+ let settled = false
435
+
436
+ const capture = (buf, sink) => {
437
+ const s = buf.toString('utf8')
438
+ if (sink === out) {
439
+ outBytes += buf.length
440
+ if (outBytes <= maxOutputBytes) out.push(s)
441
+ else truncated = true
442
+ } else {
443
+ errBytes += buf.length
444
+ if (errBytes <= maxOutputBytes) errOut.push(s)
445
+ else truncated = true
446
+ }
447
+ if (typeof onData === 'function') onData(s, sink === out ? 'stdout' : 'stderr')
448
+ }
449
+
450
+ child.stdout?.on('data', (b) => capture(b, out))
451
+ child.stderr?.on('data', (b) => capture(b, errOut))
452
+
453
+ const killTree = () => {
454
+ try {
455
+ if (platform === PLATFORM.WINDOWS) {
456
+ // /T 杀整棵树,/F 强制。即使 child 已退出也无害。
457
+ spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
458
+ } else {
459
+ try {
460
+ process.kill(-child.pid, 'SIGKILL')
461
+ } catch {
462
+ child.kill('SIGKILL')
463
+ }
464
+ }
465
+ } catch {
466
+ try {
467
+ child.kill('SIGKILL')
468
+ } catch {
469
+ /* 已经退出 */
470
+ }
471
+ }
472
+ }
473
+
474
+ const timer = timeoutMs > 0
475
+ ? setTimeout(() => {
476
+ timedOut = true
477
+ killTree()
478
+ }, timeoutMs)
479
+ : undefined
480
+ if (timer?.unref) timer.unref()
481
+
482
+ const onAbort = () => {
483
+ aborted = true
484
+ killTree()
485
+ }
486
+ if (signal) {
487
+ if (signal.aborted) onAbort()
488
+ else signal.addEventListener('abort', onAbort, { once: true })
489
+ }
490
+
491
+ const finish = (code, signalName) => {
492
+ if (settled) return
493
+ settled = true
494
+ if (timer) clearTimeout(timer)
495
+ if (signal) signal.removeEventListener('abort', onAbort)
496
+ // Windows 临时脚本目录在这里回收:进程已 close,脚本不再被读
497
+ try {
498
+ cleanup?.()
499
+ } catch {
500
+ /* 清理失败不影响结果 */
501
+ }
502
+ resolve({
503
+ ok: code === 0 && !timedOut && !aborted,
504
+ exitCode: code,
505
+ signal: signalName,
506
+ timedOut,
507
+ aborted,
508
+ truncated,
509
+ stdout: out.join(''),
510
+ stderr: errOut.join(''),
511
+ durationMs: Date.now() - startedAt,
512
+ })
513
+ }
514
+
515
+ child.on('error', (err) => {
516
+ errOut.push(String(err?.message ?? err))
517
+ finish(null, null)
518
+ })
519
+ child.on('close', (code, signalName) => finish(code, signalName))
520
+ })
521
+ }
522
+
523
+ /** 默认工作区根:用户没配 roots 时给一个保守的默认(home 下的工作目录)。 */
524
+ export function defaultRoots() {
525
+ const home = os.homedir()
526
+ const candidates = [path.join(home, 'dsh-remote-work'), path.join(home, 'work')]
527
+ for (const c of candidates) {
528
+ try {
529
+ fs.mkdirSync(c, { recursive: true })
530
+ return [c]
531
+ } catch {
532
+ /* 试下一个 */
533
+ }
534
+ }
535
+ return [home]
536
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * 副机侧 hub 指纹钉住(TOFU)落盘(P2-11)。
3
+ *
4
+ * 首连验证通过后把 hub 指纹写进 `<stateDir>/hub-pin.json`(0600,原子写),
5
+ * 之后每次握手都比对这个值 —— 不匹配 = 有东西在冒充 hub,拒绝并大声报错。
6
+ *
7
+ * 文件同时记录 endpoint(当时拨入的 hubUrl/relayUrl 归一化结果):用户自己
8
+ * 改了拨入地址属于**本地配置行为**,远程攻击者改不了 —— 此时重新 TOFU 并
9
+ * 提示,而不是逼用户手删文件。这条便利性边界在 SECURITY.md 有明示。
10
+ *
11
+ * 全部函数永不抛:读不到/读坏了按"没有 pin"处理(下次连接重新 TOFU),
12
+ * 写失败返回 false(调用方记 warn)—— 落盘问题不是错误路径,验证逻辑才是。
13
+ */
14
+ import fs from 'node:fs'
15
+ import path from 'node:path'
16
+ import { HUB_PIN_FILE_NAME, normalizeFingerprint, restrictPermissions, writeJsonAtomic } from '../identity.js'
17
+
18
+ export const HUB_PIN_FILE_VERSION = 1
19
+
20
+ /**
21
+ * 读 pin。缺失 / 损坏 / 形态不对一律 null(下次连接走 TOFU)。
22
+ * @returns {{ fingerprint: string, endpoint: string, pinnedAt: number } | null}
23
+ */
24
+ export function loadHubPin(stateDir) {
25
+ if (typeof stateDir !== 'string' || stateDir === '') return null
26
+ const file = path.join(stateDir, HUB_PIN_FILE_NAME)
27
+ try {
28
+ if (!fs.existsSync(file)) return null
29
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
30
+ const fp = normalizeFingerprint(parsed?.fingerprint)
31
+ if (!fp) return null
32
+ restrictPermissions(file)
33
+ return {
34
+ fingerprint: fp,
35
+ endpoint: typeof parsed.endpoint === 'string' ? parsed.endpoint : '',
36
+ pinnedAt: typeof parsed.pinnedAt === 'number' ? parsed.pinnedAt : 0,
37
+ }
38
+ } catch {
39
+ return null
40
+ }
41
+ }
42
+
43
+ /**
44
+ * 写 pin(原子写 + 0600)。指纹形态不对 / 路径不可用返回 false。
45
+ * @returns {boolean}
46
+ */
47
+ export function saveHubPin(stateDir, { fingerprint, endpoint = '' } = {}) {
48
+ const fp = normalizeFingerprint(fingerprint)
49
+ if (!fp || typeof stateDir !== 'string' || stateDir === '') return false
50
+ try {
51
+ writeJsonAtomic(path.join(stateDir, HUB_PIN_FILE_NAME), {
52
+ version: HUB_PIN_FILE_VERSION,
53
+ fingerprint: fp,
54
+ endpoint,
55
+ pinnedAt: Date.now(),
56
+ })
57
+ return true
58
+ } catch {
59
+ return false
60
+ }
61
+ }
62
+
63
+ /** 清除 pin(显式重置 / 诊断用)。文件不存在同样算成功;清不掉就留着(方向安全)。 */
64
+ export function clearHubPin(stateDir) {
65
+ if (typeof stateDir !== 'string' || stateDir === '') return
66
+ try {
67
+ fs.rmSync(path.join(stateDir, HUB_PIN_FILE_NAME), { force: true })
68
+ } catch {
69
+ /* 清不掉就留着 —— 下次连接继续严格匹配 */
70
+ }
71
+ }