@pyrokine/mcp-ssh 3.2.0 → 3.3.1

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.
@@ -6,7 +6,8 @@ import * as path from 'node:path';
6
6
  import { setTimeout as delay } from 'node:timers/promises';
7
7
  import ssh2 from 'ssh2';
8
8
  import { validateKnownHostsPath } from './security.js';
9
- import { checkWindowsAcl, checkWindowsKnownHostsIntegrity } from './windows-acl.js';
9
+ import { DEFAULT_EXEC_TIMEOUT_MS } from './types.js';
10
+ import { checkWindowsAcl, checkWindowsKnownHostsIntegrity, getWindowsPowerShellEnv } from './windows-acl.js';
10
11
  export class HostKeyError extends Error {
11
12
  hostKey;
12
13
  constructor(message, options) {
@@ -15,24 +16,36 @@ export class HostKeyError extends Error {
15
16
  this.hostKey = options?.hostKey;
16
17
  }
17
18
  }
18
- function assertIntegrity(filePath) {
19
- if (process.platform === 'win32') {
20
- checkWindowsKnownHostsIntegrity(filePath);
21
- return;
19
+ function assertVerificationActive(signal, deadline) {
20
+ signal?.throwIfAborted();
21
+ if (deadline !== undefined && Date.now() >= deadline) {
22
+ throw new HostKeyError('known_hosts verification deadline exhausted');
22
23
  }
23
- let current = filePath;
24
- for (;;) {
25
- const stats = fs.statSync(current);
26
- const trustedOwner = stats.uid === 0 || stats.uid === process.getuid?.();
27
- const stickyDirectory = stats.isDirectory() && (stats.mode & 0o1000) !== 0;
28
- if (!trustedOwner || ((stats.mode & 0o022) !== 0 && !stickyDirectory)) {
29
- throw new HostKeyError(`known_hosts has an untrusted owner or writer: ${current}`);
30
- }
31
- const parent = path.dirname(current);
32
- if (parent === current) {
24
+ }
25
+ function assertIntegrity(filePath, signal, deadline) {
26
+ assertVerificationActive(signal, deadline);
27
+ try {
28
+ if (process.platform === 'win32') {
29
+ checkWindowsKnownHostsIntegrity(filePath, deadline);
33
30
  return;
34
31
  }
35
- current = parent;
32
+ let current = filePath;
33
+ for (;;) {
34
+ const stats = fs.statSync(current);
35
+ const trustedOwner = stats.uid === 0 || stats.uid === process.getuid?.();
36
+ const stickyDirectory = stats.isDirectory() && (stats.mode & 0o1000) !== 0;
37
+ if (!trustedOwner || ((stats.mode & 0o022) !== 0 && !stickyDirectory)) {
38
+ throw new HostKeyError(`known_hosts has an untrusted owner or writer: ${current}`);
39
+ }
40
+ const parent = path.dirname(current);
41
+ if (parent === current) {
42
+ return;
43
+ }
44
+ current = parent;
45
+ }
46
+ }
47
+ finally {
48
+ assertVerificationActive(signal, deadline);
36
49
  }
37
50
  }
38
51
  function localProcessDomain(deadline) {
@@ -91,6 +104,7 @@ function localProcessDomain(deadline) {
91
104
  ]
92
105
  : ['-n', 'kern.bootsessionuuid'], {
93
106
  timeout: Math.max(1, Math.min(5000, deadline - Date.now())),
107
+ ...(windows ? { env: getWindowsPowerShellEnv() } : {}),
94
108
  encoding: 'utf8',
95
109
  windowsHide: true,
96
110
  maxBuffer: 16_384,
@@ -143,8 +157,9 @@ async function removeLockOwner(directory, owner) {
143
157
  // A new owner's unique filename keeps this non-recursive removal from deleting its lock.
144
158
  await removeEmptyLock(directory);
145
159
  }
146
- async function inspectLock(directory, domain, preparation = false) {
160
+ async function inspectLock(directory, domain, preparation = false, signal, deadline) {
147
161
  try {
162
+ assertVerificationActive(signal, deadline);
148
163
  const stats = await fs.promises.lstat(directory);
149
164
  if (stats.isFile()) {
150
165
  return 'legacy lock file has no verifiable owner; it was retained';
@@ -152,8 +167,9 @@ async function inspectLock(directory, domain, preparation = false) {
152
167
  if (!stats.isDirectory()) {
153
168
  return 'lock owner identity could not be verified; it was retained';
154
169
  }
155
- assertIntegrity(directory);
170
+ assertIntegrity(directory, signal, deadline);
156
171
  const entries = await fs.promises.readdir(directory);
172
+ assertVerificationActive(signal, deadline);
157
173
  if (entries.length === 0 && !preparation) {
158
174
  await removeEmptyLock(directory);
159
175
  return;
@@ -164,18 +180,21 @@ async function inspectLock(directory, domain, preparation = false) {
164
180
  }
165
181
  const ownerPath = path.join(directory, entries[0]);
166
182
  const ownerStats = await fs.promises.lstat(ownerPath);
183
+ assertVerificationActive(signal, deadline);
167
184
  if (!ownerStats.isFile() || ownerStats.size > 4096) {
168
185
  return 'lock owner identity could not be verified; it was retained';
169
186
  }
170
- assertIntegrity(ownerPath);
187
+ assertIntegrity(ownerPath, signal, deadline);
171
188
  let owner;
172
189
  try {
173
190
  owner = JSON.parse(await fs.promises.readFile(ownerPath, 'utf8'));
191
+ assertVerificationActive(signal, deadline);
174
192
  }
175
193
  catch (error) {
176
194
  if (error instanceof SyntaxError) {
177
195
  return 'lock owner identity could not be verified; it was retained';
178
196
  }
197
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
179
198
  throw error;
180
199
  }
181
200
  if (!domain ||
@@ -192,10 +211,12 @@ async function inspectLock(directory, domain, preparation = false) {
192
211
  }
193
212
  catch (error) {
194
213
  if (error.code === 'ESRCH') {
214
+ assertVerificationActive(signal, deadline);
195
215
  await removeLockOwner(directory, entries[0]);
196
216
  return;
197
217
  }
198
218
  if (error.code !== 'EPERM') {
219
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
199
220
  throw error;
200
221
  }
201
222
  return 'lock owner liveness could not be verified (EPERM); it was retained';
@@ -203,6 +224,7 @@ async function inspectLock(directory, domain, preparation = false) {
203
224
  return 'lock is held by a live process';
204
225
  }
205
226
  catch (error) {
227
+ assertVerificationActive(signal, deadline);
206
228
  if (error.code === 'ENOENT') {
207
229
  return;
208
230
  }
@@ -268,9 +290,9 @@ export class KnownHosts {
268
290
  this.userFile = userFile;
269
291
  this.systemFiles = systemFiles;
270
292
  }
271
- getHostKeyAlgorithms(host, port) {
293
+ getHostKeyAlgorithms(host, port, signal, deadline) {
272
294
  const types = new Set();
273
- for (const { type, revoked } of this.matchingKeys(knownHostName(host, port))) {
295
+ for (const { type, revoked } of this.matchingKeys(knownHostName(host, port), signal, deadline)) {
274
296
  if (!revoked) {
275
297
  types.add(type);
276
298
  }
@@ -286,30 +308,28 @@ export class KnownHosts {
286
308
  ];
287
309
  return algorithms.filter((algorithm) => types.has(algorithm.startsWith('rsa-sha2-') ? 'ssh-rsa' : algorithm));
288
310
  }
289
- async verify(host, port, rawKey, signal, deadline = Date.now() + 5000) {
311
+ async verify(host, port, rawKey, signal, deadline = Date.now() + DEFAULT_EXEC_TIMEOUT_MS) {
290
312
  const name = knownHostName(host, port);
291
313
  const parsed = ssh2.utils.parseKey(rawKey);
292
314
  if (parsed instanceof Error || Array.isArray(parsed) || parsed.type.includes('-cert-')) {
293
315
  throw new HostKeyError('Unsupported or damaged server host key');
294
316
  }
295
317
  const fingerprint = `SHA256:${createHash('sha256').update(rawKey).digest('base64').replace(/=+$/, '')}`;
296
- const check = () => {
297
- signal?.throwIfAborted();
298
- if (Date.now() >= deadline) {
299
- throw new HostKeyError('known_hosts verification deadline exhausted');
300
- }
301
- };
318
+ const check = () => assertVerificationActive(signal, deadline);
319
+ check();
320
+ const known = this.lookup(name, rawKey, signal, deadline);
302
321
  check();
303
- if (this.lookup(name, rawKey)) {
322
+ if (known) {
304
323
  return { status: 'known', fingerprint };
305
324
  }
306
325
  const real = validateKnownHostsPath(this.userFile);
307
326
  const parent = path.dirname(real);
327
+ check();
308
328
  fs.mkdirSync(parent, { recursive: true, mode: 0o700 });
309
- assertIntegrity(parent);
329
+ assertIntegrity(parent, signal, deadline);
310
330
  const lockPath = `${real}.mcp-lock`;
311
- const lockDeadline = Math.min(deadline, Date.now() + 5000);
312
- const domain = localProcessDomain(lockDeadline);
331
+ const domain = localProcessDomain(deadline);
332
+ check();
313
333
  const identity = `${process.pid}-${randomBytes(16).toString('hex')}`;
314
334
  const preparation = `${lockPath}.prepare-${identity}`;
315
335
  const owner = `owner-${identity}.json`;
@@ -324,30 +344,48 @@ export class KnownHosts {
324
344
  for (const entry of await fs.promises.readdir(parent)) {
325
345
  if (entry.startsWith(prefix) && /^\d+-[\da-f]{32}$/.test(entry.slice(prefix.length))) {
326
346
  check();
327
- await inspectLock(path.join(parent, entry), domain, true);
347
+ await inspectLock(path.join(parent, entry), domain, true, signal, deadline);
328
348
  }
329
349
  }
330
350
  check();
331
351
  await fs.promises.mkdir(preparation, { mode: 0o700 });
332
352
  prepared = true;
333
- if (process.platform === 'win32' && checkWindowsAcl(preparation, true) !== 'key_path_usable') {
334
- throw new HostKeyError('known_hosts lock preparation permissions could not be verified');
353
+ check();
354
+ if (process.platform === 'win32') {
355
+ const acl = checkWindowsAcl(preparation, true, deadline);
356
+ check();
357
+ if (acl !== 'key_path_usable') {
358
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
359
+ throw new HostKeyError('known_hosts lock preparation permissions could not be verified');
360
+ }
335
361
  }
336
362
  await fs.promises.writeFile(path.join(preparation, owner), JSON.stringify({ version: 1, pid: process.pid, domain }), {
337
363
  flag: 'wx',
338
364
  mode: 0o600,
339
365
  });
340
- assertIntegrity(path.join(preparation, owner));
366
+ assertIntegrity(path.join(preparation, owner), signal, deadline);
367
+ check();
368
+ const lockDeadline = Math.min(deadline, Date.now() + 5000);
341
369
  let waitingReason = 'another writer';
342
- while (!owned) {
370
+ const checkLockBudget = () => {
343
371
  signal?.throwIfAborted();
344
372
  if (Date.now() >= lockDeadline) {
345
373
  throw new HostKeyError(`known_hosts is locked: ${waitingReason}`);
346
374
  }
347
- let waiting = await inspectLock(lockPath, domain);
375
+ };
376
+ while (!owned) {
377
+ checkLockBudget();
378
+ let waiting;
379
+ try {
380
+ waiting = await inspectLock(lockPath, domain, false, signal, lockDeadline);
381
+ }
382
+ catch (error) {
383
+ checkLockBudget();
384
+ throw error;
385
+ }
348
386
  waitingReason = waiting ?? waitingReason;
387
+ checkLockBudget();
349
388
  if (!waiting) {
350
- check();
351
389
  try {
352
390
  // Await publication even if canceled, so ownership is recorded before cleanup.
353
391
  await fs.promises.rename(preparation, lockPath);
@@ -357,6 +395,7 @@ export class KnownHosts {
357
395
  catch (error) {
358
396
  const code = error.code;
359
397
  if (!['EEXIST', 'ENOTEMPTY', 'EPERM', 'EACCES'].includes(code ?? '')) {
398
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
360
399
  throw error;
361
400
  }
362
401
  const target = await fs.promises.lstat(lockPath).catch((cause) => {
@@ -364,35 +403,38 @@ export class KnownHosts {
364
403
  throw cause;
365
404
  }
366
405
  });
406
+ checkLockBudget();
367
407
  if (target?.isDirectory()) {
368
408
  await removeEmptyLock(lockPath);
369
409
  }
370
410
  else if ((code === 'EPERM' || code === 'EACCES') && !target?.isFile()) {
411
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
371
412
  throw error;
372
413
  }
373
414
  waiting = 'another writer published its lock';
374
415
  }
375
416
  }
376
417
  if (!owned) {
377
- if (Date.now() >= lockDeadline) {
378
- throw new HostKeyError(`known_hosts is locked: ${waiting}`);
379
- }
418
+ checkLockBudget();
380
419
  await delay(Math.min(25, lockDeadline - Date.now()), undefined, { signal });
381
420
  }
382
421
  }
383
422
  check();
384
- if (this.lookup(name, rawKey)) {
423
+ if (this.lookup(name, rawKey, signal, deadline)) {
385
424
  result = { status: 'known', fingerprint };
386
425
  }
387
426
  else {
388
- const original = this.read(this.userFile, false);
427
+ const original = this.read(this.userFile, false, signal, deadline);
389
428
  const existed = fs.existsSync(real);
390
429
  const before = existed ? fs.statSync(real) : undefined;
430
+ check();
391
431
  file = await fs.promises.open(real, existed ? fs.constants.O_WRONLY | fs.constants.O_APPEND | (fs.constants.O_NOFOLLOW ?? 0) : 'ax', 0o600);
392
432
  check();
393
- assertIntegrity(real);
433
+ assertIntegrity(real, signal, deadline);
394
434
  const opened = await file.stat();
435
+ check();
395
436
  if (before && (opened.ino !== before.ino || opened.dev !== before.dev || opened.size !== before.size)) {
437
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
396
438
  throw new HostKeyError('known_hosts changed while opening it');
397
439
  }
398
440
  const entry = `${original.length && !original.endsWith('\n') ? '\n' : ''}` +
@@ -468,27 +510,34 @@ export class KnownHosts {
468
510
  }
469
511
  return result;
470
512
  }
471
- read(filePath, system) {
472
- const real = validateKnownHostsPath(filePath, system);
473
- if (!fs.existsSync(real)) {
474
- return '';
513
+ read(filePath, system, signal, deadline) {
514
+ assertVerificationActive(signal, deadline);
515
+ try {
516
+ const real = validateKnownHostsPath(filePath, system);
517
+ if (!fs.existsSync(real)) {
518
+ return '';
519
+ }
520
+ assertIntegrity(real, signal, deadline);
521
+ const stats = fs.statSync(real);
522
+ if (!stats.isFile() || stats.size > 8 * 1024 * 1024) {
523
+ throw new HostKeyError('known_hosts must be a regular file no larger than 8 MiB');
524
+ }
525
+ return fs.readFileSync(real, 'utf8');
475
526
  }
476
- assertIntegrity(real);
477
- const stats = fs.statSync(real);
478
- if (!stats.isFile() || stats.size > 8 * 1024 * 1024) {
479
- throw new HostKeyError('known_hosts must be a regular file no larger than 8 MiB');
527
+ finally {
528
+ assertVerificationActive(signal, deadline);
480
529
  }
481
- return fs.readFileSync(real, 'utf8');
482
530
  }
483
- *matchingKeys(hostname) {
531
+ *matchingKeys(hostname, signal, deadline) {
484
532
  const files = [
485
533
  [this.userFile, false],
486
534
  [`${this.userFile}2`, false],
487
535
  ...this.systemFiles.map((name) => [name, true]),
488
536
  ];
489
537
  for (const [filePath, system] of files) {
490
- const lines = this.read(filePath, system).split(/\r?\n/);
538
+ const lines = this.read(filePath, system, signal, deadline).split(/\r?\n/);
491
539
  for (let index = 0; index < lines.length; ++index) {
540
+ assertVerificationActive(signal, deadline);
492
541
  const line = lines[index].trim();
493
542
  if (!line || line.startsWith('#')) {
494
543
  continue;
@@ -509,6 +558,7 @@ export class KnownHosts {
509
558
  key = decodeBase64(fields[2] ?? '');
510
559
  const parsed = ssh2.utils.parseKey(key);
511
560
  if (parsed instanceof Error || parsed.type !== fields[1]) {
561
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
512
562
  throw new Error('key type mismatch');
513
563
  }
514
564
  }
@@ -519,14 +569,14 @@ export class KnownHosts {
519
569
  }
520
570
  }
521
571
  }
522
- lookup(hostname, rawKey) {
572
+ lookup(hostname, rawKey, signal, deadline) {
523
573
  let accepted = false;
524
574
  const hostKey = {
525
575
  keyType: ssh2.utils.parseKey(rawKey).type,
526
576
  fingerprint: `SHA256:${createHash('sha256').update(rawKey).digest('base64').replace(/=+$/, '')}`,
527
577
  knownKeys: [],
528
578
  };
529
- for (const { key, type, revoked, file, line } of this.matchingKeys(hostname)) {
579
+ for (const { key, type, revoked, file, line } of this.matchingKeys(hostname, signal, deadline)) {
530
580
  hostKey.knownKeys.push({
531
581
  keyType: type,
532
582
  fingerprint: `SHA256:${createHash('sha256').update(key).digest('base64').replace(/=+$/, '')}`,
@@ -546,7 +596,8 @@ export class KnownHosts {
546
596
  const stored = hostKey.knownKeys
547
597
  .map((entry) => `${entry.keyType} ${entry.fingerprint} at ${entry.file}:${entry.line}`)
548
598
  .join('; ');
549
- throw new HostKeyError(`Host key changed for ${hostname}; received ${hostKey.keyType} ${hostKey.fingerprint}; stored ${stored}; verify and update known_hosts before reconnecting`, { hostKey });
599
+ throw new HostKeyError(`Host key changed for ${hostname}; received ${hostKey.keyType} ${hostKey.fingerprint}; ` +
600
+ `stored ${stored}; verify and update known_hosts before reconnecting`, { hostKey });
550
601
  }
551
602
  return accepted;
552
603
  }
package/dist/openssh.d.ts CHANGED
@@ -12,7 +12,7 @@ export declare function resolveOpenSshConfig(input: {
12
12
  port?: number;
13
13
  controlPath?: string;
14
14
  readyTimeout?: number;
15
- }): Promise<{
15
+ }, signal?: AbortSignal): Promise<{
16
16
  host: string;
17
17
  username: string;
18
18
  port: number;
@@ -32,12 +32,12 @@ export declare class OpenSshConnection {
32
32
  assertCurrent(): void;
33
33
  isAlive(): boolean;
34
34
  readonly trackProcess: (child: ChildProcess, processGroup?: boolean) => void;
35
- open(command: string): CommandChannel & {
35
+ open(command: string, withInput?: boolean): CommandChannel & {
36
36
  ready: Promise<void>;
37
37
  };
38
- consume(command: string, consume: (chunk: Buffer) => void, timeout: number): Promise<void>;
39
- capture(command: string, timeout: number, maxBytes: number): Promise<Buffer>;
40
- stat(remotePath: string, timeout: number, follow?: boolean): Promise<{
38
+ consume(command: string, consume: (chunk: Buffer) => void, timeout: number, signal?: AbortSignal): Promise<void>;
39
+ capture(command: string, timeout: number, maxBytes: number, signal?: AbortSignal): Promise<Buffer>;
40
+ stat(remotePath: string, timeout: number, follow?: boolean, signal?: AbortSignal): Promise<{
41
41
  mode: number;
42
42
  size: number;
43
43
  uid: number;
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, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, signal });
24
- track?.(child);
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
- failure = new OpenSshError(`OpenSSH request timed out after ${timeout}ms`, {
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
- failure ??= new OpenSshError('OpenSSH response exceeded its output limit', {
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,25 +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
- failure ??= error;
58
- });
59
- child.once('close', (status) => {
60
- clearTimeout(timer);
61
- if (failure) {
62
- reject(failure);
63
- }
64
- else {
65
- resolve({
66
- stdout: Buffer.concat(stdout).toString('utf8'),
67
- stderr: Buffer.concat(stderr).toString('utf8'),
68
- status,
69
- });
70
- }
71
- });
109
+ child.once('error', (error) => stop(error));
110
+ child.once('close', (status) => finish(failure, status));
72
111
  });
73
112
  }
74
- export async function resolveOpenSshConfig(input) {
113
+ export async function resolveOpenSshConfig(input, signal) {
75
114
  if (process.platform === 'win32') {
76
115
  throw new OpenSshError('The OpenSSH master backend requires a local POSIX platform', {
77
116
  code: 'unsupported_backend',
@@ -103,7 +142,7 @@ export async function resolveOpenSshConfig(input) {
103
142
  args.push('-S', path.resolve(expandTilde(input.controlPath)));
104
143
  }
105
144
  args.push('--', destination);
106
- const result = await captureSsh(args, input.readyTimeout ?? 30_000, CONFIG_OUTPUT_LIMIT);
145
+ const result = await captureSsh(args, input.readyTimeout ?? 30_000, CONFIG_OUTPUT_LIMIT, signal);
107
146
  if (result.status !== 0) {
108
147
  invalidConfig(`OpenSSH configuration could not be resolved: ${result.stderr.trim()}`);
109
148
  }
@@ -132,10 +171,11 @@ export async function resolveOpenSshConfig(input) {
132
171
  class OpenSshChannel extends PassThrough {
133
172
  stderr = new PassThrough();
134
173
  ready;
174
+ stdin;
135
175
  child;
136
176
  resolveReady;
137
177
  rejectReady;
138
- constructor(args, command, track) {
178
+ constructor(args, command, track, withInput) {
139
179
  super({ emitClose: false });
140
180
  this.ready = new Promise((resolve, reject) => {
141
181
  this.resolveReady = resolve;
@@ -146,9 +186,13 @@ class OpenSshChannel extends PassThrough {
146
186
  const token = randomBytes(32).toString('hex');
147
187
  const prefix = Buffer.from(`\x1eMCPSSH:${token}:`);
148
188
  const script = `printf ${escapeShellArg(`\x1eMCPSSH:${token}:START\x1f`)} >&2; ` +
149
- `sh -c ${escapeShellArg(command)}; status=$?; ` +
189
+ `( eval ${escapeShellArg(command)} ); status=$?; ` +
150
190
  `printf ${escapeShellArg(`\x1eMCPSSH:${token}:END:%s\x1f`)} "$status" >&2; exit "$status"`;
151
- this.child = spawn('ssh', [...args, script], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
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;
152
196
  track(this.child);
153
197
  let pending = Buffer.alloc(0);
154
198
  let remoteExitCode;
@@ -271,7 +315,7 @@ export class OpenSshConnection {
271
315
  const args = this.arguments(config);
272
316
  const timeout = config.readyTimeout ?? 30_000;
273
317
  const checked = await captureSsh([...args.slice(0, -1), '-O', 'check', config.host], timeout, CONTROL_OUTPUT_LIMIT, signal);
274
- const pid = Number(/Master running \(pid=(?<pid>\d+)\)/.exec(checked.stderr)?.[1]);
318
+ const pid = Number(/Master running \(pid=(?<pid>\d+)\)/.exec(checked.stderr)?.groups?.pid);
275
319
  if (checked.status !== 0 || !Number.isSafeInteger(pid) || pid <= 0) {
276
320
  throw new OpenSshError(`OpenSSH master is unavailable: ${checked.stderr.trim()}`, {
277
321
  code: 'master_unavailable',
@@ -284,6 +328,7 @@ export class OpenSshConnection {
284
328
  signal?.addEventListener('abort', abort, { once: true });
285
329
  try {
286
330
  if (signal?.aborted) {
331
+ // noinspection ExceptionCaughtLocallyJS -- 准备失败时仅清理本次绑定的 alias channel
287
332
  throw signal.reason;
288
333
  }
289
334
  const marker = randomBytes(32).toString('hex');
@@ -292,6 +337,7 @@ export class OpenSshConnection {
292
337
  const start = observed.stdout.lastIndexOf(`${marker}\n`);
293
338
  const lines = observed.stdout.slice(start + marker.length + 1).split('\n');
294
339
  if (observed.status !== 0 || start < 0 || !/^\d+$/.test(lines[0]) || !lines[1]) {
340
+ // noinspection ExceptionCaughtLocallyJS -- 准备失败时仅清理本次绑定的 alias channel
295
341
  throw new OpenSshError('The existing OpenSSH master did not provide its login identity', {
296
342
  code: 'master_identity_unavailable',
297
343
  backend: 'openssh',
@@ -299,6 +345,7 @@ export class OpenSshConnection {
299
345
  });
300
346
  }
301
347
  if (lines[1] !== config.username) {
348
+ // noinspection ExceptionCaughtLocallyJS -- 准备失败时仅清理本次绑定的 alias channel
302
349
  throw new OpenSshError('The existing master login does not match the requested user', {
303
350
  code: 'master_identity_mismatch',
304
351
  backend: 'openssh',
@@ -401,10 +448,11 @@ export class OpenSshConnection {
401
448
  this.close();
402
449
  }
403
450
  };
404
- open(command) {
405
- return new OpenSshChannel(this.arguments(), command, this.trackProcess);
451
+ open(command, withInput = false) {
452
+ return new OpenSshChannel(this.arguments(), command, this.trackProcess, withInput);
406
453
  }
407
- consume(command, consume, timeout) {
454
+ consume(command, consume, timeout, signal) {
455
+ signal?.throwIfAborted();
408
456
  const stream = this.open(command);
409
457
  return new Promise((resolve, reject) => {
410
458
  let settled = false;
@@ -415,6 +463,7 @@ export class OpenSshConnection {
415
463
  }
416
464
  settled = true;
417
465
  clearTimeout(timer);
466
+ signal?.removeEventListener('abort', onAbort);
418
467
  if (error) {
419
468
  stream.destroy();
420
469
  reject(error);
@@ -423,6 +472,7 @@ export class OpenSshConnection {
423
472
  resolve();
424
473
  }
425
474
  };
475
+ const onAbort = () => finish(signal?.reason instanceof Error ? signal.reason : new Error('OpenSSH request cancelled'));
426
476
  const timer = setTimeout(() => finish(new OpenSshError(`OpenSSH command timed out after ${timeout}ms`, {
427
477
  code: 'openssh_timeout',
428
478
  backend: 'openssh',
@@ -430,6 +480,10 @@ export class OpenSshConnection {
430
480
  timeout,
431
481
  retryable: false,
432
482
  })), timeout);
483
+ signal?.addEventListener('abort', onAbort, { once: true });
484
+ if (signal?.aborted) {
485
+ onAbort();
486
+ }
433
487
  stream.on('data', (chunk) => {
434
488
  if (settled) {
435
489
  return;
@@ -456,7 +510,7 @@ export class OpenSshConnection {
456
510
  })));
457
511
  });
458
512
  }
459
- async capture(command, timeout, maxBytes) {
513
+ async capture(command, timeout, maxBytes, signal) {
460
514
  const chunks = [];
461
515
  let size = 0;
462
516
  await this.consume(command, (chunk) => {
@@ -470,12 +524,12 @@ export class OpenSshConnection {
470
524
  });
471
525
  }
472
526
  chunks.push(chunk);
473
- }, timeout);
527
+ }, timeout, signal);
474
528
  return Buffer.concat(chunks);
475
529
  }
476
- async stat(remotePath, timeout, follow = true) {
530
+ async stat(remotePath, timeout, follow = true, signal) {
477
531
  const format = '%f\\0%s\\0%u\\0%g\\0%Y\\0%X\\0%d:%i:%s:%y:%z\\0';
478
- 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);
479
533
  const fields = bytes.toString('utf8').split('\0');
480
534
  const values = [Number.parseInt(fields[0], 16), ...fields.slice(1, 6).map(Number)];
481
535
  if (fields.length !== 8 || !values.every(Number.isSafeInteger) || values[1] < 0) {