The photo section of my old site had a lightbox carousel, a React component with client:load. Locally it worked. In production a click on a thumbnail did nothing, and the browser console said:
Executing inline script violates the following Content Security Policy directive 'script-src 'self''.
Either the 'unsafe-inline' keyword, a hash ('sha256-QzWFZi+FLIx23tnm9SBU4aEgx4x8DsuASP07mfqol/c='),
or a nonce ('nonce-...') is required to enable inline execution.
Two of those errors, with two different hashes. The strict CSP in Caddy did exactly what it was built for, and blocked exactly what Astro needs for hydration.
What Astro inlines
The client:* directives (client:load, client:visible, client:idle and so on) need a tiny bootstrap. It decides when a component hydrates in the browser and then runs it. Astro injects it as two small inline <script> blocks into every page with an island:
<script>(()=>{var e=async t=>{await(await t())()};(self.Astro||(self.Astro={})).load=e;w...</script>
<script>(()=>{var A=Object.defineProperty;var g=(i,o,a)=>o in i?A(i,o,{enumerable:!0,con...</script>
About 1.5 kB together. With script-src 'self' and no 'unsafe-inline', the browser blocks both. Hydration never starts, every island stays static HTML, and every event handler from React, motion and the rest is missing.
The key fact: both blocks are deterministic per Astro version. The same npm run build produces the same bytes and so the same sha256 hashes. Astro puts no random IDs, timestamps or build hashes in them.
Three options
- Allow
'unsafe-inline'for scripts. That defeats the purpose of the CSP. - Nonces. They only help if Caddy injects a fresh nonce per request into both the HTML and the header. I did not want that infrastructure on a static site.
- Hash pinning: put the exact sha256 hashes of the two inlines into the CSP.
Hash pinning fits a static site: no server logic, no work per request, just two extra tokens in script-src.
Computing the hashes
Straight from the build output, no extra tool:
python3 -c "
import re, hashlib, base64
from pathlib import Path
html = Path('dist/fotos/unterwegs/asien/malaysia/kuala-lumpur/index.html').read_text()
for body in dict.fromkeys(re.findall(r'<script(?![^]>]*\bsrc=)[^]>]*>(.*?)</script>', html, re.DOTALL)):
if body.strip():
print('sha256-' + base64.b64encode(hashlib.sha256(body.encode()).digest()).decode())
"
Any page with a client:* island will do, since the two inlines are the same on every page. The script prints the two hashes that belong in the CSP.
Patching the CSP in Caddy
In my Caddy config the CSP is a single value inside a header block:
- script-src 'self';
+ script-src 'self' 'sha256-QzWFZi+FLIx23tnm9SBU4aEgx4x8DsuASP07mfqol/c=' 'sha256-QJZDUlo/qa5AJCrG6vHyWcatjwCeWidEHQfJc601lzw=';
Everything else stays as it was: default-src 'none', img-src, style-src. Then validate and reload:
sudo caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile
sudo systemctl reload caddy
curl -sI https://adrian-altner.de/ | grep -i content-security showed the new hashes right away. On the next page load the island hydrated and the modal opened.
When Astro updates
The hashes follow the bytes of the inlines. Astro can rework the bootstrap between versions, in major releases and occasionally in minor ones. Patch and minor updates within one major usually leave it alone, but "usually" is not "always". Without a check you only notice when something breaks silently in production.
As of November 2026 there is another way: Astro 6 (March 2026) made its Content Security Policy API stable. With security: { csp: true } Astro hashes its own scripts and styles and writes the policy itself, so the hashes no longer have to be pinned by hand.1
A drift check in the deploy workflow
The right moment for the check is right after the deploy: the new build is live, the old CSP is still in place. My Forgejo runner has an extra step in the workflow:
- name: Verify CSP script-src hashes
run: |
SAMPLE_PATH='/fotos/unterwegs/asien/malaysia/kuala-lumpur/'
export LIVE_HTML="$(curl -fsSL "https://adrian-altner.de${SAMPLE_PATH}")"
export LIVE_CSP="$(curl -fsSI "https://adrian-altner.de${SAMPLE_PATH}" \
| tr -d '\r' | grep -i '^content-security-policy:')"
python3 - <<'PY'
import os, re, hashlib, base64, sys
html = os.environ['LIVE_HTML']
csp = os.environ['LIVE_CSP']
inlines = re.findall(r'<script(?![^]>]*\bsrc=)[^]>]*>(.*?)</script>', html, re.DOTALL)
served = sorted({'sha256-' + base64.b64encode(hashlib.sha256(b.encode()).digest()).decode()
for b in inlines if b.strip()})
configured = sorted(set(re.findall(r"sha256-[A-Za-z0-9+/=]+", csp)))
if set(served) == set(configured):
print(f"OK: CSP hashes match ({len(served)}).")
sys.exit(0)
print("::error title=CSP hash drift::live HTML and CSP no longer agree")
# ... print missing/stale + ready-to-paste sed patch ...
sys.exit(1)
PY
The runner reads no build directory and needs no sudo on the Caddy file. It only curls the public page, parses the two inlines from the HTML and compares them with the Content-Security-Policy response header. That is exactly what the browser sees. The runner's sudoers rule could stay narrowly limited to podman build and systemctl restart.
On drift the step fails with a Forgejo annotation and a ready-to-paste sudo sed patch in the log. Then:
- The Forgejo run goes red, with the annotation "CSP hash drift detected" and both sets of hashes side by side.
ssh hetzner, paste the patch from the log: thesedswap,caddy validate,systemctl reload caddy.- "Re-run workflow" in the Forgejo UI, and the step turns green.
The deploy workflow ran on every push and once a day at 06:00 UTC anyway, so the check came as free daily insurance.
Inline styles
Astro sometimes inlines CSS into <head> too. On my site I ran style-src 'self' 'unsafe-inline'. That was pragmatic: inline CSS is a much smaller risk than inline JavaScript, and Astro's CSS inlines are too many for hash pinning.
What I deliberately did not do
- Rewrite the lightbox as a plain
<dialog>. A native<dialog>with a few TypeScript handlers would have needed no React island, no hydration inlines and no CSP upkeep. But it was a bigger refactor and would have lost motion for the slide and drag animations. Hash pinning was the smaller change with a tiny maintenance tail. - Open
script-srcto'unsafe-inline'. Once that is in, you might as well delete the script part of the CSP. The point was a hard barrier against XSS and compromised dependencies.
The result: two hash tokens in the CSP and a Forgejo step that compares them with the live header after every deploy and goes red on drift.
- Topic
-
- Static Website A website made of finished HTML files that are built once and then served unchanged. No server code, no database.
- Web Development How this site and others are made and found: static pages, search engines, the IndieWeb and maps in the browser.
- Builds on
-
- Security Headers in Caddy A strict Content Security Policy, HSTS and no-referrer in a Caddy site block, checked with Webbkoll, securityheaders.com and the Mozilla Observatory.
- Uses
-
- Astro Tool for building websites from content such as Markdown. Ships plain HTML by default and only loads JavaScript where it is needed.
- Caddy Web server and reverse proxy that obtains and renews TLS certificates on its own, configured in a short Caddyfile.
- Forgejo Git forge to host yourself: repositories, users, SSH access and CI/CD with Forgejo Actions and self-hosted runners. Codeberg runs on it.
- Mentioned
-
- Setting Up a Forgejo Actions Runner Push-to-deploy with a self-hosted Forgejo Actions runner on the same VPS: own user, no Docker, narrow sudo rights and secrets kept in Forgejo.
- Tags