Skip to content

Commit 7026812

Browse files
committed
Add better support for preloaded scripts
You can generate nonce also for preloaded scripts by using data-csp attribute
1 parent c000a55 commit 7026812

File tree

3 files changed

+43
-1
lines changed

3 files changed

+43
-1
lines changed

plugin.jest.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,33 @@ describe('CspHtmlWebpackPlugin', () => {
144144
});
145145
});
146146

147+
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) => {
148+
const config = createWebpackConfig([
149+
new HtmlWebpackPlugin({
150+
filename: path.join(WEBPACK_OUTPUT_DIR, 'index.html'),
151+
template: path.join(
152+
__dirname,
153+
'test-utils',
154+
'fixtures',
155+
'with-preload-script-and-style.html'
156+
),
157+
}),
158+
new CspHtmlWebpackPlugin(),
159+
]);
160+
161+
webpackCompile(config, (csps) => {
162+
const expected =
163+
"base-uri 'self';" +
164+
" object-src 'none';" +
165+
" script-src 'unsafe-inline' 'self' 'unsafe-eval' 'nonce-mockedbase64string-1' 'nonce-mockedbase64string-2';" +
166+
" style-src 'unsafe-inline' 'self' 'unsafe-eval'";
167+
168+
expect(csps['index.html']).toEqual(expected);
169+
170+
done();
171+
});
172+
});
173+
147174
it('inserts a custom policy if one is defined', (done) => {
148175
const config = createWebpackConfig([
149176
new HtmlWebpackPlugin({

plugin.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,11 @@ class CspHtmlWebpackPlugin {
324324
}
325325

326326
// get all nonces for script and style tags
327-
const scriptNonce = this.setNonce($, 'script-src', 'script[src]');
327+
const scriptNonce = this.setNonce(
328+
$,
329+
'script-src',
330+
'script[src], [data-csp="script-src"]'
331+
);
328332
const styleNonce = this.setNonce($, 'style-src', 'link[rel="stylesheet"]');
329333

330334
// get all shas for script and style tags
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<!doctype html>
2+
<html lang="en-US">
3+
<head>
4+
<meta name="author" content="Slack">
5+
<title>Slack CSP HTML Webpack Plugin Tests</title>
6+
<link rel="preload" href="https://example.com/preload-example.js" as="script" data-csp="script-src">
7+
</head>
8+
<body>
9+
Body
10+
</body>
11+
</html>

0 commit comments

Comments
 (0)