Path Traversal Guard For File Access
Resolve file paths within a base directory and reject traversal attempts using dot segments and symlink escape detection.
Code
import path from'node:path';import fs from'node:fs';export function safeResolve(base,target){const resolved=path.resolve(base,target);const normBase=path.resolve(base);if(!resolved.startsWith(normBase+path.sep)&&resolved!==normBase)throw new Error('path traversal detected');return resolved;}export async function safeResolveReal(base,target){const resolved=safeResolve(base,target);const real=await fs.promises.realpath(resolved);const realBase=await fs.promises.realpath(base);if(!real.startsWith(realBase+path.sep)&&real!==realBase)throw new Error('symlink escape detected');return real;}What the code does
Count the functions safeResolve and safeResolveReal as the entire surface area of Path Traversal Guard For File Access.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. When the guard condition holds, Error is thrown rather than a bogus value returned.
Watch out for
- The only import,
node:path, is part of the Node.js standard library.
Using it in your own code
The main signature reads export function safeResolve(base,target)
The surface worth importing is safeResolve; the helpers around it are private to the snippet.
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- What happens on invalid input?
- The code refuses to continue: `Error` is thrown while the state is still recoverable.
- What does this import from outside the project?
- Only `node:path`, and that is a Node.js built-in — it comes with the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.