export const exhaustiveInvalidUriPaths = { emptyPath: "", spacesInPath: "/invalid path/with spaces", specialCharacter1: "/path/with|invalid>characters", specialCharacter2: "/path/with", reservedCharacter2: '/path/with/"quotes"', reservedCharacter3: "/path/with/[brackets]", reservedCharacter4: "/path/with/\\backslashes", nonAscii1: "/path/with/你好", nonAscii2: "/path/with/emoji/😃", mixedEncodingPath: "/path/%41A%42B%C3%28", directoryTraversal1: "/path/../../etc/passwd", directoryTraversal2: "/path/./././", } type ValidationErrorReason = | "TooLong" | "InvalidURI" | "Empty" | "ContainsQuery" | "ContainsFragment" export function isValidRedirectPath(path: string): { isValid: boolean reason: ValidationErrorReason | undefined } { const trimmedPath = path.toLowerCase().trim() const url = "https://www.example.com" + trimmedPath if (url.length > 2048) { return { isValid: false, reason: "TooLong", } } if (trimmedPath === "") { return { isValid: false, reason: "Empty", } } if (url === "/") { return { isValid: false, reason: "Empty", } } if (url.includes("?")) { return { isValid: false, reason: "ContainsQuery", } } if (url.includes("#")) { return { isValid: false, reason: "ContainsFragment", } } const regex = /^\/[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/ const isValid = regex.test(trimmedPath) return { isValid: regex.test(trimmedPath), reason: !isValid ? "InvalidURI" : undefined, } }