@pyrokine/mcp-ssh 2.4.3 → 3.1.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.
- package/README.md +257 -49
- package/README_zh.md +251 -68
- package/dist/command-risk.d.ts +2 -1
- package/dist/command-risk.js +238 -87
- package/dist/directory-verification.d.ts +7 -3
- package/dist/directory-verification.js +302 -208
- package/dist/file-mode.d.ts +6 -0
- package/dist/file-mode.js +71 -0
- package/dist/file-ops.d.ts +38 -7
- package/dist/file-ops.js +822 -293
- package/dist/forward-manager.d.ts +2 -0
- package/dist/forward-manager.js +19 -10
- package/dist/openssh.d.ts +51 -0
- package/dist/openssh.js +528 -0
- package/dist/operation-manager.d.ts +4 -4
- package/dist/operation-manager.js +28 -3
- package/dist/pty-manager.d.ts +5 -13
- package/dist/pty-manager.js +47 -15
- package/dist/remote-platform.d.ts +13 -0
- package/dist/remote-platform.js +132 -0
- package/dist/security.js +12 -2
- package/dist/session-manager.d.ts +31 -15
- package/dist/session-manager.js +483 -120
- package/dist/ssh-config.d.ts +3 -0
- package/dist/ssh-config.js +48 -20
- package/dist/tools/connection.js +132 -3
- package/dist/tools/exec.d.ts +1 -0
- package/dist/tools/exec.js +108 -31
- package/dist/tools/file.js +406 -129
- package/dist/tools/operation.js +1 -1
- package/dist/tools/pty.js +5 -3
- package/dist/tools/utils.js +2 -2
- package/dist/types.d.ts +63 -2
- package/dist/utf8.d.ts +1 -0
- package/dist/utf8.js +10 -0
- package/dist/windows-acl.d.ts +4 -0
- package/dist/windows-acl.js +109 -0
- package/package.json +4 -3
|
@@ -154,11 +154,23 @@ export class OperationManager {
|
|
|
154
154
|
ensureUtf8Boundary(record.stderr, stderrOffset, 'stderrOffset');
|
|
155
155
|
const stdoutRequestedEnd = Math.min(record.stdout.length, stdoutOffset + maxReadBytes);
|
|
156
156
|
const stdoutEnd = utf8SafeEnd(record.stdout, stdoutOffset, stdoutRequestedEnd, 'stdout');
|
|
157
|
+
if (record.finishedAt !== null &&
|
|
158
|
+
!record.stdoutTruncated &&
|
|
159
|
+
stdoutRequestedEnd === record.stdout.length &&
|
|
160
|
+
stdoutEnd < stdoutRequestedEnd) {
|
|
161
|
+
throw new Error('Operation output contains an incomplete UTF-8 sequence in stdout');
|
|
162
|
+
}
|
|
157
163
|
const stdout = record.stdout.subarray(stdoutOffset, stdoutEnd);
|
|
158
164
|
const nextStdoutOffset = record.stdoutTruncated && stdoutRequestedEnd === record.stdout.length ? stdoutRequestedEnd : stdoutEnd;
|
|
159
165
|
const remaining = maxReadBytes - stdout.length;
|
|
160
166
|
const stderrRequestedEnd = Math.min(record.stderr.length, stderrOffset + remaining);
|
|
161
167
|
const stderrEnd = utf8SafeEnd(record.stderr, stderrOffset, stderrRequestedEnd, 'stderr');
|
|
168
|
+
if (record.finishedAt !== null &&
|
|
169
|
+
!record.stderrTruncated &&
|
|
170
|
+
stderrRequestedEnd === record.stderr.length &&
|
|
171
|
+
stderrEnd < stderrRequestedEnd) {
|
|
172
|
+
throw new Error('Operation output contains an incomplete UTF-8 sequence in stderr');
|
|
173
|
+
}
|
|
162
174
|
const stderr = record.stderr.subarray(stderrOffset, stderrEnd);
|
|
163
175
|
const nextStderrOffset = record.stderrTruncated && stderrRequestedEnd === record.stderr.length ? stderrRequestedEnd : stderrEnd;
|
|
164
176
|
return {
|
|
@@ -181,6 +193,7 @@ export class OperationManager {
|
|
|
181
193
|
success: false,
|
|
182
194
|
cancelRequested: record.cancelRequested,
|
|
183
195
|
retryable: false,
|
|
196
|
+
cancellationStatus: 'not_applicable',
|
|
184
197
|
verificationError: `Operation is ${record.status}`,
|
|
185
198
|
};
|
|
186
199
|
}
|
|
@@ -190,6 +203,7 @@ export class OperationManager {
|
|
|
190
203
|
success: false,
|
|
191
204
|
cancelRequested: false,
|
|
192
205
|
retryable: true,
|
|
206
|
+
cancellationStatus: 'unknown',
|
|
193
207
|
verificationError: 'Remote operation marker has not been verified',
|
|
194
208
|
};
|
|
195
209
|
}
|
|
@@ -199,13 +213,14 @@ export class OperationManager {
|
|
|
199
213
|
success: false,
|
|
200
214
|
cancelRequested: record.cancelRequested,
|
|
201
215
|
retryable: true,
|
|
216
|
+
cancellationStatus: 'unknown',
|
|
202
217
|
verificationError: 'Remote cancellation is already in progress',
|
|
203
218
|
};
|
|
204
219
|
}
|
|
205
220
|
record.cancelInFlight = true;
|
|
206
221
|
let result;
|
|
207
222
|
try {
|
|
208
|
-
result = await this.dependencies.cancelRemote(record.alias, record.pid, record.marker, record.processGroup, record.options);
|
|
223
|
+
result = await this.dependencies.cancelRemote(record.alias, record.pid, record.marker, record.processGroup, record.options, record.processCreatedAt);
|
|
209
224
|
}
|
|
210
225
|
catch (error) {
|
|
211
226
|
record.cancelInFlight = false;
|
|
@@ -222,6 +237,7 @@ export class OperationManager {
|
|
|
222
237
|
success: result.success,
|
|
223
238
|
cancelRequested: record.cancelRequested,
|
|
224
239
|
retryable: !result.success,
|
|
240
|
+
cancellationStatus: result.success ? 'requested' : (result.cancellationStatus ?? 'unknown'),
|
|
225
241
|
...(result.error ? { verificationError: result.error } : {}),
|
|
226
242
|
};
|
|
227
243
|
}
|
|
@@ -293,7 +309,14 @@ export class OperationManager {
|
|
|
293
309
|
return;
|
|
294
310
|
}
|
|
295
311
|
this.flushMarkerBuffer(record);
|
|
296
|
-
|
|
312
|
+
const details = 'details' in error ? error.details : undefined;
|
|
313
|
+
record.status =
|
|
314
|
+
details &&
|
|
315
|
+
typeof details === 'object' &&
|
|
316
|
+
'operationStatus' in details &&
|
|
317
|
+
details.operationStatus === 'unknown'
|
|
318
|
+
? 'unknown'
|
|
319
|
+
: 'failed';
|
|
297
320
|
record.error = error.message;
|
|
298
321
|
this.finish(record);
|
|
299
322
|
}
|
|
@@ -372,7 +395,7 @@ export class OperationManager {
|
|
|
372
395
|
this.failMarker(record, 'Remote operation marker did not match the local operation');
|
|
373
396
|
return;
|
|
374
397
|
}
|
|
375
|
-
const metadata = line.slice(expectedPrefix.length).match(/^([1-9]\d*):(0|1)
|
|
398
|
+
const metadata = line.slice(expectedPrefix.length).match(/^([1-9]\d*):(0|1)(?::([1-9]\d*))?$/);
|
|
376
399
|
const pid = metadata ? Number(metadata[1]) : Number.NaN;
|
|
377
400
|
if (!metadata || !Number.isSafeInteger(pid)) {
|
|
378
401
|
this.appendStderr(record, lineBytes);
|
|
@@ -383,6 +406,7 @@ export class OperationManager {
|
|
|
383
406
|
}
|
|
384
407
|
record.pid = pid;
|
|
385
408
|
record.processGroup = metadata[2] === '1';
|
|
409
|
+
record.processCreatedAt = metadata[3];
|
|
386
410
|
record.markerVerified = true;
|
|
387
411
|
record.status = 'running';
|
|
388
412
|
this.appendStderr(record, record.markerBuffer);
|
|
@@ -435,6 +459,7 @@ export class OperationManager {
|
|
|
435
459
|
pid: record.pid,
|
|
436
460
|
processGroup: record.processGroup,
|
|
437
461
|
markerVerified: record.markerVerified,
|
|
462
|
+
processCreatedAt: record.processCreatedAt,
|
|
438
463
|
cancelRequested: record.cancelRequested,
|
|
439
464
|
startedAt: record.startedAt,
|
|
440
465
|
finishedAt: record.finishedAt,
|
package/dist/pty-manager.d.ts
CHANGED
|
@@ -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;
|
package/dist/pty-manager.js
CHANGED
|
@@ -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
|
-
|
|
54
|
-
|
|
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
|
|
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) =>
|
|
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,19 +8,33 @@
|
|
|
8
8
|
* - 会话持久化
|
|
9
9
|
*/
|
|
10
10
|
import { Client, SFTPWrapper } from 'ssh2';
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
|
|
11
|
+
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
|
+
interface SessionState {
|
|
14
14
|
config: SSHConnectionConfig;
|
|
15
15
|
connectedAt: number;
|
|
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;
|
|
22
23
|
}
|
|
24
|
+
interface Ssh2Session extends SessionState {
|
|
25
|
+
backend?: 'ssh2';
|
|
26
|
+
client: Client;
|
|
27
|
+
}
|
|
28
|
+
type SSHSession = Ssh2Session | (SessionState & {
|
|
29
|
+
backend: 'openssh';
|
|
30
|
+
transport: OpenSshConnection;
|
|
31
|
+
});
|
|
23
32
|
interface SessionConnectionInfo {
|
|
33
|
+
backend: 'ssh2' | 'openssh';
|
|
34
|
+
masterReused?: boolean;
|
|
35
|
+
identityStatus?: OpenSshMasterInfo['identityStatus'];
|
|
36
|
+
masterPid?: number;
|
|
37
|
+
observedLogin?: OpenSshMasterInfo['observedLogin'];
|
|
24
38
|
alias: string;
|
|
25
39
|
identity: string;
|
|
26
40
|
loginUser: string;
|
|
@@ -30,6 +44,10 @@ interface SessionConnectionInfo {
|
|
|
30
44
|
defaultEnvKeys: string[];
|
|
31
45
|
envKeys: string[];
|
|
32
46
|
hasJumpHost: boolean;
|
|
47
|
+
remotePlatform: 'posix' | 'windows';
|
|
48
|
+
commandShell: 'posix' | 'cmd' | 'powershell';
|
|
49
|
+
remotePathStyle: 'posix' | 'win32' | 'sftp-posix';
|
|
50
|
+
keyAclStatus?: 'key_path_usable' | 'key_acl_insecure' | 'key_acl_unverified';
|
|
33
51
|
}
|
|
34
52
|
export declare class SessionManager {
|
|
35
53
|
private sessions;
|
|
@@ -41,6 +59,7 @@ export declare class SessionManager {
|
|
|
41
59
|
private readonly forwardManager;
|
|
42
60
|
private readonly operationManager;
|
|
43
61
|
private readonly persistPath;
|
|
62
|
+
private persistQueue;
|
|
44
63
|
private defaultKeepaliveInterval;
|
|
45
64
|
private defaultKeepaliveCountMax;
|
|
46
65
|
private defaultTimeout;
|
|
@@ -66,9 +85,14 @@ export declare class SessionManager {
|
|
|
66
85
|
* 获取会话
|
|
67
86
|
*/
|
|
68
87
|
getSession(alias: string): SSHSession;
|
|
88
|
+
getOpenSshConnection(alias: string): OpenSshConnection | undefined;
|
|
69
89
|
listSessions(): SSHSessionBrief[];
|
|
70
90
|
listSessionDetails(): SSHSessionDetail[];
|
|
71
91
|
getSessionConnectionInfo(alias: string): SessionConnectionInfo;
|
|
92
|
+
requirePosixPrivilege(alias: string): void;
|
|
93
|
+
getRemotePlatform(alias: string): 'posix' | 'windows';
|
|
94
|
+
getRemotePathStyle(alias: string): 'posix' | 'win32' | 'sftp-posix';
|
|
95
|
+
getCommandShell(alias: string): 'posix' | 'cmd' | 'powershell';
|
|
72
96
|
getExternalTransferCapability(alias: string): ExternalTransferCapability;
|
|
73
97
|
/**
|
|
74
98
|
* 执行命令
|
|
@@ -109,18 +133,7 @@ export declare class SessionManager {
|
|
|
109
133
|
ptyRead(ptyId: string, options?: {
|
|
110
134
|
mode?: 'screen' | 'raw';
|
|
111
135
|
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
|
-
};
|
|
136
|
+
}): PtyReadResult;
|
|
124
137
|
ptyResize(ptyId: string, rows: number, cols: number): boolean;
|
|
125
138
|
ptyClose(ptyId: string): PtyCloseResult;
|
|
126
139
|
ptyList(): PtySessionInfo[];
|
|
@@ -134,17 +147,20 @@ export declare class SessionManager {
|
|
|
134
147
|
}>;
|
|
135
148
|
forwardClose(forwardId: string, options?: ForwardCloseOptions): Promise<ForwardCloseResult>;
|
|
136
149
|
forwardList(): PortForwardInfo[];
|
|
150
|
+
private requireSsh2Session;
|
|
137
151
|
private isSshAgentAvailable;
|
|
138
152
|
private isOpenSshKeyPathUsable;
|
|
139
153
|
private sessionIdentity;
|
|
140
154
|
private configIdentity;
|
|
141
155
|
private connectionFingerprint;
|
|
142
156
|
private resultMetadata;
|
|
157
|
+
private appendWithinByteLimit;
|
|
143
158
|
private appendOutputTail;
|
|
144
159
|
private recommendedReadCommand;
|
|
145
160
|
private emptyOutputFailureMetadata;
|
|
146
161
|
private outputMetadata;
|
|
147
162
|
private normalizeMaxOutputSize;
|
|
163
|
+
private openCommandChannel;
|
|
148
164
|
private openOperationStream;
|
|
149
165
|
private cancelRemoteOperation;
|
|
150
166
|
private execDirect;
|