Window Location User Input Validation Codemod
This codemod automatically adds URL validation to JavaScript/TypeScript code that assigns user-controlled data to window.location properties, helping to prevent open redirect vulnerabilities and XSS attacks.
Security Impact
Vulnerability Type: CWE-601 (URL Redirection to Untrusted Site) and OWASP A03:2021 (Injection)
Direct assignment of user input to window.location.href or window.location can lead to:
- Open redirect attacks allowing attackers to redirect users to malicious sites
- XSS attacks via
javascript:URLs - Phishing attacks through legitimate-looking but malicious redirects
What It Does
This codemod identifies potentially dangerous location assignments and wraps them with URL validation:
Before
javascript
After
javascript
Patterns Transformed
window.location.href = userInputwindow.location = redirectUrllocation.href = params.get('redirect')location = new URLSearchParams(...).get('next')- Template literals and string concatenation in location assignments
Patterns Excluded
The codemod intelligently skips:
- Hardcoded string literals (
window.location.href = '/dashboard') - Relative paths starting with
/or./ - Assignments already wrapped in validation
- Test files (
*.test.js,*.spec.js,__tests__/)
Installation & Usage
bash
Examples
Template Literal Assignment
javascript
Parameter-based Redirect
javascript
Validation Logic
The generated isValidURL function:
- Uses the browser's native
URL()constructor for parsing - Only allows HTTP and HTTPS protocols (blocks
javascript:,data:, etc.) - Handles relative URLs by resolving against
window.location.origin - Gracefully handles malformed URLs with try-catch
Limitations
- Does not validate against allowlists of trusted domains
- May require manual review for complex redirect logic
- Generated validation is basic - consider enhanced validation for production use
Security References
- CWE-601: URL Redirection to Untrusted Site
- OWASP Top 10 2021 - A03 Injection
- OWASP Cheat Sheet: Unvalidated Redirects and Forwards Prevention
Development
bash
License
MIT