@jackdbd/content-security-policy

content-security-policy

npm package badge install size badge CI GitHub workflow badge CodeCov badge CodeFactor badge Socket badge Conventional Commits badge

Write your Content-Security-Policy header in JavaScript, so you can have validation and automatic hashes.

About

A strict Content-Security-Policy is probably the single most important line of defense against Cross-Site Scripting (XSS) attacks.

Unfortunately, writing a good CSP header by hand is a pain. Here is why:

  • You might write an invalid CSP directive (e.g. typos, incorrect values).
  • You might write a CSP directive which is supported in one browser, but not in another one.
  • You might want to allow some inline CSS/JS in your HTML page, but you neither:
    • want to compromise security by using unsafe-inline, nor...
    • want to compute the cryptographic hash of each snippet of CSS/JS that you inlined and whitelist them by hand.

Also, you should:

  • keep your CSP quite visible in your codebase, since it's such an important configuration for your website/app.
  • generate your CSP in multiple format (JS object literal, JS array, plain text), so other tools can easily consume it.

This package validates your Content-Security-Policy directives and computes a cryptographic hash (SHA-256, SHA-384 or SHA-512) for each snippet of CSS/JS that you inline in your HTML file.

Installation

npm install @jackdbd/content-security-policy

Usage

Let's suppose you have an Eleventy site that has the following characteristics:

  • fonts self-hosted on your origin
  • stylesheets self-hosted on your origin. No CSS inlined in the <head>
  • a few event handlers inlined in the HTML
  • a few images hosted on a CDN

If your Eleventy site was generated in the _site folder, you could generate a Content-Security-Policy header with this code:

import path from 'node:path'
import { cspHeader } from '@jackdbd/content-security-policy'

const directives = {
'base-uri': ['self'],
'default-src': ['none'],
'font-src': ['self'],
'img-src': ['self', 'cdn.example.com'],
'script-src-attr': ['self', 'unsafe-hashes', 'sha256'],
'style-src-elem': ['self']
}

const patterns = [path.join('_site', '**/*.html')]

const header = await cspHeader({ directives, patterns })

The Content-Security-Policy header is made of directives. If you don't know where to start, use one of the following policies:

import {
starter_policy,
recommended_policy
} from '@jackdbd/content-security-policy/policies'

const directives = recommended_policy

Configuration

Options

Key Default Description
directives undefined Directives for your Content-Security-Policy (or Content-Security-Policy-Report-Only).
patterns undefined Glob patterns for your .html files.

Supported CSP directives

base-uri, child-src, connect-src, default-src, font-src, form-action, frame-ancestors, frame-src, img-src, manifest-src, media-src, navigate-to, object-src, report-to, sandbox, script-src, script-src-attr, script-src-elem, source-values, style-src, style-src-attr, style-src-elem, upgrade-insecure-requests, worker-src

Deprecated CSP directives

block-all-mixed-content, plugin-types, prefetch-src, referrer, report-uri, require-sri-for

Experimental CSP directives

fenced-frame-src, require-trusted-types-for, trusted-types

Docs

Docs generated by TypeDoc

📖 API Docs

This project uses API Extractor and api-documenter markdown to generate a bunch of markdown files and a .d.ts rollup file containing all type definitions consolidated into a single file. I don't find this .d.ts rollup file particularly useful. On the other hand, the markdown files that api-documenter generates are quite handy when reviewing the public API of this project.

See Generating API docs if you want to know more.

Dependencies

Package Version
debug ^4.3.4
globby ^14.0.1
himalaya ^1.1.0
zod ^3.23.4

This project is tested on Node.js >=14.21.3.

You can use a Node.js version manager like nvm, asdf or volta to manage your Node.js versions.

Troubleshooting

This project uses the debug library for logging. You can control what's logged using the DEBUG environment variable.

For example, if you set your environment variables in a .envrc file, you can do:

# print all logging statements
export DEBUG=csp:*

Alternatives

  • netlify-plugin-csp-generator. It uses jsdom to find all inlined CSS/JS snippets in your website, it computes a SHA-256 for each one of them, then it appends the CSP to your _headers file. Really cool, but you have to host you site on Netlify to use it.
  • seespee. It uses AssetGraph to build a dependency graph of your website, then it computes hashes for the assets included in such graph.

License

© 2022 - 2024 Giacomo Debidda // MIT License