Skip to content

Commit

Permalink
Add better support for preloaded scripts
Browse files Browse the repository at this point in the history
You can generate nonce also for preloaded scripts by using data-csp
attribute
  • Loading branch information
jukben committed Sep 17, 2021
1 parent c000a55 commit 7026812
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
27 changes: 27 additions & 0 deletions plugin.jest.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,33 @@ describe('CspHtmlWebpackPlugin', () => {
});
});

it('inserts the default policy, including sha-256 hashes of other inline scripts and styles found, and nonce hashes of external scripts found using data-csp="script-src" directive', (done) => {
const config = createWebpackConfig([
new HtmlWebpackPlugin({
filename: path.join(WEBPACK_OUTPUT_DIR, 'index.html'),
template: path.join(
__dirname,
'test-utils',
'fixtures',
'with-preload-script-and-style.html'
),
}),
new CspHtmlWebpackPlugin(),
]);

webpackCompile(config, (csps) => {
const expected =
"base-uri 'self';" +
" object-src 'none';" +
" script-src 'unsafe-inline' 'self' 'unsafe-eval' 'nonce-mockedbase64string-1' 'nonce-mockedbase64string-2';" +
" style-src 'unsafe-inline' 'self' 'unsafe-eval'";

expect(csps['index.html']).toEqual(expected);

done();
});
});

it('inserts a custom policy if one is defined', (done) => {
const config = createWebpackConfig([
new HtmlWebpackPlugin({
Expand Down
6 changes: 5 additions & 1 deletion plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,11 @@ class CspHtmlWebpackPlugin {
}

// get all nonces for script and style tags
const scriptNonce = this.setNonce($, 'script-src', 'script[src]');
const scriptNonce = this.setNonce(
$,
'script-src',
'script[src], [data-csp="script-src"]'
);
const styleNonce = this.setNonce($, 'style-src', 'link[rel="stylesheet"]');

// get all shas for script and style tags
Expand Down
11 changes: 11 additions & 0 deletions test-utils/fixtures/with-preload-script-and-style.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en-US">
<head>
<meta name="author" content="Slack">
<title>Slack CSP HTML Webpack Plugin Tests</title>
<link rel="preload" href="https://example.com/preload-example.js" as="script" data-csp="script-src">
</head>
<body>
Body
</body>
</html>

0 comments on commit 7026812

Please sign in to comment.