@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.
@@ -1,3 +1,4 @@
1
+ import type { SFTPWrapper } from 'ssh2';
1
2
  export declare const DEFAULT_SFTP_OPERATION_TIMEOUT_MS = 600000;
2
3
  export declare const HARD_SFTP_OPERATION_TIMEOUT_MS = 3600000;
3
4
  export declare class SftpOperationTimeoutError extends Error {
@@ -6,4 +7,18 @@ export declare class SftpOperationTimeoutError extends Error {
6
7
  constructor(timeout: number);
7
8
  }
8
9
  export declare function normalizeSftpOperationTimeout(timeout: number | undefined): number;
9
- export declare function withSftpOperationTimeout<T>(operation: Promise<T>, timeout: number | undefined, onTimeout: () => void): Promise<T>;
10
+ export declare function withSftpOperationTimeout<T>(operation: Promise<T>, timeout: number | undefined, onTimeout: () => void, signal?: AbortSignal): Promise<T>;
11
+ export declare function sftpOperationOutcome(error: unknown): Record<string, unknown>;
12
+ /** 按流记录请求状态,CLOSE 以服务端应答为准 */
13
+ export declare class SftpWriteState {
14
+ readonly remotePath: string;
15
+ acknowledgedBytes: number;
16
+ remoteCreated: boolean;
17
+ private pending;
18
+ private unknownStage?;
19
+ private failureStage?;
20
+ private stage;
21
+ constructor(remotePath: string);
22
+ track(sftp: SFTPWrapper, signal?: AbortSignal): SFTPWrapper;
23
+ outcome(error: unknown): Record<string, unknown>;
24
+ }
@@ -21,7 +21,7 @@ export function normalizeSftpOperationTimeout(timeout) {
21
21
  }
22
22
  return normalized;
23
23
  }
24
- export function withSftpOperationTimeout(operation, timeout, onTimeout) {
24
+ export function withSftpOperationTimeout(operation, timeout, onTimeout, signal) {
25
25
  const normalizedTimeout = normalizeSftpOperationTimeout(timeout);
26
26
  return new Promise((resolve, reject) => {
27
27
  let settled = false;
@@ -31,19 +31,121 @@ export function withSftpOperationTimeout(operation, timeout, onTimeout) {
31
31
  }
32
32
  settled = true;
33
33
  clearTimeout(timer);
34
+ signal?.removeEventListener('abort', abort);
34
35
  callback();
35
36
  };
36
- const timer = setTimeout(() => {
37
- settle(() => {
38
- try {
39
- onTimeout();
40
- }
41
- catch {
42
- // 超时响应优先于释放 SFTP channel 失败
43
- }
44
- reject(new SftpOperationTimeoutError(normalizedTimeout));
45
- });
46
- }, normalizedTimeout);
37
+ const cancel = (error) => settle(() => {
38
+ try {
39
+ onTimeout();
40
+ }
41
+ catch {
42
+ // 保留取消或超时的原始错误
43
+ }
44
+ reject(error);
45
+ });
46
+ const abort = () => cancel(signal?.reason ?? new Error('SFTP operation cancelled'));
47
+ const timer = setTimeout(() => cancel(new SftpOperationTimeoutError(normalizedTimeout)), normalizedTimeout);
47
48
  operation.then((value) => settle(() => resolve(value)), (error) => settle(() => reject(error)));
49
+ signal?.addEventListener('abort', abort, { once: true });
50
+ if (signal?.aborted) {
51
+ abort();
52
+ }
48
53
  });
49
54
  }
55
+ export function sftpOperationOutcome(error) {
56
+ if (!error || typeof error !== 'object') {
57
+ return {};
58
+ }
59
+ const details = 'details' in error ? error.details : undefined;
60
+ if (details && typeof details === 'object' && 'operationStatus' in details) {
61
+ return details;
62
+ }
63
+ return sftpOperationOutcome('cause' in error ? error.cause : undefined);
64
+ }
65
+ /** 按流记录请求状态,CLOSE 以服务端应答为准 */
66
+ export class SftpWriteState {
67
+ remotePath;
68
+ acknowledgedBytes = 0;
69
+ remoteCreated = false;
70
+ pending = 0;
71
+ unknownStage;
72
+ failureStage;
73
+ stage = 'open';
74
+ constructor(remotePath) {
75
+ this.remotePath = remotePath;
76
+ }
77
+ track(sftp, signal) {
78
+ return new Proxy(sftp, {
79
+ get: (target, property, receiver) => {
80
+ const method = Reflect.get(target, property);
81
+ if (typeof method !== 'function') {
82
+ return method;
83
+ }
84
+ if (property === 'createWriteStream') {
85
+ return (...args) => Reflect.apply(method, receiver, args);
86
+ }
87
+ if (property !== 'open' &&
88
+ property !== 'write' &&
89
+ property !== 'close' &&
90
+ property !== 'rename' &&
91
+ property !== 'ext_openssh_rename') {
92
+ return method.bind(target);
93
+ }
94
+ return (...args) => {
95
+ const stage = property === 'ext_openssh_rename' ? 'rename' : property;
96
+ const callback = args.pop();
97
+ if (signal?.aborted && property !== 'close') {
98
+ callback(signal.reason ?? new Error('SFTP operation cancelled'));
99
+ return;
100
+ }
101
+ this.stage = stage;
102
+ ++this.pending;
103
+ try {
104
+ return Reflect.apply(method, target, [
105
+ ...args,
106
+ (error, ...values) => {
107
+ --this.pending;
108
+ if (error) {
109
+ this.failureStage ??= stage;
110
+ const code = typeof error === 'object' && 'code' in error ? error.code : undefined;
111
+ // 数值 STATUS 为明确应答,6/7 表示连接丢失
112
+ if (typeof code !== 'number' || code === 6 || code === 7) {
113
+ this.unknownStage ??= stage;
114
+ }
115
+ }
116
+ else if (stage === 'write') {
117
+ this.acknowledgedBytes += Number(values[0]);
118
+ }
119
+ else if (stage === 'open') {
120
+ this.remoteCreated = true;
121
+ }
122
+ if (signal?.aborted && stage === 'open' && !error) {
123
+ target.end();
124
+ callback(signal.reason ?? new Error('SFTP operation cancelled'));
125
+ }
126
+ else {
127
+ callback(error, ...values);
128
+ }
129
+ },
130
+ ]);
131
+ }
132
+ catch (error) {
133
+ --this.pending;
134
+ this.failureStage ??= stage;
135
+ throw error;
136
+ }
137
+ };
138
+ },
139
+ });
140
+ }
141
+ outcome(error) {
142
+ return {
143
+ ...sftpOperationOutcome(error),
144
+ operationStatus: this.pending > 0 || this.unknownStage ? 'unknown' : 'failed',
145
+ retryable: false,
146
+ remotePath: this.remotePath,
147
+ failureStage: this.unknownStage ?? this.failureStage ?? this.stage,
148
+ acknowledgedBytes: this.acknowledgedBytes,
149
+ };
150
+ }
151
+ }
@@ -69,7 +69,7 @@ function parseHostPort(s) {
69
69
  * 注意:只解析第一跳,不支持逗号分隔的多跳链路
70
70
  */
71
71
  export function parseProxyJump(proxyJump) {
72
- if (!proxyJump) {
72
+ if (!proxyJump || proxyJump.trim().toLowerCase() === 'none') {
73
73
  return null;
74
74
  }
75
75
  // 取第一跳(如果有逗号分隔)
@@ -7,8 +7,8 @@ import * as fs from 'fs';
7
7
  import * as os from 'os';
8
8
  import * as path from 'path';
9
9
  import { z } from 'zod';
10
- import { sessionManager } from '../session-manager.js';
11
10
  import { OpenSshError, resolveOpenSshConfig } from '../openssh.js';
11
+ import { sessionManager } from '../session-manager.js';
12
12
  import { parseProxyJump, parseSSHConfig } from '../ssh-config.js';
13
13
  import { sshPortSchema } from './schema.js';
14
14
  import { expandTilde, formatError, formatResult } from './utils.js';
@@ -64,7 +64,19 @@ function loadTemplates() {
64
64
  if (!source) {
65
65
  return {};
66
66
  }
67
- const parsed = JSON.parse(source);
67
+ let parsed;
68
+ try {
69
+ parsed = JSON.parse(source);
70
+ }
71
+ catch (error) {
72
+ const message = error instanceof Error ? error.message : '';
73
+ const location = /(?:at position \d+(?: \(line \d+ column \d+\))?|\(line \d+ column \d+\))$/.exec(message)?.[0];
74
+ // JSON parser errors can contain credentials, including through Error.cause.
75
+ // eslint-disable-next-line preserve-caught-error
76
+ throw new Error('Invalid JSON in ' +
77
+ `${fromEnv !== undefined ? 'SSH_MCP_TEMPLATES' : '~/.mcp-ssh/templates.json'}` +
78
+ `${location ? ` (${location})` : ''}`);
79
+ }
68
80
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
69
81
  throw new Error('SSH templates must be an object keyed by template name');
70
82
  }
@@ -209,7 +221,7 @@ async function handleConnect(args) {
209
221
  const remotePlatform = args.remotePlatform ?? template.remotePlatform ?? 'posix';
210
222
  const commandShell = args.commandShell ?? template.commandShell ?? (remotePlatform === 'windows' ? 'powershell' : 'posix');
211
223
  if ((remotePlatform === 'windows') !== (commandShell !== 'posix')) {
212
- throw new Error('commandShell must match remotePlatform');
224
+ return formatError(new Error('commandShell must match remotePlatform'));
213
225
  }
214
226
  const remotePathStyle = args.remotePathStyle ?? template.remotePathStyle ?? (remotePlatform === 'windows' ? 'win32' : 'posix');
215
227
  const rsyncExecutable = args.rsyncExecutable ?? template.rsyncExecutable;
@@ -220,6 +232,7 @@ async function handleConnect(args) {
220
232
  const env = mergeEnv(template.env, args.env);
221
233
  const keepaliveInterval = args.keepaliveInterval ?? template.keepaliveInterval;
222
234
  const readyTimeout = args.readyTimeout ?? template.readyTimeout;
235
+ let preparationGeneration;
223
236
  let jumpHostResolved;
224
237
  if (backend === 'openssh') {
225
238
  if (password !== undefined ||
@@ -227,25 +240,26 @@ async function handleConnect(args) {
227
240
  agent !== undefined ||
228
241
  args.jumpHost ||
229
242
  template.jumpHost) {
230
- throw new OpenSshError('OpenSSH master reuse does not accept new authentication or jumpHost parameters', {
243
+ return formatError(new OpenSshError('OpenSSH master reuse does not accept new authentication or jumpHost parameters', {
231
244
  code: 'unsupported_backend',
232
245
  backend,
233
246
  capability: 'new_authentication',
234
247
  retryable: false,
235
- });
248
+ }));
236
249
  }
237
250
  if (remotePlatform !== 'posix' ||
238
251
  commandShell !== 'posix' ||
239
252
  remotePathStyle !== 'posix' ||
240
253
  (rsyncProfile && rsyncProfile !== 'posix')) {
241
- throw new OpenSshError('OpenSSH master reuse requires a POSIX remote shell and path style', {
254
+ return formatError(new OpenSshError('OpenSSH master reuse requires a POSIX remote shell and path style', {
242
255
  code: 'unsupported_backend',
243
256
  backend,
244
257
  capability: 'platform',
245
258
  retryable: false,
246
- });
259
+ }));
247
260
  }
248
- const resolved = await resolveOpenSshConfig({
261
+ const preparationAlias = requestedAlias ?? (user && host ? `${user}@${host}:${port ?? 22}` : undefined);
262
+ const prepared = await sessionManager.prepareConnection(preparationAlias, (signal) => resolveOpenSshConfig({
249
263
  configHost,
250
264
  configPath,
251
265
  host,
@@ -253,18 +267,20 @@ async function handleConnect(args) {
253
267
  port,
254
268
  controlPath,
255
269
  readyTimeout,
256
- });
270
+ }, signal));
271
+ const { result: resolved, generation } = prepared;
272
+ preparationGeneration = generation;
257
273
  host = resolved.host;
258
274
  user = resolved.username;
259
275
  port = resolved.port;
260
276
  controlPath = resolved.controlPath;
261
277
  }
262
278
  else if (controlPath !== undefined) {
263
- throw new OpenSshError('controlPath requires backend=openssh', {
279
+ return formatError(new OpenSshError('controlPath requires backend=openssh', {
264
280
  code: 'invalid_openssh_config',
265
281
  backend,
266
282
  retryable: false,
267
- });
283
+ }));
268
284
  }
269
285
  else if (configHost) {
270
286
  const allHosts = parseSSHConfig(configPath);
@@ -288,7 +304,7 @@ async function handleConnect(args) {
288
304
  agent = configAgent;
289
305
  }
290
306
  // 解析 ProxyJump(支持 user@host:port 格式)
291
- if (hostConfig.proxyJump) {
307
+ if (hostConfig.proxyJump && !(args.jumpHost ?? template.jumpHost)) {
292
308
  const parsed = parseProxyJump(hostConfig.proxyJump);
293
309
  if (parsed) {
294
310
  // 先尝试在 config 中查找对应的 Host
@@ -383,7 +399,7 @@ async function handleConnect(args) {
383
399
  keepaliveInterval,
384
400
  readyTimeout,
385
401
  jumpHost,
386
- });
402
+ }, preparationGeneration);
387
403
  const connected = sessionManager.getSessionConnectionInfo(alias);
388
404
  return formatResult({
389
405
  success: true,
@@ -401,6 +417,8 @@ async function handleConnect(args) {
401
417
  commandShell: connected.commandShell,
402
418
  remotePathStyle: connected.remotePathStyle,
403
419
  keyAclStatus: connected.keyAclStatus,
420
+ hostKey: connected.hostKey,
421
+ hostKeys: connected.hostKeys,
404
422
  host: connected.host,
405
423
  port: connected.port,
406
424
  defaultEnvKeys: connected.defaultEnvKeys,