@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/dist/session-manager.js
CHANGED
|
@@ -7,18 +7,15 @@
|
|
|
7
7
|
* - 自动重连
|
|
8
8
|
* - 会话持久化
|
|
9
9
|
*/
|
|
10
|
-
import xterm from '@xterm/headless';
|
|
11
10
|
import * as fs from 'fs';
|
|
12
|
-
import * as net from 'net';
|
|
13
11
|
import * as path from 'path';
|
|
14
12
|
import { Client } from 'ssh2';
|
|
15
|
-
|
|
13
|
+
import { ForwardManager } from './forward-manager.js';
|
|
14
|
+
import { PtyManager } from './pty-manager.js';
|
|
16
15
|
export class SessionManager {
|
|
17
16
|
sessions = new Map();
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
ptyIdCounter = 0;
|
|
21
|
-
forwardIdCounter = 0;
|
|
17
|
+
ptyManager = new PtyManager();
|
|
18
|
+
forwardManager = new ForwardManager();
|
|
22
19
|
persistPath;
|
|
23
20
|
defaultKeepaliveInterval = 30000; // 30秒
|
|
24
21
|
defaultKeepaliveCountMax = 3;
|
|
@@ -26,7 +23,6 @@ export class SessionManager {
|
|
|
26
23
|
maxReconnectAttempts = 3;
|
|
27
24
|
defaultMaxOutputSize = 10 * 1024 * 1024; // 10MB
|
|
28
25
|
reconnectDelay = 5000; // 5秒
|
|
29
|
-
defaultPtyBufferSize = 1024 * 1024; // 1MB
|
|
30
26
|
constructor(persistPath) {
|
|
31
27
|
this.persistPath = persistPath || path.join(process.env.HOME || '/tmp', '.ssh-mcp-pro', 'sessions.json');
|
|
32
28
|
this.ensurePersistDir();
|
|
@@ -83,6 +79,7 @@ export class SessionManager {
|
|
|
83
79
|
lastUsedAt: Date.now(),
|
|
84
80
|
reconnectAttempts: 0,
|
|
85
81
|
connected: true,
|
|
82
|
+
manualClose: false,
|
|
86
83
|
};
|
|
87
84
|
this.sessions.set(alias, session);
|
|
88
85
|
this.persistSessions();
|
|
@@ -90,23 +87,21 @@ export class SessionManager {
|
|
|
90
87
|
});
|
|
91
88
|
client.on('error', (err) => {
|
|
92
89
|
const session = this.sessions.get(alias);
|
|
93
|
-
if (session) {
|
|
90
|
+
if (session && session.client === client) {
|
|
94
91
|
session.connected = false;
|
|
95
92
|
}
|
|
96
|
-
|
|
93
|
+
const target = `${connectConfig.username}@${connectConfig.host}:${connectConfig.port}`;
|
|
94
|
+
const suggestion = this.diagnoseConnectionError(err);
|
|
95
|
+
reject(new Error(`SSH connection to ${target} failed: ${err.message}${suggestion ?
|
|
96
|
+
` (${suggestion})` :
|
|
97
|
+
''}`));
|
|
97
98
|
});
|
|
98
99
|
client.on('close', () => {
|
|
99
100
|
const session = this.sessions.get(alias);
|
|
100
|
-
if (session) {
|
|
101
|
+
if (session && session.client === client) {
|
|
101
102
|
session.connected = false;
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
session.reconnectAttempts++;
|
|
105
|
-
setTimeout(() => {
|
|
106
|
-
this.reconnect(alias).catch((err) => {
|
|
107
|
-
console.error(`Auto-reconnect failed for ${alias}:`, err.message);
|
|
108
|
-
});
|
|
109
|
-
}, this.reconnectDelay);
|
|
103
|
+
if (!session.manualClose) {
|
|
104
|
+
this.scheduleReconnect(alias);
|
|
110
105
|
}
|
|
111
106
|
}
|
|
112
107
|
});
|
|
@@ -121,6 +116,8 @@ export class SessionManager {
|
|
|
121
116
|
if (!session) {
|
|
122
117
|
throw new Error(`Session ${alias} not found`);
|
|
123
118
|
}
|
|
119
|
+
session.manualClose = true;
|
|
120
|
+
session.connected = false;
|
|
124
121
|
try {
|
|
125
122
|
session.client.end();
|
|
126
123
|
}
|
|
@@ -134,6 +131,10 @@ export class SessionManager {
|
|
|
134
131
|
disconnect(alias) {
|
|
135
132
|
const session = this.sessions.get(alias);
|
|
136
133
|
if (session) {
|
|
134
|
+
session.manualClose = true;
|
|
135
|
+
// 清理关联的 PTY 和 forward 资源
|
|
136
|
+
this.ptyManager.closeByAlias(alias);
|
|
137
|
+
this.forwardManager.closeByAlias(alias);
|
|
137
138
|
try {
|
|
138
139
|
session.client.end();
|
|
139
140
|
}
|
|
@@ -301,296 +302,64 @@ export class SessionManager {
|
|
|
301
302
|
});
|
|
302
303
|
});
|
|
303
304
|
}
|
|
304
|
-
|
|
305
|
-
* 启动持久化 PTY 会话
|
|
306
|
-
*/
|
|
305
|
+
// ===== PTY 委托 =====
|
|
307
306
|
async ptyStart(alias, command, options = {}) {
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
const cols = options.cols || 80;
|
|
312
|
-
const term = options.term || 'xterm-256color';
|
|
313
|
-
const maxBufferSize = options.bufferSize || this.defaultPtyBufferSize;
|
|
314
|
-
const fullCommand = this.buildCommand(command, session, options);
|
|
315
|
-
return new Promise((resolve, reject) => {
|
|
316
|
-
session.client.exec(fullCommand, {
|
|
317
|
-
pty: { rows, cols, term },
|
|
318
|
-
}, (err, stream) => {
|
|
319
|
-
if (err) {
|
|
320
|
-
reject(new Error(`PTY start failed: ${err.message}`));
|
|
321
|
-
return;
|
|
322
|
-
}
|
|
323
|
-
// 创建 xterm headless 终端仿真器
|
|
324
|
-
const terminal = new Terminal({
|
|
325
|
-
rows,
|
|
326
|
-
cols,
|
|
327
|
-
allowProposedApi: true,
|
|
328
|
-
});
|
|
329
|
-
const ptySession = {
|
|
330
|
-
id: ptyId,
|
|
331
|
-
alias,
|
|
332
|
-
command,
|
|
333
|
-
stream,
|
|
334
|
-
terminal,
|
|
335
|
-
rows,
|
|
336
|
-
cols,
|
|
337
|
-
createdAt: Date.now(),
|
|
338
|
-
lastReadAt: Date.now(),
|
|
339
|
-
rawBuffer: '',
|
|
340
|
-
maxBufferSize,
|
|
341
|
-
active: true,
|
|
342
|
-
};
|
|
343
|
-
// 监听输出数据
|
|
344
|
-
stream.on('data', (data) => {
|
|
345
|
-
if (!ptySession.active) {
|
|
346
|
-
return;
|
|
347
|
-
}
|
|
348
|
-
const chunk = data.toString('utf-8');
|
|
349
|
-
// 写入终端仿真器(解析 ANSI 序列)
|
|
350
|
-
terminal.write(chunk);
|
|
351
|
-
// 同时保留原始流(用于 raw 模式)
|
|
352
|
-
ptySession.rawBuffer += chunk;
|
|
353
|
-
if (ptySession.rawBuffer.length > maxBufferSize) {
|
|
354
|
-
ptySession.rawBuffer = ptySession.rawBuffer.slice(-maxBufferSize);
|
|
355
|
-
}
|
|
356
|
-
});
|
|
357
|
-
stream.on('close', () => {
|
|
358
|
-
ptySession.active = false;
|
|
359
|
-
});
|
|
360
|
-
stream.on('error', (err) => {
|
|
361
|
-
ptySession.active = false;
|
|
362
|
-
terminal.write(`\n[PTY Error: ${err.message}]`);
|
|
363
|
-
});
|
|
364
|
-
this.ptySessions.set(ptyId, ptySession);
|
|
365
|
-
resolve(ptyId);
|
|
366
|
-
});
|
|
367
|
-
});
|
|
307
|
+
return this.ptyManager.start({
|
|
308
|
+
execPty: (a, cmd, opts) => this.execPtyStream(a, cmd, opts),
|
|
309
|
+
}, alias, command, options);
|
|
368
310
|
}
|
|
369
|
-
/**
|
|
370
|
-
* 向 PTY 写入数据
|
|
371
|
-
*/
|
|
372
311
|
ptyWrite(ptyId, data) {
|
|
373
|
-
|
|
374
|
-
if (!ptySession) {
|
|
375
|
-
throw new Error(`PTY session '${ptyId}' not found`);
|
|
376
|
-
}
|
|
377
|
-
if (!ptySession.active) {
|
|
378
|
-
throw new Error(`PTY session '${ptyId}' is closed`);
|
|
379
|
-
}
|
|
380
|
-
return ptySession.stream.write(data);
|
|
312
|
+
return this.ptyManager.write(ptyId, data);
|
|
381
313
|
}
|
|
382
|
-
/**
|
|
383
|
-
* 读取 PTY 输出
|
|
384
|
-
*
|
|
385
|
-
* options.mode: 'screen' 返回当前屏幕内容,'raw' 返回原始 ANSI 流
|
|
386
|
-
*/
|
|
387
314
|
ptyRead(ptyId, options = {}) {
|
|
388
|
-
|
|
389
|
-
if (!ptySession) {
|
|
390
|
-
throw new Error(`PTY session '${ptyId}' not found`);
|
|
391
|
-
}
|
|
392
|
-
const mode = options.mode || 'screen';
|
|
393
|
-
const clear = options.clear !== false;
|
|
394
|
-
let data;
|
|
395
|
-
if (mode === 'screen') {
|
|
396
|
-
// 返回当前屏幕内容(解析后的纯文本)
|
|
397
|
-
data = this.getScreenContent(ptySession.terminal);
|
|
398
|
-
}
|
|
399
|
-
else {
|
|
400
|
-
// 返回原始 ANSI 流
|
|
401
|
-
data = ptySession.rawBuffer;
|
|
402
|
-
if (clear) {
|
|
403
|
-
ptySession.rawBuffer = '';
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
ptySession.lastReadAt = Date.now();
|
|
407
|
-
return {
|
|
408
|
-
data,
|
|
409
|
-
active: ptySession.active,
|
|
410
|
-
rows: ptySession.rows,
|
|
411
|
-
cols: ptySession.cols,
|
|
412
|
-
};
|
|
315
|
+
return this.ptyManager.read(ptyId, options);
|
|
413
316
|
}
|
|
414
|
-
/**
|
|
415
|
-
* 调整 PTY 窗口大小
|
|
416
|
-
*/
|
|
417
317
|
ptyResize(ptyId, rows, cols) {
|
|
418
|
-
|
|
419
|
-
if (!ptySession) {
|
|
420
|
-
throw new Error(`PTY session '${ptyId}' not found`);
|
|
421
|
-
}
|
|
422
|
-
if (!ptySession.active) {
|
|
423
|
-
throw new Error(`PTY session '${ptyId}' is closed`);
|
|
424
|
-
}
|
|
425
|
-
// 调整远程 PTY 窗口
|
|
426
|
-
ptySession.stream.setWindow(rows, cols, 0, 0);
|
|
427
|
-
// 调整本地终端仿真器
|
|
428
|
-
ptySession.terminal.resize(cols, rows);
|
|
429
|
-
ptySession.rows = rows;
|
|
430
|
-
ptySession.cols = cols;
|
|
431
|
-
return true;
|
|
318
|
+
return this.ptyManager.resize(ptyId, rows, cols);
|
|
432
319
|
}
|
|
433
|
-
/**
|
|
434
|
-
* 关闭 PTY 会话
|
|
435
|
-
*/
|
|
436
320
|
ptyClose(ptyId) {
|
|
437
|
-
|
|
438
|
-
if (!ptySession) {
|
|
439
|
-
return false;
|
|
440
|
-
}
|
|
441
|
-
try {
|
|
442
|
-
ptySession.stream.close();
|
|
443
|
-
}
|
|
444
|
-
catch { /* 忽略清理异常 */
|
|
445
|
-
}
|
|
446
|
-
try {
|
|
447
|
-
ptySession.terminal.dispose();
|
|
448
|
-
}
|
|
449
|
-
catch { /* 忽略清理异常 */
|
|
450
|
-
}
|
|
451
|
-
ptySession.active = false;
|
|
452
|
-
this.ptySessions.delete(ptyId);
|
|
453
|
-
return true;
|
|
321
|
+
return this.ptyManager.close(ptyId);
|
|
454
322
|
}
|
|
455
|
-
/**
|
|
456
|
-
* 列出所有 PTY 会话
|
|
457
|
-
*/
|
|
458
323
|
ptyList() {
|
|
459
|
-
|
|
460
|
-
for (const [id, pty] of this.ptySessions) {
|
|
461
|
-
result.push({
|
|
462
|
-
id,
|
|
463
|
-
alias: pty.alias,
|
|
464
|
-
command: pty.command,
|
|
465
|
-
rows: pty.rows,
|
|
466
|
-
cols: pty.cols,
|
|
467
|
-
createdAt: pty.createdAt,
|
|
468
|
-
lastReadAt: pty.lastReadAt,
|
|
469
|
-
bufferSize: pty.rawBuffer.length,
|
|
470
|
-
active: pty.active,
|
|
471
|
-
});
|
|
472
|
-
}
|
|
473
|
-
return result;
|
|
324
|
+
return this.ptyManager.list();
|
|
474
325
|
}
|
|
475
|
-
|
|
476
|
-
* 创建本地端口转发
|
|
477
|
-
* 本地监听 localHost:localPort,转发到远程 remoteHost:remotePort
|
|
478
|
-
*/
|
|
326
|
+
// ===== Forward 委托 =====
|
|
479
327
|
async forwardLocal(alias, localPort, remoteHost, remotePort, localHost = '127.0.0.1') {
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
}
|
|
489
|
-
socket.pipe(stream).pipe(socket);
|
|
490
|
-
});
|
|
491
|
-
});
|
|
492
|
-
server.on('error', (err) => {
|
|
493
|
-
reject(new Error(`Local forward failed: ${err.message}`));
|
|
494
|
-
});
|
|
495
|
-
server.listen(localPort, localHost, () => {
|
|
496
|
-
const fwdSession = {
|
|
497
|
-
id: forwardId,
|
|
498
|
-
alias,
|
|
499
|
-
type: 'local',
|
|
500
|
-
localHost,
|
|
501
|
-
localPort,
|
|
502
|
-
remoteHost,
|
|
503
|
-
remotePort,
|
|
504
|
-
server,
|
|
505
|
-
createdAt: Date.now(),
|
|
506
|
-
active: true,
|
|
507
|
-
};
|
|
508
|
-
this.forwardSessions.set(forwardId, fwdSession);
|
|
509
|
-
resolve(forwardId);
|
|
510
|
-
});
|
|
328
|
+
return this.forwardManager.forwardLocal({ getClient: (a) => this.getSession(a).client }, alias, localPort, remoteHost, remotePort, localHost);
|
|
329
|
+
}
|
|
330
|
+
async forwardRemote(alias, remotePort, localHost, localPort, remoteHost = '127.0.0.1') {
|
|
331
|
+
return this.forwardManager.forwardRemote({ getClient: (a) => this.getSession(a).client }, alias, remotePort, localHost, localPort, remoteHost);
|
|
332
|
+
}
|
|
333
|
+
forwardClose(forwardId) {
|
|
334
|
+
return this.forwardManager.close(forwardId, {
|
|
335
|
+
getClient: (a) => this.getSession(a).client,
|
|
511
336
|
});
|
|
512
337
|
}
|
|
338
|
+
forwardList() {
|
|
339
|
+
return this.forwardManager.list();
|
|
340
|
+
}
|
|
513
341
|
/**
|
|
514
|
-
*
|
|
515
|
-
* 远程监听 remoteHost:remotePort,转发到本地 localHost:localPort
|
|
342
|
+
* 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
|
|
516
343
|
*/
|
|
517
|
-
|
|
344
|
+
execPtyStream(alias, command, options) {
|
|
518
345
|
const session = this.getSession(alias);
|
|
519
|
-
const
|
|
346
|
+
const fullCommand = this.buildCommand(command, session, { env: options.env, cwd: options.cwd });
|
|
520
347
|
return new Promise((resolve, reject) => {
|
|
521
|
-
session.client.
|
|
348
|
+
session.client.exec(fullCommand, {
|
|
349
|
+
pty: {
|
|
350
|
+
rows: options.rows || 24,
|
|
351
|
+
cols: options.cols || 80,
|
|
352
|
+
term: options.term || 'xterm-256color',
|
|
353
|
+
},
|
|
354
|
+
}, (err, stream) => {
|
|
522
355
|
if (err) {
|
|
523
|
-
reject(new Error(`
|
|
524
|
-
return;
|
|
356
|
+
reject(new Error(`PTY exec failed: ${err.message}`));
|
|
525
357
|
}
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
alias,
|
|
529
|
-
type: 'remote',
|
|
530
|
-
localHost,
|
|
531
|
-
localPort,
|
|
532
|
-
remoteHost,
|
|
533
|
-
remotePort,
|
|
534
|
-
createdAt: Date.now(),
|
|
535
|
-
active: true,
|
|
536
|
-
};
|
|
537
|
-
this.forwardSessions.set(forwardId, fwdSession);
|
|
538
|
-
// 确保该 session 有共享的 tcp dispatcher
|
|
539
|
-
this.ensureTcpDispatcher(session, alias);
|
|
540
|
-
resolve(forwardId);
|
|
541
|
-
});
|
|
542
|
-
});
|
|
543
|
-
}
|
|
544
|
-
/**
|
|
545
|
-
* 关闭端口转发
|
|
546
|
-
*/
|
|
547
|
-
forwardClose(forwardId) {
|
|
548
|
-
const fwdSession = this.forwardSessions.get(forwardId);
|
|
549
|
-
if (!fwdSession) {
|
|
550
|
-
return false;
|
|
551
|
-
}
|
|
552
|
-
fwdSession.active = false;
|
|
553
|
-
if (fwdSession.type === 'local' && fwdSession.server) {
|
|
554
|
-
try {
|
|
555
|
-
fwdSession.server.close();
|
|
556
|
-
}
|
|
557
|
-
catch { /* 忽略清理异常 */
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
else if (fwdSession.type === 'remote') {
|
|
561
|
-
const session = this.sessions.get(fwdSession.alias);
|
|
562
|
-
if (session) {
|
|
563
|
-
try {
|
|
564
|
-
session.client.unforwardIn(fwdSession.remoteHost, fwdSession.remotePort);
|
|
565
|
-
}
|
|
566
|
-
catch { /* 忽略清理异常 */
|
|
358
|
+
else {
|
|
359
|
+
resolve(stream);
|
|
567
360
|
}
|
|
568
|
-
// 检查是否需要移除共享 dispatcher
|
|
569
|
-
this.removeTcpDispatcherIfEmpty(session, fwdSession.alias);
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
this.forwardSessions.delete(forwardId);
|
|
573
|
-
return true;
|
|
574
|
-
}
|
|
575
|
-
/**
|
|
576
|
-
* 列出所有端口转发
|
|
577
|
-
*/
|
|
578
|
-
forwardList() {
|
|
579
|
-
const result = [];
|
|
580
|
-
for (const [id, fwd] of this.forwardSessions) {
|
|
581
|
-
result.push({
|
|
582
|
-
id,
|
|
583
|
-
alias: fwd.alias,
|
|
584
|
-
type: fwd.type,
|
|
585
|
-
localHost: fwd.localHost,
|
|
586
|
-
localPort: fwd.localPort,
|
|
587
|
-
remoteHost: fwd.remoteHost,
|
|
588
|
-
remotePort: fwd.remotePort,
|
|
589
|
-
createdAt: fwd.createdAt,
|
|
590
|
-
active: fwd.active,
|
|
591
361
|
});
|
|
592
|
-
}
|
|
593
|
-
return result;
|
|
362
|
+
});
|
|
594
363
|
}
|
|
595
364
|
ensurePersistDir() {
|
|
596
365
|
const dir = path.dirname(this.persistPath);
|
|
@@ -625,6 +394,50 @@ export class SessionManager {
|
|
|
625
394
|
isAlive(session) {
|
|
626
395
|
return session.connected;
|
|
627
396
|
}
|
|
397
|
+
/**
|
|
398
|
+
* 调度自动重连(支持多次重试)
|
|
399
|
+
*/
|
|
400
|
+
scheduleReconnect(alias) {
|
|
401
|
+
const session = this.sessions.get(alias);
|
|
402
|
+
if (!session || session.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
session.reconnectAttempts++;
|
|
406
|
+
const attempt = session.reconnectAttempts;
|
|
407
|
+
setTimeout(async () => {
|
|
408
|
+
try {
|
|
409
|
+
await this.reconnect(alias);
|
|
410
|
+
}
|
|
411
|
+
catch (err) {
|
|
412
|
+
console.error(`Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}):`, err.message);
|
|
413
|
+
// reconnect 失败后继续调度下一次尝试
|
|
414
|
+
this.scheduleReconnect(alias);
|
|
415
|
+
}
|
|
416
|
+
}, this.reconnectDelay);
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* 根据错误类型生成排查建议
|
|
420
|
+
*/
|
|
421
|
+
diagnoseConnectionError(err) {
|
|
422
|
+
const msg = err.message || '';
|
|
423
|
+
const code = err.code || '';
|
|
424
|
+
if (code === 'ECONNREFUSED' || msg.includes('ECONNREFUSED')) {
|
|
425
|
+
return 'check if SSH service is running on the target host';
|
|
426
|
+
}
|
|
427
|
+
if (code === 'ETIMEDOUT' || msg.includes('ETIMEDOUT') || msg.includes('Timed out')) {
|
|
428
|
+
return 'check host reachability, firewall rules, or try a jump host';
|
|
429
|
+
}
|
|
430
|
+
if (code === 'ENOTFOUND' || msg.includes('ENOTFOUND') || msg.includes('getaddrinfo')) {
|
|
431
|
+
return 'hostname cannot be resolved, check DNS or use IP address';
|
|
432
|
+
}
|
|
433
|
+
if (msg.includes('All configured authentication methods failed')) {
|
|
434
|
+
return 'check password, key path, or key permissions (chmod 600)';
|
|
435
|
+
}
|
|
436
|
+
if (msg.includes('ECONNRESET') || msg.includes('Connection reset')) {
|
|
437
|
+
return 'connection was reset by the remote host';
|
|
438
|
+
}
|
|
439
|
+
return '';
|
|
440
|
+
}
|
|
628
441
|
/**
|
|
629
442
|
* 转义 shell 参数(使用单引号方式)
|
|
630
443
|
*/
|
|
@@ -697,84 +510,6 @@ export class SessionManager {
|
|
|
697
510
|
// 忽略写入错误
|
|
698
511
|
}
|
|
699
512
|
}
|
|
700
|
-
/**
|
|
701
|
-
* 生成 PTY 会话 ID
|
|
702
|
-
*/
|
|
703
|
-
generatePtyId() {
|
|
704
|
-
return `pty_${++this.ptyIdCounter}_${Date.now()}`;
|
|
705
|
-
}
|
|
706
|
-
/**
|
|
707
|
-
* 从终端仿真器获取当前屏幕内容
|
|
708
|
-
*/
|
|
709
|
-
getScreenContent(terminal) {
|
|
710
|
-
const buffer = terminal.buffer.active;
|
|
711
|
-
const lines = [];
|
|
712
|
-
for (let i = 0; i < terminal.rows; i++) {
|
|
713
|
-
const line = buffer.getLine(i);
|
|
714
|
-
if (line) {
|
|
715
|
-
lines.push(line.translateToString(true));
|
|
716
|
-
}
|
|
717
|
-
}
|
|
718
|
-
// 移除尾部空行
|
|
719
|
-
while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
|
|
720
|
-
lines.pop();
|
|
721
|
-
}
|
|
722
|
-
return lines.join('\n');
|
|
723
|
-
}
|
|
724
|
-
/**
|
|
725
|
-
* 生成端口转发 ID
|
|
726
|
-
*/
|
|
727
|
-
generateForwardId() {
|
|
728
|
-
return `fwd_${++this.forwardIdCounter}_${Date.now()}`;
|
|
729
|
-
}
|
|
730
|
-
/**
|
|
731
|
-
* 确保 SSH session 有共享的 tcp connection dispatcher
|
|
732
|
-
* 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
|
|
733
|
-
*/
|
|
734
|
-
ensureTcpDispatcher(session, alias) {
|
|
735
|
-
if (session.tcpDispatcher) {
|
|
736
|
-
return; // 已存在
|
|
737
|
-
}
|
|
738
|
-
const dispatcher = (info, accept, rejectConn) => {
|
|
739
|
-
// 查找匹配的 remote forward
|
|
740
|
-
for (const fwd of this.forwardSessions.values()) {
|
|
741
|
-
if (fwd.type === 'remote' &&
|
|
742
|
-
fwd.active &&
|
|
743
|
-
fwd.alias === alias &&
|
|
744
|
-
fwd.remoteHost === info.destIP &&
|
|
745
|
-
fwd.remotePort === info.destPort) {
|
|
746
|
-
// 找到匹配的 forward,建立连接
|
|
747
|
-
const stream = accept();
|
|
748
|
-
const socket = net.createConnection(fwd.localPort, fwd.localHost);
|
|
749
|
-
socket.pipe(stream).pipe(socket);
|
|
750
|
-
socket.on('error', () => stream.close());
|
|
751
|
-
stream.on('error', () => socket.destroy());
|
|
752
|
-
return;
|
|
753
|
-
}
|
|
754
|
-
}
|
|
755
|
-
// 没有匹配的 forward,拒绝连接
|
|
756
|
-
rejectConn();
|
|
757
|
-
};
|
|
758
|
-
session.tcpDispatcher = dispatcher;
|
|
759
|
-
session.client.on('tcp connection', dispatcher);
|
|
760
|
-
}
|
|
761
|
-
/**
|
|
762
|
-
* 移除 SSH session 的 tcp dispatcher(当没有 remote forward 时)
|
|
763
|
-
*/
|
|
764
|
-
removeTcpDispatcherIfEmpty(session, alias) {
|
|
765
|
-
if (!session.tcpDispatcher) {
|
|
766
|
-
return;
|
|
767
|
-
}
|
|
768
|
-
// 检查是否还有该 session 的 remote forward
|
|
769
|
-
for (const fwd of this.forwardSessions.values()) {
|
|
770
|
-
if (fwd.type === 'remote' && fwd.alias === alias && fwd.active) {
|
|
771
|
-
return; // 还有活跃的 remote forward
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
// 没有了,移除 dispatcher
|
|
775
|
-
session.client.removeListener('tcp connection', session.tcpDispatcher);
|
|
776
|
-
session.tcpDispatcher = undefined;
|
|
777
|
-
}
|
|
778
513
|
}
|
|
779
514
|
// 全局单例
|
|
780
515
|
export const sessionManager = new SessionManager();
|