Skip to content
This repository has been archived by the owner on Jan 11, 2023. It is now read-only.

Commit

Permalink
Add CSP nonce support for Webpack scripts (#1395)
Browse files Browse the repository at this point in the history
  • Loading branch information
fledgling-vish committed Aug 14, 2020
1 parent f49100d commit 949a187
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions runtime/src/server/middleware/get_page_handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,9 @@ export function get_page_handler(
const file = [].concat(build_info.assets.main).filter(file => file && /\.js$/.test(file))[0];
const main = `${req.baseUrl}/client/${file}`;

// users can set a CSP nonce using res.locals.nonce
const nonce_attr = (res.locals && res.locals.nonce) ? ` nonce="${res.locals.nonce}"` : '';

if (build_info.bundler === 'rollup') {
if (build_info.legacy_assets) {
const legacy_main = `${req.baseUrl}/client/legacy/${build_info.legacy_assets.main}`;
Expand All @@ -313,7 +316,7 @@ export function get_page_handler(
script += `var s=document.createElement("script");try{new Function("if(0)import('')")();s.src="${main}";s.type="module";s.crossOrigin="use-credentials";}catch(e){s.src="${req.baseUrl}/client/shimport@${build_info.shimport}.js";s.setAttribute("data-main","${main}")}document.head.appendChild(s)`;
}
} else {
script += `</script><script src="${main}" defer>`;
script += `</script><script${nonce_attr} src="${main}" defer>`;
}

let styles: string;
Expand Down Expand Up @@ -341,9 +344,6 @@ export function get_page_handler(
styles = (css && css.code ? `<style>${css.code}</style>` : '');
}

// users can set a CSP nonce using res.locals.nonce
const nonce_attr = (res.locals && res.locals.nonce) ? ` nonce="${res.locals.nonce}"` : '';

const body = template()
.replace('%sapper.base%', () => `<base href="${req.baseUrl}/">`)
.replace('%sapper.scripts%', () => `<script${nonce_attr}>${script}</script>`)
Expand Down

0 comments on commit 949a187

Please sign in to comment.