Skip to content

Commit

Permalink
feat: add csp hash for color script (#94)
Browse files Browse the repository at this point in the history
* feat: add csp hash for color script

* add test
  • Loading branch information
clarkdo authored Aug 2, 2021
1 parent 2ca9edc commit e2f1ffc
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
8 changes: 8 additions & 0 deletions lib/module.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { resolve } from 'path'
import { promises as fsp } from 'fs'
import crypto from 'crypto'
import defu from 'defu'
import template from 'lodash.template'
import { addTemplates } from './utils'
Expand Down Expand Up @@ -42,6 +43,13 @@ export default async function (moduleOptions) {
head[serializeProp][options.hid] = ['innerHTML']
})

this.nuxt.hook('vue-renderer:ssr:csp', (cspScriptSrcHashes) => {
const { csp } = this.options.render
const hash = crypto.createHash(csp.hashAlgorithm)
hash.update(options.script)
cspScriptSrcHashes.push(`'${csp.hashAlgorithm}-${hash.digest('base64')}'`)
})

// Add all templates
const templatesDir = resolve(__dirname, 'templates')
await addTemplates.call(this, templatesDir, 'color-mode', options)
Expand Down
24 changes: 23 additions & 1 deletion test/ssr.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ describe('ssr: true, target: server, prod mode', () => {
})

test('render', async () => {
const { body } = await get('/')
const { body, headers } = await get('/')
expect(body).toContain('nuxt-color-mode-script')
expect(headers['content-security-policy']).toBeUndefined()
})
})

Expand All @@ -61,3 +62,24 @@ describe('ssr: true, target: static, generated files', () => {
}
})
})

describe('ssr: true, csp hash on script', () => {
const rootDir = join(__dirname, '..', 'example')

setupTest({
server: true,
build: true,
rootDir,
config: {
ssr: true,
render: {
csp: true
}
}
})

test('csp hash on script', async () => {
const { headers } = await get('/')
expect(headers['content-security-policy']).toContain('sha256-')
})
})

0 comments on commit e2f1ffc

Please sign in to comment.