@pyrokine/mcp-ssh 3.0.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,16 +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';
18
+ import { HostKeyError, KnownHosts } from './known-hosts.js';
19
+ import { OpenSshConnection, OpenSshError } from './openssh.js';
19
20
  import { OperationManager } from './operation-manager.js';
20
21
  import { PtyManager } from './pty-manager.js';
21
22
  import { buildRemoteCommand, encodedPowershell, quotePowershell, remotePathStyle } from './remote-platform.js';
22
23
  import { sanitizeKeyError, validateKeyFile } from './security.js';
23
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';
24
27
  import { checkWindowsAcl } from './windows-acl.js';
25
- import { DEFAULT_EXEC_MAX_OUTPUT_SIZE, HARD_EXEC_MAX_OUTPUT_SIZE, } from './types.js';
26
28
  const OUTPUT_PREVIEW_CHARS = 4096;
27
29
  class CommandError extends Error {
28
30
  details;
@@ -46,6 +48,7 @@ export class SessionManager {
46
48
  connectInFlight = new Map();
47
49
  pendingConnections = new Map();
48
50
  connectionGenerations = new Map();
51
+ knownHosts = new KnownHosts();
49
52
  ptyManager = new PtyManager();
50
53
  forwardManager = new ForwardManager();
51
54
  operationManager;
@@ -53,7 +56,7 @@ export class SessionManager {
53
56
  persistQueue = Promise.resolve();
54
57
  defaultKeepaliveInterval = 30000; // 30秒
55
58
  defaultKeepaliveCountMax = 3;
56
- defaultTimeout = 30000; // 30秒
59
+ defaultTimeout = DEFAULT_EXEC_TIMEOUT_MS; // 30秒
57
60
  maxReconnectAttempts = 3;
58
61
  defaultMaxOutputSize = DEFAULT_EXEC_MAX_OUTPUT_SIZE;
59
62
  reconnectDelay = 5000; // 5秒
@@ -104,14 +107,17 @@ export class SessionManager {
104
107
  const cancellation = new Promise((_resolve, reject) => {
105
108
  rejectCancellation = reject;
106
109
  });
110
+ const controller = new AbortController();
107
111
  const pendingConnection = {
108
112
  generation,
109
113
  fingerprint,
114
+ signal: controller.signal,
110
115
  cancel: (error) => {
111
116
  if (cancelled) {
112
117
  return;
113
118
  }
114
119
  cancelled = true;
120
+ controller.abort(error);
115
121
  try {
116
122
  pendingConnection.client?.end();
117
123
  }
@@ -151,7 +157,12 @@ export class SessionManager {
151
157
  }
152
158
  this.invalidateAliasResources(alias);
153
159
  try {
154
- session.client.end();
160
+ if (session.backend === 'openssh') {
161
+ session.transport.close();
162
+ }
163
+ else {
164
+ session.client.end();
165
+ }
155
166
  }
156
167
  catch {
157
168
  /* 忽略已关闭的连接 */
@@ -173,7 +184,12 @@ export class SessionManager {
173
184
  }
174
185
  this.invalidateAliasResources(alias);
175
186
  try {
176
- session.client.end();
187
+ if (session.backend === 'openssh') {
188
+ session.transport.close();
189
+ }
190
+ else {
191
+ session.client.end();
192
+ }
177
193
  }
178
194
  catch {
179
195
  /* 忽略已关闭的连接 */
@@ -199,14 +215,36 @@ export class SessionManager {
199
215
  if (!session) {
200
216
  throw new Error(`Session '${alias}' not found. Use ssh_connect first.`);
201
217
  }
218
+ if (session.backend === 'openssh') {
219
+ session.transport.assertCurrent();
220
+ }
202
221
  if (!this.isAlive(session)) {
203
- throw new Error(`Session '${alias}' is disconnected. Use ssh_connect to reconnect.`);
222
+ if (session.backend === 'openssh') {
223
+ throw new OpenSshError('The bound OpenSSH master is no longer available', {
224
+ code: 'master_unavailable',
225
+ backend: 'openssh',
226
+ alias,
227
+ retryable: false,
228
+ });
229
+ }
230
+ throw (session.connectionError ??
231
+ new Error(`Session '${alias}' is disconnected. Use ssh_connect to reconnect.`));
204
232
  }
205
233
  session.lastUsedAt = Date.now();
206
234
  return session;
207
235
  }
236
+ getOpenSshConnection(alias) {
237
+ const session = this.sessions.get(alias);
238
+ if (session?.backend !== 'openssh') {
239
+ return undefined;
240
+ }
241
+ this.getSession(alias);
242
+ return session.transport;
243
+ }
208
244
  listSessions() {
209
245
  return Array.from(this.sessions, ([alias, session]) => ({
246
+ backend: session.backend ?? 'ssh2',
247
+ ...(session.backend === 'openssh' ? { masterReused: true, identityStatus: 'master_trusted' } : {}),
210
248
  alias,
211
249
  identity: this.sessionIdentity(session),
212
250
  runAs: session.config.runAs,
@@ -216,19 +254,23 @@ export class SessionManager {
216
254
  }
217
255
  listSessionDetails() {
218
256
  return Array.from(this.sessions, ([alias, session]) => ({
257
+ backend: session.backend ?? 'ssh2',
258
+ ...(session.backend === 'openssh' ? session.transport.info : {}),
219
259
  alias,
220
260
  identity: this.sessionIdentity(session),
221
261
  host: session.config.host,
222
262
  port: session.config.port ?? 22,
223
263
  username: session.config.username,
224
264
  runAs: session.config.runAs,
225
- authMethod: session.config.privateKeyPath
226
- ? 'key'
227
- : session.config.privateKey
228
- ? 'inline-key'
229
- : session.config.password
230
- ? 'password'
231
- : 'agent',
265
+ authMethod: session.backend === 'openssh'
266
+ ? 'master'
267
+ : session.config.privateKeyPath
268
+ ? 'key'
269
+ : session.config.privateKey
270
+ ? 'inline-key'
271
+ : session.config.password
272
+ ? 'password'
273
+ : 'agent',
232
274
  connected: this.isAlive(session),
233
275
  connectedAt: session.connectedAt,
234
276
  lastUsedAt: session.lastUsedAt,
@@ -242,6 +284,10 @@ export class SessionManager {
242
284
  const session = this.getSession(alias);
243
285
  const config = session.config;
244
286
  return {
287
+ backend: session.backend ?? 'ssh2',
288
+ ...(session.backend === 'openssh' ? session.transport.info : {}),
289
+ hostKey: session.hostKey,
290
+ hostKeys: session.hostKeys,
245
291
  alias,
246
292
  identity: this.sessionIdentity(session),
247
293
  loginUser: config.username,
@@ -281,6 +327,27 @@ export class SessionManager {
281
327
  getExternalTransferCapability(alias) {
282
328
  const session = this.getSession(alias);
283
329
  const config = session.config;
330
+ if (session.backend === 'openssh') {
331
+ session.transport.assertCurrent();
332
+ return {
333
+ backend: 'openssh',
334
+ controlPath: config.controlPath,
335
+ alias,
336
+ identity: this.sessionIdentity(session),
337
+ host: config.host,
338
+ port: config.port,
339
+ username: config.username,
340
+ authMethod: 'master',
341
+ hasJumpHost: false,
342
+ routeSafeForOpenSsh: true,
343
+ rsyncEligible: true,
344
+ decisionReason: 'existing_openssh_master',
345
+ rsyncExecutable: config.rsyncExecutable,
346
+ rsyncProfile: 'posix',
347
+ commandShell: 'posix',
348
+ remotePathStyle: 'posix',
349
+ };
350
+ }
284
351
  const authMethod = config.privateKeyPath
285
352
  ? 'key-path'
286
353
  : config.privateKey
@@ -398,7 +465,7 @@ export class SessionManager {
398
465
  if (!sudoPassword) {
399
466
  return this.exec(alias, `sudo ${command}`, options);
400
467
  }
401
- const session = this.getSession(alias);
468
+ const session = this.requireSsh2Session(alias, 'password-based sudo');
402
469
  const startTime = Date.now();
403
470
  const timeout = options.timeout ?? this.defaultTimeout;
404
471
  const maxOutputSize = this.normalizeMaxOutputSize(options.maxOutputSize);
@@ -516,10 +583,27 @@ export class SessionManager {
516
583
  return;
517
584
  }
518
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
+ });
519
603
  // 密码写入 stdin,sudo -S 从 stdin 读取,不出现在命令行
520
604
  stream.write(sudoPassword + '\n');
521
605
  stream.end();
522
- stream.on('close', (code) => {
606
+ stream.on('close', (code, signal) => {
523
607
  clearTimeout(timeoutId);
524
608
  if (settled) {
525
609
  return;
@@ -530,9 +614,9 @@ export class SessionManager {
530
614
  success: code === 0,
531
615
  stdout,
532
616
  stderr,
533
- exitCode: code,
617
+ exitCode: code ?? null,
534
618
  duration: Date.now() - startTime,
535
- failureKind: code === 0 ? undefined : 'remote_command',
619
+ ...this.commandExitMetadata(code, signal),
536
620
  stdoutTruncated: stdoutTruncated || undefined,
537
621
  stderrTruncated: stderrTruncated || undefined,
538
622
  ...this.outputMetadata(outputPreview()),
@@ -561,7 +645,7 @@ export class SessionManager {
561
645
  * 获取 SFTP 客户端
562
646
  */
563
647
  getSftp(alias) {
564
- const session = this.getSession(alias);
648
+ const session = this.requireSsh2Session(alias, 'SFTP');
565
649
  return new Promise((resolve, reject) => {
566
650
  session.client.sftp((err, sftp) => {
567
651
  if (!this.isCurrentSession(alias, session)) {
@@ -599,20 +683,32 @@ export class SessionManager {
599
683
  return this.ptyManager.list();
600
684
  }
601
685
  async forwardLocal(alias, localPort, remoteHost, remotePort, localHost = '127.0.0.1') {
602
- return this.forwardManager.forwardLocal({ getClient: (a) => this.getSession(a).client }, alias, localPort, remoteHost, remotePort, localHost);
686
+ return this.forwardManager.forwardLocal({ getClient: (a) => this.requireSsh2Session(a, 'port forwarding').client }, alias, localPort, remoteHost, remotePort, localHost);
603
687
  }
604
688
  // ===== Forward 委托 =====
605
689
  async forwardRemote(alias, remotePort, localHost, localPort, remoteHost = '127.0.0.1') {
606
- return this.forwardManager.forwardRemote({ getClient: (a) => this.getSession(a).client }, alias, remotePort, localHost, localPort, remoteHost);
690
+ return this.forwardManager.forwardRemote({ getClient: (a) => this.requireSsh2Session(a, 'port forwarding').client }, alias, remotePort, localHost, localPort, remoteHost);
607
691
  }
608
692
  forwardClose(forwardId, options = {}) {
609
693
  return this.forwardManager.close(forwardId, {
610
- getClient: (a) => this.getSession(a).client,
694
+ getClient: (a) => this.requireSsh2Session(a, 'port forwarding').client,
611
695
  }, options);
612
696
  }
613
697
  forwardList() {
614
698
  return this.forwardManager.list();
615
699
  }
700
+ requireSsh2Session(alias, capability) {
701
+ const session = this.getSession(alias);
702
+ if (session.backend === 'openssh') {
703
+ throw new OpenSshError(`The OpenSSH backend does not support ${capability}`, {
704
+ code: 'unsupported_backend',
705
+ backend: 'openssh',
706
+ capability,
707
+ retryable: false,
708
+ });
709
+ }
710
+ return session;
711
+ }
616
712
  isSshAgentAvailable(socketPath) {
617
713
  if (!socketPath || socketPath === 'none' || socketPath === 'pageant') {
618
714
  return false; // ssh2 can use Pageant, but the independent OpenSSH rsync process cannot inherit it.
@@ -658,6 +754,8 @@ export class SessionManager {
658
754
  ? undefined
659
755
  : Object.entries(values).sort(([left], [right]) => left.localeCompare(right));
660
756
  const payload = (value) => ({
757
+ backend: value.backend ?? 'ssh2',
758
+ controlPath: value.controlPath,
661
759
  host: value.host,
662
760
  port: value.port ?? 22,
663
761
  username: value.username,
@@ -718,18 +816,34 @@ export class SessionManager {
718
816
  return retainUtf8Suffix(next, OUTPUT_PREVIEW_CHARS).toString('utf8');
719
817
  }
720
818
  recommendedReadCommand() {
721
- return ('将远端命令输出重定向到文件,例如 command > /tmp/mcp-ssh-output.txt 2>&1,' +
722
- '再用 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
+ };
723
837
  }
724
838
  emptyOutputFailureMetadata(exitCode, preview) {
725
- if (exitCode === 0 || preview.stdoutBytes > 0 || preview.stderrBytes > 0) {
839
+ if (typeof exitCode !== 'number' || exitCode === 0 || preview.stdoutBytes > 0 || preview.stderrBytes > 0) {
726
840
  return {};
727
841
  }
728
842
  return {
729
843
  emptyOutputFailure: true,
730
844
  recommendedReadCommand: this.recommendedReadCommand(),
731
- suggestion: '远端命令以非零退出码结束,但没有 stdout/stderr。请检查 cwd、effectiveUser、shell/profile,' +
732
- '或用 set -x / 显式重定向输出到文件后再用 ssh_read_file 读取',
845
+ suggestion: '远端命令以非零退出码结束,但没有 stdout/stderr。请检查 cwd、effectiveUser、shell/profile,或用 ' +
846
+ 'set -x / 显式重定向输出到文件后再用 ssh_read_file 读取',
733
847
  };
734
848
  }
735
849
  outputMetadata(preview) {
@@ -764,11 +878,36 @@ export class SessionManager {
764
878
  }
765
879
  return maxOutputSize;
766
880
  }
881
+ openCommandChannel(session, command, options, callback) {
882
+ if (session.backend === 'openssh') {
883
+ if (options.pty) {
884
+ callback(new OpenSshError('The OpenSSH backend does not support PTY', {
885
+ code: 'unsupported_backend',
886
+ backend: 'openssh',
887
+ capability: 'PTY',
888
+ retryable: false,
889
+ }));
890
+ return;
891
+ }
892
+ try {
893
+ callback(undefined, session.transport.open(command));
894
+ }
895
+ catch (error) {
896
+ callback(error instanceof Error ? error : new Error(String(error)));
897
+ }
898
+ }
899
+ else {
900
+ session.client.exec(command, options, callback);
901
+ }
902
+ }
767
903
  async openOperationStream(alias, command, marker, options, adopt) {
768
904
  const session = this.getSession(alias);
769
905
  const markerEnv = `MCP_SSH_OPERATION_MARKER=${this.escapeShellArg(marker)}`;
770
906
  const markerLine = `__MCP_SSH_OPERATION__:${marker}:%s:%s\\n`;
771
- 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)}`);
772
911
  const wrappedCommand = `if command -v setsid >/dev/null 2>&1; then ` +
773
912
  `exec env ${markerEnv} setsid -w sh -c ${operationScript} sh 1; ` +
774
913
  `else exec env ${markerEnv} sh -c ${operationScript} sh 0; fi`;
@@ -784,7 +923,8 @@ export class SessionManager {
784
923
  const script = [
785
924
  `$operationMarker = ${quotePowershell(marker)}`,
786
925
  '$created = (Get-Process -Id $PID).StartTime.ToUniversalTime().Ticks',
787
- '[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)',
788
928
  execution,
789
929
  'if (-not $?) { exit 1 }',
790
930
  ].join('; ');
@@ -802,19 +942,24 @@ export class SessionManager {
802
942
  fullCommand = this.buildCommand(wrappedCommand, session, options);
803
943
  }
804
944
  return new Promise((resolve, reject) => {
805
- session.client.exec(fullCommand, {}, (error, stream) => {
945
+ this.openCommandChannel(session, fullCommand, {}, (error, stream) => {
806
946
  if (!this.isCurrentSession(alias, session)) {
807
947
  this.closeClientChannel(stream);
808
948
  reject(new Error('Operation start was cancelled because the SSH session changed'));
809
949
  return;
810
950
  }
811
- if (error) {
812
- reject(new Error(`Operation start failed: ${error.message}`));
951
+ if (error || !stream) {
952
+ reject(error ?? new Error('Operation start did not return a command channel'));
813
953
  return;
814
954
  }
815
955
  try {
816
956
  adopt(stream);
817
- resolve();
957
+ if (stream.ready) {
958
+ void stream.ready.then(resolve, reject);
959
+ }
960
+ else {
961
+ resolve();
962
+ }
818
963
  }
819
964
  catch (adoptionError) {
820
965
  this.closeClientChannel(stream);
@@ -838,7 +983,9 @@ export class SessionManager {
838
983
  `$expectedTicks = ${quotePowershell(processCreatedAt)}`,
839
984
  `$expectedMarker = ${quotePowershell(marker)}`,
840
985
  '$process = Get-CimInstance Win32_Process -Filter "ProcessId=$remotePid"',
841
- '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" }',
842
989
  '$script = [Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($Matches[1]))',
843
990
  'if (-not $script.Contains($expectedMarker)) { throw "operation marker mismatch" }',
844
991
  '$start = (Get-Process -Id $remotePid).StartTime.ToUniversalTime().Ticks.ToString()',
@@ -866,8 +1013,8 @@ export class SessionManager {
866
1013
  `pid=${pid}`,
867
1014
  `expected=${this.escapeShellArg(expectedMarker)}`,
868
1015
  'if [ ! -r "/proc/$pid/environ" ]; then printf "operation marker unavailable" >&2; exit 3; fi',
869
- 'if ! tr "\\000" "\\n" < "/proc/$pid/environ" | grep -Fqx -- "$expected"; then ' +
870
- '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',
871
1018
  `kill -TERM ${signalTarget}`,
872
1019
  ].join('; ');
873
1020
  try {
@@ -974,14 +1121,14 @@ export class SessionManager {
974
1121
  endDecoders();
975
1122
  rejectOnce(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
976
1123
  }, timeout);
977
- session.client.exec(fullCommand, execOptions, (err, stream) => {
1124
+ this.openCommandChannel(session, fullCommand, execOptions, (err, stream) => {
978
1125
  if (!this.isCurrentSession(alias, session)) {
979
1126
  this.closeClientChannel(stream);
980
1127
  rejectOnce(new Error('Exec was cancelled because the SSH session changed'));
981
1128
  return;
982
1129
  }
983
- if (err) {
984
- rejectOnce(new Error(`Exec failed: ${err.message}`));
1130
+ if (err || !stream) {
1131
+ rejectOnce(err ?? new Error('Exec did not return a command channel'));
985
1132
  return;
986
1133
  }
987
1134
  if (settled) {
@@ -989,7 +1136,18 @@ export class SessionManager {
989
1136
  return;
990
1137
  }
991
1138
  activeStream = stream;
992
- stream.on('close', (code) => {
1139
+ stream.on('error', (error) => {
1140
+ rejectOnce(new CommandError(error.message, {
1141
+ failureKind: 'ssh_transport',
1142
+ operationStatus: 'unknown',
1143
+ retryable: false,
1144
+ stdout,
1145
+ stderr,
1146
+ ...this.outputMetadata(outputPreview()),
1147
+ ...this.resultMetadata(session, options, context),
1148
+ }));
1149
+ });
1150
+ stream.on('close', (code, signal) => {
993
1151
  if (settled) {
994
1152
  return;
995
1153
  }
@@ -1000,9 +1158,9 @@ export class SessionManager {
1000
1158
  success: code === 0,
1001
1159
  stdout,
1002
1160
  stderr,
1003
- exitCode: code,
1161
+ exitCode: code ?? null,
1004
1162
  duration: Date.now() - startTime,
1005
- failureKind: code === 0 ? undefined : 'remote_command',
1163
+ ...this.commandExitMetadata(code, signal),
1006
1164
  stdoutTruncated: stdoutTruncated || undefined,
1007
1165
  stderrTruncated: stderrTruncated || undefined,
1008
1166
  ...this.outputMetadata(outputPreview()),
@@ -1044,9 +1202,48 @@ export class SessionManager {
1044
1202
  existing.lastUsedAt = Date.now();
1045
1203
  return alias;
1046
1204
  }
1205
+ if (existing) {
1206
+ existing.manualClose = true;
1207
+ if (existing.reconnectTimer) {
1208
+ clearTimeout(existing.reconnectTimer);
1209
+ }
1210
+ this.invalidateAliasResources(alias);
1211
+ if (existing.backend === 'openssh') {
1212
+ existing.transport.close();
1213
+ }
1214
+ else {
1215
+ existing.client.end();
1216
+ }
1217
+ }
1218
+ if (config.backend === 'openssh') {
1219
+ const transport = await OpenSshConnection.connect(config, pendingConnection.signal);
1220
+ if (!this.isCurrentPendingConnection(alias, pendingConnection)) {
1221
+ transport.close();
1222
+ throw new Error(`Connection for alias '${alias}' was cancelled before ready`);
1223
+ }
1224
+ this.sessions.set(alias, {
1225
+ backend: 'openssh',
1226
+ transport,
1227
+ config,
1228
+ connectedAt: Date.now(),
1229
+ lastUsedAt: Date.now(),
1230
+ reconnectAttempts: 0,
1231
+ connected: true,
1232
+ manualClose: false,
1233
+ });
1234
+ this.persistSessions();
1235
+ return alias;
1236
+ }
1047
1237
  const client = new Client();
1048
1238
  pendingConnection.client = client;
1049
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;
1050
1247
  const connectConfig = {
1051
1248
  host: config.host,
1052
1249
  port: config.port ?? 22,
@@ -1054,6 +1251,43 @@ export class SessionManager {
1054
1251
  readyTimeout,
1055
1252
  keepaliveInterval: config.keepaliveInterval ?? this.defaultKeepaliveInterval,
1056
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
+ },
1057
1291
  };
1058
1292
  try {
1059
1293
  if (config.password) {
@@ -1094,11 +1328,23 @@ export class SessionManager {
1094
1328
  catch (error) {
1095
1329
  throw this.createConnectionError(error, config, readyTimeout, 'key_read');
1096
1330
  }
1331
+ let jumpHostKeys = [];
1332
+ let jumpSession;
1097
1333
  if (config.jumpHost) {
1098
1334
  const jumpConfig = {
1099
1335
  ...config.jumpHost,
1100
1336
  readyTimeout: config.jumpHost.readyTimeout ?? readyTimeout,
1101
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
+ }
1102
1348
  let jumpAlias;
1103
1349
  try {
1104
1350
  jumpAlias = await this.connect(jumpConfig);
@@ -1112,8 +1358,8 @@ export class SessionManager {
1112
1358
  }
1113
1359
  throw this.createConnectionError(error, jumpConfig, jumpConfig.readyTimeout, 'jump_connect');
1114
1360
  }
1115
- const jumpSession = this.sessions.get(jumpAlias);
1116
- if (!jumpSession || !this.isAlive(jumpSession)) {
1361
+ const candidate = this.sessions.get(jumpAlias);
1362
+ if (!candidate || candidate.backend === 'openssh' || !this.isAlive(candidate)) {
1117
1363
  throw new ConnectionError(`Jump host session '${jumpAlias}' is unavailable`, {
1118
1364
  failureStage: 'transport_or_handshake',
1119
1365
  connectionStep: 'jump_connect',
@@ -1121,6 +1367,8 @@ export class SessionManager {
1121
1367
  suggestion: '重新连接跳板机,或检查 jumpHost 配置和网络路径',
1122
1368
  });
1123
1369
  }
1370
+ jumpSession = candidate;
1371
+ jumpHostKeys = jumpSession.hostKeys ?? [];
1124
1372
  connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port ?? 22, readyTimeout);
1125
1373
  }
1126
1374
  if (!this.isCurrentPendingConnection(alias, pendingConnection)) {
@@ -1141,9 +1389,21 @@ export class SessionManager {
1141
1389
  }
1142
1390
  settled = true;
1143
1391
  clearPendingConnection();
1144
- 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'));
1145
1395
  };
1146
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
+ }
1147
1407
  if (settled || !this.isCurrentPendingConnection(alias, pendingConnection)) {
1148
1408
  clearPendingConnection();
1149
1409
  client.end();
@@ -1157,8 +1417,11 @@ export class SessionManager {
1157
1417
  clearPendingConnection();
1158
1418
  const session = {
1159
1419
  client,
1420
+ jumpClient: jumpSession?.client,
1160
1421
  config,
1161
1422
  authAgent: typeof connectConfig.agent === 'string' ? connectConfig.agent : undefined,
1423
+ hostKey,
1424
+ hostKeys: [...jumpHostKeys, { ...hostKey, host: config.host, port: config.port ?? 22 }],
1162
1425
  connectedAt: Date.now(),
1163
1426
  lastUsedAt: Date.now(),
1164
1427
  reconnectAttempts: 0,
@@ -1166,22 +1429,24 @@ export class SessionManager {
1166
1429
  manualClose: false,
1167
1430
  };
1168
1431
  this.sessions.set(alias, session);
1432
+ verificationDeadline = undefined;
1169
1433
  this.persistSessions();
1170
1434
  resolve(alias);
1171
1435
  });
1172
1436
  client.on('error', (error) => {
1173
1437
  const session = this.sessions.get(alias);
1174
- if (session && session.client === client) {
1438
+ if (session && session.backend !== 'openssh' && session.client === client) {
1175
1439
  session.connected = false;
1176
1440
  }
1177
1441
  rejectConnection(error);
1178
1442
  });
1179
1443
  client.on('close', () => {
1444
+ verificationController.abort(new Error('SSH connection closed'));
1180
1445
  const session = this.sessions.get(alias);
1181
- if (session && session.client === client) {
1446
+ if (session && session.backend !== 'openssh' && session.client === client) {
1182
1447
  session.connected = false;
1183
1448
  this.invalidateAliasResources(alias);
1184
- if (!session.manualClose) {
1449
+ if (!session.manualClose && !session.connectionError) {
1185
1450
  this.scheduleReconnect(alias);
1186
1451
  }
1187
1452
  }
@@ -1190,6 +1455,14 @@ export class SessionManager {
1190
1455
  }
1191
1456
  });
1192
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
+ }
1193
1466
  client.connect(connectConfig);
1194
1467
  client.setNoDelay(true);
1195
1468
  }
@@ -1202,7 +1475,7 @@ export class SessionManager {
1202
1475
  * 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
1203
1476
  */
1204
1477
  execPtyStream(alias, command, options) {
1205
- const session = this.getSession(alias);
1478
+ const session = this.requireSsh2Session(alias, 'PTY');
1206
1479
  const fullCommand = this.buildCommand(command, session, { env: options.env, cwd: options.cwd });
1207
1480
  return new Promise((resolve, reject) => {
1208
1481
  session.client.exec(fullCommand, {
@@ -1308,15 +1581,41 @@ export class SessionManager {
1308
1581
  this.forwardManager.closeByAlias(alias);
1309
1582
  clearRsyncCache(alias);
1310
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
+ }
1311
1602
  /**
1312
1603
  * 检查连接是否存活
1313
1604
  */
1314
1605
  isAlive(session) {
1315
- return session.connected;
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));
1316
1616
  }
1317
1617
  isCurrentSession(alias, session) {
1318
- const currentSession = this.sessions.get(alias);
1319
- return currentSession === session && currentSession.client === session.client && currentSession.connected;
1618
+ return this.sessions.get(alias) === session && this.isAlive(session);
1320
1619
  }
1321
1620
  closeClientChannel(stream) {
1322
1621
  try {
@@ -1345,7 +1644,10 @@ export class SessionManager {
1345
1644
  */
1346
1645
  scheduleReconnect(alias) {
1347
1646
  const session = this.sessions.get(alias);
1348
- if (!session || session.reconnectAttempts >= this.maxReconnectAttempts) {
1647
+ if (!session ||
1648
+ session.backend === 'openssh' ||
1649
+ session.connectionError ||
1650
+ session.reconnectAttempts >= this.maxReconnectAttempts) {
1349
1651
  return;
1350
1652
  }
1351
1653
  // 清掉旧的定时器,防止重复调度
@@ -1356,16 +1658,24 @@ export class SessionManager {
1356
1658
  const attempt = session.reconnectAttempts;
1357
1659
  session.reconnectTimer = setTimeout(async () => {
1358
1660
  const current = this.sessions.get(alias);
1359
- if (current !== session || current.client !== session.client) {
1661
+ session.reconnectTimer = undefined;
1662
+ if (current !== session || session.connectionError) {
1360
1663
  return;
1361
1664
  }
1362
- session.reconnectTimer = undefined;
1363
1665
  try {
1364
1666
  await this.reconnect(alias);
1365
1667
  }
1366
1668
  catch (err) {
1367
- console.error(`Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}): ${err.message}`);
1368
- 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')) {
1369
1679
  this.scheduleReconnect(alias);
1370
1680
  }
1371
1681
  }
@@ -1400,6 +1710,14 @@ export class SessionManager {
1400
1710
  });
1401
1711
  }
1402
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
+ }
1403
1721
  if (error instanceof ConnectionError) {
1404
1722
  return new ConnectionError(error.message, {
1405
1723
  ...error.details,
@@ -1490,11 +1808,9 @@ export class SessionManager {
1490
1808
  * bash → .bashrc, zsh → .zshrc, 其他 → .profile
1491
1809
  */
1492
1810
  getLoadProfileCommand() {
1493
- return ('case "$(basename "$SHELL" 2>/dev/null)" in ' +
1494
- 'bash) [ -f ~/.bashrc ] && . ~/.bashrc ;; ' +
1495
- 'zsh) [ -f ~/.zshrc ] && . ~/.zshrc ;; ' +
1496
- '*) [ -f ~/.profile ] && . ~/.profile ;; ' +
1497
- '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; ');
1498
1814
  }
1499
1815
  /**
1500
1816
  * 持久化会话信息(异步非阻塞,避免阻塞事件循环)