@pyrokine/mcp-ssh 1.3.0 → 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.
- package/README.md +53 -3
- package/README_zh.md +54 -8
- package/dist/file-ops.d.ts +8 -3
- package/dist/file-ops.js +363 -115
- package/dist/forward-manager.d.ts +11 -1
- package/dist/forward-manager.js +76 -6
- package/dist/index.d.ts +1 -1
- package/dist/index.js +30 -3
- package/dist/pty-manager.d.ts +7 -0
- package/dist/pty-manager.js +38 -1
- package/dist/security.d.ts +24 -0
- package/dist/security.js +81 -0
- package/dist/session-manager.d.ts +20 -7
- package/dist/session-manager.js +225 -114
- package/dist/ssh-config.js +25 -14
- package/dist/tools/connection.js +26 -29
- package/dist/tools/exec.js +25 -17
- package/dist/tools/file.js +9 -5
- package/dist/tools/forward.js +19 -15
- package/dist/tools/pty.js +6 -10
- package/dist/tools/utils.d.ts +10 -0
- package/dist/tools/utils.js +22 -0
- package/package.json +56 -42
- package/src/file-ops.ts +0 -662
- package/src/forward-manager.ts +0 -258
- package/src/index.ts +0 -62
- package/src/pty-manager.ts +0 -220
- package/src/session-manager.ts +0 -661
- package/src/ssh-config.ts +0 -257
- package/src/tools/connection.ts +0 -240
- package/src/tools/exec.ts +0 -264
- package/src/tools/file.ts +0 -219
- package/src/tools/forward.ts +0 -141
- package/src/tools/index.ts +0 -9
- package/src/tools/pty.ts +0 -203
- package/src/tools/utils.ts +0 -23
- package/src/types.ts +0 -124
- package/tsconfig.json +0 -21
package/dist/session-manager.js
CHANGED
|
@@ -11,10 +11,15 @@ import * as fs from 'fs';
|
|
|
11
11
|
import * as os from 'os';
|
|
12
12
|
import * as path from 'path';
|
|
13
13
|
import { Client } from 'ssh2';
|
|
14
|
+
import { clearRsyncCache } from './file-ops.js';
|
|
14
15
|
import { ForwardManager } from './forward-manager.js';
|
|
15
16
|
import { PtyManager } from './pty-manager.js';
|
|
17
|
+
import { sanitizeKeyError, validateKeyFile } from './security.js';
|
|
18
|
+
import { escapeShellArg, expandTilde } from './tools/utils.js';
|
|
16
19
|
export class SessionManager {
|
|
17
20
|
sessions = new Map();
|
|
21
|
+
/** per-alias connect 进行中的 Promise,防止并发 connect 同一 alias 时重复建连 */
|
|
22
|
+
connectInFlight = new Map();
|
|
18
23
|
ptyManager = new PtyManager();
|
|
19
24
|
forwardManager = new ForwardManager();
|
|
20
25
|
persistPath;
|
|
@@ -22,95 +27,27 @@ export class SessionManager {
|
|
|
22
27
|
defaultKeepaliveCountMax = 3;
|
|
23
28
|
defaultTimeout = 30000; // 30秒
|
|
24
29
|
maxReconnectAttempts = 3;
|
|
25
|
-
defaultMaxOutputSize = 10 * 1024 * 1024; // 10MB
|
|
30
|
+
defaultMaxOutputSize = 10 * 1024 * 1024; // 10*1024*1024 UTF-16 chars(ASCII 时约 10MB 字节)
|
|
26
31
|
reconnectDelay = 5000; // 5秒
|
|
27
32
|
constructor(persistPath) {
|
|
28
33
|
this.persistPath = persistPath || path.join(os.homedir(), '.ssh-mcp-pro', 'sessions.json');
|
|
29
34
|
this.ensurePersistDir();
|
|
30
35
|
}
|
|
31
36
|
/**
|
|
32
|
-
* 建立 SSH
|
|
37
|
+
* 建立 SSH 连接(per-alias mutex,防止并发 connect 同一 alias 重复建连)
|
|
33
38
|
*/
|
|
34
39
|
async connect(config) {
|
|
35
40
|
const alias = this.generateAlias(config);
|
|
36
|
-
//
|
|
37
|
-
const
|
|
38
|
-
if (
|
|
39
|
-
|
|
40
|
-
return alias;
|
|
41
|
-
}
|
|
42
|
-
const client = new Client();
|
|
43
|
-
// 构建连接配置
|
|
44
|
-
const connectConfig = {
|
|
45
|
-
host: config.host,
|
|
46
|
-
port: config.port || 22,
|
|
47
|
-
username: config.username,
|
|
48
|
-
readyTimeout: config.readyTimeout || this.defaultTimeout,
|
|
49
|
-
keepaliveInterval: config.keepaliveInterval || this.defaultKeepaliveInterval,
|
|
50
|
-
keepaliveCountMax: config.keepaliveCountMax || this.defaultKeepaliveCountMax,
|
|
51
|
-
};
|
|
52
|
-
// 认证方式
|
|
53
|
-
if (config.password) {
|
|
54
|
-
connectConfig.password = config.password;
|
|
55
|
-
}
|
|
56
|
-
if (config.privateKeyPath) {
|
|
57
|
-
connectConfig.privateKey = fs.readFileSync(config.privateKeyPath);
|
|
58
|
-
}
|
|
59
|
-
if (config.privateKey) {
|
|
60
|
-
connectConfig.privateKey = config.privateKey;
|
|
61
|
-
}
|
|
62
|
-
if (config.passphrase) {
|
|
63
|
-
connectConfig.passphrase = config.passphrase;
|
|
64
|
-
}
|
|
65
|
-
// 跳板机支持
|
|
66
|
-
if (config.jumpHost) {
|
|
67
|
-
const jumpAlias = await this.connect(config.jumpHost);
|
|
68
|
-
const jumpSession = this.sessions.get(jumpAlias);
|
|
69
|
-
if (jumpSession) {
|
|
70
|
-
// 通过跳板机建立连接
|
|
71
|
-
connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port || 22);
|
|
72
|
-
}
|
|
41
|
+
// 复用同 alias 的 in-flight connect Promise
|
|
42
|
+
const inFlight = this.connectInFlight.get(alias);
|
|
43
|
+
if (inFlight) {
|
|
44
|
+
return inFlight;
|
|
73
45
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
const session = {
|
|
77
|
-
client,
|
|
78
|
-
config,
|
|
79
|
-
connectedAt: Date.now(),
|
|
80
|
-
lastUsedAt: Date.now(),
|
|
81
|
-
reconnectAttempts: 0,
|
|
82
|
-
connected: true,
|
|
83
|
-
manualClose: false,
|
|
84
|
-
};
|
|
85
|
-
this.sessions.set(alias, session);
|
|
86
|
-
this.persistSessions();
|
|
87
|
-
resolve(alias);
|
|
88
|
-
});
|
|
89
|
-
client.on('error', (err) => {
|
|
90
|
-
const session = this.sessions.get(alias);
|
|
91
|
-
if (session && session.client === client) {
|
|
92
|
-
session.connected = false;
|
|
93
|
-
}
|
|
94
|
-
const target = `${connectConfig.username}@${connectConfig.host}:${connectConfig.port}`;
|
|
95
|
-
const suggestion = this.diagnoseConnectionError(err);
|
|
96
|
-
reject(new Error(`SSH connection to ${target} failed: ${err.message}${suggestion ?
|
|
97
|
-
` (${suggestion})` :
|
|
98
|
-
''}`));
|
|
99
|
-
});
|
|
100
|
-
client.on('close', () => {
|
|
101
|
-
const session = this.sessions.get(alias);
|
|
102
|
-
if (session && session.client === client) {
|
|
103
|
-
session.connected = false;
|
|
104
|
-
// 清理绑定旧 client 的 forward/PTY 资源
|
|
105
|
-
this.forwardManager.closeByAlias(alias);
|
|
106
|
-
this.ptyManager.closeByAlias(alias);
|
|
107
|
-
if (!session.manualClose) {
|
|
108
|
-
this.scheduleReconnect(alias);
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
});
|
|
112
|
-
client.connect(connectConfig);
|
|
46
|
+
const promise = this.connectInternal(config, alias).finally(() => {
|
|
47
|
+
this.connectInFlight.delete(alias);
|
|
113
48
|
});
|
|
49
|
+
this.connectInFlight.set(alias, promise);
|
|
50
|
+
return promise;
|
|
114
51
|
}
|
|
115
52
|
/**
|
|
116
53
|
* 重新连接
|
|
@@ -125,7 +62,8 @@ export class SessionManager {
|
|
|
125
62
|
try {
|
|
126
63
|
session.client.end();
|
|
127
64
|
}
|
|
128
|
-
catch {
|
|
65
|
+
catch {
|
|
66
|
+
/* 忽略已关闭的连接 */
|
|
129
67
|
}
|
|
130
68
|
await this.connect(session.config);
|
|
131
69
|
}
|
|
@@ -136,13 +74,21 @@ export class SessionManager {
|
|
|
136
74
|
const session = this.sessions.get(alias);
|
|
137
75
|
if (session) {
|
|
138
76
|
session.manualClose = true;
|
|
77
|
+
// 清掉重连定时器,防止 disconnect 后还在尝试自动重连
|
|
78
|
+
if (session.reconnectTimer) {
|
|
79
|
+
clearTimeout(session.reconnectTimer);
|
|
80
|
+
session.reconnectTimer = undefined;
|
|
81
|
+
}
|
|
139
82
|
// 清理关联的 PTY 和 forward 资源
|
|
140
83
|
this.ptyManager.closeByAlias(alias);
|
|
141
84
|
this.forwardManager.closeByAlias(alias);
|
|
85
|
+
// 清理 file-ops 中的 rsync 可用性缓存,防止重连到不同主机后读到旧判断
|
|
86
|
+
clearRsyncCache(alias);
|
|
142
87
|
try {
|
|
143
88
|
session.client.end();
|
|
144
89
|
}
|
|
145
|
-
catch {
|
|
90
|
+
catch {
|
|
91
|
+
/* 忽略已关闭的连接 */
|
|
146
92
|
}
|
|
147
93
|
this.sessions.delete(alias);
|
|
148
94
|
this.persistSessions();
|
|
@@ -150,6 +96,13 @@ export class SessionManager {
|
|
|
150
96
|
}
|
|
151
97
|
return false;
|
|
152
98
|
}
|
|
99
|
+
/** 断开所有活跃会话(SIGINT/SIGTERM 时调用) */
|
|
100
|
+
async disconnectAll() {
|
|
101
|
+
const aliases = Array.from(this.sessions.keys());
|
|
102
|
+
for (const alias of aliases) {
|
|
103
|
+
this.disconnect(alias);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
153
106
|
/**
|
|
154
107
|
* 获取会话
|
|
155
108
|
*/
|
|
@@ -189,10 +142,10 @@ export class SessionManager {
|
|
|
189
142
|
async exec(alias, command, options = {}) {
|
|
190
143
|
const session = this.getSession(alias);
|
|
191
144
|
const startTime = Date.now();
|
|
192
|
-
const maxOutputSize = options.maxOutputSize
|
|
145
|
+
const maxOutputSize = options.maxOutputSize ?? this.defaultMaxOutputSize;
|
|
193
146
|
const fullCommand = this.buildCommand(command, session, options);
|
|
194
147
|
return new Promise((resolve, reject) => {
|
|
195
|
-
const timeout = options.timeout
|
|
148
|
+
const timeout = options.timeout ?? this.defaultTimeout;
|
|
196
149
|
let timeoutId = null;
|
|
197
150
|
let stdout = '';
|
|
198
151
|
let stderr = '';
|
|
@@ -259,10 +212,10 @@ export class SessionManager {
|
|
|
259
212
|
/**
|
|
260
213
|
* 以其他用户身份执行命令
|
|
261
214
|
*
|
|
262
|
-
* options.loadProfile 控制是否加载用户的 shell 配置(默认 true
|
|
215
|
+
* options.loadProfile 控制是否加载用户的 shell 配置(默认 true)
|
|
263
216
|
* su -c 创建非交互式 shell,不会自动执行 rc 文件,
|
|
264
|
-
* 但大多数用户的环境变量设置在 rc
|
|
265
|
-
* 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)
|
|
217
|
+
* 但大多数用户的环境变量设置在 rc 文件中,因此默认加载
|
|
218
|
+
* 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)
|
|
266
219
|
*/
|
|
267
220
|
async execAsUser(alias, command, targetUser, options = {}) {
|
|
268
221
|
// 校验用户名防止注入
|
|
@@ -270,25 +223,95 @@ export class SessionManager {
|
|
|
270
223
|
throw new Error(`Invalid username: ${targetUser}`);
|
|
271
224
|
}
|
|
272
225
|
const { loadProfile = true, ...execOpts } = options;
|
|
273
|
-
const wrappedCommand = loadProfile
|
|
274
|
-
? `${this.getLoadProfileCommand()}${command}`
|
|
275
|
-
: command;
|
|
226
|
+
const wrappedCommand = loadProfile ? `${this.getLoadProfileCommand()}${command}` : command;
|
|
276
227
|
const suCommand = `su - ${targetUser} -c ${this.escapeShellArg(wrappedCommand)}`;
|
|
277
228
|
return this.exec(alias, suCommand, execOpts);
|
|
278
229
|
}
|
|
279
230
|
/**
|
|
280
231
|
* 使用 sudo 执行命令
|
|
232
|
+
*
|
|
233
|
+
* 通过 stdin 传递密码,避免密码出现在进程列表和 audit 日志中
|
|
281
234
|
*/
|
|
282
235
|
async execSudo(alias, command, sudoPassword, options = {}) {
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
// 通过 stdin 传递密码(使用 escapeShellArg 转义)
|
|
286
|
-
sudoCommand = `echo ${this.escapeShellArg(sudoPassword)} | sudo -S ${command}`;
|
|
236
|
+
if (!sudoPassword) {
|
|
237
|
+
return this.exec(alias, `sudo ${command}`, options);
|
|
287
238
|
}
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
239
|
+
const session = this.getSession(alias);
|
|
240
|
+
const startTime = Date.now();
|
|
241
|
+
const timeout = options.timeout ?? this.defaultTimeout;
|
|
242
|
+
const maxOutputSize = options.maxOutputSize ?? this.defaultMaxOutputSize;
|
|
243
|
+
const fullCommand = this.buildCommand(`sudo -S ${command}`, session, options);
|
|
244
|
+
return new Promise((resolve, reject) => {
|
|
245
|
+
let settled = false;
|
|
246
|
+
let streamRef = null;
|
|
247
|
+
const timeoutId = setTimeout(() => {
|
|
248
|
+
if (settled) {
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
settled = true;
|
|
252
|
+
try {
|
|
253
|
+
streamRef?.close();
|
|
254
|
+
}
|
|
255
|
+
catch {
|
|
256
|
+
// ignore
|
|
257
|
+
}
|
|
258
|
+
reject(new Error(`Command timed out after ${timeout}ms`));
|
|
259
|
+
}, timeout);
|
|
260
|
+
session.client.exec(fullCommand, {}, (err, stream) => {
|
|
261
|
+
if (err) {
|
|
262
|
+
clearTimeout(timeoutId);
|
|
263
|
+
settled = true;
|
|
264
|
+
reject(new Error(`Exec failed: ${err.message}`));
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
streamRef = stream;
|
|
268
|
+
// 密码写入 stdin,sudo -S 从 stdin 读取,不出现在命令行
|
|
269
|
+
stream.write(sudoPassword + '\n');
|
|
270
|
+
stream.end();
|
|
271
|
+
let stdout = '';
|
|
272
|
+
let stderr = '';
|
|
273
|
+
let stdoutTruncated = false;
|
|
274
|
+
let stderrTruncated = false;
|
|
275
|
+
stream.on('close', (code) => {
|
|
276
|
+
clearTimeout(timeoutId);
|
|
277
|
+
if (settled) {
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
settled = true;
|
|
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
|
+
stream.on('data', (data) => {
|
|
290
|
+
if (!stdoutTruncated) {
|
|
291
|
+
const chunk = data.toString('utf-8');
|
|
292
|
+
if (stdout.length + chunk.length > maxOutputSize) {
|
|
293
|
+
stdout += chunk.slice(0, maxOutputSize - stdout.length);
|
|
294
|
+
stdoutTruncated = true;
|
|
295
|
+
}
|
|
296
|
+
else {
|
|
297
|
+
stdout += chunk;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
stream.stderr.on('data', (data) => {
|
|
302
|
+
if (!stderrTruncated) {
|
|
303
|
+
const chunk = data.toString('utf-8');
|
|
304
|
+
if (stderr.length + chunk.length > maxOutputSize) {
|
|
305
|
+
stderr += chunk.slice(0, maxOutputSize - stderr.length);
|
|
306
|
+
stderrTruncated = true;
|
|
307
|
+
}
|
|
308
|
+
else {
|
|
309
|
+
stderr += chunk;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
});
|
|
313
|
+
});
|
|
314
|
+
});
|
|
292
315
|
}
|
|
293
316
|
/**
|
|
294
317
|
* 获取 SFTP 客户端
|
|
@@ -306,12 +329,12 @@ export class SessionManager {
|
|
|
306
329
|
});
|
|
307
330
|
});
|
|
308
331
|
}
|
|
309
|
-
// ===== PTY 委托 =====
|
|
310
332
|
async ptyStart(alias, command, options = {}) {
|
|
311
333
|
return this.ptyManager.start({
|
|
312
334
|
execPty: (a, cmd, opts) => this.execPtyStream(a, cmd, opts),
|
|
313
335
|
}, alias, command, options);
|
|
314
336
|
}
|
|
337
|
+
// ===== PTY 委托 =====
|
|
315
338
|
ptyWrite(ptyId, data) {
|
|
316
339
|
return this.ptyManager.write(ptyId, data);
|
|
317
340
|
}
|
|
@@ -327,10 +350,10 @@ export class SessionManager {
|
|
|
327
350
|
ptyList() {
|
|
328
351
|
return this.ptyManager.list();
|
|
329
352
|
}
|
|
330
|
-
// ===== Forward 委托 =====
|
|
331
353
|
async forwardLocal(alias, localPort, remoteHost, remotePort, localHost = '127.0.0.1') {
|
|
332
354
|
return this.forwardManager.forwardLocal({ getClient: (a) => this.getSession(a).client }, alias, localPort, remoteHost, remotePort, localHost);
|
|
333
355
|
}
|
|
356
|
+
// ===== Forward 委托 =====
|
|
334
357
|
async forwardRemote(alias, remotePort, localHost, localPort, remoteHost = '127.0.0.1') {
|
|
335
358
|
return this.forwardManager.forwardRemote({ getClient: (a) => this.getSession(a).client }, alias, remotePort, localHost, localPort, remoteHost);
|
|
336
359
|
}
|
|
@@ -342,6 +365,88 @@ export class SessionManager {
|
|
|
342
365
|
forwardList() {
|
|
343
366
|
return this.forwardManager.list();
|
|
344
367
|
}
|
|
368
|
+
async connectInternal(config, alias) {
|
|
369
|
+
// 检查是否已有活跃连接
|
|
370
|
+
const existing = this.sessions.get(alias);
|
|
371
|
+
if (existing && this.isAlive(existing)) {
|
|
372
|
+
existing.lastUsedAt = Date.now();
|
|
373
|
+
return alias;
|
|
374
|
+
}
|
|
375
|
+
const client = new Client();
|
|
376
|
+
// 构建连接配置
|
|
377
|
+
const connectConfig = {
|
|
378
|
+
host: config.host,
|
|
379
|
+
port: config.port ?? 22,
|
|
380
|
+
username: config.username,
|
|
381
|
+
readyTimeout: config.readyTimeout ?? this.defaultTimeout,
|
|
382
|
+
keepaliveInterval: config.keepaliveInterval ?? this.defaultKeepaliveInterval,
|
|
383
|
+
keepaliveCountMax: config.keepaliveCountMax ?? this.defaultKeepaliveCountMax,
|
|
384
|
+
};
|
|
385
|
+
// 认证方式
|
|
386
|
+
if (config.password) {
|
|
387
|
+
connectConfig.password = config.password;
|
|
388
|
+
}
|
|
389
|
+
if (config.privateKeyPath) {
|
|
390
|
+
const keyPath = expandTilde(config.privateKeyPath);
|
|
391
|
+
// 路径白名单 + 大小上限校验,避免任意文件读取
|
|
392
|
+
validateKeyFile(keyPath);
|
|
393
|
+
connectConfig.privateKey = fs.readFileSync(keyPath);
|
|
394
|
+
}
|
|
395
|
+
if (config.privateKey) {
|
|
396
|
+
connectConfig.privateKey = config.privateKey;
|
|
397
|
+
}
|
|
398
|
+
if (config.passphrase) {
|
|
399
|
+
connectConfig.passphrase = config.passphrase;
|
|
400
|
+
}
|
|
401
|
+
// 跳板机支持
|
|
402
|
+
if (config.jumpHost) {
|
|
403
|
+
const jumpAlias = await this.connect(config.jumpHost);
|
|
404
|
+
const jumpSession = this.sessions.get(jumpAlias);
|
|
405
|
+
if (jumpSession) {
|
|
406
|
+
// 通过跳板机建立连接
|
|
407
|
+
connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port || 22);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
return new Promise((resolve, reject) => {
|
|
411
|
+
client.on('ready', () => {
|
|
412
|
+
const session = {
|
|
413
|
+
client,
|
|
414
|
+
config,
|
|
415
|
+
connectedAt: Date.now(),
|
|
416
|
+
lastUsedAt: Date.now(),
|
|
417
|
+
reconnectAttempts: 0,
|
|
418
|
+
connected: true,
|
|
419
|
+
manualClose: false,
|
|
420
|
+
};
|
|
421
|
+
this.sessions.set(alias, session);
|
|
422
|
+
this.persistSessions();
|
|
423
|
+
resolve(alias);
|
|
424
|
+
});
|
|
425
|
+
client.on('error', (err) => {
|
|
426
|
+
const session = this.sessions.get(alias);
|
|
427
|
+
if (session && session.client === client) {
|
|
428
|
+
session.connected = false;
|
|
429
|
+
}
|
|
430
|
+
const target = `${connectConfig.username}@${connectConfig.host}:${connectConfig.port}`;
|
|
431
|
+
const safeMessage = sanitizeKeyError(err.message);
|
|
432
|
+
const suggestion = this.diagnoseConnectionError(err);
|
|
433
|
+
reject(new Error(`SSH connection to ${target} failed: ${safeMessage}${suggestion ? ` (${suggestion})` : ''}`));
|
|
434
|
+
});
|
|
435
|
+
client.on('close', () => {
|
|
436
|
+
const session = this.sessions.get(alias);
|
|
437
|
+
if (session && session.client === client) {
|
|
438
|
+
session.connected = false;
|
|
439
|
+
// 清理绑定旧 client 的 forward/PTY 资源
|
|
440
|
+
this.forwardManager.closeByAlias(alias);
|
|
441
|
+
this.ptyManager.closeByAlias(alias);
|
|
442
|
+
if (!session.manualClose) {
|
|
443
|
+
this.scheduleReconnect(alias);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
});
|
|
447
|
+
client.connect(connectConfig);
|
|
448
|
+
});
|
|
449
|
+
}
|
|
345
450
|
/**
|
|
346
451
|
* 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
|
|
347
452
|
*/
|
|
@@ -368,7 +473,7 @@ export class SessionManager {
|
|
|
368
473
|
ensurePersistDir() {
|
|
369
474
|
const dir = path.dirname(this.persistPath);
|
|
370
475
|
if (!fs.existsSync(dir)) {
|
|
371
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
476
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
372
477
|
}
|
|
373
478
|
}
|
|
374
479
|
/**
|
|
@@ -406,9 +511,19 @@ export class SessionManager {
|
|
|
406
511
|
if (!session || session.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
407
512
|
return;
|
|
408
513
|
}
|
|
514
|
+
// 清掉旧的定时器,防止重复调度
|
|
515
|
+
if (session.reconnectTimer) {
|
|
516
|
+
clearTimeout(session.reconnectTimer);
|
|
517
|
+
}
|
|
409
518
|
session.reconnectAttempts++;
|
|
410
519
|
const attempt = session.reconnectAttempts;
|
|
411
|
-
setTimeout(async () => {
|
|
520
|
+
session.reconnectTimer = setTimeout(async () => {
|
|
521
|
+
const current = this.sessions.get(alias);
|
|
522
|
+
if (!current) {
|
|
523
|
+
// disconnect 已经把 session 移除,不再重连
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
current.reconnectTimer = undefined;
|
|
412
527
|
try {
|
|
413
528
|
await this.reconnect(alias);
|
|
414
529
|
}
|
|
@@ -443,10 +558,11 @@ export class SessionManager {
|
|
|
443
558
|
return '';
|
|
444
559
|
}
|
|
445
560
|
/**
|
|
446
|
-
* 转义 shell
|
|
561
|
+
* 转义 shell 参数(使用单引号方式,防止命令注入)
|
|
562
|
+
* 委托给 tools/utils.ts 的共享实现
|
|
447
563
|
*/
|
|
448
564
|
escapeShellArg(s) {
|
|
449
|
-
return
|
|
565
|
+
return escapeShellArg(s);
|
|
450
566
|
}
|
|
451
567
|
/**
|
|
452
568
|
* 校验用户名(只允许字母、数字、下划线、连字符)
|
|
@@ -469,9 +585,7 @@ export class SessionManager {
|
|
|
469
585
|
if (Object.keys(env).length > 0) {
|
|
470
586
|
const validEntries = Object.entries(env).filter(([k]) => this.isValidEnvKey(k));
|
|
471
587
|
if (validEntries.length > 0) {
|
|
472
|
-
const envStr = validEntries
|
|
473
|
-
.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
|
|
474
|
-
.join('; ');
|
|
588
|
+
const envStr = validEntries.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`).join('; ');
|
|
475
589
|
fullCommand = `${envStr}; ${command}`;
|
|
476
590
|
}
|
|
477
591
|
}
|
|
@@ -485,14 +599,14 @@ export class SessionManager {
|
|
|
485
599
|
* bash → .bashrc, zsh → .zshrc, 其他 → .profile
|
|
486
600
|
*/
|
|
487
601
|
getLoadProfileCommand() {
|
|
488
|
-
return 'case "$(basename "$SHELL" 2>/dev/null)" in ' +
|
|
602
|
+
return ('case "$(basename "$SHELL" 2>/dev/null)" in ' +
|
|
489
603
|
'bash) [ -f ~/.bashrc ] && . ~/.bashrc ;; ' +
|
|
490
604
|
'zsh) [ -f ~/.zshrc ] && . ~/.zshrc ;; ' +
|
|
491
605
|
'*) [ -f ~/.profile ] && . ~/.profile ;; ' +
|
|
492
|
-
'esac 2>/dev/null; ';
|
|
606
|
+
'esac 2>/dev/null; ');
|
|
493
607
|
}
|
|
494
608
|
/**
|
|
495
|
-
*
|
|
609
|
+
* 持久化会话信息(异步非阻塞,避免阻塞事件循环)
|
|
496
610
|
*/
|
|
497
611
|
persistSessions() {
|
|
498
612
|
const data = [];
|
|
@@ -507,12 +621,9 @@ export class SessionManager {
|
|
|
507
621
|
env: session.config.env,
|
|
508
622
|
});
|
|
509
623
|
}
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
catch (e) {
|
|
514
|
-
// 忽略写入错误
|
|
515
|
-
}
|
|
624
|
+
fs.promises
|
|
625
|
+
.writeFile(this.persistPath, JSON.stringify(data, null, 2), { mode: 0o600 })
|
|
626
|
+
.catch((err) => console.error('[SSH] 会话持久化写入失败:', err));
|
|
516
627
|
}
|
|
517
628
|
}
|
|
518
629
|
// 全局单例
|
package/dist/ssh-config.js
CHANGED
|
@@ -10,6 +10,22 @@
|
|
|
10
10
|
import * as fs from 'fs';
|
|
11
11
|
import * as os from 'os';
|
|
12
12
|
import * as path from 'path';
|
|
13
|
+
import { validateConfigFile } from './security.js';
|
|
14
|
+
import { expandTilde } from './tools/utils.js';
|
|
15
|
+
// hostname 仅允许字母、数字、`.`、`:`(IPv6)、`-`、`_`,拒绝空格、引号、反斜杠、`-o` 注入字符
|
|
16
|
+
const HOSTNAME_ALLOWED = /^[a-zA-Z0-9.:_-]+$/;
|
|
17
|
+
function validateHostName(value, hostBlock) {
|
|
18
|
+
if (!HOSTNAME_ALLOWED.test(value)) {
|
|
19
|
+
throw new Error(`ssh-config: Host "${hostBlock}" 的 HostName "${value}" 含非法字符(仅允许字母、数字、.、:、-、_)`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
// SSH 用户名仅允许字母、数字、`.`、`-`、`_`,拒绝 `-o` 等注入
|
|
23
|
+
const USERNAME_ALLOWED = /^[a-zA-Z0-9._-]+$/;
|
|
24
|
+
function validateUserName(value, hostBlock) {
|
|
25
|
+
if (!USERNAME_ALLOWED.test(value)) {
|
|
26
|
+
throw new Error(`ssh-config: Host "${hostBlock}" 的 User "${value}" 含非法字符(仅允许字母、数字、.、-、_)`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
13
29
|
/**
|
|
14
30
|
* 解析 host:port 或 [ipv6]:port
|
|
15
31
|
* 返回 { host, port },host 不含方括号
|
|
@@ -73,15 +89,6 @@ export function parseProxyJump(proxyJump) {
|
|
|
73
89
|
const { host, port } = parseHostPort(firstJump);
|
|
74
90
|
return { host, port };
|
|
75
91
|
}
|
|
76
|
-
/**
|
|
77
|
-
* 展开 ~ 路径
|
|
78
|
-
*/
|
|
79
|
-
function expandTilde(filePath) {
|
|
80
|
-
if (filePath.startsWith('~')) {
|
|
81
|
-
return path.join(os.homedir(), filePath.slice(1));
|
|
82
|
-
}
|
|
83
|
-
return filePath;
|
|
84
|
-
}
|
|
85
92
|
/**
|
|
86
93
|
* 剥离行尾注释
|
|
87
94
|
* "value # comment" -> "value"
|
|
@@ -92,7 +99,7 @@ function stripInlineComment(value) {
|
|
|
92
99
|
let quoteChar = '';
|
|
93
100
|
for (let i = 0; i < value.length; i++) {
|
|
94
101
|
const ch = value[i];
|
|
95
|
-
if (!inQuote && (ch === '"' || ch === '
|
|
102
|
+
if (!inQuote && (ch === '"' || ch === "'")) {
|
|
96
103
|
inQuote = true;
|
|
97
104
|
quoteChar = ch;
|
|
98
105
|
}
|
|
@@ -111,10 +118,12 @@ function stripInlineComment(value) {
|
|
|
111
118
|
* 跳过 Match 块(避免条件配置被误应用)
|
|
112
119
|
*/
|
|
113
120
|
export function parseSSHConfig(configPath) {
|
|
114
|
-
const filePath = configPath
|
|
121
|
+
const filePath = configPath ? expandTilde(configPath) : path.join(os.homedir(), '.ssh', 'config');
|
|
115
122
|
if (!fs.existsSync(filePath)) {
|
|
116
123
|
return [];
|
|
117
124
|
}
|
|
125
|
+
// 路径白名单 + 大小上限校验,避免任意大文件被读取
|
|
126
|
+
validateConfigFile(filePath);
|
|
118
127
|
const content = fs.readFileSync(filePath, 'utf-8');
|
|
119
128
|
const lines = content.split('\n');
|
|
120
129
|
// 第一遍:收集所有配置块
|
|
@@ -129,11 +138,11 @@ export function parseSSHConfig(configPath) {
|
|
|
129
138
|
continue;
|
|
130
139
|
}
|
|
131
140
|
// 解析 key value(支持 = 和空格分隔)
|
|
132
|
-
const match = trimmed.match(/^(
|
|
141
|
+
const match = trimmed.match(/^(?<key>\S+)\s*[=\s]\s*(?<rawValue>.+)$/);
|
|
133
142
|
if (!match) {
|
|
134
143
|
continue;
|
|
135
144
|
}
|
|
136
|
-
const
|
|
145
|
+
const { key, rawValue } = match.groups;
|
|
137
146
|
const keyLower = key.toLowerCase();
|
|
138
147
|
const value = stripInlineComment(rawValue);
|
|
139
148
|
if (keyLower === 'host') {
|
|
@@ -144,7 +153,7 @@ export function parseSSHConfig(configPath) {
|
|
|
144
153
|
blocks.push(currentBlock);
|
|
145
154
|
}
|
|
146
155
|
// Host 行可能有多个别名/模式,用空格分隔
|
|
147
|
-
const patterns = value.split(/\s+/).filter(p => p.length > 0);
|
|
156
|
+
const patterns = value.split(/\s+/).filter((p) => p.length > 0);
|
|
148
157
|
currentBlock = { patterns, config: {} };
|
|
149
158
|
}
|
|
150
159
|
else if (keyLower === 'match') {
|
|
@@ -160,9 +169,11 @@ export function parseSSHConfig(configPath) {
|
|
|
160
169
|
// 解析配置项(不在 Match 块内)
|
|
161
170
|
switch (keyLower) {
|
|
162
171
|
case 'hostname':
|
|
172
|
+
validateHostName(value, currentBlock.patterns.join(','));
|
|
163
173
|
currentBlock.config.hostName = value;
|
|
164
174
|
break;
|
|
165
175
|
case 'user':
|
|
176
|
+
validateUserName(value, currentBlock.patterns.join(','));
|
|
166
177
|
currentBlock.config.user = value;
|
|
167
178
|
break;
|
|
168
179
|
case 'port':
|