@pyrokine/mcp-ssh 1.1.3 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/README_zh.md +3 -1
- package/dist/forward-manager.d.ts +33 -0
- package/dist/forward-manager.js +185 -0
- package/dist/pty-manager.d.ts +37 -0
- package/dist/pty-manager.js +169 -0
- package/dist/session-manager.d.ts +15 -67
- package/dist/session-manager.js +99 -364
- package/package.json +1 -1
- package/src/forward-manager.ts +257 -0
- package/src/pty-manager.ts +220 -0
- package/src/session-manager.ts +131 -449
package/src/session-manager.ts
CHANGED
|
@@ -8,11 +8,11 @@
|
|
|
8
8
|
* - 会话持久化
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
import xterm from '@xterm/headless'
|
|
12
11
|
import * as fs from 'fs'
|
|
13
|
-
import * as net from 'net'
|
|
14
12
|
import * as path from 'path'
|
|
15
13
|
import {Client, ClientChannel, ConnectConfig, SFTPWrapper} from 'ssh2'
|
|
14
|
+
import {ForwardManager} from './forward-manager.js'
|
|
15
|
+
import {PtyManager} from './pty-manager.js'
|
|
16
16
|
import {
|
|
17
17
|
ExecOptions,
|
|
18
18
|
ExecResult,
|
|
@@ -24,68 +24,27 @@ import {
|
|
|
24
24
|
SSHSessionInfo,
|
|
25
25
|
} from './types.js'
|
|
26
26
|
|
|
27
|
-
const Terminal = xterm.Terminal as typeof import('@xterm/headless').Terminal
|
|
28
|
-
type TerminalType = import('@xterm/headless').Terminal;
|
|
29
|
-
|
|
30
27
|
interface SSHSession {
|
|
31
28
|
client: Client;
|
|
32
29
|
config: SSHConnectionConfig;
|
|
33
30
|
connectedAt: number;
|
|
34
31
|
lastUsedAt: number;
|
|
35
32
|
reconnectAttempts: number;
|
|
36
|
-
connected: boolean;
|
|
37
|
-
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
interface PtySession {
|
|
41
|
-
id: string;
|
|
42
|
-
alias: string;
|
|
43
|
-
command: string;
|
|
44
|
-
stream: ClientChannel;
|
|
45
|
-
terminal: TerminalType; // xterm headless 终端仿真器
|
|
46
|
-
rows: number;
|
|
47
|
-
cols: number;
|
|
48
|
-
createdAt: number;
|
|
49
|
-
lastReadAt: number;
|
|
50
|
-
rawBuffer: string; // 原始 ANSI 流
|
|
51
|
-
maxBufferSize: number;
|
|
52
|
-
active: boolean;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
// tcp connection 事件处理函数类型
|
|
56
|
-
type TcpConnectionHandler = (
|
|
57
|
-
info: { destIP: string; destPort: number; srcIP: string; srcPort: number },
|
|
58
|
-
accept: () => ClientChannel,
|
|
59
|
-
reject: () => void,
|
|
60
|
-
) => void;
|
|
61
|
-
|
|
62
|
-
interface ForwardSession {
|
|
63
|
-
id: string;
|
|
64
|
-
alias: string;
|
|
65
|
-
type: 'local' | 'remote';
|
|
66
|
-
localHost: string;
|
|
67
|
-
localPort: number;
|
|
68
|
-
remoteHost: string;
|
|
69
|
-
remotePort: number;
|
|
70
|
-
server?: net.Server; // 本地转发的 TCP 服务器
|
|
71
|
-
createdAt: number;
|
|
72
|
-
active: boolean;
|
|
33
|
+
connected: boolean; // 通过事件监听维护的连接状态
|
|
34
|
+
manualClose: boolean; // 标记主动关闭,阻止 close 事件触发自动重连
|
|
73
35
|
}
|
|
74
36
|
|
|
75
37
|
export class SessionManager {
|
|
76
|
-
private sessions: Map<string, SSHSession>
|
|
77
|
-
private
|
|
78
|
-
private
|
|
79
|
-
private ptyIdCounter = 0
|
|
80
|
-
private forwardIdCounter = 0
|
|
38
|
+
private sessions: Map<string, SSHSession> = new Map()
|
|
39
|
+
private readonly ptyManager = new PtyManager()
|
|
40
|
+
private readonly forwardManager = new ForwardManager()
|
|
81
41
|
private readonly persistPath: string
|
|
82
|
-
private defaultKeepaliveInterval
|
|
83
|
-
private defaultKeepaliveCountMax
|
|
84
|
-
private defaultTimeout
|
|
85
|
-
private maxReconnectAttempts
|
|
86
|
-
private defaultMaxOutputSize
|
|
87
|
-
private reconnectDelay
|
|
88
|
-
private defaultPtyBufferSize = 1024 * 1024 // 1MB
|
|
42
|
+
private defaultKeepaliveInterval = 30000 // 30秒
|
|
43
|
+
private defaultKeepaliveCountMax = 3
|
|
44
|
+
private defaultTimeout = 30000 // 30秒
|
|
45
|
+
private maxReconnectAttempts = 3
|
|
46
|
+
private defaultMaxOutputSize = 10 * 1024 * 1024 // 10MB
|
|
47
|
+
private reconnectDelay = 5000 // 5秒
|
|
89
48
|
|
|
90
49
|
constructor(persistPath?: string) {
|
|
91
50
|
this.persistPath = persistPath || path.join(
|
|
@@ -158,6 +117,7 @@ export class SessionManager {
|
|
|
158
117
|
lastUsedAt: Date.now(),
|
|
159
118
|
reconnectAttempts: 0,
|
|
160
119
|
connected: true,
|
|
120
|
+
manualClose: false,
|
|
161
121
|
}
|
|
162
122
|
this.sessions.set(alias, session)
|
|
163
123
|
this.persistSessions()
|
|
@@ -166,24 +126,22 @@ export class SessionManager {
|
|
|
166
126
|
|
|
167
127
|
client.on('error', (err) => {
|
|
168
128
|
const session = this.sessions.get(alias)
|
|
169
|
-
if (session) {
|
|
129
|
+
if (session && session.client === client) {
|
|
170
130
|
session.connected = false
|
|
171
131
|
}
|
|
172
|
-
|
|
132
|
+
const target = `${connectConfig.username}@${connectConfig.host}:${connectConfig.port}`
|
|
133
|
+
const suggestion = this.diagnoseConnectionError(err)
|
|
134
|
+
reject(new Error(`SSH connection to ${target} failed: ${err.message}${suggestion ?
|
|
135
|
+
` (${suggestion})` :
|
|
136
|
+
''}`))
|
|
173
137
|
})
|
|
174
138
|
|
|
175
139
|
client.on('close', () => {
|
|
176
140
|
const session = this.sessions.get(alias)
|
|
177
|
-
if (session) {
|
|
141
|
+
if (session && session.client === client) {
|
|
178
142
|
session.connected = false
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
session.reconnectAttempts++
|
|
182
|
-
setTimeout(() => {
|
|
183
|
-
this.reconnect(alias).catch((err) => {
|
|
184
|
-
console.error(`Auto-reconnect failed for ${alias}:`, err.message)
|
|
185
|
-
})
|
|
186
|
-
}, this.reconnectDelay)
|
|
143
|
+
if (!session.manualClose) {
|
|
144
|
+
this.scheduleReconnect(alias)
|
|
187
145
|
}
|
|
188
146
|
}
|
|
189
147
|
})
|
|
@@ -201,6 +159,9 @@ export class SessionManager {
|
|
|
201
159
|
throw new Error(`Session ${alias} not found`)
|
|
202
160
|
}
|
|
203
161
|
|
|
162
|
+
session.manualClose = true
|
|
163
|
+
session.connected = false
|
|
164
|
+
|
|
204
165
|
try {
|
|
205
166
|
session.client.end()
|
|
206
167
|
} catch { /* 忽略已关闭的连接 */
|
|
@@ -215,6 +176,10 @@ export class SessionManager {
|
|
|
215
176
|
disconnect(alias: string): boolean {
|
|
216
177
|
const session = this.sessions.get(alias)
|
|
217
178
|
if (session) {
|
|
179
|
+
session.manualClose = true
|
|
180
|
+
// 清理关联的 PTY 和 forward 资源
|
|
181
|
+
this.ptyManager.closeByAlias(alias)
|
|
182
|
+
this.forwardManager.closeByAlias(alias)
|
|
218
183
|
try {
|
|
219
184
|
session.client.end()
|
|
220
185
|
} catch { /* 忽略已关闭的连接 */
|
|
@@ -409,206 +374,39 @@ export class SessionManager {
|
|
|
409
374
|
})
|
|
410
375
|
}
|
|
411
376
|
|
|
412
|
-
|
|
413
|
-
* 启动持久化 PTY 会话
|
|
414
|
-
*/
|
|
415
|
-
async ptyStart(
|
|
416
|
-
alias: string,
|
|
417
|
-
command: string,
|
|
418
|
-
options: PtyOptions = {},
|
|
419
|
-
): Promise<string> {
|
|
420
|
-
const session = this.getSession(alias)
|
|
421
|
-
const ptyId = this.generatePtyId()
|
|
422
|
-
|
|
423
|
-
const rows = options.rows || 24
|
|
424
|
-
const cols = options.cols || 80
|
|
425
|
-
const term = options.term || 'xterm-256color'
|
|
426
|
-
const maxBufferSize = options.bufferSize || this.defaultPtyBufferSize
|
|
427
|
-
const fullCommand = this.buildCommand(command, session, options)
|
|
428
|
-
|
|
429
|
-
return new Promise((resolve, reject) => {
|
|
430
|
-
session.client.exec(
|
|
431
|
-
fullCommand,
|
|
432
|
-
{
|
|
433
|
-
pty: {rows, cols, term},
|
|
434
|
-
},
|
|
435
|
-
(err, stream) => {
|
|
436
|
-
if (err) {
|
|
437
|
-
reject(new Error(`PTY start failed: ${err.message}`))
|
|
438
|
-
return
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
// 创建 xterm headless 终端仿真器
|
|
442
|
-
const terminal = new Terminal({
|
|
443
|
-
rows,
|
|
444
|
-
cols,
|
|
445
|
-
allowProposedApi: true,
|
|
446
|
-
})
|
|
447
|
-
|
|
448
|
-
const ptySession: PtySession = {
|
|
449
|
-
id: ptyId,
|
|
450
|
-
alias,
|
|
451
|
-
command,
|
|
452
|
-
stream,
|
|
453
|
-
terminal,
|
|
454
|
-
rows,
|
|
455
|
-
cols,
|
|
456
|
-
createdAt: Date.now(),
|
|
457
|
-
lastReadAt: Date.now(),
|
|
458
|
-
rawBuffer: '',
|
|
459
|
-
maxBufferSize,
|
|
460
|
-
active: true,
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
// 监听输出数据
|
|
464
|
-
stream.on('data', (data: Buffer) => {
|
|
465
|
-
if (!ptySession.active) {
|
|
466
|
-
return
|
|
467
|
-
}
|
|
468
|
-
const chunk = data.toString('utf-8')
|
|
469
|
-
// 写入终端仿真器(解析 ANSI 序列)
|
|
470
|
-
terminal.write(chunk)
|
|
471
|
-
// 同时保留原始流(用于 raw 模式)
|
|
472
|
-
ptySession.rawBuffer += chunk
|
|
473
|
-
if (ptySession.rawBuffer.length > maxBufferSize) {
|
|
474
|
-
ptySession.rawBuffer = ptySession.rawBuffer.slice(-maxBufferSize)
|
|
475
|
-
}
|
|
476
|
-
})
|
|
477
|
-
|
|
478
|
-
stream.on('close', () => {
|
|
479
|
-
ptySession.active = false
|
|
480
|
-
})
|
|
481
|
-
|
|
482
|
-
stream.on('error', (err: Error) => {
|
|
483
|
-
ptySession.active = false
|
|
484
|
-
terminal.write(`\n[PTY Error: ${err.message}]`)
|
|
485
|
-
})
|
|
377
|
+
// ===== PTY 委托 =====
|
|
486
378
|
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
})
|
|
379
|
+
async ptyStart(alias: string, command: string, options: PtyOptions = {}): Promise<string> {
|
|
380
|
+
return this.ptyManager.start({
|
|
381
|
+
execPty: (a, cmd, opts) => this.execPtyStream(a, cmd, opts),
|
|
382
|
+
}, alias, command, options)
|
|
492
383
|
}
|
|
493
384
|
|
|
494
|
-
/**
|
|
495
|
-
* 向 PTY 写入数据
|
|
496
|
-
*/
|
|
497
385
|
ptyWrite(ptyId: string, data: string): boolean {
|
|
498
|
-
|
|
499
|
-
if (!ptySession) {
|
|
500
|
-
throw new Error(`PTY session '${ptyId}' not found`)
|
|
501
|
-
}
|
|
502
|
-
if (!ptySession.active) {
|
|
503
|
-
throw new Error(`PTY session '${ptyId}' is closed`)
|
|
504
|
-
}
|
|
505
|
-
return ptySession.stream.write(data)
|
|
386
|
+
return this.ptyManager.write(ptyId, data)
|
|
506
387
|
}
|
|
507
388
|
|
|
508
|
-
/**
|
|
509
|
-
* 读取 PTY 输出
|
|
510
|
-
*
|
|
511
|
-
* options.mode: 'screen' 返回当前屏幕内容,'raw' 返回原始 ANSI 流
|
|
512
|
-
*/
|
|
513
389
|
ptyRead(
|
|
514
390
|
ptyId: string,
|
|
515
391
|
options: { mode?: 'screen' | 'raw'; clear?: boolean } = {},
|
|
516
392
|
): { data: string; active: boolean; rows: number; cols: number } {
|
|
517
|
-
|
|
518
|
-
if (!ptySession) {
|
|
519
|
-
throw new Error(`PTY session '${ptyId}' not found`)
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
const mode = options.mode || 'screen'
|
|
523
|
-
const clear = options.clear !== false
|
|
524
|
-
|
|
525
|
-
let data: string
|
|
526
|
-
if (mode === 'screen') {
|
|
527
|
-
// 返回当前屏幕内容(解析后的纯文本)
|
|
528
|
-
data = this.getScreenContent(ptySession.terminal)
|
|
529
|
-
} else {
|
|
530
|
-
// 返回原始 ANSI 流
|
|
531
|
-
data = ptySession.rawBuffer
|
|
532
|
-
if (clear) {
|
|
533
|
-
ptySession.rawBuffer = ''
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
ptySession.lastReadAt = Date.now()
|
|
538
|
-
return {
|
|
539
|
-
data,
|
|
540
|
-
active: ptySession.active,
|
|
541
|
-
rows: ptySession.rows,
|
|
542
|
-
cols: ptySession.cols,
|
|
543
|
-
}
|
|
393
|
+
return this.ptyManager.read(ptyId, options)
|
|
544
394
|
}
|
|
545
395
|
|
|
546
|
-
/**
|
|
547
|
-
* 调整 PTY 窗口大小
|
|
548
|
-
*/
|
|
549
396
|
ptyResize(ptyId: string, rows: number, cols: number): boolean {
|
|
550
|
-
|
|
551
|
-
if (!ptySession) {
|
|
552
|
-
throw new Error(`PTY session '${ptyId}' not found`)
|
|
553
|
-
}
|
|
554
|
-
if (!ptySession.active) {
|
|
555
|
-
throw new Error(`PTY session '${ptyId}' is closed`)
|
|
556
|
-
}
|
|
557
|
-
// 调整远程 PTY 窗口
|
|
558
|
-
ptySession.stream.setWindow(rows, cols, 0, 0)
|
|
559
|
-
// 调整本地终端仿真器
|
|
560
|
-
ptySession.terminal.resize(cols, rows)
|
|
561
|
-
ptySession.rows = rows
|
|
562
|
-
ptySession.cols = cols
|
|
563
|
-
return true
|
|
397
|
+
return this.ptyManager.resize(ptyId, rows, cols)
|
|
564
398
|
}
|
|
565
399
|
|
|
566
|
-
/**
|
|
567
|
-
* 关闭 PTY 会话
|
|
568
|
-
*/
|
|
569
400
|
ptyClose(ptyId: string): boolean {
|
|
570
|
-
|
|
571
|
-
if (!ptySession) {
|
|
572
|
-
return false
|
|
573
|
-
}
|
|
574
|
-
try {
|
|
575
|
-
ptySession.stream.close()
|
|
576
|
-
} catch { /* 忽略清理异常 */
|
|
577
|
-
}
|
|
578
|
-
try {
|
|
579
|
-
ptySession.terminal.dispose()
|
|
580
|
-
} catch { /* 忽略清理异常 */
|
|
581
|
-
}
|
|
582
|
-
ptySession.active = false
|
|
583
|
-
this.ptySessions.delete(ptyId)
|
|
584
|
-
return true
|
|
401
|
+
return this.ptyManager.close(ptyId)
|
|
585
402
|
}
|
|
586
403
|
|
|
587
|
-
/**
|
|
588
|
-
* 列出所有 PTY 会话
|
|
589
|
-
*/
|
|
590
404
|
ptyList(): PtySessionInfo[] {
|
|
591
|
-
|
|
592
|
-
for (const [id, pty] of this.ptySessions) {
|
|
593
|
-
result.push({
|
|
594
|
-
id,
|
|
595
|
-
alias: pty.alias,
|
|
596
|
-
command: pty.command,
|
|
597
|
-
rows: pty.rows,
|
|
598
|
-
cols: pty.cols,
|
|
599
|
-
createdAt: pty.createdAt,
|
|
600
|
-
lastReadAt: pty.lastReadAt,
|
|
601
|
-
bufferSize: pty.rawBuffer.length,
|
|
602
|
-
active: pty.active,
|
|
603
|
-
})
|
|
604
|
-
}
|
|
605
|
-
return result
|
|
405
|
+
return this.ptyManager.list()
|
|
606
406
|
}
|
|
607
407
|
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
* 本地监听 localHost:localPort,转发到远程 remoteHost:remotePort
|
|
611
|
-
*/
|
|
408
|
+
// ===== Forward 委托 =====
|
|
409
|
+
|
|
612
410
|
async forwardLocal(
|
|
613
411
|
alias: string,
|
|
614
412
|
localPort: number,
|
|
@@ -616,53 +414,12 @@ export class SessionManager {
|
|
|
616
414
|
remotePort: number,
|
|
617
415
|
localHost: string = '127.0.0.1',
|
|
618
416
|
): Promise<string> {
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
const server = net.createServer((socket) => {
|
|
624
|
-
session.client.forwardOut(
|
|
625
|
-
socket.remoteAddress || '127.0.0.1',
|
|
626
|
-
socket.remotePort || 0,
|
|
627
|
-
remoteHost,
|
|
628
|
-
remotePort,
|
|
629
|
-
(err, stream) => {
|
|
630
|
-
if (err) {
|
|
631
|
-
socket.end()
|
|
632
|
-
return
|
|
633
|
-
}
|
|
634
|
-
socket.pipe(stream).pipe(socket)
|
|
635
|
-
},
|
|
636
|
-
)
|
|
637
|
-
})
|
|
638
|
-
|
|
639
|
-
server.on('error', (err) => {
|
|
640
|
-
reject(new Error(`Local forward failed: ${err.message}`))
|
|
641
|
-
})
|
|
642
|
-
|
|
643
|
-
server.listen(localPort, localHost, () => {
|
|
644
|
-
const fwdSession: ForwardSession = {
|
|
645
|
-
id: forwardId,
|
|
646
|
-
alias,
|
|
647
|
-
type: 'local',
|
|
648
|
-
localHost,
|
|
649
|
-
localPort,
|
|
650
|
-
remoteHost,
|
|
651
|
-
remotePort,
|
|
652
|
-
server,
|
|
653
|
-
createdAt: Date.now(),
|
|
654
|
-
active: true,
|
|
655
|
-
}
|
|
656
|
-
this.forwardSessions.set(forwardId, fwdSession)
|
|
657
|
-
resolve(forwardId)
|
|
658
|
-
})
|
|
659
|
-
})
|
|
417
|
+
return this.forwardManager.forwardLocal(
|
|
418
|
+
{getClient: (a) => this.getSession(a).client},
|
|
419
|
+
alias, localPort, remoteHost, remotePort, localHost,
|
|
420
|
+
)
|
|
660
421
|
}
|
|
661
422
|
|
|
662
|
-
/**
|
|
663
|
-
* 创建远程端口转发
|
|
664
|
-
* 远程监听 remoteHost:remotePort,转发到本地 localHost:localPort
|
|
665
|
-
*/
|
|
666
423
|
async forwardRemote(
|
|
667
424
|
alias: string,
|
|
668
425
|
remotePort: number,
|
|
@@ -670,88 +427,48 @@ export class SessionManager {
|
|
|
670
427
|
localPort: number,
|
|
671
428
|
remoteHost: string = '127.0.0.1',
|
|
672
429
|
): Promise<string> {
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
session.client.forwardIn(remoteHost, remotePort, (err) => {
|
|
678
|
-
if (err) {
|
|
679
|
-
reject(new Error(`Remote forward failed: ${err.message}`))
|
|
680
|
-
return
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
const fwdSession: ForwardSession = {
|
|
684
|
-
id: forwardId,
|
|
685
|
-
alias,
|
|
686
|
-
type: 'remote',
|
|
687
|
-
localHost,
|
|
688
|
-
localPort,
|
|
689
|
-
remoteHost,
|
|
690
|
-
remotePort,
|
|
691
|
-
createdAt: Date.now(),
|
|
692
|
-
active: true,
|
|
693
|
-
}
|
|
694
|
-
this.forwardSessions.set(forwardId, fwdSession)
|
|
695
|
-
|
|
696
|
-
// 确保该 session 有共享的 tcp dispatcher
|
|
697
|
-
this.ensureTcpDispatcher(session, alias)
|
|
698
|
-
|
|
699
|
-
resolve(forwardId)
|
|
700
|
-
})
|
|
701
|
-
})
|
|
430
|
+
return this.forwardManager.forwardRemote(
|
|
431
|
+
{getClient: (a) => this.getSession(a).client},
|
|
432
|
+
alias, remotePort, localHost, localPort, remoteHost,
|
|
433
|
+
)
|
|
702
434
|
}
|
|
703
435
|
|
|
704
|
-
/**
|
|
705
|
-
* 关闭端口转发
|
|
706
|
-
*/
|
|
707
436
|
forwardClose(forwardId: string): boolean {
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
fwdSession.active = false
|
|
714
|
-
|
|
715
|
-
if (fwdSession.type === 'local' && fwdSession.server) {
|
|
716
|
-
try {
|
|
717
|
-
fwdSession.server.close()
|
|
718
|
-
} catch { /* 忽略清理异常 */
|
|
719
|
-
}
|
|
720
|
-
} else if (fwdSession.type === 'remote') {
|
|
721
|
-
const session = this.sessions.get(fwdSession.alias)
|
|
722
|
-
if (session) {
|
|
723
|
-
try {
|
|
724
|
-
session.client.unforwardIn(fwdSession.remoteHost, fwdSession.remotePort)
|
|
725
|
-
} catch { /* 忽略清理异常 */
|
|
726
|
-
}
|
|
727
|
-
// 检查是否需要移除共享 dispatcher
|
|
728
|
-
this.removeTcpDispatcherIfEmpty(session, fwdSession.alias)
|
|
729
|
-
}
|
|
730
|
-
}
|
|
437
|
+
return this.forwardManager.close(forwardId, {
|
|
438
|
+
getClient: (a) => this.getSession(a).client,
|
|
439
|
+
})
|
|
440
|
+
}
|
|
731
441
|
|
|
732
|
-
|
|
733
|
-
return
|
|
442
|
+
forwardList(): PortForwardInfo[] {
|
|
443
|
+
return this.forwardManager.list()
|
|
734
444
|
}
|
|
735
445
|
|
|
736
446
|
/**
|
|
737
|
-
*
|
|
447
|
+
* 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
|
|
738
448
|
*/
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
449
|
+
private execPtyStream(
|
|
450
|
+
alias: string,
|
|
451
|
+
command: string,
|
|
452
|
+
options: PtyOptions,
|
|
453
|
+
): Promise<ClientChannel> {
|
|
454
|
+
const session = this.getSession(alias)
|
|
455
|
+
const fullCommand = this.buildCommand(command, session, {env: options.env, cwd: options.cwd})
|
|
456
|
+
|
|
457
|
+
return new Promise((resolve, reject) => {
|
|
458
|
+
session.client.exec(fullCommand, {
|
|
459
|
+
pty: {
|
|
460
|
+
rows: options.rows || 24,
|
|
461
|
+
cols: options.cols || 80,
|
|
462
|
+
term: options.term || 'xterm-256color',
|
|
463
|
+
},
|
|
464
|
+
}, (err, stream) => {
|
|
465
|
+
if (err) {
|
|
466
|
+
reject(new Error(`PTY exec failed: ${err.message}`))
|
|
467
|
+
} else {
|
|
468
|
+
resolve(stream)
|
|
469
|
+
}
|
|
470
|
+
})
|
|
471
|
+
})
|
|
755
472
|
}
|
|
756
473
|
|
|
757
474
|
private ensurePersistDir(): void {
|
|
@@ -800,6 +517,57 @@ export class SessionManager {
|
|
|
800
517
|
return session.connected
|
|
801
518
|
}
|
|
802
519
|
|
|
520
|
+
/**
|
|
521
|
+
* 调度自动重连(支持多次重试)
|
|
522
|
+
*/
|
|
523
|
+
private scheduleReconnect(alias: string): void {
|
|
524
|
+
const session = this.sessions.get(alias)
|
|
525
|
+
if (!session || session.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
526
|
+
return
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
session.reconnectAttempts++
|
|
530
|
+
const attempt = session.reconnectAttempts
|
|
531
|
+
|
|
532
|
+
setTimeout(async () => {
|
|
533
|
+
try {
|
|
534
|
+
await this.reconnect(alias)
|
|
535
|
+
} catch (err) {
|
|
536
|
+
console.error(
|
|
537
|
+
`Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}):`,
|
|
538
|
+
(err as Error).message,
|
|
539
|
+
)
|
|
540
|
+
// reconnect 失败后继续调度下一次尝试
|
|
541
|
+
this.scheduleReconnect(alias)
|
|
542
|
+
}
|
|
543
|
+
}, this.reconnectDelay)
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* 根据错误类型生成排查建议
|
|
548
|
+
*/
|
|
549
|
+
private diagnoseConnectionError(err: Error & { code?: string }): string {
|
|
550
|
+
const msg = err.message || ''
|
|
551
|
+
const code = err.code || ''
|
|
552
|
+
|
|
553
|
+
if (code === 'ECONNREFUSED' || msg.includes('ECONNREFUSED')) {
|
|
554
|
+
return 'check if SSH service is running on the target host'
|
|
555
|
+
}
|
|
556
|
+
if (code === 'ETIMEDOUT' || msg.includes('ETIMEDOUT') || msg.includes('Timed out')) {
|
|
557
|
+
return 'check host reachability, firewall rules, or try a jump host'
|
|
558
|
+
}
|
|
559
|
+
if (code === 'ENOTFOUND' || msg.includes('ENOTFOUND') || msg.includes('getaddrinfo')) {
|
|
560
|
+
return 'hostname cannot be resolved, check DNS or use IP address'
|
|
561
|
+
}
|
|
562
|
+
if (msg.includes('All configured authentication methods failed')) {
|
|
563
|
+
return 'check password, key path, or key permissions (chmod 600)'
|
|
564
|
+
}
|
|
565
|
+
if (msg.includes('ECONNRESET') || msg.includes('Connection reset')) {
|
|
566
|
+
return 'connection was reset by the remote host'
|
|
567
|
+
}
|
|
568
|
+
return ''
|
|
569
|
+
}
|
|
570
|
+
|
|
803
571
|
/**
|
|
804
572
|
* 转义 shell 参数(使用单引号方式)
|
|
805
573
|
*/
|
|
@@ -883,92 +651,6 @@ export class SessionManager {
|
|
|
883
651
|
}
|
|
884
652
|
}
|
|
885
653
|
|
|
886
|
-
/**
|
|
887
|
-
* 生成 PTY 会话 ID
|
|
888
|
-
*/
|
|
889
|
-
private generatePtyId(): string {
|
|
890
|
-
return `pty_${++this.ptyIdCounter}_${Date.now()}`
|
|
891
|
-
}
|
|
892
|
-
|
|
893
|
-
/**
|
|
894
|
-
* 从终端仿真器获取当前屏幕内容
|
|
895
|
-
*/
|
|
896
|
-
private getScreenContent(terminal: TerminalType): string {
|
|
897
|
-
const buffer = terminal.buffer.active
|
|
898
|
-
const lines: string[] = []
|
|
899
|
-
for (let i = 0; i < terminal.rows; i++) {
|
|
900
|
-
const line = buffer.getLine(i)
|
|
901
|
-
if (line) {
|
|
902
|
-
lines.push(line.translateToString(true))
|
|
903
|
-
}
|
|
904
|
-
}
|
|
905
|
-
// 移除尾部空行
|
|
906
|
-
while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
|
|
907
|
-
lines.pop()
|
|
908
|
-
}
|
|
909
|
-
return lines.join('\n')
|
|
910
|
-
}
|
|
911
|
-
|
|
912
|
-
/**
|
|
913
|
-
* 生成端口转发 ID
|
|
914
|
-
*/
|
|
915
|
-
private generateForwardId(): string {
|
|
916
|
-
return `fwd_${++this.forwardIdCounter}_${Date.now()}`
|
|
917
|
-
}
|
|
918
|
-
|
|
919
|
-
/**
|
|
920
|
-
* 确保 SSH session 有共享的 tcp connection dispatcher
|
|
921
|
-
* 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
|
|
922
|
-
*/
|
|
923
|
-
private ensureTcpDispatcher(session: SSHSession, alias: string): void {
|
|
924
|
-
if (session.tcpDispatcher) {
|
|
925
|
-
return // 已存在
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
const dispatcher: TcpConnectionHandler = (info, accept, rejectConn) => {
|
|
929
|
-
// 查找匹配的 remote forward
|
|
930
|
-
for (const fwd of this.forwardSessions.values()) {
|
|
931
|
-
if (fwd.type === 'remote' &&
|
|
932
|
-
fwd.active &&
|
|
933
|
-
fwd.alias === alias &&
|
|
934
|
-
fwd.remoteHost === info.destIP &&
|
|
935
|
-
fwd.remotePort === info.destPort) {
|
|
936
|
-
// 找到匹配的 forward,建立连接
|
|
937
|
-
const stream = accept()
|
|
938
|
-
const socket = net.createConnection(fwd.localPort, fwd.localHost)
|
|
939
|
-
socket.pipe(stream).pipe(socket)
|
|
940
|
-
socket.on('error', () => stream.close())
|
|
941
|
-
stream.on('error', () => socket.destroy())
|
|
942
|
-
return
|
|
943
|
-
}
|
|
944
|
-
}
|
|
945
|
-
// 没有匹配的 forward,拒绝连接
|
|
946
|
-
rejectConn()
|
|
947
|
-
}
|
|
948
|
-
|
|
949
|
-
session.tcpDispatcher = dispatcher
|
|
950
|
-
session.client.on('tcp connection', dispatcher)
|
|
951
|
-
}
|
|
952
|
-
|
|
953
|
-
/**
|
|
954
|
-
* 移除 SSH session 的 tcp dispatcher(当没有 remote forward 时)
|
|
955
|
-
*/
|
|
956
|
-
private removeTcpDispatcherIfEmpty(session: SSHSession, alias: string): void {
|
|
957
|
-
if (!session.tcpDispatcher) {
|
|
958
|
-
return
|
|
959
|
-
}
|
|
960
|
-
|
|
961
|
-
// 检查是否还有该 session 的 remote forward
|
|
962
|
-
for (const fwd of this.forwardSessions.values()) {
|
|
963
|
-
if (fwd.type === 'remote' && fwd.alias === alias && fwd.active) {
|
|
964
|
-
return // 还有活跃的 remote forward
|
|
965
|
-
}
|
|
966
|
-
}
|
|
967
|
-
|
|
968
|
-
// 没有了,移除 dispatcher
|
|
969
|
-
session.client.removeListener('tcp connection', session.tcpDispatcher)
|
|
970
|
-
session.tcpDispatcher = undefined
|
|
971
|
-
}
|
|
972
654
|
}
|
|
973
655
|
|
|
974
656
|
// 全局单例
|