Skip to content

Security Headers Analyzer — Swift 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 Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.

// security-headers — HTTP security-header analysis and grading.
//
// Language: Swift 5.9+ (Foundation only)
// Ported from src/lib/security-headers.ts
// display source — part of CosmoDev's polyglot tool pages
//
// Pure logic — no UI, no network, deterministic. Parses a raw response-header
// block (the "key: value" lines copied from DevTools' Network panel), grades
// each of 8 security headers A/B/C/F, and rolls a weighted overall score.
// Header names match case-insensitively, folded (indented) continuation lines
// join their parent value, and duplicate names join with ", ". Malformed lines
// and the HTTP status line are ignored. Never throws.

import Foundation

// MARK: - Types

/// Per-header grade: A best practice, B present but weak,
/// C missing or dangerous, F actively harmful.
enum HeaderGrade: String {
    case A, B, C, F

    /// Grade points used for the weighted overall score.
    var points: Double {
        switch self {
        case .A: return 100
        case .B: return 70
        case .C: return 40
        case .F: return 0
        }
    }
}

/// One security header as analyzed: the parsed value plus its grade and guidance.
struct ParsedHeader {
    /// Canonical name, e.g. `Strict-Transport-Security`.
    let name: String
    /// Raw value as parsed; nil when the header is absent.
    let value: String?
    let grade: HeaderGrade
    let explanation: String
    let recommendation: String
}

/// The full analysis result: per-header rows, the overall grade, and fix list.
struct HeaderAnalysis {
    let headers: [ParsedHeader]
    let grade: HeaderGrade
    /// 0-100 weighted average of per-header grades.
    let score: Int
    let recommendations: [String]
}

/// The verdict fields every grader returns; folded into `ParsedHeader`.
private struct Grading {
    let grade: HeaderGrade
    let explanation: String
    let recommendation: String
}

/// Catalog entry: canonical name, why the header matters, and its score weight.
struct HeaderSpec {
    let name: String
    let description: String
    let weight: Double
    /// The grader for this header. Kept beside the spec so the catalog is
    /// exhaustive by construction — the TS reference gets the same guarantee
    /// from a `Record<SecurityHeaderName, ...>` lookup table.
    fileprivate let grade: (String?) -> Grading
}

// One year in seconds — the minimum HSTS max-age worth calling strong.
private let ONE_YEAR = 31_536_000

// MARK: - Helpers

private extension String {
    var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) }

    /// Case-insensitive regex test.
    func matches(_ pattern: String) -> Bool {
        range(of: pattern, options: [.regularExpression, .caseInsensitive]) != nil
    }

    /// First capture group of a case-insensitive regex, or nil.
    func firstCapture(_ pattern: String) -> String? {
        guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else { return nil }
        let ns = self as NSString
        guard let match = regex.firstMatch(in: self, range: NSRange(location: 0, length: ns.length)),
              match.numberOfRanges > 1,
              match.range(at: 1).location != NSNotFound
        else { return nil }
        return ns.substring(with: match.range(at: 1))
    }
}

// MARK: - Header block parsing

/// Parse a raw header block into a lowercased-name map. Lines are `name: value`;
/// the `HTTP/1.1 200 OK` status line and any line without a colon are ignored.
/// A line starting with space/tab continues the previous header (RFC 7230
/// obs-fold); a repeated name joins its values with ", ".
func parseHeaders(_ raw: String) -> [String: String] {
    var headers: [String: String] = [:]
    var lastName: String?

    for line in raw.components(separatedBy: .newlines) {
        if let first = line.first, first == " " || first == "\t" {
            // Folded continuation — append to the previous header, if any.
            if let lastName {
                let previous = headers[lastName] ?? ""
                headers[lastName] = "\(previous) \(line.trimmed)".trimmed
            }
            continue
        }

        guard let colon = line.firstIndex(of: ":") else { continue } // status line, blank line, or junk
        let name = String(line[line.startIndex..<colon]).trimmed.lowercased()
        if name.isEmpty { continue }

        let value = String(line[line.index(after: colon)...]).trimmed
        headers[name] = headers[name].map { "\($0), \(value)" } ?? value
        lastName = name
    }
    return headers
}

// MARK: - Per-header graders (value nil == absent)

private func gradeHsts(_ value: String?) -> Grading {
    guard let value else {
        return Grading(
            grade: .C,
            explanation: "Missing - the browser accepts plain HTTP, so the first visit (and SSL-strip attacks) can downgrade the connection.",
            recommendation: "Add: strict-transport-security: max-age=31536000; includeSubDomains; preload"
        )
    }
    guard let raw = value.firstCapture(#"max-age\s*=\s*(\d+)"#) else {
        return Grading(
            grade: .B,
            explanation: "Present but malformed - no readable max-age directive (\(value)).",
            recommendation: "Use: strict-transport-security: max-age=31536000; includeSubDomains"
        )
    }
    // `Number(...)` on a `\d+` capture; an overflowing value is treated as huge, not zero.
    let maxAge = Int(raw) ?? Int.max
    if maxAge == 0 {
        return Grading(
            grade: .F,
            explanation: "max-age=0 actively deletes the HSTS policy - the site opts out of HTTPS-only enforcement.",
            recommendation: "Raise max-age to at least 31536000 (one year)."
        )
    }

    let hasSubs = value.matches(#";\s*includesubdomains"#)
    if maxAge < ONE_YEAR {
        return Grading(
            grade: .B,
            explanation: "Present with max-age=\(maxAge)s (< 1 year)\(hasSubs ? " and includeSubDomains" : "") - a shorter window weakens the guarantee.",
            recommendation: "Raise max-age to 31536000 (one year) or more."
        )
    }
    if !hasSubs {
        return Grading(
            grade: .B,
            explanation: "Strong max-age (>= 1 year), but includeSubDomains is missing - subdomains stay downgradable.",
            recommendation: "Append ; includeSubDomains once every subdomain serves HTTPS."
        )
    }

    let hasPreload = value.matches(#";\s*preload"#)
    return Grading(
        grade: .A,
        explanation: "Strong: max-age >= 1 year + includeSubDomains\(hasPreload ? " + preload - eligible for the browser preload list." : ". Add preload to join the browser preload list.")",
        recommendation: "Best practice met - nothing to change."
    )
}

private func gradeCsp(_ value: String?) -> Grading {
    guard let value else {
        return Grading(
            grade: .C,
            explanation: "Missing - no restriction on where scripts and resources load from, so injected markup runs at full power.",
            recommendation: "Add a policy, e.g.: content-security-policy: default-src 'none'; script-src 'self'; ..."
        )
    }
    let inline = value.matches("'unsafe-inline'")
    let evaluates = value.matches("'unsafe-eval'")

    if inline && evaluates {
        return Grading(
            grade: .F,
            explanation: "Actively harmful - 'unsafe-inline' + 'unsafe-eval' together re-allow inline injection and string evaluation, gutting the policy while it still looks present.",
            recommendation: "Remove 'unsafe-inline' and 'unsafe-eval'; use nonces or hashes for inline scripts."
        )
    }
    if inline || evaluates {
        let culprit = inline ? "'unsafe-inline'" : "'unsafe-eval'"
        return Grading(
            grade: .B,
            explanation: "Present but weak - \(culprit) punches a hole through the anti-XSS guarantee.",
            recommendation: "Remove \(culprit); use nonces or hashes for legitimate inline code."
        )
    }
    if !value.matches(#"(^|\s)default-src\s"#) {
        return Grading(
            grade: .B,
            explanation: "Present with no default-src - resource types not listed explicitly fall back to the browser permissive default.",
            recommendation: "Start the policy with default-src 'none' or 'self', then allow what you need."
        )
    }
    return Grading(
        grade: .A,
        explanation: "Strong - a default-src fallback with no unsafe-inline / unsafe-eval escape hatches.",
        recommendation: "Best practice met - nothing to change."
    )
}

private func gradeFrameOptions(_ value: String?) -> Grading {
    guard let value else {
        return Grading(
            grade: .C,
            explanation: "Missing - any site can embed this page in an iframe and overlay it (clickjacking).",
            recommendation: "Add: x-frame-options: DENY (or SAMEORIGIN if you embed yourself)"
        )
    }
    let v = value.trimmed.uppercased()
    if v == "DENY" || v == "SAMEORIGIN" {
        return Grading(
            grade: .A,
            explanation: "Strong - \(v) blocks framing by other origins.",
            recommendation: "Best practice met - nothing to change."
        )
    }
    if v.hasPrefix("ALLOW-FROM") {
        return Grading(
            grade: .B,
            explanation: "ALLOW-FROM is deprecated and modern browsers ignore it - the page is effectively frameable.",
            recommendation: "Replace with a CSP frame-ancestors directive (x-frame-options: DENY as fallback)."
        )
    }
    return Grading(
        grade: .B,
        explanation: "Unrecognized value (\(value)) - browsers ignore it, leaving the page frameable.",
        recommendation: "Use DENY or SAMEORIGIN."
    )
}

private func gradeContentTypeOptions(_ value: String?) -> Grading {
    guard let value else {
        return Grading(
            grade: .C,
            explanation: "Missing - browsers may sniff uploaded content into executable types.",
            recommendation: "Add: x-content-type-options: nosniff"
        )
    }
    if value.trimmed.lowercased() == "nosniff" {
        return Grading(
            grade: .A,
            explanation: "Strong - MIME sniffing is off; the declared Content-Type is final.",
            recommendation: "Best practice met - nothing to change."
        )
    }
    return Grading(
        grade: .B,
        explanation: "Present but the value (\(value)) is not nosniff, so browsers ignore the header.",
        recommendation: "Send exactly: x-content-type-options: nosniff"
    )
}

private let REFERRER_STRICT = ["no-referrer", "same-origin", "strict-origin", "strict-origin-when-cross-origin"]
private let REFERRER_WEAK = ["origin", "origin-when-cross-origin", "no-referrer-when-downgrade"]

private func gradeReferrerPolicy(_ value: String?) -> Grading {
    guard let value else {
        return Grading(
            grade: .C,
            explanation: "Missing - older browsers default to leaking the full URL to whatever site the user navigates to.",
            recommendation: "Add: referrer-policy: strict-origin-when-cross-origin (or no-referrer)"
        )
    }
    let v = value.trimmed.lowercased()
    if v == "unsafe-url" {
        return Grading(
            grade: .F,
            explanation: "Actively harmful - unsafe-url sends the full URL (including IDs and tokens in query strings) to every destination, even on plain HTTP.",
            recommendation: "Use strict-origin-when-cross-origin or no-referrer instead."
        )
    }
    if REFERRER_STRICT.contains(v) {
        return Grading(
            grade: .A,
            explanation: "Strong - \(v) leaks at most the origin cross-origin.",
            recommendation: "Best practice met - nothing to change."
        )
    }
    if REFERRER_WEAK.contains(v) {
        return Grading(
            grade: .B,
            explanation: "Present but leaky - \(v) still shares the full URL in some same- or cross-origin cases.",
            recommendation: "Tighten to strict-origin-when-cross-origin, strict-origin, same-origin, or no-referrer."
        )
    }
    return Grading(
        grade: .B,
        explanation: "Unrecognized value (\(value)) - browsers fall back to their default policy.",
        recommendation: "Use one of the standard directives, e.g. strict-origin-when-cross-origin."
    )
}

private func gradePermissionsPolicy(_ value: String?) -> Grading {
    guard let value else {
        return Grading(
            grade: .C,
            explanation: "Missing - powerful features (camera, geolocation, payment...) default to the browser policy, not yours.",
            recommendation: "Add: permissions-policy: camera=(), microphone=(), geolocation=()"
        )
    }
    // `value.replace(/\s+/g, '').toLowerCase()` — strip every space, then fold case.
    let v = value.components(separatedBy: .whitespacesAndNewlines).joined().lowercased()
    if v.isEmpty {
        return Grading(
            grade: .B,
            explanation: "Present but empty - no feature is restricted, so it declares nothing.",
            recommendation: "List the features to switch off, e.g. camera=(), microphone=()."
        )
    }
    if v == "*" || v.contains("=*") {
        return Grading(
            grade: .B,
            explanation: "Present but permissive - a =* wildcard re-allows the listed feature(s) everywhere.",
            recommendation: "Use an empty allowlist () or a specific origin instead of *."
        )
    }
    return Grading(
        grade: .A,
        explanation: "Strong - the policy restricts at least one powerful feature.",
        recommendation: "Best practice met - nothing to change."
    )
}

private func gradeXssProtection(_ value: String?) -> Grading {
    guard let value else {
        return Grading(
            grade: .A,
            explanation: "Correctly omitted - the header is deprecated; modern browsers removed the XSS Auditor it drove.",
            recommendation: "Nothing to change - rely on Content-Security-Policy instead."
        )
    }
    let v = value.trimmed
    if v == "0" || v.hasPrefix("0;") {
        return Grading(
            grade: .A,
            explanation: "Explicitly disabled ('0') - the right call for a deprecated header old browsers still honor.",
            recommendation: "Nothing to change - or remove the header entirely."
        )
    }
    if v.hasPrefix("1") {
        return Grading(
            grade: .B,
            explanation: "Deprecated - '1; mode=block' is ignored by modern browsers and the old Auditor had cross-site leaks of its own.",
            recommendation: "Send '0' or drop the header; use Content-Security-Policy for XSS defense."
        )
    }
    return Grading(
        grade: .B,
        explanation: "Present with an unrecognized value (\(value)) - remove the deprecated header.",
        recommendation: "Send '0' or drop the header entirely."
    )
}

private func gradeCoop(_ value: String?) -> Grading {
    guard let value else {
        return Grading(
            grade: .C,
            explanation: "Missing - pages that open or are opened by other origins share a browsing context with them.",
            recommendation: "Add: cross-origin-opener-policy: same-origin"
        )
    }
    let v = value.trimmed.lowercased()
    if v == "same-origin" {
        return Grading(
            grade: .A,
            explanation: "Strong - the window handle is isolated from cross-origin openers.",
            recommendation: "Best practice met - nothing to change."
        )
    }
    if v == "same-origin-allow-popups" {
        return Grading(
            grade: .B,
            explanation: "Partially isolated - popups you open keep a reference to this window.",
            recommendation: "Use same-origin unless you genuinely need cross-origin popup handles."
        )
    }
    if v == "unsafe-none" {
        return Grading(
            grade: .B,
            explanation: "Explicit opt-out - unsafe-none restores the shared browsing context COOP exists to cut.",
            recommendation: "Use same-origin unless a documented integration requires shared handles."
        )
    }
    return Grading(
        grade: .B,
        explanation: "Unrecognized value (\(value)) - browsers treat it as no COOP.",
        recommendation: "Use same-origin."
    )
}

// MARK: - Catalog

/// The 8 security headers this analyzer grades, in display order.
let SECURITY_HEADERS: [HeaderSpec] = [
    HeaderSpec(
        name: "Strict-Transport-Security",
        description: "HSTS tells the browser 'only ever reach this site over HTTPS' for max-age seconds. It defeats SSL-strip attacks, which downgrade the very first plain-HTTP visit. includeSubDomains extends the guarantee to every subdomain; preload lets the site join the browser-built HSTS preload list so even the first visit is HTTPS.",
        weight: 1.5,
        grade: gradeHsts
    ),
    HeaderSpec(
        name: "Content-Security-Policy",
        description: "CSP is the strongest anti-XSS control available in a header: it declares which sources scripts, styles, and other resources may load from. 'unsafe-inline' and 'unsafe-eval' punch holes straight through it - they re-allow inline injection and string-to-code evaluation. A default-src directive is the baseline so resource types you forgot to list inherit a restrictive fallback instead of the browser's permissive one.",
        weight: 2,
        grade: gradeCsp
    ),
    HeaderSpec(
        name: "X-Frame-Options",
        description: "Stops other sites from embedding this page in an iframe, which is the basis of clickjacking: an attacker overlays invisible UI on your framed page and harvests the victim's clicks. DENY blocks all framing; SAMEORIGIN allows only your own origin. The modern replacement is the CSP frame-ancestors directive.",
        weight: 1,
        grade: gradeFrameOptions
    ),
    HeaderSpec(
        name: "X-Content-Type-Options",
        description: "With the value nosniff, the browser must respect the declared Content-Type instead of 'helpfully' sniffing the payload. Sniffing turns an uploaded text file into executable JavaScript when its bytes look script-shaped - the classic content-type-confusion attack.",
        weight: 1,
        grade: gradeContentTypeOptions
    ),
    HeaderSpec(
        name: "Referrer-Policy",
        description: "Controls how much of the URL the browser leaks in the Referer header when the user navigates to another site. Full URLs can carry IDs, tokens, or search queries to third parties. strict-origin-when-cross-origin sends only the origin cross-origin (the browser default since 2020); no-referrer and same-origin leak even less. unsafe-url sends the full URL everywhere, including on plain-HTTP requests.",
        weight: 1,
        grade: gradeReferrerPolicy
    ),
    HeaderSpec(
        name: "Permissions-Policy",
        description: "Declares which browser features (camera, microphone, geolocation, payment, USB...) the page and its embedded iframes may use. An empty allowlist - feature=() - switches the feature off entirely; an =* wildcard re-allows it everywhere, defeating the point of declaring it.",
        weight: 1,
        grade: gradePermissionsPolicy
    ),
    HeaderSpec(
        name: "X-XSS-Protection",
        description: "The 2010-era XSS Auditor: browsers inspected reflected input in the page and blocked obviously injected scripts. Chrome removed it in 2019 (its heuristics introduced cross-site leaks of their own) and every modern browser now ignores it. The header is deprecated - CSP is the real defense. Sites either omit it or send '0' to switch old browsers off.",
        weight: 0.5,
        grade: gradeXssProtection
    ),
    HeaderSpec(
        name: "Cross-Origin-Opener-Policy",
        description: "Isolates the page's window handle from other origins. Without COOP, a site that opened your page in a popup (or was opened by it) keeps a JS reference to it, enabling some cross-window attacks and Spectre-class side channels. same-origin cuts that shared handle; unsafe-none restores the old shared browsing context.",
        weight: 1,
        grade: gradeCoop
    ),
]

// MARK: - Analysis

/// Map a weighted 0-100 score to the overall A/B/C/F grade.
private func overallGrade(_ score: Int) -> HeaderGrade {
    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
/// `ParsedHeader` row (in catalog order); the overall score is the
/// weight-adjusted average of per-header grade points, and recommendations
/// list one fix per header that is not at grade A.
func analyzeHeaders(_ raw: String) -> HeaderAnalysis {
    let parsed = parseHeaders(raw)

    let headers = SECURITY_HEADERS.map { spec -> ParsedHeader in
        let value = parsed[spec.name.lowercased()]
        let grading = spec.grade(value)
        return ParsedHeader(
            name: spec.name,
            value: value,
            grade: grading.grade,
            explanation: grading.explanation,
            recommendation: grading.recommendation
        )
    }

    let totalWeight = SECURITY_HEADERS.reduce(0.0) { $0 + $1.weight }
    let earned = zip(headers, SECURITY_HEADERS).reduce(0.0) { $0 + $1.0.grade.points * $1.1.weight }
    let score = Int((earned / totalWeight).rounded())

    let recommendations = headers.filter { $0.grade != .A }.map(\.recommendation)
    return HeaderAnalysis(headers: headers, grade: overallGrade(score), score: score, recommendations: recommendations)
}

// MARK: - Demo

func demo() {
    let raw = """
    HTTP/1.1 200 OK
    strict-transport-security: max-age=31536000; includeSubDomains; preload
    content-security-policy: default-src 'none'; script-src 'self'
    x-frame-options: DENY
    x-content-type-options: nosniff
    referrer-policy: strict-origin-when-cross-origin
    permissions-policy: camera=(), microphone=(), geolocation=()
    cross-origin-opener-policy: same-origin
    """

    let analysis = analyzeHeaders(raw)
    print("Overall: \(analysis.grade.rawValue) (\(analysis.score)/100)")
    for header in analysis.headers {
        print("  [\(header.grade.rawValue)] \(header.name): \(header.value ?? "— absent —")")
    }
    if !analysis.recommendations.isEmpty {
        print("Fixes:")
        analysis.recommendations.forEach { print("  - \($0)") }
    }
}

Also available in 8 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 →