Skip to content

Commit

Permalink
fix: add nonce to link preload tags (#59)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason Barry authored Nov 1, 2023
1 parent 7808378 commit c097ee0
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 7 deletions.
13 changes: 7 additions & 6 deletions site/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@
<html>
<head>
<title>Using CSP Nonces on Script Tags</title>
<style>
body {
font-family: sans-serif;
}
</style>
<link rel="stylesheet" href="/main.css" />
<link
rel="preload"
as="script"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"
/>
</head>
<body>
<h1>Using CSP Nonces on Script Tags</h1>
Expand Down Expand Up @@ -40,7 +41,7 @@ <h1>Using CSP Nonces on Script Tags</h1>
"ipt>" +
"document.write('<div>❌ Script tag from <code>document.write</code> has executed!</div>');" +
"</scr" +
"ipt>"
"ipt>",
);
</script>
<script>
Expand Down
3 changes: 3 additions & 0 deletions site/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
font-family: sans-serif;
}
3 changes: 2 additions & 1 deletion src/__csp-nonce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,9 @@ const handler = async (request: Request, context: Context) => {
response.headers.set(header, value);
}

const querySelectors = ["script", 'link[rel="preload"][as="script"]'];
return new HTMLRewriter()
.on("script", {
.on(querySelectors.join(","), {
element(element: HTMLElement) {
element.setAttribute("nonce", nonce);
},
Expand Down

0 comments on commit c097ee0

Please sign in to comment.