@pyrokine/mcp-ssh 2.3.2 → 2.4.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 +141 -27
- package/README_zh.md +76 -27
- package/dist/command-risk.d.ts +7 -0
- package/dist/command-risk.js +106 -0
- package/dist/directory-verification.d.ts +43 -0
- package/dist/directory-verification.js +485 -0
- package/dist/file-ops.d.ts +77 -14
- package/dist/file-ops.js +839 -205
- package/dist/forward-manager.d.ts +22 -3
- package/dist/forward-manager.js +501 -85
- package/dist/index.js +2 -1
- package/dist/operation-manager.d.ts +64 -0
- package/dist/operation-manager.js +545 -0
- package/dist/pty-manager.d.ts +1 -0
- package/dist/pty-manager.js +11 -7
- package/dist/session-manager.d.ts +47 -11
- package/dist/session-manager.js +564 -114
- package/dist/tools/connection.js +58 -17
- package/dist/tools/exec.js +7 -66
- package/dist/tools/file.d.ts +1 -0
- package/dist/tools/file.js +575 -119
- package/dist/tools/forward.js +18 -8
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.js +1 -0
- package/dist/tools/operation.d.ts +2 -0
- package/dist/tools/operation.js +134 -0
- package/dist/tools/utils.d.ts +2 -2
- package/dist/transfer-outcome.d.ts +12 -0
- package/dist/transfer-outcome.js +72 -0
- package/dist/types.d.ts +95 -6
- package/package.json +10 -8
package/dist/session-manager.js
CHANGED
|
@@ -7,12 +7,14 @@
|
|
|
7
7
|
* - 自动重连
|
|
8
8
|
* - 会话持久化
|
|
9
9
|
*/
|
|
10
|
+
import { createHash } from 'crypto';
|
|
10
11
|
import * as fs from 'fs';
|
|
11
12
|
import * as os from 'os';
|
|
12
13
|
import * as path from 'path';
|
|
13
14
|
import { Client } from 'ssh2';
|
|
14
15
|
import { clearRsyncCache } from './file-ops.js';
|
|
15
16
|
import { ForwardManager } from './forward-manager.js';
|
|
17
|
+
import { OperationManager } from './operation-manager.js';
|
|
16
18
|
import { PtyManager } from './pty-manager.js';
|
|
17
19
|
import { sanitizeKeyError, validateKeyFile } from './security.js';
|
|
18
20
|
import { escapeShellArg, expandTilde } from './tools/utils.js';
|
|
@@ -26,12 +28,23 @@ class CommandError extends Error {
|
|
|
26
28
|
this.name = 'CommandError';
|
|
27
29
|
}
|
|
28
30
|
}
|
|
31
|
+
class ConnectionError extends Error {
|
|
32
|
+
details;
|
|
33
|
+
constructor(message, details) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.details = details;
|
|
36
|
+
this.name = 'ConnectionError';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
29
39
|
export class SessionManager {
|
|
30
40
|
sessions = new Map();
|
|
31
41
|
/** per-alias connect 进行中的 Promise,防止并发 connect 同一 alias 时重复建连 */
|
|
32
42
|
connectInFlight = new Map();
|
|
43
|
+
pendingConnections = new Map();
|
|
44
|
+
connectionGenerations = new Map();
|
|
33
45
|
ptyManager = new PtyManager();
|
|
34
46
|
forwardManager = new ForwardManager();
|
|
47
|
+
operationManager;
|
|
35
48
|
persistPath;
|
|
36
49
|
defaultKeepaliveInterval = 30000; // 30秒
|
|
37
50
|
defaultKeepaliveCountMax = 3;
|
|
@@ -41,6 +54,10 @@ export class SessionManager {
|
|
|
41
54
|
reconnectDelay = 5000; // 5秒
|
|
42
55
|
constructor(persistPath) {
|
|
43
56
|
this.persistPath = persistPath || path.join(os.homedir(), '.ssh-mcp-pro', 'sessions.json');
|
|
57
|
+
this.operationManager = new OperationManager({
|
|
58
|
+
openStream: (alias, command, marker, options, adopt) => this.openOperationStream(alias, command, marker, options, adopt),
|
|
59
|
+
cancelRemote: (alias, pid, marker, processGroup, options) => this.cancelRemoteOperation(alias, pid, marker, processGroup, options),
|
|
60
|
+
});
|
|
44
61
|
this.ensurePersistDir();
|
|
45
62
|
}
|
|
46
63
|
/**
|
|
@@ -48,15 +65,54 @@ export class SessionManager {
|
|
|
48
65
|
*/
|
|
49
66
|
async connect(config) {
|
|
50
67
|
const alias = this.generateAlias(config);
|
|
51
|
-
|
|
68
|
+
const fingerprint = this.connectionFingerprint(config);
|
|
69
|
+
const requestedIdentity = this.configIdentity(config);
|
|
52
70
|
const inFlight = this.connectInFlight.get(alias);
|
|
53
71
|
if (inFlight) {
|
|
54
|
-
|
|
72
|
+
if (inFlight.fingerprint !== fingerprint) {
|
|
73
|
+
throw new CommandError(`Alias '${alias}' already has a different connection attempt in progress`, {
|
|
74
|
+
alias,
|
|
75
|
+
existingIdentity: inFlight.identity,
|
|
76
|
+
requestedIdentity,
|
|
77
|
+
suggestion: '请等待当前连接完成、换一个 alias,或先 ssh_disconnect 取消当前连接',
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
return inFlight.promise;
|
|
55
81
|
}
|
|
56
|
-
const
|
|
57
|
-
|
|
82
|
+
const generation = this.getConnectionGeneration(alias);
|
|
83
|
+
let rejectCancellation = () => undefined;
|
|
84
|
+
let cancelled = false;
|
|
85
|
+
const cancellation = new Promise((_resolve, reject) => {
|
|
86
|
+
rejectCancellation = reject;
|
|
58
87
|
});
|
|
59
|
-
|
|
88
|
+
const pendingConnection = {
|
|
89
|
+
generation,
|
|
90
|
+
fingerprint,
|
|
91
|
+
cancel: (error) => {
|
|
92
|
+
if (cancelled) {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
cancelled = true;
|
|
96
|
+
try {
|
|
97
|
+
pendingConnection.client?.end();
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
/* client 可能尚未开始连接或已经关闭 */
|
|
101
|
+
}
|
|
102
|
+
rejectCancellation(error);
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
this.pendingConnections.set(alias, pendingConnection);
|
|
106
|
+
const connectAttempt = Promise.race([this.connectInternal(config, alias, pendingConnection), cancellation]);
|
|
107
|
+
const promise = connectAttempt.finally(() => {
|
|
108
|
+
if (this.connectInFlight.get(alias)?.promise === promise) {
|
|
109
|
+
this.connectInFlight.delete(alias);
|
|
110
|
+
}
|
|
111
|
+
if (this.pendingConnections.get(alias) === pendingConnection) {
|
|
112
|
+
this.pendingConnections.delete(alias);
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
this.connectInFlight.set(alias, { identity: requestedIdentity, fingerprint, promise });
|
|
60
116
|
return promise;
|
|
61
117
|
}
|
|
62
118
|
/**
|
|
@@ -67,8 +123,14 @@ export class SessionManager {
|
|
|
67
123
|
if (!session) {
|
|
68
124
|
throw new Error(`Session ${alias} not found`);
|
|
69
125
|
}
|
|
126
|
+
this.cancelPendingConnection(alias);
|
|
70
127
|
session.manualClose = true;
|
|
71
128
|
session.connected = false;
|
|
129
|
+
if (session.reconnectTimer) {
|
|
130
|
+
clearTimeout(session.reconnectTimer);
|
|
131
|
+
session.reconnectTimer = undefined;
|
|
132
|
+
}
|
|
133
|
+
this.invalidateAliasResources(alias);
|
|
72
134
|
try {
|
|
73
135
|
session.client.end();
|
|
74
136
|
}
|
|
@@ -81,6 +143,7 @@ export class SessionManager {
|
|
|
81
143
|
* 断开连接
|
|
82
144
|
*/
|
|
83
145
|
disconnect(alias) {
|
|
146
|
+
const pendingCancelled = this.cancelPendingConnection(alias);
|
|
84
147
|
const session = this.sessions.get(alias);
|
|
85
148
|
if (session) {
|
|
86
149
|
session.manualClose = true;
|
|
@@ -89,11 +152,7 @@ export class SessionManager {
|
|
|
89
152
|
clearTimeout(session.reconnectTimer);
|
|
90
153
|
session.reconnectTimer = undefined;
|
|
91
154
|
}
|
|
92
|
-
|
|
93
|
-
this.ptyManager.closeByAlias(alias);
|
|
94
|
-
this.forwardManager.closeByAlias(alias);
|
|
95
|
-
// 清理 file-ops 中的 rsync 可用性缓存,防止重连到不同主机后读到旧判断
|
|
96
|
-
clearRsyncCache(alias);
|
|
155
|
+
this.invalidateAliasResources(alias);
|
|
97
156
|
try {
|
|
98
157
|
session.client.end();
|
|
99
158
|
}
|
|
@@ -104,11 +163,11 @@ export class SessionManager {
|
|
|
104
163
|
this.persistSessions();
|
|
105
164
|
return true;
|
|
106
165
|
}
|
|
107
|
-
return
|
|
166
|
+
return pendingCancelled;
|
|
108
167
|
}
|
|
109
168
|
/** 断开所有活跃会话(SIGINT/SIGTERM 时调用) */
|
|
110
169
|
async disconnectAll() {
|
|
111
|
-
const aliases =
|
|
170
|
+
const aliases = new Set([...this.sessions.keys(), ...this.pendingConnections.keys()]);
|
|
112
171
|
for (const alias of aliases) {
|
|
113
172
|
this.disconnect(alias);
|
|
114
173
|
}
|
|
@@ -127,33 +186,93 @@ export class SessionManager {
|
|
|
127
186
|
session.lastUsedAt = Date.now();
|
|
128
187
|
return session;
|
|
129
188
|
}
|
|
130
|
-
/**
|
|
131
|
-
* 列出所有会话
|
|
132
|
-
*/
|
|
133
189
|
listSessions() {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
190
|
+
return Array.from(this.sessions, ([alias, session]) => ({
|
|
191
|
+
alias,
|
|
192
|
+
identity: this.sessionIdentity(session),
|
|
193
|
+
runAs: session.config.runAs,
|
|
194
|
+
connected: this.isAlive(session),
|
|
195
|
+
lastUsedAt: session.lastUsedAt,
|
|
196
|
+
}));
|
|
197
|
+
}
|
|
198
|
+
listSessionDetails() {
|
|
199
|
+
return Array.from(this.sessions, ([alias, session]) => ({
|
|
200
|
+
alias,
|
|
201
|
+
identity: this.sessionIdentity(session),
|
|
202
|
+
host: session.config.host,
|
|
203
|
+
port: session.config.port || 22,
|
|
204
|
+
username: session.config.username,
|
|
205
|
+
runAs: session.config.runAs,
|
|
206
|
+
authMethod: session.config.privateKeyPath
|
|
137
207
|
? 'key'
|
|
138
|
-
: session.config.
|
|
208
|
+
: session.config.privateKey
|
|
209
|
+
? 'inline-key'
|
|
210
|
+
: session.config.password
|
|
211
|
+
? 'password'
|
|
212
|
+
: 'agent',
|
|
213
|
+
connected: this.isAlive(session),
|
|
214
|
+
connectedAt: session.connectedAt,
|
|
215
|
+
lastUsedAt: session.lastUsedAt,
|
|
216
|
+
hasJumpHost: Boolean(session.config.jumpHost),
|
|
217
|
+
}));
|
|
218
|
+
}
|
|
219
|
+
getSessionConnectionInfo(alias) {
|
|
220
|
+
const session = this.getSession(alias);
|
|
221
|
+
const config = session.config;
|
|
222
|
+
return {
|
|
223
|
+
alias,
|
|
224
|
+
identity: this.sessionIdentity(session),
|
|
225
|
+
loginUser: config.username,
|
|
226
|
+
runAs: config.runAs,
|
|
227
|
+
host: config.host,
|
|
228
|
+
port: config.port || 22,
|
|
229
|
+
defaultEnvKeys: config.defaultEnv ? Object.keys(config.defaultEnv) : [],
|
|
230
|
+
envKeys: config.env ? Object.keys(config.env) : [],
|
|
231
|
+
hasJumpHost: Boolean(config.jumpHost),
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
getExternalTransferCapability(alias) {
|
|
235
|
+
const session = this.getSession(alias);
|
|
236
|
+
const config = session.config;
|
|
237
|
+
const authMethod = config.privateKeyPath
|
|
238
|
+
? 'key-path'
|
|
239
|
+
: config.privateKey
|
|
240
|
+
? 'inline-key'
|
|
241
|
+
: config.password
|
|
139
242
|
? 'password'
|
|
140
243
|
: 'agent';
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
244
|
+
const hasJumpHost = Boolean(config.jumpHost);
|
|
245
|
+
const routeSafeForOpenSsh = !hasJumpHost;
|
|
246
|
+
const expandedKeyPath = config.privateKeyPath ? expandTilde(config.privateKeyPath) : undefined;
|
|
247
|
+
const keyPathUsable = authMethod === 'key-path' && this.isOpenSshKeyPathUsable(expandedKeyPath);
|
|
248
|
+
const agentAvailable = authMethod === 'agent' && this.isSshAgentAvailable();
|
|
249
|
+
const rsyncEligible = routeSafeForOpenSsh && (keyPathUsable || agentAvailable);
|
|
250
|
+
const decisionReason = hasJumpHost
|
|
251
|
+
? 'jump_host_route_requires_live_ssh_session'
|
|
252
|
+
: authMethod === 'password'
|
|
253
|
+
? 'password_not_forwarded_to_openssh'
|
|
254
|
+
: authMethod === 'inline-key'
|
|
255
|
+
? 'inline_private_key_not_written_to_disk'
|
|
256
|
+
: authMethod === 'key-path'
|
|
257
|
+
? keyPathUsable
|
|
258
|
+
? 'direct_openssh_compatible_key_path'
|
|
259
|
+
: 'key_path_not_openssh_compatible'
|
|
260
|
+
: agentAvailable
|
|
261
|
+
? 'direct_ssh_agent_socket'
|
|
262
|
+
: 'ssh_agent_socket_unavailable';
|
|
263
|
+
return {
|
|
264
|
+
alias,
|
|
265
|
+
identity: this.sessionIdentity(session),
|
|
266
|
+
host: config.host,
|
|
267
|
+
port: config.port || 22,
|
|
268
|
+
username: config.username,
|
|
269
|
+
authMethod,
|
|
270
|
+
keyPath: keyPathUsable ? expandedKeyPath : undefined,
|
|
271
|
+
hasJumpHost,
|
|
272
|
+
routeSafeForOpenSsh,
|
|
273
|
+
rsyncEligible,
|
|
274
|
+
decisionReason,
|
|
275
|
+
};
|
|
157
276
|
}
|
|
158
277
|
/**
|
|
159
278
|
* 执行命令
|
|
@@ -166,6 +285,21 @@ export class SessionManager {
|
|
|
166
285
|
}
|
|
167
286
|
return this.execDirect(alias, command, options, { cwd: options.cwd });
|
|
168
287
|
}
|
|
288
|
+
operationStart(alias, command, options = {}) {
|
|
289
|
+
return this.operationManager.start(alias, command, options);
|
|
290
|
+
}
|
|
291
|
+
operationStatus(operationId) {
|
|
292
|
+
return this.operationManager.status(operationId);
|
|
293
|
+
}
|
|
294
|
+
operationRead(operationId, options = {}) {
|
|
295
|
+
return this.operationManager.read(operationId, options);
|
|
296
|
+
}
|
|
297
|
+
operationCancel(operationId) {
|
|
298
|
+
return this.operationManager.cancel(operationId);
|
|
299
|
+
}
|
|
300
|
+
operationList(alias) {
|
|
301
|
+
return this.operationManager.list(alias);
|
|
302
|
+
}
|
|
169
303
|
/**
|
|
170
304
|
* 以其他用户身份执行命令
|
|
171
305
|
*
|
|
@@ -242,10 +376,25 @@ export class SessionManager {
|
|
|
242
376
|
reject(this.createCommandTimeoutError(alias, timeout, { cwd: options.cwd }, outputPreview()));
|
|
243
377
|
}, timeout);
|
|
244
378
|
session.client.exec(fullCommand, {}, (err, stream) => {
|
|
379
|
+
if (!this.isCurrentSession(alias, session)) {
|
|
380
|
+
clearTimeout(timeoutId);
|
|
381
|
+
this.closeClientChannel(stream);
|
|
382
|
+
if (!settled) {
|
|
383
|
+
settled = true;
|
|
384
|
+
reject(new Error('Sudo exec was cancelled because the SSH session changed'));
|
|
385
|
+
}
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
245
388
|
if (err) {
|
|
246
389
|
clearTimeout(timeoutId);
|
|
247
|
-
settled
|
|
248
|
-
|
|
390
|
+
if (!settled) {
|
|
391
|
+
settled = true;
|
|
392
|
+
reject(new Error(`Exec failed: ${err.message}`));
|
|
393
|
+
}
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
if (settled) {
|
|
397
|
+
this.closeClientChannel(stream);
|
|
249
398
|
return;
|
|
250
399
|
}
|
|
251
400
|
streamRef = stream;
|
|
@@ -310,12 +459,16 @@ export class SessionManager {
|
|
|
310
459
|
const session = this.getSession(alias);
|
|
311
460
|
return new Promise((resolve, reject) => {
|
|
312
461
|
session.client.sftp((err, sftp) => {
|
|
462
|
+
if (!this.isCurrentSession(alias, session)) {
|
|
463
|
+
this.destroySftp(sftp);
|
|
464
|
+
reject(new Error('SFTP request was cancelled because the SSH session changed'));
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
313
467
|
if (err) {
|
|
314
468
|
reject(err);
|
|
469
|
+
return;
|
|
315
470
|
}
|
|
316
|
-
|
|
317
|
-
resolve(sftp);
|
|
318
|
-
}
|
|
471
|
+
resolve(sftp);
|
|
319
472
|
});
|
|
320
473
|
});
|
|
321
474
|
}
|
|
@@ -347,20 +500,80 @@ export class SessionManager {
|
|
|
347
500
|
async forwardRemote(alias, remotePort, localHost, localPort, remoteHost = '127.0.0.1') {
|
|
348
501
|
return this.forwardManager.forwardRemote({ getClient: (a) => this.getSession(a).client }, alias, remotePort, localHost, localPort, remoteHost);
|
|
349
502
|
}
|
|
350
|
-
forwardClose(forwardId) {
|
|
503
|
+
forwardClose(forwardId, options = {}) {
|
|
351
504
|
return this.forwardManager.close(forwardId, {
|
|
352
505
|
getClient: (a) => this.getSession(a).client,
|
|
353
|
-
});
|
|
506
|
+
}, options);
|
|
354
507
|
}
|
|
355
508
|
forwardList() {
|
|
356
509
|
return this.forwardManager.list();
|
|
357
510
|
}
|
|
511
|
+
isSshAgentAvailable() {
|
|
512
|
+
const socketPath = process.env.SSH_AUTH_SOCK;
|
|
513
|
+
if (!socketPath) {
|
|
514
|
+
return false;
|
|
515
|
+
}
|
|
516
|
+
if (process.platform === 'win32') {
|
|
517
|
+
return true;
|
|
518
|
+
}
|
|
519
|
+
try {
|
|
520
|
+
return fs.statSync(socketPath).isSocket();
|
|
521
|
+
}
|
|
522
|
+
catch {
|
|
523
|
+
return false;
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
isOpenSshKeyPathUsable(keyPath) {
|
|
527
|
+
try {
|
|
528
|
+
const stats = fs.statSync(keyPath);
|
|
529
|
+
if (!stats.isFile()) {
|
|
530
|
+
return false;
|
|
531
|
+
}
|
|
532
|
+
if (process.platform !== 'win32' && (stats.mode & 0o077) !== 0) {
|
|
533
|
+
return false;
|
|
534
|
+
}
|
|
535
|
+
const currentUid = process.getuid?.();
|
|
536
|
+
return currentUid === undefined || stats.uid === currentUid;
|
|
537
|
+
}
|
|
538
|
+
catch {
|
|
539
|
+
return false;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
358
542
|
sessionIdentity(session) {
|
|
359
543
|
return this.configIdentity(session.config);
|
|
360
544
|
}
|
|
361
545
|
configIdentity(config) {
|
|
362
546
|
return `${config.username}@${config.host}:${config.port || 22}`;
|
|
363
547
|
}
|
|
548
|
+
connectionFingerprint(config) {
|
|
549
|
+
const secretHash = (value) => value === undefined ? undefined : createHash('sha256').update(value).digest('hex');
|
|
550
|
+
const sortedEntries = (values) => values === undefined
|
|
551
|
+
? undefined
|
|
552
|
+
: Object.entries(values).sort(([left], [right]) => left.localeCompare(right));
|
|
553
|
+
const payload = (value) => ({
|
|
554
|
+
host: value.host,
|
|
555
|
+
port: value.port || 22,
|
|
556
|
+
username: value.username,
|
|
557
|
+
alias: value.alias,
|
|
558
|
+
template: value.template,
|
|
559
|
+
runAs: value.runAs,
|
|
560
|
+
defaultEnv: sortedEntries(value.defaultEnv),
|
|
561
|
+
env: sortedEntries(value.env),
|
|
562
|
+
keepaliveInterval: value.keepaliveInterval,
|
|
563
|
+
keepaliveCountMax: value.keepaliveCountMax,
|
|
564
|
+
readyTimeout: value.readyTimeout,
|
|
565
|
+
lang: value.lang,
|
|
566
|
+
shell: value.shell,
|
|
567
|
+
password: secretHash(value.password),
|
|
568
|
+
privateKeyPath: value.privateKeyPath ? path.resolve(expandTilde(value.privateKeyPath)) : undefined,
|
|
569
|
+
privateKey: secretHash(value.privateKey),
|
|
570
|
+
passphrase: secretHash(value.passphrase),
|
|
571
|
+
jumpHost: value.jumpHost ? payload(value.jumpHost) : undefined,
|
|
572
|
+
});
|
|
573
|
+
return createHash('sha256')
|
|
574
|
+
.update(JSON.stringify(payload(config)))
|
|
575
|
+
.digest('hex');
|
|
576
|
+
}
|
|
364
577
|
resultMetadata(session, options, context) {
|
|
365
578
|
const env = options.skipSessionEnv
|
|
366
579
|
? { ...options.env }
|
|
@@ -421,6 +634,75 @@ export class SessionManager {
|
|
|
421
634
|
}
|
|
422
635
|
return maxOutputSize;
|
|
423
636
|
}
|
|
637
|
+
async openOperationStream(alias, command, marker, options, adopt) {
|
|
638
|
+
const session = this.getSession(alias);
|
|
639
|
+
const markerEnv = `MCP_SSH_OPERATION_MARKER=${this.escapeShellArg(marker)}`;
|
|
640
|
+
const markerLine = `__MCP_SSH_OPERATION__:${marker}:%s:%s\\n`;
|
|
641
|
+
const operationScript = this.escapeShellArg(`printf ${this.escapeShellArg(markerLine)} "$$" "$1" >&2; exec sh -c ${this.escapeShellArg(command)}`);
|
|
642
|
+
const wrappedCommand = `if command -v setsid >/dev/null 2>&1; then ` +
|
|
643
|
+
`exec env ${markerEnv} setsid sh -c ${operationScript} sh 1; ` +
|
|
644
|
+
`else exec env ${markerEnv} sh -c ${operationScript} sh 0; fi`;
|
|
645
|
+
const runAs = options.useLoginUser ? undefined : (options.runAs ?? session.config.runAs);
|
|
646
|
+
let fullCommand;
|
|
647
|
+
if (runAs) {
|
|
648
|
+
if (!this.isValidUsername(runAs)) {
|
|
649
|
+
throw new Error(`Invalid username: ${runAs}`);
|
|
650
|
+
}
|
|
651
|
+
const loadProfile = options.loadProfile ?? true;
|
|
652
|
+
const targetCommand = this.buildCommand(`${loadProfile ? this.getLoadProfileCommand() : ''}${wrappedCommand}`, session, options);
|
|
653
|
+
fullCommand = `su - ${runAs} -c ${this.escapeShellArg(targetCommand)}`;
|
|
654
|
+
}
|
|
655
|
+
else {
|
|
656
|
+
fullCommand = this.buildCommand(wrappedCommand, session, options);
|
|
657
|
+
}
|
|
658
|
+
return new Promise((resolve, reject) => {
|
|
659
|
+
session.client.exec(fullCommand, {}, (error, stream) => {
|
|
660
|
+
if (!this.isCurrentSession(alias, session)) {
|
|
661
|
+
this.closeClientChannel(stream);
|
|
662
|
+
reject(new Error('Operation start was cancelled because the SSH session changed'));
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
if (error) {
|
|
666
|
+
reject(new Error(`Operation start failed: ${error.message}`));
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
try {
|
|
670
|
+
adopt(stream);
|
|
671
|
+
resolve();
|
|
672
|
+
}
|
|
673
|
+
catch (adoptionError) {
|
|
674
|
+
this.closeClientChannel(stream);
|
|
675
|
+
reject(adoptionError);
|
|
676
|
+
}
|
|
677
|
+
});
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
async cancelRemoteOperation(alias, pid, marker, processGroup, options) {
|
|
681
|
+
const expectedMarker = `MCP_SSH_OPERATION_MARKER=${marker}`;
|
|
682
|
+
const signalTarget = processGroup ? `-${pid}` : `${pid}`;
|
|
683
|
+
const command = [
|
|
684
|
+
`pid=${pid}`,
|
|
685
|
+
`expected=${this.escapeShellArg(expectedMarker)}`,
|
|
686
|
+
'if [ ! -r "/proc/$pid/environ" ]; then printf "operation marker unavailable" >&2; exit 3; fi',
|
|
687
|
+
'if ! tr "\\000" "\\n" < "/proc/$pid/environ" | grep -Fqx -- "$expected"; then printf "operation marker mismatch" >&2; exit 4; fi',
|
|
688
|
+
`kill -TERM -- ${signalTarget}`,
|
|
689
|
+
].join('; ');
|
|
690
|
+
try {
|
|
691
|
+
const result = await this.exec(alias, command, {
|
|
692
|
+
runAs: options.runAs,
|
|
693
|
+
useLoginUser: options.useLoginUser,
|
|
694
|
+
loadProfile: false,
|
|
695
|
+
timeout: 5000,
|
|
696
|
+
maxOutputSize: 4096,
|
|
697
|
+
});
|
|
698
|
+
return result.success
|
|
699
|
+
? { success: true }
|
|
700
|
+
: { success: false, error: result.stderr || `Remote cancel exited with code ${result.exitCode}` };
|
|
701
|
+
}
|
|
702
|
+
catch (error) {
|
|
703
|
+
return { success: false, error: error instanceof Error ? error.message : String(error) };
|
|
704
|
+
}
|
|
705
|
+
}
|
|
424
706
|
async execDirect(alias, command, options = {}, context = {}) {
|
|
425
707
|
const session = this.getSession(alias);
|
|
426
708
|
const startTime = Date.now();
|
|
@@ -477,12 +759,17 @@ export class SessionManager {
|
|
|
477
759
|
rejectOnce(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
|
|
478
760
|
}, timeout);
|
|
479
761
|
session.client.exec(fullCommand, execOptions, (err, stream) => {
|
|
762
|
+
if (!this.isCurrentSession(alias, session)) {
|
|
763
|
+
this.closeClientChannel(stream);
|
|
764
|
+
rejectOnce(new Error('Exec was cancelled because the SSH session changed'));
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
480
767
|
if (err) {
|
|
481
768
|
rejectOnce(new Error(`Exec failed: ${err.message}`));
|
|
482
769
|
return;
|
|
483
770
|
}
|
|
484
771
|
if (settled) {
|
|
485
|
-
|
|
772
|
+
this.closeClientChannel(stream);
|
|
486
773
|
return;
|
|
487
774
|
}
|
|
488
775
|
activeStream = stream;
|
|
@@ -537,14 +824,14 @@ export class SessionManager {
|
|
|
537
824
|
});
|
|
538
825
|
});
|
|
539
826
|
}
|
|
540
|
-
async connectInternal(config, alias) {
|
|
827
|
+
async connectInternal(config, alias, pendingConnection) {
|
|
541
828
|
// 检查是否已有活跃连接
|
|
542
829
|
const existing = this.sessions.get(alias);
|
|
543
830
|
if (existing && this.isAlive(existing)) {
|
|
544
831
|
const existingIdentity = this.sessionIdentity(existing);
|
|
545
832
|
const requestedIdentity = this.configIdentity(config);
|
|
546
|
-
if (
|
|
547
|
-
throw new CommandError(`Alias '${alias}' is already connected
|
|
833
|
+
if (this.connectionFingerprint(existing.config) !== pendingConnection.fingerprint) {
|
|
834
|
+
throw new CommandError(`Alias '${alias}' is already connected with different session configuration`, {
|
|
548
835
|
alias,
|
|
549
836
|
existingIdentity,
|
|
550
837
|
requestedIdentity,
|
|
@@ -555,42 +842,97 @@ export class SessionManager {
|
|
|
555
842
|
return alias;
|
|
556
843
|
}
|
|
557
844
|
const client = new Client();
|
|
558
|
-
|
|
845
|
+
pendingConnection.client = client;
|
|
846
|
+
const readyTimeout = config.readyTimeout ?? this.defaultTimeout;
|
|
559
847
|
const connectConfig = {
|
|
560
848
|
host: config.host,
|
|
561
849
|
port: config.port ?? 22,
|
|
562
850
|
username: config.username,
|
|
563
|
-
readyTimeout
|
|
851
|
+
readyTimeout,
|
|
564
852
|
keepaliveInterval: config.keepaliveInterval ?? this.defaultKeepaliveInterval,
|
|
565
853
|
keepaliveCountMax: config.keepaliveCountMax ?? this.defaultKeepaliveCountMax,
|
|
566
854
|
};
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
855
|
+
try {
|
|
856
|
+
if (config.password) {
|
|
857
|
+
connectConfig.password = config.password;
|
|
858
|
+
}
|
|
859
|
+
if (config.privateKeyPath) {
|
|
860
|
+
const keyPath = expandTilde(config.privateKeyPath);
|
|
861
|
+
// 路径白名单 + 大小上限校验,避免任意文件读取
|
|
862
|
+
validateKeyFile(keyPath);
|
|
863
|
+
connectConfig.privateKey = fs.readFileSync(keyPath);
|
|
864
|
+
}
|
|
865
|
+
if (config.privateKey) {
|
|
866
|
+
connectConfig.privateKey = config.privateKey;
|
|
867
|
+
}
|
|
868
|
+
if (config.passphrase) {
|
|
869
|
+
connectConfig.passphrase = config.passphrase;
|
|
870
|
+
}
|
|
579
871
|
}
|
|
580
|
-
|
|
581
|
-
|
|
872
|
+
catch (error) {
|
|
873
|
+
throw this.createConnectionError(error, config, readyTimeout, 'key_read');
|
|
582
874
|
}
|
|
583
|
-
// 跳板机支持
|
|
584
875
|
if (config.jumpHost) {
|
|
585
|
-
const
|
|
876
|
+
const jumpConfig = {
|
|
877
|
+
...config.jumpHost,
|
|
878
|
+
readyTimeout: config.jumpHost.readyTimeout ?? readyTimeout,
|
|
879
|
+
};
|
|
880
|
+
let jumpAlias;
|
|
881
|
+
try {
|
|
882
|
+
jumpAlias = await this.connect(jumpConfig);
|
|
883
|
+
}
|
|
884
|
+
catch (error) {
|
|
885
|
+
if (error instanceof ConnectionError) {
|
|
886
|
+
throw new ConnectionError(error.message, {
|
|
887
|
+
...error.details,
|
|
888
|
+
connectionStep: 'jump_connect',
|
|
889
|
+
});
|
|
890
|
+
}
|
|
891
|
+
throw this.createConnectionError(error, jumpConfig, jumpConfig.readyTimeout, 'jump_connect');
|
|
892
|
+
}
|
|
586
893
|
const jumpSession = this.sessions.get(jumpAlias);
|
|
587
|
-
if (jumpSession) {
|
|
588
|
-
|
|
589
|
-
|
|
894
|
+
if (!jumpSession || !this.isAlive(jumpSession)) {
|
|
895
|
+
throw new ConnectionError(`Jump host session '${jumpAlias}' is unavailable`, {
|
|
896
|
+
failureStage: 'transport_or_handshake',
|
|
897
|
+
connectionStep: 'jump_connect',
|
|
898
|
+
retryable: true,
|
|
899
|
+
suggestion: '重新连接跳板机,或检查 jumpHost 配置和网络路径',
|
|
900
|
+
});
|
|
590
901
|
}
|
|
902
|
+
connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port || 22, readyTimeout);
|
|
903
|
+
}
|
|
904
|
+
if (!this.isCurrentPendingConnection(alias, pendingConnection)) {
|
|
905
|
+
client.end();
|
|
906
|
+
this.closeClientChannel(connectConfig.sock);
|
|
907
|
+
throw new Error(`Connection for alias '${alias}' was cancelled before SSH setup started`);
|
|
591
908
|
}
|
|
592
909
|
return new Promise((resolve, reject) => {
|
|
910
|
+
let settled = false;
|
|
911
|
+
const clearPendingConnection = () => {
|
|
912
|
+
if (this.pendingConnections.get(alias) === pendingConnection) {
|
|
913
|
+
this.pendingConnections.delete(alias);
|
|
914
|
+
}
|
|
915
|
+
};
|
|
916
|
+
const rejectConnection = (error) => {
|
|
917
|
+
if (settled) {
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
settled = true;
|
|
921
|
+
clearPendingConnection();
|
|
922
|
+
reject(this.createConnectionError(error, config, readyTimeout, 'target_connect'));
|
|
923
|
+
};
|
|
593
924
|
client.on('ready', () => {
|
|
925
|
+
if (settled || !this.isCurrentPendingConnection(alias, pendingConnection)) {
|
|
926
|
+
clearPendingConnection();
|
|
927
|
+
client.end();
|
|
928
|
+
if (!settled) {
|
|
929
|
+
settled = true;
|
|
930
|
+
reject(this.createConnectionError(new Error(`Connection for alias '${alias}' was cancelled before ready`), config, readyTimeout, 'target_connect'));
|
|
931
|
+
}
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
settled = true;
|
|
935
|
+
clearPendingConnection();
|
|
594
936
|
const session = {
|
|
595
937
|
client,
|
|
596
938
|
config,
|
|
@@ -604,29 +946,32 @@ export class SessionManager {
|
|
|
604
946
|
this.persistSessions();
|
|
605
947
|
resolve(alias);
|
|
606
948
|
});
|
|
607
|
-
client.on('error', (
|
|
949
|
+
client.on('error', (error) => {
|
|
608
950
|
const session = this.sessions.get(alias);
|
|
609
951
|
if (session && session.client === client) {
|
|
610
952
|
session.connected = false;
|
|
611
953
|
}
|
|
612
|
-
|
|
613
|
-
const safeMessage = sanitizeKeyError(err.message);
|
|
614
|
-
const suggestion = this.diagnoseConnectionError(err);
|
|
615
|
-
reject(new Error(`SSH connection to ${target} failed: ${safeMessage}${suggestion ? ` (${suggestion})` : ''}`));
|
|
954
|
+
rejectConnection(error);
|
|
616
955
|
});
|
|
617
956
|
client.on('close', () => {
|
|
618
957
|
const session = this.sessions.get(alias);
|
|
619
958
|
if (session && session.client === client) {
|
|
620
959
|
session.connected = false;
|
|
621
|
-
|
|
622
|
-
this.forwardManager.closeByAlias(alias);
|
|
623
|
-
this.ptyManager.closeByAlias(alias);
|
|
960
|
+
this.invalidateAliasResources(alias);
|
|
624
961
|
if (!session.manualClose) {
|
|
625
962
|
this.scheduleReconnect(alias);
|
|
626
963
|
}
|
|
627
964
|
}
|
|
965
|
+
else if (!settled) {
|
|
966
|
+
rejectConnection(new Error(`Connection for alias '${alias}' closed before ready`));
|
|
967
|
+
}
|
|
628
968
|
});
|
|
629
|
-
|
|
969
|
+
try {
|
|
970
|
+
client.connect(connectConfig);
|
|
971
|
+
}
|
|
972
|
+
catch (error) {
|
|
973
|
+
rejectConnection(error);
|
|
974
|
+
}
|
|
630
975
|
});
|
|
631
976
|
}
|
|
632
977
|
/**
|
|
@@ -643,12 +988,16 @@ export class SessionManager {
|
|
|
643
988
|
term: options.term || 'xterm-256color',
|
|
644
989
|
},
|
|
645
990
|
}, (err, stream) => {
|
|
991
|
+
if (!this.isCurrentSession(alias, session)) {
|
|
992
|
+
this.closeClientChannel(stream);
|
|
993
|
+
reject(new Error('PTY start was cancelled because the SSH session changed'));
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
646
996
|
if (err) {
|
|
647
997
|
reject(new Error(`PTY exec failed: ${err.message}`));
|
|
998
|
+
return;
|
|
648
999
|
}
|
|
649
|
-
|
|
650
|
-
resolve(stream);
|
|
651
|
-
}
|
|
1000
|
+
resolve(stream);
|
|
652
1001
|
});
|
|
653
1002
|
});
|
|
654
1003
|
}
|
|
@@ -667,11 +1016,35 @@ export class SessionManager {
|
|
|
667
1016
|
/**
|
|
668
1017
|
* 通过跳板机转发连接
|
|
669
1018
|
*/
|
|
670
|
-
forwardConnection(jumpClient, targetHost, targetPort) {
|
|
1019
|
+
forwardConnection(jumpClient, targetHost, targetPort, timeout) {
|
|
671
1020
|
return new Promise((resolve, reject) => {
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
1021
|
+
let settled = false;
|
|
1022
|
+
const timer = setTimeout(() => {
|
|
1023
|
+
if (settled) {
|
|
1024
|
+
return;
|
|
1025
|
+
}
|
|
1026
|
+
settled = true;
|
|
1027
|
+
reject(new ConnectionError(`Jump host forwarding to ${targetHost}:${targetPort} timed out`, {
|
|
1028
|
+
failureStage: 'ready_timeout',
|
|
1029
|
+
connectionStep: 'jump_forward',
|
|
1030
|
+
retryable: true,
|
|
1031
|
+
suggestion: '检查跳板机到目标地址的网络路径,必要时提高 readyTimeout',
|
|
1032
|
+
}));
|
|
1033
|
+
}, timeout);
|
|
1034
|
+
jumpClient.forwardOut('127.0.0.1', 0, targetHost, targetPort, (error, stream) => {
|
|
1035
|
+
if (settled) {
|
|
1036
|
+
this.closeClientChannel(stream);
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
settled = true;
|
|
1040
|
+
clearTimeout(timer);
|
|
1041
|
+
if (error) {
|
|
1042
|
+
reject(new ConnectionError(`Jump host forwarding to ${targetHost}:${targetPort} failed`, {
|
|
1043
|
+
failureStage: 'transport_or_handshake',
|
|
1044
|
+
connectionStep: 'jump_forward',
|
|
1045
|
+
retryable: true,
|
|
1046
|
+
suggestion: '检查跳板机到目标地址的网络路径、目标端口和防火墙',
|
|
1047
|
+
}));
|
|
675
1048
|
}
|
|
676
1049
|
else {
|
|
677
1050
|
resolve(stream);
|
|
@@ -679,12 +1052,62 @@ export class SessionManager {
|
|
|
679
1052
|
});
|
|
680
1053
|
});
|
|
681
1054
|
}
|
|
1055
|
+
getConnectionGeneration(alias) {
|
|
1056
|
+
return this.connectionGenerations.get(alias) ?? 0;
|
|
1057
|
+
}
|
|
1058
|
+
isCurrentPendingConnection(alias, pending) {
|
|
1059
|
+
return (this.pendingConnections.get(alias) === pending && this.getConnectionGeneration(alias) === pending.generation);
|
|
1060
|
+
}
|
|
1061
|
+
cancelPendingConnection(alias) {
|
|
1062
|
+
this.connectionGenerations.set(alias, this.getConnectionGeneration(alias) + 1);
|
|
1063
|
+
const pending = this.pendingConnections.get(alias);
|
|
1064
|
+
const inFlight = this.connectInFlight.delete(alias);
|
|
1065
|
+
if (!pending) {
|
|
1066
|
+
return inFlight;
|
|
1067
|
+
}
|
|
1068
|
+
this.pendingConnections.delete(alias);
|
|
1069
|
+
pending.cancel(new Error(`Connection for alias '${alias}' was cancelled`));
|
|
1070
|
+
return true;
|
|
1071
|
+
}
|
|
1072
|
+
invalidateAliasResources(alias) {
|
|
1073
|
+
// 连接身份变化后,旧 client 上的 operation、PTY、forward 和传输能力缓存均不再有效
|
|
1074
|
+
this.operationManager.markAliasDisconnected(alias);
|
|
1075
|
+
this.ptyManager.closeByAlias(alias);
|
|
1076
|
+
this.forwardManager.closeByAlias(alias);
|
|
1077
|
+
clearRsyncCache(alias);
|
|
1078
|
+
}
|
|
682
1079
|
/**
|
|
683
1080
|
* 检查连接是否存活
|
|
684
1081
|
*/
|
|
685
1082
|
isAlive(session) {
|
|
686
1083
|
return session.connected;
|
|
687
1084
|
}
|
|
1085
|
+
isCurrentSession(alias, session) {
|
|
1086
|
+
const currentSession = this.sessions.get(alias);
|
|
1087
|
+
return currentSession === session && currentSession.client === session.client && currentSession.connected;
|
|
1088
|
+
}
|
|
1089
|
+
closeClientChannel(stream) {
|
|
1090
|
+
try {
|
|
1091
|
+
stream?.destroy();
|
|
1092
|
+
}
|
|
1093
|
+
catch {
|
|
1094
|
+
// ignore
|
|
1095
|
+
}
|
|
1096
|
+
try {
|
|
1097
|
+
stream?.close();
|
|
1098
|
+
}
|
|
1099
|
+
catch {
|
|
1100
|
+
// ignore
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
destroySftp(sftp) {
|
|
1104
|
+
try {
|
|
1105
|
+
sftp?.destroy();
|
|
1106
|
+
}
|
|
1107
|
+
catch {
|
|
1108
|
+
// ignore
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
688
1111
|
/**
|
|
689
1112
|
* 调度自动重连(支持多次重试)
|
|
690
1113
|
*/
|
|
@@ -701,18 +1124,18 @@ export class SessionManager {
|
|
|
701
1124
|
const attempt = session.reconnectAttempts;
|
|
702
1125
|
session.reconnectTimer = setTimeout(async () => {
|
|
703
1126
|
const current = this.sessions.get(alias);
|
|
704
|
-
if (
|
|
705
|
-
// disconnect 已经把 session 移除,不再重连
|
|
1127
|
+
if (current !== session || current.client !== session.client) {
|
|
706
1128
|
return;
|
|
707
1129
|
}
|
|
708
|
-
|
|
1130
|
+
session.reconnectTimer = undefined;
|
|
709
1131
|
try {
|
|
710
1132
|
await this.reconnect(alias);
|
|
711
1133
|
}
|
|
712
1134
|
catch (err) {
|
|
713
1135
|
console.error(`Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}):`, err.message);
|
|
714
|
-
|
|
715
|
-
|
|
1136
|
+
if (this.sessions.get(alias) === session) {
|
|
1137
|
+
this.scheduleReconnect(alias);
|
|
1138
|
+
}
|
|
716
1139
|
}
|
|
717
1140
|
}, this.reconnectDelay);
|
|
718
1141
|
}
|
|
@@ -744,28 +1167,53 @@ export class SessionManager {
|
|
|
744
1167
|
],
|
|
745
1168
|
});
|
|
746
1169
|
}
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
if (code === 'ECONNREFUSED' || msg.includes('ECONNREFUSED')) {
|
|
754
|
-
return 'check if SSH service is running on the target host';
|
|
1170
|
+
createConnectionError(error, config, readyTimeout, connectionStep) {
|
|
1171
|
+
if (error instanceof ConnectionError) {
|
|
1172
|
+
return new ConnectionError(error.message, {
|
|
1173
|
+
...error.details,
|
|
1174
|
+
connectionStep: error.details.connectionStep ?? connectionStep,
|
|
1175
|
+
});
|
|
755
1176
|
}
|
|
756
|
-
|
|
757
|
-
|
|
1177
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1178
|
+
const target = `${config.username}@${config.host}:${config.port || 22}`;
|
|
1179
|
+
return new ConnectionError(`SSH connection to ${target} failed: ${sanitizeKeyError(err.message)}`, {
|
|
1180
|
+
...this.classifyConnectionError(err, readyTimeout),
|
|
1181
|
+
connectionStep,
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
classifyConnectionError(err, readyTimeout) {
|
|
1185
|
+
const message = err.message || '';
|
|
1186
|
+
const code = err.code || '';
|
|
1187
|
+
if (message.includes('All configured authentication methods failed') || err.level === 'client-authentication') {
|
|
1188
|
+
return {
|
|
1189
|
+
failureStage: 'authentication',
|
|
1190
|
+
retryable: false,
|
|
1191
|
+
suggestion: '检查用户名、密码、keyPath、passphrase 和远端 authorized_keys',
|
|
1192
|
+
};
|
|
758
1193
|
}
|
|
759
|
-
if (
|
|
760
|
-
|
|
1194
|
+
if (message.includes('Timed out while waiting for handshake') ||
|
|
1195
|
+
message.includes(`Timed out after ${readyTimeout}`)) {
|
|
1196
|
+
return {
|
|
1197
|
+
failureStage: 'ready_timeout',
|
|
1198
|
+
retryable: true,
|
|
1199
|
+
suggestion: '检查网络路径、跳板机和服务端握手延迟,必要时提高 readyTimeout',
|
|
1200
|
+
};
|
|
761
1201
|
}
|
|
762
|
-
if (
|
|
763
|
-
return '
|
|
1202
|
+
if (code === 'ENOTFOUND' || message.includes('getaddrinfo')) {
|
|
1203
|
+
return { failureStage: 'preflight', retryable: false, suggestion: '检查 host 或 DNS 配置' };
|
|
764
1204
|
}
|
|
765
|
-
if (
|
|
766
|
-
|
|
1205
|
+
if (code === 'ECONNREFUSED' ||
|
|
1206
|
+
code === 'ECONNRESET' ||
|
|
1207
|
+
code === 'ETIMEDOUT' ||
|
|
1208
|
+
message.includes('handshake') ||
|
|
1209
|
+
message.includes('ECONN')) {
|
|
1210
|
+
return {
|
|
1211
|
+
failureStage: 'transport_or_handshake',
|
|
1212
|
+
retryable: code !== 'ECONNREFUSED',
|
|
1213
|
+
suggestion: '检查目标端口、防火墙、ProxyJump 和 SSH 服务状态',
|
|
1214
|
+
};
|
|
767
1215
|
}
|
|
768
|
-
return '';
|
|
1216
|
+
return { failureStage: 'unknown', retryable: false };
|
|
769
1217
|
}
|
|
770
1218
|
/**
|
|
771
1219
|
* 转义 shell 参数(使用单引号方式,防止命令注入)
|
|
@@ -790,21 +1238,23 @@ export class SessionManager {
|
|
|
790
1238
|
* 构建完整命令:注入环境变量 + 切换工作目录
|
|
791
1239
|
*/
|
|
792
1240
|
buildCommand(command, session, options) {
|
|
793
|
-
|
|
1241
|
+
const segments = [];
|
|
794
1242
|
const env = options.skipSessionEnv
|
|
795
1243
|
? { ...options.env }
|
|
796
1244
|
: { ...session.config.defaultEnv, ...session.config.env, ...options.env };
|
|
797
|
-
if (
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
1245
|
+
if (options.cwd) {
|
|
1246
|
+
segments.push(`cd ${this.escapeShellArg(options.cwd)}`);
|
|
1247
|
+
}
|
|
1248
|
+
for (const [key, value] of Object.entries(env)) {
|
|
1249
|
+
if (this.isValidEnvKey(key)) {
|
|
1250
|
+
segments.push(`export ${key}=${this.escapeShellArg(value)}`);
|
|
802
1251
|
}
|
|
803
1252
|
}
|
|
804
|
-
if (
|
|
805
|
-
|
|
1253
|
+
if (segments.length === 0) {
|
|
1254
|
+
return command;
|
|
806
1255
|
}
|
|
807
|
-
|
|
1256
|
+
segments.push(`eval ${this.escapeShellArg(command)}`);
|
|
1257
|
+
return segments.join(' && ');
|
|
808
1258
|
}
|
|
809
1259
|
/**
|
|
810
1260
|
* 根据用户 shell 类型生成加载配置文件的命令
|