From 6562cd7074e1b04c7abc6fcab351e4458f04dde2 Mon Sep 17 00:00:00 2001 From: Evan Hahn Date: Sat, 28 Sep 2024 22:24:10 +0000 Subject: [PATCH] CSP: speed up `getDefaultDirectives` I wrote a simple benchmarking script: import * as helmet from "./index.ts"; console.time("getting"); for (let i = 0; i < 1_000_000; i++) { helmet.contentSecurityPolicy.getDefaultDirectives(); } console.timeEnd("getting"); On my machine, this took about 4.5 seconds before the change. Now, it averages about 32 milliseconds. --- middlewares/content-security-policy/index.ts | 32 +++++++++----------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/middlewares/content-security-policy/index.ts b/middlewares/content-security-policy/index.ts index 38cc436..ee4505b 100644 --- a/middlewares/content-security-policy/index.ts +++ b/middlewares/content-security-policy/index.ts @@ -39,10 +39,22 @@ interface ContentSecurityPolicy { const dangerouslyDisableDefaultSrc = Symbol("dangerouslyDisableDefaultSrc"); -const DEFAULT_DIRECTIVES: Record< +const SHOULD_BE_QUOTED: ReadonlySet = new Set([ + "none", + "self", + "strict-dynamic", + "report-sample", + "inline-speculation-rules", + "unsafe-inline", + "unsafe-eval", + "unsafe-hashes", + "wasm-unsafe-eval", +]); + +const getDefaultDirectives = (): Record< string, Iterable -> = { +> => ({ "default-src": ["'self'"], "base-uri": ["'self'"], "font-src": ["'self'", "https:", "data:"], @@ -54,21 +66,7 @@ const DEFAULT_DIRECTIVES: Record< "script-src-attr": ["'none'"], "style-src": ["'self'", "https:", "'unsafe-inline'"], "upgrade-insecure-requests": [], -}; - -const SHOULD_BE_QUOTED: ReadonlySet = new Set([ - "none", - "self", - "strict-dynamic", - "report-sample", - "inline-speculation-rules", - "unsafe-inline", - "unsafe-eval", - "unsafe-hashes", - "wasm-unsafe-eval", -]); - -const getDefaultDirectives = () => structuredClone(DEFAULT_DIRECTIVES); +}); const dashify = (str: string): string => str.replace(/[A-Z]/g, (capitalLetter) => "-" + capitalLetter.toLowerCase());