csp-builder
TypeScript icon, indicating that this package has built-in type declarations

1.1.1 • Public • Published

csp-builder

A builder tool to help generate CSPs in a type-safe way

Travis (.org) Codecov code style: prettier

Motivation

I had to create a CSP and found the process rather unintuitive and mistake-prone. If you've created a Content Security Policy before, there are 3 paths to choose (or a mixture):

  1. Use a reporting wizard (Example)

  2. Use a generator wizard (Example)

  3. Manually edit policy, usually with a wash-rinse-repeat recipe

Any path you choose, you eventually end up with a big string of CSP content, very hard to edit or maintain. This is especially true if you opt in to create the CSP manually.

For that reason, I wanted a builder tool to help me with generating the string, in a type-safe way, but could not find one, so I created this tool.

Install

npm install --save-dev csp-builder

Usage

import * as CSP from 'csp-builder';
 
const csp = new CSP.Builder();
 
const analyticsDomain = 'www.google-analytics.com';
const ownDomain = 'www.giladpeleg.com';
const reportUri = 'https://giladpeleg.report-uri.com/r/d/csp/enforce';
 
const extensiveSourceDirective = [
    CSP.PredefinedSource.Self,
    CSP.SchemaSource.Data,
    analyticsDomain,
    ownDomain,
];
const regularSourceDirective = [CSP.PredefinedSource.Self, analyticsDomain, ownDomain];
const localSourceDirective = [CSP.PredefinedSource.Self, ownDomain];
 
csp.addDirective(new CSP.DefaultSource().addValue(regularSourceDirective))
    .addDirective(new CSP.FontSource().addValue(extensiveSourceDirective))
    .addDirective(new CSP.ImageSource().addValue(extensiveSourceDirective))
    .addDirective(new CSP.MediaSource().addValue(localSourceDirective))
    .addDirective(new CSP.ObjectSource().addValue([CSP.PredefinedSource.None]))
    .addDirective(new CSP.FontSource().addValue(extensiveSourceDirective))
    .addDirective(
        new CSP.PrefetchSource().addValue([CSP.PredefinedSource.Self, analyticsDomain, ownDomain])
    )
    .addDirective(
        new CSP.ScriptSource().addValue([
            CSP.PredefinedSource.Self,
            CSP.PredefinedSource.UnsafeInline,
            analyticsDomain,
            ownDomain,
        ])
    )
    .addDirective(
        new CSP.StyleSource().addValue([
            CSP.PredefinedSource.Self,
            CSP.PredefinedSource.UnsafeInline,
            ownDomain,
        ])
    )
    .addDirective(new CSP.WorkerSource().addValue(localSourceDirective))
    .addDirective(new CSP.ReportUri().setValue(reportUri));
 
console.log(csp.stringify());

See more usages in the tests

Future plans

I've noticed there are possible optimizations to be done for the CSP, especially regarding deprecations and conciseness.

License

MIT © Gilad Peleg

Package Sidebar

Install

npm i csp-builder

Weekly Downloads

129

Version

1.1.1

License

MIT

Unpacked Size

84.3 kB

Total Files

65

Last publish

Collaborators

  • pgilad