Skip to content

Commit

Permalink
CSP: clean up getDefaultDirectives
Browse files Browse the repository at this point in the history
1. `getDefaultDirectives` is now faster, avoiding `structuredClone`.

2. We don't need to call `getDefaultDirectives`.
  • Loading branch information
EvanHahn committed May 25, 2024
1 parent d9319b8 commit fb4500a
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions middlewares/content-security-policy/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,7 @@ interface ContentSecurityPolicy {

const dangerouslyDisableDefaultSrc = Symbol("dangerouslyDisableDefaultSrc");

const DEFAULT_DIRECTIVES: Record<
string,
Iterable<ContentSecurityPolicyDirectiveValue>
> = {
const DEFAULT_DIRECTIVES: Record<string, string[]> = {
"default-src": ["'self'"],
"base-uri": ["'self'"],
"font-src": ["'self'", "https:", "data:"],
Expand All @@ -68,7 +65,19 @@ const SHOULD_BE_QUOTED: ReadonlySet<string> = new Set([
"wasm-unsafe-eval",
]);

const getDefaultDirectives = () => structuredClone(DEFAULT_DIRECTIVES);
const getDefaultDirectives = (): Record<
string,
Iterable<ContentSecurityPolicyDirectiveValue>
> => {
const result: Record<
string,
Iterable<ContentSecurityPolicyDirectiveValue>
> = {};
for (const [key, value] of Object.entries(DEFAULT_DIRECTIVES)) {
result[key] = value.concat();
}
return result;
};

const dashify = (str: string): string =>
str.replace(/[A-Z]/g, (capitalLetter) => "-" + capitalLetter.toLowerCase());
Expand All @@ -93,9 +102,7 @@ const invalidDirectiveValueError = (directiveName: string): Error =>
function normalizeDirectives(
options: Readonly<ContentSecurityPolicyOptions>,
): NormalizedDirectives {
const defaultDirectives = getDefaultDirectives();

const { useDefaults = true, directives: rawDirectives = defaultDirectives } =
const { useDefaults = true, directives: rawDirectives = DEFAULT_DIRECTIVES } =
options;

const result: NormalizedDirectives = new Map();
Expand Down Expand Up @@ -176,7 +183,7 @@ function normalizeDirectives(
}

if (useDefaults) {
Object.entries(defaultDirectives).forEach(
Object.entries(DEFAULT_DIRECTIVES).forEach(
([defaultDirectiveName, defaultDirectiveValue]) => {
if (
!result.has(defaultDirectiveName) &&
Expand Down

0 comments on commit fb4500a

Please sign in to comment.