Giter Site home page Giter Site logo

slackhq / csp-html-webpack-plugin Goto Github PK

View Code? Open in Web Editor NEW
159.0 81.0 39.0 1.63 MB

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

License: MIT License

JavaScript 96.21% HTML 3.79%
webpack csp html-webpack-plugin

csp-html-webpack-plugin's Introduction

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.

csp-html-webpack-plugin's People

Contributors

anujrnair avatar daniel-khodabakhsh avatar david-fong avatar dependabot[bot] avatar pierroberto avatar samsaggace avatar sibiraj-s avatar swac avatar wanecek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

csp-html-webpack-plugin's Issues

using with .cshtml and such

Description

I'm using the plugin with .cshtml file.
My template is like this:

@using System.Threading;
@using SOME.Controllers;
@{
    var app = ViewBag.NgModule != null ? ViewBag.NgModule : "SOME";
    var ie8 = IsIE() && GetIEVersion() <= 8;
}
<!DOCTYPE html>
<html lang="en" ng-app="@app" id="ng-app" class="height100">
<head>
    <meta charset="utf-8" />
    @if (string.IsNullOrWhiteSpace(ViewBag.Title))
    {
        <title>SOMEShare &amp; Collect</title>
    }
    else
    {
        <title>@ViewBag.Title</title>
    }
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <meta http-equiv="content-security-policy" content="" />
...

The output I'm getting is like this:

<html lang="en" ng-app="@app" id="ng-app" class="height100"><head><meta http-equiv="Content-Security-Policy" content="base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-eval' 'nonce-n1st7Y/9LxdP2jtjoIB/RA=='; style-src 'self' 'unsafe-inline'; default-src 'self' https://some.rocket.chat; worker-src 'slef' blob: data: 'unsafe-eval' 'unsafe-inline'; frame-src 'self' https://some.rocket.chat; font-src 'self' https://kendo.cdn.telerik.com data:; img-src 'self' data:; connect-src 'self' https://some.rocket.chat"></head><body class="height100">@using System.Threading;
@using SOME.Controllers;
@{
    var app = ViewBag.NgModule != null ? ViewBag.NgModule : "SOME";
    var ie8 = IsIE() && GetIEVersion() <= 8;
}



    <meta charset="utf-8">
    @if (string.IsNullOrWhiteSpace(ViewBag.Title))
    {
        <title>SOME Share & Collect</title>
    }
    else
    {
        <title>@ViewBag.Title</title>
    }
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon">
    <meta http-equiv="content-security-policy" content>

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Question OR Enhancement

In order for webpack-html-plugin to work with these files I'm using this in my .cshtml template

    <%= Object.keys(htmlWebpackPlugin.files.chunks).map(k => {
      return `<script src="~/Scripts${htmlWebpackPlugin.files.chunks[k].entry}"></script>`;
    }).join('\n') %>

It seems I need something similar for the csp-html-webpack-plugin.
Is there a better way to do it, that is not documented?

Meta tag not included when using index.ejs template

Description

Hello,
I am using HtmlWebpackPlugin to define an index.ejs file as template. I am also passing some templateParameters through the HtmlWebpackPlugin (below given random names for security but you get the picture). If I leave the csp meta tag in the index.ejs, it doesn't get overwritten by your csp plugin, and if I remove it completely then it's not even created. I must add that I am using webpack-dev-server with hot reloading to develop and test it locally. I am giving you an excerpt of both plugin configurations up till now, could you maybe shed some light as to how to use them properly?

// ... rest of code

const cspOptions = {
      'script-src': ['"self"', '"unsafe-eval"', '"resource:"'],
      'style-src': ['"self"', '"unsafe-inline"'],
      'connect-src': ['"blob:"', '"http://localthost:*"', '"ws://localhost:*"'],
      'font-src': '"self"',
      'object-src': '"blob:"',
      'img-src': ['"data:"', '"self"'],
      'media-src': '"self"',
      'form-action': '"self"',
      'child-src': ['"blob:"'],
      'worker-src': ['"blob:"', '"resource:"'],
      'frame-src': ['"blob:"', '"self"'],
      'base-uri': '"resource"',
      'block-all-mixed-content': true // Is this even working like that?
};
new HtmlWebpackPlugin({
       cspPlugin: {
           enabled: true,
           policy: cspOptions,
        }
        inject: false,
        template: './public/index.ejs',
        templateParameters: {
            platform: 'browser',
            mode: 'development',
            pathPrefix: './',
            backend: 'http://localhost:3001',
            metaDescription: 'Testing CSP',
            title: 'Test App',
        },
        minify: false
      }),
new CspHtmlWebpackPlugin(cspOptions)
// ... rest of code

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

slackhq/csp-html-webpack-plugin version: v3.0.4

node version: v8.11.1

OS version(s): Windows 10

Expected result:

Have an overwritten csp meta tag within the built index.html or if it wasn't existing have a new csp meta tag created with this plugin's configuration

Actual result:

No meta tag is overwritten or created based on this plugin's configuration

Not getting hashes in meta tag

Description

I am not seeing hashes in the meta tag when I expected I would. I do seem to get nonces, but they don't appear to work.

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

If I use this as my webpack configuration:

new HtmlWebpackPlugin( {
                filename: "../app/html/webpack_index.html",
                template: "app/html/index_template.html",
                chunks: [ "app" ],
                cspPlugin: {
                    enabled: true,
                    policy: {
                        "base-uri": "'self'",
                        "object-src": "'none'",
                        "script-src": [ "https://127.0.0.1:8080", "'self'" ],
                        "style-src": [ "https://127.0.0.1:8080", "'self'"],
                        "font-src": [ "'unsafe-inline'", "'unsafe-eval'", "https://127.0.0.1:8080", "'self'" ],
                    },
                    hashEnabled: {
                        "script-src": true,
                        "style-src": true,
                    },
                    nonceEnabled: {
                        "script-src": true,
                        "style-src": true,
                    },
                },
            } ),
            new HtmlWebpackPlugin( {
                filename: "../app/html/webpack_popup.html",
                template: "app/html/popup_template.html",
                chunks: [ "form" ],
            } ),
            new HtmlWebpackPlugin( {
                filename: "../app/html/webpack_codemirror.html",
                template: "app/html/codemirror_template.html",
                chunks: [ "editor" ],
            } ),
            new HtmlWebpackPlugin( {
                filename: "../app/html/webpack_error_wrapper.html",
                template: "app/html/error_wrapper_template.html",
                chunks: [ "error" ],
            } ),
            new HtmlWebpackPlugin( {
                filename: "../app/html/webpack_documentation.html",
                template: "app/html/documentation_template.html",
                chunks: [ "docs_entry" ],
            } ),
            new CspHtmlWebpackPlugin( {
                "base-uri": "'self'",
                "object-src": "'none'",
                "script-src": [ "'unsafe-inline'", "'unsafe-eval'", "https://127.0.0.1:8080", "'self'" ],
                "style-src": [ "'unsafe-inline'", "'unsafe-eval'", "https://127.0.0.1:8080", "'self'"],
                "font-src": [ "'unsafe-inline'", "'unsafe-eval'", "https://127.0.0.1:8080", "'self'" ],
            }, {
                enabled: true,
                hashingMethod: "sha256",
                hashEnabled: {
                    "script-src": true,
                    "style-src": true,
                },
                nonceEnabled: {
                    "script-src": false,
                    "style-src": false,
                },
            } ),

then it produces this output (for the app chunk):

<meta http-equiv="Content-Security-Policy" content="base-uri 'self'; object-src 'none'; script-src https://127.0.0.1:8080 'self' 'nonce-iy87WccFQS7zHW0XbzFJCw=='; style-src https://127.0.0.1:8080 'self' 'nonce-eqk3Sox+amk9wfdSl3g5GQ=='; font-src 'unsafe-inline' 'unsafe-eval' https://127.0.0.1:8080 'self'>

and I see this error:
<meta http-equiv="Content-Security-Policy" content="base-uri 'self'; object-src 'none'; script-src https://127.0.0.1:8080 'self' 'nonce-iy87WccFQS7zHW0XbzFJCw=='; style-src https://127.0.0.1:8080 'self' 'nonce-eqk3Sox+amk9wfdSl3g5GQ=='; font-src 'unsafe-inline' 'unsafe-eval' https://127.0.0.1:8080 'self'; connect-src 'unsafe-inline' 'unsafe-eval' https://127.0.0.1:8080 'self' https://ipv4.icanhazip.com wss://127.0.0.1:8080 https://api.keygen.sh">

which is coming from addStyles.js, part of the style-loader package.

If I now set the nonce enabled to be false, as below:

new HtmlWebpackPlugin( {
                filename: "../app/html/webpack_index.html",
                template: "app/html/index_template.html",
                chunks: [ "app" ],
                cspPlugin: {
                    enabled: true,
                    policy: {
                        "base-uri": "'self'",
                        "object-src": "'none'",
                        "script-src": [ "https://127.0.0.1:8080", "'self'" ],
                        "style-src": [ "https://127.0.0.1:8080", "'self'"],
                        "font-src": [ "'unsafe-inline'", "'unsafe-eval'", "https://127.0.0.1:8080", "'self'" ],
                    },
                    hashEnabled: {
                        "script-src": true,
                        "style-src": true,
                    },
                    nonceEnabled: {
                        "script-src": false,
                        "style-src": false,
                    },
                },
            } ),
            new HtmlWebpackPlugin( {
                filename: "../app/html/webpack_popup.html",
                template: "app/html/popup_template.html",
                chunks: [ "form" ],
            } ),
            new HtmlWebpackPlugin( {
                filename: "../app/html/webpack_codemirror.html",
                template: "app/html/codemirror_template.html",
                chunks: [ "editor" ],
            } ),
            new HtmlWebpackPlugin( {
                filename: "../app/html/webpack_error_wrapper.html",
                template: "app/html/error_wrapper_template.html",
                chunks: [ "error" ],
            } ),
            new HtmlWebpackPlugin( {
                filename: "../app/html/webpack_documentation.html",
                template: "app/html/documentation_template.html",
                chunks: [ "docs_entry" ],
            } ),
            new CspHtmlWebpackPlugin( {
                "base-uri": "'self'",
                "object-src": "'none'",
                "script-src": [ "'unsafe-inline'", "'unsafe-eval'", "https://127.0.0.1:8080", "'self'" ],
                "style-src": [ "'unsafe-inline'", "'unsafe-eval'", "https://127.0.0.1:8080", "'self'"],
                "font-src": [ "'unsafe-inline'", "'unsafe-eval'", "https://127.0.0.1:8080", "'self'" ],
            }, {
                enabled: true,
                hashingMethod: "sha256",
                hashEnabled: {
                    "script-src": true,
                    "style-src": true,
                },
                nonceEnabled: {
                    "script-src": false,
                    "style-src": false,
                },
            } ),

then it produces this output (for the app chunk):
<meta http-equiv="Content-Security-Policy" content="base-uri 'self'; object-src 'none'; script-src https://127.0.0.1:8080 'self'; style-src https://127.0.0.1:8080 'self'; font-src 'unsafe-inline' 'unsafe-eval' https://127.0.0.1:8080 'self'>

and I see this error:
Refused to apply inline style because it violates the following Content Security Policy directive: "style-src https://127.0.0.1:8080 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='), or a nonce ('nonce-...') is required to enable inline execution.

If I delete the nonceEnabled section in the app chunk settings then I get the same result as setting them to false.

So my questions are why am I not getting hashed generated and what do I need to do so that thye are generated and secondly, why is the nonce that is generated not working - how can I tell what the nonce relates to ?

Thanks for your help.

Reproducible in:

slackhq/csp-html-webpack-plugin version: 3.0.1

node version: 10.13

OS version(s): Windows 10

Steps to reproduce:

As its a question I have not tried to reproduce the issue in a cut down setup.

Expected result:

Expected to see hashes inserted into the meta tag

Actual result:

Nonces were inserted, but seemed to have no effect.

Attachments:

None

Allow `nonceEnabled` to take a single boolean value

Description

Describe your issue here.

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Feature Request:

Being able to enable/disable nonces for each directive is really nice, but in my specific case I want to disable all usage of nonces and the list of directives is steadily growing. If csp-html-webpack-plugin updates and adds support for a new directive, I have to remember to disable that one too, and truth be told: I'll likely forget to do that.

If the option could take a value of true to enable all (supported) directives and false to disable all, that'd be pretty nice :-)

As an example:

before:

            nonceEnabled: {
                'base-uri': false,
                'child-src': false,
                'connect-src': false,
                'default-src': false,
                'font-src': false,
                'form-action': false,
                'frame-ancestors': false,
                'frame-src': false,
                'img-src': false,
                'manifest-src': false,
                'media-src': false,
                'object-src': false,
                'script-src': false,
                'style-src': false,
                'trusted-types': false,
                'worker-src': false
            }

after:

            nonceEnabled: false

babel-jest should live in devDependencies

Description

babel-jest appears in the regular dependencies, so it's getting installed along with the rest of the code.

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

slackhq/csp-html-webpack-plugin version: 3.0.0

node version: 8, 10

OS version(s): macOS 10.14 (Mojave)

Steps to reproduce:

  1. npm i csp-html-webpack-plugin
  2. Inspect node_modules directory

Expected result:

Only the deps which are actually consumed are installed along with csp-html-webpack-plugin

Actual result:

babel-jest is present. Also you get a warning if you don't satisfy babel-jest's peerDependency for babel-core.

Consider adding documentation for automatic webpack server restart

Description

Hi, thank you for this great plugin!!
When tweaking my CSP in webpack.config.js, I found myself stopping and restarting my webpack server for my CSP changes to be taken into account. I ended up using nodemon to do this automatically and save time. I think this may be a common workflow, since setting up CSP involves tweaking and back-and-forth.
Do you think it would make sense for the README to include a note on how to set this up?

This is what I did:

  • Created nodemon.json in my project root:
{
  "watch": ["webpack.config.js"],
  "exec": "node scripts/start.js" // = what was in my package.json's start script
}
  • In package.json, added a new script:
 "start:watch:webpack": "nodemon",
  • Used npm run start:watch:webpack when setting up my CSP.

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Escaped html tag becomes unescaped unexpectedly

Description

If this plugin is enabled, escaped html (ex. '<' or '>' ) becomes unescaped.
So, this behavior makes unexpected output, and maybe causes potential bug.

For example:

Before

<html>
<body>
&lt;h1&gt;This is not h1.&lt;h1&gt;
</body>
</html>

After

<html>
<body>
<h1>This is not h1.</h1>
</body>
</html>

Also I found below issue (cheerio's one). This plugin uses cheerio, so it seems below issue is root cause.
cheeriojs/cheerio#1219

Do you have any solutions?

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

slackhq/csp-html-webpack-plugin version: 3.0.2

node version: v12.4.0

OS version(s): ArchLinux (latest)

Steps to reproduce:

  1. Add new CspHtmlWebpackPlugin() to webpack config to enable this plugin
  2. Build html which containing escaped html
  3. Unescaped html will be out.
  4. Remove (1.) config and rebuild
  5. Escaped html will be out. So, I think this behavior is caused by this plugin,

Expected result:

Escaped html should be escaped.

Actual result:

Escaped html becomes unescaped.

Attachments:

My webpack config (plugins section):

        plugins: [
            new MiniCssExtractPlugin({
                filename: 'style/style-[hash].css'
            }),
            new HtmlWebpackPlugin({
                filename: 'index.html',
                template: path.join(__dirname, 'src', 'index.html')
            }),
            new CspHtmlWebpackPlugin(),
            new CopyWebpackPlugin([
                {from: path.join(__dirname, 'src', 'favicon.ico'), to: './'},
                {from: path.join(__dirname, 'src', 'images'), to: 'images'},
            ]),
        ]

Example of using with Helm and multiple environment/values files

Description

Was wondering if anyone was using this with a Helm nginx + configmap deployment where some environments have different values. I'd like to be able to set a domain for test (.test.com) and a domain for production (.prod.com) with the helm chart but also have it work with values files.

Currently our values files have directives set and are overridden as needed with a values.prod.yaml file, etc.

Off the top of my head, I suppose it could be solved by creating multiple output files for each environment and the values file would inject into the config map the proper csp file output, but maybe there is a better solution?

If anyone is doing something similar and has any suggestions or comments please share as I'd like to learn the best process.

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

[Security] Nonce reuse

Nonce reuse

I have a question in regard to nonceEnabled:
I assume that the csp-html-webpack-plugin is only invoked at build time and not for every http request. If this assumption is correct, how can one prevent attackers from just copying CSP nonces and by that bypassing the entire CSP?

Relevant section in the CSP spec is here: https://w3c.github.io/webappsec-csp/#security-nonces

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

package.json metadata missing?

Description

Hi :) I got notified of 3.0.0 by dependabot in one of my repositories.

Dependabot was unable to show me the changelog and commits. I noticed that the link to the repository was https://github.com/anuj/csp-html-webpack-plugin, but that repository seems to no longer exist. I think it was migrated to slackhq.

I don't know what caused dependabot to show the old URL, but maybe adding some URLs to package.json helps? I noticed in https://www.npmjs.com/package/csp-html-webpack-plugin that there are no links in the sidebar.

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

No nonce values are showing up in the CSP string

Description

nonce values are being added to the script and style tags in my HTML, but the nonces aren't in the CSP string itself. This appears similar to #93 but I'm on Mac OS and I'm using the latest node v14.

I am using an HTML template. A minimal webpack config with this exact template does not exhibit the issue, which makes me think something about my more complex webpack config is preventing the nonces from being added to the CSP.

Curiously, hashes for inline scripts do show up in the CSP string, so it is definitely being generated.

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

I am using this config to generate a CSP.

  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/www/index.tpl.html',
      inject: 'body',
      filename: 'index.html'
    }),
    new CspHtmlWebpackPlugin({
      'script-src': '',
      'style-src': ''
    }),
    // I am using other plugins after these: mini-css-extract-plugin, webpack.IgnorePlugin, copy-webpack-plugin, dotenv-webpack, webpack.ProvidePlugin
  ]

It results in a CSP like the following:

<meta http-equiv="Content-Security-Policy" content="base-uri 'self'; object-src 'none'; script-src 'sha256-ABCXYZ=' โ€ฆ 'sha256-123999'; style-src ">

That is: it creates a CSP using hashes for inline scripts, but there are no nonces for script-src or style-src. The nonce attribute is present in a number of <script> and <style> tags in the final HTML document.

Reproducible in:

slackhq/csp-html-webpack-plugin version: 5.1.0

node version: 14.19.3

OS version(s): Mac OS 12.4

Steps to reproduce:

  1. Use the above config to build the app.
  2. View the built index.html asset.

Expected result:

The CSP content to have the nonce values in it.

Actual result:

The nonce values are attached to the script and style tags but are not present in the CSP string itself.

Attachments:

Logs, screenshots, screencast, sample project, funny gif, etc.

Enable Report-Only

Description

In order to properly test the introduction of new CSPs, it would be amazing if the plugin was able to also output a meta tag with http-equiv="Content-Security-Policy-Report-Only". Ideally, these tags could co-exist, so you can leave the already active CSPs in place, while testing new policies at the same time, i.e. it would allow two separate configurations.

I'm happy to contribute if the feature fits the scope of this plugin and nothing is in the pipeline yet...

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Generates wrong hashes

Description

Plugin generates wrong hashes since 5.0.1

What type of issue is this?

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

slackhq/csp-html-webpack-plugin versions: 5.0.1 - 5.1.0

node versions: 14.16.0 and 14.17.0

OS version(s): Windows 10

Cheerio 1.0.0-rc.4

Hi,

Can you please upgrade to Cheerio 1.0.0-rc.4?

Cheerio 1.0.0-rc.4 uses Lodash 4.17.20 which fixes vulnerabilities.

Create <meta> tag if it's not there.

Description

The <meta http-equiv="content-security-policy" content=""> tag should be created automatically if it's not present in the template.

Not everyone uses an explicit template, and instead uses the template automatically generated by HtmlWebpackPlugin.

What type of issue is this?

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Documentation may be misleading and hashEnabled option does not work

Description

Straight from the docs, we can see this:

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
    }
  }
});

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
  }
})

It tells us about the default options, but it fails to tell us that it can be used one way or another.
If that's not the case, well, it works that way for me. I was looking at the docs for the first time and immediately thought that configuration must be placed within both places, which is weird. But that doesn't seem to be the case. We don't have to define cspPolicy property within HTMLWebpackPlugin if we are using CspHtmlWebpackPlugin.

Anyways, aside from this, I came across a real issue.
The option hashEnabled does not seem to be working. If I set both properties to true or to false, it does nothing... No hash calculations of internal scripts and styles, so they are nowhere to be found within CSP tag.

However, if I only enable nonceEnabled it seems to be working, not quite sure YET, but I can see nonce hashes in the CSP tag. Howevever, nonce should be different for each page load, so that's not really what I'm looking for in my SPA.

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

I assume it's a bug, but it might be a misunderstanding of usage.
hashEnabled โ€“ not working.

Reproducible in:

slackhq/csp-html-webpack-plugin version: ^3.0.4

node version: v13.11.0

OS version(s): macOS Catalina 10.15.3 (19D76)

Steps to reproduce:

  1. Use vue-json-pretty npm package, as it will inject style on each load. Any plugin will do, but this is an example. You might also make a small script that will inject some CSS.

Expected result:

To have SHA-256 hashes within my CSP policy for internal scripts and styles.

Actual result:

Nothing. It literally does nothing.

Cannot read property 'tapAsync' of undefined when using with HTML Webpack Plugin 4.0.0-alpha.2

Description

I used the latest create-react-app CLI to bootstrap my project and then I ejected it. The latest create-react-app uses "html-webpack-plugin" version 4.0.0-alpha.2. When I use "csp-html-webpack-plugin" with it I am getting the following error

Cannot read property 'tapAsync' of undefined

I have already tried placing "csp-html-webpack-plugin" at the end of the plugins list after "html-webpack-plugin" and still I am getting the same issue.

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

slackhq/csp-html-webpack-plugin version: 2.3.0

node version: 8.12.0

OS version(s): OSX Mojave

Steps to reproduce:

  1. Bootstrap an app with the latest create-react-app CLI
  2. Eject the application
  3. Then try using "csp-html-webpack-plugin"

Expected result:

Expected the build to complete

Actual result:

Got the error "Cannot read property 'tapAsync' of undefined"

Problem in setting nonce when using a custom processFn

Description

When I use a custom processFn to procces the built policy, nonces aren't set in HTML elements. It works fine when I remove my custom processFn from additional Options

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Reproducible in:

slackhq/csp-html-webpack-plugin version: 4.0.0


Here is my code:

const cspConfigPolicy = {
  "default-src": ["'self'"],
  "connect-src": [
    "'self'",
    REACT_APP_WS_BASE_URL,
    REACT_APP_API_BASE_URL + "/",
    REACT_APP_FIREBASE_REMOTE_CONFIG_PROXY_HOST,
    REACT_APP_DATADOG_LOGS_PROXY_HOST,
    REACT_APP_DATADOG_RUM_PROXY_HOST,
    ...REACT_APP_ALLOWED_CONNECT_SRC_URLS.split(","),
    "https://firebaseinstallations.googleapis.com",
    "https://fcmregistrations.googleapis.com",
    "https://sentry.io",
    "https://www.google-analytics.com/",
  ],
  "base-uri": "'self'",
  "script-src": [
    "'self'",
    "https://www.google.com/recaptcha/",
    "https://use.fontawesome.com",
    "https://www.googletagmanager.com",
    "https://static.hotjar.com",
    "https://storage.googleapis.com/workbox-cdn/",
    "https://www.gstatic.com/",
    "'unsafe-inline'",
    ...REACT_APP_ALLOWED_SCRIPT_SRC_URLS.split(","),
  ],
  "style-src-elem": [
    "'self'",
    "'unsafe-inline'",
    "https://fonts.googleapis.com/css",
  ],
  "frame-src": [
    "'self'",
    "https://www.google.com/recaptcha/",
    ...REACT_APP_ALLOWED_FRAME_SRC_URLS.split(","),
  ],
  "font-src": ["'self'", "https://fonts.gstatic.com/"],
  "img-src": ["'self'", "data:"],
};

/**
 * Used to write the built csp in a file in the build directory
 * @param {string} builtPolicy
 */
const processBuiltCsp = (builtPolicy) => {
  fs.writeFile("./build/csp.txt", builtPolicy, (err) => {
    if (err) {
      return;
    }
  });
};

function addCspHtmlWebpackPlugin(config) {
  if (NODE_ENV === "production" && REACT_APP_CSP_ENABLE === "1") {
    config.plugins.push(
      new cspHtmlWebpackPlugin(cspConfigPolicy, {
        processFn: processBuiltCsp,
      })
    );
  }
  return config;
}

Add hashes to external scripts (CSP3)

Description

According to Mozilla's documentation, CSP3 allows for the <hash-algorithm>-<base64-value> attribute of script-src to be applied for external scripts.

As I understand it (based on reading #35 and trying out the plugin myself), hashes are not generated and included for external scripts, only inline scripts.

It'd be nice if they could be included for external scripts too. (Maybe via a default-false configuration option?)

What type of issue is this?

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Angular 8+ ready

Description

The CspHtmlWebpackPlugin is a plugin made for Webpack, but doesn't integrate with the Angular build process anymore. Since Angular 8+ will generate the index.html outside the Webpack build process. You need to use the indexTransform parameter of @angular-builders/custom-webpack to do this.

I wrote the code to do this. This code is already being used in production. But I think that it would be nicer when this code is incorporated into this project, so maintaining and testing is more easier.

You can find an example project on https://gitlab.flusso.nl/public-projects/angular-csp-html-transform-example.

I like to help / code this solution, but would like a direction how to do this.

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Nonce seems to be static - recommanded conf is dangerous for static website generators

Description

Trying to use this plugin within a static website is opening security holes by default.
For example if we follow #53, it will add static nonces on a static website.

I would recommend to disable nonces by default, and let the user enable them on when they know that they wont pack a static website

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

slackhq/csp-html-webpack-plugin version: 5.1.0

Steps to reproduce:

  1. create static website, such with as npx create-react-app my-app --template typescript
  2. Install and wire the plugin npm install react-app-rewired csp-html-webpack-plugin --save-dev
  3. Configure webpack overrides in config-overrides.js
const CspHtmlWebpackPlugin = require("csp-html-webpack-plugin");

module.exports = function override(config, env) {
  config.plugins.push(
    new CspHtmlWebpackPlugin({
      "script-src": "",
      "style-src": "",
    })
  );
  return config;
};
  1. Build with react-app-rewired build
  2. Check build/index.html file

Expected result:

Nonces are not static. At the very least, they should be generated by an inline script and injected

Actual result:

Static nonces are generated.
Uploading this to a CDN will allow anyone to grab the nunce and re-use it, bypassing the CSP

  <meta http-equiv="Content-Security-Policy"
    content="base-uri 'self'; object-src 'none'; script-src 'nonce-csu9vwLV51tCaN6biAAJFg=='; style-src 'nonce-vAVCeRTmI/cROWHcZcycQA=='">

Add support for Report-Only mode

Description

During testing and fine-tuning it is helpful to add CSP in report-only mode. It would be helpful to have an additional option that would allow to not just enable/disable the CSP but to change it to Content-Security-Policy-Report-Only

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Updated Contributor Agreement

Updated Contributor Agreement

Slack has recently updated it's contributor agreement to cover all Slack projects you might contribute to instead of just this one

As contributors to the csp-html-webpack-plugin, I'd appreciate if you wouldn't mind signing this new agreement to transfer your signature over! You rights don't change in doing so

https://cla-assistant.io/slackhq/hack-json-schema
(the url has hack-json-schema in it, but it covers all slack projects you might contribute to)

Please do let me know if you have any questions -- I'd be happy to get back to you with answers!

cc @sibiraj-s @wanecek @swac @pierroberto @ScottRocha @Daniel-Khodabakhsh

Adding nonces to inline styles in <head>

Description

When using React, Ant Design, webpack and Less - loader this plugin almost works out of the box. The only thing that does not seem to work is adding nonces to the inline styles in the element. Is their a way that you now of to get this to work?

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

slackhq/csp-html-webpack-plugin version: 5.1.0

node version: 12.18.3

OS version(s): Windows 10

Steps to reproduce:

  1. Use React and Ant-design with this override config for Create React App
const { override, fixBabelImports, addLessLoader } = require("customize-cra");
const cspHtmlWebpackPlugin = require("csp-html-webpack-plugin");
const path = require("path");

const cspConfigPolicy = {
  "default-src": "'none'",
  "base-uri": "'self'",
  "object-src": "'none'",
  "script-src": ["'self'"],
  "frame-src": [],
  "manifest-src": ["'self'"],
  "font-src": ["'self'"],
  "connect-src": [
    "'self'",
  ],
  "style-src": ["'self'", "'unsafe-inline'"],
  "img-src": [
    "'self'",
  ],
};

function addCspHtmlWebpackPlugin(config) {
  config.plugins.push(new cspHtmlWebpackPlugin(cspConfigPolicy));
  return config;
}

module.exports = override(
  fixBabelImports("import", {
    libraryName: "antd",
    libraryDirectory: "es",
    style: true,
  }),
  addLessLoader({
    lessOptions: {
      javascriptEnabled: true,
      modifyVars: {
        "ant-theme-file":
          "; @import '" +
          path.resolve(
            __dirname,
            "./src/shared-components/styles/vendors-extensions/antd.less"
          ) +
          "'",
      },
    },
  }),
  addCspHtmlWebpackPlugin
);

Expected result:

To have a nonce attribute added, same way they are added to script-tags.

Actual result:

To have nonces also added to the inline script tags

Attachments:

image

Logs, screenshots, screencast, sample project, funny gif, etc.

Elements within <noscript> are not hashed

Description

If your source HTML has a <noscript> element with e.g. an inline <style> child element, that style is not getting hashed and no hash corresponding to it can be found in the meta CSP tag in the output.

I imagine that styles within a <noscript> can and should be included when hashes are being generated.

I have looked into this and it is related to cheerio's load() function, which by default uses parse5, which acts as a javascript-enabled user agent, and so when parse5 parses the input HTML, it properly (from its perspective) does not parse the contents of a <noscript> (or more accurately it does parse it but returns the contents as plain text rather than DOM nodes).

Cheerio can be configured to use htmlparser2, and when we do that, it handles the <noscript> as desired and we get the children DOM elements (e.g. the <style>). However it seems that explicitly configuring cheerio to use htmlparser2 is done via an internal undocumented option: _useHtmlParser2: true which may not be safe for consumers such as this package to use.

You can also use cheerio's xmlMode: true option which also parses <noscript> as desired, but that changes the output HTML into an XML document and has all sorts of unwanted (most likely) side effects for the generated HTML.

References:
cheeriojs/cheerio#1105
inikulin/parse5#105
https://github.com/fb55/htmlparser2

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

slackhq/csp-html-webpack-plugin version: 4.0.0

node version: 10.19.0

OS version(s): macOS Catalina version 10.15.5

Steps to reproduce:

  1. Have a <noscript> element with a simple inline <style> child element e.g. this index.ejs template
<!doctype html>
<html lang="en">
  <head> 
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <noscript>
      <style>
        .disabled-javascript {
          color: red;
        }
      </style>
    </noscript>
  </head>
  <body>
    <h1>Hello World</h1>
  </body>
</html>
  1. Setup HtmlWebpack to use the above as its template
  2. Setup csp-html-webpack-plugin as follows:
new CspHtmlWebpackPlugin({
      'base-uri': "'self'",
      'object-src': "'none'",
      'script-src': ["'self'"],
      'style-src': ["'self'"]
    }, {
      enabled: true,
      hashingMethod: 'sha256',
      hashEnabled: {
        'script-src': true,
        'style-src': true
      },
      nonceEnabled: {
        'script-src': false,
        'style-src': false
      }
    })

Expected result:

In the generated CSP meta tag, I should see a corresponding hash entry in the style-src directive

Actual result:

In the generated CSP meta tag, I only see 'self' in the style-src directive.

Attachments:

Logs, screenshots, screencast, sample project, funny gif, etc.

Documentation tweaks

Description

Hi again :) As a newcomer to this (great!) plugin, a few things in the README.md caused minor friction for me.
I've listed a few suggestions for tweaks in README.md below. Not all of these may make sense, so feel free to point out to the ones you think don't or do!

  1. Would you consider adding const CspHtmlWebpackPlugin = require('csp-html-webpack-plugin'); for example in this section?
  2. In the full configuration example, consider replacing unsafe-eval with something else? To encourage the use of safe policies. And because if other developers are lazy like me, they first may copy the example policy into their code before editing it (andโ€”pushing the idea a bit hereโ€”it's not impossible to forget to remove unsafe-eval). unsafe-inline feels more OK, since AFAIK it's needed in Safari.
  3. In the full configuration example, consider removing processFn: defaultProcessFn or adding an // optional comment above it? Why: as mentioned, my first reflex was to paste the full config example CSP to save myself some typing time. And so I ran into defaultProcessFn is not definedโ€”which was a super quick one to fix, but it did require me to go back and edit my config. Maybe the question here is if you expect this feature to be used by most / a large part of this plugin's users? On the plus side though: this error was actually a good way for me to discover the feature / this ability to change the default method of what happens to the CSP after it has been created...

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Add nonce also for preloaded scripts

Description

At @productboard we plan to use this plugin (thanks for that!). We use script preloads to optimize loading experience. I propose that nonces should be also added on those.

<link rel="preload" href="..." as="script" crossorigin="anonymous">

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Regression in 5.0.1

Description

Describe your issue here.

  • bug

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

slackhq/csp-html-webpack-plugin version: 5.0.1

node version: 14

OS version(s): windows 10

Steps to reproduce:

git checkout http://github.com/david-fong/snakey3.git
cd snakey3
git checkout 396fe45
./scripts/pack -t
  1. open file:///.../snakey3/dist/client/index.html and observe error for incorrect script sha in the browser devtools.
  2. git checkout @~ && ./scripts/pack, then open again and observe that there is no such error.

I'm not sure why this happens.

Expected result:

I expect that bumping from version 5.0.0 to 5.0.1 shouldn't break anything.

Actual result:

Something broke.

Attachments:

Peer Dependency for WebPack v5

Description

The current package.json doesn't specify webpack 5 as a peer dependency. Is this intentional?

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

CSP header not visible in network tab

Description

I'm not sure if this is a bug or if my config is off but although I see the Content-Security-Policy meta tag generated in /build/index.html, I still don't see the header presenting in the response headers in the browser. I am using a Lambda for the other required headers but as is the purpose of this library, I can't whitelist my constantly changing chunk so I've decided to configure just CSP in a meta tag with this plug-in. I followed this article to implement it: https://medium.com/@nrshahri/csp-cra-324dd83fe5ff

Does anyone have any insight here as to why the header isn't visible? Can I not mix with Lambda?

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

slackhq/csp-html-webpack-plugin version: 3.0.4

node version: 8.10.0

OS version(s): Ubuntu 18.04

Steps to reproduce:

Expected result:

What you expected to happen

Actual result:

What actually happened

Attachments:

Logs, screenshots, screencast, sample project, funny gif, etc.

Not generating meta tag

Description

I use an ejected CRA webpack.config.js. When adding your plugin and trying to generate a CSP meta tag, nothing is appended to HTML. Any idea how I can get this to work?

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

cra 2.0.0

node version: 8.6

OS version(s):

Steps to reproduce:

Here is my webpack.config.js snippet:

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
            }
          }
        },
        {
          inject: true,
          template: paths.appHtml,
        },
        isEnvProduction
          ? {
            minify: {
              removeComments: true,
              collapseWhitespace: true,
              removeRedundantAttributes: true,
              useShortDoctype: true,
              removeEmptyAttributes: true,
              removeStyleLinkTypeAttributes: true,
              keepClosingSlash: true,
              minifyJS: true,
              minifyCSS: true,
              minifyURLs: true,
            },
          }
          : undefined
      ),

      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
          }
        }),

Expected result:

tag appended to html

Actual result:

Nothing is appended

CSP Plugin doesn't put the nonce value into CSP meta tag on Windows

Description

Describe your issue here.

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

If i use this CSP configuration on Mac

new CspHtmlWebpackPlugin(
      {
        'script-src': ['\'strict-dynamic\''],
        'style-src': ['\'self\''],
        'frame-src': ['\'none\''],
        'worker-src': ['\'none\'']
      },
      {
        enabled: true,
        hashingMethod: 'sha512',
        hashEnabled: {
          'script-src': true,
          'style-src': true
        },
        nonceEnabled: {
          'script-src': true,
          'style-src': true,
        },
      }

But if i run the same on windows pc nonces doesn't will be added to content property of CSP's meta tag

<!DOCTYPE html>
 <html>
  <head>
     <meta http-equiv="Content-Security-Policy" content="base-uri 'self'; object-src 'none'; script-src 'nonce-gn67IhFu2jJyrwY+PMSeUA==' 'strict-dynamic'; style-src 'self' 'nonce-y3gcK9oDtWf74QiBnf2rSA=='; frame-src 'none'; worker-src 'none'">
 <meta charset="UTF-8">
 <title>Title</title>
 <script defer="defer" src="static/js/main.ba2c44d7bc58ccf6207d.bundle.js" nonce="gn67IhFu2jJyrwY+PMSeUA=="> </script>
  <link href="static/css/main.6ec92936e5acaa7eae9f.bundle.css" rel="stylesheet" nonce="y3gcK9oDtWf74QiBnf2rSA==">  
 </head>
 <body>
  <div id="root"></div>
 </body>
</html>

Reproducible in:

slackhq/csp-html-webpack-plugin version: ^5.1.0

node version:I'm using electron with node v12, but i've installed the latest LTS version

OS version(s):10.0.19041

Steps to reproduce:

1.Use my configuration on both OS
2.
3.

Expected result:

What you expected to happen: the same that happen on Mac

Lodash 4.17.20

Lodash 4.17.20

Hi, can you please upgrade this to the latest version to fix vulnerabilities?

Example on how to use this with CRA + react-app-rewired?

Description

Hey folks, can you please make some example that will show how to make this thingy working with CRA + react-app-rewired? Because all my attempts failed with no result in resulting index.html

I tried rewired function like that with no avail tho. I tried a few other approaches, also no result.

function addCspHtmlWebpackPlugin(config, env) {
  config.plugins[0].options.cspPlugin = {
    enabled: true,
    policy: {
      'base-uri': "'self'",
      'script-src': ["'unsafe-inline'", "'self'"],
    },
    hashEnabled: {
      'script-src': true,
    },
    nonceEnabled: {
      'script-src': true,
    },
  }

  config.plugins.push(
    new CspHtmlWebpackPlugin(
      {
        'base-uri': "'self'",
        'script-src': ["'unsafe-inline'", "'self'"],
      },
      { ...config.plugins[0].options },
    ),
  )

  return config
}

I'm talking about this thing :)
https://github.com/timarney/react-app-rewired

Thanks!

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Yarn 2 support

Description

Does this plugin not support yarn 2? With 5.1.0:

ERROR in   TypeError: val.includes is not a function

  - plugin.js:297
    [csp-html-webpack-plugin-npm-5.1.0-40d465e733-0e41f2e490.zip]/[csp-html-web    pack-plugin]/plugin.js:297:17

  - Array.map

  - plugin.js:290 CspHtmlWebpackPlugin.buildPolicy
    [csp-html-webpack-plugin-npm-5.1.0-40d465e733-0e41f2e490.zip]/[csp-html-web    pack-plugin]/plugin.js:290:8

  - plugin.js:334 CspHtmlWebpackPlugin.processCsp
    [csp-html-webpack-plugin-npm-5.1.0-40d465e733-0e41f2e490.zip]/[csp-html-web    pack-plugin]/plugin.js:334:30


  - new Promise


  - index.js:348
    [html-webpack-plugin-npm-5.0.0-beta.1-fd77fa0afb-d71b4e4a7b.zip]/[html-webp    ack-plugin]/index.js:348:72



webpack 5.17.0 compiled with 2 errors in 4589 ms

I'll try cooking up a minimal repro later.

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

slackhq/csp-html-webpack-plugin version:

node version:

OS version(s):

Steps to reproduce:

Expected result:

What you expected to happen

Actual result:

What actually happened

Attachments:

Logs, screenshots, screencast, sample project, funny gif, etc.

XHTML mode is not honored

Description

Currently the plugin does not honor "XHTML mode": for example, if we have a configuration like this:

            new HtmlWebpackPlugin({
                filename: 'index.html',
                template: './src/index.html',
                xhtml: true,
            })

the plugin will still output html-style tags (e.g., <meta charset="utf-8"> instead of <meta charset="utf-8"/>).

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

slackhq/csp-html-webpack-plugin version: 4.0.0

node version: 12.17.0

OS version(s): any

Steps to reproduce:

See above - create a Webpack config with xhtml: true set for html-webpack-plugin

Expected result:

The generated HTML should have self-closing tags where appropriate, like

<meta charset="utf-8"/>

Actual result:

The generated markup does not honor xhtml: true:

<meta charset="utf-8">

Using this plugin with webpack, material-ui withStyles

Description

I am having an issue with this plugin and MaterialUI's withStyles functionality which allows me to write styles within JSX and generate a stylesheet dynamically. Generally I will receive the following error:

addStyles.js:397 Refused to load the stylesheet 'blob:https://host' because it violates the following Content Security Policy directive: "style-src 'unsafe-inline' 'self' 'unsafe-eval' 'sha256-8Ttgnzta3WC0XhMHqjlso6w8jFtMRzqTSufL6OFT/HQ=' 'nonce-hr9a9a5KipK/nNqlYwCf9w==' 'nonce-raSGmUULzSOykrZn2AzKOQ==' 'nonce-gm6b/nNJzNSSPll0/D8N4A==' 'nonce-0Ij+YWTEfMPWwdJ4aEg5Pw==' 'nonce-lylYG0q6NSXffVaHd+ydrg==' 'nonce-5ZbhjP2mnLu3e+iAvMFDlw==' 'nonce-2eJx+0YItmKXInI0rfaqNw==' 'nonce-1OyIfAm7sHSq2rZRWPWFCw==' 'nonce-4AdZFYimCELi/0L9XhjJ7A==' 'nonce-UCQAVe9izKqG5vo16urKXg==' 'nonce-ykGZtSKbUJYJaHJOeYNIeA==' 'nonce-tVmIhhp0G3aSy6E3dby1hg==' 'nonce-8VOErQfHOdp+kr9Sgv/+xg==' 'nonce-nhC9

I use CRA's ejected webpack. I have tried to implement various fixes to get your plugin to play nicely with Material UI withStyles but have been unsuccessful.

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • [* ] question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • [* ] I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • [ *] I've read and agree to the Code of Conduct.
  • [ *] I've searched for any related issues and avoided creating a duplicate issue.

Is anyone familiar with how to get this plugin to work nicely with Material UI and webpack?

deprecated @types/[email protected]: This is a stub types definition. anymatch provides its own type definitions

Description

remove package @types/anymatch

What type of issue is this? (place an x in one of the [ ])

  • [x ] bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • [ x] I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • [ x] I've read and agree to the Code of Conduct.
  • [ x] I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

npm WARN deprecated @types/[email protected]: This is a stub types definition. anymatch provides its own type definitions, so you do not need this installed.

Reproducible in:

slackhq/csp-html-webpack-plugin version:3.0.1

node version: v14.16.1

OS version(s): MacOS 11.3.1

Steps to reproduce:

  1. install @types/csp-html-webpack-plugin: 3.0.1

Expected result:

  1. clean install. no npm errors should appear

Actual result:

  1. npm outputs error
    "npm WARN deprecated @types/[email protected]: This is a stub types definition. anymatch provides its own type definitions, so you do not need this installed."

Wrong inline script hash when the file EOL is CRLF

Description

The hash is wrong when the index.html EOL is CRLF

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

slackhq/csp-html-webpack-plugin version: 5.1.0

node version: v16.15.1

OS version(s): Windows 10

Steps to reproduce:

  1. Change the index.html EOL to CRLF (the default EOL in Windows)
  2. Generate hash for inline script

Expected result:

The hash is generated correctly.

Actual result:

The hash is wrong for CRLF index.html

disableCspPlugin: true should not modify the template at all

Description

Describe your issue here.

What type of issue is this? (place an x in one of the [ ])

  • bug
  • enhancement (feature request)
  • question
  • documentation related
  • testing related
  • discussion

Requirements (place an x in each of the [ ])

  • [x ] I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • [x ] I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Bug Report

Filling out the following details about bugs will help us solve your issue sooner.

Reproducible in:

slackhq/csp-html-webpack-plugin version: 2.5.0

node version: 10

OS version(s): Windows 10 & Mac OXS

Steps to reproduce:

  1. set disableCspPlugin: true for files that are not index.html
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = new HtmlWebpackPlugin({
    template: './manifest.ejs',
    chunks: [],
    filename: 'manifest.json',
    inject: false,
    hash: false,
    minify: false,
    // csp plugin
    disableCspPlugin: true
});

// template ./manifest.ejs
<% const package = require('../../../package.json')%>
{
    "name": "<%=package.name%>",
}
  1. run webpack compilation

Expected result:

csp-html-webpack-plugin does NOT modify my template since it is disabled

What you expected to happen:

{
    "name": "repo-name",
}

Actual result:

<html><head></head><body>{
    "name": "repo-name",
}
</body></html>

What actually happened

even though the user specify disableCspPlugin: true, the plugin still mutates the template:

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.