@pyrokine/mcp-ssh 2.3.2 → 2.4.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.
@@ -0,0 +1,402 @@
1
+ import { randomBytes, randomUUID } from 'node:crypto';
2
+ export const DEFAULT_OPERATION_MAX_OUTPUT_BYTES = 1024 * 1024;
3
+ export const HARD_OPERATION_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
4
+ export const DEFAULT_OPERATION_READ_BYTES = 64 * 1024;
5
+ export const HARD_OPERATION_READ_BYTES = 1024 * 1024;
6
+ export const DEFAULT_OPERATION_RETENTION_MS = 60 * 60_000;
7
+ export const MAX_OPERATION_RETENTION_MS = 24 * 60 * 60_000;
8
+ const MARKER_PREFIX = '__MCP_SSH_OPERATION__';
9
+ const MARKER_LINE_LIMIT = 512;
10
+ export class OperationManager {
11
+ dependencies;
12
+ now;
13
+ operations = new Map();
14
+ sweeper;
15
+ constructor(dependencies, now = Date.now) {
16
+ this.dependencies = dependencies;
17
+ this.now = now;
18
+ this.sweeper = setInterval(() => this.sweepExpired(), 60_000);
19
+ this.sweeper.unref?.();
20
+ }
21
+ async start(alias, command, options = {}) {
22
+ const operationId = `op_${randomUUID()}`;
23
+ const marker = randomBytes(32).toString('hex');
24
+ const maxOutputBytes = this.normalizeMaxOutputBytes(options.maxOutputBytes);
25
+ const retentionMs = this.normalizeRetentionMs(options.retentionMs);
26
+ const stream = await this.dependencies.openStream(alias, command, marker, options);
27
+ const record = {
28
+ operationId,
29
+ alias,
30
+ command,
31
+ marker,
32
+ status: 'starting',
33
+ pid: null,
34
+ processGroup: false,
35
+ markerVerified: false,
36
+ cancelRequested: false,
37
+ cancelInFlight: false,
38
+ pendingTermination: null,
39
+ startedAt: this.now(),
40
+ finishedAt: null,
41
+ expiresAt: null,
42
+ retentionMs,
43
+ exitCode: null,
44
+ signal: null,
45
+ stdout: Buffer.alloc(0),
46
+ stderr: Buffer.alloc(0),
47
+ stdoutBytes: 0,
48
+ stderrBytes: 0,
49
+ stdoutTruncated: false,
50
+ stderrTruncated: false,
51
+ maxOutputBytes,
52
+ markerBuffer: Buffer.alloc(0),
53
+ stream,
54
+ options: { ...options, maxOutputBytes, retentionMs },
55
+ };
56
+ this.operations.set(operationId, record);
57
+ this.attachStream(record);
58
+ return this.info(record);
59
+ }
60
+ status(operationId) {
61
+ return this.info(this.requireOperation(operationId));
62
+ }
63
+ read(operationId, options = {}) {
64
+ const record = this.requireOperation(operationId);
65
+ const maxReadBytes = this.normalizeReadBytes(options.maxBytes);
66
+ const stdoutOffset = this.normalizeOffset(options.stdoutOffset, record.stdout.length, 'stdoutOffset');
67
+ const stderrOffset = this.normalizeOffset(options.stderrOffset, record.stderr.length, 'stderrOffset');
68
+ this.ensureUtf8Boundary(record.stdout, stdoutOffset, 'stdoutOffset');
69
+ this.ensureUtf8Boundary(record.stderr, stderrOffset, 'stderrOffset');
70
+ const stdoutEnd = this.utf8SafeEnd(record.stdout, stdoutOffset, Math.min(record.stdout.length, stdoutOffset + maxReadBytes), 'stdout');
71
+ const stdout = record.stdout.subarray(stdoutOffset, stdoutEnd);
72
+ const remaining = maxReadBytes - stdout.length;
73
+ const stderrEnd = this.utf8SafeEnd(record.stderr, stderrOffset, Math.min(record.stderr.length, stderrOffset + remaining), 'stderr');
74
+ const stderr = record.stderr.subarray(stderrOffset, stderrEnd);
75
+ return {
76
+ ...this.info(record),
77
+ stdout: stdout.toString('utf8'),
78
+ stderr: stderr.toString('utf8'),
79
+ stdoutOffset,
80
+ stderrOffset,
81
+ nextStdoutOffset: stdoutEnd,
82
+ nextStderrOffset: stderrEnd,
83
+ readBytes: stdout.length + stderr.length,
84
+ maxReadBytes,
85
+ };
86
+ }
87
+ async cancel(operationId) {
88
+ const record = this.requireOperation(operationId);
89
+ if (record.status !== 'starting' && record.status !== 'running') {
90
+ return {
91
+ ...this.info(record),
92
+ success: false,
93
+ cancelRequested: record.cancelRequested,
94
+ retryable: false,
95
+ verificationError: `Operation is ${record.status}`,
96
+ };
97
+ }
98
+ if (!record.markerVerified || record.pid === null) {
99
+ return {
100
+ ...this.info(record),
101
+ success: false,
102
+ cancelRequested: false,
103
+ retryable: true,
104
+ verificationError: 'Remote operation marker has not been verified',
105
+ };
106
+ }
107
+ if (record.cancelInFlight) {
108
+ return {
109
+ ...this.info(record),
110
+ success: false,
111
+ cancelRequested: record.cancelRequested,
112
+ retryable: true,
113
+ verificationError: 'Remote cancellation is already in progress',
114
+ };
115
+ }
116
+ record.cancelInFlight = true;
117
+ let result;
118
+ try {
119
+ result = await this.dependencies.cancelRemote(record.alias, record.pid, record.marker, record.processGroup, record.options);
120
+ }
121
+ catch (error) {
122
+ record.cancelInFlight = false;
123
+ this.finishPendingTermination(record);
124
+ throw error;
125
+ }
126
+ record.cancelInFlight = false;
127
+ if (result.success) {
128
+ record.cancelRequested = true;
129
+ }
130
+ this.finishPendingTermination(record);
131
+ return {
132
+ ...this.info(record),
133
+ success: result.success,
134
+ cancelRequested: record.cancelRequested,
135
+ retryable: !result.success,
136
+ ...(result.error ? { verificationError: result.error } : {}),
137
+ };
138
+ }
139
+ list(alias) {
140
+ this.sweepExpired();
141
+ return Array.from(this.operations.values())
142
+ .filter((record) => alias === undefined || record.alias === alias)
143
+ .map((record) => this.info(record));
144
+ }
145
+ markAliasDisconnected(alias) {
146
+ for (const record of this.operations.values()) {
147
+ if (record.alias === alias && (record.status === 'starting' || record.status === 'running')) {
148
+ record.status = 'unknown';
149
+ record.error = 'SSH session disconnected before remote process state could be confirmed';
150
+ this.finish(record);
151
+ }
152
+ }
153
+ }
154
+ sweepExpired() {
155
+ const now = this.now();
156
+ for (const [operationId, record] of this.operations) {
157
+ if (record.expiresAt !== null && record.expiresAt <= now) {
158
+ this.operations.delete(operationId);
159
+ }
160
+ }
161
+ }
162
+ close() {
163
+ clearInterval(this.sweeper);
164
+ }
165
+ attachStream(record) {
166
+ record.stream.on('data', (data) => {
167
+ record.stdoutBytes += data.length;
168
+ this.appendOutput(record, 'stdout', data);
169
+ });
170
+ record.stream.stderr.on('data', (data) => {
171
+ this.consumeMarker(record, data);
172
+ });
173
+ record.stream.on('error', (error) => {
174
+ if (record.cancelInFlight) {
175
+ record.pendingTermination ??= { type: 'error', error };
176
+ return;
177
+ }
178
+ this.finishStreamError(record, error);
179
+ });
180
+ record.stream.on('close', (code, signal) => {
181
+ const close = { type: 'close', code, signal: signal ?? null };
182
+ if (record.cancelInFlight) {
183
+ record.pendingTermination ??= close;
184
+ return;
185
+ }
186
+ this.finishStreamClose(record, close.code, close.signal);
187
+ });
188
+ }
189
+ finishPendingTermination(record) {
190
+ const pending = record.pendingTermination;
191
+ record.pendingTermination = null;
192
+ if (!pending) {
193
+ return;
194
+ }
195
+ if (pending.type === 'error') {
196
+ this.finishStreamError(record, pending.error);
197
+ return;
198
+ }
199
+ this.finishStreamClose(record, pending.code, pending.signal);
200
+ }
201
+ finishStreamError(record, error) {
202
+ if (record.status === 'unknown' || record.finishedAt !== null) {
203
+ return;
204
+ }
205
+ record.status = 'failed';
206
+ record.error = error.message;
207
+ this.finish(record);
208
+ }
209
+ finishStreamClose(record, code, signal) {
210
+ if (record.status === 'unknown' || record.finishedAt !== null) {
211
+ return;
212
+ }
213
+ record.exitCode = code;
214
+ record.signal = signal;
215
+ if (record.cancelRequested) {
216
+ record.status = 'cancelled';
217
+ }
218
+ else if (!record.markerVerified) {
219
+ record.status = 'failed';
220
+ record.error = 'Remote operation exited before its marker was verified';
221
+ }
222
+ else {
223
+ record.status = code === 0 ? 'completed' : 'failed';
224
+ }
225
+ this.finish(record);
226
+ }
227
+ consumeMarker(record, data) {
228
+ if (record.markerVerified) {
229
+ record.stderrBytes += data.length;
230
+ this.appendOutput(record, 'stderr', data);
231
+ return;
232
+ }
233
+ record.markerBuffer = Buffer.concat([record.markerBuffer, data]);
234
+ const newline = record.markerBuffer.indexOf(0x0a);
235
+ if (newline < 0) {
236
+ if (record.markerBuffer.length > MARKER_LINE_LIMIT) {
237
+ record.status = 'failed';
238
+ record.error = 'Remote operation marker exceeded the allowed length';
239
+ record.stderrBytes += record.markerBuffer.length;
240
+ this.appendOutput(record, 'stderr', record.markerBuffer);
241
+ record.markerBuffer = Buffer.alloc(0);
242
+ }
243
+ return;
244
+ }
245
+ const line = record.markerBuffer.subarray(0, newline).toString('utf8').trim();
246
+ const remainder = record.markerBuffer.subarray(newline + 1);
247
+ record.markerBuffer = Buffer.alloc(0);
248
+ const expectedPrefix = `${MARKER_PREFIX}:${record.marker}:`;
249
+ if (!line.startsWith(expectedPrefix)) {
250
+ record.status = 'failed';
251
+ record.error = 'Remote operation marker did not match the local operation';
252
+ const invalidMarker = Buffer.from(`${line}\n`);
253
+ record.stderrBytes += invalidMarker.length + remainder.length;
254
+ this.appendOutput(record, 'stderr', invalidMarker);
255
+ this.appendOutput(record, 'stderr', remainder);
256
+ return;
257
+ }
258
+ const [pidText, groupText] = line.slice(expectedPrefix.length).split(':');
259
+ const pid = Number(pidText);
260
+ if (!Number.isSafeInteger(pid) || pid <= 0 || (groupText !== '0' && groupText !== '1')) {
261
+ record.status = 'failed';
262
+ record.error = 'Remote operation marker contained invalid process metadata';
263
+ return;
264
+ }
265
+ record.pid = pid;
266
+ record.processGroup = groupText === '1';
267
+ record.markerVerified = true;
268
+ record.status = 'running';
269
+ record.stderrBytes += remainder.length;
270
+ this.appendOutput(record, 'stderr', remainder);
271
+ }
272
+ appendOutput(record, stream, data) {
273
+ const storedBytes = record.stdout.length + record.stderr.length;
274
+ const available = Math.max(0, record.maxOutputBytes - storedBytes);
275
+ const stored = data.subarray(0, available);
276
+ record[stream] = Buffer.concat([record[stream], stored]);
277
+ if (stored.length < data.length) {
278
+ if (stream === 'stdout') {
279
+ record.stdoutTruncated = true;
280
+ }
281
+ else {
282
+ record.stderrTruncated = true;
283
+ }
284
+ }
285
+ }
286
+ finish(record) {
287
+ if (record.finishedAt !== null) {
288
+ return;
289
+ }
290
+ record.finishedAt = this.now();
291
+ record.expiresAt = record.finishedAt + record.retentionMs;
292
+ }
293
+ info(record) {
294
+ return {
295
+ operationId: record.operationId,
296
+ alias: record.alias,
297
+ status: record.status,
298
+ pid: record.pid,
299
+ processGroup: record.processGroup,
300
+ markerVerified: record.markerVerified,
301
+ cancelRequested: record.cancelRequested,
302
+ startedAt: record.startedAt,
303
+ finishedAt: record.finishedAt,
304
+ expiresAt: record.expiresAt,
305
+ retentionMs: record.retentionMs,
306
+ exitCode: record.exitCode,
307
+ signal: record.signal,
308
+ stdoutBytes: record.stdoutBytes,
309
+ stderrBytes: record.stderrBytes,
310
+ stdoutStoredBytes: record.stdout.length,
311
+ stderrStoredBytes: record.stderr.length,
312
+ stdoutTruncated: record.stdoutTruncated,
313
+ stderrTruncated: record.stderrTruncated,
314
+ maxOutputBytes: record.maxOutputBytes,
315
+ ...(record.error ? { error: record.error } : {}),
316
+ };
317
+ }
318
+ requireOperation(operationId) {
319
+ this.sweepExpired();
320
+ const record = this.operations.get(operationId);
321
+ if (!record) {
322
+ throw new Error(`Operation '${operationId}' not found or expired`);
323
+ }
324
+ return record;
325
+ }
326
+ normalizeMaxOutputBytes(value) {
327
+ const normalized = value ?? DEFAULT_OPERATION_MAX_OUTPUT_BYTES;
328
+ if (!Number.isSafeInteger(normalized) || normalized <= 0 || normalized > HARD_OPERATION_MAX_OUTPUT_BYTES) {
329
+ throw new Error(`maxOutputBytes must be between 1 and ${HARD_OPERATION_MAX_OUTPUT_BYTES}`);
330
+ }
331
+ return normalized;
332
+ }
333
+ normalizeReadBytes(value) {
334
+ const normalized = value ?? DEFAULT_OPERATION_READ_BYTES;
335
+ if (!Number.isSafeInteger(normalized) || normalized <= 0 || normalized > HARD_OPERATION_READ_BYTES) {
336
+ throw new Error(`maxBytes must be between 1 and ${HARD_OPERATION_READ_BYTES}`);
337
+ }
338
+ return normalized;
339
+ }
340
+ normalizeRetentionMs(value) {
341
+ const normalized = value ?? DEFAULT_OPERATION_RETENTION_MS;
342
+ if (!Number.isSafeInteger(normalized) || normalized <= 0 || normalized > MAX_OPERATION_RETENTION_MS) {
343
+ throw new Error(`retentionMs must be between 1 and ${MAX_OPERATION_RETENTION_MS}`);
344
+ }
345
+ return normalized;
346
+ }
347
+ normalizeOffset(value, length, field) {
348
+ const normalized = value ?? 0;
349
+ if (!Number.isSafeInteger(normalized) || normalized < 0 || normalized > length) {
350
+ throw new Error(`${field} must be between 0 and ${length}`);
351
+ }
352
+ return normalized;
353
+ }
354
+ ensureUtf8Boundary(buffer, offset, field) {
355
+ if (offset < buffer.length && this.isUtf8ContinuationByte(buffer[offset])) {
356
+ throw new Error(`${field} must point to a UTF-8 character boundary`);
357
+ }
358
+ }
359
+ utf8SafeEnd(buffer, start, requestedEnd, stream) {
360
+ const limitedByMaxBytes = requestedEnd < buffer.length;
361
+ let end = requestedEnd;
362
+ if (limitedByMaxBytes) {
363
+ while (end > start && this.isUtf8ContinuationByte(buffer[end])) {
364
+ --end;
365
+ }
366
+ }
367
+ end = this.trimIncompleteUtf8Sequence(buffer, start, end);
368
+ if (end === start && requestedEnd > start && limitedByMaxBytes) {
369
+ throw new Error(`maxBytes is too small to read the next UTF-8 character from ${stream}`);
370
+ }
371
+ return end;
372
+ }
373
+ trimIncompleteUtf8Sequence(buffer, start, end) {
374
+ if (end <= start) {
375
+ return end;
376
+ }
377
+ let sequenceStart = end - 1;
378
+ while (sequenceStart > start && this.isUtf8ContinuationByte(buffer[sequenceStart])) {
379
+ --sequenceStart;
380
+ }
381
+ const expectedLength = this.utf8SequenceLength(buffer[sequenceStart]);
382
+ return sequenceStart + expectedLength > end ? sequenceStart : end;
383
+ }
384
+ utf8SequenceLength(value) {
385
+ if ((value & 0x80) === 0) {
386
+ return 1;
387
+ }
388
+ if ((value & 0xe0) === 0xc0) {
389
+ return 2;
390
+ }
391
+ if ((value & 0xf0) === 0xe0) {
392
+ return 3;
393
+ }
394
+ if ((value & 0xf8) === 0xf0) {
395
+ return 4;
396
+ }
397
+ return 1;
398
+ }
399
+ isUtf8ContinuationByte(value) {
400
+ return (value & 0xc0) === 0x80;
401
+ }
402
+ }
@@ -16,6 +16,7 @@ export declare class PtyManager {
16
16
  private idCounter;
17
17
  private readonly defaultBufferSize;
18
18
  private readonly idleTimeoutMs;
19
+ private readonly closedRetentionMs;
19
20
  private idleSweeper;
20
21
  constructor();
21
22
  start(deps: PtyDependencies, alias: string, command: string, options?: PtyOptions): Promise<string>;
@@ -12,6 +12,7 @@ export class PtyManager {
12
12
  defaultBufferSize = 1024 * 1024; // 1MB
13
13
  // 默认 idle timeout 1 小时,超时未读的 pty 自动回收
14
14
  idleTimeoutMs = Number(process.env.SSH_MCP_PTY_IDLE_TIMEOUT_MS) || 3600_000;
15
+ closedRetentionMs = Number(process.env.SSH_MCP_PTY_CLOSED_RETENTION_MS) || 300_000;
15
16
  idleSweeper = null;
16
17
  constructor() {
17
18
  this.startIdleSweeper();
@@ -40,6 +41,7 @@ export class PtyManager {
40
41
  unreadRawBytes: 0,
41
42
  maxBufferSize,
42
43
  active: true,
44
+ closedAt: null,
43
45
  };
44
46
  // 监听输出数据
45
47
  stream.on('data', (data) => {
@@ -59,17 +61,15 @@ export class PtyManager {
59
61
  }
60
62
  });
61
63
  stream.on('close', () => {
62
- ptySession.active = false;
63
- this.sessions.delete(ptyId);
64
- try {
65
- terminal.dispose();
66
- }
67
- catch (e) {
68
- console.warn(`PTY ${ptyId} terminal dispose failed:`, e.message);
64
+ if (!this.sessions.has(ptyId)) {
65
+ return;
69
66
  }
67
+ ptySession.active = false;
68
+ ptySession.closedAt = Date.now();
70
69
  });
71
70
  stream.on('error', (err) => {
72
71
  ptySession.active = false;
72
+ ptySession.closedAt = Date.now();
73
73
  terminal.write(`\n[PTY Error: ${err.message}]`);
74
74
  });
75
75
  this.sessions.set(ptyId, ptySession);
@@ -197,6 +197,10 @@ export class PtyManager {
197
197
  const now = Date.now();
198
198
  for (const [id, session] of this.sessions) {
199
199
  if (!session.active) {
200
+ const closedAt = session.closedAt ?? session.lastOutputAt ?? session.createdAt;
201
+ if (now - Math.max(closedAt, session.lastReadAt) > this.closedRetentionMs) {
202
+ this.close(id);
203
+ }
200
204
  continue;
201
205
  }
202
206
  if (now - session.lastReadAt > this.idleTimeoutMs) {
@@ -8,7 +8,7 @@
8
8
  * - 会话持久化
9
9
  */
10
10
  import { Client, SFTPWrapper } from 'ssh2';
11
- import { ExecOptions, ExecResult, PortForwardInfo, PtyOptions, PtySessionInfo, SSHConnectionConfig, SSHSessionInfo } from './types.js';
11
+ import { ExecOptions, ExecResult, ExternalTransferCapability, ForwardCloseOptions, ForwardCloseResult, OperationCancelResult, OperationInfo, OperationReadResult, OperationStartOptions, PortForwardInfo, PtyOptions, PtySessionInfo, SSHConnectionConfig, SSHSessionBrief, SSHSessionDetail } from './types.js';
12
12
  interface SSHSession {
13
13
  client: Client;
14
14
  config: SSHConnectionConfig;
@@ -26,6 +26,7 @@ export declare class SessionManager {
26
26
  private connectInFlight;
27
27
  private readonly ptyManager;
28
28
  private readonly forwardManager;
29
+ private readonly operationManager;
29
30
  private readonly persistPath;
30
31
  private defaultKeepaliveInterval;
31
32
  private defaultKeepaliveCountMax;
@@ -52,14 +53,22 @@ export declare class SessionManager {
52
53
  * 获取会话
53
54
  */
54
55
  getSession(alias: string): SSHSession;
55
- /**
56
- * 列出所有会话
57
- */
58
- listSessions(): SSHSessionInfo[];
56
+ listSessions(): SSHSessionBrief[];
57
+ listSessionDetails(): SSHSessionDetail[];
58
+ getExternalTransferCapability(alias: string): ExternalTransferCapability;
59
59
  /**
60
60
  * 执行命令
61
61
  */
62
62
  exec(alias: string, command: string, options?: ExecOptions): Promise<ExecResult>;
63
+ operationStart(alias: string, command: string, options?: OperationStartOptions): Promise<OperationInfo>;
64
+ operationStatus(operationId: string): OperationInfo;
65
+ operationRead(operationId: string, options?: {
66
+ stdoutOffset?: number;
67
+ stderrOffset?: number;
68
+ maxBytes?: number;
69
+ }): OperationReadResult;
70
+ operationCancel(operationId: string): Promise<OperationCancelResult>;
71
+ operationList(alias?: string): OperationInfo[];
63
72
  /**
64
73
  * 以其他用户身份执行命令
65
74
  *
@@ -106,8 +115,10 @@ export declare class SessionManager {
106
115
  localPort: number;
107
116
  }>;
108
117
  forwardRemote(alias: string, remotePort: number, localHost: string, localPort: number, remoteHost?: string): Promise<string>;
109
- forwardClose(forwardId: string): boolean;
118
+ forwardClose(forwardId: string, options?: ForwardCloseOptions): Promise<ForwardCloseResult>;
110
119
  forwardList(): PortForwardInfo[];
120
+ private isSshAgentAvailable;
121
+ private isOpenSshKeyPathUsable;
111
122
  private sessionIdentity;
112
123
  private configIdentity;
113
124
  private resultMetadata;
@@ -116,6 +127,8 @@ export declare class SessionManager {
116
127
  private emptyOutputFailureMetadata;
117
128
  private outputMetadata;
118
129
  private normalizeMaxOutputSize;
130
+ private openOperationStream;
131
+ private cancelRemoteOperation;
119
132
  private execDirect;
120
133
  private connectInternal;
121
134
  /**
@@ -140,10 +153,8 @@ export declare class SessionManager {
140
153
  */
141
154
  private scheduleReconnect;
142
155
  private createCommandTimeoutError;
143
- /**
144
- * 根据错误类型生成排查建议
145
- */
146
- private diagnoseConnectionError;
156
+ private createConnectionError;
157
+ private classifyConnectionError;
147
158
  /**
148
159
  * 转义 shell 参数(使用单引号方式,防止命令注入)
149
160
  * 委托给 tools/utils.ts 的共享实现