@pyrokine/mcp-ssh 2.4.0 → 2.4.2

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,6 +7,7 @@
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';
@@ -39,6 +40,8 @@ export class SessionManager {
39
40
  sessions = new Map();
40
41
  /** per-alias connect 进行中的 Promise,防止并发 connect 同一 alias 时重复建连 */
41
42
  connectInFlight = new Map();
43
+ pendingConnections = new Map();
44
+ connectionGenerations = new Map();
42
45
  ptyManager = new PtyManager();
43
46
  forwardManager = new ForwardManager();
44
47
  operationManager;
@@ -52,7 +55,7 @@ export class SessionManager {
52
55
  constructor(persistPath) {
53
56
  this.persistPath = persistPath || path.join(os.homedir(), '.ssh-mcp-pro', 'sessions.json');
54
57
  this.operationManager = new OperationManager({
55
- openStream: (alias, command, marker, options) => this.openOperationStream(alias, command, marker, options),
58
+ openStream: (alias, command, marker, options, adopt) => this.openOperationStream(alias, command, marker, options, adopt),
56
59
  cancelRemote: (alias, pid, marker, processGroup, options) => this.cancelRemoteOperation(alias, pid, marker, processGroup, options),
57
60
  });
58
61
  this.ensurePersistDir();
@@ -62,15 +65,54 @@ export class SessionManager {
62
65
  */
63
66
  async connect(config) {
64
67
  const alias = this.generateAlias(config);
65
- // 复用同 alias 的 in-flight connect Promise
68
+ const fingerprint = this.connectionFingerprint(config);
69
+ const requestedIdentity = this.configIdentity(config);
66
70
  const inFlight = this.connectInFlight.get(alias);
67
71
  if (inFlight) {
68
- 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;
69
81
  }
70
- const promise = this.connectInternal(config, alias).finally(() => {
71
- 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;
87
+ });
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
+ }
72
114
  });
73
- this.connectInFlight.set(alias, promise);
115
+ this.connectInFlight.set(alias, { identity: requestedIdentity, fingerprint, promise });
74
116
  return promise;
75
117
  }
76
118
  /**
@@ -81,8 +123,14 @@ export class SessionManager {
81
123
  if (!session) {
82
124
  throw new Error(`Session ${alias} not found`);
83
125
  }
126
+ this.cancelPendingConnection(alias);
84
127
  session.manualClose = true;
85
128
  session.connected = false;
129
+ if (session.reconnectTimer) {
130
+ clearTimeout(session.reconnectTimer);
131
+ session.reconnectTimer = undefined;
132
+ }
133
+ this.invalidateAliasResources(alias);
86
134
  try {
87
135
  session.client.end();
88
136
  }
@@ -95,6 +143,7 @@ export class SessionManager {
95
143
  * 断开连接
96
144
  */
97
145
  disconnect(alias) {
146
+ const pendingCancelled = this.cancelPendingConnection(alias);
98
147
  const session = this.sessions.get(alias);
99
148
  if (session) {
100
149
  session.manualClose = true;
@@ -103,12 +152,7 @@ export class SessionManager {
103
152
  clearTimeout(session.reconnectTimer);
104
153
  session.reconnectTimer = undefined;
105
154
  }
106
- // 清理关联资源;tracked operation 的远端状态在连接断开后无法继续证明
107
- this.operationManager.markAliasDisconnected(alias);
108
- this.ptyManager.closeByAlias(alias);
109
- this.forwardManager.closeByAlias(alias);
110
- // 清理 file-ops 中的 rsync 可用性缓存,防止重连到不同主机后读到旧判断
111
- clearRsyncCache(alias);
155
+ this.invalidateAliasResources(alias);
112
156
  try {
113
157
  session.client.end();
114
158
  }
@@ -119,11 +163,11 @@ export class SessionManager {
119
163
  this.persistSessions();
120
164
  return true;
121
165
  }
122
- return false;
166
+ return pendingCancelled;
123
167
  }
124
168
  /** 断开所有活跃会话(SIGINT/SIGTERM 时调用) */
125
169
  async disconnectAll() {
126
- const aliases = Array.from(this.sessions.keys());
170
+ const aliases = new Set([...this.sessions.keys(), ...this.pendingConnections.keys()]);
127
171
  for (const alias of aliases) {
128
172
  this.disconnect(alias);
129
173
  }
@@ -156,7 +200,7 @@ export class SessionManager {
156
200
  alias,
157
201
  identity: this.sessionIdentity(session),
158
202
  host: session.config.host,
159
- port: session.config.port || 22,
203
+ port: session.config.port ?? 22,
160
204
  username: session.config.username,
161
205
  runAs: session.config.runAs,
162
206
  authMethod: session.config.privateKeyPath
@@ -172,6 +216,21 @@ export class SessionManager {
172
216
  hasJumpHost: Boolean(session.config.jumpHost),
173
217
  }));
174
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
+ }
175
234
  getExternalTransferCapability(alias) {
176
235
  const session = this.getSession(alias);
177
236
  const config = session.config;
@@ -205,7 +264,7 @@ export class SessionManager {
205
264
  alias,
206
265
  identity: this.sessionIdentity(session),
207
266
  host: config.host,
208
- port: config.port || 22,
267
+ port: config.port ?? 22,
209
268
  username: config.username,
210
269
  authMethod,
211
270
  keyPath: keyPathUsable ? expandedKeyPath : undefined,
@@ -280,7 +339,28 @@ export class SessionManager {
280
339
  const startTime = Date.now();
281
340
  const timeout = options.timeout ?? this.defaultTimeout;
282
341
  const maxOutputSize = this.normalizeMaxOutputSize(options.maxOutputSize);
283
- const fullCommand = this.buildCommand(`sudo -S ${command}`, session, options);
342
+ const runAs = options.useLoginUser ? undefined : (options.runAs ?? session.config.runAs);
343
+ let fullCommand;
344
+ let context;
345
+ if (runAs) {
346
+ if (!this.isValidUsername(runAs)) {
347
+ throw new Error(`Invalid username: ${runAs}`);
348
+ }
349
+ const loadProfile = options.loadProfile ?? true;
350
+ const targetCommand = this.buildCommand(`${loadProfile ? this.getLoadProfileCommand() : ''}sudo -S ${command}`, session, options);
351
+ const env = { ...session.config.defaultEnv, ...session.config.env, ...options.env };
352
+ fullCommand = `su - ${runAs} -c ${this.escapeShellArg(targetCommand)}`;
353
+ context = {
354
+ runAs,
355
+ loadProfile,
356
+ cwd: options.cwd,
357
+ envInjectedKeys: Object.keys(env).filter((key) => this.isValidEnvKey(key)),
358
+ };
359
+ }
360
+ else {
361
+ fullCommand = this.buildCommand(`sudo -S ${command}`, session, options);
362
+ context = { cwd: options.cwd };
363
+ }
284
364
  return new Promise((resolve, reject) => {
285
365
  let settled = false;
286
366
  let streamRef = null;
@@ -314,13 +394,28 @@ export class SessionManager {
314
394
  catch {
315
395
  // ignore
316
396
  }
317
- reject(this.createCommandTimeoutError(alias, timeout, { cwd: options.cwd }, outputPreview()));
397
+ reject(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
318
398
  }, timeout);
319
399
  session.client.exec(fullCommand, {}, (err, stream) => {
400
+ if (!this.isCurrentSession(alias, session)) {
401
+ clearTimeout(timeoutId);
402
+ this.closeClientChannel(stream);
403
+ if (!settled) {
404
+ settled = true;
405
+ reject(new Error('Sudo exec was cancelled because the SSH session changed'));
406
+ }
407
+ return;
408
+ }
320
409
  if (err) {
321
410
  clearTimeout(timeoutId);
322
- settled = true;
323
- reject(new Error(`Exec failed: ${err.message}`));
411
+ if (!settled) {
412
+ settled = true;
413
+ reject(new Error(`Exec failed: ${err.message}`));
414
+ }
415
+ return;
416
+ }
417
+ if (settled) {
418
+ this.closeClientChannel(stream);
324
419
  return;
325
420
  }
326
421
  streamRef = stream;
@@ -344,7 +439,7 @@ export class SessionManager {
344
439
  stderrTruncated: stderrTruncated || undefined,
345
440
  ...this.outputMetadata(outputPreview()),
346
441
  ...this.emptyOutputFailureMetadata(code, outputPreview()),
347
- ...this.resultMetadata(session, options, { cwd: options.cwd }),
442
+ ...this.resultMetadata(session, options, context),
348
443
  });
349
444
  });
350
445
  stream.on('data', (data) => {
@@ -385,12 +480,16 @@ export class SessionManager {
385
480
  const session = this.getSession(alias);
386
481
  return new Promise((resolve, reject) => {
387
482
  session.client.sftp((err, sftp) => {
483
+ if (!this.isCurrentSession(alias, session)) {
484
+ this.destroySftp(sftp);
485
+ reject(new Error('SFTP request was cancelled because the SSH session changed'));
486
+ return;
487
+ }
388
488
  if (err) {
389
489
  reject(err);
490
+ return;
390
491
  }
391
- else {
392
- resolve(sftp);
393
- }
492
+ resolve(sftp);
394
493
  });
395
494
  });
396
495
  }
@@ -465,7 +564,36 @@ export class SessionManager {
465
564
  return this.configIdentity(session.config);
466
565
  }
467
566
  configIdentity(config) {
468
- return `${config.username}@${config.host}:${config.port || 22}`;
567
+ return `${config.username}@${config.host}:${config.port ?? 22}`;
568
+ }
569
+ connectionFingerprint(config) {
570
+ const secretHash = (value) => value === undefined ? undefined : createHash('sha256').update(value).digest('hex');
571
+ const sortedEntries = (values) => values === undefined
572
+ ? undefined
573
+ : Object.entries(values).sort(([left], [right]) => left.localeCompare(right));
574
+ const payload = (value) => ({
575
+ host: value.host,
576
+ port: value.port ?? 22,
577
+ username: value.username,
578
+ alias: value.alias,
579
+ template: value.template,
580
+ runAs: value.runAs,
581
+ defaultEnv: sortedEntries(value.defaultEnv),
582
+ env: sortedEntries(value.env),
583
+ keepaliveInterval: value.keepaliveInterval,
584
+ keepaliveCountMax: value.keepaliveCountMax,
585
+ readyTimeout: value.readyTimeout,
586
+ lang: value.lang,
587
+ shell: value.shell,
588
+ password: secretHash(value.password),
589
+ privateKeyPath: value.privateKeyPath ? path.resolve(expandTilde(value.privateKeyPath)) : undefined,
590
+ privateKey: secretHash(value.privateKey),
591
+ passphrase: secretHash(value.passphrase),
592
+ jumpHost: value.jumpHost ? payload(value.jumpHost) : undefined,
593
+ });
594
+ return createHash('sha256')
595
+ .update(JSON.stringify(payload(config)))
596
+ .digest('hex');
469
597
  }
470
598
  resultMetadata(session, options, context) {
471
599
  const env = options.skipSessionEnv
@@ -487,7 +615,8 @@ export class SessionManager {
487
615
  return next.length > OUTPUT_PREVIEW_CHARS ? next.slice(-OUTPUT_PREVIEW_CHARS) : next;
488
616
  }
489
617
  recommendedReadCommand() {
490
- return '将远端命令输出重定向到文件,例如 command > /tmp/mcp-ssh-output.txt 2>&1,然后用 ssh_read_file(remotePath="/tmp/mcp-ssh-output.txt", tail=true, maxBytes=65536) 分块读取';
618
+ return ('将远端命令输出重定向到文件,例如 command > /tmp/mcp-ssh-output.txt 2>&1,' +
619
+ '再用 ssh_read_file(remotePath="/tmp/mcp-ssh-output.txt", tail=true, maxBytes=65536) 分块读取');
491
620
  }
492
621
  emptyOutputFailureMetadata(exitCode, preview) {
493
622
  if (exitCode === 0 || preview.stdoutBytes > 0 || preview.stderrBytes > 0) {
@@ -496,7 +625,8 @@ export class SessionManager {
496
625
  return {
497
626
  emptyOutputFailure: true,
498
627
  recommendedReadCommand: this.recommendedReadCommand(),
499
- suggestion: '远端命令以非零退出码结束,但没有 stdout/stderr。请检查 cwd、effectiveUser、shell/profile,或用 set -x / 显式重定向输出到文件后再用 ssh_read_file 读取',
628
+ suggestion: '远端命令以非零退出码结束,但没有 stdout/stderr。请检查 cwd、effectiveUser、shell/profile,' +
629
+ '或用 set -x / 显式重定向输出到文件后再用 ssh_read_file 读取',
500
630
  };
501
631
  }
502
632
  outputMetadata(preview) {
@@ -527,7 +657,7 @@ export class SessionManager {
527
657
  }
528
658
  return maxOutputSize;
529
659
  }
530
- async openOperationStream(alias, command, marker, options) {
660
+ async openOperationStream(alias, command, marker, options, adopt) {
531
661
  const session = this.getSession(alias);
532
662
  const markerEnv = `MCP_SSH_OPERATION_MARKER=${this.escapeShellArg(marker)}`;
533
663
  const markerLine = `__MCP_SSH_OPERATION__:${marker}:%s:%s\\n`;
@@ -550,11 +680,22 @@ export class SessionManager {
550
680
  }
551
681
  return new Promise((resolve, reject) => {
552
682
  session.client.exec(fullCommand, {}, (error, stream) => {
683
+ if (!this.isCurrentSession(alias, session)) {
684
+ this.closeClientChannel(stream);
685
+ reject(new Error('Operation start was cancelled because the SSH session changed'));
686
+ return;
687
+ }
553
688
  if (error) {
554
689
  reject(new Error(`Operation start failed: ${error.message}`));
690
+ return;
555
691
  }
556
- else {
557
- resolve(stream);
692
+ try {
693
+ adopt(stream);
694
+ resolve();
695
+ }
696
+ catch (adoptionError) {
697
+ this.closeClientChannel(stream);
698
+ reject(adoptionError);
558
699
  }
559
700
  });
560
701
  });
@@ -566,7 +707,8 @@ export class SessionManager {
566
707
  `pid=${pid}`,
567
708
  `expected=${this.escapeShellArg(expectedMarker)}`,
568
709
  'if [ ! -r "/proc/$pid/environ" ]; then printf "operation marker unavailable" >&2; exit 3; fi',
569
- 'if ! tr "\\000" "\\n" < "/proc/$pid/environ" | grep -Fqx -- "$expected"; then printf "operation marker mismatch" >&2; exit 4; fi',
710
+ 'if ! tr "\\000" "\\n" < "/proc/$pid/environ" | grep -Fqx -- "$expected"; then ' +
711
+ 'printf "operation marker mismatch" >&2; exit 4; fi',
570
712
  `kill -TERM -- ${signalTarget}`,
571
713
  ].join('; ');
572
714
  try {
@@ -606,9 +748,9 @@ export class SessionManager {
606
748
  const execOptions = {};
607
749
  if (options.pty) {
608
750
  execOptions.pty = {
609
- rows: options.rows || 24,
610
- cols: options.cols || 80,
611
- term: options.term || 'xterm-256color',
751
+ rows: options.rows ?? 24,
752
+ cols: options.cols ?? 80,
753
+ term: options.term ?? 'xterm-256color',
612
754
  };
613
755
  }
614
756
  const outputPreview = () => ({
@@ -641,12 +783,17 @@ export class SessionManager {
641
783
  rejectOnce(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
642
784
  }, timeout);
643
785
  session.client.exec(fullCommand, execOptions, (err, stream) => {
786
+ if (!this.isCurrentSession(alias, session)) {
787
+ this.closeClientChannel(stream);
788
+ rejectOnce(new Error('Exec was cancelled because the SSH session changed'));
789
+ return;
790
+ }
644
791
  if (err) {
645
792
  rejectOnce(new Error(`Exec failed: ${err.message}`));
646
793
  return;
647
794
  }
648
795
  if (settled) {
649
- stream.close();
796
+ this.closeClientChannel(stream);
650
797
  return;
651
798
  }
652
799
  activeStream = stream;
@@ -701,14 +848,14 @@ export class SessionManager {
701
848
  });
702
849
  });
703
850
  }
704
- async connectInternal(config, alias) {
851
+ async connectInternal(config, alias, pendingConnection) {
705
852
  // 检查是否已有活跃连接
706
853
  const existing = this.sessions.get(alias);
707
854
  if (existing && this.isAlive(existing)) {
708
855
  const existingIdentity = this.sessionIdentity(existing);
709
856
  const requestedIdentity = this.configIdentity(config);
710
- if (existingIdentity !== requestedIdentity) {
711
- throw new CommandError(`Alias '${alias}' is already connected to ${existingIdentity}`, {
857
+ if (this.connectionFingerprint(existing.config) !== pendingConnection.fingerprint) {
858
+ throw new CommandError(`Alias '${alias}' is already connected with different session configuration`, {
712
859
  alias,
713
860
  existingIdentity,
714
861
  requestedIdentity,
@@ -719,6 +866,7 @@ export class SessionManager {
719
866
  return alias;
720
867
  }
721
868
  const client = new Client();
869
+ pendingConnection.client = client;
722
870
  const readyTimeout = config.readyTimeout ?? this.defaultTimeout;
723
871
  const connectConfig = {
724
872
  host: config.host,
@@ -775,23 +923,40 @@ export class SessionManager {
775
923
  suggestion: '重新连接跳板机,或检查 jumpHost 配置和网络路径',
776
924
  });
777
925
  }
778
- connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port || 22, readyTimeout);
926
+ connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port ?? 22, readyTimeout);
927
+ }
928
+ if (!this.isCurrentPendingConnection(alias, pendingConnection)) {
929
+ client.end();
930
+ this.closeClientChannel(connectConfig.sock);
931
+ throw new Error(`Connection for alias '${alias}' was cancelled before SSH setup started`);
779
932
  }
780
933
  return new Promise((resolve, reject) => {
781
934
  let settled = false;
935
+ const clearPendingConnection = () => {
936
+ if (this.pendingConnections.get(alias) === pendingConnection) {
937
+ this.pendingConnections.delete(alias);
938
+ }
939
+ };
782
940
  const rejectConnection = (error) => {
783
941
  if (settled) {
784
942
  return;
785
943
  }
786
944
  settled = true;
945
+ clearPendingConnection();
787
946
  reject(this.createConnectionError(error, config, readyTimeout, 'target_connect'));
788
947
  };
789
948
  client.on('ready', () => {
790
- if (settled) {
949
+ if (settled || !this.isCurrentPendingConnection(alias, pendingConnection)) {
950
+ clearPendingConnection();
791
951
  client.end();
952
+ if (!settled) {
953
+ settled = true;
954
+ reject(this.createConnectionError(new Error(`Connection for alias '${alias}' was cancelled before ready`), config, readyTimeout, 'target_connect'));
955
+ }
792
956
  return;
793
957
  }
794
958
  settled = true;
959
+ clearPendingConnection();
795
960
  const session = {
796
961
  client,
797
962
  config,
@@ -816,14 +981,14 @@ export class SessionManager {
816
981
  const session = this.sessions.get(alias);
817
982
  if (session && session.client === client) {
818
983
  session.connected = false;
819
- // 清理绑定旧 client 的资源;tracked operation 状态已无法继续证明
820
- this.operationManager.markAliasDisconnected(alias);
821
- this.forwardManager.closeByAlias(alias);
822
- this.ptyManager.closeByAlias(alias);
984
+ this.invalidateAliasResources(alias);
823
985
  if (!session.manualClose) {
824
986
  this.scheduleReconnect(alias);
825
987
  }
826
988
  }
989
+ else if (!settled) {
990
+ rejectConnection(new Error(`Connection for alias '${alias}' closed before ready`));
991
+ }
827
992
  });
828
993
  try {
829
994
  client.connect(connectConfig);
@@ -842,17 +1007,21 @@ export class SessionManager {
842
1007
  return new Promise((resolve, reject) => {
843
1008
  session.client.exec(fullCommand, {
844
1009
  pty: {
845
- rows: options.rows || 24,
846
- cols: options.cols || 80,
847
- term: options.term || 'xterm-256color',
1010
+ rows: options.rows ?? 24,
1011
+ cols: options.cols ?? 80,
1012
+ term: options.term ?? 'xterm-256color',
848
1013
  },
849
1014
  }, (err, stream) => {
1015
+ if (!this.isCurrentSession(alias, session)) {
1016
+ this.closeClientChannel(stream);
1017
+ reject(new Error('PTY start was cancelled because the SSH session changed'));
1018
+ return;
1019
+ }
850
1020
  if (err) {
851
1021
  reject(new Error(`PTY exec failed: ${err.message}`));
1022
+ return;
852
1023
  }
853
- else {
854
- resolve(stream);
855
- }
1024
+ resolve(stream);
856
1025
  });
857
1026
  });
858
1027
  }
@@ -888,7 +1057,7 @@ export class SessionManager {
888
1057
  }, timeout);
889
1058
  jumpClient.forwardOut('127.0.0.1', 0, targetHost, targetPort, (error, stream) => {
890
1059
  if (settled) {
891
- stream?.close();
1060
+ this.closeClientChannel(stream);
892
1061
  return;
893
1062
  }
894
1063
  settled = true;
@@ -907,12 +1076,62 @@ export class SessionManager {
907
1076
  });
908
1077
  });
909
1078
  }
1079
+ getConnectionGeneration(alias) {
1080
+ return this.connectionGenerations.get(alias) ?? 0;
1081
+ }
1082
+ isCurrentPendingConnection(alias, pending) {
1083
+ return (this.pendingConnections.get(alias) === pending && this.getConnectionGeneration(alias) === pending.generation);
1084
+ }
1085
+ cancelPendingConnection(alias) {
1086
+ this.connectionGenerations.set(alias, this.getConnectionGeneration(alias) + 1);
1087
+ const pending = this.pendingConnections.get(alias);
1088
+ const inFlight = this.connectInFlight.delete(alias);
1089
+ if (!pending) {
1090
+ return inFlight;
1091
+ }
1092
+ this.pendingConnections.delete(alias);
1093
+ pending.cancel(new Error(`Connection for alias '${alias}' was cancelled`));
1094
+ return true;
1095
+ }
1096
+ invalidateAliasResources(alias) {
1097
+ // 连接身份变化后,旧 client 上的 operation、PTY、forward 和传输能力缓存均不再有效
1098
+ this.operationManager.markAliasDisconnected(alias);
1099
+ this.ptyManager.closeByAlias(alias);
1100
+ this.forwardManager.closeByAlias(alias);
1101
+ clearRsyncCache(alias);
1102
+ }
910
1103
  /**
911
1104
  * 检查连接是否存活
912
1105
  */
913
1106
  isAlive(session) {
914
1107
  return session.connected;
915
1108
  }
1109
+ isCurrentSession(alias, session) {
1110
+ const currentSession = this.sessions.get(alias);
1111
+ return currentSession === session && currentSession.client === session.client && currentSession.connected;
1112
+ }
1113
+ closeClientChannel(stream) {
1114
+ try {
1115
+ stream?.destroy();
1116
+ }
1117
+ catch {
1118
+ // ignore
1119
+ }
1120
+ try {
1121
+ stream?.close();
1122
+ }
1123
+ catch {
1124
+ // ignore
1125
+ }
1126
+ }
1127
+ destroySftp(sftp) {
1128
+ try {
1129
+ sftp?.destroy();
1130
+ }
1131
+ catch {
1132
+ // ignore
1133
+ }
1134
+ }
916
1135
  /**
917
1136
  * 调度自动重连(支持多次重试)
918
1137
  */
@@ -929,18 +1148,18 @@ export class SessionManager {
929
1148
  const attempt = session.reconnectAttempts;
930
1149
  session.reconnectTimer = setTimeout(async () => {
931
1150
  const current = this.sessions.get(alias);
932
- if (!current) {
933
- // disconnect 已经把 session 移除,不再重连
1151
+ if (current !== session || current.client !== session.client) {
934
1152
  return;
935
1153
  }
936
- current.reconnectTimer = undefined;
1154
+ session.reconnectTimer = undefined;
937
1155
  try {
938
1156
  await this.reconnect(alias);
939
1157
  }
940
1158
  catch (err) {
941
1159
  console.error(`Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}):`, err.message);
942
- // reconnect 失败后继续调度下一次尝试
943
- this.scheduleReconnect(alias);
1160
+ if (this.sessions.get(alias) === session) {
1161
+ this.scheduleReconnect(alias);
1162
+ }
944
1163
  }
945
1164
  }, this.reconnectDelay);
946
1165
  }
@@ -980,7 +1199,7 @@ export class SessionManager {
980
1199
  });
981
1200
  }
982
1201
  const err = error instanceof Error ? error : new Error(String(error));
983
- const target = `${config.username}@${config.host}:${config.port || 22}`;
1202
+ const target = `${config.username}@${config.host}:${config.port ?? 22}`;
984
1203
  return new ConnectionError(`SSH connection to ${target} failed: ${sanitizeKeyError(err.message)}`, {
985
1204
  ...this.classifyConnectionError(err, readyTimeout),
986
1205
  connectionStep,
@@ -1043,21 +1262,23 @@ export class SessionManager {
1043
1262
  * 构建完整命令:注入环境变量 + 切换工作目录
1044
1263
  */
1045
1264
  buildCommand(command, session, options) {
1046
- let fullCommand = command;
1265
+ const segments = [];
1047
1266
  const env = options.skipSessionEnv
1048
1267
  ? { ...options.env }
1049
1268
  : { ...session.config.defaultEnv, ...session.config.env, ...options.env };
1050
- if (Object.keys(env).length > 0) {
1051
- const validEntries = Object.entries(env).filter(([k]) => this.isValidEnvKey(k));
1052
- if (validEntries.length > 0) {
1053
- const envStr = validEntries.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`).join('; ');
1054
- fullCommand = `${envStr}; ${command}`;
1269
+ if (options.cwd) {
1270
+ segments.push(`cd ${this.escapeShellArg(options.cwd)}`);
1271
+ }
1272
+ for (const [key, value] of Object.entries(env)) {
1273
+ if (this.isValidEnvKey(key)) {
1274
+ segments.push(`export ${key}=${this.escapeShellArg(value)}`);
1055
1275
  }
1056
1276
  }
1057
- if (options.cwd) {
1058
- fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`;
1277
+ if (segments.length === 0) {
1278
+ return command;
1059
1279
  }
1060
- return fullCommand;
1280
+ segments.push(`eval ${this.escapeShellArg(command)}`);
1281
+ return segments.join(' && ');
1061
1282
  }
1062
1283
  /**
1063
1284
  * 根据用户 shell 类型生成加载配置文件的命令
@@ -1080,7 +1301,7 @@ export class SessionManager {
1080
1301
  data.push({
1081
1302
  alias,
1082
1303
  host: session.config.host,
1083
- port: session.config.port || 22,
1304
+ port: session.config.port ?? 22,
1084
1305
  username: session.config.username,
1085
1306
  runAs: session.config.runAs,
1086
1307
  connectedAt: session.connectedAt,
@@ -0,0 +1,9 @@
1
+ export declare const DEFAULT_SFTP_OPERATION_TIMEOUT_MS = 600000;
2
+ export declare const HARD_SFTP_OPERATION_TIMEOUT_MS = 3600000;
3
+ export declare class SftpOperationTimeoutError extends Error {
4
+ readonly timeout: number;
5
+ readonly details: Record<string, unknown>;
6
+ constructor(timeout: number);
7
+ }
8
+ export declare function normalizeSftpOperationTimeout(timeout: number | undefined): number;
9
+ export declare function withSftpOperationTimeout<T>(operation: Promise<T>, timeout: number | undefined, onTimeout: () => void): Promise<T>;