@mastra/core
Version:
1 lines • 13.1 kB
Source Map (JSON)
{"version":3,"file":"server.cjs","names":["promisify","exec","nodePath","createTool","z"],"sources":["../../src/loop/network/run-command-tool.ts"],"sourcesContent":["/**\n * Node.js-specific tool for running shell commands.\n * This file is separated from validation.ts to avoid bundling Node.js\n * dependencies into browser builds.\n *\n * @security WARNING: This tool executes shell commands and can be dangerous.\n * - NEVER use with untrusted input or in multi-tenant environments\n * - Always configure allowedCommands to restrict executable commands\n * - Always set allowedBasePaths to restrict working directories\n * - Consider running in a sandboxed environment (container, VM)\n * - Review all commands that agents may construct before deployment\n */\n\nimport { exec } from 'node:child_process';\nimport nodePath from 'node:path';\nimport { promisify } from 'node:util';\n\nimport { z } from 'zod/v4';\n\nimport { createTool } from '../../tools';\n\nconst execAsync = promisify(exec);\n\n/**\n * Characters that could enable shell injection attacks.\n * These are rejected when found in command input.\n */\nconst DANGEROUS_PATTERNS = [\n /[;&|`$(){}[\\]<>]/, // Shell metacharacters\n /\\n|\\r/, // Newlines (command chaining)\n /\\\\(?![ ])/, // Backslashes (except escaped spaces)\n];\n\n/**\n * Commands that are inherently dangerous and blocked by default.\n */\nconst BLOCKED_COMMANDS = [\n 'rm',\n 'rmdir',\n 'del',\n 'format',\n 'mkfs',\n 'dd',\n 'shutdown',\n 'reboot',\n 'halt',\n 'poweroff',\n 'init',\n 'kill',\n 'killall',\n 'pkill',\n 'chmod',\n 'chown',\n 'chgrp',\n 'sudo',\n 'su',\n 'passwd',\n 'useradd',\n 'userdel',\n 'usermod',\n 'groupadd',\n 'visudo',\n 'crontab',\n 'systemctl',\n 'service',\n 'curl',\n 'wget',\n 'nc',\n 'netcat',\n 'ssh',\n 'scp',\n 'ftp',\n 'telnet',\n 'eval',\n 'source',\n 'exec',\n];\n\nexport interface RunCommandToolOptions {\n /**\n * Allowlist of command prefixes that are permitted.\n * If empty, all non-blocked commands are allowed (less secure).\n * @example ['git', 'npm', 'node', 'ls', 'cat', 'echo']\n */\n allowedCommands?: string[];\n\n /**\n * Base paths where command execution is permitted.\n * The cwd parameter must resolve to a path under one of these directories.\n * If empty, any cwd is allowed (less secure).\n * @example ['/home/user/projects', '/tmp/workspace']\n */\n allowedBasePaths?: string[];\n\n /**\n * Additional commands to block beyond the default blocklist.\n */\n additionalBlockedCommands?: string[];\n\n /**\n * Maximum execution time in milliseconds.\n * @default 30000 (30 seconds)\n */\n maxTimeout?: number;\n\n /**\n * Maximum buffer size for stdout/stderr in bytes.\n * @default 1048576 (1MB)\n */\n maxBuffer?: number;\n\n /**\n * Whether to allow potentially dangerous shell metacharacters.\n * Setting this to true is NOT recommended.\n * @default false\n */\n allowUnsafeCharacters?: boolean;\n}\n\n/**\n * Validates that a path is under one of the allowed base paths.\n */\nexport function isPathAllowed(\n targetPath: string,\n allowedBasePaths: string[],\n pathImpl: typeof nodePath.posix = nodePath,\n): boolean {\n if (allowedBasePaths.length === 0) return true;\n\n const target = pathImpl.resolve(targetPath);\n return allowedBasePaths.some(basePath => {\n const rel = pathImpl.relative(pathImpl.resolve(basePath), target);\n return rel === '' || (rel !== '..' && !rel.startsWith('..' + pathImpl.sep) && !pathImpl.isAbsolute(rel));\n });\n}\n\n/**\n * Extracts the base command from a command string, handling both `/` and `\\\\`\n * separators and common Windows executable extensions.\n */\nexport function extractBaseCommand(\n command: string,\n platform: NodeJS.Platform = process.platform,\n stripExtension = true,\n): string {\n const trimmed = command.trim();\n // Read the first shell word: whitespace ends it only outside quotes, and quote\n // characters are dropped, since the shell joins `r\"m\"` / `\"r\"m` into `rm`.\n let baseCmd = '';\n let quote = '';\n for (const ch of trimmed) {\n if (quote) {\n if (ch === quote) quote = '';\n else baseCmd += ch;\n } else if (ch === '\"' || ch === \"'\") {\n quote = ch;\n } else if (/\\s/.test(ch)) {\n break;\n } else {\n baseCmd += ch;\n }\n }\n const lastSep = Math.max(baseCmd.lastIndexOf('/'), baseCmd.lastIndexOf('\\\\'));\n const name = lastSep === -1 ? baseCmd : baseCmd.substring(lastSep + 1);\n const lower = name.toLowerCase();\n if (platform !== 'win32') return lower;\n // Windows ignores trailing dots/spaces and resolves executable extensions (`rm.exe.` runs `rm.exe`).\n // On POSIX these are distinct files, so normalizing there would let `./echo.` match an `echo` allowlist entry.\n let end = lower.length;\n while (end > 0 && (lower[end - 1] === '.' || lower[end - 1] === ' ')) end--;\n const trimmedName = lower.slice(0, end);\n return stripExtension ? trimmedName.replace(/\\.(exe|cmd|bat|com)$/, '') : trimmedName;\n}\n\n/**\n * Creates a tool that lets agents run shell commands with security restrictions.\n *\n * @security WARNING: This tool executes shell commands. Even with restrictions,\n * it should NEVER be used with untrusted input. Always:\n * - Configure allowedCommands to restrict which commands can run\n * - Configure allowedBasePaths to restrict working directories\n * - Review agent prompts to understand what commands may be generated\n * - Consider additional sandboxing (containers, VMs) for production use\n *\n * @example\n * ```typescript\n * // Secure configuration with allowlists\n * const agent = new Agent({\n * tools: {\n * runCommand: createRunCommandTool({\n * allowedCommands: ['git', 'npm', 'node'],\n * allowedBasePaths: ['/home/user/project'],\n * maxTimeout: 10000,\n * }),\n * },\n * });\n * ```\n */\nexport function createRunCommandTool(options: RunCommandToolOptions = {}) {\n const {\n allowedCommands = [],\n allowedBasePaths = [],\n additionalBlockedCommands = [],\n maxTimeout = 30000,\n maxBuffer = 1024 * 1024, // 1MB\n allowUnsafeCharacters = false,\n } = options;\n\n // Normalize configured names the same way as commands so `tool.exe` still matches on Windows.\n const blockedCommands = new Set([...BLOCKED_COMMANDS, ...additionalBlockedCommands.map(c => extractBaseCommand(c))]);\n // An allowlist entry with an explicit extension (`safe.cmd`) only permits that exact file,\n // so it can't authorize `safe.exe` or a bare `safe` that Windows might resolve to another file.\n const allowedEntries = allowedCommands.map(c => ({\n name: extractBaseCommand(c),\n full: extractBaseCommand(c, process.platform, false),\n }));\n\n return createTool({\n id: 'run-command',\n description:\n 'Execute a shell command and return the result. Only permitted commands in allowed directories can be executed.',\n inputSchema: z.object({\n command: z.string().describe('The shell command to execute'),\n timeout: z.number().default(30000).describe('Timeout in milliseconds (capped by server configuration)'),\n cwd: z.string().optional().describe('Working directory (must be within allowed paths)'),\n }),\n execute: async ({ command, timeout, cwd }) => {\n // Validate: reject dangerous characters\n if (!allowUnsafeCharacters) {\n for (const pattern of DANGEROUS_PATTERNS) {\n if (pattern.test(command)) {\n return {\n success: false,\n exitCode: 1,\n stdout: '',\n stderr: '',\n message: `Command rejected: contains potentially unsafe characters. Pattern: ${pattern.source}`,\n };\n }\n }\n }\n\n // Validate: extract and check base command\n const baseCommand = extractBaseCommand(command);\n\n // Check blocked commands\n if (blockedCommands.has(baseCommand)) {\n return {\n success: false,\n exitCode: 1,\n stdout: '',\n stderr: '',\n message: `Command rejected: '${baseCommand}' is not permitted for security reasons`,\n };\n }\n\n // Check allowlist if configured\n if (allowedCommands.length > 0) {\n const fullCommand = extractBaseCommand(command, process.platform, false);\n const isAllowed = allowedEntries.some(entry =>\n entry.full === entry.name ? entry.name === baseCommand : entry.full === fullCommand,\n );\n if (!isAllowed) {\n return {\n success: false,\n exitCode: 1,\n stdout: '',\n stderr: '',\n message: `Command rejected: '${baseCommand}' is not in the allowed commands list`,\n };\n }\n }\n\n // Validate: check cwd against allowed base paths\n if (cwd && !isPathAllowed(cwd, allowedBasePaths)) {\n return {\n success: false,\n exitCode: 1,\n stdout: '',\n stderr: '',\n message: `Command rejected: working directory '${cwd}' is not within allowed paths`,\n };\n }\n\n // Apply timeout cap\n const effectiveTimeout = Math.min(timeout || maxTimeout, maxTimeout);\n\n try {\n const { stdout, stderr } = await execAsync(command, {\n timeout: effectiveTimeout,\n cwd,\n maxBuffer,\n env: {\n ...process.env,\n // Restrict PATH to reduce attack surface (optional hardening)\n // PATH: '/usr/local/bin:/usr/bin:/bin',\n },\n });\n return {\n success: true,\n exitCode: 0,\n stdout: stdout.slice(-3000),\n stderr: stderr.slice(-1000),\n };\n } catch (error: any) {\n return {\n success: false,\n exitCode: error.code,\n stdout: error.stdout?.slice(-2000),\n stderr: error.stderr?.slice(-2000),\n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