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.
Install the plugin with npm:
npm i --save-dev csp-html-webpack-plugin
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="">
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 allowunsafe-inline
/unsafe-eval
and not include hashes for inline scripts. If any hashes are included in the policy, modern browsers ignore theunsafe-inline
rule.{boolean|Function}
enabled - if false, or the function returns false, the empty CSP tag will be stripped from the html output. ThehtmlPluginData
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
{
'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',
}
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',
})
Contributions are most welcome! Please see the included contributing file for more information.
This project is licensed under MIT. Please see the included license file for more information.