Content Security Policy Builder

2.3.0 · maintenance · verified Tue Apr 21

The `content-security-policy-builder` package, currently at version 2.3.0, provides a focused utility for programmatically constructing Content Security Policy (CSP) strings from a JavaScript object or Map. It streamlines the process of defining CSP directives by supporting various input formats, including `camelCased` or `dash-separated` directive names, and accepting both strings and arrays for directive values. The module is explicitly designated as feature-complete, with the maintainer indicating that future development will be limited to maintenance. This means no new features or breaking changes are planned, making it a stable, though static, choice for generating CSP headers. Its key differentiator lies in its robust input parsing and its singular, complete focus on translating structured input into a valid CSP string.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `content-security-policy-builder` to construct CSP strings from both a plain JavaScript object and a Map, showcasing its flexibility with different directive naming conventions and value types.

import builder from "content-security-policy-builder";

// --- Example 1: Basic directives with different input styles ---
const policy1 = builder({
  directives: {
    defaultSrc: ["'self'", "default.com"],
    scriptSrc: "scripts.com",
    "style-src": ["'self'", "styles.com", "*.cdn.com"], // dash-separated
    imgSrc: ["'self'", "data:", "images.example.com"],
    fontSrc: ["'self'", "fonts.gstatic.com"],
    objectSrc: ["'none'"], // Explicitly disable object sources
    baseUri: ["'self'"]
  }
});
console.log("Policy 1:", policy1);
// Expected output: default-src 'self' default.com; script-src scripts.com; style-src 'self' styles.com *.cdn.com; img-src 'self' data: images.example.com; font-src 'self' fonts.gstatic.com; object-src 'none'; base-uri 'self'

// --- Example 2: Using a Map for directives (useful for dynamic scenarios) ---
const dynamicDirectives = new Map([
  ["defaultSrc", ["'self'"]],
  ["scriptSrc", ["'self'", "https://cdn.example.com"]],
  ["connectSrc", ["'self'", "wss://api.example.com"]],
  ["reportUri", "/csp-report-endpoint"]
]);
const policy2 = builder({ directives: dynamicDirectives });
console.log("Policy 2:", policy2);
// Expected output: default-src 'self'; script-src 'self' https://cdn.example.com; connect-src 'self' wss://api.example.com; report-uri /csp-report-endpoint

// This demonstrates building complex CSP strings with various directive types and sources,
// including handling both camelCase and dash-separated directive names, and array/string values.

view raw JSON →