Skip to content

Content Security Policy (CSP) Middleware #324

@phertyameen

Description

@phertyameen

Labels: middleware, security, xss-prevention, medium-priority

Description:

Implement Content Security Policy headers to prevent XSS attacks, code injection, and other security vulnerabilities.

Requirements:

Set CSP headers on all responses

  • Define trusted sources for different content types:
  1. Scripts: Self, CDN domains
  2. Styles: Self, inline styles (with nonces), Google Fonts
  3. Images: Self, data URIs, CDN domains
  4. Fonts: Self, Google Fonts
  5. Connect: Self, API endpoints
  6. Frame: None (prevent clickjacking)
  • Support nonce-based inline script execution
  • Report CSP violations to monitoring endpoint
  • Different CSP policies for development vs production
  • Support CSP report-only mode for testing
  • Prevent unsafe-inline and unsafe-eval in production
  • Handle third-party integrations (analytics, payment gateways)

Acceptance Criteria:

  • CSP headers included in all responses

  • XSS attacks blocked by browser CSP enforcement

  • Legitimate resources (CDN, fonts) load correctly

  • Inline scripts use nonce-based CSP (not unsafe-inline)

  • CSP violations logged for security monitoring

  • Development mode allows more permissive policies for debugging

  • Production mode enforces strict policies

  • Third-party scripts only from whitelisted domains

  • No console errors from blocked resources

  • CSP configuration easily updated via environment variables

  • CSP Directives:

default-src: 'self'
script-src: 'self', 'nonce-{random}', trusted CDNs
style-src: 'self', 'unsafe-inline' (for styled-components), fonts.googleapis.com
img-src: 'self', data:, https:, CDN domains
font-src: 'self', fonts.gstatic.com
connect-src: 'self', API domains
frame-ancestors: 'none' (prevent clickjacking)
base-uri: 'self'
form-action: 'self'

  • Nonce Generation:

Unique nonce per request
Cryptographically random
Attached to script tags dynamically

  • CSP Reporting:

report-uri: /api/csp-violation
Log violations to security monitoring
Alert on suspicious violation patterns

  • Third-Party Integrations to Allow:

Google Fonts
CDN for static assets
Analytics services (when added)
Payment gateways (future)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions