@pyrokine/mcp-ssh 3.1.0 → 3.2.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.
@@ -13,17 +13,18 @@ import * as os from 'os';
13
13
  import * as path from 'path';
14
14
  import { Client } from 'ssh2';
15
15
  import { StringDecoder } from 'string_decoder';
16
- import { isUtf8ContinuationByte, retainUtf8Suffix } from './utf8.js';
17
16
  import { clearRsyncCache } from './file-ops.js';
18
17
  import { ForwardManager } from './forward-manager.js';
19
- import { OperationManager } from './operation-manager.js';
18
+ import { HostKeyError, KnownHosts } from './known-hosts.js';
20
19
  import { OpenSshConnection, OpenSshError } from './openssh.js';
20
+ import { OperationManager } from './operation-manager.js';
21
21
  import { PtyManager } from './pty-manager.js';
22
22
  import { buildRemoteCommand, encodedPowershell, quotePowershell, remotePathStyle } from './remote-platform.js';
23
23
  import { sanitizeKeyError, validateKeyFile } from './security.js';
24
24
  import { escapeShellArg, expandTilde } from './tools/utils.js';
25
+ import { DEFAULT_EXEC_MAX_OUTPUT_SIZE, DEFAULT_EXEC_TIMEOUT_MS, HARD_EXEC_MAX_OUTPUT_SIZE, } from './types.js';
26
+ import { isUtf8ContinuationByte, retainUtf8Suffix } from './utf8.js';
25
27
  import { checkWindowsAcl } from './windows-acl.js';
26
- import { DEFAULT_EXEC_MAX_OUTPUT_SIZE, HARD_EXEC_MAX_OUTPUT_SIZE, } from './types.js';
27
28
  const OUTPUT_PREVIEW_CHARS = 4096;
28
29
  class CommandError extends Error {
29
30
  details;
@@ -47,6 +48,7 @@ export class SessionManager {
47
48
  connectInFlight = new Map();
48
49
  pendingConnections = new Map();
49
50
  connectionGenerations = new Map();
51
+ knownHosts = new KnownHosts();
50
52
  ptyManager = new PtyManager();
51
53
  forwardManager = new ForwardManager();
52
54
  operationManager;
@@ -54,7 +56,7 @@ export class SessionManager {
54
56
  persistQueue = Promise.resolve();
55
57
  defaultKeepaliveInterval = 30000; // 30秒
56
58
  defaultKeepaliveCountMax = 3;
57
- defaultTimeout = 30000; // 30秒
59
+ defaultTimeout = DEFAULT_EXEC_TIMEOUT_MS; // 30秒
58
60
  maxReconnectAttempts = 3;
59
61
  defaultMaxOutputSize = DEFAULT_EXEC_MAX_OUTPUT_SIZE;
60
62
  reconnectDelay = 5000; // 5秒
@@ -155,10 +157,12 @@ export class SessionManager {
155
157
  }
156
158
  this.invalidateAliasResources(alias);
157
159
  try {
158
- if (session.backend === 'openssh')
160
+ if (session.backend === 'openssh') {
159
161
  session.transport.close();
160
- else
162
+ }
163
+ else {
161
164
  session.client.end();
165
+ }
162
166
  }
163
167
  catch {
164
168
  /* 忽略已关闭的连接 */
@@ -180,10 +184,12 @@ export class SessionManager {
180
184
  }
181
185
  this.invalidateAliasResources(alias);
182
186
  try {
183
- if (session.backend === 'openssh')
187
+ if (session.backend === 'openssh') {
184
188
  session.transport.close();
185
- else
189
+ }
190
+ else {
186
191
  session.client.end();
192
+ }
187
193
  }
188
194
  catch {
189
195
  /* 忽略已关闭的连接 */
@@ -209,25 +215,29 @@ export class SessionManager {
209
215
  if (!session) {
210
216
  throw new Error(`Session '${alias}' not found. Use ssh_connect first.`);
211
217
  }
212
- if (session.backend === 'openssh')
218
+ if (session.backend === 'openssh') {
213
219
  session.transport.assertCurrent();
220
+ }
214
221
  if (!this.isAlive(session)) {
215
- if (session.backend === 'openssh')
222
+ if (session.backend === 'openssh') {
216
223
  throw new OpenSshError('The bound OpenSSH master is no longer available', {
217
224
  code: 'master_unavailable',
218
225
  backend: 'openssh',
219
226
  alias,
220
227
  retryable: false,
221
228
  });
222
- throw new Error(`Session '${alias}' is disconnected. Use ssh_connect to reconnect.`);
229
+ }
230
+ throw (session.connectionError ??
231
+ new Error(`Session '${alias}' is disconnected. Use ssh_connect to reconnect.`));
223
232
  }
224
233
  session.lastUsedAt = Date.now();
225
234
  return session;
226
235
  }
227
236
  getOpenSshConnection(alias) {
228
237
  const session = this.sessions.get(alias);
229
- if (session?.backend !== 'openssh')
238
+ if (session?.backend !== 'openssh') {
230
239
  return undefined;
240
+ }
231
241
  this.getSession(alias);
232
242
  return session.transport;
233
243
  }
@@ -276,6 +286,8 @@ export class SessionManager {
276
286
  return {
277
287
  backend: session.backend ?? 'ssh2',
278
288
  ...(session.backend === 'openssh' ? session.transport.info : {}),
289
+ hostKey: session.hostKey,
290
+ hostKeys: session.hostKeys,
279
291
  alias,
280
292
  identity: this.sessionIdentity(session),
281
293
  loginUser: config.username,
@@ -571,10 +583,27 @@ export class SessionManager {
571
583
  return;
572
584
  }
573
585
  streamRef = stream;
586
+ stream.on('error', (error) => {
587
+ if (settled) {
588
+ return;
589
+ }
590
+ settled = true;
591
+ clearTimeout(timeoutId);
592
+ endDecoders();
593
+ reject(new CommandError(error.message, {
594
+ failureKind: 'ssh_transport',
595
+ operationStatus: 'unknown',
596
+ retryable: false,
597
+ stdout,
598
+ stderr,
599
+ ...this.outputMetadata(outputPreview()),
600
+ ...this.resultMetadata(session, options, context),
601
+ }));
602
+ });
574
603
  // 密码写入 stdin,sudo -S 从 stdin 读取,不出现在命令行
575
604
  stream.write(sudoPassword + '\n');
576
605
  stream.end();
577
- stream.on('close', (code) => {
606
+ stream.on('close', (code, signal) => {
578
607
  clearTimeout(timeoutId);
579
608
  if (settled) {
580
609
  return;
@@ -585,9 +614,9 @@ export class SessionManager {
585
614
  success: code === 0,
586
615
  stdout,
587
616
  stderr,
588
- exitCode: code,
617
+ exitCode: code ?? null,
589
618
  duration: Date.now() - startTime,
590
- failureKind: code === 0 ? undefined : 'remote_command',
619
+ ...this.commandExitMetadata(code, signal),
591
620
  stdoutTruncated: stdoutTruncated || undefined,
592
621
  stderrTruncated: stderrTruncated || undefined,
593
622
  ...this.outputMetadata(outputPreview()),
@@ -787,18 +816,34 @@ export class SessionManager {
787
816
  return retainUtf8Suffix(next, OUTPUT_PREVIEW_CHARS).toString('utf8');
788
817
  }
789
818
  recommendedReadCommand() {
790
- return ('将远端命令输出重定向到文件,例如 command > /tmp/mcp-ssh-output.txt 2>&1,' +
791
- '再用 ssh_read_file(remotePath="/tmp/mcp-ssh-output.txt", tail=true, maxBytes=65536) 分块读取');
819
+ return ('将远端命令输出重定向到文件,例如 command > /tmp/mcp-ssh-output.txt 2>&1,再用 ' +
820
+ 'ssh_read_file(remotePath="/tmp/mcp-ssh-output.txt", tail=true, ' +
821
+ 'maxBytes=65536) 分块读取');
822
+ }
823
+ commandExitMetadata(code, signal) {
824
+ if (typeof code === 'number' || signal) {
825
+ return {
826
+ exitSignal: signal,
827
+ failureKind: code === 0 ? undefined : 'remote_command',
828
+ operationStatus: code === 0 ? 'completed' : 'failed',
829
+ };
830
+ }
831
+ return {
832
+ failureKind: 'ssh_transport',
833
+ operationStatus: 'unknown',
834
+ retryable: false,
835
+ suggestion: 'SSH channel closed without an exit status; inspect the remote state ' + 'before repeating the command',
836
+ };
792
837
  }
793
838
  emptyOutputFailureMetadata(exitCode, preview) {
794
- if (exitCode === 0 || preview.stdoutBytes > 0 || preview.stderrBytes > 0) {
839
+ if (typeof exitCode !== 'number' || exitCode === 0 || preview.stdoutBytes > 0 || preview.stderrBytes > 0) {
795
840
  return {};
796
841
  }
797
842
  return {
798
843
  emptyOutputFailure: true,
799
844
  recommendedReadCommand: this.recommendedReadCommand(),
800
- suggestion: '远端命令以非零退出码结束,但没有 stdout/stderr。请检查 cwd、effectiveUser、shell/profile,' +
801
- '或用 set -x / 显式重定向输出到文件后再用 ssh_read_file 读取',
845
+ suggestion: '远端命令以非零退出码结束,但没有 stdout/stderr。请检查 cwd、effectiveUser、shell/profile,或用 ' +
846
+ 'set -x / 显式重定向输出到文件后再用 ssh_read_file 读取',
802
847
  };
803
848
  }
804
849
  outputMetadata(preview) {
@@ -859,7 +904,10 @@ export class SessionManager {
859
904
  const session = this.getSession(alias);
860
905
  const markerEnv = `MCP_SSH_OPERATION_MARKER=${this.escapeShellArg(marker)}`;
861
906
  const markerLine = `__MCP_SSH_OPERATION__:${marker}:%s:%s\\n`;
862
- const operationScript = this.escapeShellArg(`printf ${this.escapeShellArg(markerLine)} "$$" "$1" >&2; exec sh -c ${this.escapeShellArg(command)}`);
907
+ const operationScript = this.escapeShellArg('printf ' +
908
+ `${this.escapeShellArg(markerLine)}` +
909
+ ' "$$" "$1" >&2; exec sh -c ' +
910
+ `${this.escapeShellArg(command)}`);
863
911
  const wrappedCommand = `if command -v setsid >/dev/null 2>&1; then ` +
864
912
  `exec env ${markerEnv} setsid -w sh -c ${operationScript} sh 1; ` +
865
913
  `else exec env ${markerEnv} sh -c ${operationScript} sh 0; fi`;
@@ -875,7 +923,8 @@ export class SessionManager {
875
923
  const script = [
876
924
  `$operationMarker = ${quotePowershell(marker)}`,
877
925
  '$created = (Get-Process -Id $PID).StartTime.ToUniversalTime().Ticks',
878
- '[Console]::Error.WriteLine("__MCP_SSH_OPERATION__:{0}:{1}:0:{2}", $operationMarker, $PID, $created)',
926
+ '[Console]::Error.WriteLine("__MCP_SSH_OPERATION__:{0}:{1}:0:{2}", ' +
927
+ '$operationMarker, $PID, $created)',
879
928
  execution,
880
929
  'if (-not $?) { exit 1 }',
881
930
  ].join('; ');
@@ -905,10 +954,12 @@ export class SessionManager {
905
954
  }
906
955
  try {
907
956
  adopt(stream);
908
- if (stream.ready)
957
+ if (stream.ready) {
909
958
  void stream.ready.then(resolve, reject);
910
- else
959
+ }
960
+ else {
911
961
  resolve();
962
+ }
912
963
  }
913
964
  catch (adoptionError) {
914
965
  this.closeClientChannel(stream);
@@ -932,7 +983,9 @@ export class SessionManager {
932
983
  `$expectedTicks = ${quotePowershell(processCreatedAt)}`,
933
984
  `$expectedMarker = ${quotePowershell(marker)}`,
934
985
  '$process = Get-CimInstance Win32_Process -Filter "ProcessId=$remotePid"',
935
- 'if (-not $process -or $process.CommandLine -notmatch "-EncodedCommand\\s+([A-Za-z0-9+/=]+)") { throw "process identity unavailable" }',
986
+ 'if (-not $process -or $process.CommandLine -notmatch ' +
987
+ '"-EncodedCommand\\s+([A-Za-z0-9+/=]+)") { throw "process identity ' +
988
+ 'unavailable" }',
936
989
  '$script = [Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($Matches[1]))',
937
990
  'if (-not $script.Contains($expectedMarker)) { throw "operation marker mismatch" }',
938
991
  '$start = (Get-Process -Id $remotePid).StartTime.ToUniversalTime().Ticks.ToString()',
@@ -960,8 +1013,8 @@ export class SessionManager {
960
1013
  `pid=${pid}`,
961
1014
  `expected=${this.escapeShellArg(expectedMarker)}`,
962
1015
  'if [ ! -r "/proc/$pid/environ" ]; then printf "operation marker unavailable" >&2; exit 3; fi',
963
- 'if ! tr "\\000" "\\n" < "/proc/$pid/environ" | grep -Fqx -- "$expected"; then ' +
964
- 'printf "operation marker mismatch" >&2; exit 4; fi',
1016
+ 'if ! tr "\\000" "\\n" < "/proc/$pid/environ" | grep -Fqx -- "$expected"; ' +
1017
+ 'then printf "operation marker mismatch" >&2; exit 4; fi',
965
1018
  `kill -TERM ${signalTarget}`,
966
1019
  ].join('; ');
967
1020
  try {
@@ -1094,7 +1147,7 @@ export class SessionManager {
1094
1147
  ...this.resultMetadata(session, options, context),
1095
1148
  }));
1096
1149
  });
1097
- stream.on('close', (code) => {
1150
+ stream.on('close', (code, signal) => {
1098
1151
  if (settled) {
1099
1152
  return;
1100
1153
  }
@@ -1105,9 +1158,9 @@ export class SessionManager {
1105
1158
  success: code === 0,
1106
1159
  stdout,
1107
1160
  stderr,
1108
- exitCode: code,
1161
+ exitCode: code ?? null,
1109
1162
  duration: Date.now() - startTime,
1110
- failureKind: code === 0 ? undefined : 'remote_command',
1163
+ ...this.commandExitMetadata(code, signal),
1111
1164
  stdoutTruncated: stdoutTruncated || undefined,
1112
1165
  stderrTruncated: stderrTruncated || undefined,
1113
1166
  ...this.outputMetadata(outputPreview()),
@@ -1151,13 +1204,16 @@ export class SessionManager {
1151
1204
  }
1152
1205
  if (existing) {
1153
1206
  existing.manualClose = true;
1154
- if (existing.reconnectTimer)
1207
+ if (existing.reconnectTimer) {
1155
1208
  clearTimeout(existing.reconnectTimer);
1209
+ }
1156
1210
  this.invalidateAliasResources(alias);
1157
- if (existing.backend === 'openssh')
1211
+ if (existing.backend === 'openssh') {
1158
1212
  existing.transport.close();
1159
- else
1213
+ }
1214
+ else {
1160
1215
  existing.client.end();
1216
+ }
1161
1217
  }
1162
1218
  if (config.backend === 'openssh') {
1163
1219
  const transport = await OpenSshConnection.connect(config, pendingConnection.signal);
@@ -1181,6 +1237,13 @@ export class SessionManager {
1181
1237
  const client = new Client();
1182
1238
  pendingConnection.client = client;
1183
1239
  const readyTimeout = config.readyTimeout ?? this.defaultTimeout;
1240
+ const verificationController = new AbortController();
1241
+ const verificationSignal = AbortSignal.any([pendingConnection.signal, verificationController.signal]);
1242
+ let verificationDeadline;
1243
+ let hostKey;
1244
+ let hostKeyError;
1245
+ let hostKeyAlgorithm;
1246
+ const generation = pendingConnection.generation;
1184
1247
  const connectConfig = {
1185
1248
  host: config.host,
1186
1249
  port: config.port ?? 22,
@@ -1188,6 +1251,43 @@ export class SessionManager {
1188
1251
  readyTimeout,
1189
1252
  keepaliveInterval: config.keepaliveInterval ?? this.defaultKeepaliveInterval,
1190
1253
  keepaliveCountMax: config.keepaliveCountMax ?? this.defaultKeepaliveCountMax,
1254
+ debug: (message) => {
1255
+ const algorithm = /^Handshake: Host key format: ([\w@.-]+)$/.exec(message);
1256
+ if (algorithm) {
1257
+ hostKeyAlgorithm = algorithm[1];
1258
+ }
1259
+ },
1260
+ hostVerifier: (key, callback) => {
1261
+ void this.knownHosts
1262
+ .verify(config.host, config.port ?? 22, key, verificationSignal, verificationDeadline ?? Date.now() + readyTimeout)
1263
+ .then((trust) => {
1264
+ if (verificationSignal.aborted || this.getConnectionGeneration(alias) !== generation) {
1265
+ return;
1266
+ }
1267
+ else {
1268
+ hostKey = trust;
1269
+ callback(true);
1270
+ }
1271
+ }, (error) => {
1272
+ if (verificationSignal.aborted || this.getConnectionGeneration(alias) !== generation) {
1273
+ return;
1274
+ }
1275
+ if (!verificationSignal.aborted) {
1276
+ if (error instanceof HostKeyError && error.hostKey) {
1277
+ error.hostKey.algorithm = hostKeyAlgorithm;
1278
+ }
1279
+ hostKeyError = error;
1280
+ const session = this.sessions.get(alias);
1281
+ if (session?.backend !== 'openssh' &&
1282
+ session?.client === client &&
1283
+ !session.manualClose &&
1284
+ this.getConnectionGeneration(alias) === generation) {
1285
+ this.stopUntrustedConnection(alias, session, this.createConnectionError(error, config, readyTimeout, 'target_connect'));
1286
+ }
1287
+ }
1288
+ callback(false);
1289
+ });
1290
+ },
1191
1291
  };
1192
1292
  try {
1193
1293
  if (config.password) {
@@ -1228,11 +1328,23 @@ export class SessionManager {
1228
1328
  catch (error) {
1229
1329
  throw this.createConnectionError(error, config, readyTimeout, 'key_read');
1230
1330
  }
1331
+ let jumpHostKeys = [];
1332
+ let jumpSession;
1231
1333
  if (config.jumpHost) {
1232
1334
  const jumpConfig = {
1233
1335
  ...config.jumpHost,
1234
1336
  readyTimeout: config.jumpHost.readyTimeout ?? readyTimeout,
1235
1337
  };
1338
+ if (!jumpConfig.alias) {
1339
+ const defaultAlias = this.generateAlias(jumpConfig);
1340
+ const existing = this.sessions.get(defaultAlias);
1341
+ const inFlight = this.connectInFlight.get(defaultAlias);
1342
+ const requested = existing || inFlight ? this.connectionFingerprint(jumpConfig) : undefined;
1343
+ if ((existing && this.isAlive(existing) && this.connectionFingerprint(existing.config) !== requested) ||
1344
+ (inFlight && inFlight.fingerprint !== requested)) {
1345
+ jumpConfig.alias = `${alias}:jump:${defaultAlias}`;
1346
+ }
1347
+ }
1236
1348
  let jumpAlias;
1237
1349
  try {
1238
1350
  jumpAlias = await this.connect(jumpConfig);
@@ -1246,8 +1358,8 @@ export class SessionManager {
1246
1358
  }
1247
1359
  throw this.createConnectionError(error, jumpConfig, jumpConfig.readyTimeout, 'jump_connect');
1248
1360
  }
1249
- const jumpSession = this.sessions.get(jumpAlias);
1250
- if (!jumpSession || jumpSession.backend === 'openssh' || !this.isAlive(jumpSession)) {
1361
+ const candidate = this.sessions.get(jumpAlias);
1362
+ if (!candidate || candidate.backend === 'openssh' || !this.isAlive(candidate)) {
1251
1363
  throw new ConnectionError(`Jump host session '${jumpAlias}' is unavailable`, {
1252
1364
  failureStage: 'transport_or_handshake',
1253
1365
  connectionStep: 'jump_connect',
@@ -1255,6 +1367,8 @@ export class SessionManager {
1255
1367
  suggestion: '重新连接跳板机,或检查 jumpHost 配置和网络路径',
1256
1368
  });
1257
1369
  }
1370
+ jumpSession = candidate;
1371
+ jumpHostKeys = jumpSession.hostKeys ?? [];
1258
1372
  connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port ?? 22, readyTimeout);
1259
1373
  }
1260
1374
  if (!this.isCurrentPendingConnection(alias, pendingConnection)) {
@@ -1275,9 +1389,21 @@ export class SessionManager {
1275
1389
  }
1276
1390
  settled = true;
1277
1391
  clearPendingConnection();
1278
- reject(this.createConnectionError(error, config, readyTimeout, 'target_connect'));
1392
+ verificationController.abort(error);
1393
+ this.closeClientChannel(connectConfig.sock);
1394
+ reject(this.createConnectionError(hostKeyError ?? jumpSession?.connectionError ?? error, config, readyTimeout, 'target_connect'));
1279
1395
  };
1280
1396
  client.on('ready', () => {
1397
+ if (jumpSession?.connectionError) {
1398
+ rejectConnection(jumpSession.connectionError);
1399
+ client.end();
1400
+ return;
1401
+ }
1402
+ if (!hostKey) {
1403
+ rejectConnection(new HostKeyError('SSH ready arrived before host key verification completed'));
1404
+ client.end();
1405
+ return;
1406
+ }
1281
1407
  if (settled || !this.isCurrentPendingConnection(alias, pendingConnection)) {
1282
1408
  clearPendingConnection();
1283
1409
  client.end();
@@ -1291,8 +1417,11 @@ export class SessionManager {
1291
1417
  clearPendingConnection();
1292
1418
  const session = {
1293
1419
  client,
1420
+ jumpClient: jumpSession?.client,
1294
1421
  config,
1295
1422
  authAgent: typeof connectConfig.agent === 'string' ? connectConfig.agent : undefined,
1423
+ hostKey,
1424
+ hostKeys: [...jumpHostKeys, { ...hostKey, host: config.host, port: config.port ?? 22 }],
1296
1425
  connectedAt: Date.now(),
1297
1426
  lastUsedAt: Date.now(),
1298
1427
  reconnectAttempts: 0,
@@ -1300,6 +1429,7 @@ export class SessionManager {
1300
1429
  manualClose: false,
1301
1430
  };
1302
1431
  this.sessions.set(alias, session);
1432
+ verificationDeadline = undefined;
1303
1433
  this.persistSessions();
1304
1434
  resolve(alias);
1305
1435
  });
@@ -1311,11 +1441,12 @@ export class SessionManager {
1311
1441
  rejectConnection(error);
1312
1442
  });
1313
1443
  client.on('close', () => {
1444
+ verificationController.abort(new Error('SSH connection closed'));
1314
1445
  const session = this.sessions.get(alias);
1315
1446
  if (session && session.backend !== 'openssh' && session.client === client) {
1316
1447
  session.connected = false;
1317
1448
  this.invalidateAliasResources(alias);
1318
- if (!session.manualClose) {
1449
+ if (!session.manualClose && !session.connectionError) {
1319
1450
  this.scheduleReconnect(alias);
1320
1451
  }
1321
1452
  }
@@ -1324,6 +1455,14 @@ export class SessionManager {
1324
1455
  }
1325
1456
  });
1326
1457
  try {
1458
+ verificationDeadline = Date.now() + readyTimeout;
1459
+ const algorithms = this.knownHosts.getHostKeyAlgorithms(config.host, config.port ?? 22);
1460
+ if (algorithms.length > 0) {
1461
+ // ssh2 的 prepend 跳过已有项,先 remove 才能调整默认顺序
1462
+ connectConfig.algorithms = {
1463
+ serverHostKey: { remove: algorithms, prepend: algorithms, append: [] },
1464
+ };
1465
+ }
1327
1466
  client.connect(connectConfig);
1328
1467
  client.setNoDelay(true);
1329
1468
  }
@@ -1442,11 +1581,38 @@ export class SessionManager {
1442
1581
  this.forwardManager.closeByAlias(alias);
1443
1582
  clearRsyncCache(alias);
1444
1583
  }
1584
+ stopUntrustedConnection(alias, session, error) {
1585
+ if (this.sessions.get(alias) !== session) {
1586
+ return;
1587
+ }
1588
+ session.connectionError = error;
1589
+ session.connected = false;
1590
+ if (session.reconnectTimer) {
1591
+ clearTimeout(session.reconnectTimer);
1592
+ session.reconnectTimer = undefined;
1593
+ }
1594
+ this.invalidateAliasResources(alias);
1595
+ for (const [targetAlias, target] of this.sessions) {
1596
+ if (target.backend !== 'openssh' && target.jumpClient === session.client && !target.manualClose) {
1597
+ this.stopUntrustedConnection(targetAlias, target, new ConnectionError(error.message, { ...error.details, connectionStep: 'jump_connect' }));
1598
+ target.client.end();
1599
+ }
1600
+ }
1601
+ }
1445
1602
  /**
1446
1603
  * 检查连接是否存活
1447
1604
  */
1448
1605
  isAlive(session) {
1449
- return session.connected && (session.backend !== 'openssh' || session.transport.isAlive());
1606
+ if (!session.connected) {
1607
+ return false;
1608
+ }
1609
+ if (session.backend === 'openssh') {
1610
+ return session.transport.isAlive();
1611
+ }
1612
+ const client = session.client;
1613
+ // ssh2 在 close 事件更新 connected 前就会按 socket 状态拒绝命令
1614
+ return (!('_sock' in client) ||
1615
+ Boolean(client._sock?.writable && !client._sock.destroyed && client._sock._readableState?.ended === false));
1450
1616
  }
1451
1617
  isCurrentSession(alias, session) {
1452
1618
  return this.sessions.get(alias) === session && this.isAlive(session);
@@ -1478,7 +1644,10 @@ export class SessionManager {
1478
1644
  */
1479
1645
  scheduleReconnect(alias) {
1480
1646
  const session = this.sessions.get(alias);
1481
- if (!session || session.backend === 'openssh' || session.reconnectAttempts >= this.maxReconnectAttempts) {
1647
+ if (!session ||
1648
+ session.backend === 'openssh' ||
1649
+ session.connectionError ||
1650
+ session.reconnectAttempts >= this.maxReconnectAttempts) {
1482
1651
  return;
1483
1652
  }
1484
1653
  // 清掉旧的定时器,防止重复调度
@@ -1489,16 +1658,24 @@ export class SessionManager {
1489
1658
  const attempt = session.reconnectAttempts;
1490
1659
  session.reconnectTimer = setTimeout(async () => {
1491
1660
  const current = this.sessions.get(alias);
1492
- if (current !== session) {
1661
+ session.reconnectTimer = undefined;
1662
+ if (current !== session || session.connectionError) {
1493
1663
  return;
1494
1664
  }
1495
- session.reconnectTimer = undefined;
1496
1665
  try {
1497
1666
  await this.reconnect(alias);
1498
1667
  }
1499
1668
  catch (err) {
1500
- console.error(`Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}): ${err.message}`);
1501
- if (this.sessions.get(alias) === session) {
1669
+ console.error('Auto-reconnect failed for ' +
1670
+ `${alias}` +
1671
+ ' (' +
1672
+ `${attempt}` +
1673
+ '/' +
1674
+ `${this.maxReconnectAttempts}` +
1675
+ '): ' +
1676
+ `${err.message}`);
1677
+ if (this.sessions.get(alias) === session &&
1678
+ !(err instanceof ConnectionError && err.details.failureStage === 'host_key')) {
1502
1679
  this.scheduleReconnect(alias);
1503
1680
  }
1504
1681
  }
@@ -1533,6 +1710,14 @@ export class SessionManager {
1533
1710
  });
1534
1711
  }
1535
1712
  createConnectionError(error, config, readyTimeout, connectionStep) {
1713
+ if (error instanceof HostKeyError) {
1714
+ return new ConnectionError(error.message, {
1715
+ failureStage: 'host_key',
1716
+ connectionStep,
1717
+ retryable: false,
1718
+ hostKey: error.hostKey,
1719
+ });
1720
+ }
1536
1721
  if (error instanceof ConnectionError) {
1537
1722
  return new ConnectionError(error.message, {
1538
1723
  ...error.details,
@@ -1623,11 +1808,9 @@ export class SessionManager {
1623
1808
  * bash → .bashrc, zsh → .zshrc, 其他 → .profile
1624
1809
  */
1625
1810
  getLoadProfileCommand() {
1626
- return ('case "$(basename "$SHELL" 2>/dev/null)" in ' +
1627
- 'bash) [ -f ~/.bashrc ] && . ~/.bashrc ;; ' +
1628
- 'zsh) [ -f ~/.zshrc ] && . ~/.zshrc ;; ' +
1629
- '*) [ -f ~/.profile ] && . ~/.profile ;; ' +
1630
- 'esac 2>/dev/null; ');
1811
+ return ('case "$(basename "$SHELL" 2>/dev/null)" in bash) [ -f ~/.bashrc ] && . ' +
1812
+ '~/.bashrc ;; zsh) [ -f ~/.zshrc ] && . ~/.zshrc ;; *) [ -f ~/.profile ] ' +
1813
+ '&& . ~/.profile ;; esac 2>/dev/null; ');
1631
1814
  }
1632
1815
  /**
1633
1816
  * 持久化会话信息(异步非阻塞,避免阻塞事件循环)
@@ -1,3 +1,4 @@
1
+ import type { SFTPWrapper } from 'ssh2';
1
2
  export declare const DEFAULT_SFTP_OPERATION_TIMEOUT_MS = 600000;
2
3
  export declare const HARD_SFTP_OPERATION_TIMEOUT_MS = 3600000;
3
4
  export declare class SftpOperationTimeoutError extends Error {
@@ -6,4 +7,18 @@ export declare class SftpOperationTimeoutError extends Error {
6
7
  constructor(timeout: number);
7
8
  }
8
9
  export declare function normalizeSftpOperationTimeout(timeout: number | undefined): number;
9
- export declare function withSftpOperationTimeout<T>(operation: Promise<T>, timeout: number | undefined, onTimeout: () => void): Promise<T>;
10
+ export declare function withSftpOperationTimeout<T>(operation: Promise<T>, timeout: number | undefined, onTimeout: () => void, signal?: AbortSignal): Promise<T>;
11
+ export declare function sftpOperationOutcome(error: unknown): Record<string, unknown>;
12
+ /** 按流记录请求状态,CLOSE 以服务端应答为准 */
13
+ export declare class SftpWriteState {
14
+ readonly remotePath: string;
15
+ acknowledgedBytes: number;
16
+ remoteCreated: boolean;
17
+ private pending;
18
+ private unknownStage?;
19
+ private failureStage?;
20
+ private stage;
21
+ constructor(remotePath: string);
22
+ track(sftp: SFTPWrapper): SFTPWrapper;
23
+ outcome(error: unknown): Record<string, unknown>;
24
+ }