@pyrokine/mcp-ssh 3.1.0 → 3.2.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 +328 -104
- package/README_zh.md +173 -37
- package/dist/command-risk.js +5 -2
- package/dist/directory-verification.d.ts +10 -5
- package/dist/directory-verification.js +153 -66
- package/dist/file-mode.js +25 -13
- package/dist/file-ops.d.ts +13 -6
- package/dist/file-ops.js +477 -208
- package/dist/forward-manager.js +6 -1
- package/dist/known-hosts.d.ts +22 -0
- package/dist/known-hosts.js +553 -0
- package/dist/openssh.js +51 -26
- package/dist/operation-manager.js +13 -4
- package/dist/pty-manager.d.ts +2 -1
- package/dist/pty-manager.js +81 -19
- package/dist/remote-platform.d.ts +1 -1
- package/dist/remote-platform.js +82 -50
- package/dist/security.d.ts +2 -0
- package/dist/security.js +39 -3
- package/dist/session-manager.d.ts +22 -2
- package/dist/session-manager.js +231 -48
- package/dist/sftp-timeout.d.ts +16 -1
- package/dist/sftp-timeout.js +104 -12
- package/dist/ssh-config.js +1 -1
- package/dist/tools/connection.js +17 -3
- package/dist/tools/exec.js +83 -38
- package/dist/tools/file.js +250 -135
- package/dist/tools/operation.js +7 -5
- package/dist/tools/pty.js +16 -13
- package/dist/tools/utils.d.ts +1 -1
- package/dist/tools/utils.js +2 -2
- package/dist/types.d.ts +20 -3
- package/dist/types.js +1 -0
- package/dist/utf8.d.ts +1 -1
- package/dist/utf8.js +2 -2
- package/dist/windows-acl.d.ts +1 -0
- package/dist/windows-acl.js +167 -80
- package/package.json +5 -5
package/dist/openssh.js
CHANGED
|
@@ -58,14 +58,16 @@ async function captureSsh(args, timeout, maxBytes, signal, track) {
|
|
|
58
58
|
});
|
|
59
59
|
child.once('close', (status) => {
|
|
60
60
|
clearTimeout(timer);
|
|
61
|
-
if (failure)
|
|
61
|
+
if (failure) {
|
|
62
62
|
reject(failure);
|
|
63
|
-
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
64
65
|
resolve({
|
|
65
66
|
stdout: Buffer.concat(stdout).toString('utf8'),
|
|
66
67
|
stderr: Buffer.concat(stderr).toString('utf8'),
|
|
67
68
|
status,
|
|
68
69
|
});
|
|
70
|
+
}
|
|
69
71
|
});
|
|
70
72
|
});
|
|
71
73
|
}
|
|
@@ -88,18 +90,23 @@ export async function resolveOpenSshConfig(input) {
|
|
|
88
90
|
validateConfigFile(configPath);
|
|
89
91
|
args.push('-F', configPath);
|
|
90
92
|
}
|
|
91
|
-
if (input.configHost && input.host)
|
|
93
|
+
if (input.configHost && input.host) {
|
|
92
94
|
args.push('-o', `HostName=${input.host}`);
|
|
93
|
-
|
|
95
|
+
}
|
|
96
|
+
if (input.username) {
|
|
94
97
|
args.push('-l', input.username);
|
|
95
|
-
|
|
98
|
+
}
|
|
99
|
+
if (input.port !== undefined) {
|
|
96
100
|
args.push('-p', String(input.port));
|
|
97
|
-
|
|
101
|
+
}
|
|
102
|
+
if (input.controlPath) {
|
|
98
103
|
args.push('-S', path.resolve(expandTilde(input.controlPath)));
|
|
104
|
+
}
|
|
99
105
|
args.push('--', destination);
|
|
100
106
|
const result = await captureSsh(args, input.readyTimeout ?? 30_000, CONFIG_OUTPUT_LIMIT);
|
|
101
|
-
if (result.status !== 0)
|
|
107
|
+
if (result.status !== 0) {
|
|
102
108
|
invalidConfig(`OpenSSH configuration could not be resolved: ${result.stderr.trim()}`);
|
|
109
|
+
}
|
|
103
110
|
const config = new Map();
|
|
104
111
|
for (const line of result.stdout.split('\n')) {
|
|
105
112
|
const separator = line.indexOf(' ');
|
|
@@ -114,8 +121,9 @@ export async function resolveOpenSshConfig(input) {
|
|
|
114
121
|
if (!host || host.startsWith('-') || /[\s\0]/.test(host) || !username || /[\s:@\0]/.test(username)) {
|
|
115
122
|
invalidConfig('OpenSSH returned an invalid host or user');
|
|
116
123
|
}
|
|
117
|
-
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
124
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
118
125
|
invalidConfig('OpenSSH returned an invalid port');
|
|
126
|
+
}
|
|
119
127
|
if (!controlPath || controlPath === 'none' || /[\0\r\n]/.test(controlPath)) {
|
|
120
128
|
invalidConfig('OpenSSH requires an existing ControlPath; configure it or pass controlPath');
|
|
121
129
|
}
|
|
@@ -154,8 +162,9 @@ class OpenSshChannel extends PassThrough {
|
|
|
154
162
|
if (index < 0) {
|
|
155
163
|
let retained = Math.min(pending.length, prefix.length - 1);
|
|
156
164
|
while (retained > 0 &&
|
|
157
|
-
!pending.subarray(pending.length - retained).equals(prefix.subarray(0, retained)))
|
|
165
|
+
!pending.subarray(pending.length - retained).equals(prefix.subarray(0, retained))) {
|
|
158
166
|
--retained;
|
|
167
|
+
}
|
|
159
168
|
const count = pending.length - retained;
|
|
160
169
|
this.push(pending.subarray(0, count));
|
|
161
170
|
pending = pending.subarray(count);
|
|
@@ -166,8 +175,9 @@ class OpenSshChannel extends PassThrough {
|
|
|
166
175
|
pending = pending.subarray(index);
|
|
167
176
|
}
|
|
168
177
|
const end = pending.indexOf(0x1f, prefix.length);
|
|
169
|
-
if (end < 0 && pending.length <= prefix.length + 16)
|
|
178
|
+
if (end < 0 && pending.length <= prefix.length + 16) {
|
|
170
179
|
break;
|
|
180
|
+
}
|
|
171
181
|
if (end < 0 || end > prefix.length + 16) {
|
|
172
182
|
this.push(pending.subarray(0, 1));
|
|
173
183
|
pending = pending.subarray(1);
|
|
@@ -198,8 +208,9 @@ class OpenSshChannel extends PassThrough {
|
|
|
198
208
|
this.child.stderr.pipe(markers).pipe(this.stderr);
|
|
199
209
|
this.child.once('error', (error) => {
|
|
200
210
|
this.rejectReady(error);
|
|
201
|
-
if (!this.destroyed)
|
|
211
|
+
if (!this.destroyed) {
|
|
202
212
|
this.emit('error', error);
|
|
213
|
+
}
|
|
203
214
|
});
|
|
204
215
|
this.child.once('close', (code, signal) => {
|
|
205
216
|
if (remoteExitCode === undefined) {
|
|
@@ -212,8 +223,9 @@ class OpenSshChannel extends PassThrough {
|
|
|
212
223
|
signal,
|
|
213
224
|
});
|
|
214
225
|
this.rejectReady(error);
|
|
215
|
-
if (!this.destroyed)
|
|
226
|
+
if (!this.destroyed) {
|
|
216
227
|
this.emit('error', error);
|
|
228
|
+
}
|
|
217
229
|
}
|
|
218
230
|
this.end();
|
|
219
231
|
this.emit('close', remoteExitCode ?? null, signal);
|
|
@@ -252,13 +264,14 @@ export class OpenSshConnection {
|
|
|
252
264
|
retryable: false,
|
|
253
265
|
});
|
|
254
266
|
}
|
|
255
|
-
if (!config.controlPath)
|
|
267
|
+
if (!config.controlPath) {
|
|
256
268
|
invalidConfig('OpenSSH requires a resolved controlPath');
|
|
269
|
+
}
|
|
257
270
|
const socket = this.socket(config.controlPath);
|
|
258
271
|
const args = this.arguments(config);
|
|
259
272
|
const timeout = config.readyTimeout ?? 30_000;
|
|
260
273
|
const checked = await captureSsh([...args.slice(0, -1), '-O', 'check', config.host], timeout, CONTROL_OUTPUT_LIMIT, signal);
|
|
261
|
-
const pid = Number(/Master running \(pid=(
|
|
274
|
+
const pid = Number(/Master running \(pid=(?<pid>\d+)\)/.exec(checked.stderr)?.[1]);
|
|
262
275
|
if (checked.status !== 0 || !Number.isSafeInteger(pid) || pid <= 0) {
|
|
263
276
|
throw new OpenSshError(`OpenSSH master is unavailable: ${checked.stderr.trim()}`, {
|
|
264
277
|
code: 'master_unavailable',
|
|
@@ -270,8 +283,9 @@ export class OpenSshConnection {
|
|
|
270
283
|
const abort = () => connection.close();
|
|
271
284
|
signal?.addEventListener('abort', abort, { once: true });
|
|
272
285
|
try {
|
|
273
|
-
if (signal?.aborted)
|
|
286
|
+
if (signal?.aborted) {
|
|
274
287
|
throw signal.reason;
|
|
288
|
+
}
|
|
275
289
|
const marker = randomBytes(32).toString('hex');
|
|
276
290
|
const command = `printf ${escapeShellArg(`${marker}\\n`)}; id -u; id -un; printf '%s\\n' "$SSH_CONNECTION"`;
|
|
277
291
|
const observed = await captureSsh([...args, command], timeout, CONTROL_OUTPUT_LIMIT, signal, connection.trackProcess);
|
|
@@ -383,8 +397,9 @@ export class OpenSshConnection {
|
|
|
383
397
|
trackProcess = (child, processGroup = false) => {
|
|
384
398
|
this.processes.set(child, processGroup);
|
|
385
399
|
child.once('close', () => this.processes.delete(child));
|
|
386
|
-
if (this.closed)
|
|
400
|
+
if (this.closed) {
|
|
387
401
|
this.close();
|
|
402
|
+
}
|
|
388
403
|
};
|
|
389
404
|
open(command) {
|
|
390
405
|
return new OpenSshChannel(this.arguments(), command, this.trackProcess);
|
|
@@ -395,16 +410,18 @@ export class OpenSshConnection {
|
|
|
395
410
|
let settled = false;
|
|
396
411
|
let stderr = Buffer.alloc(0);
|
|
397
412
|
const finish = (error) => {
|
|
398
|
-
if (settled)
|
|
413
|
+
if (settled) {
|
|
399
414
|
return;
|
|
415
|
+
}
|
|
400
416
|
settled = true;
|
|
401
417
|
clearTimeout(timer);
|
|
402
418
|
if (error) {
|
|
403
419
|
stream.destroy();
|
|
404
420
|
reject(error);
|
|
405
421
|
}
|
|
406
|
-
else
|
|
422
|
+
else {
|
|
407
423
|
resolve();
|
|
424
|
+
}
|
|
408
425
|
};
|
|
409
426
|
const timer = setTimeout(() => finish(new OpenSshError(`OpenSSH command timed out after ${timeout}ms`, {
|
|
410
427
|
code: 'openssh_timeout',
|
|
@@ -414,8 +431,9 @@ export class OpenSshConnection {
|
|
|
414
431
|
retryable: false,
|
|
415
432
|
})), timeout);
|
|
416
433
|
stream.on('data', (chunk) => {
|
|
417
|
-
if (settled)
|
|
434
|
+
if (settled) {
|
|
418
435
|
return;
|
|
436
|
+
}
|
|
419
437
|
try {
|
|
420
438
|
consume(chunk);
|
|
421
439
|
}
|
|
@@ -443,13 +461,14 @@ export class OpenSshConnection {
|
|
|
443
461
|
let size = 0;
|
|
444
462
|
await this.consume(command, (chunk) => {
|
|
445
463
|
size += chunk.length;
|
|
446
|
-
if (size > maxBytes)
|
|
464
|
+
if (size > maxBytes) {
|
|
447
465
|
throw new OpenSshError('OpenSSH command exceeded its output budget', {
|
|
448
466
|
code: 'openssh_output_limit',
|
|
449
467
|
backend: 'openssh',
|
|
450
468
|
maxBytes,
|
|
451
469
|
retryable: false,
|
|
452
470
|
});
|
|
471
|
+
}
|
|
453
472
|
chunks.push(chunk);
|
|
454
473
|
}, timeout);
|
|
455
474
|
return Buffer.concat(chunks);
|
|
@@ -480,18 +499,20 @@ export class OpenSshConnection {
|
|
|
480
499
|
const deadline = Date.now() + timeout;
|
|
481
500
|
const remaining = () => {
|
|
482
501
|
const value = deadline - Date.now();
|
|
483
|
-
if (value <= 0)
|
|
502
|
+
if (value <= 0) {
|
|
484
503
|
throw new OpenSshError('OpenSSH file verification exhausted its timeout', {
|
|
485
504
|
code: 'openssh_timeout',
|
|
486
505
|
backend: 'openssh',
|
|
487
506
|
operationStatus: 'unknown',
|
|
488
507
|
retryable: false,
|
|
489
508
|
});
|
|
509
|
+
}
|
|
490
510
|
return value;
|
|
491
511
|
};
|
|
492
512
|
const before = await this.stat(remotePath, remaining());
|
|
493
|
-
if ((before.mode & 0o170000) !== 0o100000)
|
|
513
|
+
if ((before.mode & 0o170000) !== 0o100000) {
|
|
494
514
|
throw new Error('File hashing requires a regular remote file');
|
|
515
|
+
}
|
|
495
516
|
if ((maxBytes !== undefined && before.size > maxBytes) ||
|
|
496
517
|
(expectedSize !== undefined && before.size !== expectedSize)) {
|
|
497
518
|
throw new Error('Remote file size changed or exceeds the verification byte budget');
|
|
@@ -500,13 +521,15 @@ export class OpenSshConnection {
|
|
|
500
521
|
let size = 0;
|
|
501
522
|
await this.consume(`head -c ${before.size + 1} -- ${escapeShellArg(remotePath)}`, (chunk) => {
|
|
502
523
|
size += chunk.length;
|
|
503
|
-
if (size > before.size)
|
|
524
|
+
if (size > before.size) {
|
|
504
525
|
throw new Error('Remote file grew during verification');
|
|
526
|
+
}
|
|
505
527
|
hash.update(chunk);
|
|
506
528
|
}, remaining());
|
|
507
529
|
const after = await this.stat(remotePath, remaining());
|
|
508
|
-
if (size !== before.size || before.stamp !== after.stamp)
|
|
530
|
+
if (size !== before.size || before.stamp !== after.stamp) {
|
|
509
531
|
throw new Error('Remote file changed during verification');
|
|
532
|
+
}
|
|
510
533
|
return hash.digest('hex');
|
|
511
534
|
}
|
|
512
535
|
close() {
|
|
@@ -517,12 +540,14 @@ export class OpenSshConnection {
|
|
|
517
540
|
process.kill(-child.pid, 'SIGKILL');
|
|
518
541
|
}
|
|
519
542
|
catch (error) {
|
|
520
|
-
if (error.code !== 'ESRCH')
|
|
543
|
+
if (error.code !== 'ESRCH') {
|
|
521
544
|
console.error('OpenSSH process cleanup failed:', error);
|
|
545
|
+
}
|
|
522
546
|
}
|
|
523
547
|
}
|
|
524
|
-
else
|
|
548
|
+
else {
|
|
525
549
|
child.kill('SIGKILL');
|
|
550
|
+
}
|
|
526
551
|
}
|
|
527
552
|
}
|
|
528
553
|
}
|
|
@@ -164,7 +164,7 @@ export class OperationManager {
|
|
|
164
164
|
const nextStdoutOffset = record.stdoutTruncated && stdoutRequestedEnd === record.stdout.length ? stdoutRequestedEnd : stdoutEnd;
|
|
165
165
|
const remaining = maxReadBytes - stdout.length;
|
|
166
166
|
const stderrRequestedEnd = Math.min(record.stderr.length, stderrOffset + remaining);
|
|
167
|
-
const stderrEnd = utf8SafeEnd(record.stderr, stderrOffset, stderrRequestedEnd, 'stderr');
|
|
167
|
+
const stderrEnd = utf8SafeEnd(record.stderr, stderrOffset, stderrRequestedEnd, 'stderr', stderrRequestedEnd < record.stderr.length, nextStdoutOffset > stdoutOffset);
|
|
168
168
|
if (record.finishedAt !== null &&
|
|
169
169
|
!record.stderrTruncated &&
|
|
170
170
|
stderrRequestedEnd === record.stderr.length &&
|
|
@@ -284,7 +284,7 @@ export class OperationManager {
|
|
|
284
284
|
this.finishStreamError(record, error);
|
|
285
285
|
});
|
|
286
286
|
stream.on('close', (code, signal) => {
|
|
287
|
-
const close = { type: 'close', code, signal: signal
|
|
287
|
+
const close = { type: 'close', code: code ?? null, signal: signal || null };
|
|
288
288
|
if (record.cancelInFlight) {
|
|
289
289
|
record.pendingTermination ??= close;
|
|
290
290
|
return;
|
|
@@ -330,6 +330,11 @@ export class OperationManager {
|
|
|
330
330
|
if (record.cancelRequested) {
|
|
331
331
|
record.status = 'cancelled';
|
|
332
332
|
}
|
|
333
|
+
else if (code === null && signal === null) {
|
|
334
|
+
record.status = 'unknown';
|
|
335
|
+
record.error =
|
|
336
|
+
'SSH channel closed without an exit status or signal; inspect the remote operation before repeating it';
|
|
337
|
+
}
|
|
333
338
|
else if (!record.markerVerified) {
|
|
334
339
|
record.status = 'failed';
|
|
335
340
|
record.error ??= 'Remote operation exited before its marker was verified';
|
|
@@ -395,7 +400,9 @@ export class OperationManager {
|
|
|
395
400
|
this.failMarker(record, 'Remote operation marker did not match the local operation');
|
|
396
401
|
return;
|
|
397
402
|
}
|
|
398
|
-
const metadata = line
|
|
403
|
+
const metadata = line
|
|
404
|
+
.slice(expectedPrefix.length)
|
|
405
|
+
.match(/^(?<pid>[1-9]\d*):(?<processGroup>[01])(?::(?<createdAt>[1-9]\d*))?$/);
|
|
399
406
|
const pid = metadata ? Number(metadata[1]) : Number.NaN;
|
|
400
407
|
if (!metadata || !Number.isSafeInteger(pid)) {
|
|
401
408
|
this.appendStderr(record, lineBytes);
|
|
@@ -434,7 +441,9 @@ export class OperationManager {
|
|
|
434
441
|
const storedBytes = record.stdout.length + record.stderr.length;
|
|
435
442
|
const available = Math.max(0, record.maxOutputBytes - storedBytes);
|
|
436
443
|
const stored = data.subarray(0, available);
|
|
437
|
-
|
|
444
|
+
if (stored.length > 0) {
|
|
445
|
+
record[stream] = Buffer.concat([record[stream], stored]);
|
|
446
|
+
}
|
|
438
447
|
if (stored.length < data.length) {
|
|
439
448
|
if (stream === 'stdout') {
|
|
440
449
|
record.stdoutTruncated = true;
|
package/dist/pty-manager.d.ts
CHANGED
|
@@ -24,13 +24,14 @@ export declare class PtyManager {
|
|
|
24
24
|
read(ptyId: string, options?: {
|
|
25
25
|
mode?: 'screen' | 'raw';
|
|
26
26
|
clear?: boolean;
|
|
27
|
-
}): PtyReadResult
|
|
27
|
+
}): Promise<PtyReadResult>;
|
|
28
28
|
resize(ptyId: string, rows: number, cols: number): boolean;
|
|
29
29
|
close(ptyId: string): PtyCloseResult;
|
|
30
30
|
/** 关闭指定 alias 的所有 PTY 会话 */
|
|
31
31
|
closeByAlias(alias: string): void;
|
|
32
32
|
list(): PtySessionInfo[];
|
|
33
33
|
private appendOutput;
|
|
34
|
+
private disposeParser;
|
|
34
35
|
private appendRaw;
|
|
35
36
|
private endDecoder;
|
|
36
37
|
private normalizeBufferSize;
|
package/dist/pty-manager.js
CHANGED
|
@@ -44,35 +44,44 @@ export class PtyManager {
|
|
|
44
44
|
maxBufferSize,
|
|
45
45
|
decoder: new StringDecoder('utf8'),
|
|
46
46
|
decoderEnded: false,
|
|
47
|
+
pendingCharacters: 0,
|
|
48
|
+
parsing: Promise.resolve(),
|
|
49
|
+
parseWaiters: new Set(),
|
|
50
|
+
outputPaused: false,
|
|
51
|
+
disposed: false,
|
|
52
|
+
detach: () => undefined,
|
|
47
53
|
active: true,
|
|
48
54
|
closedAt: null,
|
|
49
55
|
};
|
|
50
|
-
|
|
51
|
-
stream.on('data', (data) => {
|
|
56
|
+
const onData = (data) => {
|
|
52
57
|
if (!ptySession.active || ptySession.decoderEnded) {
|
|
53
58
|
return;
|
|
54
59
|
}
|
|
55
60
|
ptySession.lastOutputAt = Date.now();
|
|
56
61
|
this.appendRaw(ptySession, data);
|
|
57
62
|
this.appendOutput(ptySession, ptySession.decoder.write(data));
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
if (!this.sessions.has(ptyId)) {
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
this.endDecoder(ptySession);
|
|
64
|
-
ptySession.active = false;
|
|
65
|
-
ptySession.closedAt = Date.now();
|
|
66
|
-
});
|
|
67
|
-
stream.on('error', (err) => {
|
|
63
|
+
};
|
|
64
|
+
const onClose = () => {
|
|
68
65
|
if (!this.sessions.has(ptyId)) {
|
|
69
66
|
return;
|
|
70
67
|
}
|
|
71
68
|
this.endDecoder(ptySession);
|
|
72
69
|
ptySession.active = false;
|
|
73
70
|
ptySession.closedAt = Date.now();
|
|
74
|
-
|
|
75
|
-
}
|
|
71
|
+
ptySession.detach();
|
|
72
|
+
};
|
|
73
|
+
const onError = (err) => {
|
|
74
|
+
this.appendOutput(ptySession, `\n[PTY Error: ${err.message}]`);
|
|
75
|
+
onClose();
|
|
76
|
+
};
|
|
77
|
+
ptySession.detach = () => {
|
|
78
|
+
stream.off('data', onData);
|
|
79
|
+
stream.off('close', onClose);
|
|
80
|
+
stream.off('error', onError);
|
|
81
|
+
};
|
|
82
|
+
stream.on('data', onData);
|
|
83
|
+
stream.on('close', onClose);
|
|
84
|
+
stream.on('error', onError);
|
|
76
85
|
this.sessions.set(ptyId, ptySession);
|
|
77
86
|
return ptyId;
|
|
78
87
|
}
|
|
@@ -87,9 +96,15 @@ export class PtyManager {
|
|
|
87
96
|
backpressured: !session.stream.write(data),
|
|
88
97
|
};
|
|
89
98
|
}
|
|
90
|
-
read(ptyId, options = {}) {
|
|
99
|
+
async read(ptyId, options = {}) {
|
|
91
100
|
const session = this.getSession(ptyId);
|
|
92
101
|
const mode = options.mode ?? 'screen';
|
|
102
|
+
if (mode === 'screen') {
|
|
103
|
+
await session.parsing;
|
|
104
|
+
if (session.disposed) {
|
|
105
|
+
throw new Error(`PTY session '${ptyId}' not found`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
93
108
|
const clear = options.clear !== false;
|
|
94
109
|
const unreadRawBytes = session.unreadRawBytes;
|
|
95
110
|
const rawBufferTruncated = session.rawBufferTruncated;
|
|
@@ -121,6 +136,7 @@ export class PtyManager {
|
|
|
121
136
|
rawBufferLimit: session.maxBufferSize,
|
|
122
137
|
rawBufferTruncated,
|
|
123
138
|
foregroundProcess: session.command,
|
|
139
|
+
...(session.parserError ? { parserError: session.parserError } : {}),
|
|
124
140
|
};
|
|
125
141
|
}
|
|
126
142
|
resize(ptyId, rows, cols) {
|
|
@@ -160,7 +176,7 @@ export class PtyManager {
|
|
|
160
176
|
}
|
|
161
177
|
this.endDecoder(session);
|
|
162
178
|
try {
|
|
163
|
-
|
|
179
|
+
this.disposeParser(session);
|
|
164
180
|
}
|
|
165
181
|
catch (error) {
|
|
166
182
|
return {
|
|
@@ -198,7 +214,7 @@ export class PtyManager {
|
|
|
198
214
|
}
|
|
199
215
|
this.endDecoder(session);
|
|
200
216
|
try {
|
|
201
|
-
|
|
217
|
+
this.disposeParser(session);
|
|
202
218
|
}
|
|
203
219
|
catch {
|
|
204
220
|
// SSH 连接已失效,继续释放本地状态
|
|
@@ -232,10 +248,56 @@ export class PtyManager {
|
|
|
232
248
|
return result;
|
|
233
249
|
}
|
|
234
250
|
appendOutput(session, output) {
|
|
235
|
-
if (output.length === 0) {
|
|
251
|
+
if (output.length === 0 || session.disposed || session.parserError) {
|
|
236
252
|
return;
|
|
237
253
|
}
|
|
238
|
-
session.
|
|
254
|
+
session.pendingCharacters += output.length;
|
|
255
|
+
if (!session.outputPaused && session.pendingCharacters >= 1024 * 1024) {
|
|
256
|
+
session.outputPaused = true;
|
|
257
|
+
session.stream.pause();
|
|
258
|
+
}
|
|
259
|
+
session.parsing = new Promise((resolve) => {
|
|
260
|
+
session.parseWaiters.add(resolve);
|
|
261
|
+
try {
|
|
262
|
+
session.terminal.write(output, () => {
|
|
263
|
+
session.parseWaiters.delete(resolve);
|
|
264
|
+
if (session.disposed) {
|
|
265
|
+
resolve();
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
session.pendingCharacters -= output.length;
|
|
269
|
+
if (session.outputPaused &&
|
|
270
|
+
session.pendingCharacters <= 256 * 1024 &&
|
|
271
|
+
session.active &&
|
|
272
|
+
!session.disposed) {
|
|
273
|
+
session.outputPaused = false;
|
|
274
|
+
session.stream.resume();
|
|
275
|
+
}
|
|
276
|
+
resolve();
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
session.parserError = error instanceof Error ? error.message : String(error);
|
|
281
|
+
session.active = false;
|
|
282
|
+
session.closedAt = Date.now();
|
|
283
|
+
session.detach();
|
|
284
|
+
session.stream.destroy();
|
|
285
|
+
for (const complete of session.parseWaiters) {
|
|
286
|
+
complete();
|
|
287
|
+
}
|
|
288
|
+
session.parseWaiters.clear();
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
disposeParser(session) {
|
|
293
|
+
session.detach();
|
|
294
|
+
session.disposed = true;
|
|
295
|
+
for (const complete of session.parseWaiters) {
|
|
296
|
+
complete();
|
|
297
|
+
}
|
|
298
|
+
session.parseWaiters.clear();
|
|
299
|
+
session.pendingCharacters = 0;
|
|
300
|
+
session.terminal.dispose();
|
|
239
301
|
}
|
|
240
302
|
appendRaw(session, data) {
|
|
241
303
|
const appended = Buffer.concat([session.rawBuffer, data]);
|
|
@@ -9,5 +9,5 @@ export declare function sftpPath(remotePath: string, style: RemotePathStyle): st
|
|
|
9
9
|
export declare function remoteShellPath(remotePath: string, style: RemotePathStyle): string;
|
|
10
10
|
export declare function quotePowershell(value: string): string;
|
|
11
11
|
export declare function encodedPowershell(script: string): string;
|
|
12
|
-
export declare function windowsCaseSemanticsScript(parent: string, names
|
|
12
|
+
export declare function windowsCaseSemanticsScript(parent: string, names?: string[]): string;
|
|
13
13
|
export declare function buildRemoteCommand(command: string, shell: CommandShell, cwd: string | undefined, env: Record<string, string>): string;
|
package/dist/remote-platform.js
CHANGED
|
@@ -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]):(?:\/(
|
|
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
|
|
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
|
|
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 =
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
[DllImport("kernel32.dll",
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
public static
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
}
|
|
93
|
-
'
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
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([Consol' +
|
|
121
|
+
'e]::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(
|
|
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)}`] : []),
|
package/dist/security.d.ts
CHANGED
|
@@ -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
|
*/
|