Validate and normalize a file path for security.
Ensures paths are safe to use by preventing directory traversal attacks and enforcing consistent formatting. All paths are normalized to use forward slashes and start with a leading slash.
This function is designed for virtual filesystem paths and rejects Windows absolute paths (e.g., C:/..., F:/...) to maintain consistency and prevent path format ambiguity.
validateFilePath(path: string, allowedPrefixes: string[]): string| Name | Type | Description |
|---|---|---|
path* | string | The path to validate and normalize. |
allowedPrefixes | string[] | Optional list of allowed path prefixes. If provided, the normalized path must start with one of these prefixes. |
validateFilePath("foo/bar") // Returns: "/foo/bar"
validateFilePath("/./foo//bar") // Returns: "/foo/bar"
validateFilePath("../etc/passwd") // Throws: Path traversal not allowed
validateFilePath("C:\\Users\\file.txt") // Throws: Windows absolute paths not supported
validateFilePath("/data/file.txt", ["/data/"]) // Returns: "/data/file.txt"
validateFilePath("/etc/file.txt", ["/data/"]) // Throws: Path must start with...