Build-time security
csp-forge
Generate a tight Content-Security-Policy from your built site.
npm i -D csp-forgeWhat it checks
<script src>,<link rel=modulepreload>,importScripts()script-src- inline
<script>(executable types only; JSON/template blocks skipped)script-src 'sha256-…' - inline event handlers (
onclick=…)script-src 'unsafe-hashes' 'sha256-…'+ warning <link rel=stylesheet>, CSS@importstyle-src- inline
<style>/style=""attributesstyle-src 'sha256-…'/'unsafe-hashes' 'sha256-…' <img>,srcset,<picture><source>,poster,<link rel=icon>, CSSurl()img-src@font-faceurl(),<link rel=preload as=font>font-srcfetch, XHR.open,WebSocket,EventSource,sendBeacon, absolute URL literals in JSconnect-src(heuristic, flagged for review)
Quick usage
CLI
npx csp-forge dist
API
const cspForge = require('csp-forge'); // or: import { generate, ... } from 'csp-forge'
const { scan, directives, policy } = await cspForge.generate({ dir: 'dist', config: { frameAncestors: "'self'" } });
console.log(cspForge.render(directives, 'nginx', { reporting: { reportTo: { name: 'csp', url: 'https://example.com/r' } } }));
const findings = cspForge.checkPolicy(currentPolicy, directives, scan);
if (cspForge.shouldFail(findings, 'error')) process.exit(1);
Every option is documented in the csp-forge docs.
CI / GitHub Action
# .github/workflows/csp.yml
name: CSP
on: [push, pull_request]
permissions: { contents: read, security-events: write }
jobs:
csp:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 20 }
- run: npm ci && npm run build
# the policy you ship (e.g. dist/_headers or a header from staging) must cover the build
- run: npx csp-forge@1 dist --check dist/_headers --sarif csp.sarif
- uses: github/codeql-action/upload-sarif@v3
if: always()
with: { sarif_file: csp.sarif }