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. |
| 3 | import { readFileSync } from 'node:fs'; |
| 4 | import { createHash } from 'node:crypto'; |
| 5 | import vm from 'node:vm'; |
| 6 | |
| 7 | let css = null; |
| 8 | const node = () => ({ set textContent(v) { css = v; }, setAttribute() {}, style: {} }); |
| 9 | const document = { |
| 10 | readyState: 'complete', getElementById: () => null, createElement: node, addEventListener() {}, |
| 11 | body: { insertBefore() {}, firstChild: null }, documentElement: {}, querySelector: () => null, querySelectorAll: () => [], |
| 12 | }; |
| 13 | const window = { addEventListener() {} }; |
| 14 | vm.runInNewContext(readFileSync(new URL('../assets/share.js', import.meta.url), 'utf8'), { window, document, setTimeout() {}, navigator: {}, location: {} }); |
| 15 | if (!css) { console.error('share css not found'); process.exit(1); } |
| 16 | process.stdout.write(`'sha256-${createHash('sha256').update(css).digest('base64')}'`); |