Générateur CSP (Basique)

Construisez une chaîne Content-Security-Policy valide depuis des listes de directives

What is Content Security Policy?

Content Security Policy (CSP) is a security standard that allows web developers to declare which sources of content are permitted to load on their pages. Delivered as an HTTP response header or a <meta> tag, CSP instructs browsers to block resources that violate the declared policy, effectively mitigating cross-site scripting (XSS), clickjacking, data injection, and other code injection attacks. By defining an explicit allowlist of trusted origins for scripts, styles, images, fonts, frames, and network connections, CSP eliminates the browser's default permissive behavior of executing any inline script or loading resources from arbitrary domains.

The W3C Content Security Policy Level 3 specification defines the current directive set and enforcement model. CSP operates on a deny-by-default principle: any resource type not explicitly allowed by a directive is blocked. This tool generates complete CSP headers from your configuration, producing a ready-to-deploy policy string that you can paste directly into your server configuration, reverse proxy rules, or HTML <meta http-equiv="Content-Security-Policy"> tags.

Core CSP Directives Explained

A Content Security Policy is composed of directives, each governing a specific resource type. Understanding these directives is essential for building policies that are both secure and functional:

  • default-src: The fallback directive for any resource type that does not have its own explicit directive. Setting default-src 'self' restricts all resources to the same origin unless overridden by a more specific directive.
  • script-src: Controls which scripts can execute on the page. Supports 'self', specific origins, 'nonce-{random}', 'sha256-{hash}', and 'strict-dynamic' for propagating trust to dynamically loaded scripts.
  • style-src: Governs CSS stylesheets and inline styles. Use nonces or hashes to allow specific inline styles without enabling 'unsafe-inline' globally.
  • img-src: Defines allowed sources for images, favicons, and image-based content. Common values include 'self', data: for inline SVGs, and CDN domains.
  • connect-src: Restricts origins for XMLHttpRequest, Fetch API, WebSocket, EventSource, and navigator.sendBeacon. Critical for APIs that communicate with backend services.
  • font-src: Controls font file loading. Typically includes 'self' and font CDN origins like Google Fonts or self-hosted font directories.
  • frame-src: Specifies which origins can be embedded in <iframe>, <frame>, and <object> elements on your page.
  • object-src: Controls plugins like Flash and Java applets. Set to 'none' in modern applications — there is no legitimate use case for plugin content today.
  • base-uri: Restricts the URLs that can appear in the <base> element, preventing attackers from redirecting relative URLs to a malicious origin.
  • form-action: Limits where forms can submit data, blocking form hijacking attacks that redirect submissions to attacker-controlled endpoints.
  • frame-ancestors: Controls which origins can embed your page in frames. Replaces the older X-Frame-Options header and prevents clickjacking attacks. Note: this directive cannot be set via <meta> tags — it requires an HTTP header.

XSS Mitigation with Nonce-Based and Hash-Based Policies

Cross-site scripting remains the most prevalent web vulnerability, and CSP is the strongest browser-enforced defense against it. Traditional CSP approaches relied on origin allowlists, but modern best practice favors nonce-based or hash-based policies for superior XSS protection:

Nonce-based CSP assigns a unique cryptographically random token to each HTTP response. Only scripts that carry the matching nonce attribute execute. The server generates a new nonce per request, making it impossible for an attacker to predict and inject a valid script tag:

  • Generate a 128-bit random nonce per response using a CSPRNG
  • Include the nonce in the CSP header: script-src 'nonce-abc123...'
  • Add the same nonce to legitimate script tags: <script nonce="abc123...">
  • Injected scripts without the nonce are blocked by the browser

Hash-based CSP allows specific inline scripts by their cryptographic hash. The browser computes the SHA-256, SHA-384, or SHA-512 hash of each inline script and compares it against the hashes declared in the policy. This approach works well for static inline scripts that do not change between deployments:

  • Compute the hash: echo -n "scriptContent" | openssl dgst -sha256 -binary | base64
  • Declare in policy: script-src 'sha256-{base64hash}'
  • Any modification to the script content invalidates the hash, blocking execution

The 'strict-dynamic' keyword extends trust from a nonced or hashed script to any scripts it loads dynamically, simplifying policies for applications that use module loaders or runtime script injection. When 'strict-dynamic' is present, allowlist entries like https: and 'self' are ignored for script loading — trust propagates only through the trusted script chain.

Violation Reporting with report-uri and report-to

Deploying a Content Security Policy without monitoring is flying blind. CSP provides built-in violation reporting mechanisms that send structured JSON reports to a configured endpoint whenever the browser blocks a resource:

The report-uri directive (CSP Level 2) specifies a URL that receives violation reports via POST requests. Each report contains the blocked URI, the violated directive, the document URI, and a sample of the offending content. While functional, report-uri is deprecated in favor of the newer Reporting API:

The report-to directive (CSP Level 3) uses the Reporting API to deliver structured reports to named endpoint groups defined in the Report-To HTTP header. This approach supports batching, retries, and priority ordering across multiple reporting endpoints.

For gradual rollout, deploy CSP in report-only mode using the Content-Security-Policy-Report-Only header. This instructs browsers to report violations without actually blocking resources — allowing you to refine your policy based on real traffic patterns before switching to enforcement mode. A typical deployment strategy follows these stages:

  1. Deploy in report-only mode with a permissive policy and monitoring endpoint
  2. Analyze violation reports to identify legitimate resources being flagged
  3. Tighten the policy iteratively, adding necessary source allowances
  4. Switch from report-only to enforcement when violations reach zero for production traffic
  5. Maintain a report-to endpoint in production to catch regressions from new deployments

CSP Generator vs CSP Inspector

This tool and the CSP Inspector serve complementary roles in the Content Security Policy workflow. The CSP Generator is a policy authoring tool — you configure directives, specify allowed sources, and it produces a complete, syntactically correct CSP header string ready for deployment. Use the generator when:

  • Building a new CSP from scratch for a web application
  • Adding directives to an existing policy
  • Generating nonce-based or hash-based script policies
  • Creating both enforcement and report-only header variants
  • Producing <meta> tag syntax for static HTML pages

The CSP Inspector performs the reverse operation — it takes an existing CSP header string and parses it into its component directives, validates syntax, detects redundancies, identifies overly permissive rules (like 'unsafe-inline' or 'unsafe-eval'), and scores the policy's security effectiveness. Use the inspector when auditing existing deployments or debugging violation reports.

A typical workflow combines both tools: generate an initial policy with this tool, deploy it in report-only mode, analyze violations, refine in the inspector, and regenerate the final enforcement policy here.

Code Examples

Constructing a strict CSP header with nonce support

// Generate a strict CSP header for a modern web application
import { randomBytes } from 'node:crypto';

function generateCspHeader(nonce) {
  const directives = {
    'default-src': ["'self'"],
    'script-src': ["'self'", `'nonce-${nonce}'`, "'strict-dynamic'"],
    'style-src': ["'self'", `'nonce-${nonce}'`],
    'img-src': ["'self'", 'data:', 'https://cdn.example.com'],
    'font-src': ["'self'"],
    'connect-src': ["'self'", 'https://api.example.com'],
    'frame-src': ["'none'"],
    'object-src': ["'none'"],
    'base-uri': ["'self'"],
    'form-action': ["'self'"],
    'frame-ancestors': ["'none'"],
    'report-to': ['csp-endpoint'],
  };

  return Object.entries(directives)
    .map(([key, values]) => `${key} ${values.join(' ')}`)
    .join('; ');
}

// Generate a per-request nonce (128-bit, base64-encoded)
const nonce = randomBytes(16).toString('base64');
const cspHeader = generateCspHeader(nonce);

// Set the header in your HTTP response
// Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-abc...' 'strict-dynamic'; ...

CSP via HTML meta tag for static sites

<!-- CSP meta tag for static HTML pages (no server-side header control) -->
<!-- Note: frame-ancestors, report-uri, and sandbox cannot be set via meta tags -->
<meta http-equiv="Content-Security-Policy" content="
  default-src 'self';
  script-src 'self' 'sha256-RFWPLDbv2BY+rCkDzsE+0fr8ylGr2R2faWMhq4lfEQc=';
  style-src 'self' 'unsafe-inline';
  img-src 'self' data: https:;
  font-src 'self';
  connect-src 'self' https://api.example.com;
  object-src 'none';
  base-uri 'self';
  form-action 'self'
">

Standards & Specifications