import path from 'path';
import os from 'os';
/**
* Safe path utilities with directory escape protection
*/
/**
* Resolve a path and ensure it doesn't escape a base directory
* Prevents directory traversal attacks
*/
export function resolveSafePath(basePath: string, userPath: string): string {
// Normalize paths
const base = path.resolve(basePath);
const requested = path.resolve(basePath, userPath);
// Ensure the requested path is within the base path
const relative = path.relative(base, requested);
if (relative.startsWith('..') || path.isAbsolute(relative)) {
throw new Error(`Access denied: Path escape attempt detected for ${userPath}`);
}
return requested;
}
/**
* Get user home directory
*/
export function getHomeDirectory(): string {
return os.homedir();
}
/**
* Get current working directory
*/
export function getCurrentDirectory(): string {
return process.cwd();
}
/**
* Normalize path for display
*/
export function normalizePath(filePath: string): string {
const home = getHomeDirectory();
if (filePath.startsWith(home)) {
return filePath.replace(home, '~');
}
return filePath;
}