@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.
@@ -101,7 +101,12 @@ export class ForwardManager {
101
101
  try {
102
102
  client.forwardOut(socket.remoteAddress || '127.0.0.1', socket.remotePort || 0, remoteHost, remotePort, (err, connectedStream) => {
103
103
  settleChannelOpen();
104
- if (err || !this.isCurrent(session) || session.lifecycle !== 'active' || !session.active) {
104
+ if (err ||
105
+ closed ||
106
+ socket.destroyed ||
107
+ !this.isCurrent(session) ||
108
+ session.lifecycle !== 'active' ||
109
+ !session.active) {
105
110
  connectedStream?.destroy();
106
111
  closeConnection();
107
112
  return;
@@ -0,0 +1,22 @@
1
+ import { type ServerHostKeyAlgorithm } from 'ssh2';
2
+ import type { ConnectionFailureDetails } from './types.js';
3
+ export interface HostKeyTrust {
4
+ status: 'known' | 'added';
5
+ fingerprint: string;
6
+ }
7
+ export declare class HostKeyError extends Error {
8
+ readonly hostKey?: ConnectionFailureDetails['hostKey'];
9
+ constructor(message: string, options?: ErrorOptions & {
10
+ hostKey?: ConnectionFailureDetails['hostKey'];
11
+ });
12
+ }
13
+ export declare class KnownHosts {
14
+ private readonly userFile;
15
+ private readonly systemFiles;
16
+ constructor(userFile?: string, systemFiles?: string[]);
17
+ getHostKeyAlgorithms(host: string, port: number): ServerHostKeyAlgorithm[];
18
+ verify(host: string, port: number, rawKey: Buffer, signal?: AbortSignal, deadline?: number): Promise<HostKeyTrust>;
19
+ private read;
20
+ private matchingKeys;
21
+ private lookup;
22
+ }
@@ -0,0 +1,563 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
3
+ import * as fs from 'node:fs';
4
+ import * as os from 'node:os';
5
+ import * as path from 'node:path';
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import ssh2 from 'ssh2';
8
+ import { validateKnownHostsPath } from './security.js';
9
+ import { checkWindowsAcl, checkWindowsKnownHostsIntegrity } from './windows-acl.js';
10
+ export class HostKeyError extends Error {
11
+ hostKey;
12
+ constructor(message, options) {
13
+ super(message, options);
14
+ this.name = 'HostKeyError';
15
+ this.hostKey = options?.hostKey;
16
+ }
17
+ }
18
+ function assertIntegrity(filePath) {
19
+ if (process.platform === 'win32') {
20
+ checkWindowsKnownHostsIntegrity(filePath);
21
+ return;
22
+ }
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) {
33
+ return;
34
+ }
35
+ current = parent;
36
+ }
37
+ }
38
+ function localProcessDomain(deadline) {
39
+ // A hostname alone cannot distinguish shared homes or different PID namespaces.
40
+ if (process.platform === 'linux') {
41
+ try {
42
+ const boot = fs.readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
43
+ const namespace = fs.readlinkSync('/proc/self/ns/pid');
44
+ if (/^[\da-f-]{36}$/.test(boot) && /^pid:\[\d+]$/.test(namespace)) {
45
+ return `${boot}:${namespace}`;
46
+ }
47
+ }
48
+ catch {
49
+ // Unavailable process-domain evidence leaves stale owners unverifiable.
50
+ }
51
+ }
52
+ if (process.platform === 'darwin' || process.platform === 'win32') {
53
+ const script = "$ErrorActionPreference = 'Stop'\n" +
54
+ "Add-Type -TypeDefinition @'\n" +
55
+ 'using System;\n' +
56
+ 'using System.Runtime.InteropServices;\n' +
57
+ 'public static class McpBootEnvironment {\n' +
58
+ ' [StructLayout(LayoutKind.Sequential)]\n' +
59
+ ' private struct BootEnvironment {\n' +
60
+ ' public Guid BootIdentifier;\n' +
61
+ ' public uint FirmwareType;\n' +
62
+ ' public ulong BootFlags;\n' +
63
+ ' }\n' +
64
+ ' [DllImport("ntdll.dll", ExactSpelling = true)]\n' +
65
+ ' private static extern int NtQuerySystemInformation(int ' +
66
+ 'informationClass,\n' +
67
+ ' out BootEnvironment information, int length, out int ' +
68
+ 'returnLength);\n' +
69
+ ' public static string Read() {\n' +
70
+ ' BootEnvironment information;\n' +
71
+ ' int length;\n' +
72
+ ' int size = Marshal.SizeOf(typeof(BootEnvironment));\n' +
73
+ ' // SystemBootEnvironmentInformation (90), ' +
74
+ 'SYSTEM_BOOT_ENVIRONMENT_INFORMATION.\n' +
75
+ ' int status = NtQuerySystemInformation(90, out information, size, ' +
76
+ 'out length);\n' +
77
+ ' if (status != 0 || length != size) throw new ' +
78
+ 'InvalidOperationException("Boot identity query failed");\n' +
79
+ ' return information.BootIdentifier.ToString("D");\n' +
80
+ ' }\n' +
81
+ '}\n' +
82
+ "'@\n" +
83
+ '[Console]::Write([McpBootEnvironment]::Read())';
84
+ const windows = process.platform === 'win32';
85
+ const result = spawnSync(windows ? 'powershell.exe' : '/usr/sbin/sysctl', windows
86
+ ? [
87
+ '-NoProfile',
88
+ '-NonInteractive',
89
+ '-EncodedCommand',
90
+ Buffer.from(script, 'utf16le').toString('base64'),
91
+ ]
92
+ : ['-n', 'kern.bootsessionuuid'], {
93
+ timeout: Math.max(1, Math.min(5000, deadline - Date.now())),
94
+ encoding: 'utf8',
95
+ windowsHide: true,
96
+ maxBuffer: 16_384,
97
+ });
98
+ const boot = result.stdout?.trim().toLowerCase();
99
+ if (!result.error &&
100
+ result.status === 0 &&
101
+ /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/.test(boot) &&
102
+ boot !== '00000000-0000-0000-0000-000000000000') {
103
+ return `${process.platform}:${boot}`;
104
+ }
105
+ }
106
+ return undefined;
107
+ }
108
+ async function removeEmptyLock(directory) {
109
+ try {
110
+ await fs.promises.rmdir(directory);
111
+ }
112
+ catch (error) {
113
+ const code = error.code;
114
+ if (code === 'ENOENT' || code === 'ENOTEMPTY' || code === 'EEXIST') {
115
+ return;
116
+ }
117
+ // Windows can report EPERM for a directory another writer has just populated.
118
+ if (code === 'EPERM') {
119
+ try {
120
+ if ((await fs.promises.readdir(directory)).length > 0) {
121
+ return;
122
+ }
123
+ }
124
+ catch (cause) {
125
+ if (cause.code === 'ENOENT') {
126
+ return;
127
+ }
128
+ throw cause;
129
+ }
130
+ }
131
+ throw error;
132
+ }
133
+ }
134
+ async function removeLockOwner(directory, owner) {
135
+ try {
136
+ await fs.promises.unlink(path.join(directory, owner));
137
+ }
138
+ catch (error) {
139
+ if (error.code !== 'ENOENT') {
140
+ throw error;
141
+ }
142
+ }
143
+ // A new owner's unique filename keeps this non-recursive removal from deleting its lock.
144
+ await removeEmptyLock(directory);
145
+ }
146
+ async function inspectLock(directory, domain, preparation = false) {
147
+ try {
148
+ const stats = await fs.promises.lstat(directory);
149
+ if (stats.isFile()) {
150
+ return 'legacy lock file has no verifiable owner; it was retained';
151
+ }
152
+ if (!stats.isDirectory()) {
153
+ return 'lock owner identity could not be verified; it was retained';
154
+ }
155
+ assertIntegrity(directory);
156
+ const entries = await fs.promises.readdir(directory);
157
+ if (entries.length === 0 && !preparation) {
158
+ await removeEmptyLock(directory);
159
+ return;
160
+ }
161
+ const match = entries.length === 1 ? /^owner-(?<pid>\d+)-(?<nonce>[\da-f]{32})\.json$/.exec(entries[0]) : null;
162
+ if (!match || (preparation && !directory.endsWith(`.prepare-${match.groups.pid}-${match.groups.nonce}`))) {
163
+ return 'lock owner identity could not be verified; it was retained';
164
+ }
165
+ const ownerPath = path.join(directory, entries[0]);
166
+ const ownerStats = await fs.promises.lstat(ownerPath);
167
+ if (!ownerStats.isFile() || ownerStats.size > 4096) {
168
+ return 'lock owner identity could not be verified; it was retained';
169
+ }
170
+ assertIntegrity(ownerPath);
171
+ let owner;
172
+ try {
173
+ owner = JSON.parse(await fs.promises.readFile(ownerPath, 'utf8'));
174
+ }
175
+ catch (error) {
176
+ if (error instanceof SyntaxError) {
177
+ return 'lock owner identity could not be verified; it was retained';
178
+ }
179
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
180
+ throw error;
181
+ }
182
+ if (!domain ||
183
+ !owner ||
184
+ owner.version !== 1 ||
185
+ owner.domain !== domain ||
186
+ owner.pid !== Number(match.groups.pid) ||
187
+ !Number.isSafeInteger(owner.pid) ||
188
+ owner.pid <= 0) {
189
+ return 'lock belongs to an unverifiable local process domain; it was retained';
190
+ }
191
+ try {
192
+ process.kill(owner.pid, 0);
193
+ }
194
+ catch (error) {
195
+ if (error.code === 'ESRCH') {
196
+ await removeLockOwner(directory, entries[0]);
197
+ return;
198
+ }
199
+ if (error.code !== 'EPERM') {
200
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
201
+ throw error;
202
+ }
203
+ return 'lock owner liveness could not be verified (EPERM); it was retained';
204
+ }
205
+ return 'lock is held by a live process';
206
+ }
207
+ catch (error) {
208
+ if (error.code === 'ENOENT') {
209
+ return;
210
+ }
211
+ if (preparation) {
212
+ return 'preparation ownership could not be verified; it was retained';
213
+ }
214
+ throw error;
215
+ }
216
+ }
217
+ function decodeBase64(value) {
218
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(value)) {
219
+ throw new HostKeyError('Invalid known_hosts key encoding');
220
+ }
221
+ const bytes = Buffer.from(value, 'base64');
222
+ if (bytes.toString('base64').replace(/=+$/, '') !== value.replace(/=+$/, '')) {
223
+ throw new HostKeyError('Invalid known_hosts key encoding');
224
+ }
225
+ return bytes;
226
+ }
227
+ function matchesPattern(pattern, hostname) {
228
+ if (pattern.startsWith('|')) {
229
+ const fields = pattern.split('|');
230
+ if (fields.length !== 4 || fields[1] !== '1') {
231
+ throw new HostKeyError('Unsupported or damaged hashed known_hosts hostname');
232
+ }
233
+ const salt = decodeBase64(fields[2]);
234
+ const expected = decodeBase64(fields[3]);
235
+ const actual = createHmac('sha1', salt).update(hostname).digest();
236
+ return expected.length === actual.length && timingSafeEqual(expected, actual);
237
+ }
238
+ const expression = pattern
239
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
240
+ .replace(/\*/g, '.*')
241
+ .replace(/\?/g, '.');
242
+ return new RegExp(`^${expression}$`, 'i').test(hostname);
243
+ }
244
+ function matchesHost(patterns, hostname) {
245
+ let positive = false;
246
+ for (const value of patterns.split(',')) {
247
+ const negative = value.startsWith('!');
248
+ if (matchesPattern(negative ? value.slice(1) : value, hostname)) {
249
+ if (negative) {
250
+ return false;
251
+ }
252
+ positive = true;
253
+ }
254
+ }
255
+ return positive;
256
+ }
257
+ function knownHostName(host, port) {
258
+ const hostname = host.replace(/^\[(?<host>.*)]$/, '$1').toLowerCase();
259
+ if (!hostname || /[\s,|!*?\0]/.test(hostname)) {
260
+ throw new HostKeyError('Invalid hostname for known_hosts verification');
261
+ }
262
+ return port === 22 ? hostname : `[${hostname}]:${port}`;
263
+ }
264
+ export class KnownHosts {
265
+ userFile;
266
+ systemFiles;
267
+ constructor(userFile = path.join(os.homedir(), '.ssh', 'known_hosts'), systemFiles = process.platform === 'win32'
268
+ ? [path.join(process.env.ProgramData ?? 'C:\\ProgramData', 'ssh', 'ssh_known_hosts')]
269
+ : ['/etc/ssh/ssh_known_hosts', '/etc/ssh/ssh_known_hosts2']) {
270
+ this.userFile = userFile;
271
+ this.systemFiles = systemFiles;
272
+ }
273
+ getHostKeyAlgorithms(host, port) {
274
+ const types = new Set();
275
+ for (const { type, revoked } of this.matchingKeys(knownHostName(host, port))) {
276
+ if (!revoked) {
277
+ types.add(type);
278
+ }
279
+ }
280
+ const algorithms = [
281
+ 'ssh-ed25519',
282
+ 'ecdsa-sha2-nistp256',
283
+ 'ecdsa-sha2-nistp384',
284
+ 'ecdsa-sha2-nistp521',
285
+ 'rsa-sha2-512',
286
+ 'rsa-sha2-256',
287
+ 'ssh-rsa',
288
+ ];
289
+ return algorithms.filter((algorithm) => types.has(algorithm.startsWith('rsa-sha2-') ? 'ssh-rsa' : algorithm));
290
+ }
291
+ async verify(host, port, rawKey, signal, deadline = Date.now() + 5000) {
292
+ const name = knownHostName(host, port);
293
+ const parsed = ssh2.utils.parseKey(rawKey);
294
+ if (parsed instanceof Error || Array.isArray(parsed) || parsed.type.includes('-cert-')) {
295
+ throw new HostKeyError('Unsupported or damaged server host key');
296
+ }
297
+ const fingerprint = `SHA256:${createHash('sha256').update(rawKey).digest('base64').replace(/=+$/, '')}`;
298
+ const check = () => {
299
+ signal?.throwIfAborted();
300
+ if (Date.now() >= deadline) {
301
+ throw new HostKeyError('known_hosts verification deadline exhausted');
302
+ }
303
+ };
304
+ check();
305
+ if (this.lookup(name, rawKey)) {
306
+ return { status: 'known', fingerprint };
307
+ }
308
+ const real = validateKnownHostsPath(this.userFile);
309
+ const parent = path.dirname(real);
310
+ fs.mkdirSync(parent, { recursive: true, mode: 0o700 });
311
+ assertIntegrity(parent);
312
+ const lockPath = `${real}.mcp-lock`;
313
+ const lockDeadline = Math.min(deadline, Date.now() + 5000);
314
+ const domain = localProcessDomain(lockDeadline);
315
+ const identity = `${process.pid}-${randomBytes(16).toString('hex')}`;
316
+ const preparation = `${lockPath}.prepare-${identity}`;
317
+ const owner = `owner-${identity}.json`;
318
+ let prepared = false;
319
+ let owned = false;
320
+ let file;
321
+ let appendStarted = false;
322
+ let result;
323
+ const failures = [];
324
+ try {
325
+ const prefix = `${path.basename(lockPath)}.prepare-`;
326
+ for (const entry of await fs.promises.readdir(parent)) {
327
+ if (entry.startsWith(prefix) && /^\d+-[\da-f]{32}$/.test(entry.slice(prefix.length))) {
328
+ check();
329
+ await inspectLock(path.join(parent, entry), domain, true);
330
+ }
331
+ }
332
+ check();
333
+ await fs.promises.mkdir(preparation, { mode: 0o700 });
334
+ prepared = true;
335
+ if (process.platform === 'win32' && checkWindowsAcl(preparation, true) !== 'key_path_usable') {
336
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
337
+ throw new HostKeyError('known_hosts lock preparation permissions could not be verified');
338
+ }
339
+ await fs.promises.writeFile(path.join(preparation, owner), JSON.stringify({ version: 1, pid: process.pid, domain }), {
340
+ flag: 'wx',
341
+ mode: 0o600,
342
+ });
343
+ assertIntegrity(path.join(preparation, owner));
344
+ let waitingReason = 'another writer';
345
+ while (!owned) {
346
+ signal?.throwIfAborted();
347
+ if (Date.now() >= lockDeadline) {
348
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
349
+ throw new HostKeyError(`known_hosts is locked: ${waitingReason}`);
350
+ }
351
+ let waiting = await inspectLock(lockPath, domain);
352
+ waitingReason = waiting ?? waitingReason;
353
+ if (!waiting) {
354
+ check();
355
+ try {
356
+ // Await publication even if canceled, so ownership is recorded before cleanup.
357
+ await fs.promises.rename(preparation, lockPath);
358
+ prepared = false;
359
+ owned = true;
360
+ }
361
+ catch (error) {
362
+ const code = error.code;
363
+ if (!['EEXIST', 'ENOTEMPTY', 'EPERM', 'EACCES'].includes(code ?? '')) {
364
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
365
+ throw error;
366
+ }
367
+ const target = await fs.promises.lstat(lockPath).catch((cause) => {
368
+ if (cause.code !== 'ENOENT') {
369
+ throw cause;
370
+ }
371
+ });
372
+ if (target?.isDirectory()) {
373
+ await removeEmptyLock(lockPath);
374
+ }
375
+ else if ((code === 'EPERM' || code === 'EACCES') && !target?.isFile()) {
376
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
377
+ throw error;
378
+ }
379
+ waiting = 'another writer published its lock';
380
+ }
381
+ }
382
+ if (!owned) {
383
+ if (Date.now() >= lockDeadline) {
384
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
385
+ throw new HostKeyError(`known_hosts is locked: ${waiting}`);
386
+ }
387
+ await delay(Math.min(25, lockDeadline - Date.now()), undefined, { signal });
388
+ }
389
+ }
390
+ check();
391
+ if (this.lookup(name, rawKey)) {
392
+ result = { status: 'known', fingerprint };
393
+ }
394
+ else {
395
+ const original = this.read(this.userFile, false);
396
+ const existed = fs.existsSync(real);
397
+ const before = existed ? fs.statSync(real) : undefined;
398
+ file = await fs.promises.open(real, existed ? fs.constants.O_WRONLY | fs.constants.O_APPEND | (fs.constants.O_NOFOLLOW ?? 0) : 'ax', 0o600);
399
+ check();
400
+ assertIntegrity(real);
401
+ const opened = await file.stat();
402
+ if (before && (opened.ino !== before.ino || opened.dev !== before.dev || opened.size !== before.size)) {
403
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
404
+ throw new HostKeyError('known_hosts changed while opening it');
405
+ }
406
+ const entry = `${original.length && !original.endsWith('\n') ? '\n' : ''}` +
407
+ `${name}` +
408
+ ' ' +
409
+ `${parsed.type}` +
410
+ ' ' +
411
+ `${rawKey.toString('base64')}` +
412
+ '\n';
413
+ appendStarted = true;
414
+ await file.writeFile(entry);
415
+ await file.sync();
416
+ check();
417
+ result = { status: 'added', fingerprint };
418
+ }
419
+ }
420
+ catch (error) {
421
+ failures.push(error);
422
+ }
423
+ finally {
424
+ if (file) {
425
+ try {
426
+ await file.close();
427
+ check();
428
+ }
429
+ catch (error) {
430
+ failures.push(error);
431
+ }
432
+ }
433
+ if (owned) {
434
+ try {
435
+ await fs.promises.unlink(path.join(lockPath, owner));
436
+ await removeEmptyLock(lockPath);
437
+ }
438
+ catch (error) {
439
+ failures.push(new HostKeyError('known_hosts lock release failed', { cause: error }));
440
+ }
441
+ }
442
+ if (prepared) {
443
+ try {
444
+ await removeLockOwner(preparation, owner);
445
+ }
446
+ catch (error) {
447
+ failures.push(new HostKeyError('known_hosts preparation cleanup failed', { cause: error }));
448
+ }
449
+ }
450
+ }
451
+ if (!failures.length) {
452
+ try {
453
+ check();
454
+ }
455
+ catch (error) {
456
+ failures.push(error);
457
+ }
458
+ }
459
+ if (failures.length) {
460
+ const reasons = failures
461
+ .map((error) => {
462
+ const cause = error instanceof Error && error.cause
463
+ ? ` (${error.cause?.code ?? ''} ${String(error.cause)})`
464
+ : '';
465
+ return `${error?.code ?? ''} ${String(error)}${cause}`.trim();
466
+ })
467
+ .join('; ');
468
+ if (!appendStarted && failures.length === 1 && (failures[0] instanceof HostKeyError || signal?.aborted)) {
469
+ throw failures[0];
470
+ }
471
+ throw new HostKeyError(appendStarted
472
+ ? 'known_hosts append result is unknown; partial bytes may remain and were ' +
473
+ 'not rolled back: ' +
474
+ `${reasons}`
475
+ : `known_hosts trust could not be saved: ${reasons}`, { cause: failures.length === 1 ? failures[0] : new AggregateError(failures) });
476
+ }
477
+ return result;
478
+ }
479
+ read(filePath, system) {
480
+ const real = validateKnownHostsPath(filePath, system);
481
+ if (!fs.existsSync(real)) {
482
+ return '';
483
+ }
484
+ assertIntegrity(real);
485
+ const stats = fs.statSync(real);
486
+ if (!stats.isFile() || stats.size > 8 * 1024 * 1024) {
487
+ throw new HostKeyError('known_hosts must be a regular file no larger than 8 MiB');
488
+ }
489
+ return fs.readFileSync(real, 'utf8');
490
+ }
491
+ *matchingKeys(hostname) {
492
+ const files = [
493
+ [this.userFile, false],
494
+ [`${this.userFile}2`, false],
495
+ ...this.systemFiles.map((name) => [name, true]),
496
+ ];
497
+ for (const [filePath, system] of files) {
498
+ const lines = this.read(filePath, system).split(/\r?\n/);
499
+ for (let index = 0; index < lines.length; ++index) {
500
+ const line = lines[index].trim();
501
+ if (!line || line.startsWith('#')) {
502
+ continue;
503
+ }
504
+ const fields = line.split(/\s+/);
505
+ const marker = fields[0].startsWith('@') ? fields.shift() : undefined;
506
+ if (!matchesHost(fields[0], hostname)) {
507
+ continue;
508
+ }
509
+ if (marker === '@cert-authority' || fields[1]?.includes('-cert-v01@openssh.com')) {
510
+ throw new HostKeyError(`Host certificates/CA entries require the OpenSSH backend: ${filePath}:${index + 1}`);
511
+ }
512
+ if (marker && marker !== '@revoked') {
513
+ throw new HostKeyError(`Unsupported known_hosts marker: ${filePath}:${index + 1}`);
514
+ }
515
+ let key;
516
+ try {
517
+ key = decodeBase64(fields[2] ?? '');
518
+ const parsed = ssh2.utils.parseKey(key);
519
+ if (parsed instanceof Error || parsed.type !== fields[1]) {
520
+ // noinspection ExceptionCaughtLocallyJS — 保留锁归属及清理失败信息
521
+ throw new Error('key type mismatch');
522
+ }
523
+ }
524
+ catch {
525
+ throw new HostKeyError(`Damaged matching known_hosts key: ${filePath}:${index + 1}`);
526
+ }
527
+ yield { key, type: fields[1], revoked: marker === '@revoked', file: filePath, line: index + 1 };
528
+ }
529
+ }
530
+ }
531
+ lookup(hostname, rawKey) {
532
+ let accepted = false;
533
+ const hostKey = {
534
+ keyType: ssh2.utils.parseKey(rawKey).type,
535
+ fingerprint: `SHA256:${createHash('sha256').update(rawKey).digest('base64').replace(/=+$/, '')}`,
536
+ knownKeys: [],
537
+ };
538
+ for (const { key, type, revoked, file, line } of this.matchingKeys(hostname)) {
539
+ hostKey.knownKeys.push({
540
+ keyType: type,
541
+ fingerprint: `SHA256:${createHash('sha256').update(key).digest('base64').replace(/=+$/, '')}`,
542
+ file,
543
+ line,
544
+ revoked,
545
+ });
546
+ const matches = key.length === rawKey.length && timingSafeEqual(key, rawKey);
547
+ if (revoked && matches) {
548
+ throw new HostKeyError(`Host key is revoked for ${hostname}: ${type} ${hostKey.fingerprint} at ${file}:${line}`, { hostKey });
549
+ }
550
+ if (!revoked && matches) {
551
+ accepted = true;
552
+ }
553
+ }
554
+ if (hostKey.knownKeys.length && !accepted) {
555
+ const stored = hostKey.knownKeys
556
+ .map((entry) => `${entry.keyType} ${entry.fingerprint} at ${entry.file}:${entry.line}`)
557
+ .join('; ');
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 });
560
+ }
561
+ return accepted;
562
+ }
563
+ }
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;