CSP Builder
Compose a Content-Security-Policy header from common directive sources.
Overview
The CSP Builder composes a Content-Security-Policy header from a checklist of directive sources — default-src, script-src, style-src, img-src, connect-src, and so on — and writes the final header in the exact format browsers expect. It enforces uniqueness, removes redundant values, and warns when you combine sources that cancel each other out ('none' with anything else).
It is for security engineers, SREs, and front-end developers hardening a site against XSS, clickjacking, and third-party script injection. Common questions it answers include how to build a Content-Security-Policy header from scratch and how to allow specific script sources without using unsafe-inline.
How it works
CSP is defined in CSP Level 3 and uses a series of directives, each holding a space-separated source list. Sources include keywords ('self', 'none', 'unsafe-inline', 'strict-dynamic'), schemes (https:, data:), hostnames (example.com), and nonces or hashes ('nonce-abc123', 'sha256-...'). Browsers fall back to default-src for any fetch directive you don't set explicitly.
The builder emits directives in a stable order, deduplicates sources, and includes a report-to or report-uri line if you want violations sent to a collector. It also flags policies that include 'unsafe-inline' alongside a nonce, which is permitted but rarely intended.
Examples
- A strict baseline produces
default-src 'self'; img-src 'self' data:; script-src 'self' 'nonce-abc123'; object-src 'none'; base-uri 'self';. - Allowing inline styles emits
style-src 'self' 'unsafe-inline'with a warning that nonces are safer. - A reporting-only header prefixes with
Content-Security-Policy-Report-Only:and appendsreport-to csp-endpoint. - A media-heavy site adds
media-src https: data:to allow audio/video from any HTTPS origin.
FAQ
Should I deliver CSP as a header or a meta tag?
The HTTP header is strongly preferred. The <meta> form has no access to certain directives (frame-ancestors, report-uri) and runs after the document starts parsing.
What's the difference between a nonce and a hash?
A nonce is a one-time token you embed on the script tag and in the header. A hash is the SHA digest of the script body. Use a hash when the script is static, a nonce when content is rendered server-side per request.
Why is unsafe-inline considered dangerous?
It defeats the main XSS protection CSP offers. Any attacker who can inject HTML can now inject executable JavaScript. Migrate to nonces or hashes when possible.
Does CSP block all XSS?
No. CSP mitigates the impact by restricting what injected code can do, but proper input validation and output escaping remain essential.