Skip to content

phil-lgr/csp-html-webpack-plugin

 
 

Repository files navigation

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

In the plugins section of your webpack config file, include the following:

new HtmlWebpackPlugin()
new CspHtmlWebpackPlugin()

Finally, add the following tag to your HTML template where you would like to add the CSP policy:

<meta http-equiv="Content-Security-Policy" content="">

Configuration

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} devAllowUnsafe - if you as the developer want to allow unsafe-inline/unsafe-eval and not include hashes for inline scripts. If any hashes are included in the policy, modern browsers ignore the unsafe-inline rule.
    • {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.
    • {string} hashingMethod - accepts 'sha256', 'sha384', 'sha512' - your node version must also accept this hashing method.

_Note: CSP runs on all files created by HTMLWebpackPlugin. You can disable it for a particular instance by setting disableCspPlugin to true in the HTMLWebpackPlugin options

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:

{
  devAllowUnsafe: false,
  enabled: true
  hashingMethod: 'sha256',
}

Full Configuration with all options:

new CspHtmlWebpackPlugin({
  'base-uri': "'self'",
  'object-src': "'none'",
  'script-src': ["'unsafe-inline'", "'self'", "'unsafe-eval'"],
  'style-src': ["'unsafe-inline'", "'self'", "'unsafe-eval'"]
}, {
  devAllowUnsafe: false,
  enabled: true
  hashingMethod: 'sha256',
})

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.

About

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

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 95.0%
  • HTML 5.0%