mirror of
https://github.com/kjanat/livedash-node.git
synced 2026-01-16 13:52:16 +01:00
feat: complete development environment setup and code quality improvements
- Set up pre-commit hooks with husky and lint-staged for automated code quality - Improved TypeScript type safety by replacing 'any' types with proper generics - Fixed markdown linting violations (MD030 spacing) across all documentation - Fixed compound adjective hyphenation in technical documentation - Fixed invalid JSON union syntax in API documentation examples - Automated code formatting and linting on commit - Enhanced error handling with better type constraints - Configured biome and markdownlint for consistent code style - All changes verified with successful production build
This commit is contained in:
@ -8,54 +8,54 @@ This document outlines the comprehensive Content Security Policy implementation
|
||||
|
||||
The enhanced CSP implementation provides:
|
||||
|
||||
- **Nonce-based script execution** for maximum security in production
|
||||
- **Strict mode policies** with configurable external domain allowlists
|
||||
- **Environment-specific configurations** for development vs production
|
||||
- **CSP violation reporting and monitoring** system with real-time analysis
|
||||
- **Advanced bypass detection and alerting** capabilities with risk assessment
|
||||
- **Comprehensive testing framework** with automated validation
|
||||
- **Performance metrics and policy recommendations**
|
||||
- **Framework compatibility** with Next.js, TailwindCSS, and Leaflet maps
|
||||
- **Nonce-based script execution** for maximum security in production
|
||||
- **Strict mode policies** with configurable external domain allowlists
|
||||
- **Environment-specific configurations** for development vs production
|
||||
- **CSP violation reporting and monitoring** system with real-time analysis
|
||||
- **Advanced bypass detection and alerting** capabilities with risk assessment
|
||||
- **Comprehensive testing framework** with automated validation
|
||||
- **Performance metrics and policy recommendations**
|
||||
- **Framework compatibility** with Next.js, TailwindCSS, and Leaflet maps
|
||||
|
||||
## Architecture
|
||||
|
||||
### Core Components
|
||||
|
||||
1. **CSP Utility Library** (`lib/csp.ts`)
|
||||
- Nonce generation with cryptographic security
|
||||
- Dynamic CSP building based on environment
|
||||
- Violation parsing and bypass detection
|
||||
- Policy validation and testing
|
||||
1. **CSP Utility Library** (`lib/csp.ts`)
|
||||
- Nonce generation with cryptographic security
|
||||
- Dynamic CSP building based on environment
|
||||
- Violation parsing and bypass detection
|
||||
- Policy validation and testing
|
||||
|
||||
2. **Middleware Implementation** (`middleware.ts`)
|
||||
- Automatic nonce generation per request
|
||||
- Environment-aware policy application
|
||||
- Enhanced security headers
|
||||
- Route-based CSP filtering
|
||||
2. **Middleware Implementation** (`middleware.ts`)
|
||||
- Automatic nonce generation per request
|
||||
- Environment-aware policy application
|
||||
- Enhanced security headers
|
||||
- Route-based CSP filtering
|
||||
|
||||
3. **Violation Reporting** (`app/api/csp-report/route.ts`)
|
||||
- Real-time violation monitoring with intelligent analysis
|
||||
- Rate-limited endpoint protection (10 reports/minute per IP)
|
||||
- Advanced bypass attempt detection with risk assessment
|
||||
- Automated alerting for critical violations with recommendations
|
||||
3. **Violation Reporting** (`app/api/csp-report/route.ts`)
|
||||
- Real-time violation monitoring with intelligent analysis
|
||||
- Rate-limited endpoint protection (10 reports/minute per IP)
|
||||
- Advanced bypass attempt detection with risk assessment
|
||||
- Automated alerting for critical violations with recommendations
|
||||
|
||||
4. **Monitoring Service** (`lib/csp-monitoring.ts`)
|
||||
- Violation tracking and metrics collection
|
||||
- Policy recommendation engine based on violation patterns
|
||||
- Export capabilities for external analysis (JSON/CSV)
|
||||
- Automatic cleanup of old violation data
|
||||
4. **Monitoring Service** (`lib/csp-monitoring.ts`)
|
||||
- Violation tracking and metrics collection
|
||||
- Policy recommendation engine based on violation patterns
|
||||
- Export capabilities for external analysis (JSON/CSV)
|
||||
- Automatic cleanup of old violation data
|
||||
|
||||
5. **Metrics API** (`app/api/csp-metrics/route.ts`)
|
||||
- Real-time CSP violation metrics (1h, 6h, 24h, 7d, 30d ranges)
|
||||
- Top violated directives and blocked URIs analysis
|
||||
- Violation trend tracking and visualization data
|
||||
- Policy optimization recommendations
|
||||
5. **Metrics API** (`app/api/csp-metrics/route.ts`)
|
||||
- Real-time CSP violation metrics (1h, 6h, 24h, 7d, 30d ranges)
|
||||
- Top violated directives and blocked URIs analysis
|
||||
- Violation trend tracking and visualization data
|
||||
- Policy optimization recommendations
|
||||
|
||||
6. **Testing Framework**
|
||||
- Comprehensive unit and integration tests
|
||||
- Enhanced CSP validation tools with security scoring
|
||||
- Automated compliance verification
|
||||
- Real-world scenario testing for application compatibility
|
||||
6. **Testing Framework**
|
||||
- Comprehensive unit and integration tests
|
||||
- Enhanced CSP validation tools with security scoring
|
||||
- Automated compliance verification
|
||||
- Real-world scenario testing for application compatibility
|
||||
|
||||
## CSP Policies
|
||||
|
||||
@ -118,9 +118,9 @@ const developmentCSP = {
|
||||
|
||||
### 1. Nonce-Based Script Execution
|
||||
|
||||
- **128-bit cryptographically secure nonces** generated per request
|
||||
- **Strict-dynamic policy** prevents inline script execution
|
||||
- **Automatic nonce injection** into layout components
|
||||
- **128-bit cryptographically secure nonces** generated per request
|
||||
- **Strict-dynamic policy** prevents inline script execution
|
||||
- **Automatic nonce injection** into layout components
|
||||
|
||||
```tsx
|
||||
// Layout with nonce support
|
||||
@ -149,27 +149,32 @@ export default async function RootLayout({ children }: { children: ReactNode })
|
||||
### 2. Content Source Restrictions
|
||||
|
||||
#### Script Sources
|
||||
- **Production**: Only `'self'` and nonce-approved scripts
|
||||
- **Development**: Additional `'unsafe-eval'` for dev tools
|
||||
- **Blocked**: All external CDNs, inline scripts without nonce
|
||||
|
||||
- **Production**: Only `'self'` and nonce-approved scripts
|
||||
- **Development**: Additional `'unsafe-eval'` for dev tools
|
||||
- **Blocked**: All external CDNs, inline scripts without nonce
|
||||
|
||||
#### Style Sources
|
||||
- **Production**: Nonce-based inline styles preferred
|
||||
- **Fallback**: `'unsafe-inline'` for TailwindCSS compatibility
|
||||
- **External**: Only self-hosted stylesheets
|
||||
|
||||
- **Production**: Nonce-based inline styles preferred
|
||||
- **Fallback**: `'unsafe-inline'` for TailwindCSS compatibility
|
||||
- **External**: Only self-hosted stylesheets
|
||||
|
||||
#### Image Sources
|
||||
- **Allowed**: Self, data URIs, schema.org, application domain
|
||||
- **Blocked**: All other external domains
|
||||
|
||||
- **Allowed**: Self, data URIs, schema.org, application domain
|
||||
- **Blocked**: All other external domains
|
||||
|
||||
#### Connection Sources
|
||||
- **Production**: Self, OpenAI API, application domain
|
||||
- **Development**: Additional WebSocket for HMR
|
||||
- **Blocked**: All other external connections
|
||||
|
||||
- **Production**: Self, OpenAI API, application domain
|
||||
- **Development**: Additional WebSocket for HMR
|
||||
- **Blocked**: All other external connections
|
||||
|
||||
### 3. XSS Protection Mechanisms
|
||||
|
||||
#### Inline Script Prevention
|
||||
|
||||
```javascript
|
||||
// Blocked by CSP
|
||||
<script>alert('xss')</script>
|
||||
@ -179,18 +184,21 @@ export default async function RootLayout({ children }: { children: ReactNode })
|
||||
```
|
||||
|
||||
#### Object Injection Prevention
|
||||
|
||||
```javascript
|
||||
// Completely blocked
|
||||
object-src 'none'
|
||||
```
|
||||
|
||||
#### Base Tag Injection Prevention
|
||||
|
||||
```javascript
|
||||
// Restricted to same origin
|
||||
base-uri 'self'
|
||||
```
|
||||
|
||||
#### Clickjacking Protection
|
||||
|
||||
```javascript
|
||||
// No framing allowed
|
||||
frame-ancestors 'none'
|
||||
@ -230,20 +238,21 @@ CSP violations are automatically reported to `/api/csp-report`:
|
||||
|
||||
### Violation Processing
|
||||
|
||||
1. **Rate Limiting**: 10 reports per minute per IP
|
||||
2. **Parsing**: Extract violation details and context
|
||||
3. **Risk Assessment**: Classify as low/medium/high risk
|
||||
4. **Bypass Detection**: Check for known attack patterns
|
||||
5. **Alerting**: Immediate notifications for critical violations
|
||||
1. **Rate Limiting**: 10 reports per minute per IP
|
||||
2. **Parsing**: Extract violation details and context
|
||||
3. **Risk Assessment**: Classify as low/medium/high risk
|
||||
4. **Bypass Detection**: Check for known attack patterns
|
||||
5. **Alerting**: Immediate notifications for critical violations
|
||||
|
||||
### Monitoring Dashboard
|
||||
|
||||
Violations are logged with:
|
||||
- Timestamp and source IP
|
||||
- User agent and referer
|
||||
- Violation type and blocked content
|
||||
- Risk level and bypass indicators
|
||||
- Response actions taken
|
||||
|
||||
- Timestamp and source IP
|
||||
- User agent and referer
|
||||
- Violation type and blocked content
|
||||
- Risk level and bypass indicators
|
||||
- Response actions taken
|
||||
|
||||
## Testing and Validation
|
||||
|
||||
@ -262,19 +271,20 @@ pnpm test:csp:full
|
||||
|
||||
### Manual Testing
|
||||
|
||||
1. **Nonce Validation**: Verify unique nonces per request
|
||||
2. **Policy Compliance**: Check all required directives
|
||||
3. **Bypass Resistance**: Test common XSS techniques
|
||||
4. **Framework Compatibility**: Ensure Next.js/TailwindCSS work
|
||||
5. **Performance Impact**: Measure overhead
|
||||
1. **Nonce Validation**: Verify unique nonces per request
|
||||
2. **Policy Compliance**: Check all required directives
|
||||
3. **Bypass Resistance**: Test common XSS techniques
|
||||
4. **Framework Compatibility**: Ensure Next.js/TailwindCSS work
|
||||
5. **Performance Impact**: Measure overhead
|
||||
|
||||
### Security Scoring
|
||||
|
||||
The validation framework provides a security score:
|
||||
- **90-100%**: Excellent implementation
|
||||
- **80-89%**: Good with minor improvements needed
|
||||
- **70-79%**: Needs attention
|
||||
- **<70%**: Serious security issues
|
||||
|
||||
- **90-100%**: Excellent implementation
|
||||
- **80-89%**: Good with minor improvements needed
|
||||
- **70-79%**: Needs attention
|
||||
- **<70%**: Serious security issues
|
||||
|
||||
## Deployment Considerations
|
||||
|
||||
@ -288,74 +298,74 @@ NODE_ENV=development # Enables permissive CSP
|
||||
|
||||
### Performance Impact
|
||||
|
||||
- **Nonce generation**: ~0.1ms per request
|
||||
- **Header processing**: ~0.05ms per request
|
||||
- **Total overhead**: <1ms per request
|
||||
- **Nonce generation**: ~0.1ms per request
|
||||
- **Header processing**: ~0.05ms per request
|
||||
- **Total overhead**: <1ms per request
|
||||
|
||||
### Browser Compatibility
|
||||
|
||||
- **Modern browsers**: Full CSP Level 3 support
|
||||
- **Legacy browsers**: Graceful degradation with X-XSS-Protection
|
||||
- **Reporting**: Supported in all major browsers
|
||||
- **Modern browsers**: Full CSP Level 3 support
|
||||
- **Legacy browsers**: Graceful degradation with X-XSS-Protection
|
||||
- **Reporting**: Supported in all major browsers
|
||||
|
||||
## Maintenance
|
||||
|
||||
### Regular Reviews
|
||||
|
||||
1. **Monthly**: Review violation reports and patterns
|
||||
2. **Quarterly**: Update content source restrictions
|
||||
3. **Per release**: Validate CSP with new features
|
||||
4. **Annually**: Security audit and penetration testing
|
||||
1. **Monthly**: Review violation reports and patterns
|
||||
2. **Quarterly**: Update content source restrictions
|
||||
3. **Per release**: Validate CSP with new features
|
||||
4. **Annually**: Security audit and penetration testing
|
||||
|
||||
### Updates and Modifications
|
||||
|
||||
When adding new content sources:
|
||||
|
||||
1. Update `buildCSP()` function in `lib/csp.ts`
|
||||
2. Add tests for new directives
|
||||
3. Validate security impact
|
||||
4. Update documentation
|
||||
1. Update `buildCSP()` function in `lib/csp.ts`
|
||||
2. Add tests for new directives
|
||||
3. Validate security impact
|
||||
4. Update documentation
|
||||
|
||||
### Incident Response
|
||||
|
||||
For CSP violations:
|
||||
|
||||
1. **High-risk violations**: Immediate investigation
|
||||
2. **Bypass attempts**: Security team notification
|
||||
3. **Mass violations**: Check for policy issues
|
||||
4. **False positives**: Adjust policies as needed
|
||||
1. **High-risk violations**: Immediate investigation
|
||||
2. **Bypass attempts**: Security team notification
|
||||
3. **Mass violations**: Check for policy issues
|
||||
4. **False positives**: Adjust policies as needed
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Development
|
||||
|
||||
- Always test CSP changes in development first
|
||||
- Use nonce provider for new inline scripts
|
||||
- Validate external resources before adding
|
||||
- Monitor console for CSP violations
|
||||
- Always test CSP changes in development first
|
||||
- Use nonce provider for new inline scripts
|
||||
- Validate external resources before adding
|
||||
- Monitor console for CSP violations
|
||||
|
||||
### Production
|
||||
|
||||
- Never disable CSP in production
|
||||
- Monitor violation rates and patterns
|
||||
- Keep nonce generation entropy high
|
||||
- Regular security audits
|
||||
- Never disable CSP in production
|
||||
- Monitor violation rates and patterns
|
||||
- Keep nonce generation entropy high
|
||||
- Regular security audits
|
||||
|
||||
### Code Review
|
||||
|
||||
- Check all inline scripts have nonce
|
||||
- Verify external resources are approved
|
||||
- Ensure CSP tests pass
|
||||
- Document any policy changes
|
||||
- Check all inline scripts have nonce
|
||||
- Verify external resources are approved
|
||||
- Ensure CSP tests pass
|
||||
- Document any policy changes
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **Inline styles blocked**: Use nonce or move to external CSS
|
||||
2. **Third-party scripts blocked**: Add to approved sources
|
||||
3. **Dev tools not working**: Ensure development CSP allows unsafe-eval
|
||||
4. **Images not loading**: Check image source restrictions
|
||||
1. **Inline styles blocked**: Use nonce or move to external CSS
|
||||
2. **Third-party scripts blocked**: Add to approved sources
|
||||
3. **Dev tools not working**: Ensure development CSP allows unsafe-eval
|
||||
4. **Images not loading**: Check image source restrictions
|
||||
|
||||
### Debug Tools
|
||||
|
||||
@ -374,19 +384,19 @@ curl -X POST /api/csp-report -d '{"csp-report": {...}}'
|
||||
|
||||
If CSP breaks production:
|
||||
|
||||
1. Check violation reports for patterns
|
||||
2. Identify blocking directive
|
||||
3. Test fix in staging environment
|
||||
4. Deploy emergency policy update
|
||||
5. Monitor for resolved issues
|
||||
1. Check violation reports for patterns
|
||||
2. Identify blocking directive
|
||||
3. Test fix in staging environment
|
||||
4. Deploy emergency policy update
|
||||
5. Monitor for resolved issues
|
||||
|
||||
## Compliance
|
||||
|
||||
This CSP implementation addresses:
|
||||
|
||||
- **OWASP Top 10**: XSS prevention
|
||||
- **CSP Level 3**: Modern security standards
|
||||
- **GDPR**: Privacy-preserving monitoring
|
||||
- **SOC 2**: Security controls documentation
|
||||
- **OWASP Top 10**: XSS prevention
|
||||
- **CSP Level 3**: Modern security standards
|
||||
- **GDPR**: Privacy-preserving monitoring
|
||||
- **SOC 2**: Security controls documentation
|
||||
|
||||
The enhanced CSP provides defense-in-depth against XSS attacks while maintaining application functionality and performance.
|
||||
The enhanced CSP provides defense-in-depth against XSS attacks while maintaining application functionality and performance.
|
||||
|
||||
Reference in New Issue
Block a user