@mastra/core1.85.06.4 kB
import { r as createTool } from "../tool-CXFwLwlu.js";
import { z } from "zod/v4";
import path from "path";
import { exec } from "child_process";
import { promisify } from "util";
// 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 = promisify(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) {
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 createTool({
id: "run-command",
description: "Execute a shell command and return the result. Only permitted commands in allowed directories can be executed.",
inputSchema: z.object({
command: z.string().describe("The shell command to execute"),
timeout: z.number().default(3e4).describe("Timeout in milliseconds (capped by server configuration)"),
cwd: 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
};
}
}
});
}
export { createRunCommandTool };
//# sourceMappingURL=server.js.map
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.