@pyrokine/mcp-ssh 3.1.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.
@@ -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;
@@ -46,7 +47,10 @@ export class SessionManager {
46
47
  /** per-alias connect 进行中的 Promise,防止并发 connect 同一 alias 时重复建连 */
47
48
  connectInFlight = new Map();
48
49
  pendingConnections = new Map();
50
+ preparingConnections = new Map();
49
51
  connectionGenerations = new Map();
52
+ cancellationSequence = 0;
53
+ knownHosts = new KnownHosts();
50
54
  ptyManager = new PtyManager();
51
55
  forwardManager = new ForwardManager();
52
56
  operationManager;
@@ -54,7 +58,7 @@ export class SessionManager {
54
58
  persistQueue = Promise.resolve();
55
59
  defaultKeepaliveInterval = 30000; // 30秒
56
60
  defaultKeepaliveCountMax = 3;
57
- defaultTimeout = 30000; // 30秒
61
+ defaultTimeout = DEFAULT_EXEC_TIMEOUT_MS; // 30秒
58
62
  maxReconnectAttempts = 3;
59
63
  defaultMaxOutputSize = DEFAULT_EXEC_MAX_OUTPUT_SIZE;
60
64
  reconnectDelay = 5000; // 5秒
@@ -69,7 +73,8 @@ export class SessionManager {
69
73
  /**
70
74
  * 建立 SSH 连接(per-alias mutex,防止并发 connect 同一 alias 重复建连)
71
75
  */
72
- async connect(config) {
76
+ async connect(config, preparationGeneration, signal) {
77
+ signal?.throwIfAborted();
73
78
  const platform = config.remotePlatform ?? 'posix';
74
79
  const shell = config.commandShell ?? (platform === 'windows' ? 'powershell' : 'posix');
75
80
  if ((platform === 'windows') !== (shell !== 'posix')) {
@@ -85,7 +90,11 @@ export class SessionManager {
85
90
  });
86
91
  }
87
92
  const alias = this.generateAlias(config);
88
- 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);
89
98
  const requestedIdentity = this.configIdentity(config);
90
99
  const inFlight = this.connectInFlight.get(alias);
91
100
  if (inFlight) {
@@ -93,6 +102,7 @@ export class SessionManager {
93
102
  throw new CommandError(`Alias '${alias}' already has a different connection attempt in progress`, {
94
103
  alias,
95
104
  existingIdentity: inFlight.identity,
105
+ differingFields: Object.keys(fields).filter((key) => fields[key] !== inFlight.fields?.[key]),
96
106
  requestedIdentity,
97
107
  suggestion: '请等待当前连接完成、换一个 alias,或先 ssh_disconnect 取消当前连接',
98
108
  });
@@ -126,8 +136,15 @@ export class SessionManager {
126
136
  },
127
137
  };
128
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 });
129
145
  const connectAttempt = Promise.race([this.connectInternal(config, alias, pendingConnection), cancellation]);
130
146
  const promise = connectAttempt.finally(() => {
147
+ signal?.removeEventListener('abort', onAbort);
131
148
  if (this.connectInFlight.get(alias)?.promise === promise) {
132
149
  this.connectInFlight.delete(alias);
133
150
  }
@@ -135,9 +152,29 @@ export class SessionManager {
135
152
  this.pendingConnections.delete(alias);
136
153
  }
137
154
  });
138
- this.connectInFlight.set(alias, { identity: requestedIdentity, fingerprint, promise });
155
+ this.connectInFlight.set(alias, { identity: requestedIdentity, fingerprint, fields, promise });
139
156
  return promise;
140
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
+ }
141
178
  /**
142
179
  * 重新连接
143
180
  */
@@ -155,10 +192,12 @@ export class SessionManager {
155
192
  }
156
193
  this.invalidateAliasResources(alias);
157
194
  try {
158
- if (session.backend === 'openssh')
195
+ if (session.backend === 'openssh') {
159
196
  session.transport.close();
160
- else
197
+ }
198
+ else {
161
199
  session.client.end();
200
+ }
162
201
  }
163
202
  catch {
164
203
  /* 忽略已关闭的连接 */
@@ -180,10 +219,12 @@ export class SessionManager {
180
219
  }
181
220
  this.invalidateAliasResources(alias);
182
221
  try {
183
- if (session.backend === 'openssh')
222
+ if (session.backend === 'openssh') {
184
223
  session.transport.close();
185
- else
224
+ }
225
+ else {
186
226
  session.client.end();
227
+ }
187
228
  }
188
229
  catch {
189
230
  /* 忽略已关闭的连接 */
@@ -196,7 +237,11 @@ export class SessionManager {
196
237
  }
197
238
  /** 断开所有活跃会话(SIGINT/SIGTERM 时调用) */
198
239
  async disconnectAll() {
199
- 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
+ ]);
200
245
  for (const alias of aliases) {
201
246
  this.disconnect(alias);
202
247
  }
@@ -209,25 +254,29 @@ export class SessionManager {
209
254
  if (!session) {
210
255
  throw new Error(`Session '${alias}' not found. Use ssh_connect first.`);
211
256
  }
212
- if (session.backend === 'openssh')
257
+ if (session.backend === 'openssh') {
213
258
  session.transport.assertCurrent();
259
+ }
214
260
  if (!this.isAlive(session)) {
215
- if (session.backend === 'openssh')
261
+ if (session.backend === 'openssh') {
216
262
  throw new OpenSshError('The bound OpenSSH master is no longer available', {
217
263
  code: 'master_unavailable',
218
264
  backend: 'openssh',
219
265
  alias,
220
266
  retryable: false,
221
267
  });
222
- throw new Error(`Session '${alias}' is disconnected. Use ssh_connect to reconnect.`);
268
+ }
269
+ throw (session.connectionError ??
270
+ new Error(`Session '${alias}' is disconnected. Use ssh_connect to reconnect.`));
223
271
  }
224
272
  session.lastUsedAt = Date.now();
225
273
  return session;
226
274
  }
227
275
  getOpenSshConnection(alias) {
228
276
  const session = this.sessions.get(alias);
229
- if (session?.backend !== 'openssh')
277
+ if (session?.backend !== 'openssh') {
230
278
  return undefined;
279
+ }
231
280
  this.getSession(alias);
232
281
  return session.transport;
233
282
  }
@@ -276,6 +325,8 @@ export class SessionManager {
276
325
  return {
277
326
  backend: session.backend ?? 'ssh2',
278
327
  ...(session.backend === 'openssh' ? session.transport.info : {}),
328
+ hostKey: session.hostKey,
329
+ hostKeys: session.hostKeys,
279
330
  alias,
280
331
  identity: this.sessionIdentity(session),
281
332
  loginUser: config.username,
@@ -449,6 +500,7 @@ export class SessionManager {
449
500
  * 通过 stdin 传递密码,避免密码出现在进程列表和 audit 日志中
450
501
  */
451
502
  async execSudo(alias, command, sudoPassword, options = {}) {
503
+ options.signal?.throwIfAborted();
452
504
  this.requirePosixPrivilege(alias);
453
505
  if (!sudoPassword) {
454
506
  return this.exec(alias, `sudo ${command}`, options);
@@ -532,11 +584,32 @@ export class SessionManager {
532
584
  stderrTruncated,
533
585
  maxOutputSize,
534
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
+ };
535
607
  const timeoutId = setTimeout(() => {
536
608
  if (settled) {
537
609
  return;
538
610
  }
539
611
  settled = true;
612
+ clearTimer();
540
613
  endDecoders();
541
614
  try {
542
615
  streamRef?.close();
@@ -546,9 +619,14 @@ export class SessionManager {
546
619
  }
547
620
  reject(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
548
621
  }, timeout);
622
+ options.signal?.addEventListener('abort', onAbort, { once: true });
623
+ if (options.signal?.aborted) {
624
+ onAbort();
625
+ return;
626
+ }
549
627
  session.client.exec(fullCommand, {}, (err, stream) => {
550
628
  if (!this.isCurrentSession(alias, session)) {
551
- clearTimeout(timeoutId);
629
+ clearTimer();
552
630
  this.closeClientChannel(stream);
553
631
  if (!settled) {
554
632
  settled = true;
@@ -558,7 +636,7 @@ export class SessionManager {
558
636
  return;
559
637
  }
560
638
  if (err) {
561
- clearTimeout(timeoutId);
639
+ clearTimer();
562
640
  if (!settled) {
563
641
  settled = true;
564
642
  endDecoders();
@@ -571,11 +649,28 @@ export class SessionManager {
571
649
  return;
572
650
  }
573
651
  streamRef = stream;
652
+ stream.on('error', (error) => {
653
+ if (settled) {
654
+ return;
655
+ }
656
+ settled = true;
657
+ clearTimer();
658
+ endDecoders();
659
+ reject(new CommandError(error.message, {
660
+ failureKind: 'ssh_transport',
661
+ operationStatus: 'unknown',
662
+ retryable: false,
663
+ stdout,
664
+ stderr,
665
+ ...this.outputMetadata(outputPreview()),
666
+ ...this.resultMetadata(session, options, context),
667
+ }));
668
+ });
574
669
  // 密码写入 stdin,sudo -S 从 stdin 读取,不出现在命令行
575
670
  stream.write(sudoPassword + '\n');
576
671
  stream.end();
577
- stream.on('close', (code) => {
578
- clearTimeout(timeoutId);
672
+ stream.on('close', (code, signal) => {
673
+ clearTimer();
579
674
  if (settled) {
580
675
  return;
581
676
  }
@@ -585,9 +680,9 @@ export class SessionManager {
585
680
  success: code === 0,
586
681
  stdout,
587
682
  stderr,
588
- exitCode: code,
683
+ exitCode: code ?? null,
589
684
  duration: Date.now() - startTime,
590
- failureKind: code === 0 ? undefined : 'remote_command',
685
+ ...this.commandExitMetadata(code, signal),
591
686
  stdoutTruncated: stdoutTruncated || undefined,
592
687
  stderrTruncated: stderrTruncated || undefined,
593
688
  ...this.outputMetadata(outputPreview()),
@@ -719,7 +814,7 @@ export class SessionManager {
719
814
  configIdentity(config) {
720
815
  return `${config.username}@${config.host}:${config.port ?? 22}`;
721
816
  }
722
- connectionFingerprint(config) {
817
+ connectionFingerprint(config, fields) {
723
818
  const secretHash = (value) => value === undefined ? undefined : createHash('sha256').update(value).digest('hex');
724
819
  const sortedEntries = (values) => values === undefined
725
820
  ? undefined
@@ -752,9 +847,13 @@ export class SessionManager {
752
847
  passphrase: secretHash(value.passphrase),
753
848
  jumpHost: value.jumpHost ? payload(value.jumpHost) : undefined,
754
849
  });
755
- return createHash('sha256')
756
- .update(JSON.stringify(payload(config)))
757
- .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');
758
857
  }
759
858
  resultMetadata(session, options, context) {
760
859
  const env = options.skipSessionEnv
@@ -787,18 +886,34 @@ export class SessionManager {
787
886
  return retainUtf8Suffix(next, OUTPUT_PREVIEW_CHARS).toString('utf8');
788
887
  }
789
888
  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) 分块读取');
889
+ return ('将远端命令输出重定向到文件,例如 command > /tmp/mcp-ssh-output.txt 2>&1,再用 ' +
890
+ 'ssh_read_file(remotePath="/tmp/mcp-ssh-output.txt", tail=true, ' +
891
+ 'maxBytes=65536) 分块读取');
892
+ }
893
+ commandExitMetadata(code, signal) {
894
+ if (typeof code === 'number' || signal) {
895
+ return {
896
+ exitSignal: signal,
897
+ failureKind: code === 0 ? undefined : 'remote_command',
898
+ operationStatus: code === 0 ? 'completed' : 'failed',
899
+ };
900
+ }
901
+ return {
902
+ failureKind: 'ssh_transport',
903
+ operationStatus: 'unknown',
904
+ retryable: false,
905
+ suggestion: 'SSH channel closed without an exit status; inspect the remote state ' + 'before repeating the command',
906
+ };
792
907
  }
793
908
  emptyOutputFailureMetadata(exitCode, preview) {
794
- if (exitCode === 0 || preview.stdoutBytes > 0 || preview.stderrBytes > 0) {
909
+ if (typeof exitCode !== 'number' || exitCode === 0 || preview.stdoutBytes > 0 || preview.stderrBytes > 0) {
795
910
  return {};
796
911
  }
797
912
  return {
798
913
  emptyOutputFailure: true,
799
914
  recommendedReadCommand: this.recommendedReadCommand(),
800
- suggestion: '远端命令以非零退出码结束,但没有 stdout/stderr。请检查 cwd、effectiveUser、shell/profile,' +
801
- '或用 set -x / 显式重定向输出到文件后再用 ssh_read_file 读取',
915
+ suggestion: '远端命令以非零退出码结束,但没有 stdout/stderr。请检查 cwd、effectiveUser、shell/profile,或用 ' +
916
+ 'set -x / 显式重定向输出到文件后再用 ssh_read_file 读取',
802
917
  };
803
918
  }
804
919
  outputMetadata(preview) {
@@ -833,7 +948,7 @@ export class SessionManager {
833
948
  }
834
949
  return maxOutputSize;
835
950
  }
836
- openCommandChannel(session, command, options, callback) {
951
+ openCommandChannel(session, command, options, callback, withInput = false) {
837
952
  if (session.backend === 'openssh') {
838
953
  if (options.pty) {
839
954
  callback(new OpenSshError('The OpenSSH backend does not support PTY', {
@@ -845,21 +960,26 @@ export class SessionManager {
845
960
  return;
846
961
  }
847
962
  try {
848
- callback(undefined, session.transport.open(command));
963
+ callback(undefined, session.transport.open(command, withInput));
849
964
  }
850
965
  catch (error) {
851
966
  callback(error instanceof Error ? error : new Error(String(error)));
852
967
  }
853
968
  }
854
969
  else {
855
- 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
+ });
856
973
  }
857
974
  }
858
975
  async openOperationStream(alias, command, marker, options, adopt) {
859
976
  const session = this.getSession(alias);
860
977
  const markerEnv = `MCP_SSH_OPERATION_MARKER=${this.escapeShellArg(marker)}`;
861
978
  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)}`);
979
+ const operationScript = this.escapeShellArg('printf ' +
980
+ `${this.escapeShellArg(markerLine)}` +
981
+ ' "$$" "$1" >&2; exec sh -c ' +
982
+ `${this.escapeShellArg(command)}`);
863
983
  const wrappedCommand = `if command -v setsid >/dev/null 2>&1; then ` +
864
984
  `exec env ${markerEnv} setsid -w sh -c ${operationScript} sh 1; ` +
865
985
  `else exec env ${markerEnv} sh -c ${operationScript} sh 0; fi`;
@@ -875,7 +995,8 @@ export class SessionManager {
875
995
  const script = [
876
996
  `$operationMarker = ${quotePowershell(marker)}`,
877
997
  '$created = (Get-Process -Id $PID).StartTime.ToUniversalTime().Ticks',
878
- '[Console]::Error.WriteLine("__MCP_SSH_OPERATION__:{0}:{1}:0:{2}", $operationMarker, $PID, $created)',
998
+ '[Console]::Error.WriteLine("__MCP_SSH_OPERATION__:{0}:{1}:0:{2}", ' +
999
+ '$operationMarker, $PID, $created)',
879
1000
  execution,
880
1001
  'if (-not $?) { exit 1 }',
881
1002
  ].join('; ');
@@ -905,10 +1026,12 @@ export class SessionManager {
905
1026
  }
906
1027
  try {
907
1028
  adopt(stream);
908
- if (stream.ready)
1029
+ if (stream.ready) {
909
1030
  void stream.ready.then(resolve, reject);
910
- else
1031
+ }
1032
+ else {
911
1033
  resolve();
1034
+ }
912
1035
  }
913
1036
  catch (adoptionError) {
914
1037
  this.closeClientChannel(stream);
@@ -932,7 +1055,9 @@ export class SessionManager {
932
1055
  `$expectedTicks = ${quotePowershell(processCreatedAt)}`,
933
1056
  `$expectedMarker = ${quotePowershell(marker)}`,
934
1057
  '$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" }',
1058
+ 'if (-not $process -or $process.CommandLine -notmatch ' +
1059
+ '"-EncodedCommand\\s+([A-Za-z0-9+/=]+)") { throw "process identity ' +
1060
+ 'unavailable" }',
936
1061
  '$script = [Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($Matches[1]))',
937
1062
  'if (-not $script.Contains($expectedMarker)) { throw "operation marker mismatch" }',
938
1063
  '$start = (Get-Process -Id $remotePid).StartTime.ToUniversalTime().Ticks.ToString()',
@@ -960,8 +1085,8 @@ export class SessionManager {
960
1085
  `pid=${pid}`,
961
1086
  `expected=${this.escapeShellArg(expectedMarker)}`,
962
1087
  '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',
1088
+ 'if ! tr "\\000" "\\n" < "/proc/$pid/environ" | grep -Fqx -- "$expected"; ' +
1089
+ 'then printf "operation marker mismatch" >&2; exit 4; fi',
965
1090
  `kill -TERM ${signalTarget}`,
966
1091
  ].join('; ');
967
1092
  try {
@@ -1049,6 +1174,7 @@ export class SessionManager {
1049
1174
  maxOutputSize,
1050
1175
  });
1051
1176
  const clearTimer = () => {
1177
+ options.signal?.removeEventListener('abort', onAbort);
1052
1178
  if (timeoutId) {
1053
1179
  clearTimeout(timeoutId);
1054
1180
  timeoutId = null;
@@ -1064,6 +1190,18 @@ export class SessionManager {
1064
1190
  activeStream?.close();
1065
1191
  reject(error);
1066
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 });
1067
1205
  timeoutId = setTimeout(() => {
1068
1206
  endDecoders();
1069
1207
  rejectOnce(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
@@ -1084,7 +1222,9 @@ export class SessionManager {
1084
1222
  }
1085
1223
  activeStream = stream;
1086
1224
  stream.on('error', (error) => {
1087
- 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', {
1088
1228
  failureKind: 'ssh_transport',
1089
1229
  operationStatus: 'unknown',
1090
1230
  retryable: false,
@@ -1094,7 +1234,7 @@ export class SessionManager {
1094
1234
  ...this.resultMetadata(session, options, context),
1095
1235
  }));
1096
1236
  });
1097
- stream.on('close', (code) => {
1237
+ stream.on('close', (code, signal) => {
1098
1238
  if (settled) {
1099
1239
  return;
1100
1240
  }
@@ -1105,9 +1245,9 @@ export class SessionManager {
1105
1245
  success: code === 0,
1106
1246
  stdout,
1107
1247
  stderr,
1108
- exitCode: code,
1248
+ exitCode: code ?? null,
1109
1249
  duration: Date.now() - startTime,
1110
- failureKind: code === 0 ? undefined : 'remote_command',
1250
+ ...this.commandExitMetadata(code, signal),
1111
1251
  stdoutTruncated: stdoutTruncated || undefined,
1112
1252
  stderrTruncated: stderrTruncated || undefined,
1113
1253
  ...this.outputMetadata(outputPreview()),
@@ -1129,7 +1269,25 @@ export class SessionManager {
1129
1269
  stderrBytes += data.length;
1130
1270
  appendStderr(stderrDecoder.write(data));
1131
1271
  });
1132
- });
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);
1133
1291
  });
1134
1292
  }
1135
1293
  async connectInternal(config, alias, pendingConnection) {
@@ -1138,11 +1296,15 @@ export class SessionManager {
1138
1296
  if (existing && this.isAlive(existing)) {
1139
1297
  const existingIdentity = this.sessionIdentity(existing);
1140
1298
  const requestedIdentity = this.configIdentity(config);
1141
- 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) {
1142
1303
  throw new CommandError(`Alias '${alias}' is already connected with different session configuration`, {
1143
1304
  alias,
1144
1305
  existingIdentity,
1145
1306
  requestedIdentity,
1307
+ differingFields: Object.keys(requestedFields).filter((key) => requestedFields[key] !== existingFields[key]),
1146
1308
  suggestion: '请换一个 alias,或先 ssh_disconnect 断开已有同名会话',
1147
1309
  });
1148
1310
  }
@@ -1151,13 +1313,16 @@ export class SessionManager {
1151
1313
  }
1152
1314
  if (existing) {
1153
1315
  existing.manualClose = true;
1154
- if (existing.reconnectTimer)
1316
+ if (existing.reconnectTimer) {
1155
1317
  clearTimeout(existing.reconnectTimer);
1318
+ }
1156
1319
  this.invalidateAliasResources(alias);
1157
- if (existing.backend === 'openssh')
1320
+ if (existing.backend === 'openssh') {
1158
1321
  existing.transport.close();
1159
- else
1322
+ }
1323
+ else {
1160
1324
  existing.client.end();
1325
+ }
1161
1326
  }
1162
1327
  if (config.backend === 'openssh') {
1163
1328
  const transport = await OpenSshConnection.connect(config, pendingConnection.signal);
@@ -1181,6 +1346,13 @@ export class SessionManager {
1181
1346
  const client = new Client();
1182
1347
  pendingConnection.client = client;
1183
1348
  const readyTimeout = config.readyTimeout ?? this.defaultTimeout;
1349
+ const verificationController = new AbortController();
1350
+ const verificationSignal = AbortSignal.any([pendingConnection.signal, verificationController.signal]);
1351
+ let verificationDeadline;
1352
+ let hostKey;
1353
+ let hostKeyError;
1354
+ let hostKeyAlgorithm;
1355
+ const generation = pendingConnection.generation;
1184
1356
  const connectConfig = {
1185
1357
  host: config.host,
1186
1358
  port: config.port ?? 22,
@@ -1188,6 +1360,43 @@ export class SessionManager {
1188
1360
  readyTimeout,
1189
1361
  keepaliveInterval: config.keepaliveInterval ?? this.defaultKeepaliveInterval,
1190
1362
  keepaliveCountMax: config.keepaliveCountMax ?? this.defaultKeepaliveCountMax,
1363
+ debug: (message) => {
1364
+ const algorithm = /^Handshake: Host key format: (?<algorithm>[\w@.-]+)$/.exec(message);
1365
+ if (algorithm) {
1366
+ hostKeyAlgorithm = algorithm.groups.algorithm;
1367
+ }
1368
+ },
1369
+ hostVerifier: (key, callback) => {
1370
+ void this.knownHosts
1371
+ .verify(config.host, config.port ?? 22, key, verificationSignal, verificationDeadline ?? Date.now() + readyTimeout)
1372
+ .then((trust) => {
1373
+ if (verificationSignal.aborted || this.getConnectionGeneration(alias) !== generation) {
1374
+ return;
1375
+ }
1376
+ else {
1377
+ hostKey = trust;
1378
+ callback(true);
1379
+ }
1380
+ }, (error) => {
1381
+ if (verificationSignal.aborted || this.getConnectionGeneration(alias) !== generation) {
1382
+ return;
1383
+ }
1384
+ if (!verificationSignal.aborted) {
1385
+ if (error instanceof HostKeyError && error.hostKey) {
1386
+ error.hostKey.algorithm = hostKeyAlgorithm;
1387
+ }
1388
+ hostKeyError = error;
1389
+ const session = this.sessions.get(alias);
1390
+ if (session?.backend !== 'openssh' &&
1391
+ session?.client === client &&
1392
+ !session.manualClose &&
1393
+ this.getConnectionGeneration(alias) === generation) {
1394
+ this.stopUntrustedConnection(alias, session, this.createConnectionError(error, config, readyTimeout, 'target_connect'));
1395
+ }
1396
+ }
1397
+ callback(false);
1398
+ });
1399
+ },
1191
1400
  };
1192
1401
  try {
1193
1402
  if (config.password) {
@@ -1200,6 +1409,7 @@ export class SessionManager {
1200
1409
  if (process.platform === 'win32') {
1201
1410
  const aclStatus = checkWindowsAcl(keyPath);
1202
1411
  if (aclStatus !== 'key_path_usable') {
1412
+ // noinspection ExceptionCaughtLocallyJS -- 密钥校验错误通过连接阶段统一返回
1203
1413
  throw new CommandError(`Private key ACL check failed: ${aclStatus}`, { code: aclStatus });
1204
1414
  }
1205
1415
  }
@@ -1217,9 +1427,11 @@ export class SessionManager {
1217
1427
  : undefined);
1218
1428
  if (agent && agent !== 'none') {
1219
1429
  if (agent === 'pageant' && process.platform !== 'win32') {
1430
+ // noinspection ExceptionCaughtLocallyJS -- agent 校验错误通过连接阶段统一返回
1220
1431
  throw new Error('Pageant authentication is only available on Windows');
1221
1432
  }
1222
1433
  if (agent !== 'pageant' && !agent.startsWith('\\\\.\\pipe\\') && !fs.existsSync(agent)) {
1434
+ // noinspection ExceptionCaughtLocallyJS -- agent 校验错误通过连接阶段统一返回
1223
1435
  throw new Error('SSH agent socket or pipe is unavailable');
1224
1436
  }
1225
1437
  connectConfig.agent = agent;
@@ -1228,11 +1440,23 @@ export class SessionManager {
1228
1440
  catch (error) {
1229
1441
  throw this.createConnectionError(error, config, readyTimeout, 'key_read');
1230
1442
  }
1443
+ let jumpHostKeys = [];
1444
+ let jumpSession;
1231
1445
  if (config.jumpHost) {
1232
1446
  const jumpConfig = {
1233
1447
  ...config.jumpHost,
1234
1448
  readyTimeout: config.jumpHost.readyTimeout ?? readyTimeout,
1235
1449
  };
1450
+ if (!jumpConfig.alias) {
1451
+ const defaultAlias = this.generateAlias(jumpConfig);
1452
+ const existing = this.sessions.get(defaultAlias);
1453
+ const inFlight = this.connectInFlight.get(defaultAlias);
1454
+ const requested = existing || inFlight ? this.connectionFingerprint(jumpConfig) : undefined;
1455
+ if ((existing && this.isAlive(existing) && this.connectionFingerprint(existing.config) !== requested) ||
1456
+ (inFlight && inFlight.fingerprint !== requested)) {
1457
+ jumpConfig.alias = `${alias}:jump:${defaultAlias}`;
1458
+ }
1459
+ }
1236
1460
  let jumpAlias;
1237
1461
  try {
1238
1462
  jumpAlias = await this.connect(jumpConfig);
@@ -1246,8 +1470,8 @@ export class SessionManager {
1246
1470
  }
1247
1471
  throw this.createConnectionError(error, jumpConfig, jumpConfig.readyTimeout, 'jump_connect');
1248
1472
  }
1249
- const jumpSession = this.sessions.get(jumpAlias);
1250
- if (!jumpSession || jumpSession.backend === 'openssh' || !this.isAlive(jumpSession)) {
1473
+ const candidate = this.sessions.get(jumpAlias);
1474
+ if (!candidate || candidate.backend === 'openssh' || !this.isAlive(candidate)) {
1251
1475
  throw new ConnectionError(`Jump host session '${jumpAlias}' is unavailable`, {
1252
1476
  failureStage: 'transport_or_handshake',
1253
1477
  connectionStep: 'jump_connect',
@@ -1255,6 +1479,8 @@ export class SessionManager {
1255
1479
  suggestion: '重新连接跳板机,或检查 jumpHost 配置和网络路径',
1256
1480
  });
1257
1481
  }
1482
+ jumpSession = candidate;
1483
+ jumpHostKeys = jumpSession.hostKeys ?? [];
1258
1484
  connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port ?? 22, readyTimeout);
1259
1485
  }
1260
1486
  if (!this.isCurrentPendingConnection(alias, pendingConnection)) {
@@ -1275,9 +1501,21 @@ export class SessionManager {
1275
1501
  }
1276
1502
  settled = true;
1277
1503
  clearPendingConnection();
1278
- reject(this.createConnectionError(error, config, readyTimeout, 'target_connect'));
1504
+ verificationController.abort(error);
1505
+ this.closeClientChannel(connectConfig.sock);
1506
+ reject(this.createConnectionError(hostKeyError ?? jumpSession?.connectionError ?? error, config, readyTimeout, 'target_connect'));
1279
1507
  };
1280
1508
  client.on('ready', () => {
1509
+ if (jumpSession?.connectionError) {
1510
+ rejectConnection(jumpSession.connectionError);
1511
+ client.end();
1512
+ return;
1513
+ }
1514
+ if (!hostKey) {
1515
+ rejectConnection(new HostKeyError('SSH ready arrived before host key verification completed'));
1516
+ client.end();
1517
+ return;
1518
+ }
1281
1519
  if (settled || !this.isCurrentPendingConnection(alias, pendingConnection)) {
1282
1520
  clearPendingConnection();
1283
1521
  client.end();
@@ -1291,8 +1529,11 @@ export class SessionManager {
1291
1529
  clearPendingConnection();
1292
1530
  const session = {
1293
1531
  client,
1532
+ jumpClient: jumpSession?.client,
1294
1533
  config,
1295
1534
  authAgent: typeof connectConfig.agent === 'string' ? connectConfig.agent : undefined,
1535
+ hostKey,
1536
+ hostKeys: [...jumpHostKeys, { ...hostKey, host: config.host, port: config.port ?? 22 }],
1296
1537
  connectedAt: Date.now(),
1297
1538
  lastUsedAt: Date.now(),
1298
1539
  reconnectAttempts: 0,
@@ -1300,6 +1541,7 @@ export class SessionManager {
1300
1541
  manualClose: false,
1301
1542
  };
1302
1543
  this.sessions.set(alias, session);
1544
+ verificationDeadline = undefined;
1303
1545
  this.persistSessions();
1304
1546
  resolve(alias);
1305
1547
  });
@@ -1311,11 +1553,12 @@ export class SessionManager {
1311
1553
  rejectConnection(error);
1312
1554
  });
1313
1555
  client.on('close', () => {
1556
+ verificationController.abort(new Error('SSH connection closed'));
1314
1557
  const session = this.sessions.get(alias);
1315
1558
  if (session && session.backend !== 'openssh' && session.client === client) {
1316
1559
  session.connected = false;
1317
1560
  this.invalidateAliasResources(alias);
1318
- if (!session.manualClose) {
1561
+ if (!session.manualClose && !session.connectionError) {
1319
1562
  this.scheduleReconnect(alias);
1320
1563
  }
1321
1564
  }
@@ -1324,6 +1567,14 @@ export class SessionManager {
1324
1567
  }
1325
1568
  });
1326
1569
  try {
1570
+ verificationDeadline = Date.now() + readyTimeout;
1571
+ const algorithms = this.knownHosts.getHostKeyAlgorithms(config.host, config.port ?? 22);
1572
+ if (algorithms.length > 0) {
1573
+ // ssh2 的 prepend 跳过已有项,先 remove 才能调整默认顺序
1574
+ connectConfig.algorithms = {
1575
+ serverHostKey: { remove: algorithms, prepend: algorithms, append: [] },
1576
+ };
1577
+ }
1327
1578
  client.connect(connectConfig);
1328
1579
  client.setNoDelay(true);
1329
1580
  }
@@ -1425,11 +1676,16 @@ export class SessionManager {
1425
1676
  return (this.pendingConnections.get(alias) === pending && this.getConnectionGeneration(alias) === pending.generation);
1426
1677
  }
1427
1678
  cancelPendingConnection(alias) {
1428
- 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
+ }
1429
1685
  const pending = this.pendingConnections.get(alias);
1430
1686
  const inFlight = this.connectInFlight.delete(alias);
1431
1687
  if (!pending) {
1432
- return inFlight;
1688
+ return inFlight || (preparations?.size ?? 0) > 0;
1433
1689
  }
1434
1690
  this.pendingConnections.delete(alias);
1435
1691
  pending.cancel(new Error(`Connection for alias '${alias}' was cancelled`));
@@ -1442,11 +1698,38 @@ export class SessionManager {
1442
1698
  this.forwardManager.closeByAlias(alias);
1443
1699
  clearRsyncCache(alias);
1444
1700
  }
1701
+ stopUntrustedConnection(alias, session, error) {
1702
+ if (this.sessions.get(alias) !== session) {
1703
+ return;
1704
+ }
1705
+ session.connectionError = error;
1706
+ session.connected = false;
1707
+ if (session.reconnectTimer) {
1708
+ clearTimeout(session.reconnectTimer);
1709
+ session.reconnectTimer = undefined;
1710
+ }
1711
+ this.invalidateAliasResources(alias);
1712
+ for (const [targetAlias, target] of this.sessions) {
1713
+ if (target.backend !== 'openssh' && target.jumpClient === session.client && !target.manualClose) {
1714
+ this.stopUntrustedConnection(targetAlias, target, new ConnectionError(error.message, { ...error.details, connectionStep: 'jump_connect' }));
1715
+ target.client.end();
1716
+ }
1717
+ }
1718
+ }
1445
1719
  /**
1446
1720
  * 检查连接是否存活
1447
1721
  */
1448
1722
  isAlive(session) {
1449
- return session.connected && (session.backend !== 'openssh' || session.transport.isAlive());
1723
+ if (!session.connected) {
1724
+ return false;
1725
+ }
1726
+ if (session.backend === 'openssh') {
1727
+ return session.transport.isAlive();
1728
+ }
1729
+ const client = session.client;
1730
+ // ssh2 在 close 事件更新 connected 前就会按 socket 状态拒绝命令
1731
+ return (!('_sock' in client) ||
1732
+ Boolean(client._sock?.writable && !client._sock.destroyed && client._sock._readableState?.ended === false));
1450
1733
  }
1451
1734
  isCurrentSession(alias, session) {
1452
1735
  return this.sessions.get(alias) === session && this.isAlive(session);
@@ -1478,7 +1761,10 @@ export class SessionManager {
1478
1761
  */
1479
1762
  scheduleReconnect(alias) {
1480
1763
  const session = this.sessions.get(alias);
1481
- if (!session || session.backend === 'openssh' || session.reconnectAttempts >= this.maxReconnectAttempts) {
1764
+ if (!session ||
1765
+ session.backend === 'openssh' ||
1766
+ session.connectionError ||
1767
+ session.reconnectAttempts >= this.maxReconnectAttempts) {
1482
1768
  return;
1483
1769
  }
1484
1770
  // 清掉旧的定时器,防止重复调度
@@ -1489,16 +1775,24 @@ export class SessionManager {
1489
1775
  const attempt = session.reconnectAttempts;
1490
1776
  session.reconnectTimer = setTimeout(async () => {
1491
1777
  const current = this.sessions.get(alias);
1492
- if (current !== session) {
1778
+ session.reconnectTimer = undefined;
1779
+ if (current !== session || session.connectionError) {
1493
1780
  return;
1494
1781
  }
1495
- session.reconnectTimer = undefined;
1496
1782
  try {
1497
1783
  await this.reconnect(alias);
1498
1784
  }
1499
1785
  catch (err) {
1500
- console.error(`Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}): ${err.message}`);
1501
- if (this.sessions.get(alias) === session) {
1786
+ console.error('Auto-reconnect failed for ' +
1787
+ `${alias}` +
1788
+ ' (' +
1789
+ `${attempt}` +
1790
+ '/' +
1791
+ `${this.maxReconnectAttempts}` +
1792
+ '): ' +
1793
+ `${err.message}`);
1794
+ if (this.sessions.get(alias) === session &&
1795
+ !(err instanceof ConnectionError && err.details.failureStage === 'host_key')) {
1502
1796
  this.scheduleReconnect(alias);
1503
1797
  }
1504
1798
  }
@@ -1533,6 +1827,14 @@ export class SessionManager {
1533
1827
  });
1534
1828
  }
1535
1829
  createConnectionError(error, config, readyTimeout, connectionStep) {
1830
+ if (error instanceof HostKeyError) {
1831
+ return new ConnectionError(error.message, {
1832
+ failureStage: 'host_key',
1833
+ connectionStep,
1834
+ retryable: false,
1835
+ hostKey: error.hostKey,
1836
+ });
1837
+ }
1536
1838
  if (error instanceof ConnectionError) {
1537
1839
  return new ConnectionError(error.message, {
1538
1840
  ...error.details,
@@ -1623,11 +1925,9 @@ export class SessionManager {
1623
1925
  * bash → .bashrc, zsh → .zshrc, 其他 → .profile
1624
1926
  */
1625
1927
  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; ');
1928
+ return ('case "$(basename "$SHELL" 2>/dev/null)" in bash) [ -f ~/.bashrc ] && . ' +
1929
+ '~/.bashrc ;; zsh) [ -f ~/.zshrc ] && . ~/.zshrc ;; *) [ -f ~/.profile ] ' +
1930
+ '&& . ~/.profile ;; esac 2>/dev/null; ');
1631
1931
  }
1632
1932
  /**
1633
1933
  * 持久化会话信息(异步非阻塞,避免阻塞事件循环)