@pyrokine/mcp-ssh 1.1.3 → 1.2.1

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.
@@ -8,11 +8,12 @@
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'
12
+ import * as os from 'os'
14
13
  import * as path from 'path'
15
14
  import {Client, ClientChannel, ConnectConfig, SFTPWrapper} from 'ssh2'
15
+ import {ForwardManager} from './forward-manager.js'
16
+ import {PtyManager} from './pty-manager.js'
16
17
  import {
17
18
  ExecOptions,
18
19
  ExecResult,
@@ -24,72 +25,31 @@ import {
24
25
  SSHSessionInfo,
25
26
  } from './types.js'
26
27
 
27
- const Terminal = xterm.Terminal as typeof import('@xterm/headless').Terminal
28
- type TerminalType = import('@xterm/headless').Terminal;
29
-
30
28
  interface SSHSession {
31
29
  client: Client;
32
30
  config: SSHConnectionConfig;
33
31
  connectedAt: number;
34
32
  lastUsedAt: number;
35
33
  reconnectAttempts: number;
36
- connected: boolean; // 通过事件监听维护的连接状态
37
- tcpDispatcher?: TcpConnectionHandler; // remote forward 共享的 dispatcher
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;
34
+ connected: boolean; // 通过事件监听维护的连接状态
35
+ manualClose: boolean; // 标记主动关闭,阻止 close 事件触发自动重连
73
36
  }
74
37
 
75
38
  export class SessionManager {
76
- private sessions: Map<string, SSHSession> = new Map()
77
- private ptySessions: Map<string, PtySession> = new Map()
78
- private forwardSessions: Map<string, ForwardSession> = new Map()
79
- private ptyIdCounter = 0
80
- private forwardIdCounter = 0
39
+ private sessions: Map<string, SSHSession> = new Map()
40
+ private readonly ptyManager = new PtyManager()
41
+ private readonly forwardManager = new ForwardManager()
81
42
  private readonly persistPath: string
82
- private defaultKeepaliveInterval = 30000 // 30秒
83
- private defaultKeepaliveCountMax = 3
84
- private defaultTimeout = 30000 // 30秒
85
- private maxReconnectAttempts = 3
86
- private defaultMaxOutputSize = 10 * 1024 * 1024 // 10MB
87
- private reconnectDelay = 5000 // 5秒
88
- private defaultPtyBufferSize = 1024 * 1024 // 1MB
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秒
89
49
 
90
50
  constructor(persistPath?: string) {
91
51
  this.persistPath = persistPath || path.join(
92
- process.env.HOME || '/tmp',
52
+ os.homedir(),
93
53
  '.ssh-mcp-pro',
94
54
  'sessions.json',
95
55
  )
@@ -158,6 +118,7 @@ export class SessionManager {
158
118
  lastUsedAt: Date.now(),
159
119
  reconnectAttempts: 0,
160
120
  connected: true,
121
+ manualClose: false,
161
122
  }
162
123
  this.sessions.set(alias, session)
163
124
  this.persistSessions()
@@ -166,24 +127,25 @@ export class SessionManager {
166
127
 
167
128
  client.on('error', (err) => {
168
129
  const session = this.sessions.get(alias)
169
- if (session) {
130
+ if (session && session.client === client) {
170
131
  session.connected = false
171
132
  }
172
- reject(new Error(`SSH connection failed: ${err.message}`))
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
+ ''}`))
173
138
  })
174
139
 
175
140
  client.on('close', () => {
176
141
  const session = this.sessions.get(alias)
177
- if (session) {
142
+ if (session && session.client === client) {
178
143
  session.connected = false
179
- // 自动重连逻辑
180
- if (session.reconnectAttempts < this.maxReconnectAttempts) {
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)
144
+ // 清理绑定旧 client 的 forward/PTY 资源
145
+ this.forwardManager.closeByAlias(alias)
146
+ this.ptyManager.closeByAlias(alias)
147
+ if (!session.manualClose) {
148
+ this.scheduleReconnect(alias)
187
149
  }
188
150
  }
189
151
  })
@@ -201,6 +163,9 @@ export class SessionManager {
201
163
  throw new Error(`Session ${alias} not found`)
202
164
  }
203
165
 
166
+ session.manualClose = true
167
+ session.connected = false
168
+
204
169
  try {
205
170
  session.client.end()
206
171
  } catch { /* 忽略已关闭的连接 */
@@ -215,6 +180,10 @@ export class SessionManager {
215
180
  disconnect(alias: string): boolean {
216
181
  const session = this.sessions.get(alias)
217
182
  if (session) {
183
+ session.manualClose = true
184
+ // 清理关联的 PTY 和 forward 资源
185
+ this.ptyManager.closeByAlias(alias)
186
+ this.forwardManager.closeByAlias(alias)
218
187
  try {
219
188
  session.client.end()
220
189
  } catch { /* 忽略已关闭的连接 */
@@ -409,206 +378,39 @@ export class SessionManager {
409
378
  })
410
379
  }
411
380
 
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
- })
381
+ // ===== PTY 委托 =====
486
382
 
487
- this.ptySessions.set(ptyId, ptySession)
488
- resolve(ptyId)
489
- },
490
- )
491
- })
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)
492
387
  }
493
388
 
494
- /**
495
- * 向 PTY 写入数据
496
- */
497
389
  ptyWrite(ptyId: string, data: string): boolean {
498
- const ptySession = this.ptySessions.get(ptyId)
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)
390
+ return this.ptyManager.write(ptyId, data)
506
391
  }
507
392
 
508
- /**
509
- * 读取 PTY 输出
510
- *
511
- * options.mode: 'screen' 返回当前屏幕内容,'raw' 返回原始 ANSI 流
512
- */
513
393
  ptyRead(
514
394
  ptyId: string,
515
395
  options: { mode?: 'screen' | 'raw'; clear?: boolean } = {},
516
396
  ): { data: string; active: boolean; rows: number; cols: number } {
517
- const ptySession = this.ptySessions.get(ptyId)
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
- }
397
+ return this.ptyManager.read(ptyId, options)
544
398
  }
545
399
 
546
- /**
547
- * 调整 PTY 窗口大小
548
- */
549
400
  ptyResize(ptyId: string, rows: number, cols: number): boolean {
550
- const ptySession = this.ptySessions.get(ptyId)
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
401
+ return this.ptyManager.resize(ptyId, rows, cols)
564
402
  }
565
403
 
566
- /**
567
- * 关闭 PTY 会话
568
- */
569
404
  ptyClose(ptyId: string): boolean {
570
- const ptySession = this.ptySessions.get(ptyId)
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
405
+ return this.ptyManager.close(ptyId)
585
406
  }
586
407
 
587
- /**
588
- * 列出所有 PTY 会话
589
- */
590
408
  ptyList(): PtySessionInfo[] {
591
- const result: PtySessionInfo[] = []
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
409
+ return this.ptyManager.list()
606
410
  }
607
411
 
608
- /**
609
- * 创建本地端口转发
610
- * 本地监听 localHost:localPort,转发到远程 remoteHost:remotePort
611
- */
412
+ // ===== Forward 委托 =====
413
+
612
414
  async forwardLocal(
613
415
  alias: string,
614
416
  localPort: number,
@@ -616,53 +418,12 @@ export class SessionManager {
616
418
  remotePort: number,
617
419
  localHost: string = '127.0.0.1',
618
420
  ): Promise<string> {
619
- const session = this.getSession(alias)
620
- const forwardId = this.generateForwardId()
621
-
622
- return new Promise((resolve, reject) => {
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
- })
421
+ return this.forwardManager.forwardLocal(
422
+ {getClient: (a) => this.getSession(a).client},
423
+ alias, localPort, remoteHost, remotePort, localHost,
424
+ )
660
425
  }
661
426
 
662
- /**
663
- * 创建远程端口转发
664
- * 远程监听 remoteHost:remotePort,转发到本地 localHost:localPort
665
- */
666
427
  async forwardRemote(
667
428
  alias: string,
668
429
  remotePort: number,
@@ -670,88 +431,48 @@ export class SessionManager {
670
431
  localPort: number,
671
432
  remoteHost: string = '127.0.0.1',
672
433
  ): Promise<string> {
673
- const session = this.getSession(alias)
674
- const forwardId = this.generateForwardId()
675
-
676
- return new Promise((resolve, reject) => {
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
- })
434
+ return this.forwardManager.forwardRemote(
435
+ {getClient: (a) => this.getSession(a).client},
436
+ alias, remotePort, localHost, localPort, remoteHost,
437
+ )
702
438
  }
703
439
 
704
- /**
705
- * 关闭端口转发
706
- */
707
440
  forwardClose(forwardId: string): boolean {
708
- const fwdSession = this.forwardSessions.get(forwardId)
709
- if (!fwdSession) {
710
- return false
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
- }
441
+ return this.forwardManager.close(forwardId, {
442
+ getClient: (a) => this.getSession(a).client,
443
+ })
444
+ }
731
445
 
732
- this.forwardSessions.delete(forwardId)
733
- return true
446
+ forwardList(): PortForwardInfo[] {
447
+ return this.forwardManager.list()
734
448
  }
735
449
 
736
450
  /**
737
- * 列出所有端口转发
451
+ * 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
738
452
  */
739
- forwardList(): PortForwardInfo[] {
740
- const result: PortForwardInfo[] = []
741
- for (const [id, fwd] of this.forwardSessions) {
742
- result.push({
743
- id,
744
- alias: fwd.alias,
745
- type: fwd.type,
746
- localHost: fwd.localHost,
747
- localPort: fwd.localPort,
748
- remoteHost: fwd.remoteHost,
749
- remotePort: fwd.remotePort,
750
- createdAt: fwd.createdAt,
751
- active: fwd.active,
752
- })
753
- }
754
- return result
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
+ })
755
476
  }
756
477
 
757
478
  private ensurePersistDir(): void {
@@ -800,6 +521,57 @@ export class SessionManager {
800
521
  return session.connected
801
522
  }
802
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
+
803
575
  /**
804
576
  * 转义 shell 参数(使用单引号方式)
805
577
  */
@@ -883,92 +655,6 @@ export class SessionManager {
883
655
  }
884
656
  }
885
657
 
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
658
  }
973
659
 
974
660
  // 全局单例