Skip to content

Commit

Permalink
fix(perf): use HTMLRewriter instead of regex for html transformation (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason Barry authored Aug 25, 2023
1 parent f053d5a commit c48daad
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions src/__csp-nonce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" };

Expand All @@ -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"
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit c48daad

Please sign in to comment.