@pyrokine/mcp-ssh 2.4.3 → 3.0.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.
@@ -7,17 +7,21 @@
7
7
  * - 自动重连
8
8
  * - 会话持久化
9
9
  */
10
- import { createHash } from 'crypto';
10
+ import { createHash, randomUUID } from 'crypto';
11
11
  import * as fs from 'fs';
12
12
  import * as os from 'os';
13
13
  import * as path from 'path';
14
14
  import { Client } from 'ssh2';
15
+ import { StringDecoder } from 'string_decoder';
16
+ import { isUtf8ContinuationByte, retainUtf8Suffix } from './utf8.js';
15
17
  import { clearRsyncCache } from './file-ops.js';
16
18
  import { ForwardManager } from './forward-manager.js';
17
19
  import { OperationManager } from './operation-manager.js';
18
20
  import { PtyManager } from './pty-manager.js';
21
+ import { buildRemoteCommand, encodedPowershell, quotePowershell, remotePathStyle } from './remote-platform.js';
19
22
  import { sanitizeKeyError, validateKeyFile } from './security.js';
20
23
  import { escapeShellArg, expandTilde } from './tools/utils.js';
24
+ import { checkWindowsAcl } from './windows-acl.js';
21
25
  import { DEFAULT_EXEC_MAX_OUTPUT_SIZE, HARD_EXEC_MAX_OUTPUT_SIZE, } from './types.js';
22
26
  const OUTPUT_PREVIEW_CHARS = 4096;
23
27
  class CommandError extends Error {
@@ -46,6 +50,7 @@ export class SessionManager {
46
50
  forwardManager = new ForwardManager();
47
51
  operationManager;
48
52
  persistPath;
53
+ persistQueue = Promise.resolve();
49
54
  defaultKeepaliveInterval = 30000; // 30秒
50
55
  defaultKeepaliveCountMax = 3;
51
56
  defaultTimeout = 30000; // 30秒
@@ -56,7 +61,7 @@ export class SessionManager {
56
61
  this.persistPath = persistPath || path.join(os.homedir(), '.ssh-mcp-pro', 'sessions.json');
57
62
  this.operationManager = new OperationManager({
58
63
  openStream: (alias, command, marker, options, adopt) => this.openOperationStream(alias, command, marker, options, adopt),
59
- cancelRemote: (alias, pid, marker, processGroup, options) => this.cancelRemoteOperation(alias, pid, marker, processGroup, options),
64
+ cancelRemote: (alias, pid, marker, processGroup, options, processCreatedAt) => this.cancelRemoteOperation(alias, pid, marker, processGroup, options, processCreatedAt),
60
65
  });
61
66
  this.ensurePersistDir();
62
67
  }
@@ -64,6 +69,20 @@ export class SessionManager {
64
69
  * 建立 SSH 连接(per-alias mutex,防止并发 connect 同一 alias 重复建连)
65
70
  */
66
71
  async connect(config) {
72
+ const platform = config.remotePlatform ?? 'posix';
73
+ const shell = config.commandShell ?? (platform === 'windows' ? 'powershell' : 'posix');
74
+ if ((platform === 'windows') !== (shell !== 'posix')) {
75
+ throw new CommandError('commandShell must match remotePlatform', {
76
+ code: 'unsupported_remote_platform',
77
+ platform,
78
+ shell,
79
+ });
80
+ }
81
+ if (platform === 'windows' && config.runAs) {
82
+ throw new CommandError('runAs is not supported for Windows remote hosts', {
83
+ code: 'unsupported_remote_platform',
84
+ });
85
+ }
67
86
  const alias = this.generateAlias(config);
68
87
  const fingerprint = this.connectionFingerprint(config);
69
88
  const requestedIdentity = this.configIdentity(config);
@@ -214,6 +233,9 @@ export class SessionManager {
214
233
  connectedAt: session.connectedAt,
215
234
  lastUsedAt: session.lastUsedAt,
216
235
  hasJumpHost: Boolean(session.config.jumpHost),
236
+ remotePlatform: session.config.remotePlatform ?? 'posix',
237
+ commandShell: session.config.commandShell ?? (session.config.remotePlatform === 'windows' ? 'powershell' : 'posix'),
238
+ remotePathStyle: remotePathStyle(session.config.remotePlatform ?? 'posix', session.config.remotePathStyle),
217
239
  }));
218
240
  }
219
241
  getSessionConnectionInfo(alias) {
@@ -229,8 +251,33 @@ export class SessionManager {
229
251
  defaultEnvKeys: config.defaultEnv ? Object.keys(config.defaultEnv) : [],
230
252
  envKeys: config.env ? Object.keys(config.env) : [],
231
253
  hasJumpHost: Boolean(config.jumpHost),
254
+ remotePlatform: config.remotePlatform ?? 'posix',
255
+ commandShell: config.commandShell ?? (config.remotePlatform === 'windows' ? 'powershell' : 'posix'),
256
+ remotePathStyle: remotePathStyle(config.remotePlatform ?? 'posix', config.remotePathStyle),
257
+ keyAclStatus: process.platform === 'win32' && config.privateKeyPath
258
+ ? checkWindowsAcl(expandTilde(config.privateKeyPath))
259
+ : undefined,
232
260
  };
233
261
  }
262
+ requirePosixPrivilege(alias) {
263
+ if (this.getRemotePlatform(alias) === 'windows') {
264
+ throw new CommandError('Remote Windows does not support su/sudo/runAs', {
265
+ code: 'unsupported_remote_platform',
266
+ remotePlatform: 'windows',
267
+ });
268
+ }
269
+ }
270
+ getRemotePlatform(alias) {
271
+ return this.getSession(alias).config.remotePlatform ?? 'posix';
272
+ }
273
+ getRemotePathStyle(alias) {
274
+ const config = this.getSession(alias).config;
275
+ return remotePathStyle(config.remotePlatform ?? 'posix', config.remotePathStyle);
276
+ }
277
+ getCommandShell(alias) {
278
+ const config = this.getSession(alias).config;
279
+ return config.commandShell ?? (config.remotePlatform === 'windows' ? 'powershell' : 'posix');
280
+ }
234
281
  getExternalTransferCapability(alias) {
235
282
  const session = this.getSession(alias);
236
283
  const config = session.config;
@@ -245,21 +292,27 @@ export class SessionManager {
245
292
  const routeSafeForOpenSsh = !hasJumpHost;
246
293
  const expandedKeyPath = config.privateKeyPath ? expandTilde(config.privateKeyPath) : undefined;
247
294
  const keyPathUsable = authMethod === 'key-path' && this.isOpenSshKeyPathUsable(expandedKeyPath);
248
- const agentAvailable = authMethod === 'agent' && this.isSshAgentAvailable();
249
- const rsyncEligible = routeSafeForOpenSsh && (keyPathUsable || agentAvailable);
295
+ const agent = session.authAgent ?? config.agent;
296
+ const agentAvailable = authMethod === 'agent' && this.isSshAgentAvailable(agent);
297
+ const profileRequired = (process.platform === 'win32' || config.remotePlatform === 'windows') && !config.rsyncProfile;
298
+ const rsyncEligible = routeSafeForOpenSsh && (keyPathUsable || agentAvailable) && !profileRequired;
250
299
  const decisionReason = hasJumpHost
251
300
  ? 'jump_host_route_requires_live_ssh_session'
252
301
  : authMethod === 'password'
253
302
  ? 'password_not_forwarded_to_openssh'
254
303
  : authMethod === 'inline-key'
255
304
  ? 'inline_private_key_not_written_to_disk'
256
- : authMethod === 'key-path'
257
- ? keyPathUsable
258
- ? 'direct_openssh_compatible_key_path'
259
- : 'key_path_not_openssh_compatible'
260
- : agentAvailable
261
- ? 'direct_ssh_agent_socket'
262
- : 'ssh_agent_socket_unavailable';
305
+ : authMethod === 'key-path' && !keyPathUsable
306
+ ? 'key_path_not_openssh_compatible'
307
+ : authMethod === 'agent' && !agentAvailable
308
+ ? agent
309
+ ? 'ssh_agent_not_openssh_compatible'
310
+ : 'ssh_agent_socket_unavailable'
311
+ : profileRequired
312
+ ? 'rsync_profile_required_for_windows'
313
+ : authMethod === 'key-path'
314
+ ? 'direct_openssh_compatible_key_path'
315
+ : 'direct_ssh_agent_socket';
263
316
  return {
264
317
  alias,
265
318
  identity: this.sessionIdentity(session),
@@ -272,6 +325,11 @@ export class SessionManager {
272
325
  routeSafeForOpenSsh,
273
326
  rsyncEligible,
274
327
  decisionReason,
328
+ agent: config.agent === 'none' ? 'none' : agentAvailable ? agent : undefined,
329
+ rsyncExecutable: config.rsyncExecutable,
330
+ rsyncProfile: config.rsyncProfile,
331
+ commandShell: config.commandShell ?? (config.remotePlatform === 'windows' ? 'powershell' : 'posix'),
332
+ remotePathStyle: remotePathStyle(config.remotePlatform ?? 'posix', config.remotePathStyle),
275
333
  };
276
334
  }
277
335
  /**
@@ -286,6 +344,9 @@ export class SessionManager {
286
344
  return this.execDirect(alias, command, options, { cwd: options.cwd });
287
345
  }
288
346
  operationStart(alias, command, options = {}) {
347
+ if (options.runAs || (this.getSession(alias).config.runAs && !options.useLoginUser)) {
348
+ this.requirePosixPrivilege(alias);
349
+ }
289
350
  return this.operationManager.start(alias, command, options);
290
351
  }
291
352
  operationStatus(operationId) {
@@ -309,6 +370,7 @@ export class SessionManager {
309
370
  * 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)
310
371
  */
311
372
  async execAsUser(alias, command, targetUser, options = {}) {
373
+ this.requirePosixPrivilege(alias);
312
374
  // 校验用户名防止注入
313
375
  if (!this.isValidUsername(targetUser)) {
314
376
  throw new Error(`Invalid username: ${targetUser}`);
@@ -332,6 +394,7 @@ export class SessionManager {
332
394
  * 通过 stdin 传递密码,避免密码出现在进程列表和 audit 日志中
333
395
  */
334
396
  async execSudo(alias, command, sudoPassword, options = {}) {
397
+ this.requirePosixPrivilege(alias);
335
398
  if (!sudoPassword) {
336
399
  return this.exec(alias, `sudo ${command}`, options);
337
400
  }
@@ -370,8 +433,39 @@ export class SessionManager {
370
433
  let stderrTail = '';
371
434
  let stdoutBytes = 0;
372
435
  let stderrBytes = 0;
436
+ let stdoutKeptBytes = 0;
437
+ let stderrKeptBytes = 0;
373
438
  let stdoutTruncated = false;
374
439
  let stderrTruncated = false;
440
+ const stdoutDecoder = new StringDecoder('utf8');
441
+ const stderrDecoder = new StringDecoder('utf8');
442
+ let decodersEnded = false;
443
+ const appendStdout = (chunk) => {
444
+ stdoutTail = this.appendOutputTail(stdoutTail, chunk);
445
+ if (!stdoutTruncated) {
446
+ const appended = this.appendWithinByteLimit(stdout, chunk, maxOutputSize - stdoutKeptBytes);
447
+ stdout = appended.text;
448
+ stdoutKeptBytes += appended.appendedBytes;
449
+ stdoutTruncated = appended.truncated;
450
+ }
451
+ };
452
+ const appendStderr = (chunk) => {
453
+ stderrTail = this.appendOutputTail(stderrTail, chunk);
454
+ if (!stderrTruncated) {
455
+ const appended = this.appendWithinByteLimit(stderr, chunk, maxOutputSize - stderrKeptBytes);
456
+ stderr = appended.text;
457
+ stderrKeptBytes += appended.appendedBytes;
458
+ stderrTruncated = appended.truncated;
459
+ }
460
+ };
461
+ const endDecoders = () => {
462
+ if (decodersEnded) {
463
+ return;
464
+ }
465
+ decodersEnded = true;
466
+ appendStdout(stdoutDecoder.end());
467
+ appendStderr(stderrDecoder.end());
468
+ };
375
469
  const outputPreview = () => ({
376
470
  stdout,
377
471
  stderr,
@@ -388,6 +482,7 @@ export class SessionManager {
388
482
  return;
389
483
  }
390
484
  settled = true;
485
+ endDecoders();
391
486
  try {
392
487
  streamRef?.close();
393
488
  }
@@ -402,6 +497,7 @@ export class SessionManager {
402
497
  this.closeClientChannel(stream);
403
498
  if (!settled) {
404
499
  settled = true;
500
+ endDecoders();
405
501
  reject(new Error('Sudo exec was cancelled because the SSH session changed'));
406
502
  }
407
503
  return;
@@ -410,6 +506,7 @@ export class SessionManager {
410
506
  clearTimeout(timeoutId);
411
507
  if (!settled) {
412
508
  settled = true;
509
+ endDecoders();
413
510
  reject(new Error(`Exec failed: ${err.message}`));
414
511
  }
415
512
  return;
@@ -428,10 +525,11 @@ export class SessionManager {
428
525
  return;
429
526
  }
430
527
  settled = true;
528
+ endDecoders();
431
529
  resolve({
432
530
  success: code === 0,
433
- stdout: stdoutTruncated ? stdout + '\n... [truncated]' : stdout,
434
- stderr: stderrTruncated ? stderr + '\n... [truncated]' : stderr,
531
+ stdout,
532
+ stderr,
435
533
  exitCode: code,
436
534
  duration: Date.now() - startTime,
437
535
  failureKind: code === 0 ? undefined : 'remote_command',
@@ -443,32 +541,18 @@ export class SessionManager {
443
541
  });
444
542
  });
445
543
  stream.on('data', (data) => {
446
- const chunk = data.toString('utf-8');
447
- stdoutBytes += data.length;
448
- stdoutTail = this.appendOutputTail(stdoutTail, chunk);
449
- if (!stdoutTruncated) {
450
- if (stdout.length + chunk.length > maxOutputSize) {
451
- stdout += chunk.slice(0, maxOutputSize - stdout.length);
452
- stdoutTruncated = true;
453
- }
454
- else {
455
- stdout += chunk;
456
- }
544
+ if (settled) {
545
+ return;
457
546
  }
547
+ stdoutBytes += data.length;
548
+ appendStdout(stdoutDecoder.write(data));
458
549
  });
459
550
  stream.stderr.on('data', (data) => {
460
- const chunk = data.toString('utf-8');
461
- stderrBytes += data.length;
462
- stderrTail = this.appendOutputTail(stderrTail, chunk);
463
- if (!stderrTruncated) {
464
- if (stderr.length + chunk.length > maxOutputSize) {
465
- stderr += chunk.slice(0, maxOutputSize - stderr.length);
466
- stderrTruncated = true;
467
- }
468
- else {
469
- stderr += chunk;
470
- }
551
+ if (settled) {
552
+ return;
471
553
  }
554
+ stderrBytes += data.length;
555
+ appendStderr(stderrDecoder.write(data));
472
556
  });
473
557
  });
474
558
  });
@@ -529,13 +613,12 @@ export class SessionManager {
529
613
  forwardList() {
530
614
  return this.forwardManager.list();
531
615
  }
532
- isSshAgentAvailable() {
533
- const socketPath = process.env.SSH_AUTH_SOCK;
534
- if (!socketPath) {
535
- return false;
616
+ isSshAgentAvailable(socketPath) {
617
+ if (!socketPath || socketPath === 'none' || socketPath === 'pageant') {
618
+ return false; // ssh2 can use Pageant, but the independent OpenSSH rsync process cannot inherit it.
536
619
  }
537
620
  if (process.platform === 'win32') {
538
- return true;
621
+ return /^\\\\\.\\pipe\\openssh-ssh-agent$/i.test(socketPath);
539
622
  }
540
623
  try {
541
624
  return fs.statSync(socketPath).isSocket();
@@ -550,6 +633,9 @@ export class SessionManager {
550
633
  if (!stats.isFile()) {
551
634
  return false;
552
635
  }
636
+ if (process.platform === 'win32' && checkWindowsAcl(keyPath) !== 'key_path_usable') {
637
+ return false;
638
+ }
553
639
  if (process.platform !== 'win32' && (stats.mode & 0o077) !== 0) {
554
640
  return false;
555
641
  }
@@ -585,6 +671,12 @@ export class SessionManager {
585
671
  readyTimeout: value.readyTimeout,
586
672
  lang: value.lang,
587
673
  shell: value.shell,
674
+ agent: value.agent,
675
+ remotePlatform: value.remotePlatform ?? 'posix',
676
+ commandShell: value.commandShell ?? (value.remotePlatform === 'windows' ? 'powershell' : 'posix'),
677
+ remotePathStyle: remotePathStyle(value.remotePlatform ?? 'posix', value.remotePathStyle),
678
+ rsyncExecutable: value.rsyncExecutable,
679
+ rsyncProfile: value.rsyncProfile,
588
680
  password: secretHash(value.password),
589
681
  privateKeyPath: value.privateKeyPath ? path.resolve(expandTilde(value.privateKeyPath)) : undefined,
590
682
  privateKey: secretHash(value.privateKey),
@@ -605,14 +697,25 @@ export class SessionManager {
605
697
  identity: this.sessionIdentity(session),
606
698
  cwd: context.cwd ?? options.cwd,
607
699
  resolvedCwd: context.cwd ?? options.cwd,
608
- shell: session.config.shell,
700
+ shell: session.config.commandShell ?? (session.config.remotePlatform === 'windows' ? 'powershell' : 'posix'),
609
701
  profileLoaded: context.loadProfile,
610
702
  envInjectedKeys: context.envInjectedKeys ?? Object.keys(env).filter((key) => this.isValidEnvKey(key)),
611
703
  };
612
704
  }
705
+ appendWithinByteLimit(current, chunk, available) {
706
+ const bytes = Buffer.from(chunk, 'utf8');
707
+ if (bytes.length <= available) {
708
+ return { text: current + chunk, appendedBytes: bytes.length, truncated: false };
709
+ }
710
+ let end = Math.max(0, available);
711
+ while (end > 0 && end < bytes.length && isUtf8ContinuationByte(bytes[end])) {
712
+ --end;
713
+ }
714
+ return { text: current + bytes.subarray(0, end).toString('utf8'), appendedBytes: end, truncated: true };
715
+ }
613
716
  appendOutputTail(current, chunk) {
614
- const next = current + chunk;
615
- return next.length > OUTPUT_PREVIEW_CHARS ? next.slice(-OUTPUT_PREVIEW_CHARS) : next;
717
+ const next = Buffer.from(current + chunk, 'utf8');
718
+ return retainUtf8Suffix(next, OUTPUT_PREVIEW_CHARS).toString('utf8');
616
719
  }
617
720
  recommendedReadCommand() {
618
721
  return ('将远端命令输出重定向到文件,例如 command > /tmp/mcp-ssh-output.txt 2>&1,' +
@@ -634,9 +737,13 @@ export class SessionManager {
634
737
  return {
635
738
  stdoutBytes: preview.stdoutBytes,
636
739
  stderrBytes: preview.stderrBytes,
637
- stdoutHead: preview.stdoutTruncated ? preview.stdout.slice(0, OUTPUT_PREVIEW_CHARS) : undefined,
740
+ stdoutHead: preview.stdoutTruncated
741
+ ? this.appendWithinByteLimit('', preview.stdout, OUTPUT_PREVIEW_CHARS).text
742
+ : undefined,
638
743
  stdoutTail: preview.stdoutTruncated ? preview.stdoutTail : undefined,
639
- stderrHead: preview.stderrTruncated ? preview.stderr.slice(0, OUTPUT_PREVIEW_CHARS) : undefined,
744
+ stderrHead: preview.stderrTruncated
745
+ ? this.appendWithinByteLimit('', preview.stderr, OUTPUT_PREVIEW_CHARS).text
746
+ : undefined,
640
747
  stderrTail: preview.stderrTruncated ? preview.stderrTail : undefined,
641
748
  recommendedReadCommand: truncated ? this.recommendedReadCommand() : undefined,
642
749
  maxOutputSize: truncated ? preview.maxOutputSize : undefined,
@@ -663,11 +770,27 @@ export class SessionManager {
663
770
  const markerLine = `__MCP_SSH_OPERATION__:${marker}:%s:%s\\n`;
664
771
  const operationScript = this.escapeShellArg(`printf ${this.escapeShellArg(markerLine)} "$$" "$1" >&2; exec sh -c ${this.escapeShellArg(command)}`);
665
772
  const wrappedCommand = `if command -v setsid >/dev/null 2>&1; then ` +
666
- `exec env ${markerEnv} setsid sh -c ${operationScript} sh 1; ` +
773
+ `exec env ${markerEnv} setsid -w sh -c ${operationScript} sh 1; ` +
667
774
  `else exec env ${markerEnv} sh -c ${operationScript} sh 0; fi`;
668
775
  const runAs = options.useLoginUser ? undefined : (options.runAs ?? session.config.runAs);
669
776
  let fullCommand;
670
- if (runAs) {
777
+ if (session.config.remotePlatform === 'windows') {
778
+ if (runAs) {
779
+ this.requirePosixPrivilege(alias);
780
+ }
781
+ const execution = session.config.commandShell === 'cmd'
782
+ ? `& cmd.exe /D /C ${quotePowershell(command)}`
783
+ : `& { ${command} }`;
784
+ const script = [
785
+ `$operationMarker = ${quotePowershell(marker)}`,
786
+ '$created = (Get-Process -Id $PID).StartTime.ToUniversalTime().Ticks',
787
+ '[Console]::Error.WriteLine("__MCP_SSH_OPERATION__:{0}:{1}:0:{2}", $operationMarker, $PID, $created)',
788
+ execution,
789
+ 'if (-not $?) { exit 1 }',
790
+ ].join('; ');
791
+ fullCommand = this.buildCommand(encodedPowershell(script), session, options);
792
+ }
793
+ else if (runAs) {
671
794
  if (!this.isValidUsername(runAs)) {
672
795
  throw new Error(`Invalid username: ${runAs}`);
673
796
  }
@@ -700,7 +823,43 @@ export class SessionManager {
700
823
  });
701
824
  });
702
825
  }
703
- async cancelRemoteOperation(alias, pid, marker, processGroup, options) {
826
+ async cancelRemoteOperation(alias, pid, marker, processGroup, options, processCreatedAt) {
827
+ if (this.getRemotePlatform(alias) === 'windows') {
828
+ if (!processCreatedAt || !/^[1-9]\d*$/.test(processCreatedAt)) {
829
+ return {
830
+ success: false,
831
+ cancellationStatus: 'unsupported',
832
+ error: 'unsupported_remote_platform: process creation time is unavailable',
833
+ };
834
+ }
835
+ const script = [
836
+ '$ErrorActionPreference = "Stop"',
837
+ `$remotePid = ${pid}`,
838
+ `$expectedTicks = ${quotePowershell(processCreatedAt)}`,
839
+ `$expectedMarker = ${quotePowershell(marker)}`,
840
+ '$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" }',
842
+ '$script = [Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($Matches[1]))',
843
+ 'if (-not $script.Contains($expectedMarker)) { throw "operation marker mismatch" }',
844
+ '$start = (Get-Process -Id $remotePid).StartTime.ToUniversalTime().Ticks.ToString()',
845
+ 'if ($start -ne $expectedTicks) { throw "process creation time mismatch" }',
846
+ 'taskkill.exe /PID $remotePid /T /F',
847
+ 'if ($LASTEXITCODE -ne 0) { throw "tree termination failed" }',
848
+ ].join('; ');
849
+ try {
850
+ const result = await this.exec(alias, encodedPowershell(script), {
851
+ useLoginUser: true,
852
+ timeout: 5000,
853
+ maxOutputSize: 4096,
854
+ });
855
+ return result.success
856
+ ? { success: true }
857
+ : { success: false, error: result.stderr || `Remote cancel exited with code ${result.exitCode}` };
858
+ }
859
+ catch (error) {
860
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
861
+ }
862
+ }
704
863
  const expectedMarker = `MCP_SSH_OPERATION_MARKER=${marker}`;
705
864
  const signalTarget = processGroup ? `-${pid}` : `${pid}`;
706
865
  const command = [
@@ -709,7 +868,7 @@ export class SessionManager {
709
868
  'if [ ! -r "/proc/$pid/environ" ]; then printf "operation marker unavailable" >&2; exit 3; fi',
710
869
  'if ! tr "\\000" "\\n" < "/proc/$pid/environ" | grep -Fqx -- "$expected"; then ' +
711
870
  'printf "operation marker mismatch" >&2; exit 4; fi',
712
- `kill -TERM -- ${signalTarget}`,
871
+ `kill -TERM ${signalTarget}`,
713
872
  ].join('; ');
714
873
  try {
715
874
  const result = await this.exec(alias, command, {
@@ -741,10 +900,41 @@ export class SessionManager {
741
900
  let stderrTail = '';
742
901
  let stdoutBytes = 0;
743
902
  let stderrBytes = 0;
903
+ let stdoutKeptBytes = 0;
904
+ let stderrKeptBytes = 0;
744
905
  let stdoutTruncated = false;
745
906
  let stderrTruncated = false;
746
907
  let settled = false;
747
908
  let activeStream = null;
909
+ const stdoutDecoder = new StringDecoder('utf8');
910
+ const stderrDecoder = new StringDecoder('utf8');
911
+ let decodersEnded = false;
912
+ const appendStdout = (chunk) => {
913
+ stdoutTail = this.appendOutputTail(stdoutTail, chunk);
914
+ if (!stdoutTruncated) {
915
+ const appended = this.appendWithinByteLimit(stdout, chunk, maxOutputSize - stdoutKeptBytes);
916
+ stdout = appended.text;
917
+ stdoutKeptBytes += appended.appendedBytes;
918
+ stdoutTruncated = appended.truncated;
919
+ }
920
+ };
921
+ const appendStderr = (chunk) => {
922
+ stderrTail = this.appendOutputTail(stderrTail, chunk);
923
+ if (!stderrTruncated) {
924
+ const appended = this.appendWithinByteLimit(stderr, chunk, maxOutputSize - stderrKeptBytes);
925
+ stderr = appended.text;
926
+ stderrKeptBytes += appended.appendedBytes;
927
+ stderrTruncated = appended.truncated;
928
+ }
929
+ };
930
+ const endDecoders = () => {
931
+ if (decodersEnded) {
932
+ return;
933
+ }
934
+ decodersEnded = true;
935
+ appendStdout(stdoutDecoder.end());
936
+ appendStderr(stderrDecoder.end());
937
+ };
748
938
  const execOptions = {};
749
939
  if (options.pty) {
750
940
  execOptions.pty = {
@@ -775,11 +965,13 @@ export class SessionManager {
775
965
  return;
776
966
  }
777
967
  settled = true;
968
+ endDecoders();
778
969
  clearTimer();
779
970
  activeStream?.close();
780
971
  reject(error);
781
972
  };
782
973
  timeoutId = setTimeout(() => {
974
+ endDecoders();
783
975
  rejectOnce(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
784
976
  }, timeout);
785
977
  session.client.exec(fullCommand, execOptions, (err, stream) => {
@@ -802,11 +994,12 @@ export class SessionManager {
802
994
  return;
803
995
  }
804
996
  settled = true;
997
+ endDecoders();
805
998
  clearTimer();
806
999
  resolve({
807
1000
  success: code === 0,
808
- stdout: stdoutTruncated ? stdout + '\n... [truncated]' : stdout,
809
- stderr: stderrTruncated ? stderr + '\n... [truncated]' : stderr,
1001
+ stdout,
1002
+ stderr,
810
1003
  exitCode: code,
811
1004
  duration: Date.now() - startTime,
812
1005
  failureKind: code === 0 ? undefined : 'remote_command',
@@ -818,32 +1011,18 @@ export class SessionManager {
818
1011
  });
819
1012
  });
820
1013
  stream.on('data', (data) => {
821
- const chunk = data.toString('utf-8');
822
- stdoutBytes += data.length;
823
- stdoutTail = this.appendOutputTail(stdoutTail, chunk);
824
- if (!stdoutTruncated) {
825
- if (stdout.length + chunk.length > maxOutputSize) {
826
- stdout += chunk.slice(0, maxOutputSize - stdout.length);
827
- stdoutTruncated = true;
828
- }
829
- else {
830
- stdout += chunk;
831
- }
1014
+ if (settled) {
1015
+ return;
832
1016
  }
1017
+ stdoutBytes += data.length;
1018
+ appendStdout(stdoutDecoder.write(data));
833
1019
  });
834
1020
  stream.stderr.on('data', (data) => {
835
- const chunk = data.toString('utf-8');
836
- stderrBytes += data.length;
837
- stderrTail = this.appendOutputTail(stderrTail, chunk);
838
- if (!stderrTruncated) {
839
- if (stderr.length + chunk.length > maxOutputSize) {
840
- stderr += chunk.slice(0, maxOutputSize - stderr.length);
841
- stderrTruncated = true;
842
- }
843
- else {
844
- stderr += chunk;
845
- }
1021
+ if (settled) {
1022
+ return;
846
1023
  }
1024
+ stderrBytes += data.length;
1025
+ appendStderr(stderrDecoder.write(data));
847
1026
  });
848
1027
  });
849
1028
  });
@@ -884,6 +1063,12 @@ export class SessionManager {
884
1063
  const keyPath = expandTilde(config.privateKeyPath);
885
1064
  // 路径白名单 + 大小上限校验,避免任意文件读取
886
1065
  validateKeyFile(keyPath);
1066
+ if (process.platform === 'win32') {
1067
+ const aclStatus = checkWindowsAcl(keyPath);
1068
+ if (aclStatus !== 'key_path_usable') {
1069
+ throw new CommandError(`Private key ACL check failed: ${aclStatus}`, { code: aclStatus });
1070
+ }
1071
+ }
887
1072
  connectConfig.privateKey = fs.readFileSync(keyPath);
888
1073
  }
889
1074
  if (config.privateKey) {
@@ -892,6 +1077,19 @@ export class SessionManager {
892
1077
  if (config.passphrase) {
893
1078
  connectConfig.passphrase = config.passphrase;
894
1079
  }
1080
+ const agent = config.agent ??
1081
+ (!config.password && !config.privateKey && !config.privateKeyPath
1082
+ ? process.env.SSH_AUTH_SOCK
1083
+ : undefined);
1084
+ if (agent && agent !== 'none') {
1085
+ if (agent === 'pageant' && process.platform !== 'win32') {
1086
+ throw new Error('Pageant authentication is only available on Windows');
1087
+ }
1088
+ if (agent !== 'pageant' && !agent.startsWith('\\\\.\\pipe\\') && !fs.existsSync(agent)) {
1089
+ throw new Error('SSH agent socket or pipe is unavailable');
1090
+ }
1091
+ connectConfig.agent = agent;
1092
+ }
895
1093
  }
896
1094
  catch (error) {
897
1095
  throw this.createConnectionError(error, config, readyTimeout, 'key_read');
@@ -960,6 +1158,7 @@ export class SessionManager {
960
1158
  const session = {
961
1159
  client,
962
1160
  config,
1161
+ authAgent: typeof connectConfig.agent === 'string' ? connectConfig.agent : undefined,
963
1162
  connectedAt: Date.now(),
964
1163
  lastUsedAt: Date.now(),
965
1164
  reconnectAttempts: 0,
@@ -992,6 +1191,7 @@ export class SessionManager {
992
1191
  });
993
1192
  try {
994
1193
  client.connect(connectConfig);
1194
+ client.setNoDelay(true);
995
1195
  }
996
1196
  catch (error) {
997
1197
  rejectConnection(error);
@@ -1030,6 +1230,14 @@ export class SessionManager {
1030
1230
  if (!fs.existsSync(dir)) {
1031
1231
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
1032
1232
  }
1233
+ if (process.platform === 'win32') {
1234
+ if (checkWindowsAcl(dir, true) !== 'key_path_usable') {
1235
+ throw new Error('privacy_not_enforced_on_windows: session directory ACL could not be verified');
1236
+ }
1237
+ if (fs.existsSync(this.persistPath) && checkWindowsAcl(this.persistPath, true) !== 'key_path_usable') {
1238
+ throw new Error('privacy_not_enforced_on_windows: existing session file ACL could not be verified');
1239
+ }
1240
+ }
1033
1241
  }
1034
1242
  /**
1035
1243
  * 生成连接别名
@@ -1156,7 +1364,7 @@ export class SessionManager {
1156
1364
  await this.reconnect(alias);
1157
1365
  }
1158
1366
  catch (err) {
1159
- console.error(`Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}):`, err.message);
1367
+ console.error(`Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}): ${err.message}`);
1160
1368
  if (this.sessions.get(alias) === session) {
1161
1369
  this.scheduleReconnect(alias);
1162
1370
  }
@@ -1174,9 +1382,9 @@ export class SessionManager {
1174
1382
  loadProfile: context.loadProfile,
1175
1383
  cwd: context.cwd,
1176
1384
  remoteProcessKnown: false,
1177
- stdoutHead: preview?.stdout.slice(0, OUTPUT_PREVIEW_CHARS),
1385
+ stdoutHead: preview ? this.appendWithinByteLimit('', preview.stdout, OUTPUT_PREVIEW_CHARS).text : undefined,
1178
1386
  stdoutTail: preview?.stdoutTail,
1179
- stderrHead: preview?.stderr.slice(0, OUTPUT_PREVIEW_CHARS),
1387
+ stderrHead: preview ? this.appendWithinByteLimit('', preview.stderr, OUTPUT_PREVIEW_CHARS).text : undefined,
1180
1388
  stderrTail: preview?.stderrTail,
1181
1389
  stdoutBytes: preview?.stdoutBytes,
1182
1390
  stderrBytes: preview?.stderrBytes,
@@ -1198,6 +1406,15 @@ export class SessionManager {
1198
1406
  connectionStep: error.details.connectionStep ?? connectionStep,
1199
1407
  });
1200
1408
  }
1409
+ if (error instanceof CommandError &&
1410
+ (error.details.code === 'key_acl_insecure' || error.details.code === 'key_acl_unverified')) {
1411
+ return new ConnectionError(error.message, {
1412
+ failureStage: 'preflight',
1413
+ connectionStep,
1414
+ retryable: false,
1415
+ keyAclStatus: error.details.code,
1416
+ });
1417
+ }
1201
1418
  const err = error instanceof Error ? error : new Error(String(error));
1202
1419
  const target = `${config.username}@${config.host}:${config.port ?? 22}`;
1203
1420
  return new ConnectionError(`SSH connection to ${target} failed: ${sanitizeKeyError(err.message)}`, {
@@ -1262,23 +1479,11 @@ export class SessionManager {
1262
1479
  * 构建完整命令:注入环境变量 + 切换工作目录
1263
1480
  */
1264
1481
  buildCommand(command, session, options) {
1265
- const segments = [];
1266
1482
  const env = options.skipSessionEnv
1267
1483
  ? { ...options.env }
1268
1484
  : { ...session.config.defaultEnv, ...session.config.env, ...options.env };
1269
- if (options.cwd) {
1270
- segments.push(`cd ${this.escapeShellArg(options.cwd)}`);
1271
- }
1272
- for (const [key, value] of Object.entries(env)) {
1273
- if (this.isValidEnvKey(key)) {
1274
- segments.push(`export ${key}=${this.escapeShellArg(value)}`);
1275
- }
1276
- }
1277
- if (segments.length === 0) {
1278
- return command;
1279
- }
1280
- segments.push(`eval ${this.escapeShellArg(command)}`);
1281
- return segments.join(' && ');
1485
+ const shell = session.config.commandShell ?? (session.config.remotePlatform === 'windows' ? 'powershell' : 'posix');
1486
+ return buildRemoteCommand(command, shell, options.cwd, env);
1282
1487
  }
1283
1488
  /**
1284
1489
  * 根据用户 shell 类型生成加载配置文件的命令
@@ -1307,6 +1512,31 @@ export class SessionManager {
1307
1512
  connectedAt: session.connectedAt,
1308
1513
  });
1309
1514
  }
1515
+ if (process.platform === 'win32') {
1516
+ const temporary = `${this.persistPath}.${randomUUID()}.tmp`;
1517
+ this.persistQueue = this.persistQueue
1518
+ .then(async () => {
1519
+ try {
1520
+ const handle = await fs.promises.open(temporary, 'wx', 0o600);
1521
+ try {
1522
+ if (checkWindowsAcl(temporary, true) !== 'key_path_usable') {
1523
+ throw new Error('privacy_not_enforced_on_windows: session file ACL could not be verified');
1524
+ }
1525
+ await handle.writeFile(JSON.stringify(data, null, 2));
1526
+ await handle.sync();
1527
+ }
1528
+ finally {
1529
+ await handle.close();
1530
+ }
1531
+ await fs.promises.rename(temporary, this.persistPath);
1532
+ }
1533
+ finally {
1534
+ await fs.promises.rm(temporary, { force: true });
1535
+ }
1536
+ })
1537
+ .catch((err) => console.error('[SSH] 会话持久化写入失败:', err));
1538
+ return;
1539
+ }
1310
1540
  fs.promises
1311
1541
  .writeFile(this.persistPath, JSON.stringify(data, null, 2), { mode: 0o600 })
1312
1542
  .catch((err) => console.error('[SSH] 会话持久化写入失败:', err));