@codemod/fetch-credentials-same-origin
Security Codemod: Transform fetch() calls to use credentials: 'same-origin' instead of credentials: 'include' to prevent CSRF vulnerabilities.
Overview
Using credentials: 'include' in fetch() calls can lead to Cross-Site Request Forgery (CSRF) vulnerabilities by automatically sending cookies with cross-origin requests. This codemod helps improve your application's security posture by transforming these calls to use credentials: 'same-origin', ensuring cookies are only sent to same-origin requests.
Security Impact
- Vulnerability: Cross-Site Request Forgery (CSRF) - CWE-352
- OWASP Category: A01:2021 – Broken Access Control
- Severity: Critical
Installation & Usage
bash
Transformations
This codemod transforms the following patterns:
Basic fetch() calls
Before:
javascript
After:
javascript
Complex options objects
Before:
javascript
After:
javascript
Variable assignments
Before:
javascript
After:
javascript
Template literals and member expressions
Before:
javascript
After:
javascript
What is NOT transformed
The codemod preserves code that is already secure or has legitimate use cases:
- fetch() calls with credentials: 'same-origin' (already secure)
- fetch() calls with credentials: 'omit' (no credentials sent)
- fetch() calls without any credentials property (uses browser default)
- Non-fetch function calls
Security Considerations
When credentials: 'include' might be legitimate
In rare cases, you might legitimately need cross-origin cookies:
- Trusted third-party APIs: When integrating with trusted services that require authentication cookies
- Single Sign-On (SSO): When implementing SSO across trusted domains
- Embedded widgets: When building widgets for trusted partner sites
After applying this codemod
- Test thoroughly: Ensure your application still functions correctly
- Review failed requests: Check for any API calls that were relying on cross-origin cookies
- Implement CSRF tokens: For state-changing operations, implement CSRF protection
- Consider SameSite cookies: Use SameSite=Strict or SameSite=Lax cookie attributes
File Patterns
The codemod processes:
- **/*.js - JavaScript files
- **/*.jsx - React JavaScript files
- **/*.ts - TypeScript files
- **/*.tsx - React TypeScript files
And excludes:
- **/node_modules/** - Dependencies
- **/*.test.* - Test files
- **/*.spec.* - Specification files
- **/test/**, **/tests/**, **/__tests__/** - Test directories
- **/dist/**, **/build/** - Build output
Development
bash
Security References
- OWASP CSRF Prevention Cheat Sheet
- MDN fetch() credentials documentation
- CWE-352: Cross-Site Request Forgery (CSRF)
- SameSite cookie attribute recommendations
License
MIT