configure-security-headers-csp
Skill9 starsChanged 5 months agoApache-2.0View on GitHub
Configures HTTP response security headers and a strict, nonce/hash-based Content-Security-Policy — script-src with a per-request nonce or sha256 hash plus 'strict-dynamic' (so you can drop host allowlists and 'unsafe-inline'), object-src 'none', base-uri 'none', frame-ancestors to control framing, a Report-Only rollout via report-to/report-uri before enforcing, plus HSTS with includeSubDomains+preload, X-Content-Type-Options: nosniff, Referrer-Policy, a deny-by-default Permissions-Policy, correct CORS (echo a single allowed origin, never wildcard '*' together with Access-Control-Allow-Credentials), and cookie flags Secure+HttpOnly+SameSite. Eliminates inline-script XSS sinks, clickjacking, MIME-sniffing, mixed content, and credentialed-CORS leaks by policy rather than per-bug patching.
In this repository147 other files it gives its agents.
- second-brain/AGENTS.mdAGENTS.md
- second-brain/CLAUDE.mdCLAUDE.md
- agent-tool-mcp-builderSkill
- api-design-reviewSkill
- async-concurrency-correctnessSkill
- audit-accessibility-wcagSkill
- audit-license-complianceSkill
- audit-technical-seoSkill
- auth-jwt-sessionSkill
- author-codemodSkill
- brainstorm-designSkill
- build-audit-loggingSkill
- build-cdc-streaming-pipelineSkill
- build-cli-toolSkill
- build-data-tableSkill
- build-etl-pipelineSkill
- build-form-validationSkill
- build-native-mobile-uiSkill
- build-office-docsSkill
- build-offline-first-syncSkill
- build-react-componentSkill
- build-realtime-channelSkill
- build-spreadsheetSkill
- build-vector-searchSkill
- caching-strategySkill
- cicd-pipeline-authorSkill
- cloud-cost-optimizeSkill
- code-commentsSkill
- code-reviewSkill
- compose-local-dev-stackSkill
- configure-bundler-buildSkill
- configure-dns-tlsSkill
- configure-reverse-proxy-lbSkill
- contract-testingSkill
- datetime-timezone-correctnessSkill
- db-migration-safetySkill
- debug-ci-pipeline-failureSkill
- debug-flaky-testsSkill
- debug-frontend-browserSkill
- debug-root-causeSkill
- defend-llm-prompt-injectionSkill
- deliver-webhooksSkill
- dependency-upgradeSkill
- deploy-releaseSkill
- design-api-paginationSkill
- design-authorization-modelSkill
- design-backup-dr-recoverySkill
- design-event-sourcing-cqrsSkill
- design-multi-tenancySkill
- design-protobuf-grpc-serviceSkill
- design-relational-schemaSkill
- design-search-index-infraSkill
- design-state-machineSkill
- design-token-systemSkill
- diff-table-paritySkill
- distributed-locks-leasesSkill
- dockerfile-optimizeSkill
- encrypt-sensitive-dataSkill
- error-messageSkill
- estimate-workSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 82
Never trust substring/regex matches like endsWith('.example.com') (matches evilexample.com) or startsWith('https://example.com') (matches …
- Very specific: line 83
If you don't need credentials, prefer Access-Control-Allow-Origin: * without credentials — that's safe and simpler.
- Very specific: line 113
Scan the live headers: run the response through securityheaders.com / Mozilla Observatory, or curl -sI https://site — confirm a single …
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
When to Use
Reach for this skill when the task is setting HTTP response headers and CSP as defense-in-depth policy, not chasing one specific vulnerability:
- "Add a Content-Security-Policy" / "our CSP uses 'unsafe-inline' — make it strict"
- "After turning on CSP the page broke: Refused to execute inline script / Refused to load the stylesheet"
- "Enable HSTS / submit the domain to the preload list"
- "Stop the site from being framed / set frame-ancestors / X-Frame-Options"
- "Set Referrer-Policy and lock down Permissions-Policy (camera, geolocation, FLoC)"
- "Our CORS sends
Access-Control-Allow-Origin: *with credentials — is that safe?" (no) - "Cookies missing Secure/HttpOnly/SameSite" / harden the Set-Cookie flags
NOT this skill:
- Finding/fixing a concrete bug — reflected/stored XSS sink, open redirect, SSRF, SQLi — and sanitizing the offending code path → remediate-web-vulnerabilities (this skill is the header containment layer that limits the blast radius of such bugs)
- Configuring the CDN/WAF/edge that injects, caches, or overrides these headers, or rate-limits at the edge → setup-cdn-edge-waf (this skill defines the header values it should emit)
- TLS certs, cipher suites, OCSP, ACME issuance, the TLS handshake behind HSTS → configure-dns-tls (HSTS only asserts TLS is mandatory; it doesn't provision it)
- Reverse-proxy/load-balancer routing where you might also add these headers (nginx/Envoy/Traefik) → configure-reverse-proxy-lb (this skill says which headers; that one places them in the proxy)
- The OAuth/OIDC redirect, token, and session-cookie protocol → integrate-oauth-oidc / auth-jwt-session (this skill only hardens the cookie flags and CORS around them)
- Structured threat enumeration (STRIDE) or a full audit pass → threat-model-stride / security-review
- Active fuzzing/DAST to prove a bypass → fuzz-dynamic-security-test
Steps
Default to a strict, nonce- or hash-based CSP — host allowlists are obsolete and bypassable. Allowlist CSPs (
script-src 'self' cdn.example.com) are trivially defeated via JSONP endpoints, open redirects, or AngularJS on a whitelisted host (Google's own research found ~94% of allowlist CSPs bypassable). The strict pattern:Content-Security-Policy: script-src 'nonce-{RANDOM}' 'strict-dynamic' https: 'unsafe-inline'; object-src 'none'; base-uri 'none'; require-trusted-types-for 'script'; report-uri /csp-report; report-to csp'strict-dynamic'lets a nonced/hashed script load further scripts it creates, so you don't enumerate every CDN. When present, browsers that understand it ignorehttps:and'unsafe-inline'— those are fallbacks for old browsers only, not a real relaxation.object-src 'none'kills Flash/<object>injection;base-uri 'none'stops<base href>from rewriting relative script URLs.- You usually don't need
default-srcmicromanaged oncescript-srcis strict; the dangerous directive is script execution.
Generate a fresh 128-bit nonce per response and stamp it on every inline
<script>. The nonce must be cryptographically random and unique per HTTP response (never reuse, never hardcode) — a static nonce is equivalent to'unsafe-inline'.Stack Generate Apply Express res.locals.nonce = crypto.randomBytes(16).toString('base64')helmet contentSecurityPolicywith(req,res)=>nonce;<script nonce="<%= nonce %>">`Next.js nonce in middleware.ts, pass via headerNext injects nonce into its own scripts when CSP header has a nonce Django django-csp@csp_update/{{ request.csp_nonce }}<script nonce="{{ request.csp_nonce }}">Rails config.content_security_policy_nonce_generatorjavascript_tag nonce: true/nonce: truein tagsGo/Caddy/nginx per-request var (sub_filter or middleware) template the nonce into markup For static/cached HTML where you can't inject a per-response nonce, use
'sha256-...'hashes of each inline script's exact bytes instead (compute at build time). Nonces require dynamic rendering; hashes work on a CDN.Roll out in Report-Only first — never flip enforcing CSP straight to prod. Ship
Content-Security-Policy-Report-Only(same policy) alongside any existing enforced policy, collect violations for days/weeks, fix legitimate breakage, then promote to the enforcing header. Wire reporting with the modernreport-to(aReporting-Endpointsheader naming a collector) and keep deprecatedreport-urifor older browsers:Reporting-Endpoints: csp="https://example.com/csp-report" Content-Security-Policy-Report-Only: script-src 'nonce-...' 'strict-dynamic'; report-to csp; report-uri /csp-reportExpect noise from browser extensions injecting inline scripts — triage by
blocked-uri/source-file; don't widen the policy to silence extension reports.- Set
frame-ancestorsto control framing — it supersedes X-Frame-Options.frame-ancestors 'none'(no framing) orframe-ancestors 'self' https://trusted.example.com(allow specific embedders). Browsers honorframe-ancestorsover the legacyX-Frame-Options: DENY|SAMEORIGINwhen both exist; keepX-Frame-Options: DENYonly as a fallback for ancient clients. XFO has no allowlist-multiple-origins capability —frame-ancestorsis the real control. Pin the rest of the header set — each closes a specific class.
Header Value (strong default) Closes Strict-Transport-Securitymax-age=63072000; includeSubDomains; preloadSSL-strip / downgrade; mandates HTTPS for 2y X-Content-Type-OptionsnosniffMIME-sniffing a JSON/text response into executable HTML/JS Referrer-Policystrict-origin-when-cross-origin(orno-referrer)leaking full URL + query (tokens) in RefererPermissions-Policycamera=(), microphone=(), geolocation=(), interest-cohort=()abuse of powerful features; deny-by-default ()= nobodyCross-Origin-Opener-Policysame-origincross-window attacks; required (with COEP) to re-enable SharedArrayBufferCross-Origin-Resource-Policysame-origin(orsame-site)side-channel/Spectre cross-origin reads (data leak) X-Frame-OptionsDENY(legacy fallback only)clickjacking on old browsers (else use frame-ancestors)HSTS rules: only send over HTTPS;
includeSubDomainscovers every subdomain (verify they're all HTTPS first);preloadis a near-irreversible commitment — once on the browser preload list, removal takes months, so don't add it until you're certain all subdomains are HTTPS-only. Submit at hstspreload.org.Permissions-Policyreplaces the oldFeature-Policy;interest-cohort=()opts out of FLoC/Topics.- CORS: echo exactly one validated origin — NEVER wildcard with credentials. The single most common CORS vuln is
Access-Control-Allow-Origin: *(or reflectingOriginblindly) together withAccess-Control-Allow-Credentials: true, which lets any site read authenticated responses.- The spec forbids
*+ credentials — but reflecting theOriginheader unchecked is the same hole. Validate the incomingOriginagainst an allowlist, and only then echo it back:Access-Control-Allow-Origin: <that exact origin>+Vary: Origin. - Never trust substring/regex matches like
endsWith('.example.com')(matchesevilexample.com) orstartsWith('https://example.com')(matcheshttps://example.com.evil.com). Match the full origin against an explicit set. - If you don't need credentials, prefer
Access-Control-Allow-Origin: *without credentials — that's safe and simpler. Don't reflectnull(sandboxed iframes/file://sendOrigin: null— allowlistingnullis exploitable). - Set
Vary: Originwhenever the ACAO value depends on the request, or a cache will serve one origin's allowed-response to another.
- The spec forbids
Harden cookies:
Secure; HttpOnly; SameSite— and__Host-for session cookies. Every session/auth cookie:Set-Cookie: __Host-session=...; Secure; HttpOnly; SameSite=Lax; Path=/Secure— only sent over HTTPS.HttpOnly— invisible todocument.cookie, so an XSS can't exfiltrate it.SameSite=Lax(default-safe; blocks cross-site POST CSRF) orStrictfor the most sensitive; useSameSite=None; Secureonly for genuine cross-site cookies (and then you need CSRF defense).- The
__Host-prefix forcesSecure,Path=/, and noDomain— the browser rejects the cookie if those aren't met, preventing subdomain cookie-fixation. Use it for session cookies.__Secure-is the weaker variant (just requiresSecure).
- Set headers once, at the right layer, and don't let it get clobbered. Prefer a single source of truth: app middleware (helmet /
secure_headers/django-csp) or the edge/proxy — not both fighting. If a CDN/WAF (setup-cdn-edge-waf) or reverse proxy (configure-reverse-proxy-lb) also injects headers, confirm which wins (proxies often append, producing duplicate/conflicting CSP — the browser then enforces the intersection, which can silently break the page). Apply headers to all responses including errors, redirects, and API/JSON. Use helmet (Express),secure_headersgem (Rails),django-csp+SecurityMiddleware(Django), orsecurityheadersmiddleware (Go) rather than hand-rolling.
Common Errors
- Allowlist CSP with
'unsafe-inline'.script-src 'self' 'unsafe-inline'provides essentially zero XSS protection — inline injected scripts run. Fix: nonce/hash +'strict-dynamic', drop'unsafe-inline'(keep it only as the old-browser fallback that strict-dynamic neutralizes). - Reusing or hardcoding the nonce. A static/cached nonce =
'unsafe-inline'; the attacker just reads it from the page and reuses it. Fix: fresh CSPRNG nonce per response; for cacheable HTML use hashes instead. - Flipping enforcing CSP straight to prod. You blank-screen real users on day one. Fix:
-Report-Onlyfirst, collect viareport-to/report-uri, fix breakage, then enforce. 'unsafe-eval'left in to satisfy a library. Re-openseval/Functioninjection. Fix: move to a CSP-compatible build (no runtime eval); add Trusted Types (require-trusted-types-for 'script') instead of loosening.- CSP only on HTML, missing
object-src/base-uri.<base>hijack or<object>injection bypasses a script-only policy. Fix: always addobject-src 'none'; base-uri 'none'. Access-Control-Allow-Origin: *(or reflected Origin) withAllow-Credentials: true. Any website reads the victim's authenticated data. Fix: allowlist + echo the single matched origin +Vary: Origin; or drop credentials and use*.- Substring origin matching.
origin.endsWith('example.com')allowsnotexample.com/example.com.evil.com. Fix: exact full-origin set membership. - HSTS
preloadadded prematurely / withoutincludeSubDomains. A non-HTTPS subdomain becomes unreachable, and preload removal takes months. Fix: confirm every subdomain is HTTPS-only beforeincludeSubDomains; preload; rampmax-ageup gradually. - Setting HSTS over plain HTTP. Ignored by browsers and a sign of misconfig. Fix: emit HSTS only on HTTPS responses; redirect HTTP→HTTPS first.
- Cookies without
HttpOnly/Secure/SameSite. XSS steals the session; CSRF rides it; it leaks over HTTP. Fix:__Host-name=...; Secure; HttpOnly; SameSite=Lax. - Duplicate CSP headers from app + proxy. Browser enforces the intersection of all CSP headers, silently breaking the stricter-than-intended result. Fix: one owner of the header; verify the response has a single CSP.
- Missing
nosniff, so an API returns user content astext/html. Browser sniffs and executes it. Fix:X-Content-Type-Options: nosniffon every response and correctContent-Type.
Verify
- Scan the live headers: run the response through
securityheaders.com/ Mozilla Observatory, orcurl -sI https://site— confirm a singleContent-Security-Policy,Strict-Transport-Security,X-Content-Type-Options: nosniff,Referrer-Policy,Permissions-Policy, andframe-ancestorspresent, with no duplicates. - CSP is strict: the policy contains a
'nonce-...'or'sha256-...'inscript-srcwith'strict-dynamic'and no standalone'unsafe-inline'/'unsafe-eval'that a modern browser honors;object-src 'none'andbase-uri 'none'present. Validate with Google's CSP Evaluator. - Nonce is per-response: fetch the page twice — the nonce value differs each time and matches the inline
<script nonce=...>tags. - Report-Only worked: the violation collector received reports and they were triaged before enforcing; the enforced policy doesn't blank the app (load the real pages, check the console for
Refused to...). - CORS is safe:
curl -H 'Origin: https://evil.com' -Ito a credentialed endpoint returns noAccess-Control-Allow-Originforevil.com(or omits credentials); an allowlisted origin gets that exact origin echoed plusVary: Origin. No*+credentials anywhere. - Cookies hardened:
Set-Cookieon the session cookie showsSecure; HttpOnly; SameSite=...(and__Host-prefix for session); inspect in DevTools → Application → Cookies. - HSTS sane:
Strict-Transport-Securityonly on HTTPS,max-age≥ 1 year,includeSubDomainsonly if every subdomain is HTTPS;preloadonly when committed (verify at hstspreload.org). - Clickjacking blocked: attempt to frame the site from another origin → blocked by
frame-ancestors;X-Content-Type-Options: nosniffconfirmed so atext/plainAPI body isn't sniffed to HTML.
Done = a strict nonce/hash CSP with 'strict-dynamic' and no honored 'unsafe-inline', rolled out via Report-Only then enforced; HSTS (preload only when safe), nosniff, frame-ancestors, Referrer-Policy and a deny-by-default Permissions-Policy all present exactly once; CORS validates origin against an allowlist and never pairs */reflected-origin with credentials; and session cookies carry Secure+HttpOnly+SameSite (__Host- prefixed) — all proven by the header scan, CSP evaluator, and CORS/cookie checks above.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

