Production Implementation Strategies

Production Implementation Strategies

Implementing advanced CSP patterns in production requires careful planning:

// Production CSP Implementation
class ProductionCSPImplementation {
  constructor(config) {
    this.config = config;
    this.combinator = new AdvancedCSPCombinator();
  }
  
  // Middleware for production use
  createProductionMiddleware() {
    return async (req, res, next) => {
      try {
        // Determine CSP level based on user agent
        const cspLevel = this.determineCSPLevel(req.headers['user-agent']);
        
        // Generate appropriate policy
        const { nonce, policy } = await this.generatePolicyForLevel(cspLevel);
        
        // Set security headers
        this.setSecurityHeaders(res, policy);
        
        // Make nonce available to application
        res.locals.nonce = nonce;
        res.locals.cspLevel = cspLevel;
        
        // Add performance monitoring
        res.locals.cspTiming = {
          start: Date.now(),
          level: cspLevel
        };
        
        next();
      } catch (error) {
        console.error('CSP middleware error:', error);
        // Fallback to basic CSP on error
        res.setHeader('Content-Security-Policy', this.config.fallbackPolicy);
        next();
      }
    };
  }
  
  determineCSPLevel(userAgent) {
    // Simple browser detection (use proper library in production)
    const ua = userAgent.toLowerCase();
    
    if (ua.includes('chrome/9') || ua.includes('firefox/8')) {
      return 'advanced'; // Strict-dynamic support
    } else if (ua.includes('chrome/4') || ua.includes('firefox/3')) {
      return 'modern'; // Nonce support
    } else {
      return 'basic'; // Fallback
    }
  }
  
  async generatePolicyForLevel(level) {
    switch (level) {
      case 'advanced':
        return this.combinator.generateHybridPolicy({ 
          backwardCompatible: false 
        });
        
      case 'modern':
        const nonce = this.combinator.nonceManager.generateNonce();
        return {
          nonce,
          policy: this.generateNoncePolicy(nonce)
        };
        
      default:
        return {
          nonce: null,
          policy: this.config.fallbackPolicy
        };
    }
  }
  
  setSecurityHeaders(res, cspPolicy) {
    // CSP header
    res.setHeader('Content-Security-Policy', cspPolicy);
    
    // Additional security headers
    res.setHeader('X-Content-Type-Options', 'nosniff');
    res.setHeader('X-Frame-Options', 'DENY');
    res.setHeader('X-XSS-Protection', '0'); // Disabled in favor of CSP
    res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
    
    // Feature Policy / Permissions Policy
    res.setHeader('Permissions-Policy', 
      'accelerometer=(), camera=(), geolocation=(), microphone=()'
    );
  }
  
  generateNoncePolicy(nonce) {
    return [
      "default-src 'self'",
      `script-src 'self' 'nonce-${nonce}'`,
      `style-src 'self' 'nonce-${nonce}'`,
      "img-src 'self' data: https:",
      "font-src 'self'",
      "connect-src 'self'",
      "frame-ancestors 'none'",
      "base-uri 'self'",
      "form-action 'self'"
    ].join('; ');
  }
}

Advanced CSP patterns like nonces, hashes, and strict-dynamic provide powerful tools for implementing robust security policies while maintaining application functionality. By understanding and properly implementing these patterns, developers can create CSP policies that effectively prevent XSS attacks without compromising user experience or development flexibility. The key to success lies in choosing the right pattern for your specific use case and implementing it with careful attention to browser compatibility and performance considerations.## Common CSP Errors and How to Fix Them

Content Security Policy implementation often encounters predictable errors that can frustrate developers and compromise security goals. Understanding these common errors, their root causes, and proven solutions enables faster troubleshooting and more robust implementations. This comprehensive guide catalogs the most frequent CSP errors, explains why they occur, and provides practical fixes with real-world code examples.