Path Traversal Guard For File Access

Resolve file paths within a base directory and reject traversal attempts using dot segments and symlink escape detection.

JavascriptSecurity Boundaries

Code

javascriptsnippet
1 line
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

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.