Safe Path Join Blocking Traversal
A path resolver that joins untrusted segments onto a base directory and rejects any attempt to escape it via dot dot segments or absolute paths.
Code
import { isAbsolute, join, normalize, resolve, sep } from "node:path";
export class PathTraversalError extends Error {
constructor(message: string) {
super(message);
this.name = "PathTraversalError";
}
}
/**
* Resolve untrusted segments against a base directory, refusing any escape.
* Containment is verified with an explicit prefix check after normalization. */
export function safeJoin(baseDir: string, ...segments: string[]): string {
const base = resolve(baseDir);
for (const segment of segments) {
if (typeof segment !== "string" || segment.length === 0) {
throw new PathTraversalError("path segments must be non-empty strings");
}
if (isAbsolute(segment)) {
throw new PathTraversalError("absolute path segments are not allowed: " + segment);
}
}
const target = normalize(join(base, ...segments));
if (target !== base && !target.startsWith(base + sep)) {
throw new PathTraversalError("resolved path escapes the base directory: " + target);
}
return target;
}Joining a user supplied filename onto a base directory with plain path.join lets ../../etc/passwd escape the base and read or write outside it.
Use case: engineers serving files or writing uploads from user supplied names
Inputs / outputs
- Input: a base directory and one or more untrusted path segments
- Output: the resolved absolute path inside the base, or a PathTraversalError
Error conditions
- segment contains a parent directory escape
- segment is absolute
- resolved path falls outside the base
Approach
reject absolute segments, normalize the join, then verify the resolved path still starts with the base directory plus a separator.
Implementation
import { isAbsolute, join, normalize, resolve, sep } from "node:path";
export class PathTraversalError extends Error {
constructor(message: string) {
super(message);
this.name = "PathTraversalError";
}
}
/**
* Resolve untrusted segments against a base directory, refusing any escape.
* Containment is verified with an explicit prefix check after normalization. */
export function safeJoin(baseDir: string, ...segments: string[]): string {
const base = resolve(baseDir);
for (const segment of segments) {
if (typeof segment !== "string" || segment.length === 0) {
throw new PathTraversalError("path segments must be non-empty strings");
}
if (isAbsolute(segment)) {
throw new PathTraversalError("absolute path segments are not allowed: " + segment);
}
}
const target = normalize(join(base, ...segments));
if (target !== base && !target.startsWith(base + sep)) {
throw new PathTraversalError("resolved path escapes the base directory: " + target);
}
return target;
}
Verification tests
import { test } from "node:test";
import assert from "node:assert/strict";
import { sep, join, resolve } from "node:path";
import { PathTraversalError, safeJoin } from "./example.ts";
// 期望值按当前平台构造,避免硬编码 POSIX 路径在 Windows 上失败
const base = resolve("/srv/files");
test("allows a plain nested segment", () => {
const out = safeJoin(base, "reports", "2026", "q1.csv");
assert.equal(out, join(base, "reports", "2026", "q1.csv"));
});
test("allows the base directory itself", () => {
assert.equal(safeJoin(base), base);
});
test("rejects a dot dot escape", () => {
assert.throws(
() => safeJoin(base, "..", "..", "etc", "passwd"),
PathTraversalError,
);
});
test("rejects an absolute segment", () => {
assert.throws(() => safeJoin(base, "/etc/passwd"), PathTraversalError);
});
test("rejects an empty segment", () => {
assert.throws(() => safeJoin(base, ""), PathTraversalError);
});
Dependencies and running
No external dependencies (standard library only).
Runtime: node >= 18 Entry point: node –experimental-strip-types example.ts
Limitations and error handling
no symlink resolution (a symlink inside the base can still point outside); no Windows device names check.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.