-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(perf): use HTMLRewriter instead of regex for html transformation (#…
…48)
- Loading branch information
Jason Barry
authored
Aug 25, 2023
1 parent
f053d5a
commit c48daad
Showing
1 changed file
with
10 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,6 +3,8 @@ | |
import type { Config, Context } from "netlify:edge"; | ||
// @ts-expect-error | ||
import { randomBytes } from "node:crypto"; | ||
// @ts-expect-error | ||
import { HTMLRewriter } from "https://ghuc.cc/worker-tools/[email protected]/index.ts"; | ||
|
||
import inputs from "./__csp-nonce-inputs.json" assert { type: "json" }; | ||
|
||
|
@@ -16,7 +18,7 @@ type Params = { | |
const params = inputs as Params; | ||
|
||
const handler = async (request: Request, context: Context) => { | ||
const response = await context.next(); | ||
const response = await context.next(request); | ||
|
||
let header = params.reportOnly | ||
? "content-security-policy-report-only" | ||
|
@@ -109,13 +111,13 @@ const handler = async (request: Request, context: Context) => { | |
response.headers.set(header, value); | ||
} | ||
|
||
// time to do some regex magic | ||
const page = await response.text(); | ||
const rewrittenPage = page.replace( | ||
/<script([^>]*)>/gi, | ||
`<script$1 nonce="${nonce}">` | ||
); | ||
return new Response(rewrittenPage, response); | ||
return new HTMLRewriter() | ||
.on("script", { | ||
element(element) { | ||
element.setAttribute("nonce", nonce); | ||
}, | ||
}) | ||
.transform(response); | ||
}; | ||
|
||
// Top 50 most common extensions (minus .html and .htm) according to Humio | ||
|