Skip to content

CSP Builder — JavaScript source

Build a Content-Security-Policy header interactively. Toggle directives, add sources, see the assembled header in real time — with a security score that flags unsafe sources.

This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

/**
 * csp-builder — Content-Security-Policy assembly, parsing, linting and scoring.
 *
 * Language: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
 * CosmoDev polyglot showcase port of the `csp-builder` tool, ported from
 * src/lib/csp-builder.ts (the canonical TypeScript implementation).
 *
 * Why this file exists: every decision in CSP handling — build order, lenient
 * parsing, risk linting, scoring — is pure deterministic string logic, so the
 * exact same code runs in a browser tab and on a server. The UI catalog is
 * trimmed to [name, kind] pairs; descriptions, risk labels and default
 * sources are display metadata the core API never needs.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

/** The directive catalog, in canonical build/display order: [name, kind]. */
const CATALOG = [
  ['default-src', 'sources'], ['script-src', 'sources'], ['style-src', 'sources'],
  ['img-src', 'sources'], ['connect-src', 'sources'], ['font-src', 'sources'],
  ['frame-src', 'sources'], ['media-src', 'sources'], ['object-src', 'sources'],
  ['base-uri', 'sources'], ['form-action', 'sources'], ['frame-ancestors', 'sources'],
  ['report-uri', 'url'], ['upgrade-insecure-requests', 'flag'],
  ['block-all-mixed-content', 'flag'],
];

/** Flags emit as a bare name; the known names order the build output. */
const FLAG_DIRECTIVES = new Set(CATALOG.filter(([, k]) => k === 'flag').map(([n]) => n));
const KNOWN_DIRECTIVES = new Set(CATALOG.map(([n]) => n));

/**
 * Assemble a policy map into the `Content-Security-Policy` header value.
 * Known directives emit in catalog order, unknown ones after them in
 * insertion order (JS objects preserve it, exactly what the TS Record relies
 * on). Flags emit as a bare name; source/url directives with an empty list
 * are omitted (a valueless directive is invalid CSP). Empty map -> ''.
 */
export function buildCSP(directives) {
  const parts = [];
  const emit = (name) => {
    const sources = directives[name];
    if (sources === undefined) return;
    if (FLAG_DIRECTIVES.has(name)) parts.push(name);
    else if (sources.length > 0) parts.push(`${name} ${sources.join(' ')}`);
  };
  for (const [name] of CATALOG) emit(name);
  for (const name of Object.keys(directives)) {
    if (!KNOWN_DIRECTIVES.has(name)) emit(name);
  }
  return parts.join('; ');
}

/**
 * Parse a CSP header value back into a policy map. Lenient: splits on
 * semicolons and whitespace, lowercases directive names, ignores empty
 * tokens, and strips an optional leading `Content-Security-Policy:` label so
 * a pasted full header line works. Duplicate directives keep only the first
 * occurrence (matching how browsers honor them). Never throws; garbage in, {} out.
 */
export function parseCSP(header) {
  let text = header.trim();
  if (/^content-security-policy\s*:/i.test(text)) text = text.slice(text.indexOf(':') + 1);
  const out = {};
  for (const token of text.split(';')) {
    const words = token.trim().split(/\s+/).filter(Boolean);
    if (words.length === 0) continue;
    const name = words[0].toLowerCase();
    if (out[name] === undefined) out[name] = words.slice(1);
  }
  return out;
}

/** Sources treated as security-weakening, compared case-insensitively. */
const RISKY_SOURCES = new Set(["'unsafe-inline'", "'unsafe-eval'", 'data:', 'http:', '*']);

/**
 * True when a source weakens the policy: 'unsafe-inline', 'unsafe-eval',
 * 'data:', 'http:', the bare wildcard '*', or any insecure http:// URL.
 */
export function isRiskySource(source) {
  const s = source.trim().toLowerCase();
  return RISKY_SOURCES.has(s) || s.startsWith('http://');
}

/** Short human explanation for each risky source (tooltip text in the UI). */
const RISK_EXPLANATIONS = {
  "'unsafe-inline'": "Allows inline <script>/<style> and event handlers - defeats most of CSP's XSS protection.",
  "'unsafe-eval'": 'Allows eval() and similar code execution - weakens XSS protection.',
  '*': 'Allows every origin - effectively no restriction for this directive.',
  'data:': 'data: URIs can carry arbitrary payloads and are same-origin - attackers can smuggle content through them.',
  'http:': 'Allows insecure origins - a network attacker can inject or tamper with subresources.',
};

/** Explanation for any risky source; falls back to the generic insecure-origin text. */
export function riskExplanation(source) {
  return RISK_EXPLANATIONS[source.trim().toLowerCase()] ?? 'Insecure http:// URL - traffic can be tampered with in transit.';
}

/**
 * Lint a policy: warns when default-src is missing (unset directives fall
 * back to the browser's allow-everything default) and flags every risky
 * source. Issues with directive === '' are policy-wide.
 */
export function validateCSP(directives) {
  const issues = [];
  if (directives['default-src'] === undefined) {
    issues.push({
      directive: '',
      source: null,
      message: "No default-src - every directive you don't set explicitly falls back to the browser's permissive default.",
    });
  }
  for (const [name, sources] of Object.entries(directives)) {
    for (const src of sources) {
      if (isRiskySource(src)) {
        issues.push({ directive: name, source: src, message: `${name}: ${src} weakens this policy - ${riskExplanation(src)}` });
      }
    }
  }
  return issues;
}

/** Score penalty per risky source (case-insensitive key). */
const SCORE_PENALTIES = { "'unsafe-inline'": 20, "'unsafe-eval'": 15, '*': 20, 'data:': 10, 'http:': 10 };

/**
 * Security score, 0-100. Starts at 100; each risky source subtracts its
 * penalty (insecure http:// URLs subtract 10), and a missing default-src
 * subtracts 10. Clamped to 0-100. Deterministic.
 */
export function securityScore(directives) {
  let score = 100;
  if (directives['default-src'] === undefined) score -= 10;
  for (const sources of Object.values(directives)) {
    for (const src of sources) {
      const s = src.trim().toLowerCase();
      score -= SCORE_PENALTIES[s] ?? (s.startsWith('http://') ? 10 : 0);
    }
  }
  return Math.max(0, Math.min(100, score));
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →