@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.
- package/README.md +395 -112
- package/README_zh.md +211 -45
- package/dist/command-risk.js +5 -2
- package/dist/directory-verification.d.ts +10 -5
- package/dist/directory-verification.js +161 -74
- package/dist/file-mode.js +25 -13
- package/dist/file-ops.d.ts +22 -11
- package/dist/file-ops.js +605 -230
- package/dist/forward-manager.js +6 -1
- package/dist/known-hosts.d.ts +22 -0
- package/dist/known-hosts.js +563 -0
- package/dist/openssh.d.ts +5 -5
- package/dist/openssh.js +138 -59
- 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 +29 -3
- package/dist/session-manager.js +367 -67
- package/dist/sftp-timeout.d.ts +16 -1
- package/dist/sftp-timeout.js +114 -12
- package/dist/ssh-config.js +1 -1
- package/dist/tools/connection.js +31 -13
- package/dist/tools/exec.js +147 -71
- package/dist/tools/file.js +333 -146
- 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/transfer-outcome.js +1 -1
- package/dist/types.d.ts +24 -4
- 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 +6 -6
package/dist/openssh.js
CHANGED
|
@@ -3,8 +3,8 @@ import { createHash, randomBytes } from 'crypto';
|
|
|
3
3
|
import * as fs from 'fs';
|
|
4
4
|
import * as path from 'path';
|
|
5
5
|
import { PassThrough, Transform } from 'stream';
|
|
6
|
-
import { escapeShellArg, expandTilde } from './tools/utils.js';
|
|
7
6
|
import { validateConfigFile } from './security.js';
|
|
7
|
+
import { escapeShellArg, expandTilde } from './tools/utils.js';
|
|
8
8
|
const CONFIG_OUTPUT_LIMIT = 512 * 1024;
|
|
9
9
|
const CONTROL_OUTPUT_LIMIT = 16 * 1024;
|
|
10
10
|
export class OpenSshError extends Error {
|
|
@@ -19,33 +19,86 @@ function invalidConfig(message) {
|
|
|
19
19
|
throw new OpenSshError(message, { code: 'invalid_openssh_config', backend: 'openssh', retryable: false });
|
|
20
20
|
}
|
|
21
21
|
async function captureSsh(args, timeout, maxBytes, signal, track) {
|
|
22
|
+
signal?.throwIfAborted();
|
|
22
23
|
return new Promise((resolve, reject) => {
|
|
23
|
-
const child = spawn('ssh', args, {
|
|
24
|
-
|
|
24
|
+
const child = spawn('ssh', args, {
|
|
25
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
26
|
+
windowsHide: true,
|
|
27
|
+
detached: true,
|
|
28
|
+
});
|
|
29
|
+
track?.(child, true);
|
|
25
30
|
const stdout = [];
|
|
26
31
|
const stderr = [];
|
|
27
32
|
let bytes = 0;
|
|
33
|
+
let settled = false;
|
|
28
34
|
let failure;
|
|
35
|
+
let stopTimer;
|
|
36
|
+
const finish = (error, status = null) => {
|
|
37
|
+
if (settled) {
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
settled = true;
|
|
41
|
+
clearTimeout(timer);
|
|
42
|
+
clearTimeout(stopTimer);
|
|
43
|
+
signal?.removeEventListener('abort', onAbort);
|
|
44
|
+
if (error) {
|
|
45
|
+
child.stdout.destroy();
|
|
46
|
+
child.stderr.destroy();
|
|
47
|
+
reject(error);
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
resolve({
|
|
51
|
+
stdout: Buffer.concat(stdout).toString('utf8'),
|
|
52
|
+
stderr: Buffer.concat(stderr).toString('utf8'),
|
|
53
|
+
status,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const stop = (error) => {
|
|
58
|
+
if (settled || failure) {
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
failure = error;
|
|
62
|
+
if (child.pid) {
|
|
63
|
+
try {
|
|
64
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
65
|
+
}
|
|
66
|
+
catch (cleanupError) {
|
|
67
|
+
if (cleanupError.code !== 'ESRCH') {
|
|
68
|
+
console.error('OpenSSH process cleanup failed:', cleanupError);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
child.stdout.destroy();
|
|
73
|
+
child.stderr.destroy();
|
|
74
|
+
stopTimer = setTimeout(() => finish(error), 100);
|
|
75
|
+
};
|
|
76
|
+
const onAbort = () => stop(signal?.reason instanceof Error ? signal.reason : new Error('OpenSSH request cancelled'));
|
|
29
77
|
const timer = setTimeout(() => {
|
|
30
|
-
|
|
78
|
+
stop(new OpenSshError(`OpenSSH request timed out after ${timeout}ms`, {
|
|
31
79
|
code: 'openssh_timeout',
|
|
32
80
|
backend: 'openssh',
|
|
33
81
|
timeout,
|
|
34
82
|
operationStatus: 'unknown',
|
|
35
83
|
retryable: false,
|
|
36
|
-
});
|
|
37
|
-
child.kill('SIGKILL');
|
|
84
|
+
}));
|
|
38
85
|
}, timeout);
|
|
86
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
87
|
+
if (signal?.aborted) {
|
|
88
|
+
onAbort();
|
|
89
|
+
}
|
|
39
90
|
const collect = (chunks) => (chunk) => {
|
|
91
|
+
if (settled) {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
40
94
|
bytes += chunk.length;
|
|
41
95
|
if (bytes > maxBytes) {
|
|
42
|
-
|
|
96
|
+
stop(new OpenSshError('OpenSSH response exceeded its output limit', {
|
|
43
97
|
code: 'openssh_output_limit',
|
|
44
98
|
backend: 'openssh',
|
|
45
99
|
maxBytes,
|
|
46
100
|
retryable: false,
|
|
47
|
-
});
|
|
48
|
-
child.kill('SIGKILL');
|
|
101
|
+
}));
|
|
49
102
|
}
|
|
50
103
|
else {
|
|
51
104
|
chunks.push(chunk);
|
|
@@ -53,23 +106,11 @@ async function captureSsh(args, timeout, maxBytes, signal, track) {
|
|
|
53
106
|
};
|
|
54
107
|
child.stdout.on('data', collect(stdout));
|
|
55
108
|
child.stderr.on('data', collect(stderr));
|
|
56
|
-
child.once('error', (error) =>
|
|
57
|
-
|
|
58
|
-
});
|
|
59
|
-
child.once('close', (status) => {
|
|
60
|
-
clearTimeout(timer);
|
|
61
|
-
if (failure)
|
|
62
|
-
reject(failure);
|
|
63
|
-
else
|
|
64
|
-
resolve({
|
|
65
|
-
stdout: Buffer.concat(stdout).toString('utf8'),
|
|
66
|
-
stderr: Buffer.concat(stderr).toString('utf8'),
|
|
67
|
-
status,
|
|
68
|
-
});
|
|
69
|
-
});
|
|
109
|
+
child.once('error', (error) => stop(error));
|
|
110
|
+
child.once('close', (status) => finish(failure, status));
|
|
70
111
|
});
|
|
71
112
|
}
|
|
72
|
-
export async function resolveOpenSshConfig(input) {
|
|
113
|
+
export async function resolveOpenSshConfig(input, signal) {
|
|
73
114
|
if (process.platform === 'win32') {
|
|
74
115
|
throw new OpenSshError('The OpenSSH master backend requires a local POSIX platform', {
|
|
75
116
|
code: 'unsupported_backend',
|
|
@@ -88,18 +129,23 @@ export async function resolveOpenSshConfig(input) {
|
|
|
88
129
|
validateConfigFile(configPath);
|
|
89
130
|
args.push('-F', configPath);
|
|
90
131
|
}
|
|
91
|
-
if (input.configHost && input.host)
|
|
132
|
+
if (input.configHost && input.host) {
|
|
92
133
|
args.push('-o', `HostName=${input.host}`);
|
|
93
|
-
|
|
134
|
+
}
|
|
135
|
+
if (input.username) {
|
|
94
136
|
args.push('-l', input.username);
|
|
95
|
-
|
|
137
|
+
}
|
|
138
|
+
if (input.port !== undefined) {
|
|
96
139
|
args.push('-p', String(input.port));
|
|
97
|
-
|
|
140
|
+
}
|
|
141
|
+
if (input.controlPath) {
|
|
98
142
|
args.push('-S', path.resolve(expandTilde(input.controlPath)));
|
|
143
|
+
}
|
|
99
144
|
args.push('--', destination);
|
|
100
|
-
const result = await captureSsh(args, input.readyTimeout ?? 30_000, CONFIG_OUTPUT_LIMIT);
|
|
101
|
-
if (result.status !== 0)
|
|
145
|
+
const result = await captureSsh(args, input.readyTimeout ?? 30_000, CONFIG_OUTPUT_LIMIT, signal);
|
|
146
|
+
if (result.status !== 0) {
|
|
102
147
|
invalidConfig(`OpenSSH configuration could not be resolved: ${result.stderr.trim()}`);
|
|
148
|
+
}
|
|
103
149
|
const config = new Map();
|
|
104
150
|
for (const line of result.stdout.split('\n')) {
|
|
105
151
|
const separator = line.indexOf(' ');
|
|
@@ -114,8 +160,9 @@ export async function resolveOpenSshConfig(input) {
|
|
|
114
160
|
if (!host || host.startsWith('-') || /[\s\0]/.test(host) || !username || /[\s:@\0]/.test(username)) {
|
|
115
161
|
invalidConfig('OpenSSH returned an invalid host or user');
|
|
116
162
|
}
|
|
117
|
-
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
163
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
118
164
|
invalidConfig('OpenSSH returned an invalid port');
|
|
165
|
+
}
|
|
119
166
|
if (!controlPath || controlPath === 'none' || /[\0\r\n]/.test(controlPath)) {
|
|
120
167
|
invalidConfig('OpenSSH requires an existing ControlPath; configure it or pass controlPath');
|
|
121
168
|
}
|
|
@@ -124,10 +171,11 @@ export async function resolveOpenSshConfig(input) {
|
|
|
124
171
|
class OpenSshChannel extends PassThrough {
|
|
125
172
|
stderr = new PassThrough();
|
|
126
173
|
ready;
|
|
174
|
+
stdin;
|
|
127
175
|
child;
|
|
128
176
|
resolveReady;
|
|
129
177
|
rejectReady;
|
|
130
|
-
constructor(args, command, track) {
|
|
178
|
+
constructor(args, command, track, withInput) {
|
|
131
179
|
super({ emitClose: false });
|
|
132
180
|
this.ready = new Promise((resolve, reject) => {
|
|
133
181
|
this.resolveReady = resolve;
|
|
@@ -138,9 +186,13 @@ class OpenSshChannel extends PassThrough {
|
|
|
138
186
|
const token = randomBytes(32).toString('hex');
|
|
139
187
|
const prefix = Buffer.from(`\x1eMCPSSH:${token}:`);
|
|
140
188
|
const script = `printf ${escapeShellArg(`\x1eMCPSSH:${token}:START\x1f`)} >&2; ` +
|
|
141
|
-
`
|
|
189
|
+
`( eval ${escapeShellArg(command)} ); status=$?; ` +
|
|
142
190
|
`printf ${escapeShellArg(`\x1eMCPSSH:${token}:END:%s\x1f`)} "$status" >&2; exit "$status"`;
|
|
143
|
-
this.child = spawn('ssh', [...args, script], {
|
|
191
|
+
this.child = spawn('ssh', [...args, script], {
|
|
192
|
+
stdio: [withInput ? 'pipe' : 'ignore', 'pipe', 'pipe'],
|
|
193
|
+
windowsHide: true,
|
|
194
|
+
});
|
|
195
|
+
this.stdin = this.child.stdin ?? undefined;
|
|
144
196
|
track(this.child);
|
|
145
197
|
let pending = Buffer.alloc(0);
|
|
146
198
|
let remoteExitCode;
|
|
@@ -154,8 +206,9 @@ class OpenSshChannel extends PassThrough {
|
|
|
154
206
|
if (index < 0) {
|
|
155
207
|
let retained = Math.min(pending.length, prefix.length - 1);
|
|
156
208
|
while (retained > 0 &&
|
|
157
|
-
!pending.subarray(pending.length - retained).equals(prefix.subarray(0, retained)))
|
|
209
|
+
!pending.subarray(pending.length - retained).equals(prefix.subarray(0, retained))) {
|
|
158
210
|
--retained;
|
|
211
|
+
}
|
|
159
212
|
const count = pending.length - retained;
|
|
160
213
|
this.push(pending.subarray(0, count));
|
|
161
214
|
pending = pending.subarray(count);
|
|
@@ -166,8 +219,9 @@ class OpenSshChannel extends PassThrough {
|
|
|
166
219
|
pending = pending.subarray(index);
|
|
167
220
|
}
|
|
168
221
|
const end = pending.indexOf(0x1f, prefix.length);
|
|
169
|
-
if (end < 0 && pending.length <= prefix.length + 16)
|
|
222
|
+
if (end < 0 && pending.length <= prefix.length + 16) {
|
|
170
223
|
break;
|
|
224
|
+
}
|
|
171
225
|
if (end < 0 || end > prefix.length + 16) {
|
|
172
226
|
this.push(pending.subarray(0, 1));
|
|
173
227
|
pending = pending.subarray(1);
|
|
@@ -198,8 +252,9 @@ class OpenSshChannel extends PassThrough {
|
|
|
198
252
|
this.child.stderr.pipe(markers).pipe(this.stderr);
|
|
199
253
|
this.child.once('error', (error) => {
|
|
200
254
|
this.rejectReady(error);
|
|
201
|
-
if (!this.destroyed)
|
|
255
|
+
if (!this.destroyed) {
|
|
202
256
|
this.emit('error', error);
|
|
257
|
+
}
|
|
203
258
|
});
|
|
204
259
|
this.child.once('close', (code, signal) => {
|
|
205
260
|
if (remoteExitCode === undefined) {
|
|
@@ -212,8 +267,9 @@ class OpenSshChannel extends PassThrough {
|
|
|
212
267
|
signal,
|
|
213
268
|
});
|
|
214
269
|
this.rejectReady(error);
|
|
215
|
-
if (!this.destroyed)
|
|
270
|
+
if (!this.destroyed) {
|
|
216
271
|
this.emit('error', error);
|
|
272
|
+
}
|
|
217
273
|
}
|
|
218
274
|
this.end();
|
|
219
275
|
this.emit('close', remoteExitCode ?? null, signal);
|
|
@@ -252,13 +308,14 @@ export class OpenSshConnection {
|
|
|
252
308
|
retryable: false,
|
|
253
309
|
});
|
|
254
310
|
}
|
|
255
|
-
if (!config.controlPath)
|
|
311
|
+
if (!config.controlPath) {
|
|
256
312
|
invalidConfig('OpenSSH requires a resolved controlPath');
|
|
313
|
+
}
|
|
257
314
|
const socket = this.socket(config.controlPath);
|
|
258
315
|
const args = this.arguments(config);
|
|
259
316
|
const timeout = config.readyTimeout ?? 30_000;
|
|
260
317
|
const checked = await captureSsh([...args.slice(0, -1), '-O', 'check', config.host], timeout, CONTROL_OUTPUT_LIMIT, signal);
|
|
261
|
-
const pid = Number(/Master running \(pid=(
|
|
318
|
+
const pid = Number(/Master running \(pid=(?<pid>\d+)\)/.exec(checked.stderr)?.groups?.pid);
|
|
262
319
|
if (checked.status !== 0 || !Number.isSafeInteger(pid) || pid <= 0) {
|
|
263
320
|
throw new OpenSshError(`OpenSSH master is unavailable: ${checked.stderr.trim()}`, {
|
|
264
321
|
code: 'master_unavailable',
|
|
@@ -270,14 +327,17 @@ export class OpenSshConnection {
|
|
|
270
327
|
const abort = () => connection.close();
|
|
271
328
|
signal?.addEventListener('abort', abort, { once: true });
|
|
272
329
|
try {
|
|
273
|
-
if (signal?.aborted)
|
|
330
|
+
if (signal?.aborted) {
|
|
331
|
+
// noinspection ExceptionCaughtLocallyJS -- 准备失败时仅清理本次绑定的 alias channel
|
|
274
332
|
throw signal.reason;
|
|
333
|
+
}
|
|
275
334
|
const marker = randomBytes(32).toString('hex');
|
|
276
335
|
const command = `printf ${escapeShellArg(`${marker}\\n`)}; id -u; id -un; printf '%s\\n' "$SSH_CONNECTION"`;
|
|
277
336
|
const observed = await captureSsh([...args, command], timeout, CONTROL_OUTPUT_LIMIT, signal, connection.trackProcess);
|
|
278
337
|
const start = observed.stdout.lastIndexOf(`${marker}\n`);
|
|
279
338
|
const lines = observed.stdout.slice(start + marker.length + 1).split('\n');
|
|
280
339
|
if (observed.status !== 0 || start < 0 || !/^\d+$/.test(lines[0]) || !lines[1]) {
|
|
340
|
+
// noinspection ExceptionCaughtLocallyJS -- 准备失败时仅清理本次绑定的 alias channel
|
|
281
341
|
throw new OpenSshError('The existing OpenSSH master did not provide its login identity', {
|
|
282
342
|
code: 'master_identity_unavailable',
|
|
283
343
|
backend: 'openssh',
|
|
@@ -285,6 +345,7 @@ export class OpenSshConnection {
|
|
|
285
345
|
});
|
|
286
346
|
}
|
|
287
347
|
if (lines[1] !== config.username) {
|
|
348
|
+
// noinspection ExceptionCaughtLocallyJS -- 准备失败时仅清理本次绑定的 alias channel
|
|
288
349
|
throw new OpenSshError('The existing master login does not match the requested user', {
|
|
289
350
|
code: 'master_identity_mismatch',
|
|
290
351
|
backend: 'openssh',
|
|
@@ -383,29 +444,35 @@ export class OpenSshConnection {
|
|
|
383
444
|
trackProcess = (child, processGroup = false) => {
|
|
384
445
|
this.processes.set(child, processGroup);
|
|
385
446
|
child.once('close', () => this.processes.delete(child));
|
|
386
|
-
if (this.closed)
|
|
447
|
+
if (this.closed) {
|
|
387
448
|
this.close();
|
|
449
|
+
}
|
|
388
450
|
};
|
|
389
|
-
open(command) {
|
|
390
|
-
return new OpenSshChannel(this.arguments(), command, this.trackProcess);
|
|
451
|
+
open(command, withInput = false) {
|
|
452
|
+
return new OpenSshChannel(this.arguments(), command, this.trackProcess, withInput);
|
|
391
453
|
}
|
|
392
|
-
consume(command, consume, timeout) {
|
|
454
|
+
consume(command, consume, timeout, signal) {
|
|
455
|
+
signal?.throwIfAborted();
|
|
393
456
|
const stream = this.open(command);
|
|
394
457
|
return new Promise((resolve, reject) => {
|
|
395
458
|
let settled = false;
|
|
396
459
|
let stderr = Buffer.alloc(0);
|
|
397
460
|
const finish = (error) => {
|
|
398
|
-
if (settled)
|
|
461
|
+
if (settled) {
|
|
399
462
|
return;
|
|
463
|
+
}
|
|
400
464
|
settled = true;
|
|
401
465
|
clearTimeout(timer);
|
|
466
|
+
signal?.removeEventListener('abort', onAbort);
|
|
402
467
|
if (error) {
|
|
403
468
|
stream.destroy();
|
|
404
469
|
reject(error);
|
|
405
470
|
}
|
|
406
|
-
else
|
|
471
|
+
else {
|
|
407
472
|
resolve();
|
|
473
|
+
}
|
|
408
474
|
};
|
|
475
|
+
const onAbort = () => finish(signal?.reason instanceof Error ? signal.reason : new Error('OpenSSH request cancelled'));
|
|
409
476
|
const timer = setTimeout(() => finish(new OpenSshError(`OpenSSH command timed out after ${timeout}ms`, {
|
|
410
477
|
code: 'openssh_timeout',
|
|
411
478
|
backend: 'openssh',
|
|
@@ -413,9 +480,14 @@ export class OpenSshConnection {
|
|
|
413
480
|
timeout,
|
|
414
481
|
retryable: false,
|
|
415
482
|
})), timeout);
|
|
483
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
484
|
+
if (signal?.aborted) {
|
|
485
|
+
onAbort();
|
|
486
|
+
}
|
|
416
487
|
stream.on('data', (chunk) => {
|
|
417
|
-
if (settled)
|
|
488
|
+
if (settled) {
|
|
418
489
|
return;
|
|
490
|
+
}
|
|
419
491
|
try {
|
|
420
492
|
consume(chunk);
|
|
421
493
|
}
|
|
@@ -438,25 +510,26 @@ export class OpenSshConnection {
|
|
|
438
510
|
})));
|
|
439
511
|
});
|
|
440
512
|
}
|
|
441
|
-
async capture(command, timeout, maxBytes) {
|
|
513
|
+
async capture(command, timeout, maxBytes, signal) {
|
|
442
514
|
const chunks = [];
|
|
443
515
|
let size = 0;
|
|
444
516
|
await this.consume(command, (chunk) => {
|
|
445
517
|
size += chunk.length;
|
|
446
|
-
if (size > maxBytes)
|
|
518
|
+
if (size > maxBytes) {
|
|
447
519
|
throw new OpenSshError('OpenSSH command exceeded its output budget', {
|
|
448
520
|
code: 'openssh_output_limit',
|
|
449
521
|
backend: 'openssh',
|
|
450
522
|
maxBytes,
|
|
451
523
|
retryable: false,
|
|
452
524
|
});
|
|
525
|
+
}
|
|
453
526
|
chunks.push(chunk);
|
|
454
|
-
}, timeout);
|
|
527
|
+
}, timeout, signal);
|
|
455
528
|
return Buffer.concat(chunks);
|
|
456
529
|
}
|
|
457
|
-
async stat(remotePath, timeout, follow = true) {
|
|
530
|
+
async stat(remotePath, timeout, follow = true, signal) {
|
|
458
531
|
const format = '%f\\0%s\\0%u\\0%g\\0%Y\\0%X\\0%d:%i:%s:%y:%z\\0';
|
|
459
|
-
const bytes = await this.capture(`LC_ALL=C stat ${follow ? '-L ' : ''}--printf=${escapeShellArg(format)} -- ${escapeShellArg(remotePath)}`, timeout, 4096);
|
|
532
|
+
const bytes = await this.capture(`LC_ALL=C stat ${follow ? '-L ' : ''}--printf=${escapeShellArg(format)} -- ${escapeShellArg(remotePath)}`, timeout, 4096, signal);
|
|
460
533
|
const fields = bytes.toString('utf8').split('\0');
|
|
461
534
|
const values = [Number.parseInt(fields[0], 16), ...fields.slice(1, 6).map(Number)];
|
|
462
535
|
if (fields.length !== 8 || !values.every(Number.isSafeInteger) || values[1] < 0) {
|
|
@@ -480,18 +553,20 @@ export class OpenSshConnection {
|
|
|
480
553
|
const deadline = Date.now() + timeout;
|
|
481
554
|
const remaining = () => {
|
|
482
555
|
const value = deadline - Date.now();
|
|
483
|
-
if (value <= 0)
|
|
556
|
+
if (value <= 0) {
|
|
484
557
|
throw new OpenSshError('OpenSSH file verification exhausted its timeout', {
|
|
485
558
|
code: 'openssh_timeout',
|
|
486
559
|
backend: 'openssh',
|
|
487
560
|
operationStatus: 'unknown',
|
|
488
561
|
retryable: false,
|
|
489
562
|
});
|
|
563
|
+
}
|
|
490
564
|
return value;
|
|
491
565
|
};
|
|
492
566
|
const before = await this.stat(remotePath, remaining());
|
|
493
|
-
if ((before.mode & 0o170000) !== 0o100000)
|
|
567
|
+
if ((before.mode & 0o170000) !== 0o100000) {
|
|
494
568
|
throw new Error('File hashing requires a regular remote file');
|
|
569
|
+
}
|
|
495
570
|
if ((maxBytes !== undefined && before.size > maxBytes) ||
|
|
496
571
|
(expectedSize !== undefined && before.size !== expectedSize)) {
|
|
497
572
|
throw new Error('Remote file size changed or exceeds the verification byte budget');
|
|
@@ -500,13 +575,15 @@ export class OpenSshConnection {
|
|
|
500
575
|
let size = 0;
|
|
501
576
|
await this.consume(`head -c ${before.size + 1} -- ${escapeShellArg(remotePath)}`, (chunk) => {
|
|
502
577
|
size += chunk.length;
|
|
503
|
-
if (size > before.size)
|
|
578
|
+
if (size > before.size) {
|
|
504
579
|
throw new Error('Remote file grew during verification');
|
|
580
|
+
}
|
|
505
581
|
hash.update(chunk);
|
|
506
582
|
}, remaining());
|
|
507
583
|
const after = await this.stat(remotePath, remaining());
|
|
508
|
-
if (size !== before.size || before.stamp !== after.stamp)
|
|
584
|
+
if (size !== before.size || before.stamp !== after.stamp) {
|
|
509
585
|
throw new Error('Remote file changed during verification');
|
|
586
|
+
}
|
|
510
587
|
return hash.digest('hex');
|
|
511
588
|
}
|
|
512
589
|
close() {
|
|
@@ -517,12 +594,14 @@ export class OpenSshConnection {
|
|
|
517
594
|
process.kill(-child.pid, 'SIGKILL');
|
|
518
595
|
}
|
|
519
596
|
catch (error) {
|
|
520
|
-
if (error.code !== 'ESRCH')
|
|
597
|
+
if (error.code !== 'ESRCH') {
|
|
521
598
|
console.error('OpenSSH process cleanup failed:', error);
|
|
599
|
+
}
|
|
522
600
|
}
|
|
523
601
|
}
|
|
524
|
-
else
|
|
602
|
+
else {
|
|
525
603
|
child.kill('SIGKILL');
|
|
604
|
+
}
|
|
526
605
|
}
|
|
527
606
|
}
|
|
528
607
|
}
|
|
@@ -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;
|