@pyrokine/mcp-ssh 3.0.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.
- package/README.md +423 -102
- package/README_zh.md +300 -74
- package/dist/command-risk.js +5 -2
- package/dist/directory-verification.d.ts +10 -3
- package/dist/directory-verification.js +271 -55
- package/dist/file-mode.js +25 -13
- package/dist/file-ops.d.ts +20 -6
- package/dist/file-ops.js +669 -282
- package/dist/forward-manager.js +6 -1
- package/dist/known-hosts.d.ts +22 -0
- package/dist/known-hosts.js +553 -0
- package/dist/openssh.d.ts +51 -0
- package/dist/openssh.js +553 -0
- package/dist/operation-manager.d.ts +2 -3
- package/dist/operation-manager.js +33 -5
- package/dist/pty-manager.d.ts +2 -1
- package/dist/pty-manager.js +81 -19
- package/dist/remote-platform.d.ts +1 -1
- package/dist/remote-platform.js +82 -50
- package/dist/security.d.ts +2 -0
- package/dist/security.js +39 -3
- package/dist/session-manager.d.ts +40 -4
- package/dist/session-manager.js +377 -61
- package/dist/sftp-timeout.d.ts +16 -1
- package/dist/sftp-timeout.js +104 -12
- package/dist/ssh-config.js +1 -1
- package/dist/tools/connection.js +89 -5
- package/dist/tools/exec.js +90 -37
- package/dist/tools/file.js +457 -146
- package/dist/tools/operation.js +7 -5
- package/dist/tools/pty.js +16 -13
- package/dist/tools/utils.d.ts +1 -1
- package/dist/tools/utils.js +2 -2
- package/dist/types.d.ts +46 -5
- package/dist/types.js +1 -0
- package/dist/utf8.d.ts +1 -1
- package/dist/utf8.js +2 -2
- package/dist/windows-acl.d.ts +1 -0
- package/dist/windows-acl.js +167 -80
- package/package.json +6 -5
package/dist/sftp-timeout.d.ts
CHANGED
|
@@ -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): SFTPWrapper;
|
|
23
|
+
outcome(error: unknown): Record<string, unknown>;
|
|
24
|
+
}
|
package/dist/sftp-timeout.js
CHANGED
|
@@ -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
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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
|
+
}
|
package/dist/ssh-config.js
CHANGED
package/dist/tools/connection.js
CHANGED
|
@@ -7,6 +7,7 @@ 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 { OpenSshError, resolveOpenSshConfig } from '../openssh.js';
|
|
10
11
|
import { sessionManager } from '../session-manager.js';
|
|
11
12
|
import { parseProxyJump, parseSSHConfig } from '../ssh-config.js';
|
|
12
13
|
import { sshPortSchema } from './schema.js';
|
|
@@ -28,6 +29,9 @@ const templateJumpHostSchema = z.object({
|
|
|
28
29
|
readyTimeout: z.number().int().positive().max(600000).optional(),
|
|
29
30
|
});
|
|
30
31
|
const connectionTemplateSchema = z.object({
|
|
32
|
+
backend: z.enum(['ssh2', 'openssh']).optional(),
|
|
33
|
+
controlPath: z.string().optional(),
|
|
34
|
+
configPath: z.string().optional(),
|
|
31
35
|
configHost: z.string().optional(),
|
|
32
36
|
host: z.string().optional(),
|
|
33
37
|
user: z.string().optional(),
|
|
@@ -60,7 +64,19 @@ function loadTemplates() {
|
|
|
60
64
|
if (!source) {
|
|
61
65
|
return {};
|
|
62
66
|
}
|
|
63
|
-
|
|
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
|
+
}
|
|
64
80
|
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
65
81
|
throw new Error('SSH templates must be an object keyed by template name');
|
|
66
82
|
}
|
|
@@ -101,6 +117,11 @@ function mergeEnv(templateEnv, argsEnv) {
|
|
|
101
117
|
}
|
|
102
118
|
// ========== Schemas ==========
|
|
103
119
|
const connectSchema = z.object({
|
|
120
|
+
backend: z
|
|
121
|
+
.enum(['ssh2', 'openssh'])
|
|
122
|
+
.optional()
|
|
123
|
+
.describe('连接后端,默认 ssh2;openssh 仅复用用户已有 master,失败不新建连接'),
|
|
124
|
+
controlPath: z.string().optional().describe('OpenSSH master 的 socket 路径,默认取 ssh -G 的 ControlPath'),
|
|
104
125
|
template: z.string().optional().describe('连接模板名,从 SSH_MCP_TEMPLATES 或 ~/.mcp-ssh/templates.json 读取'),
|
|
105
126
|
configHost: z.string().optional().describe('使用 ~/.ssh/config 中的 Host 配置(推荐)'),
|
|
106
127
|
configPath: z.string().optional().describe('SSH 配置文件路径(默认 ~/.ssh/config)'),
|
|
@@ -153,6 +174,11 @@ const disconnectSchema = z.object({
|
|
|
153
174
|
alias: z.string().describe('连接别名'),
|
|
154
175
|
});
|
|
155
176
|
const sessionFieldSchema = z.enum([
|
|
177
|
+
'backend',
|
|
178
|
+
'masterReused',
|
|
179
|
+
'identityStatus',
|
|
180
|
+
'masterPid',
|
|
181
|
+
'observedLogin',
|
|
156
182
|
'alias',
|
|
157
183
|
'identity',
|
|
158
184
|
'runAs',
|
|
@@ -182,6 +208,9 @@ const configListSchema = z.object({
|
|
|
182
208
|
async function handleConnect(args) {
|
|
183
209
|
try {
|
|
184
210
|
const template = getTemplate(args.template);
|
|
211
|
+
const backend = args.backend ?? template.backend ?? 'ssh2';
|
|
212
|
+
const configPath = args.configPath ?? template.configPath;
|
|
213
|
+
let controlPath = args.controlPath ?? template.controlPath;
|
|
185
214
|
const configHost = args.configHost ?? template.configHost;
|
|
186
215
|
let host = args.host ?? template.host;
|
|
187
216
|
let user = args.user ?? template.user ?? template.username;
|
|
@@ -204,8 +233,53 @@ async function handleConnect(args) {
|
|
|
204
233
|
const keepaliveInterval = args.keepaliveInterval ?? template.keepaliveInterval;
|
|
205
234
|
const readyTimeout = args.readyTimeout ?? template.readyTimeout;
|
|
206
235
|
let jumpHostResolved;
|
|
207
|
-
if (
|
|
208
|
-
|
|
236
|
+
if (backend === 'openssh') {
|
|
237
|
+
if (password !== undefined ||
|
|
238
|
+
keyPath !== undefined ||
|
|
239
|
+
agent !== undefined ||
|
|
240
|
+
args.jumpHost ||
|
|
241
|
+
template.jumpHost) {
|
|
242
|
+
throw new OpenSshError('OpenSSH master reuse does not accept new authentication or jumpHost parameters', {
|
|
243
|
+
code: 'unsupported_backend',
|
|
244
|
+
backend,
|
|
245
|
+
capability: 'new_authentication',
|
|
246
|
+
retryable: false,
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
if (remotePlatform !== 'posix' ||
|
|
250
|
+
commandShell !== 'posix' ||
|
|
251
|
+
remotePathStyle !== 'posix' ||
|
|
252
|
+
(rsyncProfile && rsyncProfile !== 'posix')) {
|
|
253
|
+
throw new OpenSshError('OpenSSH master reuse requires a POSIX remote shell and path style', {
|
|
254
|
+
code: 'unsupported_backend',
|
|
255
|
+
backend,
|
|
256
|
+
capability: 'platform',
|
|
257
|
+
retryable: false,
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
const resolved = await resolveOpenSshConfig({
|
|
261
|
+
configHost,
|
|
262
|
+
configPath,
|
|
263
|
+
host,
|
|
264
|
+
username: user,
|
|
265
|
+
port,
|
|
266
|
+
controlPath,
|
|
267
|
+
readyTimeout,
|
|
268
|
+
});
|
|
269
|
+
host = resolved.host;
|
|
270
|
+
user = resolved.username;
|
|
271
|
+
port = resolved.port;
|
|
272
|
+
controlPath = resolved.controlPath;
|
|
273
|
+
}
|
|
274
|
+
else if (controlPath !== undefined) {
|
|
275
|
+
throw new OpenSshError('controlPath requires backend=openssh', {
|
|
276
|
+
code: 'invalid_openssh_config',
|
|
277
|
+
backend,
|
|
278
|
+
retryable: false,
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
else if (configHost) {
|
|
282
|
+
const allHosts = parseSSHConfig(configPath);
|
|
209
283
|
const hostConfig = allHosts.find((h) => h.host === configHost);
|
|
210
284
|
if (!hostConfig) {
|
|
211
285
|
return formatResult({
|
|
@@ -226,7 +300,7 @@ async function handleConnect(args) {
|
|
|
226
300
|
agent = configAgent;
|
|
227
301
|
}
|
|
228
302
|
// 解析 ProxyJump(支持 user@host:port 格式)
|
|
229
|
-
if (hostConfig.proxyJump) {
|
|
303
|
+
if (hostConfig.proxyJump && !(args.jumpHost ?? template.jumpHost)) {
|
|
230
304
|
const parsed = parseProxyJump(hostConfig.proxyJump);
|
|
231
305
|
if (parsed) {
|
|
232
306
|
// 先尝试在 config 中查找对应的 Host
|
|
@@ -300,6 +374,8 @@ async function handleConnect(args) {
|
|
|
300
374
|
.filter((session) => session.identity === identity && session.alias !== finalAlias && session.connected)
|
|
301
375
|
.map((session) => ({ alias: session.alias, runAs: session.runAs, connectedAt: session.connectedAt }));
|
|
302
376
|
const alias = await sessionManager.connect({
|
|
377
|
+
backend,
|
|
378
|
+
controlPath,
|
|
303
379
|
host,
|
|
304
380
|
port: finalPort,
|
|
305
381
|
username: user,
|
|
@@ -323,6 +399,11 @@ async function handleConnect(args) {
|
|
|
323
399
|
const connected = sessionManager.getSessionConnectionInfo(alias);
|
|
324
400
|
return formatResult({
|
|
325
401
|
success: true,
|
|
402
|
+
backend: connected.backend,
|
|
403
|
+
masterReused: connected.masterReused,
|
|
404
|
+
identityStatus: connected.identityStatus,
|
|
405
|
+
masterPid: connected.masterPid,
|
|
406
|
+
observedLogin: connected.observedLogin,
|
|
326
407
|
alias: connected.alias,
|
|
327
408
|
reused,
|
|
328
409
|
identity: connected.identity,
|
|
@@ -332,6 +413,8 @@ async function handleConnect(args) {
|
|
|
332
413
|
commandShell: connected.commandShell,
|
|
333
414
|
remotePathStyle: connected.remotePathStyle,
|
|
334
415
|
keyAclStatus: connected.keyAclStatus,
|
|
416
|
+
hostKey: connected.hostKey,
|
|
417
|
+
hostKeys: connected.hostKeys,
|
|
335
418
|
host: connected.host,
|
|
336
419
|
port: connected.port,
|
|
337
420
|
defaultEnvKeys: connected.defaultEnvKeys,
|
|
@@ -413,7 +496,8 @@ async function handleConfigList(args) {
|
|
|
413
496
|
export function registerConnectionTools(server) {
|
|
414
497
|
server.registerTool('ssh_connect', {
|
|
415
498
|
description: [
|
|
416
|
-
'建立 SSH
|
|
499
|
+
'建立 SSH 会话,默认 ssh2 支持密码、密钥和跳板机;backend=openssh 仅复用用户已有主连接,失败不新建连接或重新认证',
|
|
500
|
+
'OpenSSH 后端沿用用户 master 的信任,支持 POSIX 命令、后台操作和 rsync 同步;断开 alias 保留用户 master,未适配能力明确报错',
|
|
417
501
|
'',
|
|
418
502
|
'可通过 configHost 参数使用 ~/.ssh/config 中的配置,无需重复填写连接信息;模板会在连接前校验端口和嵌套 jumpHost 字段',
|
|
419
503
|
'支持 Host 多别名、Host * 全局默认继承、ProxyJump(user@host:port 格式)',
|
package/dist/tools/exec.js
CHANGED
|
@@ -8,9 +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 {
|
|
11
|
+
import { sftpOperationOutcome } from '../sftp-timeout.js';
|
|
12
|
+
import { OpenSshError } from '../openssh.js';
|
|
12
13
|
import { encodedPowershell, quotePowershell, sftpPath } from '../remote-platform.js';
|
|
13
|
-
import {
|
|
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';
|
|
14
17
|
import { windowsTemporaryPathScript } from '../windows-acl.js';
|
|
15
18
|
import { sshPortSchema } from './schema.js';
|
|
16
19
|
import { escapeShellArg, formatError, formatResult } from './utils.js'; // ========== Schemas ==========
|
|
@@ -98,7 +101,11 @@ const execParallelSchema = z.object({
|
|
|
98
101
|
const execScriptSchema = z.object({
|
|
99
102
|
alias: z.string().describe('连接别名'),
|
|
100
103
|
script: z.string().describe('脚本内容'),
|
|
101
|
-
interpreter: z.string().optional().describe('
|
|
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"];每项作为独立参数传递'),
|
|
102
109
|
targetUser: z.string().optional().describe('目标用户名,优先级高于 runAs'),
|
|
103
110
|
runAs: z.string().optional().describe('本次脚本使用的目标用户'),
|
|
104
111
|
cwd: z.string().optional().describe('工作目录(可选)'),
|
|
@@ -122,7 +129,7 @@ async function handleExec(args) {
|
|
|
122
129
|
});
|
|
123
130
|
return formatResult({
|
|
124
131
|
...result,
|
|
125
|
-
commandRisk: classifyCommandRisk(args.command, args.timeout,
|
|
132
|
+
commandRisk: classifyCommandRisk(args.command, args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, result.shell),
|
|
126
133
|
});
|
|
127
134
|
}
|
|
128
135
|
catch (error) {
|
|
@@ -142,7 +149,7 @@ async function handleExecAsUser(args) {
|
|
|
142
149
|
});
|
|
143
150
|
return formatResult({
|
|
144
151
|
...result,
|
|
145
|
-
commandRisk: classifyCommandRisk(args.command, args.timeout,
|
|
152
|
+
commandRisk: classifyCommandRisk(args.command, args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, result.shell),
|
|
146
153
|
});
|
|
147
154
|
}
|
|
148
155
|
const result = await sessionManager.exec(args.alias, args.command, {
|
|
@@ -154,7 +161,7 @@ async function handleExecAsUser(args) {
|
|
|
154
161
|
});
|
|
155
162
|
return formatResult({
|
|
156
163
|
...result,
|
|
157
|
-
commandRisk: classifyCommandRisk(args.command, args.timeout,
|
|
164
|
+
commandRisk: classifyCommandRisk(args.command, args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, result.shell),
|
|
158
165
|
});
|
|
159
166
|
}
|
|
160
167
|
catch (error) {
|
|
@@ -176,31 +183,69 @@ async function handleExecSudo(args) {
|
|
|
176
183
|
return formatError(error);
|
|
177
184
|
}
|
|
178
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
|
+
}
|
|
179
219
|
async function handleExecBatch(args) {
|
|
180
220
|
try {
|
|
181
221
|
const stopOnError = args.stopOnError !== false;
|
|
182
222
|
const results = [];
|
|
223
|
+
const budget = { remaining: REQUEST_OUTPUT_LIMIT, truncated: false };
|
|
183
224
|
for (let i = 0; i < args.commands.length; i++) {
|
|
184
|
-
const commandRisk = classifyCommandRisk(args.commands[i], args.timeout, sessionManager.getCommandShell(args.alias));
|
|
185
225
|
try {
|
|
186
|
-
const execResult = await sessionManager.exec(args.alias, args.commands[i], {
|
|
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
|
+
});
|
|
187
230
|
results.push({
|
|
188
231
|
index: i,
|
|
189
232
|
commandRedacted: true,
|
|
190
|
-
commandRisk,
|
|
191
|
-
...execResult,
|
|
233
|
+
commandRisk: classifyCommandRisk(args.commands[i], args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, execResult.shell),
|
|
234
|
+
...boundExecOutput(execResult, budget),
|
|
192
235
|
});
|
|
193
|
-
if (execResult.
|
|
236
|
+
if (!execResult.success && stopOnError) {
|
|
194
237
|
break;
|
|
195
238
|
}
|
|
196
239
|
}
|
|
197
240
|
catch (err) {
|
|
241
|
+
const failure = executionFailure(err);
|
|
198
242
|
results.push({
|
|
199
243
|
index: i,
|
|
200
244
|
commandRedacted: true,
|
|
201
|
-
commandRisk
|
|
202
|
-
|
|
203
|
-
|
|
245
|
+
commandRisk: failure.shell
|
|
246
|
+
? classifyCommandRisk(args.commands[i], args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, failure.shell)
|
|
247
|
+
: undefined,
|
|
248
|
+
...boundExecOutput(failure, budget),
|
|
204
249
|
});
|
|
205
250
|
if (stopOnError) {
|
|
206
251
|
break;
|
|
@@ -212,6 +257,9 @@ async function handleExecBatch(args) {
|
|
|
212
257
|
total: args.commands.length,
|
|
213
258
|
executed: results.length,
|
|
214
259
|
results,
|
|
260
|
+
maxOutputBytes: REQUEST_OUTPUT_LIMIT,
|
|
261
|
+
outputBytes: REQUEST_OUTPUT_LIMIT - budget.remaining,
|
|
262
|
+
outputTruncated: budget.truncated || undefined,
|
|
215
263
|
});
|
|
216
264
|
}
|
|
217
265
|
catch (error) {
|
|
@@ -258,23 +306,17 @@ async function mapWithConcurrency(items, limit, worker) {
|
|
|
258
306
|
async function handleExecParallel(args) {
|
|
259
307
|
try {
|
|
260
308
|
const concurrency = Math.min(args.maxConcurrency ?? EXEC_PARALLEL_DEFAULT_CONCURRENCY, args.aliases.length);
|
|
309
|
+
const budget = { remaining: REQUEST_OUTPUT_LIMIT, truncated: false };
|
|
261
310
|
const results = await mapWithConcurrency(args.aliases, concurrency, async (alias) => {
|
|
262
311
|
try {
|
|
263
312
|
const execResult = await sessionManager.exec(alias, args.command, {
|
|
264
313
|
timeout: args.timeout,
|
|
265
|
-
maxOutputSize: args.maxOutputSize,
|
|
314
|
+
maxOutputSize: Math.max(1, Math.min(args.maxOutputSize ?? DEFAULT_EXEC_MAX_OUTPUT_SIZE, budget.remaining)),
|
|
266
315
|
});
|
|
267
|
-
return {
|
|
268
|
-
alias,
|
|
269
|
-
...execResult,
|
|
270
|
-
};
|
|
316
|
+
return { alias, ...boundExecOutput(execResult, budget) };
|
|
271
317
|
}
|
|
272
318
|
catch (err) {
|
|
273
|
-
return {
|
|
274
|
-
alias,
|
|
275
|
-
success: false,
|
|
276
|
-
error: err instanceof Error ? err.message : String(err),
|
|
277
|
-
};
|
|
319
|
+
return { alias, ...boundExecOutput(executionFailure(err), budget) };
|
|
278
320
|
}
|
|
279
321
|
});
|
|
280
322
|
return formatResult({
|
|
@@ -282,6 +324,9 @@ async function handleExecParallel(args) {
|
|
|
282
324
|
total: args.aliases.length,
|
|
283
325
|
concurrency,
|
|
284
326
|
results,
|
|
327
|
+
maxOutputBytes: REQUEST_OUTPUT_LIMIT,
|
|
328
|
+
outputBytes: REQUEST_OUTPUT_LIMIT - budget.remaining,
|
|
329
|
+
outputTruncated: budget.truncated || undefined,
|
|
285
330
|
});
|
|
286
331
|
}
|
|
287
332
|
catch (error) {
|
|
@@ -335,8 +380,17 @@ async function handleExecScript(args) {
|
|
|
335
380
|
let ownsRemotePath = false;
|
|
336
381
|
let executionStarted = false;
|
|
337
382
|
try {
|
|
383
|
+
if (sessionManager.getOpenSshConnection(args.alias)) {
|
|
384
|
+
throw new OpenSshError('The OpenSSH backend does not support temporary script uploads; use ssh_exec for inline commands', {
|
|
385
|
+
code: 'unsupported_backend',
|
|
386
|
+
backend: 'openssh',
|
|
387
|
+
capability: 'script_upload',
|
|
388
|
+
retryable: false,
|
|
389
|
+
});
|
|
390
|
+
}
|
|
338
391
|
const windows = sessionManager.getRemotePlatform(args.alias) === 'windows';
|
|
339
392
|
const interpreter = args.interpreter ?? (windows ? sessionManager.getCommandShell(args.alias) : 'bash');
|
|
393
|
+
const interpreterArgs = args.interpreterArgs ?? [];
|
|
340
394
|
const { effectiveUser, loginUser } = resolveScriptUsers(args);
|
|
341
395
|
if (windows && (args.targetUser || args.runAs || effectiveUser)) {
|
|
342
396
|
sessionManager.requirePosixPrivilege(args.alias);
|
|
@@ -365,7 +419,7 @@ async function handleExecScript(args) {
|
|
|
365
419
|
throw new Error('Remote Windows temporary directory lookup failed');
|
|
366
420
|
}
|
|
367
421
|
remoteSftpPath = sftpPath(remotePath, sessionManager.getRemotePathStyle(args.alias));
|
|
368
|
-
await fileOps.prepareWindowsRemotePrivateFile(args.alias, remoteSftpPath, args.timeout, remotePath);
|
|
422
|
+
await fileOps.prepareWindowsRemotePrivateFile(args.alias, remoteSftpPath, args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, remotePath);
|
|
369
423
|
ownsRemotePath = true;
|
|
370
424
|
}
|
|
371
425
|
else {
|
|
@@ -389,10 +443,16 @@ async function handleExecScript(args) {
|
|
|
389
443
|
await prepareRemoteScript(args.alias, remotePath, effectiveUser, loginUser, args.timeout);
|
|
390
444
|
}
|
|
391
445
|
const command = windows
|
|
392
|
-
?
|
|
393
|
-
?
|
|
394
|
-
|
|
395
|
-
|
|
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(' ');
|
|
396
456
|
const execOptions = {
|
|
397
457
|
timeout: args.timeout,
|
|
398
458
|
cwd: args.cwd,
|
|
@@ -418,14 +478,7 @@ async function handleExecScript(args) {
|
|
|
418
478
|
const cleanupWarning = remoteSftpPath && ownsRemotePath && (args.keepScript !== true || !executionStarted)
|
|
419
479
|
? await cleanupRemoteScript(args.alias, remoteSftpPath, args.timeout)
|
|
420
480
|
: undefined;
|
|
421
|
-
|
|
422
|
-
return formatResult({
|
|
423
|
-
success: false,
|
|
424
|
-
error: error instanceof Error ? error.message : String(error),
|
|
425
|
-
cleanupWarning,
|
|
426
|
-
});
|
|
427
|
-
}
|
|
428
|
-
return formatError(error);
|
|
481
|
+
return formatError(error, { ...sftpOperationOutcome(error), cleanupWarning });
|
|
429
482
|
}
|
|
430
483
|
}
|
|
431
484
|
// ========== Register ==========
|