• Stars
    star
    159
  • Rank 235,916 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A plugin which, when combined with HTMLWebpackPlugin, adds CSP tags to the HTML output.

CSP HTML Webpack Plugin

License npm Code Style Build Status codecov

About

This plugin will generate meta content for your Content Security Policy tag and input the correct data into your HTML template, generated by html-webpack-plugin.

All inline JS and CSS will be hashed and inserted into the policy.

Installation

Install the plugin with npm:

npm i --save-dev csp-html-webpack-plugin

Basic Usage

Include the following in your webpack config:

const HtmlWebpackPlugin = require('html-webpack-plugin');
const CspHtmlWebpackPlugin = require('csp-html-webpack-plugin');

module.exports = {
  // rest of webpack config

  plugins: [
    new HtmlWebpackPlugin()
    new CspHtmlWebpackPlugin({
      // config here, see below
    })
  ]
}

Recommended Configuration

By default, the csp-html-webpack-plugin has a very lax policy. You should configure it for your needs.

A good starting policy would be the following:

new CspHtmlWebpackPlugin({
  'script-src': '',
  'style-src': ''
});

Although we're configuring script-src and style-src to be blank, the CSP plugin will scan your HTML generated in html-webpack-plugin for external/inline script and style tags, and will add the appropriate hashes and nonces to your CSP policy. This configuration will also add a base-uri and object-src entry that exist in the default policy:

<meta http-equiv="Content-Security-Policy" content="
  base-uri 'self';
  object-src 'none';
  script-src 'sha256-0Tumwf1AbPDHZO4kdvXUd4c5PiHwt55hre+RDxj9O3Q='
             'nonce-hOlyTAhW5QI5p+rv9VUPZg==';
  style-src 'sha256-zfLUTOi9wwJktpDIoBZQecK4DNIVxW8Tl0cadROvQgo='
">

This configuration should work for most use cases, and will provide a strong layer of extra security.

All Configuration Options

CspHtmlWebpackPlugin

This CspHtmlWebpackPlugin accepts 2 params with the following structure:

  • {object} Policy (optional) - a flat object which defines your CSP policy. Valid keys and values can be found on the MDN CSP page. Values can either be a string, or an array of strings.
  • {object} Additional Options (optional) - a flat object with the optional configuration options:
    • {boolean|Function} enabled - if false, or the function returns false, the empty CSP tag will be stripped from the html output.
      • The htmlPluginData is passed into the function as it's first param.
      • If enabled is set the false, it will disable generating a CSP for all instances of HtmlWebpackPlugin in your webpack config.
    • {string} hashingMethod - accepts 'sha256', 'sha384', 'sha512' - your node version must also accept this hashing method.
    • {object} hashEnabled - a <string, boolean> entry for which policy rules are allowed to include hashes
    • {object} nonceEnabled - a <string, boolean> entry for which policy rules are allowed to include nonces
    • {Function} processFn - allows the developer to overwrite the default method of what happens to the CSP after it has been created
      • Parameters are:
        • builtPolicy: a string containing the completed policy;
        • htmlPluginData: the HtmlWebpackPlugin object;
        • $: the cheerio object of the html file currently being processed
        • compilation: Internal webpack object to manipulate the build

HtmlWebpackPlugin

The plugin also adds a new config option onto each HtmlWebpackPlugin instance:

  • {object} cspPlugin - an object containing the following properties:
    • {boolean} enabled - if false, the CSP tag will be removed from the HTML which this HtmlWebpackPlugin instance is generating.
    • {object} policy - A custom policy which should be applied only to this instance of the HtmlWebpackPlugin
    • {object} hashEnabled - a <string, boolean> entry for which policy rules are allowed to include hashes
    • {object} nonceEnabled - a <string, boolean> entry for which policy rules are allowed to include nonces
    • {Function} processFn - allows the developer to overwrite the default method of what happens to the CSP after it has been created
      • Parameters are:
        • builtPolicy: a string containing the completed policy;
        • htmlPluginData: the HtmlWebpackPlugin object;
        • $: the cheerio object of the html file currently being processed
        • compilation: Internal webpack object to manipulate the build

Order of Precedence:

You don't have to include the same policy / hashEnabled / nonceEnabled configuration object in both HtmlWebpackPlugin and CspHtmlWebpackPlugin.

  • Config included in CspHtmlWebpackPlugin will be applied to all instances of HtmlWebpackPlugin.
  • Config included in a single HtmlWebpackPlugin instantiation will only be applied to that instance.

In the case where a config object is defined in multiple places, it will be merged in the order defined below, with former keys overriding latter. This means entries for a specific rule will not be merged; they will be replaced.

> HtmlWebpackPlugin cspPlugin.policy
> CspHtmlWebpackPlugin policy
> CspHtmlWebpackPlugin defaultPolicy

Appendix

Default Policy:

{
  'base-uri': "'self'",
  'object-src': "'none'",
  'script-src': ["'unsafe-inline'", "'self'", "'unsafe-eval'"],
  'style-src': ["'unsafe-inline'", "'self'", "'unsafe-eval'"]
};

Default Additional Options:

{
  enabled: true
  hashingMethod: 'sha256',
  hashEnabled: {
    'script-src': true,
    'style-src': true
  },
  nonceEnabled: {
    'script-src': true,
    'style-src': true
  },
  processFn: defaultProcessFn
}

Full Default Configuration:

new HtmlWebpackPlugin({
  cspPlugin: {
    enabled: true,
    policy: {
      'base-uri': "'self'",
      'object-src': "'none'",
      'script-src': ["'unsafe-inline'", "'self'", "'unsafe-eval'"],
      'style-src': ["'unsafe-inline'", "'self'", "'unsafe-eval'"]
    },
    hashEnabled: {
      'script-src': true,
      'style-src': true
    },
    nonceEnabled: {
      'script-src': true,
      'style-src': true
    },
    processFn: defaultProcessFn  // defined in the plugin itself
  }
});

new CspHtmlWebpackPlugin({
  'base-uri': "'self'",
  'object-src': "'none'",
  'script-src': ["'unsafe-inline'", "'self'", "'unsafe-eval'"],
  'style-src': ["'unsafe-inline'", "'self'", "'unsafe-eval'"]
}, {
  enabled: true,
  hashingMethod: 'sha256',
  hashEnabled: {
    'script-src': true,
    'style-src': true
  },
  nonceEnabled: {
    'script-src': true,
    'style-src': true
  },
  processFn: defaultProcessFn  // defined in the plugin itself
})

Advanced Usage

Generating a file containing the CSP directives

Some specific directives require the CSP to be sent to the client via a response header (e.g. report-uri and report-to) You can set your own processFn callback to make this happen.

nginx

In your webpack config:

const RawSource = require('webpack-sources').RawSource;

function generateNginxHeaderFile(
  builtPolicy,
  _htmlPluginData,
  _obj,
  compilation
) {
  const header =
    'add_header Content-Security-Policy "' +
    builtPolicy +
    '; report-uri /csp-report/ ";';
  compilation.emitAsset('nginx-csp-header.conf', new RawSource(header));
}

module.exports = {
  {...},
  plugins: [
    new CspHtmlWebpackPlugin(
      {...}, {
      processFn: generateNginxHeaderFile
    })
  ]
};

In your nginx config:

location / {
  ...
  include /path/to/webpack/output/nginx-csp-header.conf
}

Contribution

Contributions are most welcome! Please see the included contributing file for more information.

License

This project is licensed under MIT. Please see the included license file for more information.

More Repositories

1

nebula

A scalable overlay networking tool with a focus on performance, simplicity and security
Go
14,374
star
2

SlackTextViewController

⛔️**DEPRECATED** ⛔️ A drop-in UIViewController subclass with a growing text input view and other useful messaging features
Objective-C
8,330
star
3

PanModal

An elegant and highly customizable presentation API for constructing bottom sheet modals on iOS.
Swift
3,631
star
4

go-audit

go-audit is an alternative to the auditd daemon that ships with many distros
Go
1,569
star
5

circuit

⚑️ A Compose-driven architecture for Kotlin and Android applications.
Kotlin
1,432
star
6

EitherNet

A pluggable sealed API result type for modeling Retrofit responses.
Kotlin
735
star
7

goSDL

goSDL
PHP
522
star
8

foundry

Gradle and IntelliJ build tooling used in Slack's Android repo
Kotlin
429
star
9

slack-api-docs

API Docs for Slack.com
427
star
10

compose-lints

Lint checks to aid with a healthy adoption of Compose
Kotlin
387
star
11

keeper

A Gradle plugin that infers Proguard/R8 keep rules for androidTest sources.
Kotlin
259
star
12

slack-lints

A collection of custom Android/Kotlin lint checks we use in our Android and Kotlin code bases at Slack.
Kotlin
231
star
13

astra

Astra is a structured log search and analytics engine developed by Slack and Salesforce
Java
209
star
14

magic-cli

Ruby
199
star
15

simple-kubernetes-webhook

This project is aimed at illustrating how to build a fully functioning kubernetes admission webhook in the simplest way possible.
Go
183
star
16

hakana

Another typechecker for Hack, built by Slack
Rust
75
star
17

hack-sql-fake

A library for testing database driven code in Hack
Hack
74
star
18

vscode-hack

Hack language & HHVM debugger support for Visual Studio Code
TypeScript
73
star
19

gsuite-oauth-third-party-app-report

Start enforcing G Suite third-party apps via OAuth
JavaScript
55
star
20

backend-interview-prep-questions

A few questions & data to help you prepare for the Slack HQ backend interview
PLpgSQL
45
star
21

moshi-gson-interop

An interop tool for safely mixing Moshi and Gson models in JSON serialization.
Kotlin
43
star
22

kotlin-cli-util

Kotlin CLI utilities, mostly intended for use with Clikt
Kotlin
36
star
23

tree-sitter-hack

Hack grammar for tree-sitter
JavaScript
33
star
24

hack-json-schema

Generate Hack JSON Schema validators based on a JSON Schema.
Hack
27
star
25

auto-value-kotlin

An AutoValue extension that generates binary and source compatible equivalent Kotlin data classes of AutoValue models.
Kotlin
26
star
26

deanimator

Go package that can detect animated images and "deanimate" them by rendering just the first frame as a static image.
Go
25
star
27

es-query-simple

A tiny command line utility to query elasticsearch. "
Python
23
star
28

go-rsyslog-pstats

Parses and forwards rsyslog process stats to a local statsite, statsd, or wire protocol compatible service.
Go
21
star
29

tiny-thumb

Novel, efficient, and practical image compression with visually appealing results. 🀏 ✨
Go
15
star
30

backend-interview-prerequisites

A project to ensure that your backend onsite interview at Slack runs smoothly.
Go
12
star
31

sqlite-go-connect

A simple go app that connects to a sqlite3 database
Go
11
star
32

sqlite-python-connect

Short bit of code to connect to a sqlite db and run a query in python
Python
10
star
33

hack-graphql

Playground for a hack graphql server
Hack
8
star
34

protoc-gen-ts

A Typescript Protocol Buffer Implementation from the Future ✨
TypeScript
8
star
35

htmlsanitizer-hack

A port of the PHP HTML Purifier originally developed by Edward Z. Yang into Hacklang
Hack
7
star
36

sqlite-java-connect

This is a minimal repo project that connects to a sqlite3 database and returns a single row.
Java
6
star
37

slack-astra-app

Grafana plugin that adds support for Astra
TypeScript
6
star
38

grpc-hack

A gRPC extension for HHVM
C++
4
star
39

sqlite-ruby-connect

Just a tiny lil something to connect to SQLite using Ruby
PLpgSQL
3
star
40

proto-hack

hacklang generator for protobuf
Hack
3
star
41

snow

Python
2
star
42

.github

1
star
43

go-metrics-prometheus

Go
1
star
44

quota

1
star