Writing Content Security Policy Headers With LLMs in November 2026: Start in Report-Only, Use Nonces Instead of unsafe-inline, and Tighten One Directive at a Time
Ask an LLM to "add a Content Security Policy to my app" and you will usually get one of two results. The first is a policy so loose it does nothing: script-src * 'unsafe-inline' 'unsafe-eval', which lets almost any script run. The second is a policy so strict it breaks your site the moment you deploy it, because the model never saw your analytics snippet, your inline event handlers, or the third-party widget on the checkout page.
A good CSP sits between those two, and getting there is a process rather than a one-shot prompt. This guide shows how to use an LLM to help you write, test, and tighten a Content Security Policy without locking out your own users.
What a CSP actually does
A Content Security Policy is an HTTP response header that tells the browser which sources of scripts, styles, images, frames, and other content a page is allowed to load. If an attacker manages to inject a <script> tag into your page through a cross-site scripting (XSS) bug, a well-written CSP stops the browser from running it.
That last part is important: CSP is a second line of defense. It does not fix XSS. You still need to escape output and sanitize HTML. CSP limits the damage when something slips through.
The header looks like this:
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'none'
Each part separated by a semicolon is a directive. default-src is the fallback for most fetch types you do not list separately. script-src controls JavaScript. object-src 'none' blocks plugins like old Flash embeds. base-uri stops an injected <base> tag from rewriting where your relative URLs point.
A CSP works like a building's visitor list: anything not on it does not get in, no matter how it got through the door. Image: Mega Tower, Ortigas Center, visitor's pass by LastCelebration, CC0, via Wikimedia Commons.
Step 1: Give the model an inventory, not a guess
The most common reason LLM-written policies break sites is that the model has to guess what your pages load. Do not let it guess. Before you prompt, collect a real inventory:
- Every external domain your pages load scripts, styles, fonts, images, or iframes from. Open your browser's developer tools, go to the Network tab, load your main pages, and note the domains.
- Every inline
<script>block and inlinestyleattribute in your templates. - Every inline event handler, such as
onclick="..."oronload="...". - Any use of
eval(),new Function(), or string arguments tosetTimeout. - Where your API calls go (this feeds
connect-src), including WebSocket URLs. - Whether your HTML is rendered per request by a server, or served as static files from a CDN.
A quick way to find inline scripts and handlers in a codebase:
grep -rnE "<script(\s[^>]*)?>[^<]" templates/ src/
grep -rnE "\son(click|load|submit|change|error)=" templates/ src/
Paste that inventory into your prompt. A prompt that works well looks like this:
Write a Content-Security-Policy for this app.
Rendering: server-rendered HTML from Express, one response per request.
External script hosts: https://js.stripe.com, https://plausible.io
External style hosts: https://fonts.googleapis.com
Font hosts: https://fonts.gstatic.com
Images: self, data: URIs, https://images.example-cdn.com
Frames we embed: https://js.stripe.com
API and WebSocket: https://api.example.com, wss://api.example.com
Inline scripts: 3 (listed below)
Inline event handlers: 7 onclick attributes (listed below)
Requirements: no 'unsafe-inline' for scripts, no 'unsafe-eval'.
Use nonces. Explain each directive in one line.
Also list every code change needed for the policy to work.
The last line matters most. A strict policy almost always requires code changes, and you want the model to tell you about them up front rather than leaving you to discover them in the console.
Step 2: Prefer nonces over host allowlists for scripts
Many LLMs still default to the older style of CSP, which lists every allowed script domain:
script-src 'self' https://cdn.jsdelivr.net https://www.googletagmanager.com
The trouble with host allowlists is that large public hosts often serve files an attacker can abuse, such as old library versions or JSONP endpoints. If the host is allowed, anything on it is allowed.
The approach recommended in current security guidance is a nonce-based policy. Your server generates a fresh random value for every response, puts it in the header, and adds the same value to each script tag it trusts:
Content-Security-Policy: script-src 'nonce-R4nd0mV4lu3' 'strict-dynamic'; object-src 'none'; base-uri 'none'
<script nonce="R4nd0mV4lu3" src="/app.js"></script>
An injected script will not have the right nonce, so the browser refuses to run it. 'strict-dynamic' means scripts that a trusted script loads are trusted too, which keeps tag managers and bundler-loaded chunks working without listing every host.
Here is a minimal Express example. Ask the model for the equivalent in your framework, and check that it matches these rules:
import crypto from "node:crypto";
app.use((req, res, next) => {
const nonce = crypto.randomBytes(16).toString("base64");
res.locals.cspNonce = nonce;
res.setHeader(
"Content-Security-Policy",
[
`script-src 'nonce-${nonce}' 'strict-dynamic'`,
"object-src 'none'",
"base-uri 'none'",
"frame-ancestors 'self'",
].join("; ")
);
next();
});
Things to check in whatever the model gives you:
- The nonce is new on every response. A nonce stored in a constant, an environment variable, or generated once at startup is useless, because an attacker can read it from any page.
- The nonce comes from a cryptographically secure generator (
crypto.randomBytes, Python'ssecrets, and so on), with at least 128 bits of randomness. NotMath.random(). - The nonce is only added to script tags you wrote. If your template engine adds it to user-provided HTML, you have handed the attacker the key.
- Pages with a nonce are not cached and shared between users. If a CDN caches the HTML, every visitor gets the same nonce.
When you cannot use nonces: hashes
If your site is static HTML served from a CDN, you cannot generate a nonce per request. Use hashes instead. A hash source allows one exact inline script whose SHA-256 digest matches:
script-src 'sha256-B2yPHKaXnvFWtRChIbabYmUBFZdVfKKXHbWtWidDVF8=' 'strict-dynamic'
Ask the model to write a build step that computes the hashes from your final HTML files, rather than asking it to compute hashes by hand. LLMs cannot reliably produce a correct SHA-256 digest in their head, and a wrong hash silently blocks the script. Generate them with a tool:
echo -n 'console.log("hello")' | openssl dgst -sha256 -binary | openssl base64
The hash must cover the exact bytes between the opening and closing script tags, including whitespace and newlines. A reformatting step after hashing will break it.
A nonce is a pass issued fresh for each visit. A gate that accepts last week's pass is not checking anything. Image: At the gate 130812-Z-IB888-008 by Spc. Lerone Simmons (U.S. Army), Public domain, via Wikimedia Commons.
Step 3: Ship it in Report-Only mode first
Never deploy a new CSP straight into enforcement on a live site. Browsers support a second header, Content-Security-Policy-Report-Only, which reports what the policy would block without blocking anything.
Content-Security-Policy-Report-Only: script-src 'nonce-...' 'strict-dynamic'; object-src 'none'; base-uri 'none'; report-to csp-endpoint
Reporting-Endpoints: csp-endpoint="https://example.com/csp-reports"
The report-to directive with the Reporting-Endpoints header is the newer reporting mechanism. The older report-uri directive is deprecated but still widely supported, and many sites send both during the transition so that browsers without report-to support still report. Ask the model to include both and to explain which browsers use which.
You also need somewhere for reports to land. Ask the LLM for a small endpoint that accepts the report JSON, drops obviously noisy entries, and logs the rest. Check that it:
- Limits the request body size, because anyone can post to it.
- Rate-limits by IP or simply samples, so a misbehaving page cannot flood your logs.
- Does not trust anything in the report. Reports come from browsers you do not control and can be forged.
Run Report-Only for long enough to see real traffic on all your important pages: sign-up, checkout, account settings, any page with embedded content. A few days to a week is typical for small sites.
Reading the reports with an LLM
This is where an LLM is genuinely useful. Export a sample of reports and ask the model to group them:
Here are 200 CSP violation reports from Report-Only mode.
Group them by violated directive and blocked URI.
For each group, say whether it looks like:
(a) our own code that needs fixing,
(b) a legitimate third party we should allow,
(c) a browser extension or other noise.
Do not suggest 'unsafe-inline' or wildcard sources.
Browser extensions inject scripts and styles into pages and generate a lot of reports with sources like chrome-extension:// or moz-extension://. Those are noise. Do not loosen your policy to silence them. Verify the model's groupings yourself before acting on them, especially anything it labels as noise.
Step 4: Fix your code instead of loosening the policy
Most violations from your own code fall into a few patterns. Ask the model to rewrite each one, and review the diff:
- Inline event handlers.
<button onclick="save()">is blocked by a nonce policy. Move it to a script:document.querySelector("#save").addEventListener("click", save). javascript:URLs.<a href="javascript:openMenu()">is also blocked. Replace with a button and an event listener.evalandnew Function. These need'unsafe-eval'. Find out which library uses them; many template and schema libraries have a mode that avoids them.- Inline scripts that set config. Put the data in a
<script type="application/json" id="config">block and read it withJSON.parse, or give the inline block a nonce.
Inline style attributes are blocked by a strict style-src. Many sites accept 'unsafe-inline' for styles as a practical trade-off, since style injection is far less dangerous than script injection. If you take that trade-off, do it deliberately and write down why, rather than letting the model add it to get rid of errors.
Step 5: Add the directives that are easy wins
Some directives cost almost nothing and close real gaps. Make sure your final policy includes:
object-src 'none'to block plugin content.base-uri 'none'(or'self'if you use a base tag) so injected base tags cannot redirect your scripts.frame-ancestors 'self'(or'none') to stop other sites from framing your pages for clickjacking. This replaces the olderX-Frame-Optionsheader for modern browsers, and it only works in a real HTTP header, not in a<meta>tag.form-action 'self'plus any payment or login hosts your forms really submit to, so an injected form cannot post your users' data elsewhere.
The fact that frame-ancestors and reporting are ignored in a meta tag catches people out. If the model suggests putting your CSP in <meta http-equiv="Content-Security-Policy">, ask it to move it to a response header, unless you truly cannot set headers on your host.
Step 6: Enforce, then tighten one directive at a time
When the reports from your own pages are quiet, switch the header name from Content-Security-Policy-Report-Only to Content-Security-Policy. Keep a Report-Only header alongside it for the next, stricter version you want to try. That way you are always enforcing a policy you have tested, and testing the next one on real traffic.
Change one directive per release. If you tighten script-src, connect-src, and img-src at once and something breaks, you will spend more time finding out which change did it.
Testing the policy you deploy
Do not trust that the header is set just because the code is merged. Check the real response:
curl -sI https://example.com/ | grep -i content-security-policy
Then check that:
- The header appears on every HTML response, including error pages and redirects that render HTML. Frameworks often skip middleware on 404 pages.
- Two requests return two different nonces.
- There is only one enforcing policy. If both your app and your CDN or reverse proxy add a CSP header, the browser enforces both, and content must pass every one.
- An injected test script is actually blocked. On a staging site, add
<script>alert(1)</script>to a page without a nonce and confirm the console shows a violation and no alert.
Google's free CSP Evaluator at csp-evaluator.withgoogle.com checks a policy for common weaknesses, such as missing object-src or risky allowlisted hosts. It is a useful second opinion on what the LLM produced.
Red flags in LLM-generated policies
Reject or question any generated policy that contains:
'unsafe-inline'inscript-srcwithout a nonce or hash. (When a nonce or hash is present, browsers that support them ignore'unsafe-inline', so some policies include it only as a fallback for very old browsers. Ask the model which case you are in.)'unsafe-eval'with no explanation of which library needs it.- Wildcards like
*,https:, or*.amazonaws.cominscript-src. data:inscript-src. It is fine inimg-src, not for scripts.- A nonce that is hardcoded, reused, or generated with a non-cryptographic random function.
- Hashes the model wrote out itself instead of computing them with a tool.
- Domains in the policy that are not in the inventory you gave it. Ask where each one came from.
A checklist to keep
- Build an inventory of everything your pages load, plus inline scripts and handlers.
- Give the inventory to the model and ask for a nonce-based (or hash-based, for static sites) policy, plus the code changes it needs.
- Review nonce generation: fresh, secure, per response, never cached.
- Deploy as Report-Only with a safe reporting endpoint.
- Group reports, fix your own code, ignore extension noise.
- Add
object-src,base-uri,frame-ancestors, andform-action. - Switch to enforcing, keep testing the next version in Report-Only, and tighten one directive at a time.
- Verify the real header with curl and a staged injection test.
An LLM can save you hours of reading directive reference pages, and it is very good at turning a pile of violation reports into a short list of fixes. What it cannot do is see your site. Give it the facts, make it explain every source it allows, and let real browser reports, not the model's confidence, decide when the policy is ready to enforce.
Comments
Post a Comment