/** * 0929/13-04. What the declared Content-Security-Policy * (config/hosting/security-headers.json) may not allow. * scripts/verify-hosting-headers.ts compares a host's answer with it; this * reads what it allows. check:browser-security (FE-GATE-013) runs it, and * check:security:fixtures (FE-GATE-029) holds it to a rejected fixture. */ const UNSAFE_SOURCES = new Set(["'unsafe-inline'", "'unsafe-eval'", "*"]); /** Directives whose sources decide what script or plugin code may run or style may apply. */ const CODE_DIRECTIVES = new Set([ "default-src", "script-src", "script-src-elem", "script-src-attr", "style-src", "style-src-elem", "style-src-attr", "object-src", ]); /** A scheme-only source (`https:`) lets any host on it run script. */ const SCHEME_ONLY = /^[a-z][a-z0-9+.-]*:$/u; const SCRIPT_DIRECTIVES = new Set(["default-src", "script-src", "script-src-elem", "object-src"]); /** * The directives as a browser reads them (CSP3): names and keywords in any * case, and the first of a repeated directive, the later ones ignored. */ function directivesOf(policy: string): Map { const directives = new Map(); for (const part of policy.split(";")) { const [name, ...sources] = part.trim().split(/\s+/u); const key = name?.toLowerCase(); if (key && !directives.has(key)) { directives.set(key, sources.map((source) => source.toLowerCase())); } } return directives; } export function cspPolicyProblems(policy: string): string[] { const directives = directivesOf(policy); const problems: string[] = []; if (!directives.has("script-src") && !directives.has("default-src")) { problems.push("no script-src and no default-src"); } for (const [name, sources] of directives) { if (!CODE_DIRECTIVES.has(name)) continue; for (const source of sources) { if (UNSAFE_SOURCES.has(source)) problems.push(`${name} allows ${source}`); else if (SCRIPT_DIRECTIVES.has(name) && SCHEME_ONLY.test(source)) { problems.push(`${name} allows the whole scheme ${source}`); } } } return problems; } /** * The problems of the policy a security-headers document (the shape of * config/hosting/security-headers.json) declares, its header name in any case. */ export function declaredCspProblems(securityHeadersJson: string): string[] { const document = JSON.parse(securityHeadersJson) as { headers?: Record }; const policy = Object.entries(document.headers ?? {}).find( ([name]) => name.toLowerCase() === "content-security-policy", )?.[1]; return typeof policy === "string" ? cspPolicyProblems(policy) : ["no Content-Security-Policy header"]; }