@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.
@@ -36,7 +36,7 @@ export function remoteShellPath(remotePath, style) {
36
36
  if (style !== 'sftp-posix') {
37
37
  return remotePath;
38
38
  }
39
- const drive = /^\/([a-zA-Z]):(?:\/(.*))?$/.exec(remotePath);
39
+ const drive = /^\/(?<drive>[a-zA-Z]):(?:\/(?<path>.*))?$/.exec(remotePath);
40
40
  if (drive) {
41
41
  return `${drive[1].toUpperCase()}:\\${(drive[2] ?? '').replace(/\//g, '\\')}`;
42
42
  }
@@ -49,56 +49,84 @@ export function quotePowershell(value) {
49
49
  return `'${value.replace(/'/g, "''")}'`;
50
50
  }
51
51
  export function encodedPowershell(script) {
52
- return `powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script, 'utf16le').toString('base64')}`;
52
+ return ('powershell.exe -NoProfile -NonInteractive -EncodedCommand ' +
53
+ `${Buffer.from(script, 'utf16le').toString('base64')}`);
53
54
  }
54
55
  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`;
56
+ return ("$ErrorActionPreference = 'Stop'\n" +
57
+ "Add-Type -TypeDefinition @'\n" +
58
+ 'using System;\n' +
59
+ 'using System.ComponentModel;\n' +
60
+ 'using System.Runtime.InteropServices;\n' +
61
+ 'using Microsoft.Win32.SafeHandles;\n' +
62
+ 'public static class McpCaseSemantics {\n' +
63
+ ' [StructLayout(LayoutKind.Sequential)]\n' +
64
+ ' public struct FILE_CASE_SENSITIVE_INFO { public uint Flags; }\n' +
65
+ ' [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = ' +
66
+ 'true, ExactSpelling = true)]\n' +
67
+ ' public static extern SafeFileHandle CreateFileW(string path, uint ' +
68
+ 'access, uint share, IntPtr security, uint disposition, uint attributes, ' +
69
+ 'IntPtr template);\n' +
70
+ ' [DllImport("kernel32.dll", SetLastError = true)]\n' +
71
+ ' [return: MarshalAs(UnmanagedType.Bool)]\n' +
72
+ ' public static extern bool ' +
73
+ 'GetFileInformationByHandleEx(SafeFileHandle handle, int infoClass, out ' +
74
+ 'FILE_CASE_SENSITIVE_INFO info, uint size);\n' +
75
+ ' [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = ' +
76
+ 'true, ExactSpelling = true)]\n' +
77
+ ' public static extern int CompareStringOrdinal(string left, int ' +
78
+ 'leftLength, string right, int rightLength, ' +
79
+ '[MarshalAs(UnmanagedType.Bool)] bool ignoreCase);\n' +
80
+ ' private static int Compare(string left, string right) {\n' +
81
+ ' int result = CompareStringOrdinal(left, left.Length, right, ' +
82
+ 'right.Length, true);\n' +
83
+ ' if (result == 0) { throw new ' +
84
+ 'Win32Exception(Marshal.GetLastWin32Error()); }\n' +
85
+ ' return result - 2;\n' +
86
+ ' }\n' +
87
+ ' public static uint DirectoryFlags(string parent) {\n' +
88
+ ' // FILE_READ_ATTRIBUTES; FILE_SHARE_READ | WRITE | DELETE; ' +
89
+ 'OPEN_EXISTING; NORMAL | BACKUP_SEMANTICS.\n' +
90
+ ' using (SafeFileHandle handle = CreateFileW(parent, 128, 7, ' +
91
+ 'IntPtr.Zero, 3, 128 | 33554432, IntPtr.Zero)) {\n' +
92
+ ' if (handle.IsInvalid) { throw new ' +
93
+ 'Win32Exception(Marshal.GetLastWin32Error()); }\n' +
94
+ ' FILE_CASE_SENSITIVE_INFO info;\n' +
95
+ ' if (!GetFileInformationByHandleEx(handle, 23, out info, 4)) ' +
96
+ '{ throw new Win32Exception(Marshal.GetLastWin32Error()); }\n' +
97
+ ' return info.Flags;\n' +
98
+ ' }\n' +
99
+ ' }\n' +
100
+ ' public static string[] Collision(string[] names) {\n' +
101
+ ' Array.Sort(names, Compare);\n' +
102
+ ' for (int i = 1; i < names.Length; ++i) {\n' +
103
+ ' if (Compare(names[i - 1], names[i]) == 0) { return new ' +
104
+ 'string[] { names[i - 1], names[i] }; }\n' +
105
+ ' }\n' +
106
+ ' return null;\n' +
107
+ ' }\n' +
108
+ '}\n' +
109
+ "'@\n" +
110
+ '$parent = ' +
111
+ `${quotePowershell(parent)}` +
112
+ '\n' +
113
+ "if (-not [System.IO.Directory]::Exists($parent)) { throw 'candidate " +
114
+ "parent directory does not exist' }\n" +
115
+ '$caseSensitive = ([McpCaseSemantics]::DirectoryFlags($parent) -band 1) ' +
116
+ '-ne 0\n' +
117
+ '$names = ' +
118
+ `${names === undefined
119
+ ? '[string[]](ConvertFrom-Json ' +
120
+ '([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String(' +
121
+ '[Console]::In.ReadToEnd()))))'
122
+ : `[string[]]@(${names.map(quotePowershell).join(', ')})`}` +
123
+ '\n' +
124
+ '$collision = $null\n' +
125
+ 'if (-not $caseSensitive) { $collision = ' +
126
+ '[McpCaseSemantics]::Collision($names) }\n' +
127
+ '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)\n' +
128
+ '@{ caseSensitive = $caseSensitive; collision = $collision } | ' +
129
+ 'ConvertTo-Json -Compress');
102
130
  }
103
131
  export function buildRemoteCommand(command, shell, cwd, env) {
104
132
  const validKey = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
@@ -122,7 +150,11 @@ export function buildRemoteCommand(command, shell, cwd, env) {
122
150
  ...(cwd ? [`Set-Location -LiteralPath ${quotePowershell(cwd)}`] : []),
123
151
  ...Object.entries(env).map(([key, value]) => `$env:${key} = ${quotePowershell(value)}`),
124
152
  ];
125
- return encodedPowershell(`$ErrorActionPreference = 'Stop'; ${setup.join('; ')}; & cmd.exe /D /V:OFF /S /C ${quotePowershell(command)}; exit $LASTEXITCODE`);
153
+ return encodedPowershell("$ErrorActionPreference = 'Stop'; " +
154
+ `${setup.join('; ')}` +
155
+ '; & cmd.exe /D /V:OFF /S /C ' +
156
+ `${quotePowershell(command)}` +
157
+ '; exit $LASTEXITCODE');
126
158
  }
127
159
  const setup = [
128
160
  ...(cwd ? [`cd ${escapeShellArg(cwd)}`] : []),
@@ -18,6 +18,8 @@ export declare function validateKeyFile(p: string): void;
18
18
  * 同 validateKeyFile:原路径 + realpath 都必须在白名单
19
19
  */
20
20
  export declare function validateConfigFile(p: string): void;
21
+ /** known_hosts protects write integrity; public read access is permitted. */
22
+ export declare function validateKnownHostsPath(filePath: string, system?: boolean): string;
21
23
  /**
22
24
  * 脱敏 ssh2 keyParser 错误,避免 PEM 文件 cipher/kdf 字段被泄露
23
25
  */
package/dist/security.js CHANGED
@@ -20,9 +20,12 @@ function getAllowedDirs() {
20
20
  function isUnderAllowedDir(resolved) {
21
21
  const allowed = getAllowedDirs();
22
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)));
23
+ const roots = fs.existsSync(dir) ? [dir, fs.realpathSync(dir)] : [dir];
24
+ return roots.some((root) => {
25
+ const relative = path.relative(root, resolved);
26
+ return (relative === '' ||
27
+ (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)));
28
+ });
26
29
  });
27
30
  return { ok, allowed };
28
31
  }
@@ -75,6 +78,39 @@ export function validateConfigFile(p) {
75
78
  throw new Error(`SSH config file too large: ${stats.size} bytes (max ${MAX_CONFIG_FILE_SIZE})`);
76
79
  }
77
80
  }
81
+ /** known_hosts protects write integrity; public read access is permitted. */
82
+ export function validateKnownHostsPath(filePath, system = false) {
83
+ const resolveRealPath = (candidate) => {
84
+ let ancestor = candidate;
85
+ const suffix = [];
86
+ while (!fs.existsSync(ancestor)) {
87
+ const parent = path.dirname(ancestor);
88
+ if (parent === ancestor) {
89
+ throw new Error('known_hosts path has no existing ancestor');
90
+ }
91
+ suffix.unshift(path.basename(ancestor));
92
+ ancestor = parent;
93
+ }
94
+ return path.join(fs.realpathSync(ancestor), ...suffix);
95
+ };
96
+ const allowed = getAllowedDirs();
97
+ if (system && process.platform === 'win32') {
98
+ allowed.push(path.resolve(process.env.ProgramData ?? 'C:\\ProgramData', 'ssh'));
99
+ }
100
+ // Resolve trusted roots as well as files: system ancestors such as /etc can be aliases.
101
+ const realAllowed = allowed.map(resolveRealPath);
102
+ const under = (candidate, directories) => directories.some((dir) => {
103
+ const relative = path.relative(dir, candidate);
104
+ return (relative === '' ||
105
+ (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)));
106
+ });
107
+ const resolved = path.resolve(filePath);
108
+ const real = resolveRealPath(resolved);
109
+ if (!under(resolved, [...allowed, ...realAllowed]) || !under(real, realAllowed)) {
110
+ throw new Error('known_hosts path is outside the allowed SSH directories');
111
+ }
112
+ return real;
113
+ }
78
114
  /**
79
115
  * 脱敏 ssh2 keyParser 错误,避免 PEM 文件 cipher/kdf 字段被泄露
80
116
  */
@@ -8,8 +8,9 @@
8
8
  * - 会话持久化
9
9
  */
10
10
  import { Client, SFTPWrapper } from 'ssh2';
11
+ import { type HostKeyTrust } from './known-hosts.js';
11
12
  import { OpenSshConnection } from './openssh.js';
12
- import { ExecOptions, ExecResult, ExternalTransferCapability, ForwardCloseOptions, ForwardCloseResult, OperationCancelResult, OperationInfo, OperationReadResult, OperationStartOptions, OpenSshMasterInfo, PortForwardInfo, PtyCloseResult, PtyOptions, PtyReadResult, PtySessionInfo, PtyWriteResult, SSHConnectionConfig, SSHSessionBrief, SSHSessionDetail } from './types.js';
13
+ import { ConnectionFailureDetails, ExecOptions, ExecResult, ExternalTransferCapability, ForwardCloseOptions, ForwardCloseResult, OpenSshMasterInfo, OperationCancelResult, OperationInfo, OperationReadResult, OperationStartOptions, PortForwardInfo, PtyCloseResult, PtyOptions, PtyReadResult, PtySessionInfo, PtyWriteResult, SSHConnectionConfig, SSHSessionBrief, SSHSessionDetail } from './types.js';
13
14
  interface SessionState {
14
15
  config: SSHConnectionConfig;
15
16
  connectedAt: number;
@@ -17,6 +18,12 @@ interface SessionState {
17
18
  reconnectAttempts: number;
18
19
  connected: boolean;
19
20
  authAgent?: string;
21
+ hostKey?: HostKeyTrust;
22
+ hostKeys?: (HostKeyTrust & {
23
+ host: string;
24
+ port: number;
25
+ })[];
26
+ connectionError?: ConnectionError;
20
27
  manualClose: boolean;
21
28
  /** 当前正在等待的重连定时器,disconnect 时需要清除以防 zombie 重连 */
22
29
  reconnectTimer?: NodeJS.Timeout;
@@ -24,6 +31,7 @@ interface SessionState {
24
31
  interface Ssh2Session extends SessionState {
25
32
  backend?: 'ssh2';
26
33
  client: Client;
34
+ jumpClient?: Client;
27
35
  }
28
36
  type SSHSession = Ssh2Session | (SessionState & {
29
37
  backend: 'openssh';
@@ -48,13 +56,25 @@ interface SessionConnectionInfo {
48
56
  commandShell: 'posix' | 'cmd' | 'powershell';
49
57
  remotePathStyle: 'posix' | 'win32' | 'sftp-posix';
50
58
  keyAclStatus?: 'key_path_usable' | 'key_acl_insecure' | 'key_acl_unverified';
59
+ hostKey?: HostKeyTrust;
60
+ hostKeys?: (HostKeyTrust & {
61
+ host: string;
62
+ port: number;
63
+ })[];
64
+ }
65
+ declare class ConnectionError extends Error {
66
+ readonly details: ConnectionFailureDetails;
67
+ constructor(message: string, details: ConnectionFailureDetails);
51
68
  }
52
69
  export declare class SessionManager {
53
70
  private sessions;
54
71
  /** per-alias connect 进行中的 Promise,防止并发 connect 同一 alias 时重复建连 */
55
72
  private connectInFlight;
56
73
  private pendingConnections;
74
+ private preparingConnections;
57
75
  private connectionGenerations;
76
+ private cancellationSequence;
77
+ private readonly knownHosts;
58
78
  private readonly ptyManager;
59
79
  private readonly forwardManager;
60
80
  private readonly operationManager;
@@ -70,7 +90,11 @@ export declare class SessionManager {
70
90
  /**
71
91
  * 建立 SSH 连接(per-alias mutex,防止并发 connect 同一 alias 重复建连)
72
92
  */
73
- connect(config: SSHConnectionConfig): Promise<string>;
93
+ connect(config: SSHConnectionConfig, preparationGeneration?: number, signal?: AbortSignal): Promise<string>;
94
+ prepareConnection<T>(alias: string | undefined, prepare: (signal: AbortSignal) => Promise<T>): Promise<{
95
+ result: T;
96
+ generation?: number;
97
+ }>;
74
98
  /**
75
99
  * 重新连接
76
100
  */
@@ -133,7 +157,7 @@ export declare class SessionManager {
133
157
  ptyRead(ptyId: string, options?: {
134
158
  mode?: 'screen' | 'raw';
135
159
  clear?: boolean;
136
- }): PtyReadResult;
160
+ }): Promise<PtyReadResult>;
137
161
  ptyResize(ptyId: string, rows: number, cols: number): boolean;
138
162
  ptyClose(ptyId: string): PtyCloseResult;
139
163
  ptyList(): PtySessionInfo[];
@@ -157,6 +181,7 @@ export declare class SessionManager {
157
181
  private appendWithinByteLimit;
158
182
  private appendOutputTail;
159
183
  private recommendedReadCommand;
184
+ private commandExitMetadata;
160
185
  private emptyOutputFailureMetadata;
161
186
  private outputMetadata;
162
187
  private normalizeMaxOutputSize;
@@ -182,6 +207,7 @@ export declare class SessionManager {
182
207
  private isCurrentPendingConnection;
183
208
  private cancelPendingConnection;
184
209
  private invalidateAliasResources;
210
+ private stopUntrustedConnection;
185
211
  /**
186
212
  * 检查连接是否存活
187
213
  */