Branchwell

Jobley / website · jobley.ai / tools / csp-hash.mjs

1// Prints the CSP hash ('sha256-…') of the <style> block assets/share.js adds to the page,
2// so _headers can keep style-src strict without editing the shared script. Used by build-site.py.
3import { readFileSync } from 'node:fs';
4import { createHash } from 'node:crypto';
5import vm from 'node:vm';
6
7let css = null;
8const node = () => ({ set textContent(v) { css = v; }, setAttribute() {}, style: {} });
9const document = {
10 readyState: 'complete', getElementById: () => null, createElement: node, addEventListener() {},
11 body: { insertBefore() {}, firstChild: null }, documentElement: {}, querySelector: () => null, querySelectorAll: () => [],
12};
13const window = { addEventListener() {} };
14vm.runInNewContext(readFileSync(new URL('../assets/share.js', import.meta.url), 'utf8'), { window, document, setTimeout() {}, navigator: {}, location: {} });
15if (!css) { console.error('share css not found'); process.exit(1); }
16process.stdout.write(`'sha256-${createHash('sha256').update(css).digest('base64')}'`);