Skip to content

Commit

Permalink
feat: add nonce for CSP
Browse files Browse the repository at this point in the history
  • Loading branch information
imsunhao committed Feb 13, 2019
1 parent cd48869 commit 99fd56b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
6 changes: 6 additions & 0 deletions src/utils/random.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import base64url from 'base64url'
import { randomBytes } from 'crypto'

export function randomStringAsBase64Url(size: number) {
return base64url(randomBytes(size))
}
15 changes: 12 additions & 3 deletions src/utils/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import path from 'path'
import { getConfig } from 'src/utils'
import consola from 'consola'
import serialize from 'serialize-javascript'
import { randomStringAsBase64Url } from './random'

function isStaticResourceUrl(url: string) {
const ext = path.extname(url)
Expand All @@ -32,7 +33,11 @@ function getWindowEnv(renderEnv: string[]) {
return serialize(env, { isJSON: true })
}

function getContextHead(req: BuildService.Request, injectContext: any) {
function getContextHead(
req: BuildService.Request,
injectContext: any,
nonce: string
) {
if (!req.renderEnv) {
consola.fatal('req.renderEnv is undefined')
return ''
Expand All @@ -47,7 +52,8 @@ function getContextHead(req: BuildService.Request, injectContext: any) {
env.NODE_ENV === 'production'
? ';(function(){var s;(s=document.currentScript||document.scripts[document.scripts.length-1]).parentNode.removeChild(s);}());'
: ''
return `<script>window.__INJECT_ENV__ = ${getWindowEnv(
const nonceStr = nonce ? `nonce="${nonce}"` : ''
return `<script ${nonceStr}>window.__INJECT_ENV__ = ${getWindowEnv(
req.renderEnv
)};window.__INJECT_CONTEXT__ = ${serialize(injectContext, {
isJSON: true
Expand Down Expand Up @@ -111,18 +117,21 @@ export function getRender(
}
}

const nonce = randomStringAsBase64Url(12)

const context = {
...opts.context,
pageInfo: {
title: ' ', // default title @see util/mixins/index
keywords: '',
description: ''
},
nonce,
headers: req.headers,
url: req.url,
cookies: req.cookies,
injectContext: req.injectContext || {},
head: getContextHead(req, opts.context)
head: getContextHead(req, opts.context, nonce)
}

renderer.renderToString(context, (err: any, html: string) => {
Expand Down

0 comments on commit 99fd56b

Please sign in to comment.