Skip to content

Commit 53786dc

Browse files
authored
feat: add CSP with nonce support (#2478)
1 parent c48315d commit 53786dc

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

src/server/HeadHtmlSupport.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ export default class HeadHtmlSupport {
3131
const update = (obj, keys) => {
3232
keys.sort();
3333
for (const k of keys) {
34+
if (k === 'nonce') {
35+
// ignore nonce attribute, because it can change on every request
36+
// eslint-disable-next-line no-continue
37+
continue;
38+
}
39+
3440
let v = obj[k];
3541
if (v !== undefined) {
3642
if (Array.isArray(v)) {

src/server/utils.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,19 +89,21 @@ const utils = {
8989
if (match) {
9090
const { index } = match;
9191
// eslint-disable-next-line no-param-reassign
92+
const nonceMatch = body.match(/nonce="([a-zA-Z0-9+/=]+)"/);
93+
const nonce = nonceMatch ? ` nonce="${nonceMatch[1]}"` : '';
9294
let newbody = body.substring(0, index);
9395
if (process.env.CODESPACES === 'true') {
94-
newbody += `<script>
96+
newbody += `<script${nonce}>
9597
window.LiveReloadOptions = {
9698
host: new URL(location.href).hostname.replace(/-[0-9]+\\.preview\\.app\\.github\\.dev/, '-35729.preview.app.github.dev'),
9799
port: 443,
98100
https: true,
99101
};
100102
</script>`;
101103
} else {
102-
newbody += `<script>window.LiveReloadOptions={port:${server.port},host:location.hostname,https:${server.scheme === 'https'}};</script>`;
104+
newbody += `<script${nonce}>window.LiveReloadOptions={port:${server.port},host:location.hostname,https:${server.scheme === 'https'}};</script>`;
103105
}
104-
newbody += '<script src="/__internal__/livereload.js"></script>';
106+
newbody += `<script${nonce} src="/__internal__/livereload.js"></script>`;
105107
newbody += body.substring(index);
106108
return newbody;
107109
}

0 commit comments

Comments
 (0)