@pyrokine/mcp-ssh 3.2.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.
@@ -176,6 +176,7 @@ async function inspectLock(directory, domain, preparation = false) {
176
176
  if (error instanceof SyntaxError) {
177
177
  return 'lock owner identity could not be verified; it was retained';
178
178
  }
179
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
179
180
  throw error;
180
181
  }
181
182
  if (!domain ||
@@ -196,6 +197,7 @@ async function inspectLock(directory, domain, preparation = false) {
196
197
  return;
197
198
  }
198
199
  if (error.code !== 'EPERM') {
200
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
199
201
  throw error;
200
202
  }
201
203
  return 'lock owner liveness could not be verified (EPERM); it was retained';
@@ -331,6 +333,7 @@ export class KnownHosts {
331
333
  await fs.promises.mkdir(preparation, { mode: 0o700 });
332
334
  prepared = true;
333
335
  if (process.platform === 'win32' && checkWindowsAcl(preparation, true) !== 'key_path_usable') {
336
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
334
337
  throw new HostKeyError('known_hosts lock preparation permissions could not be verified');
335
338
  }
336
339
  await fs.promises.writeFile(path.join(preparation, owner), JSON.stringify({ version: 1, pid: process.pid, domain }), {
@@ -342,6 +345,7 @@ export class KnownHosts {
342
345
  while (!owned) {
343
346
  signal?.throwIfAborted();
344
347
  if (Date.now() >= lockDeadline) {
348
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
345
349
  throw new HostKeyError(`known_hosts is locked: ${waitingReason}`);
346
350
  }
347
351
  let waiting = await inspectLock(lockPath, domain);
@@ -357,6 +361,7 @@ export class KnownHosts {
357
361
  catch (error) {
358
362
  const code = error.code;
359
363
  if (!['EEXIST', 'ENOTEMPTY', 'EPERM', 'EACCES'].includes(code ?? '')) {
364
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
360
365
  throw error;
361
366
  }
362
367
  const target = await fs.promises.lstat(lockPath).catch((cause) => {
@@ -368,6 +373,7 @@ export class KnownHosts {
368
373
  await removeEmptyLock(lockPath);
369
374
  }
370
375
  else if ((code === 'EPERM' || code === 'EACCES') && !target?.isFile()) {
376
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
371
377
  throw error;
372
378
  }
373
379
  waiting = 'another writer published its lock';
@@ -375,6 +381,7 @@ export class KnownHosts {
375
381
  }
376
382
  if (!owned) {
377
383
  if (Date.now() >= lockDeadline) {
384
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
378
385
  throw new HostKeyError(`known_hosts is locked: ${waiting}`);
379
386
  }
380
387
  await delay(Math.min(25, lockDeadline - Date.now()), undefined, { signal });
@@ -393,6 +400,7 @@ export class KnownHosts {
393
400
  assertIntegrity(real);
394
401
  const opened = await file.stat();
395
402
  if (before && (opened.ino !== before.ino || opened.dev !== before.dev || opened.size !== before.size)) {
403
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
396
404
  throw new HostKeyError('known_hosts changed while opening it');
397
405
  }
398
406
  const entry = `${original.length && !original.endsWith('\n') ? '\n' : ''}` +
@@ -509,6 +517,7 @@ export class KnownHosts {
509
517
  key = decodeBase64(fields[2] ?? '');
510
518
  const parsed = ssh2.utils.parseKey(key);
511
519
  if (parsed instanceof Error || parsed.type !== fields[1]) {
520
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
512
521
  throw new Error('key type mismatch');
513
522
  }
514
523
  }
@@ -546,7 +555,8 @@ export class KnownHosts {
546
555
  const stored = hostKey.knownKeys
547
556
  .map((entry) => `${entry.keyType} ${entry.fingerprint} at ${entry.file}:${entry.line}`)
548
557
  .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 });
558
+ throw new HostKeyError(`Host key changed for ${hostname}; received ${hostKey.keyType} ${hostKey.fingerprint}; ` +
559
+ `stored ${stored}; verify and update known_hosts before reconnecting`, { hostKey });
550
560
  }
551
561
  return accepted;
552
562
  }
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) {
@@ -117,8 +117,8 @@ export function windowsCaseSemanticsScript(parent, names) {
117
117
  '$names = ' +
118
118
  `${names === undefined
119
119
  ? '[string[]](ConvertFrom-Json ' +
120
- '([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Consol' +
121
- 'e]::In.ReadToEnd()))))'
120
+ '([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String(' +
121
+ '[Console]::In.ReadToEnd()))))'
122
122
  : `[string[]]@(${names.map(quotePowershell).join(', ')})`}` +
123
123
  '\n' +
124
124
  '$collision = $null\n' +
@@ -71,7 +71,9 @@ export declare class SessionManager {
71
71
  /** per-alias connect 进行中的 Promise,防止并发 connect 同一 alias 时重复建连 */
72
72
  private connectInFlight;
73
73
  private pendingConnections;
74
+ private preparingConnections;
74
75
  private connectionGenerations;
76
+ private cancellationSequence;
75
77
  private readonly knownHosts;
76
78
  private readonly ptyManager;
77
79
  private readonly forwardManager;
@@ -88,7 +90,11 @@ export declare class SessionManager {
88
90
  /**
89
91
  * 建立 SSH 连接(per-alias mutex,防止并发 connect 同一 alias 重复建连)
90
92
  */
91
- connect(config: SSHConnectionConfig): Promise<string>;
93
+ connect(config: SSHConnectionConfig, preparationGeneration?: number, signal?: AbortSignal): Promise<string>;
94
+ prepareConnection<T>(alias: string | undefined, prepare: (signal: AbortSignal) => Promise<T>): Promise<{
95
+ result: T;
96
+ generation?: number;
97
+ }>;
92
98
  /**
93
99
  * 重新连接
94
100
  */