@pyrokine/mcp-ssh 1.2.2 → 2.0.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,661 +0,0 @@
1
- /**
2
- * SSH Session Manager - 连接池管理
3
- *
4
- * 功能:
5
- * - 连接池复用
6
- * - 心跳保持
7
- * - 自动重连
8
- * - 会话持久化
9
- */
10
-
11
- import * as fs from 'fs'
12
- import * as os from 'os'
13
- import * as path from 'path'
14
- import {Client, ClientChannel, ConnectConfig, SFTPWrapper} from 'ssh2'
15
- import {ForwardManager} from './forward-manager.js'
16
- import {PtyManager} from './pty-manager.js'
17
- import {
18
- ExecOptions,
19
- ExecResult,
20
- PersistedSession,
21
- PortForwardInfo,
22
- PtyOptions,
23
- PtySessionInfo,
24
- SSHConnectionConfig,
25
- SSHSessionInfo,
26
- } from './types.js'
27
-
28
- interface SSHSession {
29
- client: Client;
30
- config: SSHConnectionConfig;
31
- connectedAt: number;
32
- lastUsedAt: number;
33
- reconnectAttempts: number;
34
- connected: boolean; // 通过事件监听维护的连接状态
35
- manualClose: boolean; // 标记主动关闭,阻止 close 事件触发自动重连
36
- }
37
-
38
- export class SessionManager {
39
- private sessions: Map<string, SSHSession> = new Map()
40
- private readonly ptyManager = new PtyManager()
41
- private readonly forwardManager = new ForwardManager()
42
- private readonly persistPath: string
43
- private defaultKeepaliveInterval = 30000 // 30秒
44
- private defaultKeepaliveCountMax = 3
45
- private defaultTimeout = 30000 // 30秒
46
- private maxReconnectAttempts = 3
47
- private defaultMaxOutputSize = 10 * 1024 * 1024 // 10MB
48
- private reconnectDelay = 5000 // 5秒
49
-
50
- constructor(persistPath?: string) {
51
- this.persistPath = persistPath || path.join(
52
- os.homedir(),
53
- '.ssh-mcp-pro',
54
- 'sessions.json',
55
- )
56
- this.ensurePersistDir()
57
- }
58
-
59
- /**
60
- * 建立 SSH 连接
61
- */
62
- async connect(config: SSHConnectionConfig): Promise<string> {
63
- const alias = this.generateAlias(config)
64
-
65
- // 检查是否已有活跃连接
66
- const existing = this.sessions.get(alias)
67
- if (existing && this.isAlive(existing)) {
68
- existing.lastUsedAt = Date.now()
69
- return alias
70
- }
71
-
72
- const client = new Client()
73
-
74
- // 构建连接配置
75
- const connectConfig: ConnectConfig = {
76
- host: config.host,
77
- port: config.port || 22,
78
- username: config.username,
79
- readyTimeout: config.readyTimeout || this.defaultTimeout,
80
- keepaliveInterval: config.keepaliveInterval || this.defaultKeepaliveInterval,
81
- keepaliveCountMax: config.keepaliveCountMax || this.defaultKeepaliveCountMax,
82
- }
83
-
84
- // 认证方式
85
- if (config.password) {
86
- connectConfig.password = config.password
87
- }
88
- if (config.privateKeyPath) {
89
- connectConfig.privateKey = fs.readFileSync(config.privateKeyPath)
90
- }
91
- if (config.privateKey) {
92
- connectConfig.privateKey = config.privateKey
93
- }
94
- if (config.passphrase) {
95
- connectConfig.passphrase = config.passphrase
96
- }
97
-
98
- // 跳板机支持
99
- if (config.jumpHost) {
100
- const jumpAlias = await this.connect(config.jumpHost)
101
- const jumpSession = this.sessions.get(jumpAlias)
102
- if (jumpSession) {
103
- // 通过跳板机建立连接
104
- connectConfig.sock = await this.forwardConnection(
105
- jumpSession.client,
106
- config.host,
107
- config.port || 22,
108
- )
109
- }
110
- }
111
-
112
- return new Promise((resolve, reject) => {
113
- client.on('ready', () => {
114
- const session: SSHSession = {
115
- client,
116
- config,
117
- connectedAt: Date.now(),
118
- lastUsedAt: Date.now(),
119
- reconnectAttempts: 0,
120
- connected: true,
121
- manualClose: false,
122
- }
123
- this.sessions.set(alias, session)
124
- this.persistSessions()
125
- resolve(alias)
126
- })
127
-
128
- client.on('error', (err) => {
129
- const session = this.sessions.get(alias)
130
- if (session && session.client === client) {
131
- session.connected = false
132
- }
133
- const target = `${connectConfig.username}@${connectConfig.host}:${connectConfig.port}`
134
- const suggestion = this.diagnoseConnectionError(err)
135
- reject(new Error(`SSH connection to ${target} failed: ${err.message}${suggestion ?
136
- ` (${suggestion})` :
137
- ''}`))
138
- })
139
-
140
- client.on('close', () => {
141
- const session = this.sessions.get(alias)
142
- if (session && session.client === client) {
143
- session.connected = false
144
- // 清理绑定旧 client 的 forward/PTY 资源
145
- this.forwardManager.closeByAlias(alias)
146
- this.ptyManager.closeByAlias(alias)
147
- if (!session.manualClose) {
148
- this.scheduleReconnect(alias)
149
- }
150
- }
151
- })
152
-
153
- client.connect(connectConfig)
154
- })
155
- }
156
-
157
- /**
158
- * 重新连接
159
- */
160
- async reconnect(alias: string): Promise<void> {
161
- const session = this.sessions.get(alias)
162
- if (!session) {
163
- throw new Error(`Session ${alias} not found`)
164
- }
165
-
166
- session.manualClose = true
167
- session.connected = false
168
-
169
- try {
170
- session.client.end()
171
- } catch { /* 忽略已关闭的连接 */
172
- }
173
-
174
- await this.connect(session.config)
175
- }
176
-
177
- /**
178
- * 断开连接
179
- */
180
- disconnect(alias: string): boolean {
181
- const session = this.sessions.get(alias)
182
- if (session) {
183
- session.manualClose = true
184
- // 清理关联的 PTY 和 forward 资源
185
- this.ptyManager.closeByAlias(alias)
186
- this.forwardManager.closeByAlias(alias)
187
- try {
188
- session.client.end()
189
- } catch { /* 忽略已关闭的连接 */
190
- }
191
- this.sessions.delete(alias)
192
- this.persistSessions()
193
- return true
194
- }
195
- return false
196
- }
197
-
198
- /**
199
- * 获取会话
200
- */
201
- getSession(alias: string): SSHSession {
202
- const session = this.sessions.get(alias)
203
- if (!session) {
204
- throw new Error(`Session '${alias}' not found. Use ssh_connect first.`)
205
- }
206
- if (!this.isAlive(session)) {
207
- throw new Error(`Session '${alias}' is disconnected. Use ssh_connect to reconnect.`)
208
- }
209
- session.lastUsedAt = Date.now()
210
- return session
211
- }
212
-
213
- /**
214
- * 列出所有会话
215
- */
216
- listSessions(): SSHSessionInfo[] {
217
- const result: SSHSessionInfo[] = []
218
- for (const [alias, session] of this.sessions) {
219
- result.push({
220
- alias,
221
- host: session.config.host,
222
- port: session.config.port || 22,
223
- username: session.config.username,
224
- connected: this.isAlive(session),
225
- connectedAt: session.connectedAt,
226
- lastUsedAt: session.lastUsedAt,
227
- env: session.config.env,
228
- })
229
- }
230
- return result
231
- }
232
-
233
- /**
234
- * 执行命令
235
- */
236
- async exec(
237
- alias: string,
238
- command: string,
239
- options: ExecOptions = {},
240
- ): Promise<ExecResult> {
241
- const session = this.getSession(alias)
242
- const startTime = Date.now()
243
- const maxOutputSize = options.maxOutputSize || this.defaultMaxOutputSize
244
- const fullCommand = this.buildCommand(command, session, options)
245
-
246
- return new Promise((resolve, reject) => {
247
- const timeout = options.timeout || this.defaultTimeout
248
- let timeoutId: NodeJS.Timeout | null = null
249
- let stdout = ''
250
- let stderr = ''
251
- let stdoutTruncated = false
252
- let stderrTruncated = false
253
-
254
- const execOptions: any = {}
255
-
256
- // PTY 模式
257
- if (options.pty) {
258
- execOptions.pty = {
259
- rows: options.rows || 24,
260
- cols: options.cols || 80,
261
- term: options.term || 'xterm-256color',
262
- }
263
- }
264
-
265
- session.client.exec(fullCommand, execOptions, (err, stream) => {
266
- if (err) {
267
- reject(new Error(`Exec failed: ${err.message}`))
268
- return
269
- }
270
-
271
- // 设置超时
272
- timeoutId = setTimeout(() => {
273
- stream.close()
274
- reject(new Error(`Command timed out after ${timeout}ms`))
275
- }, timeout)
276
-
277
- stream.on('close', (code: number) => {
278
- if (timeoutId) {
279
- clearTimeout(timeoutId)
280
- }
281
- resolve({
282
- success: code === 0,
283
- stdout: stdoutTruncated ? stdout + '\n... [truncated]' : stdout,
284
- stderr: stderrTruncated ? stderr + '\n... [truncated]' : stderr,
285
- exitCode: code,
286
- duration: Date.now() - startTime,
287
- })
288
- })
289
-
290
- stream.on('data', (data: Buffer) => {
291
- if (!stdoutTruncated) {
292
- const chunk = data.toString('utf-8')
293
- if (stdout.length + chunk.length > maxOutputSize) {
294
- stdout += chunk.slice(0, maxOutputSize - stdout.length)
295
- stdoutTruncated = true
296
- } else {
297
- stdout += chunk
298
- }
299
- }
300
- })
301
-
302
- stream.stderr.on('data', (data: Buffer) => {
303
- if (!stderrTruncated) {
304
- const chunk = data.toString('utf-8')
305
- if (stderr.length + chunk.length > maxOutputSize) {
306
- stderr += chunk.slice(0, maxOutputSize - stderr.length)
307
- stderrTruncated = true
308
- } else {
309
- stderr += chunk
310
- }
311
- }
312
- })
313
- })
314
- })
315
- }
316
-
317
- /**
318
- * 以其他用户身份执行命令
319
- *
320
- * options.loadProfile 控制是否加载用户的 shell 配置(默认 true)。
321
- * su -c 创建非交互式 shell,不会自动执行 rc 文件,
322
- * 但大多数用户的环境变量设置在 rc 文件中,因此默认加载。
323
- * 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)。
324
- */
325
- async execAsUser(
326
- alias: string,
327
- command: string,
328
- targetUser: string,
329
- options: ExecOptions & { loadProfile?: boolean } = {},
330
- ): Promise<ExecResult> {
331
- // 校验用户名防止注入
332
- if (!this.isValidUsername(targetUser)) {
333
- throw new Error(`Invalid username: ${targetUser}`)
334
- }
335
-
336
- const { loadProfile = true, ...execOpts } = options
337
-
338
- const wrappedCommand = loadProfile
339
- ? `${this.getLoadProfileCommand()}${command}`
340
- : command
341
-
342
- const suCommand = `su - ${targetUser} -c ${this.escapeShellArg(wrappedCommand)}`
343
- return this.exec(alias, suCommand, execOpts)
344
- }
345
-
346
- /**
347
- * 使用 sudo 执行命令
348
- */
349
- async execSudo(
350
- alias: string,
351
- command: string,
352
- sudoPassword?: string,
353
- options: ExecOptions = {},
354
- ): Promise<ExecResult> {
355
- let sudoCommand: string
356
- if (sudoPassword) {
357
- // 通过 stdin 传递密码(使用 escapeShellArg 转义)
358
- sudoCommand = `echo ${this.escapeShellArg(sudoPassword)} | sudo -S ${command}`
359
- } else {
360
- sudoCommand = `sudo ${command}`
361
- }
362
- return this.exec(alias, sudoCommand, options)
363
- }
364
-
365
- /**
366
- * 获取 SFTP 客户端
367
- */
368
- getSftp(alias: string): Promise<SFTPWrapper> {
369
- const session = this.getSession(alias)
370
- return new Promise((resolve, reject) => {
371
- session.client.sftp((err, sftp) => {
372
- if (err) {
373
- reject(err)
374
- } else {
375
- resolve(sftp)
376
- }
377
- })
378
- })
379
- }
380
-
381
- // ===== PTY 委托 =====
382
-
383
- async ptyStart(alias: string, command: string, options: PtyOptions = {}): Promise<string> {
384
- return this.ptyManager.start({
385
- execPty: (a, cmd, opts) => this.execPtyStream(a, cmd, opts),
386
- }, alias, command, options)
387
- }
388
-
389
- ptyWrite(ptyId: string, data: string): boolean {
390
- return this.ptyManager.write(ptyId, data)
391
- }
392
-
393
- ptyRead(
394
- ptyId: string,
395
- options: { mode?: 'screen' | 'raw'; clear?: boolean } = {},
396
- ): { data: string; active: boolean; rows: number; cols: number } {
397
- return this.ptyManager.read(ptyId, options)
398
- }
399
-
400
- ptyResize(ptyId: string, rows: number, cols: number): boolean {
401
- return this.ptyManager.resize(ptyId, rows, cols)
402
- }
403
-
404
- ptyClose(ptyId: string): boolean {
405
- return this.ptyManager.close(ptyId)
406
- }
407
-
408
- ptyList(): PtySessionInfo[] {
409
- return this.ptyManager.list()
410
- }
411
-
412
- // ===== Forward 委托 =====
413
-
414
- async forwardLocal(
415
- alias: string,
416
- localPort: number,
417
- remoteHost: string,
418
- remotePort: number,
419
- localHost: string = '127.0.0.1',
420
- ): Promise<string> {
421
- return this.forwardManager.forwardLocal(
422
- { getClient: (a) => this.getSession(a).client },
423
- alias, localPort, remoteHost, remotePort, localHost,
424
- )
425
- }
426
-
427
- async forwardRemote(
428
- alias: string,
429
- remotePort: number,
430
- localHost: string,
431
- localPort: number,
432
- remoteHost: string = '127.0.0.1',
433
- ): Promise<string> {
434
- return this.forwardManager.forwardRemote(
435
- { getClient: (a) => this.getSession(a).client },
436
- alias, remotePort, localHost, localPort, remoteHost,
437
- )
438
- }
439
-
440
- forwardClose(forwardId: string): boolean {
441
- return this.forwardManager.close(forwardId, {
442
- getClient: (a) => this.getSession(a).client,
443
- })
444
- }
445
-
446
- forwardList(): PortForwardInfo[] {
447
- return this.forwardManager.list()
448
- }
449
-
450
- /**
451
- * 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
452
- */
453
- private execPtyStream(
454
- alias: string,
455
- command: string,
456
- options: PtyOptions,
457
- ): Promise<ClientChannel> {
458
- const session = this.getSession(alias)
459
- const fullCommand = this.buildCommand(command, session, { env: options.env, cwd: options.cwd })
460
-
461
- return new Promise((resolve, reject) => {
462
- session.client.exec(fullCommand, {
463
- pty: {
464
- rows: options.rows || 24,
465
- cols: options.cols || 80,
466
- term: options.term || 'xterm-256color',
467
- },
468
- }, (err, stream) => {
469
- if (err) {
470
- reject(new Error(`PTY exec failed: ${err.message}`))
471
- } else {
472
- resolve(stream)
473
- }
474
- })
475
- })
476
- }
477
-
478
- private ensurePersistDir(): void {
479
- const dir = path.dirname(this.persistPath)
480
- if (!fs.existsSync(dir)) {
481
- fs.mkdirSync(dir, { recursive: true })
482
- }
483
- }
484
-
485
- /**
486
- * 生成连接别名
487
- */
488
- private generateAlias(config: SSHConnectionConfig): string {
489
- return config.alias || `${config.username}@${config.host}:${config.port}`
490
- }
491
-
492
- /**
493
- * 通过跳板机转发连接
494
- */
495
- private forwardConnection(
496
- jumpClient: Client,
497
- targetHost: string,
498
- targetPort: number,
499
- ): Promise<ClientChannel> {
500
- return new Promise((resolve, reject) => {
501
- jumpClient.forwardOut(
502
- '127.0.0.1',
503
- 0,
504
- targetHost,
505
- targetPort,
506
- (err, stream) => {
507
- if (err) {
508
- reject(err)
509
- } else {
510
- resolve(stream)
511
- }
512
- },
513
- )
514
- })
515
- }
516
-
517
- /**
518
- * 检查连接是否存活
519
- */
520
- private isAlive(session: SSHSession): boolean {
521
- return session.connected
522
- }
523
-
524
- /**
525
- * 调度自动重连(支持多次重试)
526
- */
527
- private scheduleReconnect(alias: string): void {
528
- const session = this.sessions.get(alias)
529
- if (!session || session.reconnectAttempts >= this.maxReconnectAttempts) {
530
- return
531
- }
532
-
533
- session.reconnectAttempts++
534
- const attempt = session.reconnectAttempts
535
-
536
- setTimeout(async () => {
537
- try {
538
- await this.reconnect(alias)
539
- } catch (err) {
540
- console.error(
541
- `Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}):`,
542
- (err as Error).message,
543
- )
544
- // reconnect 失败后继续调度下一次尝试
545
- this.scheduleReconnect(alias)
546
- }
547
- }, this.reconnectDelay)
548
- }
549
-
550
- /**
551
- * 根据错误类型生成排查建议
552
- */
553
- private diagnoseConnectionError(err: Error & { code?: string }): string {
554
- const msg = err.message || ''
555
- const code = err.code || ''
556
-
557
- if (code === 'ECONNREFUSED' || msg.includes('ECONNREFUSED')) {
558
- return 'check if SSH service is running on the target host'
559
- }
560
- if (code === 'ETIMEDOUT' || msg.includes('ETIMEDOUT') || msg.includes('Timed out')) {
561
- return 'check host reachability, firewall rules, or try a jump host'
562
- }
563
- if (code === 'ENOTFOUND' || msg.includes('ENOTFOUND') || msg.includes('getaddrinfo')) {
564
- return 'hostname cannot be resolved, check DNS or use IP address'
565
- }
566
- if (msg.includes('All configured authentication methods failed')) {
567
- return 'check password, key path, or key permissions (chmod 600)'
568
- }
569
- if (msg.includes('ECONNRESET') || msg.includes('Connection reset')) {
570
- return 'connection was reset by the remote host'
571
- }
572
- return ''
573
- }
574
-
575
- /**
576
- * 转义 shell 参数(使用单引号方式)
577
- */
578
- private escapeShellArg(s: string): string {
579
- return `'${s.replace(/'/g, '\'\\\'\'')}'`
580
- }
581
-
582
- /**
583
- * 校验用户名(只允许字母、数字、下划线、连字符)
584
- */
585
- private isValidUsername(username: string): boolean {
586
- return /^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(username)
587
- }
588
-
589
- /**
590
- * 校验环境变量名(只允许字母、数字、下划线,不能以数字开头)
591
- */
592
- private isValidEnvKey(key: string): boolean {
593
- return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)
594
- }
595
-
596
- /**
597
- * 构建完整命令:注入环境变量 + 切换工作目录
598
- */
599
- private buildCommand(
600
- command: string,
601
- session: SSHSession,
602
- options: { env?: Record<string, string>; cwd?: string },
603
- ): string {
604
- let fullCommand = command
605
- const env = { ...session.config.env, ...options.env }
606
-
607
- if (Object.keys(env).length > 0) {
608
- const validEntries = Object.entries(env).filter(([k]) => this.isValidEnvKey(k))
609
- if (validEntries.length > 0) {
610
- const envStr = validEntries
611
- .map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
612
- .join('; ')
613
- fullCommand = `${envStr}; ${command}`
614
- }
615
- }
616
-
617
- if (options.cwd) {
618
- fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`
619
- }
620
- return fullCommand
621
- }
622
-
623
- /**
624
- * 根据用户 shell 类型生成加载配置文件的命令
625
- * bash → .bashrc, zsh → .zshrc, 其他 → .profile
626
- */
627
- private getLoadProfileCommand(): string {
628
- return 'case "$(basename "$SHELL" 2>/dev/null)" in ' +
629
- 'bash) [ -f ~/.bashrc ] && . ~/.bashrc ;; ' +
630
- 'zsh) [ -f ~/.zshrc ] && . ~/.zshrc ;; ' +
631
- '*) [ -f ~/.profile ] && . ~/.profile ;; ' +
632
- 'esac 2>/dev/null; '
633
- }
634
-
635
- /**
636
- * 持久化会话信息
637
- */
638
- private persistSessions(): void {
639
- const data: PersistedSession[] = []
640
- for (const [alias, session] of this.sessions) {
641
- // 不保存敏感信息(密码、密钥)
642
- data.push({
643
- alias,
644
- host: session.config.host,
645
- port: session.config.port || 22,
646
- username: session.config.username,
647
- connectedAt: session.connectedAt,
648
- env: session.config.env,
649
- })
650
- }
651
- try {
652
- fs.writeFileSync(this.persistPath, JSON.stringify(data, null, 2))
653
- } catch (e) {
654
- // 忽略写入错误
655
- }
656
- }
657
-
658
- }
659
-
660
- // 全局单例
661
- export const sessionManager = new SessionManager()