Skip to content

Commit

Permalink
CSP: speed up getDefaultDirectives
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
EvanHahn committed Sep 28, 2024
1 parent a603b0b commit deb5569
Showing 1 changed file with 15 additions and 17 deletions.
32 changes: 15 additions & 17 deletions middlewares/content-security-policy/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,22 @@ interface ContentSecurityPolicy {

const dangerouslyDisableDefaultSrc = Symbol("dangerouslyDisableDefaultSrc");

const DEFAULT_DIRECTIVES: Record<
const SHOULD_BE_QUOTED: ReadonlySet<string> = 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<ContentSecurityPolicyDirectiveValue>
> = {
> => ({
"default-src": ["'self'"],
"base-uri": ["'self'"],
"font-src": ["'self'", "https:", "data:"],
Expand All @@ -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<string> = 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());
Expand Down

0 comments on commit deb5569

Please sign in to comment.