@pyrokine/mcp-ssh 2.4.0 → 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,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;
72
87
  });
73
- 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 });
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
  }
@@ -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;
@@ -317,10 +376,25 @@ export class SessionManager {
317
376
  reject(this.createCommandTimeoutError(alias, timeout, { cwd: options.cwd }, outputPreview()));
318
377
  }, timeout);
319
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
+ }
320
388
  if (err) {
321
389
  clearTimeout(timeoutId);
322
- settled = true;
323
- 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);
324
398
  return;
325
399
  }
326
400
  streamRef = stream;
@@ -385,12 +459,16 @@ export class SessionManager {
385
459
  const session = this.getSession(alias);
386
460
  return new Promise((resolve, reject) => {
387
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
+ }
388
467
  if (err) {
389
468
  reject(err);
469
+ return;
390
470
  }
391
- else {
392
- resolve(sftp);
393
- }
471
+ resolve(sftp);
394
472
  });
395
473
  });
396
474
  }
@@ -467,6 +545,35 @@ export class SessionManager {
467
545
  configIdentity(config) {
468
546
  return `${config.username}@${config.host}:${config.port || 22}`;
469
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
+ }
470
577
  resultMetadata(session, options, context) {
471
578
  const env = options.skipSessionEnv
472
579
  ? { ...options.env }
@@ -527,7 +634,7 @@ export class SessionManager {
527
634
  }
528
635
  return maxOutputSize;
529
636
  }
530
- async openOperationStream(alias, command, marker, options) {
637
+ async openOperationStream(alias, command, marker, options, adopt) {
531
638
  const session = this.getSession(alias);
532
639
  const markerEnv = `MCP_SSH_OPERATION_MARKER=${this.escapeShellArg(marker)}`;
533
640
  const markerLine = `__MCP_SSH_OPERATION__:${marker}:%s:%s\\n`;
@@ -550,11 +657,22 @@ export class SessionManager {
550
657
  }
551
658
  return new Promise((resolve, reject) => {
552
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
+ }
553
665
  if (error) {
554
666
  reject(new Error(`Operation start failed: ${error.message}`));
667
+ return;
555
668
  }
556
- else {
557
- resolve(stream);
669
+ try {
670
+ adopt(stream);
671
+ resolve();
672
+ }
673
+ catch (adoptionError) {
674
+ this.closeClientChannel(stream);
675
+ reject(adoptionError);
558
676
  }
559
677
  });
560
678
  });
@@ -641,12 +759,17 @@ export class SessionManager {
641
759
  rejectOnce(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
642
760
  }, timeout);
643
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
+ }
644
767
  if (err) {
645
768
  rejectOnce(new Error(`Exec failed: ${err.message}`));
646
769
  return;
647
770
  }
648
771
  if (settled) {
649
- stream.close();
772
+ this.closeClientChannel(stream);
650
773
  return;
651
774
  }
652
775
  activeStream = stream;
@@ -701,14 +824,14 @@ export class SessionManager {
701
824
  });
702
825
  });
703
826
  }
704
- async connectInternal(config, alias) {
827
+ async connectInternal(config, alias, pendingConnection) {
705
828
  // 检查是否已有活跃连接
706
829
  const existing = this.sessions.get(alias);
707
830
  if (existing && this.isAlive(existing)) {
708
831
  const existingIdentity = this.sessionIdentity(existing);
709
832
  const requestedIdentity = this.configIdentity(config);
710
- if (existingIdentity !== requestedIdentity) {
711
- 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`, {
712
835
  alias,
713
836
  existingIdentity,
714
837
  requestedIdentity,
@@ -719,6 +842,7 @@ export class SessionManager {
719
842
  return alias;
720
843
  }
721
844
  const client = new Client();
845
+ pendingConnection.client = client;
722
846
  const readyTimeout = config.readyTimeout ?? this.defaultTimeout;
723
847
  const connectConfig = {
724
848
  host: config.host,
@@ -777,21 +901,38 @@ export class SessionManager {
777
901
  }
778
902
  connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port || 22, readyTimeout);
779
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`);
908
+ }
780
909
  return new Promise((resolve, reject) => {
781
910
  let settled = false;
911
+ const clearPendingConnection = () => {
912
+ if (this.pendingConnections.get(alias) === pendingConnection) {
913
+ this.pendingConnections.delete(alias);
914
+ }
915
+ };
782
916
  const rejectConnection = (error) => {
783
917
  if (settled) {
784
918
  return;
785
919
  }
786
920
  settled = true;
921
+ clearPendingConnection();
787
922
  reject(this.createConnectionError(error, config, readyTimeout, 'target_connect'));
788
923
  };
789
924
  client.on('ready', () => {
790
- if (settled) {
925
+ if (settled || !this.isCurrentPendingConnection(alias, pendingConnection)) {
926
+ clearPendingConnection();
791
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
+ }
792
932
  return;
793
933
  }
794
934
  settled = true;
935
+ clearPendingConnection();
795
936
  const session = {
796
937
  client,
797
938
  config,
@@ -816,14 +957,14 @@ export class SessionManager {
816
957
  const session = this.sessions.get(alias);
817
958
  if (session && session.client === client) {
818
959
  session.connected = false;
819
- // 清理绑定旧 client 的资源;tracked operation 状态已无法继续证明
820
- this.operationManager.markAliasDisconnected(alias);
821
- this.forwardManager.closeByAlias(alias);
822
- this.ptyManager.closeByAlias(alias);
960
+ this.invalidateAliasResources(alias);
823
961
  if (!session.manualClose) {
824
962
  this.scheduleReconnect(alias);
825
963
  }
826
964
  }
965
+ else if (!settled) {
966
+ rejectConnection(new Error(`Connection for alias '${alias}' closed before ready`));
967
+ }
827
968
  });
828
969
  try {
829
970
  client.connect(connectConfig);
@@ -847,12 +988,16 @@ export class SessionManager {
847
988
  term: options.term || 'xterm-256color',
848
989
  },
849
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
+ }
850
996
  if (err) {
851
997
  reject(new Error(`PTY exec failed: ${err.message}`));
998
+ return;
852
999
  }
853
- else {
854
- resolve(stream);
855
- }
1000
+ resolve(stream);
856
1001
  });
857
1002
  });
858
1003
  }
@@ -888,7 +1033,7 @@ export class SessionManager {
888
1033
  }, timeout);
889
1034
  jumpClient.forwardOut('127.0.0.1', 0, targetHost, targetPort, (error, stream) => {
890
1035
  if (settled) {
891
- stream?.close();
1036
+ this.closeClientChannel(stream);
892
1037
  return;
893
1038
  }
894
1039
  settled = true;
@@ -907,12 +1052,62 @@ export class SessionManager {
907
1052
  });
908
1053
  });
909
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
+ }
910
1079
  /**
911
1080
  * 检查连接是否存活
912
1081
  */
913
1082
  isAlive(session) {
914
1083
  return session.connected;
915
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
+ }
916
1111
  /**
917
1112
  * 调度自动重连(支持多次重试)
918
1113
  */
@@ -929,18 +1124,18 @@ export class SessionManager {
929
1124
  const attempt = session.reconnectAttempts;
930
1125
  session.reconnectTimer = setTimeout(async () => {
931
1126
  const current = this.sessions.get(alias);
932
- if (!current) {
933
- // disconnect 已经把 session 移除,不再重连
1127
+ if (current !== session || current.client !== session.client) {
934
1128
  return;
935
1129
  }
936
- current.reconnectTimer = undefined;
1130
+ session.reconnectTimer = undefined;
937
1131
  try {
938
1132
  await this.reconnect(alias);
939
1133
  }
940
1134
  catch (err) {
941
1135
  console.error(`Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}):`, err.message);
942
- // reconnect 失败后继续调度下一次尝试
943
- this.scheduleReconnect(alias);
1136
+ if (this.sessions.get(alias) === session) {
1137
+ this.scheduleReconnect(alias);
1138
+ }
944
1139
  }
945
1140
  }, this.reconnectDelay);
946
1141
  }
@@ -1043,21 +1238,23 @@ export class SessionManager {
1043
1238
  * 构建完整命令:注入环境变量 + 切换工作目录
1044
1239
  */
1045
1240
  buildCommand(command, session, options) {
1046
- let fullCommand = command;
1241
+ const segments = [];
1047
1242
  const env = options.skipSessionEnv
1048
1243
  ? { ...options.env }
1049
1244
  : { ...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}`;
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)}`);
1055
1251
  }
1056
1252
  }
1057
- if (options.cwd) {
1058
- fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`;
1253
+ if (segments.length === 0) {
1254
+ return command;
1059
1255
  }
1060
- return fullCommand;
1256
+ segments.push(`eval ${this.escapeShellArg(command)}`);
1257
+ return segments.join(' && ');
1061
1258
  }
1062
1259
  /**
1063
1260
  * 根据用户 shell 类型生成加载配置文件的命令
@@ -220,22 +220,23 @@ async function handleConnect(args) {
220
220
  readyTimeout,
221
221
  jumpHost,
222
222
  });
223
+ const connected = sessionManager.getSessionConnectionInfo(alias);
223
224
  return formatResult({
224
225
  success: true,
225
- alias,
226
+ alias: connected.alias,
226
227
  reused,
227
- identity,
228
- loginUser: user,
229
- runAs,
230
- host,
231
- port: finalPort,
232
- defaultEnvKeys: defaultEnv ? Object.keys(defaultEnv) : [],
233
- envKeys: env ? Object.keys(env) : [],
228
+ identity: connected.identity,
229
+ loginUser: connected.loginUser,
230
+ runAs: connected.runAs,
231
+ host: connected.host,
232
+ port: connected.port,
233
+ defaultEnvKeys: connected.defaultEnvKeys,
234
+ envKeys: connected.envKeys,
234
235
  reusableSessions,
235
236
  suggestion: reusableSessions.length > 0
236
237
  ? '已有同 identity 的连接,可直接复用 reusableSessions 中的 alias'
237
238
  : undefined,
238
- message: `Connected to ${identity}${jumpHost ? ' via jump host' : ''}`,
239
+ message: `Connected to ${connected.identity}${connected.hasJumpHost ? ' via jump host' : ''}`,
239
240
  });
240
241
  }
241
242
  catch (error) {
@@ -5,4 +5,5 @@
5
5
  * ssh_list_dir, ssh_file_info, ssh_mkdir, ssh_sync
6
6
  */
7
7
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
8
+ export declare function createAtomicUploadPath(remotePath: string): string;
8
9
  export declare function registerFileTools(server: McpServer): void;