Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
public static enforcePathRestrictions(givenTrustedRoot: string, givenPath: string): string {
const trustedRoot = FileEngine.path.resolve(givenTrustedRoot);
const trustedRootDetails = FileEngine.path.parse(trustedRoot);
if (trustedRootDetails.root === trustedRootDetails.dir && trustedRootDetails.base === '') {
const message = `"${trustedRoot}" cannot be the root of the filesystem.`;
throw new PathValidationError(message);
}
const unsafePath = FileEngine.path.resolve(trustedRoot, givenPath);
if (unsafePath.startsWith(trustedRoot) === false) {
const message = `Path traversal has been detected. Allowed path was "${trustedRoot}" but tested path "${givenPath}" attempted to reach "${unsafePath}"`;
throw new PathValidationError(message);
}
return unsafePath;
}