Skip to content

Commit 5449d9e

Browse files
committedNov 28, 2022
feat(ssr): add csp nonce to all elements
add csp nonce to all elements that could potentiall be affected by CSP directives
1 parent 9dd006b commit 5449d9e

File tree

1 file changed

+17
-6
lines changed
  • packages/server-renderer/src/template-renderer

1 file changed

+17
-6
lines changed
 

‎packages/server-renderer/src/template-renderer/index.ts

+17-6
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,9 @@ export default class TemplateRenderer {
150150
? cssFiles
151151
.map(
152152
({ file }) =>
153-
`<link rel="stylesheet" href="${this.publicPath}${file}">`
153+
`<link rel="stylesheet" href="${
154+
this.publicPath
155+
}${file}"${getNonceAttribute(context)}>`
154156
)
155157
.join('')
156158
: '') +
@@ -193,7 +195,7 @@ export default class TemplateRenderer {
193195
}
194196
return `<link rel="preload" href="${this.publicPath}${file}"${
195197
asType !== '' ? ` as="${asType}"` : ''
196-
}${extra}>`
198+
}${extra}${getNonceAttribute(context)}>`
197199
})
198200
.join('')
199201
} else {
@@ -216,7 +218,9 @@ export default class TemplateRenderer {
216218
if (alreadyRendered(file)) {
217219
return ''
218220
}
219-
return `<link rel="prefetch" href="${this.publicPath}${file}">`
221+
return `<link rel="prefetch" href="${
222+
this.publicPath
223+
}${file}"${getNonceAttribute(context)}>`
220224
})
221225
.join('')
222226
} else {
@@ -234,9 +238,10 @@ export default class TemplateRenderer {
234238
const autoRemove = __DEV__
235239
? ''
236240
: ';(function(){var s;(s=document.currentScript||document.scripts[document.scripts.length-1]).parentNode.removeChild(s);}());'
237-
const nonceAttr = context.nonce ? ` nonce="${context.nonce}"` : ''
238241
return context[contextKey]
239-
? `<script${nonceAttr}>window.${windowKey}=${state}${autoRemove}</script>`
242+
? `<script${getNonceAttribute(
243+
context
244+
)}>window.${windowKey}=${state}${autoRemove}</script>`
240245
: ''
241246
}
242247

@@ -249,7 +254,9 @@ export default class TemplateRenderer {
249254
const needed = [initial[0]].concat(async, initial.slice(1))
250255
return needed
251256
.map(({ file }) => {
252-
return `<script src="${this.publicPath}${file}" defer></script>`
257+
return `<script src="${
258+
this.publicPath
259+
}${file}" defer${getNonceAttribute(context)}></script>`
253260
})
254261
.join('')
255262
} else {
@@ -304,3 +311,7 @@ function getPreloadType(ext: string): string {
304311
return ''
305312
}
306313
}
314+
315+
function getNonceAttribute(context: Record<string, any>): string {
316+
return context.nonce ? ` nonce="${context.nonce}"` : ''
317+
}

0 commit comments

Comments
 (0)
Failed to load comments.