Skip to content

Commit 42a2109

Browse files
author
Jason Barry
authored
fix: remove style-src directive checks (#15)
1 parent 5176879 commit 42a2109

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

src/__csp-nonce.ts

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,10 @@ const handler = async (request: Request, context: Context) => {
2525

2626
// html only
2727
if (
28-
!request.headers.get("accept")?.startsWith("text/html") ||
29-
!response.headers.get("content-type").startsWith("text/html")
28+
!(
29+
request.headers.get("accept")?.startsWith("text/html") &&
30+
response.headers.get("content-type").startsWith("text/html")
31+
)
3032
) {
3133
return response;
3234
}
@@ -38,7 +40,6 @@ const handler = async (request: Request, context: Context) => {
3840
// https://content-security-policy.com/strict-dynamic/
3941
const rules = `'nonce-${nonce}' 'strict-dynamic' 'unsafe-inline' 'self' https: http:`;
4042
const scriptSrc = `script-src ${rules}`;
41-
const styleSrc = `style-src ${rules}`;
4243
const reportUri = `report-uri /.netlify/functions/__csp-violations`;
4344

4445
const csp = response.headers.get(header);
@@ -51,36 +52,35 @@ const handler = async (request: Request, context: Context) => {
5152
if (d.startsWith("script-src")) {
5253
return d.replace("script-src", scriptSrc);
5354
}
54-
if (d.startsWith("style-src")) {
55-
return d.replace("style-src", styleSrc);
56-
}
55+
// intentionally omit report-uri: theirs should take precedence
5756
return d;
5857
})
5958
.filter(Boolean);
6059
// push our rules if the directives don't exist yet
6160
if (!directives.find((d) => d.startsWith("script-src"))) {
6261
directives.push(scriptSrc);
6362
}
64-
if (!directives.find((d) => d.startsWith("style-src"))) {
65-
directives.push(styleSrc);
63+
if (!directives.find((d) => d.startsWith("report-uri"))) {
64+
directives.push(reportUri);
6665
}
6766
const value = directives.join("; ");
6867
response.headers.set(header, value);
6968
} else {
7069
// make a new ruleset of directives if no CSP present
71-
const value = [scriptSrc, styleSrc, reportUri].join("; ");
70+
const value = [scriptSrc, reportUri].join("; ");
7271
response.headers.set(header, value);
7372
}
7473

7574
// time to do some regex magic
7675
const page = await response.text();
7776
const rewrittenPage = page.replace(
78-
/<(script|style)([^>]*)>/gi,
79-
`<$1$2 nonce="${nonce}">`
77+
/<script([^>]*)>/gi,
78+
`<$1 nonce="${nonce}">`
8079
);
8180
return new Response(rewrittenPage, response);
8281
};
8382

83+
// Top 50 most common extensions (minus .html and .htm) according to Humio
8484
const excludedExtensions = [
8585
"aspx",
8686
"avif",

0 commit comments

Comments
 (0)