add csp.policies

This commit is contained in:
dojineko 2018-02-01 21:20:28 +09:00
parent 1582df149d
commit 4fb644fdb3
2 changed files with 26 additions and 6 deletions

View File

@ -315,7 +315,8 @@ Options.defaults = {
csp: { csp: {
enabled: false, enabled: false,
hashAlgorithm: 'sha256', hashAlgorithm: 'sha256',
allowedSources: [] allowedSources: undefined,
policies: undefined
} }
}, },
watchers: { watchers: {

View File

@ -68,12 +68,31 @@ module.exports = async function nuxtMiddleware(req, res, next) {
} }
if (this.options.render.csp && this.options.render.csp.enabled) { if (this.options.render.csp && this.options.render.csp.enabled) {
const allowedSources = cspScriptSrcHashes.concat(this.options.render.csp.allowedSources) const allowedSources = this.options.render.csp.allowedSources
const policies = {...{}, ...this.options.render.csp.policies}
let cspStr = `script-src 'self' ${(cspScriptSrcHashes).join(' ')}`
if (Array.isArray(allowedSources)) {
// For compatible section
cspStr = `script-src 'self' ${cspScriptSrcHashes.concat(allowedSources).join(' ')}`
} else if (typeof policies === 'object' && policies !== null && !Array.isArray(policies)) {
// Set default policy if necessary
if (!policies['script-src'] || !Array.isArray(policies['script-src'])) {
policies['script-src'] = [`'self'`].concat(cspScriptSrcHashes)
} else {
policies['script-src'] = cspScriptSrcHashes.concat(policies['script-src'])
if (!policies['script-src'].includes(`'self'`)) {
policies['script-src'] = [`'self'`].concat(policies['script-src'])
}
}
res.setHeader( // Make content-security-policy string
'Content-Security-Policy', let cspArr = []
`script-src 'self' ${(allowedSources).join(' ')}` Object.keys(policies).forEach((k) => {
) cspArr.push(`${k} ${policies[k].join(' ')}`)
})
cspStr = cspArr.join('; ')
}
res.setHeader('Content-Security-Policy', cspStr)
} }
// Send response // Send response