UNPKG

safe-commander-mcp

Version:

A secure MCP server for executing whitelisted development commands with comprehensive security controls and resource limits

38 lines (37 loc) 1.83 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validatePath = validatePath; const node_path_1 = require("node:path"); /** * Security: Path traversal prevention * * @param inputPath - The input path to validate * @param allowedBasePath - The allowed base directory path * @returns The validated and resolved path * @throws Error if path traversal is detected or path is invalid */ function validatePath(inputPath, allowedBasePath) { if (!inputPath || typeof inputPath !== 'string' || inputPath.trim() === '') { // Allow empty paths to default to current directory within allowed path inputPath = '.'; } try { // Normalize and resolve the paths const normalizedInput = (0, node_path_1.normalize)(inputPath); const resolvedAllowed = (0, node_path_1.resolve)(allowedBasePath); const resolvedInput = (0, node_path_1.resolve)(resolvedAllowed, normalizedInput); // Ensure the allowed path ends with a separator for proper comparison const allowedWithSeparator = resolvedAllowed + (resolvedAllowed.endsWith('/') ? '' : '/'); const inputWithSeparator = resolvedInput + (resolvedInput.endsWith('/') ? '' : '/'); // Check if the resolved path is within the allowed directory // Must either be exactly the allowed path or start with allowedPath + separator if (resolvedInput !== resolvedAllowed && !inputWithSeparator.startsWith(allowedWithSeparator)) { throw new Error('Path traversal attempt detected - path must be within allowed directory'); } return resolvedInput; } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown path validation error'; throw new Error(`Invalid path: ${errorMessage}`); } }