apiveritas
Version:
Lightweight CLI tool for consumer-driven API contract testing via JSON schema and payload comparisons.
62 lines (61 loc) • 2.93 kB
JavaScript
;
/**
* @file PathValidator.
* @author Mario Galea
* @description
* Provides safety checks and resolution logic for user-specified folder paths.
* Ensures configuration paths are not empty, malformed, or pointing to sensitive system directories.
* This module protects against accidental misconfiguration that could overwrite or access critical files.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PathValidator = void 0;
const path_1 = __importDefault(require("path"));
/**
* PathValidator validates folder paths used in the ApiVeritas config.
* It prevents the use of dangerous or inappropriate system paths and ensures
* that all folder paths used in the tool are safe and well-formed.
*/
class PathValidator {
/**
* Determines if the given path is suspicious and potentially harmful (e.g., a system directory).
* This prevents users from accidentally targeting critical areas of the filesystem.
*
* @param {string} p - Path to evaluate
* @returns {boolean} True if the path is deemed risky
*/
static isSuspiciousPath(p) {
const normalized = path_1.default.resolve(p).toLowerCase();
return this.riskyRoots.some(root => normalized === root || normalized.startsWith(root + path_1.default.sep));
}
/**
* Validates and resolves a folder path from the configuration.
* If the path is empty, undefined, or suspicious, a fallback path is used instead.
* Logs a warning when falling back, if a logger is provided.
*
* @param {string | undefined} folderPath - The path string provided by the user (relative or absolute)
* @param {string} fallbackPath - The default path to use if validation fails
* @param {string} label - Label used in logging to identify the setting (e.g., "payloadsPath")
* @param {{ warn: (msg: string) => void }} [logger] - Optional logger with a `warn` method
* @returns {string} A safe and validated absolute path
*/
static validateFolderPath(folderPath, fallbackPath, label, logger) {
if (!folderPath || folderPath.trim() === '') {
logger?.warn(`Config: ${label} not set or empty. Using default: ${fallbackPath}`);
return fallbackPath;
}
const resolved = path_1.default.resolve(folderPath);
if (this.isSuspiciousPath(resolved)) {
logger?.warn(`Config: ${label} path "${resolved}" is suspicious or unsafe. Using default: ${fallbackPath}`);
return fallbackPath;
}
return resolved;
}
}
exports.PathValidator = PathValidator;
/**
* List of system-critical root paths considered unsafe to write into or use as output folders.
*/
PathValidator.riskyRoots = ['/', '/etc', '/bin', '/boot', '/sys', '/proc'];