@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.
@@ -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
- // 复用同 alias 的 in-flight connect Promise
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
- return inFlight;
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 promise = this.connectInternal(config, alias).finally(() => {
57
- this.connectInFlight.delete(alias);
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
- this.connectInFlight.set(alias, promise);
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
- // 清理关联的 PTY 和 forward 资源
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 false;
166
+ return pendingCancelled;
108
167
  }
109
168
  /** 断开所有活跃会话(SIGINT/SIGTERM 时调用) */
110
169
  async disconnectAll() {
111
- const aliases = Array.from(this.sessions.keys());
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
- const result = [];
135
- for (const [alias, session] of this.sessions) {
136
- const authMethod = session.config.privateKeyPath
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.password
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
- const port = session.config.port || 22;
142
- result.push({
143
- alias,
144
- identity: this.sessionIdentity(session),
145
- host: session.config.host,
146
- port,
147
- username: session.config.username,
148
- runAs: session.config.runAs,
149
- keyPath: session.config.privateKeyPath,
150
- authMethod,
151
- connected: this.isAlive(session),
152
- connectedAt: session.connectedAt,
153
- lastUsedAt: session.lastUsedAt,
154
- });
155
- }
156
- return result;
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 = true;
248
- reject(new Error(`Exec failed: ${err.message}`));
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
- else {
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
- stream.close();
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 (existingIdentity !== requestedIdentity) {
547
- throw new CommandError(`Alias '${alias}' is already connected to ${existingIdentity}`, {
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: config.readyTimeout ?? this.defaultTimeout,
851
+ readyTimeout,
564
852
  keepaliveInterval: config.keepaliveInterval ?? this.defaultKeepaliveInterval,
565
853
  keepaliveCountMax: config.keepaliveCountMax ?? this.defaultKeepaliveCountMax,
566
854
  };
567
- // 认证方式
568
- if (config.password) {
569
- connectConfig.password = config.password;
570
- }
571
- if (config.privateKeyPath) {
572
- const keyPath = expandTilde(config.privateKeyPath);
573
- // 路径白名单 + 大小上限校验,避免任意文件读取
574
- validateKeyFile(keyPath);
575
- connectConfig.privateKey = fs.readFileSync(keyPath);
576
- }
577
- if (config.privateKey) {
578
- connectConfig.privateKey = config.privateKey;
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
- if (config.passphrase) {
581
- connectConfig.passphrase = config.passphrase;
872
+ catch (error) {
873
+ throw this.createConnectionError(error, config, readyTimeout, 'key_read');
582
874
  }
583
- // 跳板机支持
584
875
  if (config.jumpHost) {
585
- const jumpAlias = await this.connect(config.jumpHost);
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
- connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port || 22);
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', (err) => {
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
- const target = `${connectConfig.username}@${connectConfig.host}:${connectConfig.port}`;
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
- // 清理绑定旧 client 的 forward/PTY 资源
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
- client.connect(connectConfig);
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
- else {
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
- jumpClient.forwardOut('127.0.0.1', 0, targetHost, targetPort, (err, stream) => {
673
- if (err) {
674
- reject(err);
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 (!current) {
705
- // disconnect 已经把 session 移除,不再重连
1127
+ if (current !== session || current.client !== session.client) {
706
1128
  return;
707
1129
  }
708
- current.reconnectTimer = undefined;
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
- // reconnect 失败后继续调度下一次尝试
715
- this.scheduleReconnect(alias);
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
- diagnoseConnectionError(err) {
751
- const msg = err.message || '';
752
- const code = err.code || '';
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
- if (code === 'ETIMEDOUT' || msg.includes('ETIMEDOUT') || msg.includes('Timed out')) {
757
- return 'check host reachability, firewall rules, or try a jump host';
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 (code === 'ENOTFOUND' || msg.includes('ENOTFOUND') || msg.includes('getaddrinfo')) {
760
- return 'hostname cannot be resolved, check DNS or use IP address';
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 (msg.includes('All configured authentication methods failed')) {
763
- return 'check password, key path, or key permissions (chmod 600)';
1202
+ if (code === 'ENOTFOUND' || message.includes('getaddrinfo')) {
1203
+ return { failureStage: 'preflight', retryable: false, suggestion: '检查 host 或 DNS 配置' };
764
1204
  }
765
- if (msg.includes('ECONNRESET') || msg.includes('Connection reset')) {
766
- return 'connection was reset by the remote host';
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
- let fullCommand = command;
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 (Object.keys(env).length > 0) {
798
- const validEntries = Object.entries(env).filter(([k]) => this.isValidEnvKey(k));
799
- if (validEntries.length > 0) {
800
- const envStr = validEntries.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`).join('; ');
801
- fullCommand = `${envStr}; ${command}`;
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 (options.cwd) {
805
- fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`;
1253
+ if (segments.length === 0) {
1254
+ return command;
806
1255
  }
807
- return fullCommand;
1256
+ segments.push(`eval ${this.escapeShellArg(command)}`);
1257
+ return segments.join(' && ');
808
1258
  }
809
1259
  /**
810
1260
  * 根据用户 shell 类型生成加载配置文件的命令