@pyrokine/mcp-ssh 3.1.0 → 3.2.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.
@@ -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,111 @@ 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) {
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
+ this.stage = stage;
98
+ ++this.pending;
99
+ try {
100
+ return Reflect.apply(method, target, [
101
+ ...args,
102
+ (error, ...values) => {
103
+ --this.pending;
104
+ if (error) {
105
+ this.failureStage ??= stage;
106
+ const code = typeof error === 'object' && 'code' in error ? error.code : undefined;
107
+ // 数值 STATUS 为明确应答,6/7 表示连接丢失
108
+ if (typeof code !== 'number' || code === 6 || code === 7) {
109
+ this.unknownStage ??= stage;
110
+ }
111
+ }
112
+ else if (stage === 'write') {
113
+ this.acknowledgedBytes += Number(values[0]);
114
+ }
115
+ else if (stage === 'open') {
116
+ this.remoteCreated = true;
117
+ }
118
+ callback(error, ...values);
119
+ },
120
+ ]);
121
+ }
122
+ catch (error) {
123
+ --this.pending;
124
+ this.failureStage ??= stage;
125
+ throw error;
126
+ }
127
+ };
128
+ },
129
+ });
130
+ }
131
+ outcome(error) {
132
+ return {
133
+ ...sftpOperationOutcome(error),
134
+ operationStatus: this.pending > 0 || this.unknownStage ? 'unknown' : 'failed',
135
+ retryable: false,
136
+ remotePath: this.remotePath,
137
+ failureStage: this.unknownStage ?? this.failureStage ?? this.stage,
138
+ acknowledgedBytes: this.acknowledgedBytes,
139
+ };
140
+ }
141
+ }
@@ -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
  }
@@ -288,7 +300,7 @@ async function handleConnect(args) {
288
300
  agent = configAgent;
289
301
  }
290
302
  // 解析 ProxyJump(支持 user@host:port 格式)
291
- if (hostConfig.proxyJump) {
303
+ if (hostConfig.proxyJump && !(args.jumpHost ?? template.jumpHost)) {
292
304
  const parsed = parseProxyJump(hostConfig.proxyJump);
293
305
  if (parsed) {
294
306
  // 先尝试在 config 中查找对应的 Host
@@ -401,6 +413,8 @@ async function handleConnect(args) {
401
413
  commandShell: connected.commandShell,
402
414
  remotePathStyle: connected.remotePathStyle,
403
415
  keyAclStatus: connected.keyAclStatus,
416
+ hostKey: connected.hostKey,
417
+ hostKeys: connected.hostKeys,
404
418
  host: connected.host,
405
419
  port: connected.port,
406
420
  defaultEnvKeys: connected.defaultEnvKeys,
@@ -8,10 +8,12 @@ import { randomUUID } from 'crypto';
8
8
  import { z } from 'zod';
9
9
  import { classifyCommandRisk } from '../command-risk.js';
10
10
  import * as fileOps from '../file-ops.js';
11
- import { sessionManager } from '../session-manager.js';
11
+ import { sftpOperationOutcome } from '../sftp-timeout.js';
12
12
  import { OpenSshError } from '../openssh.js';
13
13
  import { encodedPowershell, quotePowershell, sftpPath } from '../remote-platform.js';
14
- import { HARD_EXEC_MAX_OUTPUT_SIZE } from '../types.js';
14
+ import { sessionManager } from '../session-manager.js';
15
+ import { DEFAULT_EXEC_MAX_OUTPUT_SIZE, DEFAULT_EXEC_TIMEOUT_MS, HARD_EXEC_MAX_OUTPUT_SIZE, } from '../types.js';
16
+ import { utf8SafeEnd } from '../utf8.js';
15
17
  import { windowsTemporaryPathScript } from '../windows-acl.js';
16
18
  import { sshPortSchema } from './schema.js';
17
19
  import { escapeShellArg, formatError, formatResult } from './utils.js'; // ========== Schemas ==========
@@ -99,7 +101,11 @@ const execParallelSchema = z.object({
99
101
  const execScriptSchema = z.object({
100
102
  alias: z.string().describe('连接别名'),
101
103
  script: z.string().describe('脚本内容'),
102
- interpreter: z.string().optional().describe('解释器,默认 bash'),
104
+ interpreter: z.string().optional().describe('解释器可执行文件名或路径,POSIX 默认 bash,Windows 默认连接 shell'),
105
+ interpreterArgs: z
106
+ .array(z.string().refine((value) => !value.includes('\0'), '解释器参数不能包含 NUL'))
107
+ .optional()
108
+ .describe('解释器参数数组,默认空数组,例如 python3 配合 ["-I"];每项作为独立参数传递'),
103
109
  targetUser: z.string().optional().describe('目标用户名,优先级高于 runAs'),
104
110
  runAs: z.string().optional().describe('本次脚本使用的目标用户'),
105
111
  cwd: z.string().optional().describe('工作目录(可选)'),
@@ -123,7 +129,7 @@ async function handleExec(args) {
123
129
  });
124
130
  return formatResult({
125
131
  ...result,
126
- commandRisk: classifyCommandRisk(args.command, args.timeout, sessionManager.getCommandShell(args.alias)),
132
+ commandRisk: classifyCommandRisk(args.command, args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, result.shell),
127
133
  });
128
134
  }
129
135
  catch (error) {
@@ -143,7 +149,7 @@ async function handleExecAsUser(args) {
143
149
  });
144
150
  return formatResult({
145
151
  ...result,
146
- commandRisk: classifyCommandRisk(args.command, args.timeout, sessionManager.getCommandShell(args.alias)),
152
+ commandRisk: classifyCommandRisk(args.command, args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, result.shell),
147
153
  });
148
154
  }
149
155
  const result = await sessionManager.exec(args.alias, args.command, {
@@ -155,7 +161,7 @@ async function handleExecAsUser(args) {
155
161
  });
156
162
  return formatResult({
157
163
  ...result,
158
- commandRisk: classifyCommandRisk(args.command, args.timeout, sessionManager.getCommandShell(args.alias)),
164
+ commandRisk: classifyCommandRisk(args.command, args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, result.shell),
159
165
  });
160
166
  }
161
167
  catch (error) {
@@ -177,31 +183,69 @@ async function handleExecSudo(args) {
177
183
  return formatError(error);
178
184
  }
179
185
  }
186
+ const REQUEST_OUTPUT_LIMIT = 16 * 1024 * 1024;
187
+ function boundExecOutput(result, budget) {
188
+ const bounded = { ...result };
189
+ budget.truncated ||= result.stdoutTruncated === true || result.stderrTruncated === true;
190
+ for (const field of ['stdout', 'stderr', 'stdoutHead', 'stdoutTail', 'stderrHead', 'stderrTail']) {
191
+ const value = bounded[field];
192
+ if (value === undefined) {
193
+ continue;
194
+ }
195
+ const bytes = Buffer.from(value);
196
+ const end = utf8SafeEnd(bytes, 0, Math.min(bytes.length, budget.remaining), field, budget.remaining < bytes.length, true);
197
+ bounded[field] = bytes.subarray(0, end).toString('utf8');
198
+ budget.remaining -= end;
199
+ if (end < bytes.length) {
200
+ budget.truncated = true;
201
+ if (field.startsWith('stdout')) {
202
+ bounded.stdoutTruncated = true;
203
+ }
204
+ else {
205
+ bounded.stderrTruncated = true;
206
+ }
207
+ }
208
+ }
209
+ return bounded;
210
+ }
211
+ function executionFailure(error) {
212
+ const details = error && typeof error === 'object' && 'details' in error ? error.details : undefined;
213
+ return {
214
+ ...(details && typeof details === 'object' ? details : {}),
215
+ success: false,
216
+ error: error instanceof Error ? error.message : String(error),
217
+ };
218
+ }
180
219
  async function handleExecBatch(args) {
181
220
  try {
182
221
  const stopOnError = args.stopOnError !== false;
183
222
  const results = [];
223
+ const budget = { remaining: REQUEST_OUTPUT_LIMIT, truncated: false };
184
224
  for (let i = 0; i < args.commands.length; i++) {
185
- const commandRisk = classifyCommandRisk(args.commands[i], args.timeout, sessionManager.getCommandShell(args.alias));
186
225
  try {
187
- const execResult = await sessionManager.exec(args.alias, args.commands[i], { timeout: args.timeout });
226
+ const execResult = await sessionManager.exec(args.alias, args.commands[i], {
227
+ timeout: args.timeout,
228
+ maxOutputSize: Math.max(1, Math.min(DEFAULT_EXEC_MAX_OUTPUT_SIZE, budget.remaining)),
229
+ });
188
230
  results.push({
189
231
  index: i,
190
232
  commandRedacted: true,
191
- commandRisk,
192
- ...execResult,
233
+ commandRisk: classifyCommandRisk(args.commands[i], args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, execResult.shell),
234
+ ...boundExecOutput(execResult, budget),
193
235
  });
194
- if (execResult.exitCode !== 0 && stopOnError) {
236
+ if (!execResult.success && stopOnError) {
195
237
  break;
196
238
  }
197
239
  }
198
240
  catch (err) {
241
+ const failure = executionFailure(err);
199
242
  results.push({
200
243
  index: i,
201
244
  commandRedacted: true,
202
- commandRisk,
203
- success: false,
204
- error: err instanceof Error ? err.message : String(err),
245
+ commandRisk: failure.shell
246
+ ? classifyCommandRisk(args.commands[i], args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, failure.shell)
247
+ : undefined,
248
+ ...boundExecOutput(failure, budget),
205
249
  });
206
250
  if (stopOnError) {
207
251
  break;
@@ -213,6 +257,9 @@ async function handleExecBatch(args) {
213
257
  total: args.commands.length,
214
258
  executed: results.length,
215
259
  results,
260
+ maxOutputBytes: REQUEST_OUTPUT_LIMIT,
261
+ outputBytes: REQUEST_OUTPUT_LIMIT - budget.remaining,
262
+ outputTruncated: budget.truncated || undefined,
216
263
  });
217
264
  }
218
265
  catch (error) {
@@ -259,23 +306,17 @@ async function mapWithConcurrency(items, limit, worker) {
259
306
  async function handleExecParallel(args) {
260
307
  try {
261
308
  const concurrency = Math.min(args.maxConcurrency ?? EXEC_PARALLEL_DEFAULT_CONCURRENCY, args.aliases.length);
309
+ const budget = { remaining: REQUEST_OUTPUT_LIMIT, truncated: false };
262
310
  const results = await mapWithConcurrency(args.aliases, concurrency, async (alias) => {
263
311
  try {
264
312
  const execResult = await sessionManager.exec(alias, args.command, {
265
313
  timeout: args.timeout,
266
- maxOutputSize: args.maxOutputSize,
314
+ maxOutputSize: Math.max(1, Math.min(args.maxOutputSize ?? DEFAULT_EXEC_MAX_OUTPUT_SIZE, budget.remaining)),
267
315
  });
268
- return {
269
- alias,
270
- ...execResult,
271
- };
316
+ return { alias, ...boundExecOutput(execResult, budget) };
272
317
  }
273
318
  catch (err) {
274
- return {
275
- alias,
276
- success: false,
277
- error: err instanceof Error ? err.message : String(err),
278
- };
319
+ return { alias, ...boundExecOutput(executionFailure(err), budget) };
279
320
  }
280
321
  });
281
322
  return formatResult({
@@ -283,6 +324,9 @@ async function handleExecParallel(args) {
283
324
  total: args.aliases.length,
284
325
  concurrency,
285
326
  results,
327
+ maxOutputBytes: REQUEST_OUTPUT_LIMIT,
328
+ outputBytes: REQUEST_OUTPUT_LIMIT - budget.remaining,
329
+ outputTruncated: budget.truncated || undefined,
286
330
  });
287
331
  }
288
332
  catch (error) {
@@ -336,15 +380,17 @@ async function handleExecScript(args) {
336
380
  let ownsRemotePath = false;
337
381
  let executionStarted = false;
338
382
  try {
339
- if (sessionManager.getOpenSshConnection(args.alias))
383
+ if (sessionManager.getOpenSshConnection(args.alias)) {
340
384
  throw new OpenSshError('The OpenSSH backend does not support temporary script uploads; use ssh_exec for inline commands', {
341
385
  code: 'unsupported_backend',
342
386
  backend: 'openssh',
343
387
  capability: 'script_upload',
344
388
  retryable: false,
345
389
  });
390
+ }
346
391
  const windows = sessionManager.getRemotePlatform(args.alias) === 'windows';
347
392
  const interpreter = args.interpreter ?? (windows ? sessionManager.getCommandShell(args.alias) : 'bash');
393
+ const interpreterArgs = args.interpreterArgs ?? [];
348
394
  const { effectiveUser, loginUser } = resolveScriptUsers(args);
349
395
  if (windows && (args.targetUser || args.runAs || effectiveUser)) {
350
396
  sessionManager.requirePosixPrivilege(args.alias);
@@ -373,7 +419,7 @@ async function handleExecScript(args) {
373
419
  throw new Error('Remote Windows temporary directory lookup failed');
374
420
  }
375
421
  remoteSftpPath = sftpPath(remotePath, sessionManager.getRemotePathStyle(args.alias));
376
- await fileOps.prepareWindowsRemotePrivateFile(args.alias, remoteSftpPath, args.timeout, remotePath);
422
+ await fileOps.prepareWindowsRemotePrivateFile(args.alias, remoteSftpPath, args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, remotePath);
377
423
  ownsRemotePath = true;
378
424
  }
379
425
  else {
@@ -397,10 +443,16 @@ async function handleExecScript(args) {
397
443
  await prepareRemoteScript(args.alias, remotePath, effectiveUser, loginUser, args.timeout);
398
444
  }
399
445
  const command = windows
400
- ? interpreter.toLowerCase().startsWith('cmd')
401
- ? `cmd.exe /D /C "${remotePath.replace(/"/g, '""')}"`
402
- : encodedPowershell(`& ${quotePowershell(remotePath)}; if (-not $?) { exit 1 }`)
403
- : `${escapeShellArg(interpreter)} ${escapeShellArg(remotePath)}`;
446
+ ? interpreterArgs.length > 0
447
+ ? encodedPowershell(`& ${[interpreter, ...interpreterArgs].map(quotePowershell).join(' ')} ` +
448
+ (interpreter.toLowerCase().startsWith('cmd')
449
+ ? `/D /V:OFF /S /C ${quotePowershell(`"${remotePath.replace(/"/g, '""')}"`)}`
450
+ : `-File ${quotePowershell(remotePath)}`) +
451
+ '; exit $LASTEXITCODE')
452
+ : interpreter.toLowerCase().startsWith('cmd')
453
+ ? `cmd.exe /D /C "${remotePath.replace(/"/g, '""')}"`
454
+ : encodedPowershell(`& ${quotePowershell(remotePath)}; if (-not $?) { exit 1 }`)
455
+ : [interpreter, ...interpreterArgs, remotePath].map(escapeShellArg).join(' ');
404
456
  const execOptions = {
405
457
  timeout: args.timeout,
406
458
  cwd: args.cwd,
@@ -426,14 +478,7 @@ async function handleExecScript(args) {
426
478
  const cleanupWarning = remoteSftpPath && ownsRemotePath && (args.keepScript !== true || !executionStarted)
427
479
  ? await cleanupRemoteScript(args.alias, remoteSftpPath, args.timeout)
428
480
  : undefined;
429
- if (cleanupWarning) {
430
- return formatResult({
431
- success: false,
432
- error: error instanceof Error ? error.message : String(error),
433
- cleanupWarning,
434
- });
435
- }
436
- return formatError(error);
481
+ return formatError(error, { ...sftpOperationOutcome(error), cleanupWarning });
437
482
  }
438
483
  }
439
484
  // ========== Register ==========