Skip to content

Commit

Permalink
Allow nonceEnabled and hashEnabled to take single boolean values
Browse files Browse the repository at this point in the history
Providing a single boolean value to either of these options will now apply
the value to each provided policy directive.

Closes #98
  • Loading branch information
StephanBijzitter committed Sep 15, 2021
1 parent c000a55 commit 871d133
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,17 @@ const defaultProcessFn = (builtPolicy, htmlPluginData, $) => {
: $.html();
};

const convert = (keys, value) =>
typeof value !== 'boolean'
? value
: keys.reduce(
(previousValue, currentValue) => ({
...previousValue,
[currentValue]: value,
}),
{}
);

const defaultPolicy = {
'base-uri': "'self'",
'object-src': "'none'",
Expand All @@ -56,14 +67,8 @@ const defaultPolicy = {
const defaultAdditionalOpts = {
enabled: true,
hashingMethod: 'sha256',
hashEnabled: {
'script-src': true,
'style-src': true,
},
nonceEnabled: {
'script-src': true,
'style-src': true,
},
hashEnabled: true,
nonceEnabled: true,
processFn: defaultProcessFn,
};

Expand Down Expand Up @@ -112,14 +117,22 @@ class CspHtmlWebpackPlugin {
this.validatePolicy(compilation);

// 2. Lets set which hashes and nonces are enabled for this HtmlWebpackPlugin instance
const policyKeys = Object.keys(this.policy);

this.hashEnabled = Object.freeze({
...this.opts.hashEnabled,
...get(htmlPluginData, 'plugin.options.cspPlugin.hashEnabled', {}),
...convert(policyKeys, this.opts.hashEnabled),
...convert(
policyKeys,
get(htmlPluginData, 'plugin.options.cspPlugin.hashEnabled', {})
),
});

this.nonceEnabled = Object.freeze({
...this.opts.nonceEnabled,
...get(htmlPluginData, 'plugin.options.cspPlugin.nonceEnabled', {}),
...convert(policyKeys, this.opts.nonceEnabled),
...convert(
policyKeys,
get(htmlPluginData, 'plugin.options.cspPlugin.nonceEnabled', {})
),
});

// 3. Get the processFn for this HtmlWebpackPlugin instance.
Expand Down

0 comments on commit 871d133

Please sign in to comment.