Skip to content

Commit 6562cd7

Browse files
committed
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.
1 parent a8befb3 commit 6562cd7

File tree

1 file changed

+15
-17
lines changed
  • middlewares/content-security-policy

1 file changed

+15
-17
lines changed

middlewares/content-security-policy/index.ts

+15-17
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,22 @@ interface ContentSecurityPolicy {
3939

4040
const dangerouslyDisableDefaultSrc = Symbol("dangerouslyDisableDefaultSrc");
4141

42-
const DEFAULT_DIRECTIVES: Record<
42+
const SHOULD_BE_QUOTED: ReadonlySet<string> = new Set([
43+
"none",
44+
"self",
45+
"strict-dynamic",
46+
"report-sample",
47+
"inline-speculation-rules",
48+
"unsafe-inline",
49+
"unsafe-eval",
50+
"unsafe-hashes",
51+
"wasm-unsafe-eval",
52+
]);
53+
54+
const getDefaultDirectives = (): Record<
4355
string,
4456
Iterable<ContentSecurityPolicyDirectiveValue>
45-
> = {
57+
> => ({
4658
"default-src": ["'self'"],
4759
"base-uri": ["'self'"],
4860
"font-src": ["'self'", "https:", "data:"],
@@ -54,21 +66,7 @@ const DEFAULT_DIRECTIVES: Record<
5466
"script-src-attr": ["'none'"],
5567
"style-src": ["'self'", "https:", "'unsafe-inline'"],
5668
"upgrade-insecure-requests": [],
57-
};
58-
59-
const SHOULD_BE_QUOTED: ReadonlySet<string> = new Set([
60-
"none",
61-
"self",
62-
"strict-dynamic",
63-
"report-sample",
64-
"inline-speculation-rules",
65-
"unsafe-inline",
66-
"unsafe-eval",
67-
"unsafe-hashes",
68-
"wasm-unsafe-eval",
69-
]);
70-
71-
const getDefaultDirectives = () => structuredClone(DEFAULT_DIRECTIVES);
69+
});
7270

7371
const dashify = (str: string): string =>
7472
str.replace(/[A-Z]/g, (capitalLetter) => "-" + capitalLetter.toLowerCase());

0 commit comments

Comments
 (0)