// Fills the inline-script hashes into dist/_headers after a build.//// The Content-Security-Policy in public/_headers allows no 'unsafe-inline'// for scripts. The inline scripts the site does carry (the theme and page// iris bootstraps and the Vercel stubs in Base.astro, and any module Astro// inlines) are allowed by SHA-256 hash instead, which a browser accepts// only for the exact text. Astro rewrites inlined modules on every build,// so the hashes are computed from the built HTML rather than by hand.//// Runs last in `npm run build`. Anything that adds an inline <script> to a// page is covered automatically; an inline script that is NOT in dist at// build time (injected at runtime) will be refused by the browser.import { createHash } from'node:crypto';
import { readFileSync, writeFileSync } from'node:fs';
import { readdirSync, statSync } from'node:fs';
import { join } from'node:path';
const DIST ='dist';
const HEADERS = join(DIST, '_headers');
const TOKEN ='__INLINE_SCRIPT_HASHES__';
function* htmlFiles(dir) {
for (const name of readdirSync(dir)) {
const p = join(dir, name);
if (statSync(p).isDirectory()) yield* htmlFiles(p);
elseif (name.endsWith('.html')) yield p;
}
}
// A <script> with no src and a JavaScript type. JSON blocks (JSON-LD) are// data the browser never executes, so they need no hash.const SCRIPT =/<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
const isData = (attrs) => /\btype\s*=\s*["']?(application\/(ld\+)?json|text\/(template|x-|plain))/i.test(attrs);const hashes = new Set();let files = 0;for (const file of htmlFiles(DIST)) { files++; const html = readFileSync(file, 'utf8'); for (const [, attrs, body] of html.matchAll(SCRIPT)) { if (/\bsrc\s*=/i.test(attrs) || isData(attrs)) continue; hashes.add(`'sha256-${createHash('sha256').update(body).digest('base64')}'`); }}const headers = readFileSync(HEADERS, 'utf8');if (!headers.includes(TOKEN)) { console.error(`csp-hashes: ${HEADERS} has no ${TOKEN} placeholder`); process.exit(1);}const out = headers.replace(TOKEN, [...hashes].join(''));const longest = Math.max(...out.split('\n').map((l) => l.length));if (longest > 2000) { console.error(`csp-hashes: a _headers line is ${longest} chars; Cloudflare's limit is 2000`); process.exit(1);}writeFileSync(HEADERS, out);console.log(`csp-hashes: ${hashes.size} inline script hash(es) from ${files} pages -> ${HEADERS} (longest line ${longest})`);