@pyrokine/mcp-ssh 1.1.0 → 1.1.3
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 +81 -72
- package/README_zh.md +81 -73
- package/dist/file-ops.d.ts +7 -10
- package/dist/file-ops.js +94 -176
- package/dist/index.js +8 -938
- package/dist/session-manager.d.ts +72 -67
- package/dist/session-manager.js +228 -240
- package/dist/ssh-config.d.ts +0 -4
- package/dist/ssh-config.js +3 -10
- package/dist/tools/connection.d.ts +7 -0
- package/dist/tools/connection.js +215 -0
- package/dist/tools/exec.d.ts +8 -0
- package/dist/tools/exec.js +221 -0
- package/dist/tools/file.d.ts +8 -0
- package/dist/tools/file.js +192 -0
- package/dist/tools/forward.d.ts +7 -0
- package/dist/tools/forward.js +116 -0
- package/dist/tools/index.d.ts +8 -0
- package/dist/tools/index.js +8 -0
- package/dist/tools/pty.d.ts +7 -0
- package/dist/tools/pty.js +178 -0
- package/dist/tools/utils.d.ts +22 -0
- package/dist/tools/utils.js +21 -0
- package/dist/types.d.ts +0 -7
- package/package.json +3 -2
- package/src/file-ops.ts +526 -596
- package/src/index.ts +25 -1084
- package/src/session-manager.ts +938 -945
- package/src/ssh-config.ts +183 -190
- package/src/tools/connection.ts +240 -0
- package/src/tools/exec.ts +260 -0
- package/src/tools/file.ts +219 -0
- package/src/tools/forward.ts +141 -0
- package/src/tools/index.ts +9 -0
- package/src/tools/pty.ts +203 -0
- package/src/tools/utils.ts +23 -0
- package/src/types.ts +84 -93
- package/tsconfig.json +7 -2
package/dist/session-manager.js
CHANGED
|
@@ -7,12 +7,12 @@
|
|
|
7
7
|
* - 自动重连
|
|
8
8
|
* - 会话持久化
|
|
9
9
|
*/
|
|
10
|
-
import
|
|
10
|
+
import xterm from '@xterm/headless';
|
|
11
11
|
import * as fs from 'fs';
|
|
12
|
+
import * as net from 'net';
|
|
12
13
|
import * as path from 'path';
|
|
13
|
-
import
|
|
14
|
+
import { Client } from 'ssh2';
|
|
14
15
|
const Terminal = xterm.Terminal;
|
|
15
|
-
import * as net from 'net';
|
|
16
16
|
export class SessionManager {
|
|
17
17
|
sessions = new Map();
|
|
18
18
|
ptySessions = new Map();
|
|
@@ -24,23 +24,13 @@ export class SessionManager {
|
|
|
24
24
|
defaultKeepaliveCountMax = 3;
|
|
25
25
|
defaultTimeout = 30000; // 30秒
|
|
26
26
|
maxReconnectAttempts = 3;
|
|
27
|
+
defaultMaxOutputSize = 10 * 1024 * 1024; // 10MB
|
|
28
|
+
reconnectDelay = 5000; // 5秒
|
|
27
29
|
defaultPtyBufferSize = 1024 * 1024; // 1MB
|
|
28
30
|
constructor(persistPath) {
|
|
29
31
|
this.persistPath = persistPath || path.join(process.env.HOME || '/tmp', '.ssh-mcp-pro', 'sessions.json');
|
|
30
32
|
this.ensurePersistDir();
|
|
31
33
|
}
|
|
32
|
-
ensurePersistDir() {
|
|
33
|
-
const dir = path.dirname(this.persistPath);
|
|
34
|
-
if (!fs.existsSync(dir)) {
|
|
35
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* 生成连接别名
|
|
40
|
-
*/
|
|
41
|
-
generateAlias(config) {
|
|
42
|
-
return config.alias || `${config.username}@${config.host}:${config.port}`;
|
|
43
|
-
}
|
|
44
34
|
/**
|
|
45
35
|
* 建立 SSH 连接
|
|
46
36
|
*/
|
|
@@ -81,8 +71,7 @@ export class SessionManager {
|
|
|
81
71
|
const jumpSession = this.sessions.get(jumpAlias);
|
|
82
72
|
if (jumpSession) {
|
|
83
73
|
// 通过跳板机建立连接
|
|
84
|
-
|
|
85
|
-
connectConfig.sock = stream;
|
|
74
|
+
connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port || 22);
|
|
86
75
|
}
|
|
87
76
|
}
|
|
88
77
|
return new Promise((resolve, reject) => {
|
|
@@ -114,33 +103,16 @@ export class SessionManager {
|
|
|
114
103
|
if (session.reconnectAttempts < this.maxReconnectAttempts) {
|
|
115
104
|
session.reconnectAttempts++;
|
|
116
105
|
setTimeout(() => {
|
|
117
|
-
this.reconnect(alias).catch(() => {
|
|
118
|
-
|
|
106
|
+
this.reconnect(alias).catch((err) => {
|
|
107
|
+
console.error(`Auto-reconnect failed for ${alias}:`, err.message);
|
|
108
|
+
});
|
|
109
|
+
}, this.reconnectDelay);
|
|
119
110
|
}
|
|
120
111
|
}
|
|
121
112
|
});
|
|
122
113
|
client.connect(connectConfig);
|
|
123
114
|
});
|
|
124
115
|
}
|
|
125
|
-
/**
|
|
126
|
-
* 通过跳板机转发连接
|
|
127
|
-
*/
|
|
128
|
-
forwardConnection(jumpClient, targetHost, targetPort) {
|
|
129
|
-
return new Promise((resolve, reject) => {
|
|
130
|
-
jumpClient.forwardOut('127.0.0.1', 0, targetHost, targetPort, (err, stream) => {
|
|
131
|
-
if (err)
|
|
132
|
-
reject(err);
|
|
133
|
-
else
|
|
134
|
-
resolve(stream);
|
|
135
|
-
});
|
|
136
|
-
});
|
|
137
|
-
}
|
|
138
|
-
/**
|
|
139
|
-
* 检查连接是否存活
|
|
140
|
-
*/
|
|
141
|
-
isAlive(session) {
|
|
142
|
-
return session.connected;
|
|
143
|
-
}
|
|
144
116
|
/**
|
|
145
117
|
* 重新连接
|
|
146
118
|
*/
|
|
@@ -152,7 +124,8 @@ export class SessionManager {
|
|
|
152
124
|
try {
|
|
153
125
|
session.client.end();
|
|
154
126
|
}
|
|
155
|
-
catch {
|
|
127
|
+
catch { /* 忽略已关闭的连接 */
|
|
128
|
+
}
|
|
156
129
|
await this.connect(session.config);
|
|
157
130
|
}
|
|
158
131
|
/**
|
|
@@ -164,21 +137,14 @@ export class SessionManager {
|
|
|
164
137
|
try {
|
|
165
138
|
session.client.end();
|
|
166
139
|
}
|
|
167
|
-
catch {
|
|
140
|
+
catch { /* 忽略已关闭的连接 */
|
|
141
|
+
}
|
|
168
142
|
this.sessions.delete(alias);
|
|
169
143
|
this.persistSessions();
|
|
170
144
|
return true;
|
|
171
145
|
}
|
|
172
146
|
return false;
|
|
173
147
|
}
|
|
174
|
-
/**
|
|
175
|
-
* 断开所有连接
|
|
176
|
-
*/
|
|
177
|
-
disconnectAll() {
|
|
178
|
-
for (const alias of this.sessions.keys()) {
|
|
179
|
-
this.disconnect(alias);
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
148
|
/**
|
|
183
149
|
* 获取会话
|
|
184
150
|
*/
|
|
@@ -212,41 +178,14 @@ export class SessionManager {
|
|
|
212
178
|
}
|
|
213
179
|
return result;
|
|
214
180
|
}
|
|
215
|
-
/**
|
|
216
|
-
* 转义 shell 参数(使用单引号方式)
|
|
217
|
-
*/
|
|
218
|
-
escapeShellArg(s) {
|
|
219
|
-
return `'${s.replace(/'/g, "'\\''")}'`;
|
|
220
|
-
}
|
|
221
181
|
/**
|
|
222
182
|
* 执行命令
|
|
223
183
|
*/
|
|
224
184
|
async exec(alias, command, options = {}) {
|
|
225
185
|
const session = this.getSession(alias);
|
|
226
186
|
const startTime = Date.now();
|
|
227
|
-
const maxOutputSize = options.maxOutputSize ||
|
|
228
|
-
|
|
229
|
-
let fullCommand = command;
|
|
230
|
-
const env = { ...session.config.env, ...options.env };
|
|
231
|
-
if (Object.keys(env).length > 0) {
|
|
232
|
-
// 校验并过滤环境变量名
|
|
233
|
-
const validEnvEntries = Object.entries(env).filter(([k]) => {
|
|
234
|
-
if (!this.isValidEnvKey(k)) {
|
|
235
|
-
// 静默忽略非法环境变量名
|
|
236
|
-
return false;
|
|
237
|
-
}
|
|
238
|
-
return true;
|
|
239
|
-
});
|
|
240
|
-
if (validEnvEntries.length > 0) {
|
|
241
|
-
const envStr = validEnvEntries
|
|
242
|
-
.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
|
|
243
|
-
.join('; ');
|
|
244
|
-
fullCommand = `${envStr}; ${command}`;
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
if (options.cwd) {
|
|
248
|
-
fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`;
|
|
249
|
-
}
|
|
187
|
+
const maxOutputSize = options.maxOutputSize || this.defaultMaxOutputSize;
|
|
188
|
+
const fullCommand = this.buildCommand(command, session, options);
|
|
250
189
|
return new Promise((resolve, reject) => {
|
|
251
190
|
const timeout = options.timeout || this.defaultTimeout;
|
|
252
191
|
let timeoutId = null;
|
|
@@ -274,8 +213,9 @@ export class SessionManager {
|
|
|
274
213
|
reject(new Error(`Command timed out after ${timeout}ms`));
|
|
275
214
|
}, timeout);
|
|
276
215
|
stream.on('close', (code) => {
|
|
277
|
-
if (timeoutId)
|
|
216
|
+
if (timeoutId) {
|
|
278
217
|
clearTimeout(timeoutId);
|
|
218
|
+
}
|
|
279
219
|
resolve({
|
|
280
220
|
success: code === 0,
|
|
281
221
|
stdout: stdoutTruncated ? stdout + '\n... [truncated]' : stdout,
|
|
@@ -311,28 +251,25 @@ export class SessionManager {
|
|
|
311
251
|
});
|
|
312
252
|
});
|
|
313
253
|
}
|
|
314
|
-
/**
|
|
315
|
-
* 校验用户名(只允许字母、数字、下划线、连字符)
|
|
316
|
-
*/
|
|
317
|
-
isValidUsername(username) {
|
|
318
|
-
return /^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(username);
|
|
319
|
-
}
|
|
320
|
-
/**
|
|
321
|
-
* 校验环境变量名(只允许字母、数字、下划线,不能以数字开头)
|
|
322
|
-
*/
|
|
323
|
-
isValidEnvKey(key) {
|
|
324
|
-
return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key);
|
|
325
|
-
}
|
|
326
254
|
/**
|
|
327
255
|
* 以其他用户身份执行命令
|
|
256
|
+
*
|
|
257
|
+
* options.loadProfile 控制是否加载用户的 shell 配置(默认 true)。
|
|
258
|
+
* su -c 创建非交互式 shell,不会自动执行 rc 文件,
|
|
259
|
+
* 但大多数用户的环境变量设置在 rc 文件中,因此默认加载。
|
|
260
|
+
* 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)。
|
|
328
261
|
*/
|
|
329
262
|
async execAsUser(alias, command, targetUser, options = {}) {
|
|
330
263
|
// 校验用户名防止注入
|
|
331
264
|
if (!this.isValidUsername(targetUser)) {
|
|
332
265
|
throw new Error(`Invalid username: ${targetUser}`);
|
|
333
266
|
}
|
|
334
|
-
const
|
|
335
|
-
|
|
267
|
+
const { loadProfile = true, ...execOpts } = options;
|
|
268
|
+
const wrappedCommand = loadProfile
|
|
269
|
+
? `${this.getLoadProfileCommand()}${command}`
|
|
270
|
+
: command;
|
|
271
|
+
const suCommand = `su - ${targetUser} -c ${this.escapeShellArg(wrappedCommand)}`;
|
|
272
|
+
return this.exec(alias, suCommand, execOpts);
|
|
336
273
|
}
|
|
337
274
|
/**
|
|
338
275
|
* 使用 sudo 执行命令
|
|
@@ -355,55 +292,15 @@ export class SessionManager {
|
|
|
355
292
|
const session = this.getSession(alias);
|
|
356
293
|
return new Promise((resolve, reject) => {
|
|
357
294
|
session.client.sftp((err, sftp) => {
|
|
358
|
-
if (err)
|
|
295
|
+
if (err) {
|
|
359
296
|
reject(err);
|
|
360
|
-
|
|
297
|
+
}
|
|
298
|
+
else {
|
|
361
299
|
resolve(sftp);
|
|
300
|
+
}
|
|
362
301
|
});
|
|
363
302
|
});
|
|
364
303
|
}
|
|
365
|
-
/**
|
|
366
|
-
* 持久化会话信息
|
|
367
|
-
*/
|
|
368
|
-
persistSessions() {
|
|
369
|
-
const data = [];
|
|
370
|
-
for (const [alias, session] of this.sessions) {
|
|
371
|
-
// 不保存敏感信息(密码、密钥)
|
|
372
|
-
data.push({
|
|
373
|
-
alias,
|
|
374
|
-
host: session.config.host,
|
|
375
|
-
port: session.config.port || 22,
|
|
376
|
-
username: session.config.username,
|
|
377
|
-
connectedAt: session.connectedAt,
|
|
378
|
-
env: session.config.env,
|
|
379
|
-
});
|
|
380
|
-
}
|
|
381
|
-
try {
|
|
382
|
-
fs.writeFileSync(this.persistPath, JSON.stringify(data, null, 2));
|
|
383
|
-
}
|
|
384
|
-
catch (e) {
|
|
385
|
-
// 忽略写入错误
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
/**
|
|
389
|
-
* 加载持久化的会话信息(仅用于显示,不自动重连)
|
|
390
|
-
*/
|
|
391
|
-
loadPersistedSessions() {
|
|
392
|
-
try {
|
|
393
|
-
if (fs.existsSync(this.persistPath)) {
|
|
394
|
-
return JSON.parse(fs.readFileSync(this.persistPath, 'utf-8'));
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
catch { }
|
|
398
|
-
return [];
|
|
399
|
-
}
|
|
400
|
-
// ========== PTY 会话管理 ==========
|
|
401
|
-
/**
|
|
402
|
-
* 生成 PTY 会话 ID
|
|
403
|
-
*/
|
|
404
|
-
generatePtyId() {
|
|
405
|
-
return `pty_${++this.ptyIdCounter}_${Date.now()}`;
|
|
406
|
-
}
|
|
407
304
|
/**
|
|
408
305
|
* 启动持久化 PTY 会话
|
|
409
306
|
*/
|
|
@@ -414,18 +311,7 @@ export class SessionManager {
|
|
|
414
311
|
const cols = options.cols || 80;
|
|
415
312
|
const term = options.term || 'xterm-256color';
|
|
416
313
|
const maxBufferSize = options.bufferSize || this.defaultPtyBufferSize;
|
|
417
|
-
|
|
418
|
-
let fullCommand = command;
|
|
419
|
-
const env = { ...session.config.env, ...options.env };
|
|
420
|
-
if (Object.keys(env).length > 0) {
|
|
421
|
-
const envStr = Object.entries(env)
|
|
422
|
-
.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
|
|
423
|
-
.join('; ');
|
|
424
|
-
fullCommand = `${envStr}; ${command}`;
|
|
425
|
-
}
|
|
426
|
-
if (options.cwd) {
|
|
427
|
-
fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`;
|
|
428
|
-
}
|
|
314
|
+
const fullCommand = this.buildCommand(command, session, options);
|
|
429
315
|
return new Promise((resolve, reject) => {
|
|
430
316
|
session.client.exec(fullCommand, {
|
|
431
317
|
pty: { rows, cols, term },
|
|
@@ -456,8 +342,9 @@ export class SessionManager {
|
|
|
456
342
|
};
|
|
457
343
|
// 监听输出数据
|
|
458
344
|
stream.on('data', (data) => {
|
|
459
|
-
if (!ptySession.active)
|
|
345
|
+
if (!ptySession.active) {
|
|
460
346
|
return;
|
|
347
|
+
}
|
|
461
348
|
const chunk = data.toString('utf-8');
|
|
462
349
|
// 写入终端仿真器(解析 ANSI 序列)
|
|
463
350
|
terminal.write(chunk);
|
|
@@ -492,27 +379,10 @@ export class SessionManager {
|
|
|
492
379
|
}
|
|
493
380
|
return ptySession.stream.write(data);
|
|
494
381
|
}
|
|
495
|
-
/**
|
|
496
|
-
* 从终端仿真器获取当前屏幕内容
|
|
497
|
-
*/
|
|
498
|
-
getScreenContent(terminal) {
|
|
499
|
-
const buffer = terminal.buffer.active;
|
|
500
|
-
const lines = [];
|
|
501
|
-
for (let i = 0; i < terminal.rows; i++) {
|
|
502
|
-
const line = buffer.getLine(i);
|
|
503
|
-
if (line) {
|
|
504
|
-
lines.push(line.translateToString(true));
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
// 移除尾部空行
|
|
508
|
-
while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
|
|
509
|
-
lines.pop();
|
|
510
|
-
}
|
|
511
|
-
return lines.join('\n');
|
|
512
|
-
}
|
|
513
382
|
/**
|
|
514
383
|
* 读取 PTY 输出
|
|
515
|
-
*
|
|
384
|
+
*
|
|
385
|
+
* options.mode: 'screen' 返回当前屏幕内容,'raw' 返回原始 ANSI 流
|
|
516
386
|
*/
|
|
517
387
|
ptyRead(ptyId, options = {}) {
|
|
518
388
|
const ptySession = this.ptySessions.get(ptyId);
|
|
@@ -571,11 +441,13 @@ export class SessionManager {
|
|
|
571
441
|
try {
|
|
572
442
|
ptySession.stream.close();
|
|
573
443
|
}
|
|
574
|
-
catch {
|
|
444
|
+
catch { /* 忽略清理异常 */
|
|
445
|
+
}
|
|
575
446
|
try {
|
|
576
447
|
ptySession.terminal.dispose();
|
|
577
448
|
}
|
|
578
|
-
catch {
|
|
449
|
+
catch { /* 忽略清理异常 */
|
|
450
|
+
}
|
|
579
451
|
ptySession.active = false;
|
|
580
452
|
this.ptySessions.delete(ptyId);
|
|
581
453
|
return true;
|
|
@@ -600,25 +472,6 @@ export class SessionManager {
|
|
|
600
472
|
}
|
|
601
473
|
return result;
|
|
602
474
|
}
|
|
603
|
-
/**
|
|
604
|
-
* 关闭所有 PTY 会话
|
|
605
|
-
*/
|
|
606
|
-
ptyCloseAll() {
|
|
607
|
-
let count = 0;
|
|
608
|
-
for (const ptyId of this.ptySessions.keys()) {
|
|
609
|
-
if (this.ptyClose(ptyId)) {
|
|
610
|
-
count++;
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
return count;
|
|
614
|
-
}
|
|
615
|
-
// ========== 端口转发 ==========
|
|
616
|
-
/**
|
|
617
|
-
* 生成端口转发 ID
|
|
618
|
-
*/
|
|
619
|
-
generateForwardId() {
|
|
620
|
-
return `fwd_${++this.forwardIdCounter}_${Date.now()}`;
|
|
621
|
-
}
|
|
622
475
|
/**
|
|
623
476
|
* 创建本地端口转发
|
|
624
477
|
* 本地监听 localHost:localPort,转发到远程 remoteHost:remotePort
|
|
@@ -688,10 +541,195 @@ export class SessionManager {
|
|
|
688
541
|
});
|
|
689
542
|
});
|
|
690
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 { /* 忽略清理异常 */
|
|
567
|
+
}
|
|
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
|
+
});
|
|
592
|
+
}
|
|
593
|
+
return result;
|
|
594
|
+
}
|
|
595
|
+
ensurePersistDir() {
|
|
596
|
+
const dir = path.dirname(this.persistPath);
|
|
597
|
+
if (!fs.existsSync(dir)) {
|
|
598
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* 生成连接别名
|
|
603
|
+
*/
|
|
604
|
+
generateAlias(config) {
|
|
605
|
+
return config.alias || `${config.username}@${config.host}:${config.port}`;
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* 通过跳板机转发连接
|
|
609
|
+
*/
|
|
610
|
+
forwardConnection(jumpClient, targetHost, targetPort) {
|
|
611
|
+
return new Promise((resolve, reject) => {
|
|
612
|
+
jumpClient.forwardOut('127.0.0.1', 0, targetHost, targetPort, (err, stream) => {
|
|
613
|
+
if (err) {
|
|
614
|
+
reject(err);
|
|
615
|
+
}
|
|
616
|
+
else {
|
|
617
|
+
resolve(stream);
|
|
618
|
+
}
|
|
619
|
+
});
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* 检查连接是否存活
|
|
624
|
+
*/
|
|
625
|
+
isAlive(session) {
|
|
626
|
+
return session.connected;
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* 转义 shell 参数(使用单引号方式)
|
|
630
|
+
*/
|
|
631
|
+
escapeShellArg(s) {
|
|
632
|
+
return `'${s.replace(/'/g, '\'\\\'\'')}'`;
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* 校验用户名(只允许字母、数字、下划线、连字符)
|
|
636
|
+
*/
|
|
637
|
+
isValidUsername(username) {
|
|
638
|
+
return /^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(username);
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* 校验环境变量名(只允许字母、数字、下划线,不能以数字开头)
|
|
642
|
+
*/
|
|
643
|
+
isValidEnvKey(key) {
|
|
644
|
+
return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key);
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* 构建完整命令:注入环境变量 + 切换工作目录
|
|
648
|
+
*/
|
|
649
|
+
buildCommand(command, session, options) {
|
|
650
|
+
let fullCommand = command;
|
|
651
|
+
const env = { ...session.config.env, ...options.env };
|
|
652
|
+
if (Object.keys(env).length > 0) {
|
|
653
|
+
const validEntries = Object.entries(env).filter(([k]) => this.isValidEnvKey(k));
|
|
654
|
+
if (validEntries.length > 0) {
|
|
655
|
+
const envStr = validEntries
|
|
656
|
+
.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
|
|
657
|
+
.join('; ');
|
|
658
|
+
fullCommand = `${envStr}; ${command}`;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
if (options.cwd) {
|
|
662
|
+
fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`;
|
|
663
|
+
}
|
|
664
|
+
return fullCommand;
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* 根据用户 shell 类型生成加载配置文件的命令
|
|
668
|
+
* bash → .bashrc, zsh → .zshrc, 其他 → .profile
|
|
669
|
+
*/
|
|
670
|
+
getLoadProfileCommand() {
|
|
671
|
+
return 'case "$(basename "$SHELL" 2>/dev/null)" in ' +
|
|
672
|
+
'bash) [ -f ~/.bashrc ] && . ~/.bashrc ;; ' +
|
|
673
|
+
'zsh) [ -f ~/.zshrc ] && . ~/.zshrc ;; ' +
|
|
674
|
+
'*) [ -f ~/.profile ] && . ~/.profile ;; ' +
|
|
675
|
+
'esac 2>/dev/null; ';
|
|
676
|
+
}
|
|
677
|
+
/**
|
|
678
|
+
* 持久化会话信息
|
|
679
|
+
*/
|
|
680
|
+
persistSessions() {
|
|
681
|
+
const data = [];
|
|
682
|
+
for (const [alias, session] of this.sessions) {
|
|
683
|
+
// 不保存敏感信息(密码、密钥)
|
|
684
|
+
data.push({
|
|
685
|
+
alias,
|
|
686
|
+
host: session.config.host,
|
|
687
|
+
port: session.config.port || 22,
|
|
688
|
+
username: session.config.username,
|
|
689
|
+
connectedAt: session.connectedAt,
|
|
690
|
+
env: session.config.env,
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
try {
|
|
694
|
+
fs.writeFileSync(this.persistPath, JSON.stringify(data, null, 2));
|
|
695
|
+
}
|
|
696
|
+
catch (e) {
|
|
697
|
+
// 忽略写入错误
|
|
698
|
+
}
|
|
699
|
+
}
|
|
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
|
+
}
|
|
691
730
|
/**
|
|
692
731
|
* 确保 SSH session 有共享的 tcp connection dispatcher
|
|
693
732
|
* 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
|
|
694
|
-
* @param alias - session 的 map key
|
|
695
733
|
*/
|
|
696
734
|
ensureTcpDispatcher(session, alias) {
|
|
697
735
|
if (session.tcpDispatcher) {
|
|
@@ -722,7 +760,6 @@ export class SessionManager {
|
|
|
722
760
|
}
|
|
723
761
|
/**
|
|
724
762
|
* 移除 SSH session 的 tcp dispatcher(当没有 remote forward 时)
|
|
725
|
-
* @param alias - session 的 map key
|
|
726
763
|
*/
|
|
727
764
|
removeTcpDispatcherIfEmpty(session, alias) {
|
|
728
765
|
if (!session.tcpDispatcher) {
|
|
@@ -738,55 +775,6 @@ export class SessionManager {
|
|
|
738
775
|
session.client.removeListener('tcp connection', session.tcpDispatcher);
|
|
739
776
|
session.tcpDispatcher = undefined;
|
|
740
777
|
}
|
|
741
|
-
/**
|
|
742
|
-
* 关闭端口转发
|
|
743
|
-
*/
|
|
744
|
-
forwardClose(forwardId) {
|
|
745
|
-
const fwdSession = this.forwardSessions.get(forwardId);
|
|
746
|
-
if (!fwdSession) {
|
|
747
|
-
return false;
|
|
748
|
-
}
|
|
749
|
-
fwdSession.active = false;
|
|
750
|
-
if (fwdSession.type === 'local' && fwdSession.server) {
|
|
751
|
-
try {
|
|
752
|
-
fwdSession.server.close();
|
|
753
|
-
}
|
|
754
|
-
catch { }
|
|
755
|
-
}
|
|
756
|
-
else if (fwdSession.type === 'remote') {
|
|
757
|
-
const session = this.sessions.get(fwdSession.alias);
|
|
758
|
-
if (session) {
|
|
759
|
-
try {
|
|
760
|
-
session.client.unforwardIn(fwdSession.remoteHost, fwdSession.remotePort);
|
|
761
|
-
}
|
|
762
|
-
catch { }
|
|
763
|
-
// 检查是否需要移除共享 dispatcher
|
|
764
|
-
this.removeTcpDispatcherIfEmpty(session, fwdSession.alias);
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
this.forwardSessions.delete(forwardId);
|
|
768
|
-
return true;
|
|
769
|
-
}
|
|
770
|
-
/**
|
|
771
|
-
* 列出所有端口转发
|
|
772
|
-
*/
|
|
773
|
-
forwardList() {
|
|
774
|
-
const result = [];
|
|
775
|
-
for (const [id, fwd] of this.forwardSessions) {
|
|
776
|
-
result.push({
|
|
777
|
-
id,
|
|
778
|
-
alias: fwd.alias,
|
|
779
|
-
type: fwd.type,
|
|
780
|
-
localHost: fwd.localHost,
|
|
781
|
-
localPort: fwd.localPort,
|
|
782
|
-
remoteHost: fwd.remoteHost,
|
|
783
|
-
remotePort: fwd.remotePort,
|
|
784
|
-
createdAt: fwd.createdAt,
|
|
785
|
-
active: fwd.active,
|
|
786
|
-
});
|
|
787
|
-
}
|
|
788
|
-
return result;
|
|
789
|
-
}
|
|
790
778
|
}
|
|
791
779
|
// 全局单例
|
|
792
780
|
export const sessionManager = new SessionManager();
|
package/dist/ssh-config.d.ts
CHANGED
|
@@ -33,7 +33,3 @@ export declare function parseProxyJump(proxyJump: string): ParsedProxyJump | nul
|
|
|
33
33
|
* 跳过 Match 块(避免条件配置被误应用)
|
|
34
34
|
*/
|
|
35
35
|
export declare function parseSSHConfig(configPath?: string): SSHConfigHost[];
|
|
36
|
-
/**
|
|
37
|
-
* 根据 Host 名称获取配置
|
|
38
|
-
*/
|
|
39
|
-
export declare function getHostConfig(hostName: string, configPath?: string): SSHConfigHost | null;
|
package/dist/ssh-config.js
CHANGED
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
* - ProxyJump 解析(支持 user@host:port 格式)
|
|
9
9
|
*/
|
|
10
10
|
import * as fs from 'fs';
|
|
11
|
-
import * as path from 'path';
|
|
12
11
|
import * as os from 'os';
|
|
12
|
+
import * as path from 'path';
|
|
13
13
|
/**
|
|
14
14
|
* 解析 host:port 或 [ipv6]:port
|
|
15
15
|
* 返回 { host, port },host 不含方括号
|
|
@@ -71,7 +71,7 @@ export function parseProxyJump(proxyJump) {
|
|
|
71
71
|
return { user, host, port };
|
|
72
72
|
}
|
|
73
73
|
const { host, port } = parseHostPort(firstJump);
|
|
74
|
-
return {
|
|
74
|
+
return { host, port };
|
|
75
75
|
}
|
|
76
76
|
/**
|
|
77
77
|
* 展开 ~ 路径
|
|
@@ -92,7 +92,7 @@ function stripInlineComment(value) {
|
|
|
92
92
|
let quoteChar = '';
|
|
93
93
|
for (let i = 0; i < value.length; i++) {
|
|
94
94
|
const ch = value[i];
|
|
95
|
-
if (!inQuote && (ch === '"' || ch ===
|
|
95
|
+
if (!inQuote && (ch === '"' || ch === '\'')) {
|
|
96
96
|
inQuote = true;
|
|
97
97
|
quoteChar = ch;
|
|
98
98
|
}
|
|
@@ -207,10 +207,3 @@ export function parseSSHConfig(configPath) {
|
|
|
207
207
|
}
|
|
208
208
|
return hosts;
|
|
209
209
|
}
|
|
210
|
-
/**
|
|
211
|
-
* 根据 Host 名称获取配置
|
|
212
|
-
*/
|
|
213
|
-
export function getHostConfig(hostName, configPath) {
|
|
214
|
-
const hosts = parseSSHConfig(configPath);
|
|
215
|
-
return hosts.find(h => h.host === hostName) || null;
|
|
216
|
-
}
|