All files / helpers url.ts

100% Statements 4/4
100% Branches 5/5
100% Functions 1/1
100% Lines 4/4

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34                                                1x 27x 3x         24x    
/**
 * URL security utilities to prevent Open Redirect attacks
 */
 
/**
 * Validates that a return URL is safe for redirection.
 *
 * Prevents Open Redirect vulnerabilities by ensuring the URL:
 * - Starts with a single slash (relative path)
 * - Does not start with // (protocol-relative URL)
 * - Does not start with /\ (IE-specific bypass)
 * - Does not use dangerous protocols (javascript:, data:, vbscript:, etc.)
 *
 * @param url - The URL to validate
 * @returns true if the URL is safe for redirection
 *
 * @example
 * ```typescript
 * isValidReturnUrl('/dashboard')     // true
 * isValidReturnUrl('/articles/123')  // true
 * isValidReturnUrl('//evil.com')     // false
 * isValidReturnUrl('javascript:...')  // false
 * ```
 */
export function isValidReturnUrl(url?: string): boolean {
    if (!url) {
        return false;
    }
 
    // Must start with single slash (relative path)
    // Reject: //, /\, javascript:, data:, etc.
    return url.startsWith('/') && !url.startsWith('//') && !url.startsWith('/\\');
}