@pyrokine/mcp-ssh 1.3.0 → 2.0.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.
- 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 +10 -1
- package/dist/forward-manager.js +72 -6
- package/dist/index.d.ts +1 -1
- package/dist/index.js +30 -3
- package/dist/pty-manager.d.ts +5 -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 +226 -117
- 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/dist/types.d.ts +0 -2
- 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
|
*/
|
|
@@ -178,7 +131,6 @@ export class SessionManager {
|
|
|
178
131
|
connected: this.isAlive(session),
|
|
179
132
|
connectedAt: session.connectedAt,
|
|
180
133
|
lastUsedAt: session.lastUsedAt,
|
|
181
|
-
env: session.config.env,
|
|
182
134
|
});
|
|
183
135
|
}
|
|
184
136
|
return result;
|
|
@@ -189,10 +141,10 @@ export class SessionManager {
|
|
|
189
141
|
async exec(alias, command, options = {}) {
|
|
190
142
|
const session = this.getSession(alias);
|
|
191
143
|
const startTime = Date.now();
|
|
192
|
-
const maxOutputSize = options.maxOutputSize
|
|
144
|
+
const maxOutputSize = options.maxOutputSize ?? this.defaultMaxOutputSize;
|
|
193
145
|
const fullCommand = this.buildCommand(command, session, options);
|
|
194
146
|
return new Promise((resolve, reject) => {
|
|
195
|
-
const timeout = options.timeout
|
|
147
|
+
const timeout = options.timeout ?? this.defaultTimeout;
|
|
196
148
|
let timeoutId = null;
|
|
197
149
|
let stdout = '';
|
|
198
150
|
let stderr = '';
|
|
@@ -259,10 +211,10 @@ export class SessionManager {
|
|
|
259
211
|
/**
|
|
260
212
|
* 以其他用户身份执行命令
|
|
261
213
|
*
|
|
262
|
-
* options.loadProfile 控制是否加载用户的 shell 配置(默认 true
|
|
214
|
+
* options.loadProfile 控制是否加载用户的 shell 配置(默认 true)
|
|
263
215
|
* su -c 创建非交互式 shell,不会自动执行 rc 文件,
|
|
264
|
-
* 但大多数用户的环境变量设置在 rc
|
|
265
|
-
* 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)
|
|
216
|
+
* 但大多数用户的环境变量设置在 rc 文件中,因此默认加载
|
|
217
|
+
* 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)
|
|
266
218
|
*/
|
|
267
219
|
async execAsUser(alias, command, targetUser, options = {}) {
|
|
268
220
|
// 校验用户名防止注入
|
|
@@ -270,25 +222,95 @@ export class SessionManager {
|
|
|
270
222
|
throw new Error(`Invalid username: ${targetUser}`);
|
|
271
223
|
}
|
|
272
224
|
const { loadProfile = true, ...execOpts } = options;
|
|
273
|
-
const wrappedCommand = loadProfile
|
|
274
|
-
? `${this.getLoadProfileCommand()}${command}`
|
|
275
|
-
: command;
|
|
225
|
+
const wrappedCommand = loadProfile ? `${this.getLoadProfileCommand()}${command}` : command;
|
|
276
226
|
const suCommand = `su - ${targetUser} -c ${this.escapeShellArg(wrappedCommand)}`;
|
|
277
227
|
return this.exec(alias, suCommand, execOpts);
|
|
278
228
|
}
|
|
279
229
|
/**
|
|
280
230
|
* 使用 sudo 执行命令
|
|
231
|
+
*
|
|
232
|
+
* 通过 stdin 传递密码,避免密码出现在进程列表和 audit 日志中
|
|
281
233
|
*/
|
|
282
234
|
async execSudo(alias, command, sudoPassword, options = {}) {
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
// 通过 stdin 传递密码(使用 escapeShellArg 转义)
|
|
286
|
-
sudoCommand = `echo ${this.escapeShellArg(sudoPassword)} | sudo -S ${command}`;
|
|
235
|
+
if (!sudoPassword) {
|
|
236
|
+
return this.exec(alias, `sudo ${command}`, options);
|
|
287
237
|
}
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
238
|
+
const session = this.getSession(alias);
|
|
239
|
+
const startTime = Date.now();
|
|
240
|
+
const timeout = options.timeout ?? this.defaultTimeout;
|
|
241
|
+
const maxOutputSize = options.maxOutputSize ?? this.defaultMaxOutputSize;
|
|
242
|
+
const fullCommand = this.buildCommand(`sudo -S ${command}`, session, options);
|
|
243
|
+
return new Promise((resolve, reject) => {
|
|
244
|
+
let settled = false;
|
|
245
|
+
let streamRef = null;
|
|
246
|
+
const timeoutId = setTimeout(() => {
|
|
247
|
+
if (settled) {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
settled = true;
|
|
251
|
+
try {
|
|
252
|
+
streamRef?.close();
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
// ignore
|
|
256
|
+
}
|
|
257
|
+
reject(new Error(`Command timed out after ${timeout}ms`));
|
|
258
|
+
}, timeout);
|
|
259
|
+
session.client.exec(fullCommand, {}, (err, stream) => {
|
|
260
|
+
if (err) {
|
|
261
|
+
clearTimeout(timeoutId);
|
|
262
|
+
settled = true;
|
|
263
|
+
reject(new Error(`Exec failed: ${err.message}`));
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
streamRef = stream;
|
|
267
|
+
// 密码写入 stdin,sudo -S 从 stdin 读取,不出现在命令行
|
|
268
|
+
stream.write(sudoPassword + '\n');
|
|
269
|
+
stream.end();
|
|
270
|
+
let stdout = '';
|
|
271
|
+
let stderr = '';
|
|
272
|
+
let stdoutTruncated = false;
|
|
273
|
+
let stderrTruncated = false;
|
|
274
|
+
stream.on('close', (code) => {
|
|
275
|
+
clearTimeout(timeoutId);
|
|
276
|
+
if (settled) {
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
settled = true;
|
|
280
|
+
resolve({
|
|
281
|
+
success: code === 0,
|
|
282
|
+
stdout: stdoutTruncated ? stdout + '\n... [truncated]' : stdout,
|
|
283
|
+
stderr: stderrTruncated ? stderr + '\n... [truncated]' : stderr,
|
|
284
|
+
exitCode: code,
|
|
285
|
+
duration: Date.now() - startTime,
|
|
286
|
+
});
|
|
287
|
+
});
|
|
288
|
+
stream.on('data', (data) => {
|
|
289
|
+
if (!stdoutTruncated) {
|
|
290
|
+
const chunk = data.toString('utf-8');
|
|
291
|
+
if (stdout.length + chunk.length > maxOutputSize) {
|
|
292
|
+
stdout += chunk.slice(0, maxOutputSize - stdout.length);
|
|
293
|
+
stdoutTruncated = true;
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
stdout += chunk;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
stream.stderr.on('data', (data) => {
|
|
301
|
+
if (!stderrTruncated) {
|
|
302
|
+
const chunk = data.toString('utf-8');
|
|
303
|
+
if (stderr.length + chunk.length > maxOutputSize) {
|
|
304
|
+
stderr += chunk.slice(0, maxOutputSize - stderr.length);
|
|
305
|
+
stderrTruncated = true;
|
|
306
|
+
}
|
|
307
|
+
else {
|
|
308
|
+
stderr += chunk;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
});
|
|
313
|
+
});
|
|
292
314
|
}
|
|
293
315
|
/**
|
|
294
316
|
* 获取 SFTP 客户端
|
|
@@ -306,12 +328,12 @@ export class SessionManager {
|
|
|
306
328
|
});
|
|
307
329
|
});
|
|
308
330
|
}
|
|
309
|
-
// ===== PTY 委托 =====
|
|
310
331
|
async ptyStart(alias, command, options = {}) {
|
|
311
332
|
return this.ptyManager.start({
|
|
312
333
|
execPty: (a, cmd, opts) => this.execPtyStream(a, cmd, opts),
|
|
313
334
|
}, alias, command, options);
|
|
314
335
|
}
|
|
336
|
+
// ===== PTY 委托 =====
|
|
315
337
|
ptyWrite(ptyId, data) {
|
|
316
338
|
return this.ptyManager.write(ptyId, data);
|
|
317
339
|
}
|
|
@@ -327,10 +349,10 @@ export class SessionManager {
|
|
|
327
349
|
ptyList() {
|
|
328
350
|
return this.ptyManager.list();
|
|
329
351
|
}
|
|
330
|
-
// ===== Forward 委托 =====
|
|
331
352
|
async forwardLocal(alias, localPort, remoteHost, remotePort, localHost = '127.0.0.1') {
|
|
332
353
|
return this.forwardManager.forwardLocal({ getClient: (a) => this.getSession(a).client }, alias, localPort, remoteHost, remotePort, localHost);
|
|
333
354
|
}
|
|
355
|
+
// ===== Forward 委托 =====
|
|
334
356
|
async forwardRemote(alias, remotePort, localHost, localPort, remoteHost = '127.0.0.1') {
|
|
335
357
|
return this.forwardManager.forwardRemote({ getClient: (a) => this.getSession(a).client }, alias, remotePort, localHost, localPort, remoteHost);
|
|
336
358
|
}
|
|
@@ -342,6 +364,88 @@ export class SessionManager {
|
|
|
342
364
|
forwardList() {
|
|
343
365
|
return this.forwardManager.list();
|
|
344
366
|
}
|
|
367
|
+
async connectInternal(config, alias) {
|
|
368
|
+
// 检查是否已有活跃连接
|
|
369
|
+
const existing = this.sessions.get(alias);
|
|
370
|
+
if (existing && this.isAlive(existing)) {
|
|
371
|
+
existing.lastUsedAt = Date.now();
|
|
372
|
+
return alias;
|
|
373
|
+
}
|
|
374
|
+
const client = new Client();
|
|
375
|
+
// 构建连接配置
|
|
376
|
+
const connectConfig = {
|
|
377
|
+
host: config.host,
|
|
378
|
+
port: config.port ?? 22,
|
|
379
|
+
username: config.username,
|
|
380
|
+
readyTimeout: config.readyTimeout ?? this.defaultTimeout,
|
|
381
|
+
keepaliveInterval: config.keepaliveInterval ?? this.defaultKeepaliveInterval,
|
|
382
|
+
keepaliveCountMax: config.keepaliveCountMax ?? this.defaultKeepaliveCountMax,
|
|
383
|
+
};
|
|
384
|
+
// 认证方式
|
|
385
|
+
if (config.password) {
|
|
386
|
+
connectConfig.password = config.password;
|
|
387
|
+
}
|
|
388
|
+
if (config.privateKeyPath) {
|
|
389
|
+
const keyPath = expandTilde(config.privateKeyPath);
|
|
390
|
+
// 路径白名单 + 大小上限校验,避免任意文件读取
|
|
391
|
+
validateKeyFile(keyPath);
|
|
392
|
+
connectConfig.privateKey = fs.readFileSync(keyPath);
|
|
393
|
+
}
|
|
394
|
+
if (config.privateKey) {
|
|
395
|
+
connectConfig.privateKey = config.privateKey;
|
|
396
|
+
}
|
|
397
|
+
if (config.passphrase) {
|
|
398
|
+
connectConfig.passphrase = config.passphrase;
|
|
399
|
+
}
|
|
400
|
+
// 跳板机支持
|
|
401
|
+
if (config.jumpHost) {
|
|
402
|
+
const jumpAlias = await this.connect(config.jumpHost);
|
|
403
|
+
const jumpSession = this.sessions.get(jumpAlias);
|
|
404
|
+
if (jumpSession) {
|
|
405
|
+
// 通过跳板机建立连接
|
|
406
|
+
connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port || 22);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return new Promise((resolve, reject) => {
|
|
410
|
+
client.on('ready', () => {
|
|
411
|
+
const session = {
|
|
412
|
+
client,
|
|
413
|
+
config,
|
|
414
|
+
connectedAt: Date.now(),
|
|
415
|
+
lastUsedAt: Date.now(),
|
|
416
|
+
reconnectAttempts: 0,
|
|
417
|
+
connected: true,
|
|
418
|
+
manualClose: false,
|
|
419
|
+
};
|
|
420
|
+
this.sessions.set(alias, session);
|
|
421
|
+
this.persistSessions();
|
|
422
|
+
resolve(alias);
|
|
423
|
+
});
|
|
424
|
+
client.on('error', (err) => {
|
|
425
|
+
const session = this.sessions.get(alias);
|
|
426
|
+
if (session && session.client === client) {
|
|
427
|
+
session.connected = false;
|
|
428
|
+
}
|
|
429
|
+
const target = `${connectConfig.username}@${connectConfig.host}:${connectConfig.port}`;
|
|
430
|
+
const safeMessage = sanitizeKeyError(err.message);
|
|
431
|
+
const suggestion = this.diagnoseConnectionError(err);
|
|
432
|
+
reject(new Error(`SSH connection to ${target} failed: ${safeMessage}${suggestion ? ` (${suggestion})` : ''}`));
|
|
433
|
+
});
|
|
434
|
+
client.on('close', () => {
|
|
435
|
+
const session = this.sessions.get(alias);
|
|
436
|
+
if (session && session.client === client) {
|
|
437
|
+
session.connected = false;
|
|
438
|
+
// 清理绑定旧 client 的 forward/PTY 资源
|
|
439
|
+
this.forwardManager.closeByAlias(alias);
|
|
440
|
+
this.ptyManager.closeByAlias(alias);
|
|
441
|
+
if (!session.manualClose) {
|
|
442
|
+
this.scheduleReconnect(alias);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
client.connect(connectConfig);
|
|
447
|
+
});
|
|
448
|
+
}
|
|
345
449
|
/**
|
|
346
450
|
* 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
|
|
347
451
|
*/
|
|
@@ -368,7 +472,7 @@ export class SessionManager {
|
|
|
368
472
|
ensurePersistDir() {
|
|
369
473
|
const dir = path.dirname(this.persistPath);
|
|
370
474
|
if (!fs.existsSync(dir)) {
|
|
371
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
475
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
372
476
|
}
|
|
373
477
|
}
|
|
374
478
|
/**
|
|
@@ -406,9 +510,19 @@ export class SessionManager {
|
|
|
406
510
|
if (!session || session.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
407
511
|
return;
|
|
408
512
|
}
|
|
513
|
+
// 清掉旧的定时器,防止重复调度
|
|
514
|
+
if (session.reconnectTimer) {
|
|
515
|
+
clearTimeout(session.reconnectTimer);
|
|
516
|
+
}
|
|
409
517
|
session.reconnectAttempts++;
|
|
410
518
|
const attempt = session.reconnectAttempts;
|
|
411
|
-
setTimeout(async () => {
|
|
519
|
+
session.reconnectTimer = setTimeout(async () => {
|
|
520
|
+
const current = this.sessions.get(alias);
|
|
521
|
+
if (!current) {
|
|
522
|
+
// disconnect 已经把 session 移除,不再重连
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
current.reconnectTimer = undefined;
|
|
412
526
|
try {
|
|
413
527
|
await this.reconnect(alias);
|
|
414
528
|
}
|
|
@@ -443,10 +557,11 @@ export class SessionManager {
|
|
|
443
557
|
return '';
|
|
444
558
|
}
|
|
445
559
|
/**
|
|
446
|
-
* 转义 shell
|
|
560
|
+
* 转义 shell 参数(使用单引号方式,防止命令注入)
|
|
561
|
+
* 委托给 tools/utils.ts 的共享实现
|
|
447
562
|
*/
|
|
448
563
|
escapeShellArg(s) {
|
|
449
|
-
return
|
|
564
|
+
return escapeShellArg(s);
|
|
450
565
|
}
|
|
451
566
|
/**
|
|
452
567
|
* 校验用户名(只允许字母、数字、下划线、连字符)
|
|
@@ -469,9 +584,7 @@ export class SessionManager {
|
|
|
469
584
|
if (Object.keys(env).length > 0) {
|
|
470
585
|
const validEntries = Object.entries(env).filter(([k]) => this.isValidEnvKey(k));
|
|
471
586
|
if (validEntries.length > 0) {
|
|
472
|
-
const envStr = validEntries
|
|
473
|
-
.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
|
|
474
|
-
.join('; ');
|
|
587
|
+
const envStr = validEntries.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`).join('; ');
|
|
475
588
|
fullCommand = `${envStr}; ${command}`;
|
|
476
589
|
}
|
|
477
590
|
}
|
|
@@ -485,34 +598,30 @@ export class SessionManager {
|
|
|
485
598
|
* bash → .bashrc, zsh → .zshrc, 其他 → .profile
|
|
486
599
|
*/
|
|
487
600
|
getLoadProfileCommand() {
|
|
488
|
-
return 'case "$(basename "$SHELL" 2>/dev/null)" in ' +
|
|
601
|
+
return ('case "$(basename "$SHELL" 2>/dev/null)" in ' +
|
|
489
602
|
'bash) [ -f ~/.bashrc ] && . ~/.bashrc ;; ' +
|
|
490
603
|
'zsh) [ -f ~/.zshrc ] && . ~/.zshrc ;; ' +
|
|
491
604
|
'*) [ -f ~/.profile ] && . ~/.profile ;; ' +
|
|
492
|
-
'esac 2>/dev/null; ';
|
|
605
|
+
'esac 2>/dev/null; ');
|
|
493
606
|
}
|
|
494
607
|
/**
|
|
495
|
-
*
|
|
608
|
+
* 持久化会话信息(异步非阻塞,避免阻塞事件循环)
|
|
496
609
|
*/
|
|
497
610
|
persistSessions() {
|
|
498
611
|
const data = [];
|
|
499
612
|
for (const [alias, session] of this.sessions) {
|
|
500
|
-
//
|
|
613
|
+
// 不保存敏感信息(密码、密钥、环境变量)
|
|
501
614
|
data.push({
|
|
502
615
|
alias,
|
|
503
616
|
host: session.config.host,
|
|
504
617
|
port: session.config.port || 22,
|
|
505
618
|
username: session.config.username,
|
|
506
619
|
connectedAt: session.connectedAt,
|
|
507
|
-
env: session.config.env,
|
|
508
620
|
});
|
|
509
621
|
}
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
catch (e) {
|
|
514
|
-
// 忽略写入错误
|
|
515
|
-
}
|
|
622
|
+
fs.promises
|
|
623
|
+
.writeFile(this.persistPath, JSON.stringify(data, null, 2), { mode: 0o600 })
|
|
624
|
+
.catch((err) => console.error('[SSH] 会话持久化写入失败:', err));
|
|
516
625
|
}
|
|
517
626
|
}
|
|
518
627
|
// 全局单例
|
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':
|