Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

csp3-parser

jan53n37ISC1.0.11TypeScript support: included

A CSP3 Parser based on W3 specification

CSP, Content Security Policy, CSP3, CSP parser, security, web security, directive parser, policy parser, CSP analysis, CSP tools, content-security-policy, directive handling, security headers, web development, CSP compliance

readme

CSP3 Parser

A robust CSP3 (Content Security Policy 3) parser that complies with the W3C CSP3 Specification. It parses complex CSP strings into structured JavaScript objects, making it easier to analyze and process Content Security Policies programmatically.


Usage

Parsing

import { parse } from "csp3-parser";

const csp =
    "default-src 'self' https://example.com; script-src 'unsafe-inline' 'self' https://cdn.example.com; img-src https://images.example.com data: 'self'; object-src 'none'";
const result = parse(csp);

console.log(result);
// Output:
// {
//   "default-src": [
//     { type: "keyword", value: "self" },
//     { type: "host", value: "https://example.com" }
//   ],
//   "script-src": [
//     { type: "keyword", value: "unsafe-inline" },
//     { type: "keyword", value: "self" },
//     { type: "host", value: "https://cdn.example.com" }
//   ],
//   "img-src": [
//     { type: "host", value: "https://images.example.com" },
//     { type: "scheme", value: "data" },
//     { type: "keyword", value: "self" }
//   ],
//   "object-src": [
//     { type: "keyword", value: "none" }
//   ]
// }

Serialization

import { serialize } from "csp3-parser";

/**
 * @type {import("csp3-parser/types").CSPParserResult}
 */
const csp = {
    "default-src": [
        { type: "keyword", value: "self" },
        { type: "host", value: "https://example.com" },
    ],
    "script-src": [
        { type: "keyword", value: "unsafe-inline" },
        { type: "keyword", value: "self" },
        { type: "host", value: "https://cdn.example.com" },
    ],
    "img-src": [
        { type: "host", value: "https://images.example.com" },
        { type: "scheme", value: "data" },
        { type: "keyword", value: "self" },
    ],
    "object-src": [
        { type: "keyword", value: "none" },
    ],
};

const result = serialize(csp);

console.log(result);
// Output:
// default-src 'self' https://example.com; script-src 'unsafe-inline' 'self' https://cdn.example.com; img-src https://images.example.com data: 'self'; object-src 'none'