feat: xss protection middleware #32
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Enhanced XSS Protection Middleware
This PR implements a comprehensive security middleware that protects our application against various Cross-Site Scripting (XSS) attack vectors. The solution provides robust input validation and sanitization while preserving legitimate content from WYSIWYG editors.
Key Features
Multi-layered Defense Approach
The middleware implements a multi-layered security approach that:
DOMPurify Integration
The core sanitization engine leverages DOMPurify, configured with:
Style Attribute Protection
The middleware includes specialized protection against CSS-based attacks:
url()values in CSSURL Sanitization
Comprehensive URL protection to prevent JavaScript injection:
rel="nofollow noopener noreferrer"Recursive Object Sanitization
The middleware implements a recursive approach to sanitize complex nested data structures:
CSS Expression Protection:
Implemented via
uponSanitizeAttributehookurl()values, and embedded scriptsEnhanced Style Protection
The middleware includes a specialized function to handle CSS-based attacks. This function provides a three-stage cleaning process:
Recursive Object Sanitization
The middleware implements a depth-first traversal of complex objects.
Security Benefits
This implementation addresses multiple XSS attack vectors:
Comprehensive Testing
The middleware includes an extensive test suite with 41 test cases covering:
Performance Considerations
Conclusion
This middleware provides robust XSS protection while balancing security and functionality. It sanitizes user input across the application while preserving legitimate content from WYSIWYG editors. The implementation handles modern attack vectors, complex nested structures, and preserves the UX by forcing links to open in new tabs with proper security attributes.
The comprehensive test suite ensures the middleware's effectiveness against a wide range of attack patterns while maintaining backward compatibility with existing functionality.