Security Headers Analyzer — JavaScript source
Paste HTTP response headers to analyze security posture. Checks CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and Permissions-Policy.
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
/**
* security-headers — HTTP response-header analysis and grading.
*
* Language: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
* CosmoDev polyglot showcase port of the `security-headers` tool, ported from
* src/lib/security-headers.ts.
*
* Why this file exists: grading security headers is pure string work, so the
* exact logic that powers the web tool runs anywhere JS does — paste the
* "key: value" lines from DevTools' Network panel and any environment gets
* the same A/B/C/F verdicts, weighted score, and fix list as the live tool.
* Catalog blurbs are omitted for brevity; every grade, explanation, and
* score matches the TypeScript lib byte for byte.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
// The 8 graded headers with their score weights, in display order. The long
// "why it matters" blurbs live in src/lib/security-headers.ts.
const SECURITY_HEADERS = [
{ name: 'Strict-Transport-Security', weight: 1.5 },
{ name: 'Content-Security-Policy', weight: 2 },
{ name: 'X-Frame-Options', weight: 1 },
{ name: 'X-Content-Type-Options', weight: 1 },
{ name: 'Referrer-Policy', weight: 1 },
{ name: 'Permissions-Policy', weight: 1 },
{ name: 'X-XSS-Protection', weight: 0.5 },
{ name: 'Cross-Origin-Opener-Policy', weight: 1 },
];
const GRADE_POINTS = { A: 100, B: 70, C: 40, F: 0 }; // grade -> score points
const ONE_YEAR = 31536000; // minimum HSTS max-age worth calling strong
const BEST = 'Best practice met - nothing to change.';
const REFERRER_STRICT = ['no-referrer', 'same-origin', 'strict-origin', 'strict-origin-when-cross-origin'];
const REFERRER_WEAK = ['origin', 'origin-when-cross-origin', 'no-referrer-when-downgrade'];
/**
* Parse a raw header block into a Map keyed by lowercased name. Lines are
* `name: value`; the `HTTP/1.1 200 OK` status line and any line without a
* colon are ignored, an indented line continues the previous header (RFC
* 7230 obs-fold), and a repeated name joins its values with ", ". Never
* throws - a pasted header block is untrusted input.
*/
export function parseHeaders(raw) {
const headers = new Map();
let lastName = null;
for (const line of String(raw ?? '').split(/\r?\n/)) {
if (/^\s/.test(line)) {
if (lastName !== null) headers.set(lastName, `${headers.get(lastName) ?? ''} ${line.trim()}`.trim());
continue; // folded continuation
}
const colon = line.indexOf(':');
if (colon === -1) continue; // status line, blank line, or junk
const name = line.slice(0, colon).trim().toLowerCase();
if (name === '') continue;
const value = line.slice(colon + 1).trim();
const prev = headers.get(name);
headers.set(name, prev === undefined ? value : `${prev}, ${value}`);
lastName = name;
}
return headers;
}
// --- Per-header graders: value (null when absent) -> [grade, explanation, recommendation] ---
function gradeHsts(v) {
if (v === null) return ['C', 'Missing - the browser accepts plain HTTP, so the first visit (and SSL-strip attacks) can downgrade the connection.', 'Add: strict-transport-security: max-age=31536000; includeSubDomains; preload'];
const m = /max-age\s*=\s*(\d+)/i.exec(v);
if (m === null) return ['B', `Present but malformed - no readable max-age directive (${v}).`, 'Use: strict-transport-security: max-age=31536000; includeSubDomains'];
const maxAge = Number(m[1]);
if (maxAge === 0) return ['F', 'max-age=0 actively deletes the HSTS policy - the site opts out of HTTPS-only enforcement.', 'Raise max-age to at least 31536000 (one year).'];
const subs = /;\s*includesubdomains/i.test(v);
if (maxAge < ONE_YEAR) return ['B', `Present with max-age=${maxAge}s (< 1 year)${subs ? ' and includeSubDomains' : ''} - a shorter window weakens the guarantee.`, 'Raise max-age to 31536000 (one year) or more.'];
if (!subs) return ['B', 'Strong max-age (>= 1 year), but includeSubDomains is missing - subdomains stay downgradable.', 'Append ; includeSubDomains once every subdomain serves HTTPS.'];
const pre = /;\s*preload/i.test(v);
return ['A', `Strong: max-age >= 1 year + includeSubDomains${pre ? ' + preload - eligible for the browser preload list.' : '. Add preload to join the browser preload list.'}`, BEST];
}
function gradeCsp(v) {
if (v === null) return ['C', 'Missing - no restriction on where scripts and resources load from, so injected markup runs at full power.', "Add a policy, e.g.: content-security-policy: default-src 'none'; script-src 'self'; ..."];
const inline = /'unsafe-inline'/i.test(v);
const evaluates = /'unsafe-eval'/i.test(v);
if (inline && evaluates) return ['F', "Actively harmful - 'unsafe-inline' + 'unsafe-eval' together re-allow inline injection and string evaluation, gutting the policy while it still looks present.", "Remove 'unsafe-inline' and 'unsafe-eval'; use nonces or hashes for inline scripts."];
if (inline || evaluates) {
const culprit = inline ? "'unsafe-inline'" : "'unsafe-eval'";
return ['B', `Present but weak - ${culprit} punches a hole through the anti-XSS guarantee.`, `Remove ${culprit}; use nonces or hashes for legitimate inline code.`];
}
if (!/(^|\s)default-src\s/i.test(v)) return ['B', 'Present with no default-src - resource types not listed explicitly fall back to the browser permissive default.', "Start the policy with default-src 'none' or 'self', then allow what you need."];
return ['A', 'Strong - a default-src fallback with no unsafe-inline / unsafe-eval escape hatches.', BEST];
}
function gradeFrameOptions(v) {
if (v === null) return ['C', 'Missing - any site can embed this page in an iframe and overlay it (clickjacking).', 'Add: x-frame-options: DENY (or SAMEORIGIN if you embed yourself)'];
const u = v.trim().toUpperCase();
if (u === 'DENY' || u === 'SAMEORIGIN') return ['A', `Strong - ${u} blocks framing by other origins.`, BEST];
if (u.startsWith('ALLOW-FROM')) return ['B', 'ALLOW-FROM is deprecated and modern browsers ignore it - the page is effectively frameable.', 'Replace with a CSP frame-ancestors directive (x-frame-options: DENY as fallback).'];
return ['B', `Unrecognized value (${v}) - browsers ignore it, leaving the page frameable.`, 'Use DENY or SAMEORIGIN.'];
}
function gradeContentTypeOptions(v) {
if (v === null) return ['C', 'Missing - browsers may sniff uploaded content into executable types.', 'Add: x-content-type-options: nosniff'];
if (v.trim().toLowerCase() === 'nosniff') return ['A', 'Strong - MIME sniffing is off; the declared Content-Type is final.', BEST];
return ['B', `Present but the value (${v}) is not nosniff, so browsers ignore the header.`, 'Send exactly: x-content-type-options: nosniff'];
}
function gradeReferrerPolicy(v) {
if (v === null) return ['C', 'Missing - older browsers default to leaking the full URL to whatever site the user navigates to.', 'Add: referrer-policy: strict-origin-when-cross-origin (or no-referrer)'];
const p = v.trim().toLowerCase();
if (p === 'unsafe-url') return ['F', 'Actively harmful - unsafe-url sends the full URL (including IDs and tokens in query strings) to every destination, even on plain HTTP.', 'Use strict-origin-when-cross-origin or no-referrer instead.'];
if (REFERRER_STRICT.includes(p)) return ['A', `Strong - ${p} leaks at most the origin cross-origin.`, BEST];
if (REFERRER_WEAK.includes(p)) return ['B', `Present but leaky - ${p} still shares the full URL in some same- or cross-origin cases.`, 'Tighten to strict-origin-when-cross-origin, strict-origin, same-origin, or no-referrer.'];
return ['B', `Unrecognized value (${v}) - browsers fall back to their default policy.`, 'Use one of the standard directives, e.g. strict-origin-when-cross-origin.'];
}
function gradePermissionsPolicy(v) {
if (v === null) return ['C', 'Missing - powerful features (camera, geolocation, payment...) default to the browser policy, not yours.', 'Add: permissions-policy: camera=(), microphone=(), geolocation=()'];
const p = v.replace(/\s+/g, '').toLowerCase();
if (p === '') return ['B', 'Present but empty - no feature is restricted, so it declares nothing.', 'List the features to switch off, e.g. camera=(), microphone=().'];
if (p === '*' || p.includes('=*')) return ['B', 'Present but permissive - a =* wildcard re-allows the listed feature(s) everywhere.', 'Use an empty allowlist () or a specific origin instead of *.'];
return ['A', 'Strong - the policy restricts at least one powerful feature.', BEST];
}
function gradeXssProtection(v) {
if (v === null) return ['A', 'Correctly omitted - the header is deprecated; modern browsers removed the XSS Auditor it drove.', 'Nothing to change - rely on Content-Security-Policy instead.'];
const t = v.trim();
if (t === '0' || t.startsWith('0;')) return ['A', "Explicitly disabled ('0') - the right call for a deprecated header old browsers still honor.", 'Nothing to change - or remove the header entirely.'];
if (t.startsWith('1')) return ['B', "Deprecated - '1; mode=block' is ignored by modern browsers and the old Auditor had cross-site leaks of its own.", "Send '0' or drop the header; use Content-Security-Policy for XSS defense."];
return ['B', `Present with an unrecognized value (${v}) - remove the deprecated header.`, "Send '0' or drop the header entirely."];
}
function gradeCoop(v) {
if (v === null) return ['C', 'Missing - pages that open or are opened by other origins share a browsing context with them.', 'Add: cross-origin-opener-policy: same-origin'];
const p = v.trim().toLowerCase();
if (p === 'same-origin') return ['A', 'Strong - the window handle is isolated from cross-origin openers.', BEST];
if (p === 'same-origin-allow-popups') return ['B', 'Partially isolated - popups you open keep a reference to this window.', 'Use same-origin unless you genuinely need cross-origin popup handles.'];
if (p === 'unsafe-none') return ['B', 'Explicit opt-out - unsafe-none restores the shared browsing context COOP exists to cut.', 'Use same-origin unless a documented integration requires shared handles.'];
return ['B', `Unrecognized value (${v}) - browsers treat it as no COOP.`, 'Use same-origin.'];
}
// Compile-time-complete grader table: every catalog name has a grader.
const GRADERS = {
'Strict-Transport-Security': gradeHsts,
'Content-Security-Policy': gradeCsp,
'X-Frame-Options': gradeFrameOptions,
'X-Content-Type-Options': gradeContentTypeOptions,
'Referrer-Policy': gradeReferrerPolicy,
'Permissions-Policy': gradePermissionsPolicy,
'X-XSS-Protection': gradeXssProtection,
'Cross-Origin-Opener-Policy': gradeCoop,
};
/** Map a weighted 0-100 score to the overall A/B/C/F grade. */
function overallGrade(score) {
if (score >= 90) return 'A';
if (score >= 70) return 'B';
if (score >= 45) return 'C';
return 'F';
}
/**
* Analyze a raw HTTP response-header block. Every catalog header gets a
* {name, value, grade, explanation, recommendation} row in catalog order;
* the overall score is the weight-adjusted average of per-header grade
* points, and recommendations list one fix per header below grade A.
*/
export function analyzeHeaders(raw) {
const parsed = parseHeaders(raw);
const headers = SECURITY_HEADERS.map((spec) => {
const value = parsed.get(spec.name.toLowerCase()) ?? null;
const [grade, explanation, recommendation] = GRADERS[spec.name](value);
return { name: spec.name, value, grade, explanation, recommendation };
});
const totalWeight = SECURITY_HEADERS.reduce((sum, spec) => sum + spec.weight, 0);
const score = Math.round(headers.reduce((sum, h, i) => sum + GRADE_POINTS[h.grade] * SECURITY_HEADERS[i].weight, 0) / totalWeight);
const recommendations = headers.filter((h) => h.grade !== 'A').map((h) => h.recommendation);
return { headers, grade: overallGrade(score), score, recommendations };
}
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 →