API

CSP Toolkit

This project was birthed from Vite Plugin CSP Guard and it actually houses generic CSP logic.

The Goal

This Toolkit package is a stepping stone in order to bring support to other frameworks, bundlers, etc. I'll be writing guides for each major framework and bundler out there.

Installation

Usage

definePolicy (recommended)

Build a policy with camelCase directive keys and unquoted keyword tokens. The library adds the single quotes CSP expects for keywords like 'self'. The returned value is a CSPPolicy with a .toString() helper (same output as policyToString).

import {
  definePolicy,
  nonce,
  self,
  none,
  unsafeInline,
  strictDynamic,
  blob,
  data,
} from "csp-toolkit"
 
const cspNonce = "…" // e.g. from generateNonce()
 
const policy = definePolicy({
  defaultSrc: [self],
  scriptSrc: [self, nonce(cspNonce), strictDynamic],
  styleSrc: [self, unsafeInline],
  imgSrc: [self, blob, data, "https://cdn.example.com"],
  fontSrc: [self],
  objectSrc: [none],
  baseUri: [self],
})
 
const header = policy.toString()
// or: import { policyToString } from "csp-toolkit"; policyToString(policy)

Keyword constants (optional): self, none, unsafeInline, unsafeEval, unsafeHashes, strictDynamic, reportSample, wasmUnsafeEval, inlineSpeculationRules. You can also use string literals such as "self"; both are equivalent.

Scheme constants: data, blob, filesystem, mediastream, https, http, ws, wss (values are data:, blob:, etc.).

Dynamic sources: nonce(value) and hash(algorithm, base64Digest) produce quoted nonce-… / sha*-… source expressions for use inside definePolicy or plain CSPPolicy arrays.

Types

import type { CSPPolicy, CSPKeys, HashAlgorithms } from "csp-toolkit"
import type {
  FetchDirectives,
  DocumentDirectives,
  NavigationDirectives,
  ReportingDirectives,
  OtherDirectives,
  DeprecatedDirectives,
} from "csp-toolkit"

CSPKeys is a TypeScript type only (there is no runtime list of keys). Use it to narrow directive names in your own helpers.

definePolicy input types:

import type { DefinePolicyInput, DefinedPolicy, CamelDirective } from "csp-toolkit"
import type { CspSource, CspKeyword, CspSchemeToken } from "csp-toolkit"

mergePolicies

Merge two CSPPolicy objects. Duplicate sources in the same directive are deduplicated.

import { mergePolicies } from "csp-toolkit"
 
const merged = mergePolicies(basePolicy, overlay, false)

policyToString

Turn a CSPPolicy into a single header/meta string.

import { policyToString } from "csp-toolkit"
 
const header = policyToString(policy)

Node (hashing, nonce)

import { generateHash } from "csp-toolkit/node" // sync; algorithm: sha256 | sha384 | sha512
import { generateNonce } from "csp-toolkit/node"

Edge (hashing, nonce)

import { generateHash } from "csp-toolkit/edge" // async Web Crypto
import { generateNonce } from "csp-toolkit/edge"

Prefer definePolicy for new code; raw CSPPolicy objects and mergePolicies remain fully supported.