Skip to content

Commit

Permalink
feat(ssr): add csp nonce to all elements
Browse files Browse the repository at this point in the history
add csp nonce to all elements that could potentiall be affected by CSP directives
  • Loading branch information
blake-newman committed Nov 28, 2022
1 parent 9dd006b commit 5449d9e
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions packages/server-renderer/src/template-renderer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,9 @@ export default class TemplateRenderer {
? cssFiles
.map(
({ file }) =>
`<link rel="stylesheet" href="${this.publicPath}${file}">`
`<link rel="stylesheet" href="${
this.publicPath
}${file}"${getNonceAttribute(context)}>`
)
.join('')
: '') +
Expand Down Expand Up @@ -193,7 +195,7 @@ export default class TemplateRenderer {
}
return `<link rel="preload" href="${this.publicPath}${file}"${
asType !== '' ? ` as="${asType}"` : ''
}${extra}>`
}${extra}${getNonceAttribute(context)}>`
})
.join('')
} else {
Expand All @@ -216,7 +218,9 @@ export default class TemplateRenderer {
if (alreadyRendered(file)) {
return ''
}
return `<link rel="prefetch" href="${this.publicPath}${file}">`
return `<link rel="prefetch" href="${
this.publicPath
}${file}"${getNonceAttribute(context)}>`
})
.join('')
} else {
Expand All @@ -234,9 +238,10 @@ export default class TemplateRenderer {
const autoRemove = __DEV__
? ''
: ';(function(){var s;(s=document.currentScript||document.scripts[document.scripts.length-1]).parentNode.removeChild(s);}());'
const nonceAttr = context.nonce ? ` nonce="${context.nonce}"` : ''
return context[contextKey]
? `<script${nonceAttr}>window.${windowKey}=${state}${autoRemove}</script>`
? `<script${getNonceAttribute(
context
)}>window.${windowKey}=${state}${autoRemove}</script>`
: ''
}

Expand All @@ -249,7 +254,9 @@ export default class TemplateRenderer {
const needed = [initial[0]].concat(async, initial.slice(1))
return needed
.map(({ file }) => {
return `<script src="${this.publicPath}${file}" defer></script>`
return `<script src="${
this.publicPath
}${file}" defer${getNonceAttribute(context)}></script>`
})
.join('')
} else {
Expand Down Expand Up @@ -304,3 +311,7 @@ function getPreloadType(ext: string): string {
return ''
}
}

function getNonceAttribute(context: Record<string, any>): string {
return context.nonce ? ` nonce="${context.nonce}"` : ''
}

0 comments on commit 5449d9e

Please sign in to comment.