@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.
@@ -32,6 +32,8 @@ export declare class ForwardManager {
32
32
  list(): PortForwardInfo[];
33
33
  private pendingChannelOpensForAlias;
34
34
  private waitForConnectionDrain;
35
+ private recordConnectionClosed;
36
+ private notifyConnectionDrainIfIdle;
35
37
  private waitForChannelOpenDrain;
36
38
  private closeLocalListener;
37
39
  private closeRemoteListener;
@@ -84,14 +84,7 @@ export class ForwardManager {
84
84
  if (!socket.destroyed) {
85
85
  socket.destroy();
86
86
  }
87
- session.activeConnections = Math.max(0, session.activeConnections - 1);
88
- session.lastActivityAt = Date.now();
89
- if (session.activeConnections === 0) {
90
- for (const resolve of session.connectionDrainWaiters) {
91
- resolve();
92
- }
93
- session.connectionDrainWaiters.clear();
94
- }
87
+ this.recordConnectionClosed(session);
95
88
  };
96
89
  socket.once('close', closeConnection);
97
90
  socket.once('error', closeConnection);
@@ -346,6 +339,9 @@ export class ForwardManager {
346
339
  for (const connection of fwd.connections) {
347
340
  connection.destroy();
348
341
  }
342
+ fwd.connections.clear();
343
+ fwd.activeConnections = 0;
344
+ this.notifyConnectionDrainIfIdle(fwd);
349
345
  this.sessions.delete(fwd.id);
350
346
  if (fwd.type === 'local' && fwd.server && !fwd.closePromise) {
351
347
  this.closeServerAfterCancelledCreation(fwd.server);
@@ -405,6 +401,20 @@ export class ForwardManager {
405
401
  fwd.connectionDrainWaiters.add(resolve);
406
402
  });
407
403
  }
404
+ recordConnectionClosed(fwd) {
405
+ fwd.activeConnections = Math.max(0, fwd.activeConnections - 1);
406
+ fwd.lastActivityAt = Date.now();
407
+ this.notifyConnectionDrainIfIdle(fwd);
408
+ }
409
+ notifyConnectionDrainIfIdle(fwd) {
410
+ if (fwd.activeConnections !== 0) {
411
+ return;
412
+ }
413
+ for (const resolve of fwd.connectionDrainWaiters) {
414
+ resolve();
415
+ }
416
+ fwd.connectionDrainWaiters.clear();
417
+ }
408
418
  waitForChannelOpenDrain(fwd) {
409
419
  if (fwd.pendingChannelOpens === 0) {
410
420
  return Promise.resolve();
@@ -636,8 +646,7 @@ export class ForwardManager {
636
646
  closed = true;
637
647
  fwd.connections.delete(stream);
638
648
  fwd.connections.delete(socket);
639
- fwd.activeConnections = Math.max(0, fwd.activeConnections - 1);
640
- fwd.lastActivityAt = Date.now();
649
+ this.recordConnectionClosed(fwd);
641
650
  };
642
651
  socket.pipe(stream).pipe(socket);
643
652
  socket.on('error', () => stream.close());
@@ -14,9 +14,10 @@ export declare class OperationStartError extends Error {
14
14
  }
15
15
  export interface OperationDependencies {
16
16
  openStream(alias: string, command: string, marker: string, options: OperationStartOptions, adopt: (stream: ClientChannel) => void): Promise<void>;
17
- cancelRemote(alias: string, pid: number, marker: string, processGroup: boolean, options: OperationStartOptions): Promise<{
17
+ cancelRemote(alias: string, pid: number, marker: string, processGroup: boolean, options: OperationStartOptions, processCreatedAt?: string): Promise<{
18
18
  success: boolean;
19
19
  error?: string;
20
+ cancellationStatus?: 'unsupported' | 'unknown';
20
21
  }>;
21
22
  }
22
23
  export declare class OperationManager {
@@ -181,6 +181,7 @@ export class OperationManager {
181
181
  success: false,
182
182
  cancelRequested: record.cancelRequested,
183
183
  retryable: false,
184
+ cancellationStatus: 'not_applicable',
184
185
  verificationError: `Operation is ${record.status}`,
185
186
  };
186
187
  }
@@ -190,6 +191,7 @@ export class OperationManager {
190
191
  success: false,
191
192
  cancelRequested: false,
192
193
  retryable: true,
194
+ cancellationStatus: 'unknown',
193
195
  verificationError: 'Remote operation marker has not been verified',
194
196
  };
195
197
  }
@@ -199,13 +201,14 @@ export class OperationManager {
199
201
  success: false,
200
202
  cancelRequested: record.cancelRequested,
201
203
  retryable: true,
204
+ cancellationStatus: 'unknown',
202
205
  verificationError: 'Remote cancellation is already in progress',
203
206
  };
204
207
  }
205
208
  record.cancelInFlight = true;
206
209
  let result;
207
210
  try {
208
- result = await this.dependencies.cancelRemote(record.alias, record.pid, record.marker, record.processGroup, record.options);
211
+ result = await this.dependencies.cancelRemote(record.alias, record.pid, record.marker, record.processGroup, record.options, record.processCreatedAt);
209
212
  }
210
213
  catch (error) {
211
214
  record.cancelInFlight = false;
@@ -222,6 +225,7 @@ export class OperationManager {
222
225
  success: result.success,
223
226
  cancelRequested: record.cancelRequested,
224
227
  retryable: !result.success,
228
+ cancellationStatus: result.success ? 'requested' : (result.cancellationStatus ?? 'unknown'),
225
229
  ...(result.error ? { verificationError: result.error } : {}),
226
230
  };
227
231
  }
@@ -372,7 +376,7 @@ export class OperationManager {
372
376
  this.failMarker(record, 'Remote operation marker did not match the local operation');
373
377
  return;
374
378
  }
375
- const metadata = line.slice(expectedPrefix.length).match(/^([1-9]\d*):(0|1)$/);
379
+ const metadata = line.slice(expectedPrefix.length).match(/^([1-9]\d*):(0|1)(?::([1-9]\d*))?$/);
376
380
  const pid = metadata ? Number(metadata[1]) : Number.NaN;
377
381
  if (!metadata || !Number.isSafeInteger(pid)) {
378
382
  this.appendStderr(record, lineBytes);
@@ -383,6 +387,7 @@ export class OperationManager {
383
387
  }
384
388
  record.pid = pid;
385
389
  record.processGroup = metadata[2] === '1';
390
+ record.processCreatedAt = metadata[3];
386
391
  record.markerVerified = true;
387
392
  record.status = 'running';
388
393
  this.appendStderr(record, record.markerBuffer);
@@ -435,6 +440,7 @@ export class OperationManager {
435
440
  pid: record.pid,
436
441
  processGroup: record.processGroup,
437
442
  markerVerified: record.markerVerified,
443
+ processCreatedAt: record.processCreatedAt,
438
444
  cancelRequested: record.cancelRequested,
439
445
  startedAt: record.startedAt,
440
446
  finishedAt: record.finishedAt,
@@ -4,7 +4,7 @@
4
4
  * 负责 PTY 会话的完整生命周期:创建、读写、调整大小、关闭
5
5
  */
6
6
  import type { ClientChannel } from 'ssh2';
7
- import type { PtyCloseResult, PtyOptions, PtySessionInfo, PtyWriteResult } from './types.js';
7
+ import type { PtyCloseResult, PtyOptions, PtyReadResult, PtySessionInfo, PtyWriteResult } from './types.js';
8
8
  export declare const HARD_PTY_BUFFER_SIZE: number;
9
9
  /** PTY 创建所需的外部依赖 */
10
10
  export interface PtyDependencies {
@@ -24,23 +24,15 @@ export declare class PtyManager {
24
24
  read(ptyId: string, options?: {
25
25
  mode?: 'screen' | 'raw';
26
26
  clear?: boolean;
27
- }): {
28
- data: string;
29
- active: boolean;
30
- rows: number;
31
- cols: number;
32
- lastInputAt: number | null;
33
- lastOutputAt: number | null;
34
- lastReadAt: number;
35
- unreadRawBytes: number;
36
- rawBufferLimit: number;
37
- foregroundProcess: string;
38
- };
27
+ }): PtyReadResult;
39
28
  resize(ptyId: string, rows: number, cols: number): boolean;
40
29
  close(ptyId: string): PtyCloseResult;
41
30
  /** 关闭指定 alias 的所有 PTY 会话 */
42
31
  closeByAlias(alias: string): void;
43
32
  list(): PtySessionInfo[];
33
+ private appendOutput;
34
+ private appendRaw;
35
+ private endDecoder;
44
36
  private normalizeBufferSize;
45
37
  private startIdleSweeper;
46
38
  private sweepIdle;
@@ -4,6 +4,7 @@
4
4
  * 负责 PTY 会话的完整生命周期:创建、读写、调整大小、关闭
5
5
  */
6
6
  import xterm from '@xterm/headless';
7
+ import { StringDecoder } from 'string_decoder';
7
8
  const Terminal = xterm.Terminal;
8
9
  export const HARD_PTY_BUFFER_SIZE = 16 * 1024 * 1024;
9
10
  export class PtyManager {
@@ -37,37 +38,37 @@ export class PtyManager {
37
38
  lastInputAt: null,
38
39
  lastOutputAt: null,
39
40
  lastReadAt: Date.now(),
40
- rawBuffer: '',
41
+ rawBuffer: Buffer.alloc(0),
41
42
  unreadRawBytes: 0,
43
+ rawBufferTruncated: false,
42
44
  maxBufferSize,
45
+ decoder: new StringDecoder('utf8'),
46
+ decoderEnded: false,
43
47
  active: true,
44
48
  closedAt: null,
45
49
  };
46
50
  // 监听输出数据
47
51
  stream.on('data', (data) => {
48
- if (!ptySession.active) {
52
+ if (!ptySession.active || ptySession.decoderEnded) {
49
53
  return;
50
54
  }
51
- const chunk = data.toString('utf-8');
52
55
  ptySession.lastOutputAt = Date.now();
53
- // 写入终端仿真器(解析 ANSI 序列)
54
- terminal.write(chunk);
55
- // 同时保留原始流(用于 raw 模式)
56
- ptySession.rawBuffer += chunk;
57
- ptySession.unreadRawBytes += Buffer.byteLength(chunk, 'utf-8');
58
- if (ptySession.rawBuffer.length > maxBufferSize) {
59
- ptySession.rawBuffer = ptySession.rawBuffer.slice(-maxBufferSize);
60
- ptySession.unreadRawBytes = Math.min(ptySession.unreadRawBytes, Buffer.byteLength(ptySession.rawBuffer, 'utf-8'));
61
- }
56
+ this.appendRaw(ptySession, data);
57
+ this.appendOutput(ptySession, ptySession.decoder.write(data));
62
58
  });
63
59
  stream.on('close', () => {
64
60
  if (!this.sessions.has(ptyId)) {
65
61
  return;
66
62
  }
63
+ this.endDecoder(ptySession);
67
64
  ptySession.active = false;
68
65
  ptySession.closedAt = Date.now();
69
66
  });
70
67
  stream.on('error', (err) => {
68
+ if (!this.sessions.has(ptyId)) {
69
+ return;
70
+ }
71
+ this.endDecoder(ptySession);
71
72
  ptySession.active = false;
72
73
  ptySession.closedAt = Date.now();
73
74
  terminal.write(`\n[PTY Error: ${err.message}]`);
@@ -90,28 +91,35 @@ export class PtyManager {
90
91
  const session = this.getSession(ptyId);
91
92
  const mode = options.mode ?? 'screen';
92
93
  const clear = options.clear !== false;
94
+ const unreadRawBytes = session.unreadRawBytes;
95
+ const rawBufferTruncated = session.rawBufferTruncated;
93
96
  let data;
97
+ let dataBase64;
94
98
  if (mode === 'screen') {
95
99
  data = this.getScreenContent(session.terminal);
96
100
  }
97
101
  else {
98
- data = session.rawBuffer;
102
+ data = session.rawBuffer.toString('utf8');
103
+ dataBase64 = session.rawBuffer.toString('base64');
99
104
  if (clear) {
100
- session.rawBuffer = '';
105
+ session.rawBuffer = Buffer.alloc(0);
101
106
  session.unreadRawBytes = 0;
107
+ session.rawBufferTruncated = false;
102
108
  }
103
109
  }
104
110
  session.lastReadAt = Date.now();
105
111
  return {
106
112
  data,
113
+ dataBase64,
107
114
  active: session.active,
108
115
  rows: session.rows,
109
116
  cols: session.cols,
110
117
  lastInputAt: session.lastInputAt,
111
118
  lastOutputAt: session.lastOutputAt,
112
119
  lastReadAt: session.lastReadAt,
113
- unreadRawBytes: session.unreadRawBytes,
120
+ unreadRawBytes,
114
121
  rawBufferLimit: session.maxBufferSize,
122
+ rawBufferTruncated,
115
123
  foregroundProcess: session.command,
116
124
  };
117
125
  }
@@ -150,6 +158,7 @@ export class PtyManager {
150
158
  };
151
159
  }
152
160
  }
161
+ this.endDecoder(session);
153
162
  try {
154
163
  session.terminal.dispose();
155
164
  }
@@ -187,6 +196,7 @@ export class PtyManager {
187
196
  catch {
188
197
  // SSH 连接已失效,继续释放本地状态
189
198
  }
199
+ this.endDecoder(session);
190
200
  try {
191
201
  session.terminal.dispose();
192
202
  }
@@ -214,12 +224,34 @@ export class PtyManager {
214
224
  bufferSize: pty.rawBuffer.length,
215
225
  unreadRawBytes: pty.unreadRawBytes,
216
226
  rawBufferLimit: pty.maxBufferSize,
227
+ rawBufferTruncated: pty.rawBufferTruncated,
217
228
  foregroundProcess: pty.command,
218
229
  active: pty.active,
219
230
  });
220
231
  }
221
232
  return result;
222
233
  }
234
+ appendOutput(session, output) {
235
+ if (output.length === 0) {
236
+ return;
237
+ }
238
+ session.terminal.write(output);
239
+ }
240
+ appendRaw(session, data) {
241
+ const appended = Buffer.concat([session.rawBuffer, data]);
242
+ if (appended.length > session.maxBufferSize) {
243
+ session.rawBufferTruncated = true;
244
+ }
245
+ session.rawBuffer = appended.subarray(Math.max(0, appended.length - session.maxBufferSize));
246
+ session.unreadRawBytes = session.rawBuffer.length;
247
+ }
248
+ endDecoder(session) {
249
+ if (session.decoderEnded) {
250
+ return;
251
+ }
252
+ session.decoderEnded = true;
253
+ this.appendOutput(session, session.decoder.end());
254
+ }
223
255
  normalizeBufferSize(bufferSize) {
224
256
  if (bufferSize === undefined) {
225
257
  return this.defaultBufferSize;
@@ -0,0 +1,13 @@
1
+ import * as path from 'node:path';
2
+ import type { CommandShell, RemotePathStyle, RemotePlatform } from './types.js';
3
+ export declare function remotePathModule(style: RemotePathStyle): typeof path.posix | typeof path.win32;
4
+ export declare function remoteJoin(style: RemotePathStyle, parent: string, child: string): string;
5
+ export declare function remoteDirname(style: RemotePathStyle, remotePath: string): string;
6
+ export declare function remoteNormalize(style: RemotePathStyle, remotePath: string): string;
7
+ export declare function remotePathStyle(platform: RemotePlatform, style?: RemotePathStyle): RemotePathStyle;
8
+ export declare function sftpPath(remotePath: string, style: RemotePathStyle): string;
9
+ export declare function remoteShellPath(remotePath: string, style: RemotePathStyle): string;
10
+ export declare function quotePowershell(value: string): string;
11
+ export declare function encodedPowershell(script: string): string;
12
+ export declare function windowsCaseSemanticsScript(parent: string, names: string[]): string;
13
+ export declare function buildRemoteCommand(command: string, shell: CommandShell, cwd: string | undefined, env: Record<string, string>): string;
@@ -0,0 +1,132 @@
1
+ import * as path from 'node:path';
2
+ import { escapeShellArg } from './tools/utils.js';
3
+ export function remotePathModule(style) {
4
+ return style === 'win32' ? path.win32 : path.posix;
5
+ }
6
+ export function remoteJoin(style, parent, child) {
7
+ const joined = remotePathModule(style).join(parent, child);
8
+ return style === 'sftp-posix' && parent.startsWith('//') ? `/${joined}` : joined;
9
+ }
10
+ export function remoteDirname(style, remotePath) {
11
+ const parent = remotePathModule(style).dirname(remotePath);
12
+ return style === 'sftp-posix' && remotePath.startsWith('//') && parent.startsWith('/') && !parent.startsWith('//')
13
+ ? `/${parent}`
14
+ : parent;
15
+ }
16
+ export function remoteNormalize(style, remotePath) {
17
+ const normalized = remotePathModule(style).normalize(remotePath);
18
+ return style === 'sftp-posix' && remotePath.startsWith('//') ? `/${normalized}` : normalized;
19
+ }
20
+ export function remotePathStyle(platform, style) {
21
+ return style ?? (platform === 'windows' ? 'win32' : 'posix');
22
+ }
23
+ export function sftpPath(remotePath, style) {
24
+ if (style !== 'sftp-posix') {
25
+ return remotePath;
26
+ }
27
+ if (/^[a-zA-Z]:[\\/]/.test(remotePath)) {
28
+ return `/${remotePath[0].toUpperCase()}:${remotePath.slice(2).replace(/\\/g, '/')}`;
29
+ }
30
+ if (remotePath.startsWith('\\\\')) {
31
+ return `//${remotePath.slice(2).replace(/\\/g, '/')}`;
32
+ }
33
+ return remotePath.replace(/\\/g, '/');
34
+ }
35
+ export function remoteShellPath(remotePath, style) {
36
+ if (style !== 'sftp-posix') {
37
+ return remotePath;
38
+ }
39
+ const drive = /^\/([a-zA-Z]):(?:\/(.*))?$/.exec(remotePath);
40
+ if (drive) {
41
+ return `${drive[1].toUpperCase()}:\\${(drive[2] ?? '').replace(/\//g, '\\')}`;
42
+ }
43
+ if (/^\/\/[^/]+\/[^/]+/.test(remotePath)) {
44
+ return `\\\\${remotePath.slice(2).replace(/\//g, '\\')}`;
45
+ }
46
+ throw new Error('Windows shell path cannot be derived from this SFTP path; use a drive or UNC path');
47
+ }
48
+ export function quotePowershell(value) {
49
+ return `'${value.replace(/'/g, "''")}'`;
50
+ }
51
+ export function encodedPowershell(script) {
52
+ return `powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script, 'utf16le').toString('base64')}`;
53
+ }
54
+ export function windowsCaseSemanticsScript(parent, names) {
55
+ return `$ErrorActionPreference = 'Stop'
56
+ Add-Type -TypeDefinition @'
57
+ using System;
58
+ using System.ComponentModel;
59
+ using System.Runtime.InteropServices;
60
+ using Microsoft.Win32.SafeHandles;
61
+ public static class McpCaseSemantics {
62
+ [StructLayout(LayoutKind.Sequential)]
63
+ public struct FILE_CASE_SENSITIVE_INFO { public uint Flags; }
64
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
65
+ public static extern SafeFileHandle CreateFileW(string path, uint access, uint share, IntPtr security, uint disposition, uint attributes, IntPtr template);
66
+ [DllImport("kernel32.dll", SetLastError = true)]
67
+ [return: MarshalAs(UnmanagedType.Bool)]
68
+ public static extern bool GetFileInformationByHandleEx(SafeFileHandle handle, int infoClass, out FILE_CASE_SENSITIVE_INFO info, uint size);
69
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
70
+ public static extern int CompareStringOrdinal(string left, int leftLength, string right, int rightLength, [MarshalAs(UnmanagedType.Bool)] bool ignoreCase);
71
+ private static int Compare(string left, string right) {
72
+ int result = CompareStringOrdinal(left, left.Length, right, right.Length, true);
73
+ if (result == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); }
74
+ return result - 2;
75
+ }
76
+ public static uint DirectoryFlags(string parent) {
77
+ // FILE_READ_ATTRIBUTES; FILE_SHARE_READ | WRITE | DELETE; OPEN_EXISTING; NORMAL | BACKUP_SEMANTICS.
78
+ using (SafeFileHandle handle = CreateFileW(parent, 128, 7, IntPtr.Zero, 3, 128 | 33554432, IntPtr.Zero)) {
79
+ if (handle.IsInvalid) { throw new Win32Exception(Marshal.GetLastWin32Error()); }
80
+ FILE_CASE_SENSITIVE_INFO info;
81
+ if (!GetFileInformationByHandleEx(handle, 23, out info, 4)) { throw new Win32Exception(Marshal.GetLastWin32Error()); }
82
+ return info.Flags;
83
+ }
84
+ }
85
+ public static string[] Collision(string[] names) {
86
+ Array.Sort(names, Compare);
87
+ for (int i = 1; i < names.Length; ++i) {
88
+ if (Compare(names[i - 1], names[i]) == 0) { return new string[] { names[i - 1], names[i] }; }
89
+ }
90
+ return null;
91
+ }
92
+ }
93
+ '@
94
+ $parent = ${quotePowershell(parent)}
95
+ if (-not [System.IO.Directory]::Exists($parent)) { throw 'candidate parent directory does not exist' }
96
+ $caseSensitive = ([McpCaseSemantics]::DirectoryFlags($parent) -band 1) -ne 0
97
+ $names = [string[]]@(${names.map(quotePowershell).join(', ')})
98
+ $collision = $null
99
+ if (-not $caseSensitive) { $collision = [McpCaseSemantics]::Collision($names) }
100
+ [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
101
+ @{ caseSensitive = $caseSensitive; collision = $collision } | ConvertTo-Json -Compress`;
102
+ }
103
+ export function buildRemoteCommand(command, shell, cwd, env) {
104
+ const validKey = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
105
+ for (const key of Object.keys(env)) {
106
+ if (!validKey.test(key)) {
107
+ throw new Error(`Invalid environment variable name: ${key}`);
108
+ }
109
+ }
110
+ if (shell === 'powershell') {
111
+ const setup = [
112
+ ...(cwd ? [`Set-Location -LiteralPath ${quotePowershell(cwd)}; if (-not $?) { throw 'cwd failed' }`] : []),
113
+ ...Object.entries(env).map(([key, value]) => `$env:${key} = ${quotePowershell(value)}`),
114
+ ];
115
+ return encodedPowershell(`& { ${setup.join('; ')}; & { ${command} }; if (-not $?) { exit 1 } }`);
116
+ }
117
+ if (shell === 'cmd') {
118
+ if (!cwd && Object.keys(env).length === 0) {
119
+ return `cmd.exe /D /V:OFF /S /C "(${command})"`;
120
+ }
121
+ const setup = [
122
+ ...(cwd ? [`Set-Location -LiteralPath ${quotePowershell(cwd)}`] : []),
123
+ ...Object.entries(env).map(([key, value]) => `$env:${key} = ${quotePowershell(value)}`),
124
+ ];
125
+ return encodedPowershell(`$ErrorActionPreference = 'Stop'; ${setup.join('; ')}; & cmd.exe /D /V:OFF /S /C ${quotePowershell(command)}; exit $LASTEXITCODE`);
126
+ }
127
+ const setup = [
128
+ ...(cwd ? [`cd ${escapeShellArg(cwd)}`] : []),
129
+ ...Object.entries(env).map(([key, value]) => `export ${key}=${escapeShellArg(value)}`),
130
+ ];
131
+ return setup.length ? `${setup.join(' && ')} && eval ${escapeShellArg(command)}` : command;
132
+ }
package/dist/security.js CHANGED
@@ -11,7 +11,7 @@ import * as path from 'path';
11
11
  const MAX_KEY_FILE_SIZE = 64 * 1024; // 私钥实际不会超过 64KB
12
12
  const MAX_CONFIG_FILE_SIZE = 1024 * 1024; // SSH config 上限 1MB
13
13
  function getAllowedDirs() {
14
- const base = [path.resolve(os.homedir(), '.ssh'), '/etc/ssh'];
14
+ const base = [path.resolve(os.homedir(), '.ssh'), ...(process.platform === 'win32' ? [] : ['/etc/ssh'])];
15
15
  const env = process.env.SSH_MCP_ALLOWED_KEY_DIRS?.split(path.delimiter)
16
16
  .map((d) => d.trim())
17
17
  .filter(Boolean) ?? [];
@@ -19,7 +19,11 @@ function getAllowedDirs() {
19
19
  }
20
20
  function isUnderAllowedDir(resolved) {
21
21
  const allowed = getAllowedDirs();
22
- const ok = allowed.some((dir) => resolved === dir || resolved.startsWith(dir + path.sep));
22
+ const ok = allowed.some((dir) => {
23
+ const relative = path.relative(dir, resolved);
24
+ return (relative === '' ||
25
+ (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)));
26
+ });
23
27
  return { ok, allowed };
24
28
  }
25
29
  /**
@@ -40,6 +44,9 @@ export function validateKeyFile(p) {
40
44
  throw new Error(`Invalid private key path: symlink target falls outside the whitelist`);
41
45
  }
42
46
  const stats = fs.statSync(real);
47
+ if (!stats.isFile()) {
48
+ throw new Error('Private key path must point to a regular file');
49
+ }
43
50
  if (stats.size > MAX_KEY_FILE_SIZE) {
44
51
  throw new Error(`Private key file too large: ${stats.size} bytes (max ${MAX_KEY_FILE_SIZE})`);
45
52
  }
@@ -61,6 +68,9 @@ export function validateConfigFile(p) {
61
68
  throw new Error(`Invalid config path: symlink target falls outside the whitelist`);
62
69
  }
63
70
  const stats = fs.statSync(real);
71
+ if (!stats.isFile()) {
72
+ throw new Error('SSH config path must point to a regular file');
73
+ }
64
74
  if (stats.size > MAX_CONFIG_FILE_SIZE) {
65
75
  throw new Error(`SSH config file too large: ${stats.size} bytes (max ${MAX_CONFIG_FILE_SIZE})`);
66
76
  }
@@ -8,7 +8,7 @@
8
8
  * - 会话持久化
9
9
  */
10
10
  import { Client, SFTPWrapper } from 'ssh2';
11
- import { ExecOptions, ExecResult, ExternalTransferCapability, ForwardCloseOptions, ForwardCloseResult, OperationCancelResult, OperationInfo, OperationReadResult, OperationStartOptions, PortForwardInfo, PtyCloseResult, PtyOptions, PtySessionInfo, PtyWriteResult, SSHConnectionConfig, SSHSessionBrief, SSHSessionDetail } from './types.js';
11
+ import { ExecOptions, ExecResult, ExternalTransferCapability, ForwardCloseOptions, ForwardCloseResult, OperationCancelResult, OperationInfo, OperationReadResult, OperationStartOptions, PortForwardInfo, PtyCloseResult, PtyOptions, PtyReadResult, PtySessionInfo, PtyWriteResult, SSHConnectionConfig, SSHSessionBrief, SSHSessionDetail } from './types.js';
12
12
  interface SSHSession {
13
13
  client: Client;
14
14
  config: SSHConnectionConfig;
@@ -16,6 +16,7 @@ interface SSHSession {
16
16
  lastUsedAt: number;
17
17
  reconnectAttempts: number;
18
18
  connected: boolean;
19
+ authAgent?: string;
19
20
  manualClose: boolean;
20
21
  /** 当前正在等待的重连定时器,disconnect 时需要清除以防 zombie 重连 */
21
22
  reconnectTimer?: NodeJS.Timeout;
@@ -30,6 +31,10 @@ interface SessionConnectionInfo {
30
31
  defaultEnvKeys: string[];
31
32
  envKeys: string[];
32
33
  hasJumpHost: boolean;
34
+ remotePlatform: 'posix' | 'windows';
35
+ commandShell: 'posix' | 'cmd' | 'powershell';
36
+ remotePathStyle: 'posix' | 'win32' | 'sftp-posix';
37
+ keyAclStatus?: 'key_path_usable' | 'key_acl_insecure' | 'key_acl_unverified';
33
38
  }
34
39
  export declare class SessionManager {
35
40
  private sessions;
@@ -41,6 +46,7 @@ export declare class SessionManager {
41
46
  private readonly forwardManager;
42
47
  private readonly operationManager;
43
48
  private readonly persistPath;
49
+ private persistQueue;
44
50
  private defaultKeepaliveInterval;
45
51
  private defaultKeepaliveCountMax;
46
52
  private defaultTimeout;
@@ -69,6 +75,10 @@ export declare class SessionManager {
69
75
  listSessions(): SSHSessionBrief[];
70
76
  listSessionDetails(): SSHSessionDetail[];
71
77
  getSessionConnectionInfo(alias: string): SessionConnectionInfo;
78
+ requirePosixPrivilege(alias: string): void;
79
+ getRemotePlatform(alias: string): 'posix' | 'windows';
80
+ getRemotePathStyle(alias: string): 'posix' | 'win32' | 'sftp-posix';
81
+ getCommandShell(alias: string): 'posix' | 'cmd' | 'powershell';
72
82
  getExternalTransferCapability(alias: string): ExternalTransferCapability;
73
83
  /**
74
84
  * 执行命令
@@ -109,18 +119,7 @@ export declare class SessionManager {
109
119
  ptyRead(ptyId: string, options?: {
110
120
  mode?: 'screen' | 'raw';
111
121
  clear?: boolean;
112
- }): {
113
- data: string;
114
- active: boolean;
115
- rows: number;
116
- cols: number;
117
- lastInputAt: number | null;
118
- lastOutputAt: number | null;
119
- lastReadAt: number;
120
- unreadRawBytes: number;
121
- rawBufferLimit: number;
122
- foregroundProcess: string;
123
- };
122
+ }): PtyReadResult;
124
123
  ptyResize(ptyId: string, rows: number, cols: number): boolean;
125
124
  ptyClose(ptyId: string): PtyCloseResult;
126
125
  ptyList(): PtySessionInfo[];
@@ -140,6 +139,7 @@ export declare class SessionManager {
140
139
  private configIdentity;
141
140
  private connectionFingerprint;
142
141
  private resultMetadata;
142
+ private appendWithinByteLimit;
143
143
  private appendOutputTail;
144
144
  private recommendedReadCommand;
145
145
  private emptyOutputFailureMetadata;