npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@jackdbd/content-security-policy

v3.0.0

Published

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

Downloads

432

Readme

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