Skip to content

Commit 5ebf60f

Browse files
sunecosuripi0
authored andcommitted
feat: external script support for CSP (nuxt#2608)
1 parent 809d388 commit 5ebf60f

File tree

4 files changed

+13
-5
lines changed

4 files changed

+13
-5
lines changed

lib/common/options.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,9 @@ Options.defaults = {
305305
etag: {
306306
weak: false
307307
},
308-
csp: undefined
308+
csp: {
309+
allowedSouces: []
310+
}
309311
},
310312
watchers: {
311313
webpack: {

lib/core/middleware/nuxt.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,11 @@ module.exports = async function nuxtMiddleware(req, res, next) {
6767
res.setHeader('Link', pushAssets.join(','))
6868
}
6969

70-
if (this.options.render.csp) {
70+
if (this.options.render.csp.hashAlgorithm) {
71+
let allowedSources = cspScriptSrcHashes.concat(this.options.render.csp.allowedSources)
7172
res.setHeader(
7273
'Content-Security-Policy',
73-
`script-src 'self' ${(cspScriptSrcHashes || []).join(' ')}`
74+
`script-src 'self' ${(allowedSources || []).join(' ')}`
7475
)
7576
}
7677

lib/core/renderer.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,7 @@ module.exports = class Renderer {
361361
isJSON: true
362362
})};`
363363
let cspScriptSrcHashes = []
364-
if (this.options.render.csp) {
364+
if (this.options.render.csp.hashAlgorithm) {
365365
let hash = crypto.createHash(this.options.render.csp.hashAlgorithm)
366366
hash.update(serializedSession)
367367
cspScriptSrcHashes.push(

test/basic.ssr.test.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,10 @@ test.serial('Init Nuxt.js', async t => {
2424
stats: false
2525
},
2626
render: {
27-
csp: true
27+
csp: {
28+
hashAlgorithm: 'sha256',
29+
allowedSources: ['https://example.com', 'https://example.io']
30+
}
2831
}
2932
}
3033

@@ -256,6 +259,8 @@ test('Content-Security-Policy Header', async t => {
256259
})
257260
// Verify functionality
258261
t.regex(headers['content-security-policy'], /script-src 'self' 'sha256-.*'/)
262+
t.true(headers['content-security-policy'].includes('https://example.com'))
263+
t.true(headers['content-security-policy'].includes('https://example.io'))
259264
})
260265

261266
test('/_nuxt/server-bundle.json should return 404', async t => {

0 commit comments

Comments
 (0)