@pyrokine/mcp-ssh 3.2.0 → 3.3.0

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.
@@ -47,7 +47,9 @@ export class SessionManager {
47
47
  /** per-alias connect 进行中的 Promise,防止并发 connect 同一 alias 时重复建连 */
48
48
  connectInFlight = new Map();
49
49
  pendingConnections = new Map();
50
+ preparingConnections = new Map();
50
51
  connectionGenerations = new Map();
52
+ cancellationSequence = 0;
51
53
  knownHosts = new KnownHosts();
52
54
  ptyManager = new PtyManager();
53
55
  forwardManager = new ForwardManager();
@@ -71,7 +73,8 @@ export class SessionManager {
71
73
  /**
72
74
  * 建立 SSH 连接(per-alias mutex,防止并发 connect 同一 alias 重复建连)
73
75
  */
74
- async connect(config) {
76
+ async connect(config, preparationGeneration, signal) {
77
+ signal?.throwIfAborted();
75
78
  const platform = config.remotePlatform ?? 'posix';
76
79
  const shell = config.commandShell ?? (platform === 'windows' ? 'powershell' : 'posix');
77
80
  if ((platform === 'windows') !== (shell !== 'posix')) {
@@ -87,7 +90,11 @@ export class SessionManager {
87
90
  });
88
91
  }
89
92
  const alias = this.generateAlias(config);
90
- const fingerprint = this.connectionFingerprint(config);
93
+ if (preparationGeneration !== undefined && preparationGeneration < this.getConnectionGeneration(alias)) {
94
+ throw new Error(`Connection for alias '${alias}' was cancelled after configuration preparation`);
95
+ }
96
+ const fields = {};
97
+ const fingerprint = this.connectionFingerprint(config, fields);
91
98
  const requestedIdentity = this.configIdentity(config);
92
99
  const inFlight = this.connectInFlight.get(alias);
93
100
  if (inFlight) {
@@ -95,6 +102,7 @@ export class SessionManager {
95
102
  throw new CommandError(`Alias '${alias}' already has a different connection attempt in progress`, {
96
103
  alias,
97
104
  existingIdentity: inFlight.identity,
105
+ differingFields: Object.keys(fields).filter((key) => fields[key] !== inFlight.fields?.[key]),
98
106
  requestedIdentity,
99
107
  suggestion: '请等待当前连接完成、换一个 alias,或先 ssh_disconnect 取消当前连接',
100
108
  });
@@ -128,8 +136,15 @@ export class SessionManager {
128
136
  },
129
137
  };
130
138
  this.pendingConnections.set(alias, pendingConnection);
139
+ const onAbort = () => {
140
+ if (this.pendingConnections.get(alias) === pendingConnection) {
141
+ this.cancelPendingConnection(alias);
142
+ }
143
+ };
144
+ signal?.addEventListener('abort', onAbort, { once: true });
131
145
  const connectAttempt = Promise.race([this.connectInternal(config, alias, pendingConnection), cancellation]);
132
146
  const promise = connectAttempt.finally(() => {
147
+ signal?.removeEventListener('abort', onAbort);
133
148
  if (this.connectInFlight.get(alias)?.promise === promise) {
134
149
  this.connectInFlight.delete(alias);
135
150
  }
@@ -137,9 +152,29 @@ export class SessionManager {
137
152
  this.pendingConnections.delete(alias);
138
153
  }
139
154
  });
140
- this.connectInFlight.set(alias, { identity: requestedIdentity, fingerprint, promise });
155
+ this.connectInFlight.set(alias, { identity: requestedIdentity, fingerprint, fields, promise });
141
156
  return promise;
142
157
  }
158
+ async prepareConnection(alias, prepare) {
159
+ const generation = this.cancellationSequence;
160
+ const controller = new AbortController();
161
+ const attempts = alias === undefined ? undefined : (this.preparingConnections.get(alias) ?? new Set());
162
+ if (alias !== undefined) {
163
+ attempts.add(controller);
164
+ this.preparingConnections.set(alias, attempts);
165
+ }
166
+ try {
167
+ const result = await prepare(controller.signal);
168
+ controller.signal.throwIfAborted();
169
+ return { result, generation };
170
+ }
171
+ finally {
172
+ attempts?.delete(controller);
173
+ if (alias !== undefined && attempts?.size === 0 && this.preparingConnections.get(alias) === attempts) {
174
+ this.preparingConnections.delete(alias);
175
+ }
176
+ }
177
+ }
143
178
  /**
144
179
  * 重新连接
145
180
  */
@@ -202,7 +237,11 @@ export class SessionManager {
202
237
  }
203
238
  /** 断开所有活跃会话(SIGINT/SIGTERM 时调用) */
204
239
  async disconnectAll() {
205
- const aliases = new Set([...this.sessions.keys(), ...this.pendingConnections.keys()]);
240
+ const aliases = new Set([
241
+ ...this.sessions.keys(),
242
+ ...this.pendingConnections.keys(),
243
+ ...this.preparingConnections.keys(),
244
+ ]);
206
245
  for (const alias of aliases) {
207
246
  this.disconnect(alias);
208
247
  }
@@ -461,6 +500,7 @@ export class SessionManager {
461
500
  * 通过 stdin 传递密码,避免密码出现在进程列表和 audit 日志中
462
501
  */
463
502
  async execSudo(alias, command, sudoPassword, options = {}) {
503
+ options.signal?.throwIfAborted();
464
504
  this.requirePosixPrivilege(alias);
465
505
  if (!sudoPassword) {
466
506
  return this.exec(alias, `sudo ${command}`, options);
@@ -544,11 +584,32 @@ export class SessionManager {
544
584
  stderrTruncated,
545
585
  maxOutputSize,
546
586
  });
587
+ const clearTimer = () => {
588
+ clearTimeout(timeoutId);
589
+ options.signal?.removeEventListener('abort', onAbort);
590
+ };
591
+ const onAbort = () => {
592
+ if (settled) {
593
+ return;
594
+ }
595
+ settled = true;
596
+ endDecoders();
597
+ clearTimer();
598
+ this.closeClientChannel(streamRef ?? undefined);
599
+ reject(new CommandError('SSH command request was cancelled; remote process state is unknown', {
600
+ failureKind: 'ssh_transport',
601
+ operationStatus: 'unknown',
602
+ retryable: false,
603
+ ...this.outputMetadata(outputPreview()),
604
+ ...this.resultMetadata(session, options, context),
605
+ }));
606
+ };
547
607
  const timeoutId = setTimeout(() => {
548
608
  if (settled) {
549
609
  return;
550
610
  }
551
611
  settled = true;
612
+ clearTimer();
552
613
  endDecoders();
553
614
  try {
554
615
  streamRef?.close();
@@ -558,9 +619,14 @@ export class SessionManager {
558
619
  }
559
620
  reject(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
560
621
  }, timeout);
622
+ options.signal?.addEventListener('abort', onAbort, { once: true });
623
+ if (options.signal?.aborted) {
624
+ onAbort();
625
+ return;
626
+ }
561
627
  session.client.exec(fullCommand, {}, (err, stream) => {
562
628
  if (!this.isCurrentSession(alias, session)) {
563
- clearTimeout(timeoutId);
629
+ clearTimer();
564
630
  this.closeClientChannel(stream);
565
631
  if (!settled) {
566
632
  settled = true;
@@ -570,7 +636,7 @@ export class SessionManager {
570
636
  return;
571
637
  }
572
638
  if (err) {
573
- clearTimeout(timeoutId);
639
+ clearTimer();
574
640
  if (!settled) {
575
641
  settled = true;
576
642
  endDecoders();
@@ -588,7 +654,7 @@ export class SessionManager {
588
654
  return;
589
655
  }
590
656
  settled = true;
591
- clearTimeout(timeoutId);
657
+ clearTimer();
592
658
  endDecoders();
593
659
  reject(new CommandError(error.message, {
594
660
  failureKind: 'ssh_transport',
@@ -604,7 +670,7 @@ export class SessionManager {
604
670
  stream.write(sudoPassword + '\n');
605
671
  stream.end();
606
672
  stream.on('close', (code, signal) => {
607
- clearTimeout(timeoutId);
673
+ clearTimer();
608
674
  if (settled) {
609
675
  return;
610
676
  }
@@ -748,7 +814,7 @@ export class SessionManager {
748
814
  configIdentity(config) {
749
815
  return `${config.username}@${config.host}:${config.port ?? 22}`;
750
816
  }
751
- connectionFingerprint(config) {
817
+ connectionFingerprint(config, fields) {
752
818
  const secretHash = (value) => value === undefined ? undefined : createHash('sha256').update(value).digest('hex');
753
819
  const sortedEntries = (values) => values === undefined
754
820
  ? undefined
@@ -781,9 +847,13 @@ export class SessionManager {
781
847
  passphrase: secretHash(value.passphrase),
782
848
  jumpHost: value.jumpHost ? payload(value.jumpHost) : undefined,
783
849
  });
784
- return createHash('sha256')
785
- .update(JSON.stringify(payload(config)))
786
- .digest('hex');
850
+ const normalized = payload(config);
851
+ if (fields) {
852
+ for (const [key, value] of Object.entries(normalized)) {
853
+ fields[key] = JSON.stringify(value);
854
+ }
855
+ }
856
+ return createHash('sha256').update(JSON.stringify(normalized)).digest('hex');
787
857
  }
788
858
  resultMetadata(session, options, context) {
789
859
  const env = options.skipSessionEnv
@@ -878,7 +948,7 @@ export class SessionManager {
878
948
  }
879
949
  return maxOutputSize;
880
950
  }
881
- openCommandChannel(session, command, options, callback) {
951
+ openCommandChannel(session, command, options, callback, withInput = false) {
882
952
  if (session.backend === 'openssh') {
883
953
  if (options.pty) {
884
954
  callback(new OpenSshError('The OpenSSH backend does not support PTY', {
@@ -890,14 +960,16 @@ export class SessionManager {
890
960
  return;
891
961
  }
892
962
  try {
893
- callback(undefined, session.transport.open(command));
963
+ callback(undefined, session.transport.open(command, withInput));
894
964
  }
895
965
  catch (error) {
896
966
  callback(error instanceof Error ? error : new Error(String(error)));
897
967
  }
898
968
  }
899
969
  else {
900
- session.client.exec(command, options, callback);
970
+ session.client.exec(command, options, (error, channel) => {
971
+ callback(error, channel ? Object.assign(channel, { stdin: channel }) : undefined);
972
+ });
901
973
  }
902
974
  }
903
975
  async openOperationStream(alias, command, marker, options, adopt) {
@@ -1102,6 +1174,7 @@ export class SessionManager {
1102
1174
  maxOutputSize,
1103
1175
  });
1104
1176
  const clearTimer = () => {
1177
+ options.signal?.removeEventListener('abort', onAbort);
1105
1178
  if (timeoutId) {
1106
1179
  clearTimeout(timeoutId);
1107
1180
  timeoutId = null;
@@ -1117,6 +1190,18 @@ export class SessionManager {
1117
1190
  activeStream?.close();
1118
1191
  reject(error);
1119
1192
  };
1193
+ const onAbort = () => rejectOnce(new CommandError('SSH command request was cancelled; remote process state is unknown', {
1194
+ failureKind: 'ssh_transport',
1195
+ operationStatus: 'unknown',
1196
+ retryable: false,
1197
+ ...this.outputMetadata(outputPreview()),
1198
+ ...this.resultMetadata(session, options, context),
1199
+ }));
1200
+ if (options.signal?.aborted) {
1201
+ onAbort();
1202
+ return;
1203
+ }
1204
+ options.signal?.addEventListener('abort', onAbort, { once: true });
1120
1205
  timeoutId = setTimeout(() => {
1121
1206
  endDecoders();
1122
1207
  rejectOnce(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
@@ -1137,7 +1222,9 @@ export class SessionManager {
1137
1222
  }
1138
1223
  activeStream = stream;
1139
1224
  stream.on('error', (error) => {
1140
- rejectOnce(new CommandError(error.message, {
1225
+ rejectOnce(new CommandError(options.stdin === undefined
1226
+ ? error.message
1227
+ : 'SSH command channel failed; remote process state is unknown', {
1141
1228
  failureKind: 'ssh_transport',
1142
1229
  operationStatus: 'unknown',
1143
1230
  retryable: false,
@@ -1182,7 +1269,25 @@ export class SessionManager {
1182
1269
  stderrBytes += data.length;
1183
1270
  appendStderr(stderrDecoder.write(data));
1184
1271
  });
1185
- });
1272
+ if (options.stdin !== undefined) {
1273
+ const inputFailure = () => rejectOnce(new CommandError('SSH command input could not be delivered; remote process state is unknown', { failureKind: 'ssh_transport', operationStatus: 'unknown', retryable: false }));
1274
+ if (!stream.stdin) {
1275
+ inputFailure();
1276
+ return;
1277
+ }
1278
+ stream.stdin.on('error', inputFailure);
1279
+ try {
1280
+ stream.stdin.end(options.stdin, 'utf8', (error) => {
1281
+ if (error) {
1282
+ inputFailure();
1283
+ }
1284
+ });
1285
+ }
1286
+ catch {
1287
+ inputFailure();
1288
+ }
1289
+ }
1290
+ }, options.stdin !== undefined);
1186
1291
  });
1187
1292
  }
1188
1293
  async connectInternal(config, alias, pendingConnection) {
@@ -1191,11 +1296,15 @@ export class SessionManager {
1191
1296
  if (existing && this.isAlive(existing)) {
1192
1297
  const existingIdentity = this.sessionIdentity(existing);
1193
1298
  const requestedIdentity = this.configIdentity(config);
1194
- if (this.connectionFingerprint(existing.config) !== pendingConnection.fingerprint) {
1299
+ const existingFields = {};
1300
+ const requestedFields = {};
1301
+ this.connectionFingerprint(config, requestedFields);
1302
+ if (this.connectionFingerprint(existing.config, existingFields) !== pendingConnection.fingerprint) {
1195
1303
  throw new CommandError(`Alias '${alias}' is already connected with different session configuration`, {
1196
1304
  alias,
1197
1305
  existingIdentity,
1198
1306
  requestedIdentity,
1307
+ differingFields: Object.keys(requestedFields).filter((key) => requestedFields[key] !== existingFields[key]),
1199
1308
  suggestion: '请换一个 alias,或先 ssh_disconnect 断开已有同名会话',
1200
1309
  });
1201
1310
  }
@@ -1252,9 +1361,9 @@ export class SessionManager {
1252
1361
  keepaliveInterval: config.keepaliveInterval ?? this.defaultKeepaliveInterval,
1253
1362
  keepaliveCountMax: config.keepaliveCountMax ?? this.defaultKeepaliveCountMax,
1254
1363
  debug: (message) => {
1255
- const algorithm = /^Handshake: Host key format: ([\w@.-]+)$/.exec(message);
1364
+ const algorithm = /^Handshake: Host key format: (?<algorithm>[\w@.-]+)$/.exec(message);
1256
1365
  if (algorithm) {
1257
- hostKeyAlgorithm = algorithm[1];
1366
+ hostKeyAlgorithm = algorithm.groups.algorithm;
1258
1367
  }
1259
1368
  },
1260
1369
  hostVerifier: (key, callback) => {
@@ -1300,6 +1409,7 @@ export class SessionManager {
1300
1409
  if (process.platform === 'win32') {
1301
1410
  const aclStatus = checkWindowsAcl(keyPath);
1302
1411
  if (aclStatus !== 'key_path_usable') {
1412
+ // noinspection ExceptionCaughtLocallyJS -- 密钥校验错误通过连接阶段统一返回
1303
1413
  throw new CommandError(`Private key ACL check failed: ${aclStatus}`, { code: aclStatus });
1304
1414
  }
1305
1415
  }
@@ -1317,9 +1427,11 @@ export class SessionManager {
1317
1427
  : undefined);
1318
1428
  if (agent && agent !== 'none') {
1319
1429
  if (agent === 'pageant' && process.platform !== 'win32') {
1430
+ // noinspection ExceptionCaughtLocallyJS -- agent 校验错误通过连接阶段统一返回
1320
1431
  throw new Error('Pageant authentication is only available on Windows');
1321
1432
  }
1322
1433
  if (agent !== 'pageant' && !agent.startsWith('\\\\.\\pipe\\') && !fs.existsSync(agent)) {
1434
+ // noinspection ExceptionCaughtLocallyJS -- agent 校验错误通过连接阶段统一返回
1323
1435
  throw new Error('SSH agent socket or pipe is unavailable');
1324
1436
  }
1325
1437
  connectConfig.agent = agent;
@@ -1564,11 +1676,16 @@ export class SessionManager {
1564
1676
  return (this.pendingConnections.get(alias) === pending && this.getConnectionGeneration(alias) === pending.generation);
1565
1677
  }
1566
1678
  cancelPendingConnection(alias) {
1567
- this.connectionGenerations.set(alias, this.getConnectionGeneration(alias) + 1);
1679
+ this.connectionGenerations.set(alias, ++this.cancellationSequence);
1680
+ const preparations = this.preparingConnections.get(alias);
1681
+ this.preparingConnections.delete(alias);
1682
+ for (const controller of preparations ?? []) {
1683
+ controller.abort(new Error(`Connection for alias '${alias}' was cancelled during configuration preparation`));
1684
+ }
1568
1685
  const pending = this.pendingConnections.get(alias);
1569
1686
  const inFlight = this.connectInFlight.delete(alias);
1570
1687
  if (!pending) {
1571
- return inFlight;
1688
+ return inFlight || (preparations?.size ?? 0) > 0;
1572
1689
  }
1573
1690
  this.pendingConnections.delete(alias);
1574
1691
  pending.cancel(new Error(`Connection for alias '${alias}' was cancelled`));
@@ -19,6 +19,6 @@ export declare class SftpWriteState {
19
19
  private failureStage?;
20
20
  private stage;
21
21
  constructor(remotePath: string);
22
- track(sftp: SFTPWrapper): SFTPWrapper;
22
+ track(sftp: SFTPWrapper, signal?: AbortSignal): SFTPWrapper;
23
23
  outcome(error: unknown): Record<string, unknown>;
24
24
  }
@@ -74,7 +74,7 @@ export class SftpWriteState {
74
74
  constructor(remotePath) {
75
75
  this.remotePath = remotePath;
76
76
  }
77
- track(sftp) {
77
+ track(sftp, signal) {
78
78
  return new Proxy(sftp, {
79
79
  get: (target, property, receiver) => {
80
80
  const method = Reflect.get(target, property);
@@ -94,6 +94,10 @@ export class SftpWriteState {
94
94
  return (...args) => {
95
95
  const stage = property === 'ext_openssh_rename' ? 'rename' : property;
96
96
  const callback = args.pop();
97
+ if (signal?.aborted && property !== 'close') {
98
+ callback(signal.reason ?? new Error('SFTP operation cancelled'));
99
+ return;
100
+ }
97
101
  this.stage = stage;
98
102
  ++this.pending;
99
103
  try {
@@ -115,7 +119,13 @@ export class SftpWriteState {
115
119
  else if (stage === 'open') {
116
120
  this.remoteCreated = true;
117
121
  }
118
- callback(error, ...values);
122
+ if (signal?.aborted && stage === 'open' && !error) {
123
+ target.end();
124
+ callback(signal.reason ?? new Error('SFTP operation cancelled'));
125
+ }
126
+ else {
127
+ callback(error, ...values);
128
+ }
119
129
  },
120
130
  ]);
121
131
  }
@@ -221,7 +221,7 @@ async function handleConnect(args) {
221
221
  const remotePlatform = args.remotePlatform ?? template.remotePlatform ?? 'posix';
222
222
  const commandShell = args.commandShell ?? template.commandShell ?? (remotePlatform === 'windows' ? 'powershell' : 'posix');
223
223
  if ((remotePlatform === 'windows') !== (commandShell !== 'posix')) {
224
- throw new Error('commandShell must match remotePlatform');
224
+ return formatError(new Error('commandShell must match remotePlatform'));
225
225
  }
226
226
  const remotePathStyle = args.remotePathStyle ?? template.remotePathStyle ?? (remotePlatform === 'windows' ? 'win32' : 'posix');
227
227
  const rsyncExecutable = args.rsyncExecutable ?? template.rsyncExecutable;
@@ -232,6 +232,7 @@ async function handleConnect(args) {
232
232
  const env = mergeEnv(template.env, args.env);
233
233
  const keepaliveInterval = args.keepaliveInterval ?? template.keepaliveInterval;
234
234
  const readyTimeout = args.readyTimeout ?? template.readyTimeout;
235
+ let preparationGeneration;
235
236
  let jumpHostResolved;
236
237
  if (backend === 'openssh') {
237
238
  if (password !== undefined ||
@@ -239,25 +240,26 @@ async function handleConnect(args) {
239
240
  agent !== undefined ||
240
241
  args.jumpHost ||
241
242
  template.jumpHost) {
242
- throw new OpenSshError('OpenSSH master reuse does not accept new authentication or jumpHost parameters', {
243
+ return formatError(new OpenSshError('OpenSSH master reuse does not accept new authentication or jumpHost parameters', {
243
244
  code: 'unsupported_backend',
244
245
  backend,
245
246
  capability: 'new_authentication',
246
247
  retryable: false,
247
- });
248
+ }));
248
249
  }
249
250
  if (remotePlatform !== 'posix' ||
250
251
  commandShell !== 'posix' ||
251
252
  remotePathStyle !== 'posix' ||
252
253
  (rsyncProfile && rsyncProfile !== 'posix')) {
253
- throw new OpenSshError('OpenSSH master reuse requires a POSIX remote shell and path style', {
254
+ return formatError(new OpenSshError('OpenSSH master reuse requires a POSIX remote shell and path style', {
254
255
  code: 'unsupported_backend',
255
256
  backend,
256
257
  capability: 'platform',
257
258
  retryable: false,
258
- });
259
+ }));
259
260
  }
260
- const resolved = await resolveOpenSshConfig({
261
+ const preparationAlias = requestedAlias ?? (user && host ? `${user}@${host}:${port ?? 22}` : undefined);
262
+ const prepared = await sessionManager.prepareConnection(preparationAlias, (signal) => resolveOpenSshConfig({
261
263
  configHost,
262
264
  configPath,
263
265
  host,
@@ -265,18 +267,20 @@ async function handleConnect(args) {
265
267
  port,
266
268
  controlPath,
267
269
  readyTimeout,
268
- });
270
+ }, signal));
271
+ const { result: resolved, generation } = prepared;
272
+ preparationGeneration = generation;
269
273
  host = resolved.host;
270
274
  user = resolved.username;
271
275
  port = resolved.port;
272
276
  controlPath = resolved.controlPath;
273
277
  }
274
278
  else if (controlPath !== undefined) {
275
- throw new OpenSshError('controlPath requires backend=openssh', {
279
+ return formatError(new OpenSshError('controlPath requires backend=openssh', {
276
280
  code: 'invalid_openssh_config',
277
281
  backend,
278
282
  retryable: false,
279
- });
283
+ }));
280
284
  }
281
285
  else if (configHost) {
282
286
  const allHosts = parseSSHConfig(configPath);
@@ -395,7 +399,7 @@ async function handleConnect(args) {
395
399
  keepaliveInterval,
396
400
  readyTimeout,
397
401
  jumpHost,
398
- });
402
+ }, preparationGeneration);
399
403
  const connected = sessionManager.getSessionConnectionInfo(alias);
400
404
  return formatResult({
401
405
  success: true,