@pyrokine/mcp-ssh 2.4.3 → 3.1.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.
@@ -32,6 +32,8 @@ export declare class ForwardManager {
32
32
  list(): PortForwardInfo[];
33
33
  private pendingChannelOpensForAlias;
34
34
  private waitForConnectionDrain;
35
+ private recordConnectionClosed;
36
+ private notifyConnectionDrainIfIdle;
35
37
  private waitForChannelOpenDrain;
36
38
  private closeLocalListener;
37
39
  private closeRemoteListener;
@@ -84,14 +84,7 @@ export class ForwardManager {
84
84
  if (!socket.destroyed) {
85
85
  socket.destroy();
86
86
  }
87
- session.activeConnections = Math.max(0, session.activeConnections - 1);
88
- session.lastActivityAt = Date.now();
89
- if (session.activeConnections === 0) {
90
- for (const resolve of session.connectionDrainWaiters) {
91
- resolve();
92
- }
93
- session.connectionDrainWaiters.clear();
94
- }
87
+ this.recordConnectionClosed(session);
95
88
  };
96
89
  socket.once('close', closeConnection);
97
90
  socket.once('error', closeConnection);
@@ -346,6 +339,9 @@ export class ForwardManager {
346
339
  for (const connection of fwd.connections) {
347
340
  connection.destroy();
348
341
  }
342
+ fwd.connections.clear();
343
+ fwd.activeConnections = 0;
344
+ this.notifyConnectionDrainIfIdle(fwd);
349
345
  this.sessions.delete(fwd.id);
350
346
  if (fwd.type === 'local' && fwd.server && !fwd.closePromise) {
351
347
  this.closeServerAfterCancelledCreation(fwd.server);
@@ -405,6 +401,20 @@ export class ForwardManager {
405
401
  fwd.connectionDrainWaiters.add(resolve);
406
402
  });
407
403
  }
404
+ recordConnectionClosed(fwd) {
405
+ fwd.activeConnections = Math.max(0, fwd.activeConnections - 1);
406
+ fwd.lastActivityAt = Date.now();
407
+ this.notifyConnectionDrainIfIdle(fwd);
408
+ }
409
+ notifyConnectionDrainIfIdle(fwd) {
410
+ if (fwd.activeConnections !== 0) {
411
+ return;
412
+ }
413
+ for (const resolve of fwd.connectionDrainWaiters) {
414
+ resolve();
415
+ }
416
+ fwd.connectionDrainWaiters.clear();
417
+ }
408
418
  waitForChannelOpenDrain(fwd) {
409
419
  if (fwd.pendingChannelOpens === 0) {
410
420
  return Promise.resolve();
@@ -636,8 +646,7 @@ export class ForwardManager {
636
646
  closed = true;
637
647
  fwd.connections.delete(stream);
638
648
  fwd.connections.delete(socket);
639
- fwd.activeConnections = Math.max(0, fwd.activeConnections - 1);
640
- fwd.lastActivityAt = Date.now();
649
+ this.recordConnectionClosed(fwd);
641
650
  };
642
651
  socket.pipe(stream).pipe(socket);
643
652
  socket.on('error', () => stream.close());
@@ -0,0 +1,51 @@
1
+ import { type ChildProcess } from 'child_process';
2
+ import type { CommandChannel, OpenSshMasterInfo, SSHConnectionConfig } from './types.js';
3
+ export declare class OpenSshError extends Error {
4
+ readonly details: Record<string, unknown>;
5
+ constructor(message: string, details: Record<string, unknown>);
6
+ }
7
+ export declare function resolveOpenSshConfig(input: {
8
+ configHost?: string;
9
+ configPath?: string;
10
+ host?: string;
11
+ username?: string;
12
+ port?: number;
13
+ controlPath?: string;
14
+ readyTimeout?: number;
15
+ }): Promise<{
16
+ host: string;
17
+ username: string;
18
+ port: number;
19
+ controlPath: string;
20
+ }>;
21
+ export declare class OpenSshConnection {
22
+ readonly config: SSHConnectionConfig;
23
+ readonly info: OpenSshMasterInfo;
24
+ private readonly processes;
25
+ private readonly socketIdentity;
26
+ private closed;
27
+ private constructor();
28
+ static connect(config: SSHConnectionConfig, signal?: AbortSignal): Promise<OpenSshConnection>;
29
+ private static socket;
30
+ private static arguments;
31
+ arguments(): string[];
32
+ assertCurrent(): void;
33
+ isAlive(): boolean;
34
+ readonly trackProcess: (child: ChildProcess, processGroup?: boolean) => void;
35
+ open(command: string): CommandChannel & {
36
+ ready: Promise<void>;
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<{
41
+ mode: number;
42
+ size: number;
43
+ uid: number;
44
+ gid: number;
45
+ mtime: number;
46
+ atime: number;
47
+ stamp: string;
48
+ }>;
49
+ hashFile(remotePath: string, algorithm: 'md5' | 'sha256', timeout: number, maxBytes?: number, expectedSize?: number): Promise<string>;
50
+ close(): void;
51
+ }
@@ -0,0 +1,528 @@
1
+ import { spawn } from 'child_process';
2
+ import { createHash, randomBytes } from 'crypto';
3
+ import * as fs from 'fs';
4
+ import * as path from 'path';
5
+ import { PassThrough, Transform } from 'stream';
6
+ import { escapeShellArg, expandTilde } from './tools/utils.js';
7
+ import { validateConfigFile } from './security.js';
8
+ const CONFIG_OUTPUT_LIMIT = 512 * 1024;
9
+ const CONTROL_OUTPUT_LIMIT = 16 * 1024;
10
+ export class OpenSshError extends Error {
11
+ details;
12
+ constructor(message, details) {
13
+ super(message);
14
+ this.details = details;
15
+ this.name = 'OpenSshError';
16
+ }
17
+ }
18
+ function invalidConfig(message) {
19
+ throw new OpenSshError(message, { code: 'invalid_openssh_config', backend: 'openssh', retryable: false });
20
+ }
21
+ async function captureSsh(args, timeout, maxBytes, signal, track) {
22
+ return new Promise((resolve, reject) => {
23
+ const child = spawn('ssh', args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, signal });
24
+ track?.(child);
25
+ const stdout = [];
26
+ const stderr = [];
27
+ let bytes = 0;
28
+ let failure;
29
+ const timer = setTimeout(() => {
30
+ failure = new OpenSshError(`OpenSSH request timed out after ${timeout}ms`, {
31
+ code: 'openssh_timeout',
32
+ backend: 'openssh',
33
+ timeout,
34
+ operationStatus: 'unknown',
35
+ retryable: false,
36
+ });
37
+ child.kill('SIGKILL');
38
+ }, timeout);
39
+ const collect = (chunks) => (chunk) => {
40
+ bytes += chunk.length;
41
+ if (bytes > maxBytes) {
42
+ failure ??= new OpenSshError('OpenSSH response exceeded its output limit', {
43
+ code: 'openssh_output_limit',
44
+ backend: 'openssh',
45
+ maxBytes,
46
+ retryable: false,
47
+ });
48
+ child.kill('SIGKILL');
49
+ }
50
+ else {
51
+ chunks.push(chunk);
52
+ }
53
+ };
54
+ child.stdout.on('data', collect(stdout));
55
+ 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
+ else
64
+ resolve({
65
+ stdout: Buffer.concat(stdout).toString('utf8'),
66
+ stderr: Buffer.concat(stderr).toString('utf8'),
67
+ status,
68
+ });
69
+ });
70
+ });
71
+ }
72
+ export async function resolveOpenSshConfig(input) {
73
+ if (process.platform === 'win32') {
74
+ throw new OpenSshError('The OpenSSH master backend requires a local POSIX platform', {
75
+ code: 'unsupported_backend',
76
+ backend: 'openssh',
77
+ capability: 'local_platform',
78
+ retryable: false,
79
+ });
80
+ }
81
+ const destination = input.configHost ?? input.host;
82
+ if (!destination || destination.startsWith('-') || /[\0\r\n]/.test(destination)) {
83
+ invalidConfig('An OpenSSH host or configHost is required');
84
+ }
85
+ const args = ['-G', '-T', '-o', 'BatchMode=yes', '-o', 'PermitLocalCommand=no'];
86
+ if (input.configPath) {
87
+ const configPath = path.resolve(expandTilde(input.configPath));
88
+ validateConfigFile(configPath);
89
+ args.push('-F', configPath);
90
+ }
91
+ if (input.configHost && input.host)
92
+ args.push('-o', `HostName=${input.host}`);
93
+ if (input.username)
94
+ args.push('-l', input.username);
95
+ if (input.port !== undefined)
96
+ args.push('-p', String(input.port));
97
+ if (input.controlPath)
98
+ args.push('-S', path.resolve(expandTilde(input.controlPath)));
99
+ args.push('--', destination);
100
+ const result = await captureSsh(args, input.readyTimeout ?? 30_000, CONFIG_OUTPUT_LIMIT);
101
+ if (result.status !== 0)
102
+ invalidConfig(`OpenSSH configuration could not be resolved: ${result.stderr.trim()}`);
103
+ const config = new Map();
104
+ for (const line of result.stdout.split('\n')) {
105
+ const separator = line.indexOf(' ');
106
+ if (separator > 0 && !config.has(line.slice(0, separator))) {
107
+ config.set(line.slice(0, separator), line.slice(separator + 1));
108
+ }
109
+ }
110
+ const host = config.get('hostname') ?? '';
111
+ const username = config.get('user') ?? '';
112
+ const port = Number(config.get('port'));
113
+ const controlPath = config.get('controlpath');
114
+ if (!host || host.startsWith('-') || /[\s\0]/.test(host) || !username || /[\s:@\0]/.test(username)) {
115
+ invalidConfig('OpenSSH returned an invalid host or user');
116
+ }
117
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
118
+ invalidConfig('OpenSSH returned an invalid port');
119
+ if (!controlPath || controlPath === 'none' || /[\0\r\n]/.test(controlPath)) {
120
+ invalidConfig('OpenSSH requires an existing ControlPath; configure it or pass controlPath');
121
+ }
122
+ return { host, username, port, controlPath: path.resolve(expandTilde(controlPath)) };
123
+ }
124
+ class OpenSshChannel extends PassThrough {
125
+ stderr = new PassThrough();
126
+ ready;
127
+ child;
128
+ resolveReady;
129
+ rejectReady;
130
+ constructor(args, command, track) {
131
+ super({ emitClose: false });
132
+ this.ready = new Promise((resolve, reject) => {
133
+ this.resolveReady = resolve;
134
+ this.rejectReady = reject;
135
+ });
136
+ // 消费者可能在等待通道就绪前收到进程错误
137
+ void this.ready.catch(() => undefined);
138
+ const token = randomBytes(32).toString('hex');
139
+ const prefix = Buffer.from(`\x1eMCPSSH:${token}:`);
140
+ const script = `printf ${escapeShellArg(`\x1eMCPSSH:${token}:START\x1f`)} >&2; ` +
141
+ `sh -c ${escapeShellArg(command)}; status=$?; ` +
142
+ `printf ${escapeShellArg(`\x1eMCPSSH:${token}:END:%s\x1f`)} "$status" >&2; exit "$status"`;
143
+ this.child = spawn('ssh', [...args, script], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
144
+ track(this.child);
145
+ let pending = Buffer.alloc(0);
146
+ let remoteExitCode;
147
+ let started = false;
148
+ const resolveReady = this.resolveReady;
149
+ const markers = new Transform({
150
+ transform(chunk, _encoding, callback) {
151
+ pending = Buffer.concat([pending, chunk]);
152
+ while (pending.length > 0) {
153
+ const index = pending.indexOf(prefix);
154
+ if (index < 0) {
155
+ let retained = Math.min(pending.length, prefix.length - 1);
156
+ while (retained > 0 &&
157
+ !pending.subarray(pending.length - retained).equals(prefix.subarray(0, retained)))
158
+ --retained;
159
+ const count = pending.length - retained;
160
+ this.push(pending.subarray(0, count));
161
+ pending = pending.subarray(count);
162
+ break;
163
+ }
164
+ if (index > 0) {
165
+ this.push(pending.subarray(0, index));
166
+ pending = pending.subarray(index);
167
+ }
168
+ const end = pending.indexOf(0x1f, prefix.length);
169
+ if (end < 0 && pending.length <= prefix.length + 16)
170
+ break;
171
+ if (end < 0 || end > prefix.length + 16) {
172
+ this.push(pending.subarray(0, 1));
173
+ pending = pending.subarray(1);
174
+ continue;
175
+ }
176
+ const marker = pending.subarray(prefix.length, end).toString('ascii');
177
+ if (marker === 'START' && !started) {
178
+ started = true;
179
+ resolveReady();
180
+ }
181
+ else if (/^END:(?:0|[1-9]\d{0,2})$/.test(marker) && Number(marker.slice(4)) <= 255) {
182
+ remoteExitCode = Number(marker.slice(4));
183
+ }
184
+ else {
185
+ this.push(pending.subarray(0, end + 1));
186
+ }
187
+ pending = pending.subarray(end + 1);
188
+ }
189
+ callback();
190
+ },
191
+ flush(callback) {
192
+ this.push(pending);
193
+ pending = Buffer.alloc(0);
194
+ callback();
195
+ },
196
+ });
197
+ this.child.stdout.pipe(this, { end: false });
198
+ this.child.stderr.pipe(markers).pipe(this.stderr);
199
+ this.child.once('error', (error) => {
200
+ this.rejectReady(error);
201
+ if (!this.destroyed)
202
+ this.emit('error', error);
203
+ });
204
+ this.child.once('close', (code, signal) => {
205
+ if (remoteExitCode === undefined) {
206
+ const error = new OpenSshError('OpenSSH channel ended without a remote exit status; remote state is unknown', {
207
+ code: 'openssh_transport_error',
208
+ backend: 'openssh',
209
+ operationStatus: 'unknown',
210
+ retryable: false,
211
+ exitCode: code,
212
+ signal,
213
+ });
214
+ this.rejectReady(error);
215
+ if (!this.destroyed)
216
+ this.emit('error', error);
217
+ }
218
+ this.end();
219
+ this.emit('close', remoteExitCode ?? null, signal);
220
+ });
221
+ }
222
+ close() {
223
+ this.destroy();
224
+ }
225
+ _destroy(error, callback) {
226
+ this.rejectReady(error ?? new Error('OpenSSH channel was closed'));
227
+ this.child.kill('SIGKILL');
228
+ this.stderr.destroy();
229
+ callback(error);
230
+ }
231
+ }
232
+ export class OpenSshConnection {
233
+ config;
234
+ info;
235
+ processes = new Map();
236
+ socketIdentity;
237
+ closed = false;
238
+ constructor(config, socket, pid) {
239
+ this.config = config;
240
+ this.socketIdentity = `${socket.dev}:${socket.ino}`;
241
+ this.info = { backend: 'openssh', masterReused: true, identityStatus: 'master_trusted', masterPid: pid };
242
+ }
243
+ static async connect(config, signal) {
244
+ if (process.platform === 'win32' ||
245
+ config.remotePlatform === 'windows' ||
246
+ config.commandShell === 'cmd' ||
247
+ config.commandShell === 'powershell') {
248
+ throw new OpenSshError('The OpenSSH master backend supports local and remote POSIX platforms', {
249
+ code: 'unsupported_backend',
250
+ backend: 'openssh',
251
+ capability: 'platform',
252
+ retryable: false,
253
+ });
254
+ }
255
+ if (!config.controlPath)
256
+ invalidConfig('OpenSSH requires a resolved controlPath');
257
+ const socket = this.socket(config.controlPath);
258
+ const args = this.arguments(config);
259
+ const timeout = config.readyTimeout ?? 30_000;
260
+ const checked = await captureSsh([...args.slice(0, -1), '-O', 'check', config.host], timeout, CONTROL_OUTPUT_LIMIT, signal);
261
+ const pid = Number(/Master running \(pid=(\d+)\)/.exec(checked.stderr)?.[1]);
262
+ if (checked.status !== 0 || !Number.isSafeInteger(pid) || pid <= 0) {
263
+ throw new OpenSshError(`OpenSSH master is unavailable: ${checked.stderr.trim()}`, {
264
+ code: 'master_unavailable',
265
+ backend: 'openssh',
266
+ retryable: false,
267
+ });
268
+ }
269
+ const connection = new OpenSshConnection(config, socket, pid);
270
+ const abort = () => connection.close();
271
+ signal?.addEventListener('abort', abort, { once: true });
272
+ try {
273
+ if (signal?.aborted)
274
+ throw signal.reason;
275
+ const marker = randomBytes(32).toString('hex');
276
+ const command = `printf ${escapeShellArg(`${marker}\\n`)}; id -u; id -un; printf '%s\\n' "$SSH_CONNECTION"`;
277
+ const observed = await captureSsh([...args, command], timeout, CONTROL_OUTPUT_LIMIT, signal, connection.trackProcess);
278
+ const start = observed.stdout.lastIndexOf(`${marker}\n`);
279
+ const lines = observed.stdout.slice(start + marker.length + 1).split('\n');
280
+ if (observed.status !== 0 || start < 0 || !/^\d+$/.test(lines[0]) || !lines[1]) {
281
+ throw new OpenSshError('The existing OpenSSH master did not provide its login identity', {
282
+ code: 'master_identity_unavailable',
283
+ backend: 'openssh',
284
+ retryable: false,
285
+ });
286
+ }
287
+ if (lines[1] !== config.username) {
288
+ throw new OpenSshError('The existing master login does not match the requested user', {
289
+ code: 'master_identity_mismatch',
290
+ backend: 'openssh',
291
+ requestedUser: config.username,
292
+ observedUser: lines[1],
293
+ retryable: false,
294
+ });
295
+ }
296
+ connection.info.observedLogin = {
297
+ uid: Number(lines[0]),
298
+ username: lines[1],
299
+ sshConnection: lines[2] || undefined,
300
+ };
301
+ connection.assertCurrent();
302
+ return connection;
303
+ }
304
+ catch (error) {
305
+ connection.close();
306
+ throw error;
307
+ }
308
+ finally {
309
+ signal?.removeEventListener('abort', abort);
310
+ }
311
+ }
312
+ static socket(controlPath) {
313
+ let socket;
314
+ try {
315
+ socket = fs.statSync(controlPath);
316
+ }
317
+ catch {
318
+ throw new OpenSshError('The existing OpenSSH control socket is unavailable', {
319
+ code: 'master_unavailable',
320
+ backend: 'openssh',
321
+ retryable: false,
322
+ });
323
+ }
324
+ if (!socket.isSocket() || socket.uid !== process.getuid?.()) {
325
+ throw new OpenSshError('ControlPath must refer to a socket owned by the current user', {
326
+ code: 'invalid_control_socket',
327
+ backend: 'openssh',
328
+ retryable: false,
329
+ });
330
+ }
331
+ return socket;
332
+ }
333
+ static arguments(config) {
334
+ return [
335
+ '-F',
336
+ '/dev/null',
337
+ '-S',
338
+ config.controlPath,
339
+ '-T',
340
+ '-o',
341
+ 'ControlMaster=no',
342
+ '-o',
343
+ 'BatchMode=yes',
344
+ '-o',
345
+ 'ProxyCommand=/bin/false',
346
+ '-o',
347
+ 'ProxyUseFdpass=no',
348
+ '-o',
349
+ 'PermitLocalCommand=no',
350
+ '-o',
351
+ 'ClearAllForwardings=yes',
352
+ '-p',
353
+ String(config.port),
354
+ '-l',
355
+ config.username,
356
+ config.host,
357
+ ];
358
+ }
359
+ arguments() {
360
+ this.assertCurrent();
361
+ return OpenSshConnection.arguments(this.config);
362
+ }
363
+ assertCurrent() {
364
+ const socket = OpenSshConnection.socket(this.config.controlPath);
365
+ if (this.closed || `${socket.dev}:${socket.ino}` !== this.socketIdentity) {
366
+ throw new OpenSshError('The OpenSSH master socket changed; reconnect the alias to bind it again', {
367
+ code: 'master_changed',
368
+ backend: 'openssh',
369
+ retryable: false,
370
+ });
371
+ }
372
+ }
373
+ isAlive() {
374
+ try {
375
+ this.assertCurrent();
376
+ process.kill(this.info.masterPid, 0);
377
+ return true;
378
+ }
379
+ catch {
380
+ return false;
381
+ }
382
+ }
383
+ trackProcess = (child, processGroup = false) => {
384
+ this.processes.set(child, processGroup);
385
+ child.once('close', () => this.processes.delete(child));
386
+ if (this.closed)
387
+ this.close();
388
+ };
389
+ open(command) {
390
+ return new OpenSshChannel(this.arguments(), command, this.trackProcess);
391
+ }
392
+ consume(command, consume, timeout) {
393
+ const stream = this.open(command);
394
+ return new Promise((resolve, reject) => {
395
+ let settled = false;
396
+ let stderr = Buffer.alloc(0);
397
+ const finish = (error) => {
398
+ if (settled)
399
+ return;
400
+ settled = true;
401
+ clearTimeout(timer);
402
+ if (error) {
403
+ stream.destroy();
404
+ reject(error);
405
+ }
406
+ else
407
+ resolve();
408
+ };
409
+ const timer = setTimeout(() => finish(new OpenSshError(`OpenSSH command timed out after ${timeout}ms`, {
410
+ code: 'openssh_timeout',
411
+ backend: 'openssh',
412
+ operationStatus: 'unknown',
413
+ timeout,
414
+ retryable: false,
415
+ })), timeout);
416
+ stream.on('data', (chunk) => {
417
+ if (settled)
418
+ return;
419
+ try {
420
+ consume(chunk);
421
+ }
422
+ catch (error) {
423
+ finish(error instanceof Error ? error : new Error(String(error)));
424
+ }
425
+ });
426
+ stream.stderr.on('data', (chunk) => {
427
+ stderr = Buffer.concat([stderr, chunk.subarray(0, Math.max(0, 4096 - stderr.length))]);
428
+ });
429
+ stream.on('error', finish);
430
+ stream.on('close', (code) => finish(code === 0
431
+ ? undefined
432
+ : new OpenSshError(`OpenSSH remote command failed: ${stderr.toString('utf8').trim() || `exit ${code}`}`, {
433
+ code: 'remote_command',
434
+ backend: 'openssh',
435
+ exitCode: code,
436
+ stderr: stderr.toString('utf8'),
437
+ retryable: false,
438
+ })));
439
+ });
440
+ }
441
+ async capture(command, timeout, maxBytes) {
442
+ const chunks = [];
443
+ let size = 0;
444
+ await this.consume(command, (chunk) => {
445
+ size += chunk.length;
446
+ if (size > maxBytes)
447
+ throw new OpenSshError('OpenSSH command exceeded its output budget', {
448
+ code: 'openssh_output_limit',
449
+ backend: 'openssh',
450
+ maxBytes,
451
+ retryable: false,
452
+ });
453
+ chunks.push(chunk);
454
+ }, timeout);
455
+ return Buffer.concat(chunks);
456
+ }
457
+ async stat(remotePath, timeout, follow = true) {
458
+ 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);
460
+ const fields = bytes.toString('utf8').split('\0');
461
+ const values = [Number.parseInt(fields[0], 16), ...fields.slice(1, 6).map(Number)];
462
+ if (fields.length !== 8 || !values.every(Number.isSafeInteger) || values[1] < 0) {
463
+ throw new OpenSshError('OpenSSH stat returned invalid metadata', {
464
+ code: 'invalid_remote_metadata',
465
+ backend: 'openssh',
466
+ retryable: false,
467
+ });
468
+ }
469
+ return {
470
+ mode: values[0],
471
+ size: values[1],
472
+ uid: values[2],
473
+ gid: values[3],
474
+ mtime: values[4],
475
+ atime: values[5],
476
+ stamp: fields[6],
477
+ };
478
+ }
479
+ async hashFile(remotePath, algorithm, timeout, maxBytes, expectedSize) {
480
+ const deadline = Date.now() + timeout;
481
+ const remaining = () => {
482
+ const value = deadline - Date.now();
483
+ if (value <= 0)
484
+ throw new OpenSshError('OpenSSH file verification exhausted its timeout', {
485
+ code: 'openssh_timeout',
486
+ backend: 'openssh',
487
+ operationStatus: 'unknown',
488
+ retryable: false,
489
+ });
490
+ return value;
491
+ };
492
+ const before = await this.stat(remotePath, remaining());
493
+ if ((before.mode & 0o170000) !== 0o100000)
494
+ throw new Error('File hashing requires a regular remote file');
495
+ if ((maxBytes !== undefined && before.size > maxBytes) ||
496
+ (expectedSize !== undefined && before.size !== expectedSize)) {
497
+ throw new Error('Remote file size changed or exceeds the verification byte budget');
498
+ }
499
+ const hash = createHash(algorithm);
500
+ let size = 0;
501
+ await this.consume(`head -c ${before.size + 1} -- ${escapeShellArg(remotePath)}`, (chunk) => {
502
+ size += chunk.length;
503
+ if (size > before.size)
504
+ throw new Error('Remote file grew during verification');
505
+ hash.update(chunk);
506
+ }, remaining());
507
+ const after = await this.stat(remotePath, remaining());
508
+ if (size !== before.size || before.stamp !== after.stamp)
509
+ throw new Error('Remote file changed during verification');
510
+ return hash.digest('hex');
511
+ }
512
+ close() {
513
+ this.closed = true;
514
+ for (const [child, processGroup] of this.processes) {
515
+ if (processGroup && child.pid) {
516
+ try {
517
+ process.kill(-child.pid, 'SIGKILL');
518
+ }
519
+ catch (error) {
520
+ if (error.code !== 'ESRCH')
521
+ console.error('OpenSSH process cleanup failed:', error);
522
+ }
523
+ }
524
+ else
525
+ child.kill('SIGKILL');
526
+ }
527
+ }
528
+ }
@@ -1,5 +1,4 @@
1
- import type { ClientChannel } from 'ssh2';
2
- import type { OperationCancelResult, OperationInfo, OperationReadResult, OperationStartOptions } from './types.js';
1
+ import type { CommandChannel, OperationCancelResult, OperationInfo, OperationReadResult, OperationStartOptions } from './types.js';
3
2
  export declare const DEFAULT_OPERATION_MAX_OUTPUT_BYTES: number;
4
3
  export declare const HARD_OPERATION_MAX_OUTPUT_BYTES: number;
5
4
  export declare const DEFAULT_OPERATION_READ_BYTES: number;
@@ -13,10 +12,11 @@ export declare class OperationStartError extends Error {
13
12
  constructor(message: string, details: Record<string, unknown>);
14
13
  }
15
14
  export interface OperationDependencies {
16
- openStream(alias: string, command: string, marker: string, options: OperationStartOptions, adopt: (stream: ClientChannel) => void): Promise<void>;
17
- cancelRemote(alias: string, pid: number, marker: string, processGroup: boolean, options: OperationStartOptions): Promise<{
15
+ openStream(alias: string, command: string, marker: string, options: OperationStartOptions, adopt: (stream: CommandChannel) => void): Promise<void>;
16
+ cancelRemote(alias: string, pid: number, marker: string, processGroup: boolean, options: OperationStartOptions, processCreatedAt?: string): Promise<{
18
17
  success: boolean;
19
18
  error?: string;
19
+ cancellationStatus?: 'unsupported' | 'unknown';
20
20
  }>;
21
21
  }
22
22
  export declare class OperationManager {