Files
skills/public/security-security-headers.html
zeekay 747dafba10 Register WebMCP tools on every page, and name each page's twin from site.py
Every page now loads /webmcp.js, scripts/webmcp.ts with its types
stripped (npm run webmcp). Where the browser has document.modelContext
it registers two read-only tools: search_skills over the published
skills index, and get_skill, which returns a skill's markdown checked
against the index digest. The markdown alternate link moves from
build.py to site.py, so CI holds every page to it.

The API catalog gains the site itself (llms.txt and the skills index)
and hanzo.ai/agents; the live discovery check now fetches every
catalog link. tests/site.mjs drives the tools through a recording
modelContext, and checks a browser without one loads clean.
2026-10-26 20:57:05 -07:00

738 lines
37 KiB
HTML

<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>security-security-headers</title>
<meta name="color-scheme" content="dark">
<style>
/* Committed to one visual world: a dark instrument panel. No light variant —
the dot field and the hairline rules only read on black, and a naive
inversion would wash both out. Every colour is painted explicitly so the page
never borrows a host background. */
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
:root{
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
--font-zen-pixel-square:'Zen Pixel Square',monospace;
--mono:var(--font-zen-mono);
--sans:var(--font-zen-sans);
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
--r:999px; --r-soft:14px;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
/* The dot field. A halftone made of one repeating radial-gradient, faded out
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
/* No overflow clip here: the dot field is inset to the box already, and a clip
would cut off the copy-prompt menu. */
.hero{position:relative;border-bottom:1px solid var(--line)}
.hero::before{content:"";position:absolute;inset:0;
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
background-size:7px 7px;
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
pointer-events:none}
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
nav{border-bottom:1px solid var(--line)}
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
justify-content:space-between;align-items:center;gap:1rem}
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--ink);text-decoration:none;
display:inline-flex;align-items:center;gap:.6rem}
.brand i{font-style:normal;color:var(--faint)}
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--soft);text-decoration:none}
nav a.up:hover{color:var(--ink)}
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
h1 em{font-style:normal;color:var(--faint)}
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
line-height:1.2;font-weight:400}
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
.btn.solid:hover{background:#d8d8d4}
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
/* Copy-prompt selector. Each row copies the prompt for its own target. */
.copy{position:relative;display:inline-flex}
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
padding:.4rem;display:flex;flex-direction:column;
box-shadow:0 12px 32px rgba(0,0,0,.75)}
.menu[hidden]{display:none}
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
white-space:nowrap}
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
.mi:hover .mark{color:var(--ink)}
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
letter-spacing:.1em;text-transform:uppercase}
/* Works-with bar: one scrolling row, name and mark per agent. */
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
display:flex;align-items:center}
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
-webkit-overflow-scrolling:touch;
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
.bar::-webkit-scrollbar{display:none}
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
text-decoration:none;background:var(--ground)}
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
.agent .mark{width:.95rem;height:.95rem}
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
p{margin:0 0 1rem;max-width:70ch}
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
li{margin:.22rem 0}
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
text-decoration-color:var(--line-hi)}
a:hover{text-decoration-color:var(--ink)}
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
display:block;overflow-x:auto}
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
.curl{display:block;background:var(--panel);border:1px solid var(--line);
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
white-space:pre;line-height:1.9}
.curl b{color:var(--ink);font-weight:400}
.curl i{font-style:normal;color:var(--faint)}
/* index */
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
#q:focus{outline:none;border-color:var(--soft)}
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
text-transform:uppercase;margin:0 0 2rem}
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
padding-bottom:.45rem}
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
border-radius:var(--r-soft);text-decoration:none}
.row:hover{background:#0a0a0a}
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
color:var(--faint);font-size:.85rem}
footer a{color:var(--soft)}
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
margin:0 0 2rem;font-size:.85rem}
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
border-bottom:1px solid var(--line);padding-bottom:.4rem}
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
.fmap a:hover{text-decoration:underline}
.fmap div{color:var(--faint);line-height:1.5}
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
@media (max-width:640px){
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
.btns{gap:.5rem}
.btn{padding:.75rem 1.15rem;font-size:.68rem}
.copy,.copy .btn{width:100%;justify-content:center}
.menu{left:0;right:0;min-width:0}
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
.strip b{border-right:0;padding-right:0}
.bar{width:100%}
}
</style>
<link rel="icon" href="/favicon.svg">
<link rel="canonical" href="https://hanzoskills.com/security-security-headers">
<link rel="alternate" type="text/markdown" href="/security-security-headers.md">
<script type="module" src="/webmcp.js"></script>
</head>
<!-- Reading this with a machine? Every page here is also plain markdown.
This one: https://hanzoskills.com/security-security-headers.md
Index: https://hanzoskills.com/llms.txt
Corpus: https://hanzoskills.com/all.md
Append .md to any path for the markdown twin. -->
<body>
<nav><div class="in">
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
<a class="up" href="/">All skills</a>
</div></nav>
<div class="wrap">
<h1>security-security-headers</h1><p class="lede">HTTP security headers including CSP, HSTS, X-Frame-Options, CORS, and other protective headers for web application security</p><h1>Security: Security Headers</h1>
<p><strong>Scope</strong>: HTTP security headers, CSP, HSTS, CORS, XSS protection <strong>Lines</strong>: ~350 <strong>Last Updated</strong>: 2025-10-27</p>
<h2>When to Use This Skill</h2>
<p>Activate this skill when:</p>
<ul><li>Hardening web application security</li><li>Preventing clickjacking, XSS, and MITM attacks</li><li>Configuring Content Security Policy (CSP)</li><li>Setting up CORS for APIs</li><li>Implementing HTTPS enforcement (HSTS)</li><li>Protecting against browser-based attacks</li><li>Passing security audits and penetration tests</li></ul>
<h2>Essential Security Headers</h2>
<h3>Complete Header Configuration</h3>
<pre><code class="lang-python">from flask import Flask, make_response
app = Flask(__name__)
@app.after_request
def add_security_headers(response):
&quot;&quot;&quot;Apply security headers to all responses&quot;&quot;&quot;
# Prevent clickjacking
response.headers[&#x27;X-Frame-Options&#x27;] = &#x27;DENY&#x27;
# Enable browser XSS protection
response.headers[&#x27;X-XSS-Protection&#x27;] = &#x27;1; mode=block&#x27;
# Prevent MIME type sniffing
response.headers[&#x27;X-Content-Type-Options&#x27;] = &#x27;nosniff&#x27;
# Enforce HTTPS
response.headers[&#x27;Strict-Transport-Security&#x27;] = (
&#x27;max-age=31536000; includeSubDomains; preload&#x27;
)
# Content Security Policy
response.headers[&#x27;Content-Security-Policy&#x27;] = (
&quot;default-src &#x27;self&#x27;; &quot;
&quot;script-src &#x27;self&#x27; https://cdn.example.com; &quot;
&quot;style-src &#x27;self&#x27; &#x27;unsafe-inline&#x27;; &quot;
&quot;img-src &#x27;self&#x27; data: https:; &quot;
&quot;font-src &#x27;self&#x27; https://fonts.gstatic.com; &quot;
&quot;connect-src &#x27;self&#x27; https://api.example.com; &quot;
&quot;frame-ancestors &#x27;none&#x27;; &quot;
&quot;base-uri &#x27;self&#x27;; &quot;
&quot;form-action &#x27;self&#x27;;&quot;
)
# Referrer policy
response.headers[&#x27;Referrer-Policy&#x27;] = &#x27;strict-origin-when-cross-origin&#x27;
# Permissions policy (formerly Feature Policy)
response.headers[&#x27;Permissions-Policy&#x27;] = (
&#x27;geolocation=(), microphone=(), camera=()&#x27;
)
return response</code></pre>
<h2>Content Security Policy (CSP)</h2>
<h3>CSP Directives</h3>
<pre><code class="lang-python">class CSPBuilder:
&quot;&quot;&quot;Build Content Security Policy header&quot;&quot;&quot;
def __init__(self):
self.directives = {
&#x27;default-src&#x27;: [&quot;&#x27;self&#x27;&quot;],
&#x27;script-src&#x27;: [&quot;&#x27;self&#x27;&quot;],
&#x27;style-src&#x27;: [&quot;&#x27;self&#x27;&quot;],
&#x27;img-src&#x27;: [&quot;&#x27;self&#x27;&quot;],
&#x27;font-src&#x27;: [&quot;&#x27;self&#x27;&quot;],
&#x27;connect-src&#x27;: [&quot;&#x27;self&#x27;&quot;],
&#x27;media-src&#x27;: [&quot;&#x27;self&#x27;&quot;],
&#x27;object-src&#x27;: [&quot;&#x27;none&#x27;&quot;],
&#x27;frame-src&#x27;: [&quot;&#x27;none&#x27;&quot;],
&#x27;frame-ancestors&#x27;: [&quot;&#x27;none&#x27;&quot;],
&#x27;base-uri&#x27;: [&quot;&#x27;self&#x27;&quot;],
&#x27;form-action&#x27;: [&quot;&#x27;self&#x27;&quot;],
&#x27;upgrade-insecure-requests&#x27;: []
}
def allow_scripts_from(self, *sources):
&quot;&quot;&quot;Allow scripts from specific sources&quot;&quot;&quot;
self.directives[&#x27;script-src&#x27;].extend(sources)
return self
def allow_styles_from(self, *sources):
&quot;&quot;&quot;Allow styles from specific sources&quot;&quot;&quot;
self.directives[&#x27;style-src&#x27;].extend(sources)
return self
def allow_images_from(self, *sources):
&quot;&quot;&quot;Allow images from specific sources&quot;&quot;&quot;
self.directives[&#x27;img-src&#x27;].extend(sources)
return self
def allow_inline_scripts(self, nonce: str = None):
&quot;&quot;&quot;Allow inline scripts (use nonce for security)&quot;&quot;&quot;
if nonce:
self.directives[&#x27;script-src&#x27;].append(f&quot;&#x27;nonce-{nonce}&#x27;&quot;)
else:
# Less secure - avoid if possible
self.directives[&#x27;script-src&#x27;].append(&quot;&#x27;unsafe-inline&#x27;&quot;)
return self
def allow_inline_styles(self):
&quot;&quot;&quot;Allow inline styles&quot;&quot;&quot;
self.directives[&#x27;style-src&#x27;].append(&quot;&#x27;unsafe-inline&#x27;&quot;)
return self
def report_to(self, endpoint: str):
&quot;&quot;&quot;Set CSP violation reporting endpoint&quot;&quot;&quot;
self.directives[&#x27;report-uri&#x27;] = [endpoint]
return self
def build(self) -&gt; str:
&quot;&quot;&quot;Build CSP header string&quot;&quot;&quot;
parts = []
for directive, sources in self.directives.items():
if sources:
parts.append(f&quot;{directive} {&#x27; &#x27;.join(sources)}&quot;)
else:
parts.append(directive)
return &#x27;; &#x27;.join(parts)
# Usage
csp = (CSPBuilder()
.allow_scripts_from(&#x27;https://cdn.jsdelivr.net&#x27;, &#x27;https://www.googletagmanager.com&#x27;)
.allow_styles_from(&#x27;https://fonts.googleapis.com&#x27;)
.allow_images_from(&#x27;data:&#x27;, &#x27;https:&#x27;)
.report_to(&#x27;/csp-violation-report&#x27;)
.build())
# Result:
# &quot;default-src &#x27;self&#x27;; script-src &#x27;self&#x27; https://cdn.jsdelivr.net https://www.googletagmanager.com; ...&quot;</code></pre>
<h3>CSP with Nonces (Recommended)</h3>
<pre><code class="lang-python">import secrets
from flask import Flask, render_template, g
app = Flask(__name__)
@app.before_request
def generate_csp_nonce():
&quot;&quot;&quot;Generate unique nonce for each request&quot;&quot;&quot;
g.csp_nonce = secrets.token_urlsafe(16)
@app.after_request
def add_csp_header(response):
&quot;&quot;&quot;Add CSP with nonce&quot;&quot;&quot;
nonce = getattr(g, &#x27;csp_nonce&#x27;, None)
if nonce:
csp = (
f&quot;default-src &#x27;self&#x27;; &quot;
f&quot;script-src &#x27;self&#x27; &#x27;nonce-{nonce}&#x27;; &quot;
f&quot;style-src &#x27;self&#x27; &#x27;nonce-{nonce}&#x27;; &quot;
f&quot;object-src &#x27;none&#x27;;&quot;
)
response.headers[&#x27;Content-Security-Policy&#x27;] = csp
return response
@app.route(&#x27;/&#x27;)
def index():
&quot;&quot;&quot;Template can use nonce for inline scripts&quot;&quot;&quot;
return render_template(&#x27;index.html&#x27;, csp_nonce=g.csp_nonce)</code></pre>
<pre><code class="lang-html">&lt;!-- Template with nonce --&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;!-- Inline style with nonce --&gt;
&lt;style nonce=&quot;{{ csp_nonce }}&quot;&gt;
body { background: white; }
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;!-- Inline script with nonce --&gt;
&lt;script nonce=&quot;{{ csp_nonce }}&quot;&gt;
console.log(&#x27;This script is allowed&#x27;);
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>
<h3>CSP Violation Reporting</h3>
<pre><code class="lang-python">@app.route(&#x27;/csp-violation-report&#x27;, methods=[&#x27;POST&#x27;])
def csp_violation():
&quot;&quot;&quot;Handle CSP violation reports&quot;&quot;&quot;
import json
report = request.get_json()
# Log violation
logger.warning(&#x27;CSP Violation&#x27;, extra={
&#x27;document_uri&#x27;: report.get(&#x27;document-uri&#x27;),
&#x27;violated_directive&#x27;: report.get(&#x27;violated-directive&#x27;),
&#x27;blocked_uri&#x27;: report.get(&#x27;blocked-uri&#x27;),
&#x27;source_file&#x27;: report.get(&#x27;source-file&#x27;),
&#x27;line_number&#x27;: report.get(&#x27;line-number&#x27;)
})
# Store in database for analysis
db.insert_csp_violation(report)
return &#x27;&#x27;, 204 # No content</code></pre>
<h2>Strict-Transport-Security (HSTS)</h2>
<h3>HSTS Configuration</h3>
<pre><code class="lang-python"># Basic HSTS
response.headers[&#x27;Strict-Transport-Security&#x27;] = &#x27;max-age=31536000&#x27;
# HSTS with subdomains
response.headers[&#x27;Strict-Transport-Security&#x27;] = (
&#x27;max-age=31536000; includeSubDomains&#x27;
)
# HSTS with preload (submit to browser preload list)
response.headers[&#x27;Strict-Transport-Security&#x27;] = (
&#x27;max-age=31536000; includeSubDomains; preload&#x27;
)
# ⚠️ Remove HSTS (emergency only)
response.headers[&#x27;Strict-Transport-Security&#x27;] = &#x27;max-age=0&#x27;</code></pre>
<h3>HTTPS Redirect Middleware</h3>
<pre><code class="lang-python">from flask import Flask, redirect, request
app = Flask(__name__)
@app.before_request
def redirect_to_https():
&quot;&quot;&quot;Enforce HTTPS for all requests&quot;&quot;&quot;
if not request.is_secure and app.config.get(&#x27;FORCE_HTTPS&#x27;):
url = request.url.replace(&#x27;http://&#x27;, &#x27;https://&#x27;, 1)
return redirect(url, code=301)</code></pre>
<h2>X-Frame-Options</h2>
<h3>Clickjacking Prevention</h3>
<pre><code class="lang-python"># Deny all framing (most secure)
response.headers[&#x27;X-Frame-Options&#x27;] = &#x27;DENY&#x27;
# Allow framing from same origin
response.headers[&#x27;X-Frame-Options&#x27;] = &#x27;SAMEORIGIN&#x27;
# Allow framing from specific domain (deprecated, use CSP)
response.headers[&#x27;X-Frame-Options&#x27;] = &#x27;ALLOW-FROM https://trusted.com&#x27;
# Modern alternative: CSP frame-ancestors
response.headers[&#x27;Content-Security-Policy&#x27;] = &quot;frame-ancestors &#x27;none&#x27;&quot; # Deny
response.headers[&#x27;Content-Security-Policy&#x27;] = &quot;frame-ancestors &#x27;self&#x27;&quot; # Same origin
response.headers[&#x27;Content-Security-Policy&#x27;] = &quot;frame-ancestors https://trusted.com&quot; # Specific domain</code></pre>
<h2>Cross-Origin Resource Sharing (CORS)</h2>
<h3>CORS Configuration</h3>
<pre><code class="lang-python">from flask_cors import CORS
# Allow all origins (development only)
app = Flask(__name__)
CORS(app) # ⚠️ Not for production
# Specific origin
CORS(app, origins=[&#x27;https://example.com&#x27;])
# Multiple origins with credentials
CORS(app,
origins=[&#x27;https://app1.example.com&#x27;, &#x27;https://app2.example.com&#x27;],
supports_credentials=True,
allow_headers=[&#x27;Content-Type&#x27;, &#x27;Authorization&#x27;],
expose_headers=[&#x27;X-Total-Count&#x27;],
max_age=3600)
# Manual CORS handling
@app.after_request
def add_cors_headers(response):
origin = request.headers.get(&#x27;Origin&#x27;)
# Whitelist allowed origins
allowed_origins = [
&#x27;https://app.example.com&#x27;,
&#x27;https://admin.example.com&#x27;
]
if origin in allowed_origins:
response.headers[&#x27;Access-Control-Allow-Origin&#x27;] = origin
response.headers[&#x27;Access-Control-Allow-Credentials&#x27;] = &#x27;true&#x27;
response.headers[&#x27;Access-Control-Allow-Methods&#x27;] = &#x27;GET, POST, PUT, DELETE, OPTIONS&#x27;
response.headers[&#x27;Access-Control-Allow-Headers&#x27;] = &#x27;Content-Type, Authorization&#x27;
response.headers[&#x27;Access-Control-Max-Age&#x27;] = &#x27;3600&#x27;
return response
# Preflight request handler
@app.route(&#x27;/&lt;path:path&gt;&#x27;, methods=[&#x27;OPTIONS&#x27;])
def handle_preflight(path):
&quot;&quot;&quot;Handle CORS preflight requests&quot;&quot;&quot;
return &#x27;&#x27;, 204</code></pre>
<h3>CORS Security Considerations</h3>
<pre><code class="lang-python"># ❌ VULNERABLE - Reflecting Origin header
@app.after_request
def vulnerable_cors(response):
# Never do this - allows any origin
origin = request.headers.get(&#x27;Origin&#x27;)
response.headers[&#x27;Access-Control-Allow-Origin&#x27;] = origin # VULNERABLE
return response
# ✅ SECURE - Whitelist validation
@app.after_request
def secure_cors(response):
origin = request.headers.get(&#x27;Origin&#x27;)
# Validate against whitelist
if origin in ALLOWED_ORIGINS:
response.headers[&#x27;Access-Control-Allow-Origin&#x27;] = origin
elif &#x27;*&#x27; in ALLOWED_ORIGINS and not CREDENTIALS_REQUIRED:
# Only allow wildcard without credentials
response.headers[&#x27;Access-Control-Allow-Origin&#x27;] = &#x27;*&#x27;
return response</code></pre>
<h2>Other Security Headers</h2>
<h3>X-Content-Type-Options</h3>
<pre><code class="lang-python"># Prevent MIME type sniffing
response.headers[&#x27;X-Content-Type-Options&#x27;] = &#x27;nosniff&#x27;
# Ensures browsers respect Content-Type header
# Prevents IE/Chrome from interpreting files as different type</code></pre>
<h3>Referrer-Policy</h3>
<pre><code class="lang-python"># Don&#x27;t send referrer
response.headers[&#x27;Referrer-Policy&#x27;] = &#x27;no-referrer&#x27;
# Send only origin (no path)
response.headers[&#x27;Referrer-Policy&#x27;] = &#x27;origin&#x27;
# Send full URL to same origin, origin to cross-origin
response.headers[&#x27;Referrer-Policy&#x27;] = &#x27;origin-when-cross-origin&#x27;
# Strict: only HTTPS → HTTPS
response.headers[&#x27;Referrer-Policy&#x27;] = &#x27;strict-origin-when-cross-origin&#x27;
# No referrer to less secure (HTTPS → HTTP)
response.headers[&#x27;Referrer-Policy&#x27;] = &#x27;no-referrer-when-downgrade&#x27;</code></pre>
<h3>Permissions-Policy</h3>
<pre><code class="lang-python"># Disable all features
response.headers[&#x27;Permissions-Policy&#x27;] = (
&#x27;geolocation=(), microphone=(), camera=(), &#x27;
&#x27;payment=(), usb=(), magnetometer=(), gyroscope=()&#x27;
)
# Allow specific features for self
response.headers[&#x27;Permissions-Policy&#x27;] = (
&#x27;geolocation=(self), camera=(self)&#x27;
)
# Allow for specific origins
response.headers[&#x27;Permissions-Policy&#x27;] = (
&#x27;geolocation=(self &quot;https://maps.example.com&quot;)&#x27;
)</code></pre>
<h3>X-XSS-Protection (Legacy)</h3>
<pre><code class="lang-python"># Enable XSS filter (legacy browsers)
response.headers[&#x27;X-XSS-Protection&#x27;] = &#x27;1; mode=block&#x27;
# Note: Modern browsers rely on CSP instead
# Still useful for older browsers</code></pre>
<h2>Framework-Specific Implementations</h2>
<h3>FastAPI Security Headers</h3>
<pre><code class="lang-python">from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.trustedhost import TrustedHostMiddleware
app = FastAPI()
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins=[&#x27;https://example.com&#x27;],
allow_credentials=True,
allow_methods=[&#x27;GET&#x27;, &#x27;POST&#x27;, &#x27;PUT&#x27;, &#x27;DELETE&#x27;],
allow_headers=[&#x27;*&#x27;],
)
# Trusted hosts
app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=[&#x27;example.com&#x27;, &#x27;*.example.com&#x27;]
)
# Custom security headers
@app.middleware(&quot;http&quot;)
async def add_security_headers(request, call_next):
response = await call_next(request)
response.headers[&#x27;X-Frame-Options&#x27;] = &#x27;DENY&#x27;
response.headers[&#x27;X-Content-Type-Options&#x27;] = &#x27;nosniff&#x27;
response.headers[&#x27;X-XSS-Protection&#x27;] = &#x27;1; mode=block&#x27;
response.headers[&#x27;Strict-Transport-Security&#x27;] = (
&#x27;max-age=31536000; includeSubDomains&#x27;
)
response.headers[&#x27;Content-Security-Policy&#x27;] = (
&quot;default-src &#x27;self&#x27;; script-src &#x27;self&#x27; https://cdn.example.com&quot;
)
return response</code></pre>
<h3>Express.js (Helmet)</h3>
<pre><code class="lang-javascript">const express = require(&#x27;express&#x27;);
const helmet = require(&#x27;helmet&#x27;);
const app = express();
// Use Helmet with all defaults
app.use(helmet());
// Custom configuration
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: [&quot;&#x27;self&#x27;&quot;],
scriptSrc: [&quot;&#x27;self&#x27;&quot;, &quot;https://cdn.jsdelivr.net&quot;],
styleSrc: [&quot;&#x27;self&#x27;&quot;, &quot;&#x27;unsafe-inline&#x27;&quot;],
imgSrc: [&quot;&#x27;self&#x27;&quot;, &quot;data:&quot;, &quot;https:&quot;],
connectSrc: [&quot;&#x27;self&#x27;&quot;, &quot;https://api.example.com&quot;],
fontSrc: [&quot;&#x27;self&#x27;&quot;, &quot;https://fonts.gstatic.com&quot;],
objectSrc: [&quot;&#x27;none&#x27;&quot;],
frameAncestors: [&quot;&#x27;none&#x27;&quot;],
},
},
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true
},
}));</code></pre>
<h3>Nginx Configuration</h3>
<pre><code class="lang-nginx"># Security headers in Nginx
server {
listen 443 ssl http2;
server_name example.com;
# HSTS
add_header Strict-Transport-Security &quot;max-age=31536000; includeSubDomains; preload&quot; always;
# CSP
add_header Content-Security-Policy &quot;default-src &#x27;self&#x27;; script-src &#x27;self&#x27; https://cdn.example.com&quot; always;
# Clickjacking protection
add_header X-Frame-Options &quot;DENY&quot; always;
# MIME type sniffing protection
add_header X-Content-Type-Options &quot;nosniff&quot; always;
# XSS protection
add_header X-XSS-Protection &quot;1; mode=block&quot; always;
# Referrer policy
add_header Referrer-Policy &quot;strict-origin-when-cross-origin&quot; always;
# Permissions policy
add_header Permissions-Policy &quot;geolocation=(), microphone=(), camera=()&quot; always;
location / {
proxy_pass http://backend;
}
}</code></pre>
<h2>Testing Security Headers</h2>
<h3>Automated Testing</h3>
<pre><code class="lang-python">import requests
def test_security_headers():
&quot;&quot;&quot;Test if security headers are present&quot;&quot;&quot;
response = requests.get(&#x27;https://example.com&#x27;)
# Required headers
assert &#x27;Strict-Transport-Security&#x27; in response.headers
assert &#x27;X-Frame-Options&#x27; in response.headers
assert &#x27;X-Content-Type-Options&#x27; in response.headers
assert &#x27;Content-Security-Policy&#x27; in response.headers
# Validate HSTS
hsts = response.headers[&#x27;Strict-Transport-Security&#x27;]
assert &#x27;max-age=31536000&#x27; in hsts
assert &#x27;includeSubDomains&#x27; in hsts
# Validate CSP
csp = response.headers[&#x27;Content-Security-Policy&#x27;]
assert &quot;default-src &#x27;self&#x27;&quot; in csp
# Check no insecure headers
assert &#x27;X-Powered-By&#x27; not in response.headers # Remove server info</code></pre>
<h3>Manual Testing Tools</h3>
<pre><code class="lang-bash"># Check headers with curl
curl -I https://example.com
# Check with httpie
http HEAD https://example.com
# Online tools:
# - https://securityheaders.com
# - https://observatory.mozilla.org</code></pre>
<h2>Security Best Practices</h2>
<h3>Security Headers Checklist</h3>
<p><strong>Essential Headers</strong>:</p>
<ul><li>[ ] Strict-Transport-Security (HSTS)</li><li>[ ] Content-Security-Policy (CSP)</li><li>[ ] X-Frame-Options or CSP frame-ancestors</li><li>[ ] X-Content-Type-Options: nosniff</li><li>[ ] Referrer-Policy</li></ul>
<p><strong>CORS Configuration</strong>:</p>
<ul><li>[ ] Whitelist allowed origins (no wildcard with credentials)</li><li>[ ] Specify allowed methods and headers</li><li>[ ] Set appropriate max-age for preflight caching</li><li>[ ] Enable credentials only when necessary</li></ul>
<p><strong>CSP Best Practices</strong>:</p>
<ul><li>[ ] Start with restrictive policy</li><li>[ ] Use nonces for inline scripts/styles</li><li>[ ] Avoid &#x27;unsafe-inline&#x27; and &#x27;unsafe-eval&#x27;</li><li>[ ] Enable CSP reporting</li><li>[ ] Test in report-only mode first</li></ul>
<p><strong>General</strong>:</p>
<ul><li>[ ] Remove server identification headers (X-Powered-By, Server)</li><li>[ ] Enforce HTTPS everywhere</li><li>[ ] Set Permissions-Policy to disable unused features</li><li>[ ] Regular security header audits</li></ul>
<h2>Level 3: Resources</h2>
<h3>Comprehensive Reference</h3>
<p><strong>Location</strong>: <code>skills/security/security-headers/resources/REFERENCE.md</code></p>
<p>The REFERENCE.md file (1200+ lines) provides exhaustive coverage of:</p>
<ul><li>All major security headers (HSTS, CSP, X-Frame-Options, X-Content-Type-Options, etc.)</li><li>Complete CSP directives reference (script-src, style-src, img-src, connect-src, etc.)</li><li>CSP Levels 1, 2, and 3 feature comparison</li><li>SameSite cookie attributes (Strict, Lax, None)</li><li>Referrer-Policy options and privacy considerations</li><li>Permissions-Policy (Feature-Policy successor)</li><li>CORS headers configuration patterns</li><li>Cookie security attributes and prefixes (__Secure-, __Host-)</li><li>Attack vectors and mitigations (XSS, clickjacking, CSRF, MIME sniffing)</li><li>Browser compatibility matrices</li><li>Testing and validation tools</li><li>Implementation patterns for Nginx, Apache, Express, Flask, Django, Next.js</li><li>Security header grading criteria (Mozilla Observatory, SecurityHeaders.com)</li><li>Advanced topics: nonce rotation, CSP for SPAs, Subresource Integrity (SRI)</li></ul>
<h3>Executable Scripts</h3>
<p><strong>Location</strong>: <code>skills/security/security-headers/resources/scripts/</code></p>
<ol><li><strong>check_headers.py</strong> - Security headers scanner and grading tool</li></ol>
<ul><li>Scans URLs for security headers</li><li>Grades security posture (A+ to F)</li><li>Analyzes header configuration and identifies issues</li><li>Provides detailed recommendations</li><li>Supports JSON output for CI/CD integration</li><li>Usage: <code>./check_headers.py https://example.com --json</code></li></ul>
<ol><li><strong>generate_csp.py</strong> - CSP policy generator from site crawl</li></ol>
<ul><li>Crawls website to discover resource sources</li><li>Generates CSP policy based on actual usage</li><li>Supports strict mode and hash generation</li><li>Identifies inline scripts and styles</li><li>Provides detailed source analysis by directive</li><li>Usage: <code>./generate_csp.py https://example.com --depth 3 --strict</code></li></ul>
<ol><li><strong>test_headers.sh</strong> - Batch header testing across multiple domains</li></ol>
<ul><li>Tests security headers across multiple URLs</li><li>Supports batch testing from file</li><li>Parallel execution for performance</li><li>Multiple output formats (text, JSON, CSV)</li><li>Header comparison across environments</li><li>Usage: <code>./test_headers.sh -f domains.txt --output json</code></li></ul>
<h3>Configuration Examples</h3>
<p><strong>Location</strong>: <code>skills/security/security-headers/resources/examples/</code></p>
<ol><li><strong>nginx-security-headers.conf</strong> - Production-ready Nginx configuration</li></ol>
<ul><li>Complete security headers for all response types</li><li>CSP policies for static sites, SPAs, and SSR applications</li><li>HSTS with preload configuration</li><li>Permissions-Policy feature restrictions</li><li>Cookie security attributes</li><li>Special configurations for API endpoints and static assets</li></ul>
<ol><li><strong>apache-security-headers.htaccess</strong> - Apache .htaccess configuration</li></ol>
<ul><li>mod_headers-based security header configuration</li><li>CORS handling and preflight request support</li><li>File access protection patterns</li><li>MIME type configuration</li><li>Cache control for static assets</li><li>Environment-specific CSP policies</li></ul>
<ol><li><strong>flask-security-headers.py</strong> - Flask middleware implementation</li></ol>
<ul><li>Production-ready SecurityHeaders middleware class</li><li>CSP nonce generation per request</li><li>Per-route CSP policy decorators</li><li>Secure cookie helper functions</li><li>Complete working Flask application example</li><li>Both class-based and decorator-based approaches</li></ul>
<ol><li><strong>next-security-headers.ts</strong> - Next.js security headers configuration</li></ol>
<ul><li>next.config.js static headers approach</li><li>Middleware-based dynamic headers with nonces</li><li>CSP nonce injection and access in components</li><li>CSP violation report handler</li><li>Complete examples for Server Components and Scripts</li><li>TypeScript type definitions</li></ul>
<p>All scripts are executable, include --help documentation, and follow production-ready patterns.</p>
<h2>Related Skills</h2>
<ul><li><code>security-input-validation.md</code> - CSP and XSS prevention</li><li><code>security-vulnerability-assessment.md</code> - Testing security headers</li><li><code>frontend-performance.md</code> - CSP impact on resource loading</li><li><code>api-error-handling.md</code> - CORS error handling</li></ul>
<hr>
<p><strong>Last Updated</strong>: 2025-10-27 <strong>Format Version</strong>: 1.0 (Atomic)</p>
<footer>
<div class="fmap">
<div><b>Build</b>
<a href="https://hanzo.app">hanzo.app</a> app builder
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
<div><b>Run</b>
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
<div><b>Account</b>
<a href="https://hanzo.id">hanzo.id</a> sign in
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
<div><b>Company</b>
<a href="https://hanzo.ai">hanzo.ai</a> canonical
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
</div>
<div class="fend"><a href="/security-security-headers.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
</footer>
</div></body></html>