UNPKG

@mastra/core

Version:
210 lines (209 loc) • 6.88 kB
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); const require_rolldown_runtime = require("../rolldown-runtime-BrhgMLW6.cjs"); const require_tool = require("../tool-BMl4Lb5_.cjs"); let zod_v4 = require("zod/v4"); let path = require("path"); path = require_rolldown_runtime.__toESM(path, 1); let child_process = require("child_process"); // src/loop/network/run-command-tool.ts /** * Node.js-specific tool for running shell commands. * This file is separated from validation.ts to avoid bundling Node.js * dependencies into browser builds. * * @security WARNING: This tool executes shell commands and can be dangerous. * - NEVER use with untrusted input or in multi-tenant environments * - Always configure allowedCommands to restrict executable commands * - Always set allowedBasePaths to restrict working directories * - Consider running in a sandboxed environment (container, VM) * - Review all commands that agents may construct before deployment */ const execAsync = (0, require("util").promisify)(child_process.exec); /** * Characters that could enable shell injection attacks. * These are rejected when found in command input. */ const DANGEROUS_PATTERNS = [ /[;&|`$(){}[\]<>]/, /\n|\r/, /\\(?![ ])/ ]; /** * Commands that are inherently dangerous and blocked by default. */ const BLOCKED_COMMANDS = [ "rm", "rmdir", "del", "format", "mkfs", "dd", "shutdown", "reboot", "halt", "poweroff", "init", "kill", "killall", "pkill", "chmod", "chown", "chgrp", "sudo", "su", "passwd", "useradd", "userdel", "usermod", "groupadd", "visudo", "crontab", "systemctl", "service", "curl", "wget", "nc", "netcat", "ssh", "scp", "ftp", "telnet", "eval", "source", "exec" ]; /** * Validates that a path is under one of the allowed base paths. */ function isPathAllowed(targetPath, allowedBasePaths, pathImpl = path.default) { if (allowedBasePaths.length === 0) return true; const target = pathImpl.resolve(targetPath); return allowedBasePaths.some((basePath) => { const rel = pathImpl.relative(pathImpl.resolve(basePath), target); return rel === "" || rel !== ".." && !rel.startsWith(".." + pathImpl.sep) && !pathImpl.isAbsolute(rel); }); } /** * Extracts the base command from a command string, handling both `/` and `\\` * separators and common Windows executable extensions. */ function extractBaseCommand(command, platform = process.platform, stripExtension = true) { const trimmed = command.trim(); let baseCmd = ""; let quote = ""; for (const ch of trimmed) if (quote) { if (ch === quote) quote = ""; else baseCmd += ch; } else if (ch === "\"" || ch === "'") quote = ch; else if (/\s/.test(ch)) break; else baseCmd += ch; const lastSep = Math.max(baseCmd.lastIndexOf("/"), baseCmd.lastIndexOf("\\")); const lower = (lastSep === -1 ? baseCmd : baseCmd.substring(lastSep + 1)).toLowerCase(); if (platform !== "win32") return lower; let end = lower.length; while (end > 0 && (lower[end - 1] === "." || lower[end - 1] === " ")) end--; const trimmedName = lower.slice(0, end); return stripExtension ? trimmedName.replace(/\.(exe|cmd|bat|com)$/, "") : trimmedName; } /** * Creates a tool that lets agents run shell commands with security restrictions. * * @security WARNING: This tool executes shell commands. Even with restrictions, * it should NEVER be used with untrusted input. Always: * - Configure allowedCommands to restrict which commands can run * - Configure allowedBasePaths to restrict working directories * - Review agent prompts to understand what commands may be generated * - Consider additional sandboxing (containers, VMs) for production use * * @example * ```typescript * // Secure configuration with allowlists * const agent = new Agent({ * tools: { * runCommand: createRunCommandTool({ * allowedCommands: ['git', 'npm', 'node'], * allowedBasePaths: ['/home/user/project'], * maxTimeout: 10000, * }), * }, * }); * ``` */ function createRunCommandTool(options = {}) { const { allowedCommands = [], allowedBasePaths = [], additionalBlockedCommands = [], maxTimeout = 3e4, maxBuffer = 1048576, allowUnsafeCharacters = false } = options; const blockedCommands = /* @__PURE__ */ new Set([...BLOCKED_COMMANDS, ...additionalBlockedCommands.map((c) => extractBaseCommand(c))]); const allowedEntries = allowedCommands.map((c) => ({ name: extractBaseCommand(c), full: extractBaseCommand(c, process.platform, false) })); return require_tool.createTool({ id: "run-command", description: "Execute a shell command and return the result. Only permitted commands in allowed directories can be executed.", inputSchema: zod_v4.z.object({ command: zod_v4.z.string().describe("The shell command to execute"), timeout: zod_v4.z.number().default(3e4).describe("Timeout in milliseconds (capped by server configuration)"), cwd: zod_v4.z.string().optional().describe("Working directory (must be within allowed paths)") }), execute: async ({ command, timeout, cwd }) => { if (!allowUnsafeCharacters) { for (const pattern of DANGEROUS_PATTERNS) if (pattern.test(command)) return { success: false, exitCode: 1, stdout: "", stderr: "", message: `Command rejected: contains potentially unsafe characters. Pattern: ${pattern.source}` }; } const baseCommand = extractBaseCommand(command); if (blockedCommands.has(baseCommand)) return { success: false, exitCode: 1, stdout: "", stderr: "", message: `Command rejected: '${baseCommand}' is not permitted for security reasons` }; if (allowedCommands.length > 0) { const fullCommand = extractBaseCommand(command, process.platform, false); if (!allowedEntries.some((entry) => entry.full === entry.name ? entry.name === baseCommand : entry.full === fullCommand)) return { success: false, exitCode: 1, stdout: "", stderr: "", message: `Command rejected: '${baseCommand}' is not in the allowed commands list` }; } if (cwd && !isPathAllowed(cwd, allowedBasePaths)) return { success: false, exitCode: 1, stdout: "", stderr: "", message: `Command rejected: working directory '${cwd}' is not within allowed paths` }; const effectiveTimeout = Math.min(timeout || maxTimeout, maxTimeout); try { const { stdout, stderr } = await execAsync(command, { timeout: effectiveTimeout, cwd, maxBuffer, env: { ...process.env } }); return { success: true, exitCode: 0, stdout: stdout.slice(-3e3), stderr: stderr.slice(-1e3) }; } catch (error) { return { success: false, exitCode: error.code, stdout: error.stdout?.slice(-2e3), stderr: error.stderr?.slice(-2e3), message: error.message }; } } }); } exports.createRunCommandTool = createRunCommandTool; //# sourceMappingURL=server.cjs.map