Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/lib/path-validation.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import fs from 'fs';
import path from 'path';

/**
* Validates that a resolved path is within the given directory.
* Follows symlinks to prevent symlink-based path traversal.
* Throws if the path escapes the directory (path traversal).
* Returns the resolved (normalized) path.
*/
export function assertWithinDir(targetPath: string, allowedDir: string): string {
const resolved = path.resolve(targetPath);
const dir = path.resolve(allowedDir);
const resolved = fs.realpathSync(targetPath);
const dir = fs.realpathSync(allowedDir);
if (!resolved.startsWith(dir + path.sep) && resolved !== dir) {
throw new Error(`Path traversal detected: ${resolved} is outside allowed directory ${dir}`);
}
Expand Down