Skip to content

Commit fb0f1d5

Browse files
committed
Add better support for preloaded scripts by using data-csp="script-src"
1 parent 00c0f1f commit fb0f1d5

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

plugin.jest.js

+27
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

+1-1
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ class CspHtmlWebpackPlugin {
327327
const scriptNonce = this.setNonce(
328328
$,
329329
'script-src',
330-
'script[src], link[rel="preload"][as="script"]'
330+
'script[src], [data-csp="script-src"]'
331331
);
332332
const styleNonce = this.setNonce($, 'style-src', 'link[rel="stylesheet"]');
333333

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)