dsh-copilot-vision 1.3.3 → 1.5.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.
@@ -1,1328 +0,0 @@
1
- // ============================================================================
2
- // vp-ssh-core.js —— Vision-Pilot 远程执行层(独立维护的实现副本)
3
- // ----------------------------------------------------------------------------
4
- //
5
- // 为何是副本而不是 import:
6
- // 源实现的 package.json exports 只暴露 "." 与 "./package.json",子路径 import 会
7
- // ERR_PACKAGE_PATH_NOT_EXPORTED;跨目录 file-URL 导入又会让
8
- // createRequire(import.meta.url) 上溯到源目录解析 ssh2,那里没有 node_modules。
9
- // 因此本文件独立维护,所有修改只在本副本内进行。
10
- // ============================================================================
11
- //
12
- // 许可与归属(重要):
13
- // 本文件派生自 dsh-dolphin-security@0.3.1 的 dolphin-ssh-core.js
14
- // (MIT,Copyright (c) 2026 Dolphin Contributors),其上游为
15
- // dsh-web/packages/dsh-ssh(Apache License 2.0,Copyright (c) dsh-web contributors)。
16
- // → 许可证原文:THIRD_PARTY_LICENSES/
17
- // → 本项目对本文件所做修改的逐条说明:THIRD_PARTY_NOTICES.md「一、派生代码」
18
- // → Apache-2.0 覆盖的部分在再分发时仍受 Apache License 2.0 约束。
19
- //
20
- // 原始文件头要点:
21
- // ============================================================================
22
- // 远程巡检 SSH 核心
23
- // ----------------------------------------------------------------------------
24
- // 基于 ESM 独立封装
25
- // 适配:移除宿主专属上下文(cordis 等),以及仅面向 Web 界面的 client 与
26
- // pty / tunnel 模块
27
- // → 本文件零宿主依赖、零对外网络回连,运行时唯一三方依赖是 ssh2。
28
- //
29
- // 模块格式说明(重要):
30
- // 本包 package.json 声明了 "type": "module"。在 type:module 下,.js 文件无法使用
31
- // require / module.exports,强行写 CJS 会导致 node 直接抛 ReferenceError。
32
- // 因此本文件为 ESM,但对 CJS 生态的 ssh2 使用 createRequire 兼容加载:
33
- // import { createHostStore, createSshEngine } from './vp-ssh-core.js'
34
- //
35
- // 用法:
36
- // node src/vp-ssh-core.js 跑内置自检(不建立任何真实连接)
37
- // ============================================================================
38
-
39
- import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
40
- import { homedir } from 'node:os'
41
- import { dirname, join, isAbsolute, relative, resolve } from 'node:path'
42
- import { fileURLToPath } from 'node:url'
43
- import { createRequire } from 'node:module'
44
-
45
- const require = createRequire(import.meta.url)
46
-
47
- // ============================================================================
48
- // 0. ssh2 惰性解析
49
- // ----------------------------------------------------------------------------
50
- // ssh2 1.17 是 CJS 包。这里刻意做成惰性加载:模块导入、建库、列主机、校验
51
- // 等路径完全不触碰 ssh2,只有真正发起连接时才解析。这样在 ssh2 尚未安装的
52
- // 机器上,本文件依然能被正常 import 和自检。
53
- // ============================================================================
54
-
55
- let ssh2Module
56
-
57
- /** 解析 ssh2(失败时给出可执行的修复提示)。 */
58
- function loadSsh2() {
59
- if (ssh2Module !== undefined) return ssh2Module
60
- const override = process.env.DOLPHIN_SSH2_MODULE
61
- const candidates = override !== undefined && override !== '' ? [override, 'ssh2'] : ['ssh2']
62
- let lastError
63
- for (const spec of candidates) {
64
- try {
65
- ssh2Module = require(spec)
66
- return ssh2Module
67
- } catch (error) {
68
- lastError = error
69
- }
70
- }
71
- throw new Error(
72
- '缺少依赖 ssh2:npm install ssh2@1.17.0\n' +
73
- '若已装在别处,可用 DOLPHIN_SSH2_MODULE=<绝对路径或包名> 指定。\n' +
74
- '原始错误:' + (lastError instanceof Error ? lastError.message : String(lastError)),
75
- )
76
- }
77
-
78
- /** ssh2 是否可用(只读探测,不抛异常)。 */
79
- export function isSsh2Available() {
80
- try {
81
- loadSsh2()
82
- return true
83
- } catch {
84
- return false
85
- }
86
- }
87
-
88
- // ============================================================================
89
- // 1. protocol.ts —— 纯类型契约(运行时为空,仅保留 JSDoc)
90
- // ============================================================================
91
-
92
- /**
93
- * @typedef {'key'|'password'|'agent'} SshAuthKind
94
- *
95
- * @typedef {Object} SshHostEntry
96
- * @property {string} alias
97
- * @property {string} host
98
- * @property {number} port
99
- * @property {string} user
100
- * @property {{kind: SshAuthKind, keyPath?: string, passphrase?: string,
101
- * password?: string, agentPath?: string}} auth
102
- * @property {string[]} proxyJump
103
- * @property {string} [description]
104
- * @property {string} [environment]
105
- * @property {string[]} tags
106
- * @property {string} [location]
107
- * @property {number} createdAt
108
- * @property {number} updatedAt
109
- *
110
- * @typedef {Object} SshHostSummary // 脱敏投影,不含任何密钥
111
- * @typedef {Object} ExecResult
112
- * @property {boolean} success
113
- * @property {number|null} exitCode
114
- * @property {boolean} timedOut
115
- * @property {string} stdout
116
- * @property {string} stderr
117
- * @property {number} durationMs
118
- * @property {string} [error]
119
- *
120
- * @typedef {Object} ClusterResult
121
- * @typedef {Object} TestResult
122
- * @property {boolean} ok
123
- * @property {number} [latencyMs]
124
- * @property {string} [error]
125
- *
126
- * @typedef {Object} TransferProgress
127
- * @typedef {Object} RemoteDirEntry
128
- */
129
-
130
- // protocol.ts 中仅面向 HTTP 路由与 Web 界面的导出未纳入本模块:
131
- // SSH_API_BASE / SSH_API / TerminalServerFrame / TerminalClientFrame
132
- // TransferStreamLine / ApiErrorBody
133
-
134
- // ============================================================================
135
- // 2. home 解析 —— DSH_HOME 解析(内联实现,不依赖宿主包)
136
- // ----------------------------------------------------------------------------
137
- // 与宿主解耦后不再默认读写 ~/.dsh,改为优先 ~/.dolphin,避免和宿主插件抢目录。
138
- // resolveDolphinHome() 仅保留导出以维持 API 兼容,本副本的
139
- // storePath() 已改用 Vision-Pilot 自己的目录规则,不再调用它。
140
- // ============================================================================
141
-
142
- /**
143
- * 解析数据目录。
144
- * 优先级:$DOLPHIN_HOME > $DSH_HOME > ~/.dolphin
145
- */
146
- export function resolveDolphinHome(env = process.env, home = homedir()) {
147
- const raw = env.DOLPHIN_HOME ?? env.DSH_HOME
148
- if (raw !== undefined && raw.trim() !== '') {
149
- const expanded = expandHome(raw.trim(), home)
150
- return isAbsolute(expanded) ? expanded : join(process.cwd(), expanded)
151
- }
152
- return join(home, '.dolphin')
153
- }
154
-
155
- /** 展开路径前缀的 ~。 */
156
- export function expandHome(path, home = homedir()) {
157
- if (path === '~') return home
158
- if (path.startsWith('~/') || path.startsWith('~\\')) return join(home, path.slice(2))
159
- return path
160
- }
161
-
162
- // ============================================================================
163
- // 3. store.ts —— 主机配置存储(纯文件 I/O,无 cordis)
164
- // ----------------------------------------------------------------------------
165
- // 原子写:写 .tmp 再 rename;权限 0600(Windows 上 mode 基本被忽略,无害)。
166
- // 文件损坏时 rename 为 .corrupt-<ts> 并降级为空库,绝不静默覆盖。
167
- // ============================================================================
168
-
169
- const FORMAT_VERSION = 1
170
-
171
- /**
172
- * 默认存储文件位置。
173
- * 用 Vision-Pilot 专属文件名,不与宿主侧其他工具共享同一个主机库文件。
174
- * 理由:HostStore.load() 在文件不可解析时会静默 renameSync 成 .corrupt-<ts>
175
- * 并返回空库且不抛错,而 doAcquire() 每次建连都要走 store.find() → load();
176
- * 若共用同一文件,任一插件遇到一次坏文件就会把对方的主机列表改名挪走。
177
- * 优先级:$DSH_HOME/vision-pilot-ssh-hosts.json > ~/.vision-pilot/ssh-hosts.json
178
- * 注意:这里刻意不读 $DOLPHIN_HOME —— Vision-Pilot 不应隐式继承别的工具的数据目录选择。
179
- */
180
- export function storePath() {
181
- const dshHome = process.env.DSH_HOME
182
- if (dshHome !== undefined && dshHome.trim() !== '') {
183
- const expanded = expandHome(dshHome.trim())
184
- const base = isAbsolute(expanded) ? expanded : join(process.cwd(), expanded)
185
- return join(base, 'vision-pilot-ssh-hosts.json')
186
- }
187
- return join(homedir(), '.vision-pilot', 'ssh-hosts.json')
188
- }
189
-
190
- /** 标准 OpenSSH 配置路径(导入用)。 */
191
- export function sshConfigPath() {
192
- return join(homedir(), '.ssh', 'config')
193
- }
194
-
195
- /** 别名语法:字母数字开头,允许点、连字符、下划线。 */
196
- const ALIAS_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/
197
-
198
- /** 校验别名,返回错误信息或 undefined。 */
199
- export function validateAlias(alias) {
200
- if (!ALIAS_RE.test(alias)) return 'alias must be letters, digits, dots, hyphens or underscores'
201
- return undefined
202
- }
203
-
204
- /** 校验主机 payload,返回错误信息或 undefined。 */
205
- export function validateHostPayload(payload) {
206
- if (typeof payload !== 'object' || payload === null) return 'body must be a JSON object'
207
- const p = payload
208
- if (typeof p.host !== 'string' || p.host.trim() === '') return 'host is required'
209
- if (typeof p.user !== 'string' || p.user.trim() === '') return 'user is required'
210
- const auth = p.auth
211
- if (auth !== undefined) {
212
- if (typeof auth !== 'object' || auth === null) return 'auth must be an object'
213
- if (auth.kind !== 'key' && auth.kind !== 'password' && auth.kind !== 'agent') return 'auth.kind must be key, password or agent'
214
- if (auth.kind === 'key' && (typeof auth.keyPath !== 'string' || auth.keyPath.trim() === '')) {
215
- return 'auth.keyPath is required for key auth'
216
- }
217
- if (auth.kind === 'password' && auth.password !== undefined && typeof auth.password !== 'string') {
218
- return 'auth.password must be a string when provided'
219
- }
220
- if (auth.kind === 'agent' && auth.agentPath !== undefined && typeof auth.agentPath !== 'string') {
221
- return 'auth.agentPath must be a string when provided'
222
- }
223
- }
224
- if (p.port !== undefined && (typeof p.port !== 'number' || !Number.isInteger(p.port) || p.port < 1 || p.port > 65535)) {
225
- return 'port must be an integer in 1..65535'
226
- }
227
- if (p.proxyJump !== undefined && (!Array.isArray(p.proxyJump) || p.proxyJump.some(x => typeof x !== 'string' || x === ''))) {
228
- return 'proxyJump must be an array of alias strings'
229
- }
230
- if (p.tags !== undefined && (!Array.isArray(p.tags) || p.tags.some(x => typeof x !== 'string'))) {
231
- return 'tags must be an array of strings'
232
- }
233
- return undefined
234
- }
235
-
236
- /** 规范化 agent 端点:去掉空白、展开 ~、解析 SSH_AUTH_SOCK 记号。 */
237
- export function normalizeAgentPath(agentPath) {
238
- const trimmed = agentPath?.trim()
239
- if (trimmed === undefined || trimmed === '') return undefined
240
- if (trimmed === 'SSH_AUTH_SOCK' || trimmed === '$SSH_AUTH_SOCK') {
241
- const sock = process.env.SSH_AUTH_SOCK
242
- return sock !== undefined && sock !== '' ? sock : undefined
243
- }
244
- return expandHome(trimmed)
245
- }
246
-
247
- export class HostStore {
248
- /**
249
- * @param {string} [path] 存储文件路径(默认走 storePath():
250
- * $DSH_HOME/vision-pilot-ssh-hosts.json 或 ~/.vision-pilot/ssh-hosts.json)
251
- * @param {string} [sshConfigOverride] 仅测试用:覆盖 ~/.ssh/config 路径
252
- */
253
- constructor(path, sshConfigOverride) {
254
- this.path = resolve(path ?? storePath())
255
- this.sshConfigOverride = sshConfigOverride
256
- this.skippedNames = new Set()
257
- this.cache = undefined
258
- }
259
-
260
- list() {
261
- return this.load().hosts
262
- }
263
-
264
- find(alias) {
265
- return this.list().find(entry => entry.alias === alias)
266
- }
267
-
268
- /** 脱敏投影:永不外泄 password / passphrase / 私钥内容。 */
269
- summarize(entry) {
270
- let keyReady = true
271
- if (entry.auth.kind === 'key' && entry.auth.keyPath) {
272
- keyReady = existsSync(expandHome(entry.auth.keyPath))
273
- } else if (entry.auth.kind === 'agent') {
274
- keyReady = false
275
- }
276
- return {
277
- alias: entry.alias,
278
- host: entry.host,
279
- port: entry.port,
280
- user: entry.user,
281
- auth: entry.auth.kind,
282
- keyReady,
283
- proxyJump: [...entry.proxyJump],
284
- ...(entry.description !== undefined ? { description: entry.description } : {}),
285
- ...(entry.environment !== undefined ? { environment: entry.environment } : {}),
286
- tags: [...entry.tags],
287
- ...(entry.location !== undefined ? { location: entry.location } : {}),
288
- createdAt: entry.createdAt,
289
- updatedAt: entry.updatedAt,
290
- }
291
- }
292
-
293
- create(payload) {
294
- const alias = payload.alias?.trim()
295
- if (!alias) throw new Error('alias is required')
296
- const aliasError = validateAlias(alias)
297
- if (aliasError !== undefined) throw new Error(aliasError)
298
- const bodyError = validateHostPayload(payload)
299
- if (bodyError !== undefined) throw new Error(bodyError)
300
- if (payload.auth === undefined) throw new Error('auth is required')
301
- const file = this.load()
302
- if (file.hosts.some(entry => entry.alias === alias)) throw new Error(`alias '${alias}' already exists`)
303
- const now = Date.now()
304
- const entry = {
305
- alias,
306
- host: payload.host.trim(),
307
- port: payload.port ?? 22,
308
- user: payload.user.trim(),
309
- auth: {
310
- kind: payload.auth.kind,
311
- keyPath: payload.auth.kind === 'key' ? expandHome(payload.auth.keyPath?.trim() ?? '') : undefined,
312
- passphrase: payload.auth.kind === 'key' ? payload.auth.passphrase ?? undefined : undefined,
313
- password: payload.auth.kind === 'password' ? payload.auth.password : undefined,
314
- agentPath: payload.auth.kind === 'agent' ? normalizeAgentPath(payload.auth.agentPath) : undefined,
315
- },
316
- proxyJump: [...(payload.proxyJump ?? [])],
317
- description: payload.description?.trim() || undefined,
318
- environment: payload.environment?.trim() || undefined,
319
- tags: [...(payload.tags ?? [])].map(tag => tag.trim()).filter(tag => tag !== ''),
320
- location: payload.location?.trim() || undefined,
321
- createdAt: now,
322
- updatedAt: now,
323
- }
324
- file.hosts.push(entry)
325
- this.save(file)
326
- return entry
327
- }
328
-
329
- update(alias, patch) {
330
- const file = this.load()
331
- const entry = file.hosts.find(candidate => candidate.alias === alias)
332
- if (entry === undefined) throw new Error(`alias '${alias}' not found`)
333
- if (patch.host !== undefined && (typeof patch.host !== 'string' || patch.host.trim() === '')) {
334
- throw new Error('host is required')
335
- }
336
- if (patch.user !== undefined && (typeof patch.user !== 'string' || patch.user.trim() === '')) {
337
- throw new Error('user is required')
338
- }
339
- if (patch.port !== undefined && (typeof patch.port !== 'number' || !Number.isInteger(patch.port) || patch.port < 1 || patch.port > 65535)) {
340
- throw new Error('port must be an integer in 1..65535')
341
- }
342
- if (patch.proxyJump !== undefined && (!Array.isArray(patch.proxyJump) || patch.proxyJump.some(x => typeof x !== 'string' || x === ''))) {
343
- throw new Error('proxyJump must be an array of alias strings')
344
- }
345
- if (patch.tags !== undefined && (!Array.isArray(patch.tags) || patch.tags.some(x => typeof x !== 'string'))) {
346
- throw new Error('tags must be an array of strings')
347
- }
348
- if (patch.host !== undefined) entry.host = patch.host.trim()
349
- if (patch.port !== undefined) entry.port = patch.port
350
- if (patch.user !== undefined) entry.user = patch.user.trim()
351
- if (patch.auth !== undefined) {
352
- const auth = patch.auth
353
- if (auth.kind !== 'key' && auth.kind !== 'password' && auth.kind !== 'agent') throw new Error('auth.kind must be key, password or agent')
354
- if (auth.kind === 'key' && (typeof auth.keyPath !== 'string' || auth.keyPath.trim() === '')) {
355
- throw new Error('auth.keyPath is required for key auth')
356
- }
357
- if (auth.kind === 'password' && auth.password !== undefined && typeof auth.password !== 'string') {
358
- throw new Error('auth.password must be a string when provided')
359
- }
360
- if (auth.kind === 'agent' && auth.agentPath !== undefined && typeof auth.agentPath !== 'string') {
361
- throw new Error('auth.agentPath must be a string when provided')
362
- }
363
- // 换了密钥路径但没给 passphrase ⇒ 新密钥没有口令;只有路径不变时才沿用旧口令。
364
- const keyChanged = auth.kind === 'key'
365
- && auth.keyPath !== undefined
366
- && expandHome(auth.keyPath.trim()) !== entry.auth.keyPath
367
- entry.auth = {
368
- kind: auth.kind,
369
- keyPath: auth.kind === 'key' ? expandHome(auth.keyPath?.trim() ?? '') : undefined,
370
- passphrase: auth.kind === 'key'
371
- ? (auth.passphrase !== undefined ? auth.passphrase : (keyChanged ? undefined : entry.auth.passphrase))
372
- : undefined,
373
- password: auth.kind === 'password' ? auth.password : undefined,
374
- agentPath: auth.kind === 'agent'
375
- ? (auth.agentPath !== undefined ? normalizeAgentPath(auth.agentPath) : entry.auth.agentPath)
376
- : undefined,
377
- }
378
- }
379
- if (patch.proxyJump !== undefined) entry.proxyJump = [...patch.proxyJump]
380
- if (patch.description !== undefined) entry.description = patch.description.trim() || undefined
381
- if (patch.environment !== undefined) entry.environment = patch.environment.trim() || undefined
382
- if (patch.tags !== undefined) entry.tags = [...patch.tags].map(tag => tag.trim()).filter(tag => tag !== '')
383
- if (patch.location !== undefined) entry.location = patch.location.trim() || undefined
384
- entry.updatedAt = Date.now()
385
- this.save(file)
386
- return entry
387
- }
388
-
389
- delete(alias) {
390
- const file = this.load()
391
- const index = file.hosts.findIndex(candidate => candidate.alias === alias)
392
- if (index < 0) throw new Error(`alias '${alias}' not found`)
393
- file.hosts.splice(index, 1)
394
- this.save(file)
395
- }
396
-
397
- /** 从 ~/.ssh/config 导入(跳过通配符块、无 HostName 的块、已存在的别名)。 */
398
- importFromSshConfig() {
399
- this.skippedNames = new Set()
400
- const configPath = this.sshConfigOverride ?? sshConfigPath()
401
- if (!existsSync(configPath)) return { parsed: 0, added: 0, skipped: 0, skippedNames: [] }
402
- const lines = readFileSync(configPath, 'utf8').split(/\r?\n/)
403
- const blocks = []
404
- let current
405
- const skip = (name, seen) => {
406
- if (name !== '' && !seen.has(name)) {
407
- seen.add(name)
408
- this.skippedNames.add(name)
409
- }
410
- }
411
- for (const raw of lines) {
412
- const line = raw.trim()
413
- if (line === '' || line.startsWith('#')) continue
414
- const match = /^([A-Za-z0-9_\-]+)\s+(.+)$/.exec(line)
415
- if (match === null) continue
416
- const key = match[1].toLowerCase()
417
- const value = match[2].trim()
418
- if (key === 'host') {
419
- current = { pattern: value, props: {} }
420
- blocks.push(current)
421
- } else if (current !== undefined) {
422
- current.props[key] = value
423
- }
424
- }
425
- let added = 0
426
- for (const block of blocks) {
427
- const pattern = block.pattern.split(/\s+/)[0]
428
- if (pattern.includes('*') || pattern.includes('?')) {
429
- skip(pattern, this.skippedNames)
430
- continue
431
- }
432
- const hostName = block.props.hostname
433
- if (hostName === undefined || hostName === '') {
434
- skip(pattern, this.skippedNames)
435
- continue
436
- }
437
- if (this.list().some(entry => entry.alias === pattern)) {
438
- skip(pattern, this.skippedNames)
439
- continue
440
- }
441
- const payload = {
442
- alias: pattern,
443
- host: hostName,
444
- port: block.props.port !== undefined ? Number.parseInt(block.props.port, 10) : 22,
445
- user: block.props.user ?? process.env.USER ?? 'root',
446
- auth: {
447
- kind: block.props.identityfile !== undefined
448
- ? 'key'
449
- : block.props.identityagent !== undefined && block.props.identityagent.toLowerCase() !== 'none'
450
- ? 'agent'
451
- : 'password',
452
- keyPath: block.props.identityfile,
453
- password: block.props.password,
454
- agentPath: block.props.identityagent !== undefined && block.props.identityagent.toLowerCase() !== 'none'
455
- ? normalizeAgentPath(block.props.identityagent)
456
- : undefined,
457
- },
458
- proxyJump: block.props.proxyjump !== undefined
459
- ? block.props.proxyjump.split(',').map(hop => hop.trim()).filter(hop => hop !== '')
460
- : [],
461
- description: block.props.description,
462
- environment: block.props.environment,
463
- tags: (block.props.tags ?? '').split(',').map(tag => tag.trim()).filter(tag => tag !== ''),
464
- location: block.props.location,
465
- }
466
- try {
467
- this.create(payload)
468
- added += 1
469
- } catch {
470
- skip(pattern, this.skippedNames)
471
- }
472
- }
473
- return { parsed: blocks.length, added, skipped: this.skippedNames.size, skippedNames: [...this.skippedNames] }
474
- }
475
-
476
- /** 按 mtime+size 缓存:list/find 每次建连都会走,文件没变就别重复解析。 */
477
- load() {
478
- let stats
479
- try {
480
- stats = statSync(this.path)
481
- } catch {
482
- this.cache = undefined
483
- return { version: FORMAT_VERSION, hosts: [] }
484
- }
485
- if (this.cache !== undefined && this.cache.mtimeMs === stats.mtimeMs && this.cache.size === stats.size) {
486
- return this.cache.file
487
- }
488
- try {
489
- const parsed = JSON.parse(readFileSync(this.path, 'utf8'))
490
- if (typeof parsed !== 'object' || parsed === null || !Array.isArray(parsed.hosts)) {
491
- throw new Error('store file shape invalid')
492
- }
493
- this.cache = { mtimeMs: stats.mtimeMs, size: stats.size, file: parsed }
494
- return parsed
495
- } catch {
496
- // 损坏的库不能让插件变砖,也不能被下次 save 静默覆盖 —— 改名留档后从空库启动。
497
- this.cache = undefined
498
- try {
499
- renameSync(this.path, `${this.path}.corrupt-${Date.now()}`)
500
- } catch { /* best effort */ }
501
- return { version: FORMAT_VERSION, hosts: [] }
502
- }
503
- }
504
-
505
- save(file) {
506
- const dir = dirname(this.path)
507
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 })
508
- const tmp = this.path + '.tmp'
509
- writeFileSync(tmp, JSON.stringify(file, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })
510
- renameSync(tmp, this.path)
511
- this.cache = undefined
512
- }
513
- }
514
-
515
- /**
516
- * 工厂:实例化 HostStore。
517
- * @param {string} [path] 存储文件路径,省略则用本文件的 storePath()
518
- * (Vision-Pilot 专属主机库,不与宿主侧其他工具共享文件)
519
- * @returns {HostStore}
520
- */
521
- export function createHostStore(path) {
522
- return new HostStore(path)
523
- }
524
-
525
- // ============================================================================
526
- // 4. engine/connection-pool.ts —— 连接池、跳板链、exec
527
- // ============================================================================
528
-
529
- /**
530
- * 引擎默认旋钮。
531
- * 与上游故意分叉:用 Object.freeze() 冻结,防止模块级可变默认值被下游污染。
532
- * 上游此处是普通对象字面量。冻结安全性已读码确认:全文件无 DEFAULTS.xxx 赋值,
533
- * 使用点只有 buildConnectConfig 的默认参数、SshEngine 的 {...DEFAULTS, ...options}
534
- * 浅拷贝、以及自检里的只读传参 —— 均为读取,冻结后行为不变。
535
- */
536
- export const DEFAULTS = Object.freeze({
537
- idleTimeoutMs: 30 * 60_000,
538
- connectTimeoutMs: 15_000,
539
- keepaliveIntervalMs: 15_000,
540
- maxOutputBytes: 2 * 1024 * 1024,
541
- defaultExecTimeoutMs: 60_000,
542
- defaultMaxWorkers: 8,
543
- sftpConcurrency: 8,
544
- })
545
-
546
- /**
547
- * 为一条主机记录构造 ssh2 连接配置(私钥按内容读入,不是路径)。
548
- * @param {SshHostEntry} entry
549
- * @param {*} [sock] 跳板链传下来的 stream
550
- * @param {typeof DEFAULTS} opts
551
- */
552
- export function buildConnectConfig(entry, sock, opts = DEFAULTS) {
553
- const config = {
554
- host: entry.host,
555
- port: entry.port,
556
- username: entry.user,
557
- readyTimeout: opts.connectTimeoutMs,
558
- keepaliveInterval: opts.keepaliveIntervalMs,
559
- keepaliveCountMax: 3,
560
- tryKeyboard: true,
561
- }
562
- if (sock !== undefined) config.sock = sock
563
- if (entry.auth.kind === 'password') {
564
- config.password = entry.auth.password
565
- } else if (entry.auth.kind === 'agent') {
566
- const agentPath = resolveAgentPath(entry.auth.agentPath)
567
- if (agentPath === undefined) {
568
- throw new Error('ssh-agent is not available: set SSH_AUTH_SOCK or configure an agent path (use \'pageant\' for PuTTY Pageant on Windows)')
569
- }
570
- config.agent = agentPath
571
- } else {
572
- const keyPath = entry.auth.keyPath === undefined ? undefined : expandHome(entry.auth.keyPath)
573
- if (keyPath === undefined || !existsSync(keyPath)) {
574
- throw new Error('private key not found: ' + (entry.auth.keyPath ?? '(unset)'))
575
- }
576
- config.privateKey = readFileSync(keyPath, 'utf8')
577
- if (entry.auth.passphrase !== undefined && entry.auth.passphrase !== '') {
578
- config.passphrase = entry.auth.passphrase
579
- }
580
- }
581
- return config
582
- }
583
-
584
- /** 解析 agent 端点:显式路径 > $SSH_AUTH_SOCK > Windows 回退 pageant。 */
585
- export function resolveAgentPath(agentPath) {
586
- const explicit = normalizeAgentPath(agentPath)
587
- if (explicit !== undefined) return explicit
588
- const sock = process.env.SSH_AUTH_SOCK
589
- if (sock !== undefined && sock !== '') return sock
590
- if (process.platform === 'win32') return 'pageant'
591
- return undefined
592
- }
593
-
594
- /** 建一个 ssh2 client(ready 兑现,error/close 拒绝)。 */
595
- export function connectClient(config, onKeyboardInteractive) {
596
- const { Client } = loadSsh2()
597
- return new Promise((resolvePromise, reject) => {
598
- const client = new Client()
599
- let settled = false
600
- const fail = (error) => {
601
- if (settled) return
602
- settled = true
603
- try { client.destroy() } catch { /* already closed */ }
604
- reject(error instanceof Error ? error : new Error(String(error)))
605
- }
606
- client.once('ready', () => {
607
- if (settled) return
608
- settled = true
609
- resolvePromise(client)
610
- })
611
- client.on('keyboard-interactive', (name, instructions, instructionsLang, prompts, finish) => {
612
- if (onKeyboardInteractive !== undefined) {
613
- onKeyboardInteractive(name, instructions, instructionsLang, prompts.map(p => ({ prompt: p.prompt, echo: Boolean(p.echo) })), finish)
614
- return
615
- }
616
- // 已配置 password 且所有提示都在问密码 ⇒ 自动应答(PAM 兜底)
617
- if (config.password !== undefined && prompts.length > 0 && prompts.every(p => /password/i.test(p.prompt))) {
618
- finish(prompts.map(() => config.password))
619
- return
620
- }
621
- fail(new Error('Authentication failed (keyboard-interactive): ' + (prompts.map(p => p.prompt.trim()).join(', ') || 'unsupported interactive challenge')))
622
- })
623
- // 握手后仍保留 error 监听:TCP 通但握手断时 ssh2 会二次 emit error,
624
- // 没有兜底监听就会变成 unhandled 'error'。settled 守卫让后续 emit 变空操作。
625
- client.on('error', fail)
626
- try {
627
- client.connect(config)
628
- } catch (error) {
629
- fail(error)
630
- }
631
- })
632
- }
633
-
634
- /** 按字节预算截断输出(标记 truncated,且不切断代理对)。 */
635
- export function appendOutput(target, chunk, maxBytes) {
636
- if (target.truncated) return
637
- if (target.text.length + chunk.length > maxBytes) {
638
- let cut = chunk.toString('utf8').slice(0, maxBytes - target.text.length)
639
- if (/[\uD800-\uDBFF]$/.test(cut)) cut = cut.slice(0, -1)
640
- target.text += cut + '…[output truncated]'
641
- target.truncated = true
642
- return
643
- }
644
- target.text += chunk.toString('utf8')
645
- }
646
-
647
- /**
648
- * 建立完整跳板链:逐跳 forwardOut,末跳连目标。
649
- * 任一环节失败都会 end 掉已建立的跳,绝不泄漏中间连接。
650
- */
651
- export async function connectChain(engine, entry, onKeyboardInteractive) {
652
- const hops = []
653
- let sock
654
- const chain = entry.proxyJump
655
- try {
656
- for (let index = 0; index < chain.length; index += 1) {
657
- const hopAlias = chain[index]
658
- const hop = engine.store.find(hopAlias)
659
- if (hop === undefined) {
660
- throw new Error('proxyJump alias \'' + hopAlias + '\' not found — create it first')
661
- }
662
- const hopClient = await connectClient(buildConnectConfig(hop, sock, engine.opts), onKeyboardInteractive)
663
- hops.push(hopClient)
664
- const next = index + 1 < chain.length ? engine.store.find(chain[index + 1]) : undefined
665
- const nextHost = next !== undefined ? next.host : entry.host
666
- const nextPort = next !== undefined ? next.port : entry.port
667
- sock = await new Promise((resolvePromise, reject) => {
668
- hopClient.forwardOut('127.0.0.1', 0, nextHost, nextPort, (error, stream) => {
669
- if (error !== undefined) reject(error)
670
- else resolvePromise(stream)
671
- })
672
- })
673
- }
674
- } catch (error) {
675
- for (const client of hops) client.end()
676
- throw error
677
- }
678
- let target
679
- try {
680
- target = await connectClient(buildConnectConfig(entry, sock, engine.opts), onKeyboardInteractive)
681
- return { client: target, hops }
682
- } catch (error) {
683
- for (const client of hops) client.end()
684
- if (target !== undefined) {
685
- try { target.destroy() } catch { /* already destroyed */ }
686
- }
687
- throw error
688
- }
689
- }
690
-
691
- /** 取(或建)某别名的池化连接;同名并发只建一次。 */
692
- export async function acquire(engine, alias) {
693
- const pending = engine.acquireQueue.get(alias)
694
- if (pending !== undefined) return pending
695
- const task = doAcquire(engine, alias)
696
- engine.acquireQueue.set(alias, task)
697
- try {
698
- return await task
699
- } finally {
700
- if (engine.acquireQueue.get(alias) === task) engine.acquireQueue.delete(alias)
701
- }
702
- }
703
-
704
- async function doAcquire(engine, alias) {
705
- const entry = engine.store.find(alias)
706
- if (entry === undefined) throw new Error('alias \'' + alias + '\' not found — add it first')
707
- const { client, hops } = await connectChain(engine, entry)
708
- const record = { client, hops, idleAt: Date.now(), pinned: false, broken: false, inFlight: 0 }
709
- client.on('error', () => { record.broken = true })
710
- client.on('close', () => { record.broken = true })
711
- engine.pool.set(alias, record)
712
- return record
713
- }
714
-
715
- /** 拆掉某别名的连接;并发重建后旧记录不再属于调用者时不动。 */
716
- export function disposeRecord(engine, alias, record) {
717
- const current = engine.pool.get(alias)
718
- if (record !== undefined && current !== record) return
719
- if (current === undefined) return
720
- engine.pool.delete(alias)
721
- endRecordChain(current)
722
- }
723
-
724
- export function endRecordChain(record) {
725
- try { record.client.end() } catch { /* already closed */ }
726
- for (const hop of record.hops) {
727
- try { hop.end() } catch { /* already closed */ }
728
- }
729
- }
730
-
731
- /** 清扫空闲连接(跳过 pinned 与在途操作)。 */
732
- export function sweepPool(engine) {
733
- const cutoff = Date.now() - engine.opts.idleTimeoutMs
734
- for (const [alias, record] of engine.pool) {
735
- if (!record.pinned && record.inFlight === 0 && record.idleAt < cutoff) {
736
- disposeRecord(engine, alias, record)
737
- }
738
- }
739
- }
740
-
741
- /**
742
- * 带重连的操作包裹器。
743
- * 只有连接真的断了才重放 —— 健康连接上的失败是逻辑错误,直接抛出不重放。
744
- * ⚠️ 重连重放会重复执行非幂等命令;跑部署类命令请传 attempts = 1。
745
- */
746
- export async function withClient(engine, alias, fn, attempts = 3) {
747
- let lastError
748
- for (let attempt = 1; attempt <= attempts; attempt += 1) {
749
- let record = engine.pool.get(alias)
750
- if (record === undefined || record.broken) {
751
- if (record !== undefined) disposeRecord(engine, alias, record)
752
- record = await acquire(engine, alias)
753
- }
754
- record.idleAt = Date.now()
755
- record.inFlight += 1
756
- try {
757
- const result = await fn(record.client)
758
- record.idleAt = Date.now()
759
- return result
760
- } catch (error) {
761
- lastError = error
762
- if (!record.broken) throw error
763
- disposeRecord(engine, alias, record)
764
- } finally {
765
- record.inFlight -= 1
766
- }
767
- }
768
- throw lastError instanceof Error ? lastError : new Error(String(lastError))
769
- }
770
-
771
- /** 在 alias 上执行一条命令(复用池化连接)。 */
772
- export async function execCommand(engine, alias, command, timeoutMs, attempts) {
773
- const started = Date.now()
774
- const budget = timeoutMs !== undefined && timeoutMs > 0 ? timeoutMs : engine.opts.defaultExecTimeoutMs
775
- return withClient(engine, alias, async (client) => {
776
- return await new Promise((resolvePromise, reject) => {
777
- client.exec(command, (error, stream) => {
778
- if (error !== undefined) {
779
- reject(error)
780
- return
781
- }
782
- const stdout = { text: '', truncated: false }
783
- const stderr = { text: '', truncated: false }
784
- let timedOut = false
785
- let settled = false
786
- const finish = () => {
787
- if (settled) return
788
- settled = true
789
- clearTimeout(timer)
790
- resolvePromise({
791
- success: false,
792
- exitCode: null,
793
- timedOut,
794
- stdout: stdout.text,
795
- stderr: stderr.text,
796
- durationMs: Date.now() - started,
797
- error: timedOut ? 'command timed out after ' + budget + ' ms' : undefined,
798
- })
799
- }
800
- const timer = setTimeout(() => {
801
- timedOut = true
802
- try { stream.signal('KILL') } catch { /* channel gone */ }
803
- try { stream.close() } catch { /* channel gone */ }
804
- // 硬截止:对端不 ack 也立刻结算,后续 stream 'close' 变空操作。
805
- finish()
806
- }, budget)
807
- stream.on('data', (chunk) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes))
808
- stream.stderr.on('data', (chunk) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes))
809
- stream.on('close', (code) => {
810
- if (settled) return
811
- settled = true
812
- clearTimeout(timer)
813
- if (typeof code !== 'number' && !timedOut) {
814
- // 通道没有退出码就关闭 = 连接中途掉了;抛错让 withClient 重连重试。
815
- reject(new Error('ssh: connection lost mid-flight (channel closed without an exit status)'))
816
- return
817
- }
818
- resolvePromise({
819
- success: code === 0,
820
- exitCode: code,
821
- timedOut,
822
- stdout: stdout.text,
823
- stderr: stderr.text,
824
- durationMs: Date.now() - started,
825
- })
826
- })
827
- stream.on('error', (streamError) => {
828
- if (settled) return
829
- settled = true
830
- clearTimeout(timer)
831
- reject(streamError)
832
- })
833
- })
834
- })
835
- }, attempts ?? 3)
836
- }
837
-
838
- // ============================================================================
839
- // 4.1 提权护栏
840
- // ----------------------------------------------------------------------------
841
- // assertNoPrivilegeEscalation 原本属于上层的巡逻逻辑,SSH 核心本身不含此函数;
842
- // 本副本把判定函数一并移植进来,因为 Vision-Pilot 的远程层同样
843
- // 不允许任何提权命令下发。注意:本副本不把它自动挂进 execCommand —— 是否对所有
844
- // 远程命令强制前置校验,由上层调用方决定,避免误伤命令文本里恰好含关键字的场景。
845
- // ============================================================================
846
-
847
- // 硬闸门:任何含提权/系统污染语义的命令一律拦截。
848
- export function assertNoPrivilegeEscalation(command) {
849
- const s = String(command)
850
- if (/\bsudo\b/.test(s)) {
851
- throw new Error(`安全红线:检测到 sudo,已阻止下发 —— ${s.slice(0, 120)}`)
852
- }
853
- if (s.includes('--break-system-packages')) {
854
- throw new Error(`安全红线:检测到 --break-system-packages,已阻止下发 —— ${s.slice(0, 120)}`)
855
- }
856
- return true
857
- }
858
- // Vision-Pilot 远程层不需要提权,此闸门作为额外护栏保留。
859
-
860
- // ============================================================================
861
- // 5. engine/sftp.ts —— 上传 / 下载 / 列目录
862
- // ============================================================================
863
-
864
- /** 遍历本地目录,返回所有文件的相对路径(不跟随符号链接)。 */
865
- export function walkLocalDir(root) {
866
- const files = []
867
- const visit = (dir) => {
868
- for (const name of readdirSync(dir)) {
869
- const full = join(dir, name)
870
- // 用 lstat 而非 stat:符号链接绝不能跟随(ln -s . self 会无限递归)。
871
- const stat = lstatSync(full)
872
- if (stat.isSymbolicLink()) continue
873
- if (stat.isDirectory()) visit(full)
874
- else if (stat.isFile()) files.push(relative(root, full).replaceAll('\\', '/'))
875
- }
876
- }
877
- visit(root)
878
- return files
879
- }
880
-
881
- export async function upload(engine, alias, localPath, remotePath, recursive, onProgress) {
882
- if (!remotePath.startsWith('/')) {
883
- throw new Error('remotePath must be an absolute path (got \'' + remotePath + '\')')
884
- }
885
- const local = resolve(localPath)
886
- if (!existsSync(local)) throw new Error('local path not found: \'' + localPath + '\'')
887
- return withClient(engine, alias, (client) => withSftp(client, async (sftp) => {
888
- const stat = statSync(local)
889
- let files
890
- if (stat.isDirectory()) {
891
- if (!recursive) throw new Error('\'' + localPath + '\' is a directory — enable recursive upload')
892
- files = walkLocalDir(local)
893
- await ensureRemoteDir(sftp, remotePath)
894
- } else {
895
- files = ['']
896
- await ensureRemoteDir(sftp, dirname(remotePath))
897
- }
898
- let bytes = 0
899
- for (const rel of files) {
900
- const src = rel === '' ? local : join(local, rel)
901
- const remoteRel = rel.split(/[\\/]/).join('/')
902
- const dst = rel === '' ? remotePath : remotePath.replace(/\/$/, '') + '/' + remoteRel
903
- await fastTransfer(sftp, 'put', src, dst, engine.opts.sftpConcurrency, onProgress)
904
- bytes += statSync(src).size
905
- }
906
- return { bytes, files: files.length }
907
- }))
908
- }
909
-
910
- export async function download(engine, alias, remotePath, localPath, onProgress) {
911
- return withClient(engine, alias, (client) => withSftp(client, async (sftp) => {
912
- const stat = await new Promise((resolvePromise, reject) => {
913
- sftp.stat(remotePath, (error, stats) => error !== undefined ? reject(error) : resolvePromise(stats))
914
- })
915
- if (stat.isDirectory()) {
916
- throw new Error('\'' + remotePath + '\' is a directory — directory download is not supported yet (download individual files)')
917
- }
918
- const local = resolve(localPath)
919
- if (!existsSync(dirname(local))) mkdirSync(dirname(local), { recursive: true })
920
- await fastTransfer(sftp, 'get', remotePath, local, engine.opts.sftpConcurrency, onProgress)
921
- return { bytes: statSync(local).size }
922
- }))
923
- }
924
-
925
- export async function ls(engine, alias, path) {
926
- return withClient(engine, alias, (client) => withSftp(client, async (sftp) => {
927
- return await new Promise((resolvePromise, reject) => {
928
- sftp.readdir(path, (error, list) => {
929
- if (error !== undefined) {
930
- reject(error)
931
- return
932
- }
933
- resolvePromise(list.map(item => ({
934
- name: item.filename,
935
- type: item.attrs.isDirectory() ? 'dir' : item.attrs.isFile() ? 'file' : 'other',
936
- size: item.attrs.size,
937
- mtimeMs: item.attrs.mtime * 1000,
938
- mode: item.attrs.mode,
939
- })))
940
- })
941
- })
942
- }))
943
- }
944
-
945
- /**
946
- * 开一个 SFTP 通道并在结算时精确释放一次。
947
- * ssh2 的 subsystem channel 不 end() 就会一直占着,直到 sshd 的
948
- * MaxSessions 打满、之后所有 open 全失败。
949
- */
950
- async function withSftp(client, run) {
951
- const sftp = await sftpChannel(client)
952
- let ended = false
953
- const endOnce = () => {
954
- if (ended) return
955
- ended = true
956
- try { sftp.end() } catch { /* channel already closed */ }
957
- }
958
- sftp.once('close', endOnce)
959
- try {
960
- return await run(sftp)
961
- } finally {
962
- endOnce()
963
- }
964
- }
965
-
966
- function sftpChannel(client) {
967
- return new Promise((resolvePromise, reject) => {
968
- client.sftp((error, sftp) => error !== undefined ? reject(error) : resolvePromise(sftp))
969
- })
970
- }
971
-
972
- /** 逐段 stat→mkdir 建远端目录链。 */
973
- function ensureRemoteDir(sftp, remote) {
974
- return new Promise((resolvePromise, reject) => {
975
- const segments = remote.replace(/^\/+/, '').split('/').filter(segment => segment !== '')
976
- const walk = (index) => {
977
- if (index >= segments.length) {
978
- resolvePromise()
979
- return
980
- }
981
- const current = '/' + segments.slice(0, index + 1).join('/')
982
- sftp.stat(current, (statError) => {
983
- if (statError === undefined) {
984
- walk(index + 1)
985
- return
986
- }
987
- sftp.mkdir(current, (mkdirError) => {
988
- if (mkdirError !== undefined) {
989
- reject(mkdirError)
990
- return
991
- }
992
- walk(index + 1)
993
- })
994
- })
995
- }
996
- walk(0)
997
- })
998
- }
999
-
1000
- function fastTransfer(sftp, kind, src, dst, concurrency, onProgress) {
1001
- return new Promise((resolvePromise, reject) => {
1002
- const file = kind === 'put' ? dst : src
1003
- const finalSize = () => statSync(kind === 'put' ? src : dst).size
1004
- let last = 0
1005
- let lastEmit = 0
1006
- const started = Date.now()
1007
- if (kind === 'put') {
1008
- onProgress?.({ phase: 'transferring', file, transferred: 0, total: statSync(src).size, percent: 0 })
1009
- }
1010
- const step = (transferred, _chunk, total) => {
1011
- const now = Date.now()
1012
- // 节流:高速链路每个 chunk 回调一次,UI 只需要 ~10 帧/秒。
1013
- if (now - lastEmit < 100 && transferred < total) return
1014
- lastEmit = now
1015
- const elapsed = (now - started) / 1000
1016
- onProgress?.({
1017
- phase: 'transferring',
1018
- file,
1019
- transferred,
1020
- total,
1021
- percent: total > 0 ? Math.round((transferred / total) * 1000) / 10 : 0,
1022
- speedBps: elapsed > 0 ? Math.round((transferred - last) / elapsed) : undefined,
1023
- })
1024
- last = transferred
1025
- }
1026
- const done = (error) => {
1027
- if (error !== undefined) {
1028
- onProgress?.({ phase: 'error', file, transferred: 0, total: 0, percent: 0, error: String(error) })
1029
- reject(error)
1030
- } else {
1031
- onProgress?.({ phase: 'done', file, transferred: finalSize(), total: finalSize(), percent: 100 })
1032
- resolvePromise()
1033
- }
1034
- }
1035
- if (kind === 'put') sftp.fastPut(src, dst, { concurrency, step }, done)
1036
- else sftp.fastGet(src, dst, { concurrency, step }, done)
1037
- })
1038
- }
1039
-
1040
- // ============================================================================
1041
- // 6. engine/cluster.ts —— 批量并发执行
1042
- // ============================================================================
1043
-
1044
- /**
1045
- * 在多台主机上并发执行同一条命令。
1046
- * 过滤条件取交集:aliases / environment / tags(tags 为 ALL 语义)。
1047
- */
1048
- export async function cluster(engine, options) {
1049
- let targets = engine.store.list()
1050
- if (options.aliases !== undefined && options.aliases.length > 0) {
1051
- targets = targets.filter(entry => options.aliases.includes(entry.alias))
1052
- }
1053
- if (options.environment !== undefined && options.environment !== '') {
1054
- targets = targets.filter(entry => entry.environment === options.environment)
1055
- }
1056
- if (options.tags !== undefined && options.tags.length > 0) {
1057
- targets = targets.filter(entry => options.tags.every(tag => entry.tags.includes(tag)))
1058
- }
1059
- if (targets.length === 0) return []
1060
- if (options.maxWorkers !== undefined && (!Number.isInteger(options.maxWorkers) || options.maxWorkers < 1)) {
1061
- throw new Error('maxWorkers must be a positive integer')
1062
- }
1063
- const workers = Math.min(engine.opts.defaultMaxWorkers, options.maxWorkers ?? engine.opts.defaultMaxWorkers, targets.length)
1064
- const results = []
1065
- const queue = [...targets]
1066
- const run = async () => {
1067
- while (queue.length > 0) {
1068
- const entry = queue.shift()
1069
- try {
1070
- const result = await execCommand(engine, entry.alias, options.command, options.timeoutMs)
1071
- results.push({
1072
- alias: entry.alias,
1073
- ok: result.success,
1074
- exitCode: result.exitCode,
1075
- timedOut: result.timedOut,
1076
- stdout: result.stdout,
1077
- stderr: result.stderr,
1078
- durationMs: result.durationMs,
1079
- })
1080
- } catch (error) {
1081
- results.push({ alias: entry.alias, ok: false, error: error instanceof Error ? error.message : String(error) })
1082
- }
1083
- }
1084
- }
1085
- await Promise.all(Array.from({ length: workers }, () => run()))
1086
- return results
1087
- }
1088
-
1089
- // ============================================================================
1090
- // 7. engine.ts —— SshEngine 门面
1091
- // ----------------------------------------------------------------------------
1092
- // 已从原门面移除:openShell(依赖 engine/pty.ts + @xterm 浏览器半区)、
1093
- // startTunnel / listTunnels / stopTunnel / stopAllTunnels(依赖 engine/tunnel.ts)、
1094
- // tunnels 字段与 nextTunnelId。dropAlias 退化为纯连接回收。
1095
- // ============================================================================
1096
-
1097
- export class SshEngine {
1098
- constructor(store, options) {
1099
- this.store = store
1100
- this.opts = { ...DEFAULTS, ...options }
1101
- this.pool = new Map()
1102
- this.acquireQueue = new Map()
1103
- this.sweepTimer = setInterval(() => sweepPool(this), Math.max(10_000, this.opts.idleTimeoutMs / 4))
1104
- this.sweepTimer.unref?.()
1105
- }
1106
-
1107
- /** 脱敏主机列表(可按 alias/description/host/tags 模糊过滤)。 */
1108
- list(query) {
1109
- const needle = query?.trim().toLowerCase()
1110
- return this.store.list()
1111
- .filter(entry => needle === undefined || needle === ''
1112
- || entry.alias.toLowerCase().includes(needle)
1113
- || (entry.description ?? '').toLowerCase().includes(needle)
1114
- || entry.host.toLowerCase().includes(needle)
1115
- || entry.tags.some(tag => tag.toLowerCase().includes(needle)))
1116
- .map(entry => this.store.summarize(entry))
1117
- }
1118
-
1119
- find(alias) {
1120
- const entry = this.store.find(alias)
1121
- return entry === undefined ? undefined : this.store.summarize(entry)
1122
- }
1123
-
1124
- /**
1125
- * 在 alias 上执行一条命令。
1126
- * @param {string} alias
1127
- * @param {string} command
1128
- * @param {number} [timeoutMs]
1129
- * @param {number} [attempts] 断线重连次数;跑非幂等命令请传 1(默认 3)
1130
- */
1131
- async exec(alias, command, timeoutMs, attempts) {
1132
- return execCommand(this, alias, command, timeoutMs, attempts)
1133
- }
1134
-
1135
- /** 批量并发执行。 */
1136
- async cluster(options) {
1137
- return cluster(this, options)
1138
- }
1139
-
1140
- /** 连通性探测(执行 echo ok)。 */
1141
- async test(alias) {
1142
- const started = Date.now()
1143
- try {
1144
- const result = await this.exec(alias, 'echo ok', 10_000)
1145
- return result.success
1146
- ? { ok: true, latencyMs: result.durationMs }
1147
- : { ok: false, latencyMs: result.durationMs, error: 'remote exit code ' + result.exitCode }
1148
- } catch (error) {
1149
- return { ok: false, latencyMs: Date.now() - started, error: error instanceof Error ? error.message : String(error) }
1150
- }
1151
- }
1152
-
1153
- async upload(alias, localPath, remotePath, recursive, onProgress) {
1154
- return upload(this, alias, localPath, remotePath, recursive, onProgress)
1155
- }
1156
-
1157
- async download(alias, remotePath, localPath, onProgress) {
1158
- return download(this, alias, remotePath, localPath, onProgress)
1159
- }
1160
-
1161
- async ls(alias, path) {
1162
- return ls(this, alias, path)
1163
- }
1164
-
1165
- /** 丢弃该别名上的全部活动产物(现在只有连接),下次操作按当前配置重连。 */
1166
- dropAlias(alias) {
1167
- disposeRecord(this, alias)
1168
- }
1169
-
1170
- /** 关闭所有连接并停掉清扫定时器。 */
1171
- dispose() {
1172
- if (this.sweepTimer !== undefined) clearInterval(this.sweepTimer)
1173
- for (const alias of [...this.pool.keys()]) disposeRecord(this, alias)
1174
- }
1175
- }
1176
-
1177
- /**
1178
- * 工厂:实例化 SshEngine。
1179
- * @param {HostStore} store
1180
- * @param {Partial<typeof DEFAULTS>} [options]
1181
- * @returns {SshEngine}
1182
- */
1183
- export function createSshEngine(store, options) {
1184
- return new SshEngine(store, options)
1185
- }
1186
-
1187
- // ============================================================================
1188
- // 8. 自检:node src/vp-ssh-core.js
1189
- // ----------------------------------------------------------------------------
1190
- // 全程不建立任何真实连接,不写仓库目录,临时库放在系统临时目录。
1191
- // ============================================================================
1192
-
1193
- async function selfTest() {
1194
- const { tmpdir } = await import('node:os')
1195
- const { rmSync } = await import('node:fs')
1196
- const { join: joinPath } = await import('node:path')
1197
-
1198
- const line = (text = '') => console.log(text)
1199
- const ok = (label, detail = '') => line(` [PASS] ${label}${detail === '' ? '' : ' → ' + detail}`)
1200
- const info = (label, detail) => line(` [INFO] ${label} → ${detail}`)
1201
-
1202
- line('╔══════════════════════════════════════════════════════════════════════╗')
1203
- line('║ vp-ssh-core.js 自检 ║')
1204
- line('╚══════════════════════════════════════════════════════════════════════╝')
1205
- line()
1206
-
1207
- // --- 1. 依赖探测 --------------------------------------------------------
1208
- line('【1】依赖探测')
1209
- const ssh2Ready = isSsh2Available()
1210
- if (ssh2Ready) {
1211
- const mod = loadSsh2()
1212
- ok('ssh2 可解析', `导出 Client=${typeof mod.Client}`)
1213
- } else {
1214
- info('ssh2 未安装', '惰性加载,导入/建库/校验不受影响;建连前需 npm install ssh2@1.17.0')
1215
- }
1216
- ok('零 DSH / cordis 依赖', '本文件仅 import node:* 内置模块')
1217
-
1218
- // --- 2. HostStore -------------------------------------------------------
1219
- line()
1220
- line('【2】HostStore(临时库,跑完删除)')
1221
- const tmpFile = joinPath(tmpdir(), `vp-ssh-selftest-${process.pid}.json`)
1222
- const keyFile = joinPath(tmpdir(), `vp-ssh-selftest-${process.pid}.key`)
1223
- writeFileSync(keyFile, '-----BEGIN OPENSSH PRIVATE KEY-----\n(self-test fixture)\n-----END OPENSSH PRIVATE KEY-----\n')
1224
- const store = createHostStore(tmpFile)
1225
- info('库路径', store.path)
1226
-
1227
- ok('空库 list()', JSON.stringify(store.list()))
1228
-
1229
- store.create({
1230
- alias: 'web-01',
1231
- host: '192.168.1.10',
1232
- port: 22,
1233
- user: 'ops',
1234
- auth: { kind: 'key', keyPath: keyFile },
1235
- tags: ['prod', 'nginx'],
1236
- environment: 'production',
1237
- description: '前置机',
1238
- })
1239
- store.create({
1240
- alias: 'db-01',
1241
- host: '192.168.1.20',
1242
- user: 'root',
1243
- auth: { kind: 'password', password: 'not-a-real-password' },
1244
- tags: ['prod', 'mysql'],
1245
- environment: 'production',
1246
- })
1247
- store.create({
1248
- alias: 'jump-01',
1249
- host: '10.0.0.1',
1250
- user: 'bastion',
1251
- auth: { kind: 'agent' },
1252
- tags: ['bastion'],
1253
- environment: 'production',
1254
- })
1255
- ok('写入 3 条主机', store.list().map(e => e.alias).join(', '))
1256
-
1257
- const summary = store.summarize(store.find('db-01'))
1258
- const leaked = JSON.stringify(summary).includes('not-a-real-password')
1259
- ok('summarize() 脱敏', leaked ? '密钥泄漏!' : `auth=${summary.auth}, 无明文口令字段`)
1260
- ok('keyReady 探测', `web-01.keyReady=${store.summarize(store.find('web-01')).keyReady}`)
1261
-
1262
- const dup = (() => { try { store.create({ alias: 'web-01', host: 'x', user: 'y', auth: { kind: 'agent' } }); return null } catch (e) { return e.message } })()
1263
- ok('重复别名被拒', dup ?? '未拒绝!')
1264
- const badAlias = (() => { try { store.create({ alias: '-bad-', host: 'x', user: 'y', auth: { kind: 'agent' } }); return null } catch (e) { return e.message } })()
1265
- ok('非法别名被拒', badAlias ?? '未拒绝!')
1266
- const badPort = (() => { try { store.create({ alias: 'bad-port', host: 'x', user: 'y', port: 99999, auth: { kind: 'agent' } }); return null } catch (e) { return e.message } })()
1267
- ok('非法端口被拒', badPort ?? '未拒绝!')
1268
-
1269
- // --- 3. buildConnectConfig ---------------------------------------------
1270
- line()
1271
- line('【3】buildConnectConfig(不建连)')
1272
- const cfgKey = buildConnectConfig(store.find('web-01'), undefined, DEFAULTS)
1273
- ok('key 认证', `host=${cfgKey.host}:${cfgKey.port} username=${cfgKey.username} privateKey=${cfgKey.privateKey.length} 字符(内容不打印)`)
1274
- ok('keepalive', `readyTimeout=${cfgKey.readyTimeout} keepaliveInterval=${cfgKey.keepaliveInterval} keepaliveCountMax=${cfgKey.keepaliveCountMax} tryKeyboard=${cfgKey.tryKeyboard}`)
1275
- const cfgPwd = buildConnectConfig(store.find('db-01'), undefined, DEFAULTS)
1276
- ok('password 认证', `username=${cfgPwd.username} password 已载入=${cfgPwd.password !== undefined}`)
1277
-
1278
- // --- 4. SshEngine -------------------------------------------------------
1279
- line()
1280
- line('【4】SshEngine')
1281
- const engine = createSshEngine(store)
1282
- ok('暴露接口', ['list', 'find', 'exec', 'cluster', 'test', 'upload', 'download', 'ls', 'dropAlias', 'dispose']
1283
- .map(name => `${name}${typeof engine[name] === 'function' ? '' : '✗'}`).join(', '))
1284
- ok('主机列表', engine.list('prod').map(e => e.alias).join(', '))
1285
- ok('模糊过滤', `list('nginx') → ${engine.list('nginx').map(e => e.alias).join(', ') || '(空)'}`)
1286
-
1287
- const miss = await engine.exec('no-such-host', 'echo ok')
1288
- .then(() => null, e => e.message)
1289
- ok('未知别名 exec 报错', miss ?? '未报错!')
1290
-
1291
- const probe = await engine.test('no-such-host')
1292
- ok('未知别名 test 降级', `ok=${probe.ok} error="${probe.error}"`)
1293
-
1294
- let clusterSafety = ''
1295
- try {
1296
- await engine.cluster({ command: 'echo ok', maxWorkers: 0 })
1297
- clusterSafety = '未校验 maxWorkers!'
1298
- } catch (e) {
1299
- clusterSafety = e.message
1300
- }
1301
- ok('cluster 参数校验', clusterSafety)
1302
-
1303
- // --- 5. 清理 ------------------------------------------------------------
1304
- engine.dispose()
1305
- ok('dispose() 无异常', `pool.size=${engine.pool.size}`)
1306
- try { rmSync(tmpFile, { force: true }) } catch { /* best effort */ }
1307
- try { rmSync(keyFile, { force: true }) } catch { /* best effort */ }
1308
- ok('临时文件已清理', tmpFile)
1309
-
1310
- line()
1311
- line('──────────────────────────────────────────────────────────────────────')
1312
- line(`自检结束:ssh2 ${ssh2Ready ? '已就位,可发起真实连接' : '未安装(惰性加载,需时再装)'}`)
1313
- line('默认主机库位置:' + storePath())
1314
- line('──────────────────────────────────────────────────────────────────────')
1315
- }
1316
-
1317
- const invokedDirectly = process.argv[1] !== undefined
1318
- && resolve(process.argv[1]) === fileURLToPath(import.meta.url)
1319
-
1320
- if (invokedDirectly) {
1321
- selfTest().then(
1322
- () => process.exit(0),
1323
- (error) => {
1324
- console.error('\n自检失败:', error)
1325
- process.exit(1)
1326
- },
1327
- )
1328
- }