gossan-headless 0.3.3

Headless Chromium browser engine for executing JavaScript and trapping dynamic XHRs in gossan, part of the security research ecosystem
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
#![forbid(unsafe_code)]
// pedantic moved to workspace [lints.clippy] in root Cargo.toml
#![cfg_attr(
    not(test),
    deny(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::todo,
        clippy::unimplemented,
        clippy::panic
    )
)]
#![allow(
    clippy::module_name_repetitions,
    clippy::must_use_candidate,
    clippy::missing_errors_doc
)]

//! Headless browser scanning (screenshot, DOM analysis, SPA detection).
//!
//! Uses `runtime-headless` (Chromium CDP) to render JavaScript-heavy pages and extract
//! security-relevant signals that static HTTP probing cannot see.

use async_trait::async_trait;
use futures::StreamExt;
use gossan_core::{Config, ScanInput, Scanner, Target};
use runtime_headless::chromiumoxide::Browser;
use runtime_headless::{BrowserLaunchOptions, BrowserRuntime};
use secfinding::{Evidence, Finding, FindingBuilder, Severity};
use std::time::Duration;
/// Headless browser scanner (screenshot, DOM analysis, SPA spider, dynamic endpoint discovery).
pub struct HeadlessScanner;

/// Launch options shared by the scanner and its tests (via `runtime-headless`).
#[must_use]
pub fn browser_launch_options() -> BrowserLaunchOptions {
    let mut options = BrowserLaunchOptions::default_stealth();
    // Preserves pre-migration `BrowserConfig::builder().with_head()` posture.
    options.headed = true;
    options.new_headless_mode = false;
    options.no_sandbox = true;
    options
}

fn finding_builder(
    target: &Target,
    severity: Severity,
    title: impl Into<String>,
    detail: impl Into<String>,
) -> FindingBuilder {
    Finding::builder("headless", target.domain().unwrap_or("?"), severity)
        .title(title)
        .detail(detail)
        .kind(secfinding::FindingKind::InfoDisclosure)
}

#[async_trait]
impl Scanner for HeadlessScanner {
    fn name(&self) -> &'static str {
        "headless"
    }

    fn tags(&self) -> &[&'static str] {
        &["headless", "browser", "dynamic"]
    }

    fn accepts(&self, target: &Target) -> bool {
        matches!(target, Target::Web(_))
    }

    async fn run(&self, input: ScanInput, config: &Config) -> anyhow::Result<()> {
        // Drain the inbound target stream into an owned Vec. The
        // ScanInput contract migrated from a buffered `targets: Vec<_>`
        // field to a streaming `target_rx: Mutex<UnboundedReceiver>` 
        // headless was missed in that migration. Pull synchronously
        // here because chromiumoxide's per-tab work needs an owned set
        // upfront to size the buffer_unordered pool.
        let owned: Vec<Target> = {
            let mut rx = input.target_rx.lock().await;
            let mut buf = Vec::new();
            // recv() until the pipeline closes the inbox — try_recv races the
            // sender and drops asynchronously delivered targets.
            while let Some(t) = rx.recv().await {
                buf.push(t);
            }
            buf
        };

        if owned.is_empty() {
            return Ok(());
        }

        let runtime = std::sync::Arc::new(
            BrowserRuntime::launch(&browser_launch_options())
                .await
                .map_err(|e| anyhow::anyhow!("Failed to launch browser: {e}"))?,
        );

        // Parallel execution of all targets using the single browser instance
        let results: Vec<anyhow::Result<(Target, Vec<Finding>)>> = futures::stream::iter(owned)
            .map(|target| {
                let runtime = std::sync::Arc::clone(&runtime);
                let config = config.clone();
                async move { analyze_target(runtime.browser(), target, &config).await }
            })
            // Browser limit for tabs
            .buffer_unordered(config.concurrency.min(10).max(1))
            .collect()
            .await;

        for res in results {
            match res {
                Ok((target, findings)) => {
                    input.emit_target(target).await;
                    for f in findings {
                        input.emit(f).await;
                    }
                }
                Err(e) => {
                    tracing::warn!(err = %e, "headless analyze_target failed; skipping target");
                }
            }
        }

        // `runtime` drops here: BrowserRuntime::Drop aborts the CDP handler task.
        Ok(())
    }
}

async fn analyze_target(
    browser: &Browser,
    mut target: Target,
    config: &Config,
) -> anyhow::Result<(Target, Vec<Finding>)> {
    let Target::Web(ref asset) = target else {
        return Ok((target, vec![]));
    };
    let mut findings = Vec::new();

    let page = match tokio::time::timeout(
        std::time::Duration::from_secs(15),
        browser.new_page(asset.url.as_str()),
    )
    .await
    {
        Ok(Ok(p)) => p,
        Ok(Err(e)) => return Err(e.into()),
        Err(_) => {
            return Err(anyhow::anyhow!(
                "headless: browser.new_page timed out after 15s"
            ));
        }
    };

    // ── XHR / Fetch Hooking (Oneshot Dynamic Discovery) ──────────────────
    // Inject a script to proxy XHR and fetch to catch endpoints that
    // standard event listeners might miss due to race conditions.
    let hook_js = r#"
        (function() {
            window._santh_requests = [];
            
            // Hook Fetch, guard against environments where fetch is undefined
            // (e.g. CSP-blocked or very old browsers).
            if (typeof window.fetch === 'function') {
                const oldFetch = window.fetch;
                window.fetch = function() {
                    window._santh_requests.push({ url: arguments[0], type: 'fetch' });
                    return oldFetch.apply(this, arguments);
                };
            }

            // Hook XHR (guard against missing XMLHttpRequest).
            if (typeof XMLHttpRequest === 'function') {
                const oldOpen = XMLHttpRequest.prototype.open;
                XMLHttpRequest.prototype.open = function() {
                    window._santh_requests.push({ url: arguments[1], type: 'xhr' });
                    return oldOpen.apply(this, arguments);
                };
            }
        })();
    "#;
    if let Err(e) = page.evaluate_on_new_document(hook_js).await {
        tracing::warn!(error = %e, url = %asset.url, "failed to install headless network hooks");
    }

    // Start event listener early to catch everything from the jump
    let mut request_events = page
        .event_listener::<runtime_headless::chromiumoxide::cdp::browser_protocol::network::EventRequestWillBeSent>()
        .await?;

    match tokio::time::timeout(
        std::time::Duration::from_secs(15),
        page.goto(asset.url.as_str()),
    )
    .await
    {
        Ok(Ok(_)) => {}
        Ok(Err(e)) => {
            tracing::warn!(error = %e, url = %asset.url, "headless navigation failed");
        }
        Err(_) => {
            tracing::warn!(url = %asset.url, "headless navigation timed out");
        }
    }

    // Wait for the initial DOM load (bounded to prevent indefinite hang).
    match tokio::time::timeout(
        std::time::Duration::from_secs(15),
        page.wait_for_navigation(),
    )
    .await
    {
        Ok(Ok(_)) => {}
        Ok(Err(e)) => {
            tracing::warn!(error = %e, url = %asset.url, "headless wait_for_navigation failed");
        }
        Err(_) => {
            tracing::warn!(url = %asset.url, "headless wait_for_navigation timed out");
        }
    }

    // ── 1. Authenticated Login (Katana-style) ─────────────────────────────
    if let (Some(user), Some(pass)) = (&config.auth_user, &config.auth_pass) {
        let login_probe = r#"
            (function() {
                const forms = document.forms;
                for (const f of forms) {
                    let hasPassword = false;
                    let userField = null;
                    let passField = null;
                    for (const i of f.elements) {
                        const t = (i.type || '').toLowerCase();
                        if (t === 'password') {
                            hasPassword = true;
                            passField = i;
                        } else if (t === 'text' || t === 'email' || t === 'username') {
                            if (!userField) userField = i;
                        }
                    }
                    if (hasPassword && userField && passField) {
                        userField.setAttribute('data-santh-auth', 'user');
                        passField.setAttribute('data-santh-auth', 'pass');
                        return true;
                    }
                }
                return false;
            })()
        "#;

        if let Ok(res) = tokio::time::timeout(
            std::time::Duration::from_secs(10),
            page.evaluate(login_probe),
        )
        .await
        {
            let res = match res {
                Ok(r) => Some(r),
                Err(e) => {
                    tracing::warn!(
                        error = %e,
                        "headless: auth login-probe evaluate failed; continuing remaining probes"
                    );
                    None
                }
            };
            if let Some(res) = res {
            if res.value().and_then(|v| v.as_bool()).unwrap_or(false) {
                if let Ok(user_el) = page.find_element("input[data-santh-auth='user']").await {
                    if let Err(e) = user_el.type_str(user).await {
                        tracing::warn!(error = %e, "headless: auth username type_str failed");
                    }
                } else {
                    tracing::warn!("headless: auth username field not found after probe");
                }
                if let Ok(pass_el) = page.find_element("input[data-santh-auth='pass']").await {
                    if let Err(e) = pass_el.type_str(pass).await {
                        tracing::warn!(error = %e, "headless: auth password type_str failed");
                    }
                    if let Err(e) = pass_el.press_key("Enter").await {
                        tracing::warn!(error = %e, "headless: auth Enter keypress failed");
                    }
                } else {
                    tracing::warn!("headless: auth password field not found after probe");
                }
                // Allow some time for the login to process and session to establish
                tokio::time::sleep(Duration::from_secs(3)).await;
            }
        
            }
}
    }

    // ── 2. Stateful Spidering (Clicking all a/button) ─────────────────────
    let click_probe = r#"
        (function() {
            const elements = document.querySelectorAll('a, button');
            const result = [];
            for (let i = 0; i < Math.min(elements.length, 30); i++) {
                const el = elements[i];
                const text = (el.innerText || el.value || '').toLowerCase();
                // Skip destructive actions to avoid losing session or breaking state
                if (text.includes('logout') || text.includes('sign out') || text.includes('delete') || text.includes('remove')) {
                    continue;
                }
                el.setAttribute('data-santh-click', i);
                result.push(i);
            }
            return result;
        })()
    "#;

    if let Ok(res) = tokio::time::timeout(
        std::time::Duration::from_secs(10),
        page.evaluate(click_probe),
    )
    .await
    {
        match res {
            Ok(r) => {
                if let Some(idxs) = r.value().and_then(|v| v.as_array()) {
                    for idx in idxs {
                        if let Some(i) = idx.as_u64() {
                            let selector = format!("[data-santh-click='{}']", i);
                            if let Ok(el) = page.find_element(&selector).await {
                                if let Err(e) = el.click().await {
                                    tracing::debug!(error = %e, selector = %selector, "headless: spider click failed");
                                }
                                // Brief wait for dynamic route changes or background XHRs
                                tokio::time::sleep(Duration::from_millis(400)).await;
                            }
                        }
                    }
                }
            }
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "headless: click-probe evaluate failed; continuing without spider clicks"
                );
            }
        }
    } else {
        tracing::warn!("headless: click-probe evaluate timed out; continuing without spider clicks");
    }

    // Final idle to catch trailing asynchronous requests (React/Vue/Angular)
    tokio::time::sleep(Duration::from_secs(2)).await;

    // ── 3. Evidence Collection ─────────────────────────────────────────────

    // Collect findings from our injected JS hook
    if let Ok(res) = tokio::time::timeout(
        std::time::Duration::from_secs(10),
        page.evaluate("window._santh_requests"),
    )
    .await
    {
        let res = match res {
            Ok(r) => Some(r),
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "headless: request-hook collection evaluate failed; continuing remaining probes"
                );
                None
            }
        };
        if let Some(res) = res {
        if let Some(reqs) = res.value().and_then(|v| v.as_array()) {
            for r in reqs {
                let url = r.get("url").and_then(|v| v.as_str()).unwrap_or("");
                let typ = r.get("type").and_then(|v| v.as_str()).unwrap_or("unknown");
                if !url.is_empty() && !url.starts_with("data:") {
                    gossan_core::try_push_finding(
                        finding_builder(
                            &target,
                            Severity::Info,
                            format!("Dynamic {} Endpoint Hooked", typ.to_uppercase()),
                            format!("Injected hook trapped runtime {} request to: {}", typ, url),
                        )
                        .tag("recon")
                        .tag("hooked_request")
                        .evidence(Evidence::raw(url.to_string())),
                        &mut findings,
                    );
                }
            }
        }
    
        }
}

    // Drain all trapped network requests from the CDP listener too
    while let Ok(Some(req)) =
        tokio::time::timeout(Duration::from_millis(200), request_events.next()).await
    {
        let url = req.request.url.clone();

        // Filter out obvious noise, trap API paths
        if url.contains("api") || url.ends_with(".json") || url.ends_with(".graphql") {
            gossan_core::try_push_finding(
                finding_builder(
                    &target,
                    Severity::Info,
                    "Dynamic API Endpoint Trapped",
                    format!("Trapped runtime XHR request to: {}", url),
                )
                .tag("recon")
                .tag("dynamic_xhr")
                .evidence(Evidence::HttpResponse {
                    status: 200,
                    headers: vec![],
                    body_excerpt: Some(
                        format!(
                            "Method: {}, Headers: {:?}",
                            req.request.method, req.request.headers
                        )
                        .into(),
                    ),
                }),
                &mut findings,
            );
        }
    }

    // ── Global Variable Extraction ──────────────────────────────────────────
    // Look for common sensitive global variables or config objects
    let js_probe = r#"
        (function() {
            const interesting = [];
            const keys = ['config', 'env', 'process', 'API_KEY', 'SECRET', 'TOKEN', 'auth', 'firebase', 'aws'];
            for (const key of Object.keys(window)) {
                if (keys.some(k => key.toLowerCase().includes(k.toLowerCase()))) {
                    try {
                        const val = window[key];
                        if (val && typeof val === 'object') {
                            interesting.push({key, value: JSON.stringify(val).substring(0, 500)});
                        } else if (val) {
                            interesting.push({key, value: String(val).substring(0, 200)});
                        }
                    } catch(e) {}
                }
            }
            return interesting;
        })()
    "#;

    if let Ok(res) =
        tokio::time::timeout(std::time::Duration::from_secs(10), page.evaluate(js_probe)).await
    {
        let res = match res {
            Ok(r) => Some(r),
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "headless: js-global probe evaluate failed; continuing remaining probes"
                );
                None
            }
        };
        if let Some(res) = res {
        if let Some(interesting) = res.value().and_then(|v| v.as_array()) {
            for item in interesting {
                let key = item.get("key").and_then(|v| v.as_str()).unwrap_or("?");
                let value = item.get("value").and_then(|v| v.as_str()).unwrap_or("?");

                gossan_core::try_push_finding(finding_builder(
                    &target,
                    Severity::Low,
                    format!("Sensitive JS global detected: {}", key),
                    format!("Found global object/variable `{}` which may contain configuration or credentials.", key),
                )
                .tag("recon")
                .tag("js-global")
                .evidence(Evidence::raw(format!("{}: {}", key, value))), &mut findings);
            }
        }
    
        }
}

    // ── Form Extraction ─────────────────────────────────────────────────────
    let form_probe = r#"
        (function() {
            const forms = [];
            for (const f of document.forms) {
                const inputs = [];
                for (const i of f.elements) {
                    if (i.name) {
                        inputs.push([i.name, i.type || 'text']);
                    }
                }
                forms.push({
                    action: f.action,
                    method: f.method || 'GET',
                    inputs: inputs
                });
            }
            return forms;
        })()
    "#;

    let mut discovered_forms = Vec::new();
    if let Ok(res) = tokio::time::timeout(
        std::time::Duration::from_secs(10),
        page.evaluate(form_probe),
    )
    .await
    {
        let res = match res {
            Ok(r) => Some(r),
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "headless: form-extraction probe evaluate failed; continuing remaining probes"
                );
                None
            }
        };
        if let Some(res) = res {
        if let Some(forms) = res.value().and_then(|v| v.as_array()) {
            for f in forms {
                let action = f
                    .get("action")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let method = f
                    .get("method")
                    .and_then(|v| v.as_str())
                    .unwrap_or("GET")
                    .to_string();
                let mut inputs = Vec::new();
                if let Some(ins) = f.get("inputs").and_then(|v| v.as_array()) {
                    for i in ins {
                        if let Some(pair) = i.as_array() {
                            let name = pair
                                .first()
                                .and_then(|v| v.as_str())
                                .unwrap_or("")
                                .to_string();
                            let typ = pair
                                .get(1)
                                .and_then(|v| v.as_str())
                                .unwrap_or("text")
                                .to_string();
                            inputs.push((name, typ));
                        }
                    }
                }
                discovered_forms.push(gossan_core::DiscoveredForm {
                    action,
                    method,
                    inputs,
                });
            }
        }
    
        }
}

    if let Err(e) = tokio::time::timeout(std::time::Duration::from_secs(10), page.close()).await {
        tracing::debug!(error = %e, "headless page.close timed out or failed");
    }

    // Update the asset with discovered forms
    if let Target::Web(ref mut asset) = target {
        asset.forms = discovered_forms;
    }

    Ok((target, findings))
}

#[cfg(test)]
mod tests {
    use super::*;
    use gossan_core::{HostTarget, Protocol, ServiceTarget, WebAssetTarget};
    use url::Url;

    fn web_target() -> Target {
        Target::Web(Box::new(WebAssetTarget {
            url: Url::parse("https://example.com")
                .unwrap_or_else(|_| Url::parse("http://127.0.0.1").unwrap()),
            service: ServiceTarget {
                host: HostTarget {
                    ip: "127.0.0.1"
                        .parse()
                        .unwrap_or_else(|_| "127.0.0.1".parse().unwrap()),
                    domain: Some("example.com".into()),
                },
                port: 443,
                protocol: Protocol::Tcp,
                banner: None,
                tls: true,
            },
            tech: vec![],
            status: 200,
            title: None,
            favicon_hash: None,
            body_hash: None,
            forms: vec![],
            params: vec![],
        }))
    }

    #[test]
    fn scanner_metadata_is_stable() {
        let scanner = HeadlessScanner;
        assert_eq!(scanner.name(), "headless");
    }

    #[test]
    fn scanner_accepts_only_web_targets() {
        let scanner = HeadlessScanner;
        assert!(scanner.accepts(&web_target()));
        assert!(!scanner.accepts(&Target::Host(HostTarget {
            ip: "127.0.0.1"
                .parse()
                .unwrap_or_else(|_| "127.0.0.1".parse().unwrap()),
            domain: None,
        })));
    }

    #[test]
    fn browser_launch_routes_through_runtime_headless() {
        let opts = browser_launch_options();
        let expected = BrowserLaunchOptions::default_stealth();
        assert!(opts.headed);
        assert!(opts.no_sandbox);
        assert_eq!(opts.window_width, expected.window_width);
        assert_eq!(opts.window_height, expected.window_height);
        assert!(!opts.new_headless_mode);
        assert_eq!(opts.extra_args, expected.extra_args);
    }

    #[tokio::test]
    #[ignore = "W3-F009: headless Chromium launch >60s; run with cargo test -- --ignored"]
    async fn test_analyze_target_graceful_on_invalid_url() {
        let runtime = match BrowserRuntime::launch(&browser_launch_options()).await {
            Ok(r) => r,
            Err(_) => return,
        };
        let browser = runtime.browser();

        let mut target = web_target();
        if let Target::Web(ref mut asset) = target {
            asset.url = Url::parse("http://0.0.0.0:1").expect("Invalid URL");
        }
        let config = Config::default();

        let result = analyze_target(&browser, target, &config).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    #[ignore = "W3-F009: headless Chromium launch >60s; run with cargo test -- --ignored"]
    async fn test_analyze_target_with_incomplete_auth_does_not_panic() {
        let runtime = match BrowserRuntime::launch(&browser_launch_options()).await {
            Ok(r) => r,
            Err(_) => return,
        };
        let browser = runtime.browser();

        let target = web_target();
        let mut config = Config::default();
        config.auth_user = Some("admin".into());
        config.auth_pass = None; // Should skip login logic

        let _ = analyze_target(&browser, target, &config).await;
    }

    // ── Timeout math ──────────────────────────────────────────────────────

    #[test]
    fn new_page_timeout_is_15_seconds() {
        let d = std::time::Duration::from_secs(15);
        assert_eq!(d.as_secs(), 15);
    }

    #[test]
    fn goto_timeout_is_15_seconds() {
        let d = std::time::Duration::from_secs(15);
        assert_eq!(d.as_secs(), 15);
    }

    // ── Finding builder ───────────────────────────────────────────────────

    #[test]
    fn finding_builder_sets_correct_scanner_and_kind() {
        let target = web_target();
        let fb = finding_builder(&target, Severity::High, "title", "detail");
        let f = fb.build_or_log().expect("valid finding");
        assert_eq!(f.scanner(), "headless");
        assert_eq!(f.severity(), Severity::High);
    }

    // ── Hook JS safety ────────────────────────────────────────────────────

    #[test]
    fn hook_js_does_not_use_eval() {
        let hook_js = r#"
        (function() {
            window._santh_requests = [];
            
            // Hook Fetch, guard against environments where fetch is undefined
            // (e.g. CSP-blocked or very old browsers).
            if (typeof window.fetch === 'function') {
                const oldFetch = window.fetch;
                window.fetch = function() {
                    window._santh_requests.push({ url: arguments[0], type: 'fetch' });
                    return oldFetch.apply(this, arguments);
                };
            }

            // Hook XHR (guard against missing XMLHttpRequest).
            if (typeof XMLHttpRequest === 'function') {
                const oldOpen = XMLHttpRequest.prototype.open;
                XMLHttpRequest.prototype.open = function() {
                    window._santh_requests.push({ url: arguments[1], type: 'xhr' });
                    return oldOpen.apply(this, arguments);
                };
            }
        })();
    "#;
        assert!(
            !hook_js.to_lowercase().contains("eval("),
            "hook JS must not use eval() for CSP compatibility"
        );
        assert!(
            !hook_js.to_lowercase().contains("new function("),
            "hook JS must not use dynamic code execution"
        );
    }

    #[test]
    fn hook_js_guards_missing_fetch() {
        let hook_js = r#"
        (function() {
            window._santh_requests = [];
            
            // Hook Fetch, guard against environments where fetch is undefined
            // (e.g. CSP-blocked or very old browsers).
            if (typeof window.fetch === 'function') {
                const oldFetch = window.fetch;
                window.fetch = function() {
                    window._santh_requests.push({ url: arguments[0], type: 'fetch' });
                    return oldFetch.apply(this, arguments);
                };
            }

            // Hook XHR (guard against missing XMLHttpRequest).
            if (typeof XMLHttpRequest === 'function') {
                const oldOpen = XMLHttpRequest.prototype.open;
                XMLHttpRequest.prototype.open = function() {
                    window._santh_requests.push({ url: arguments[1], type: 'xhr' });
                    return oldOpen.apply(this, arguments);
                };
            }
        })();
    "#;
        assert!(
            hook_js.contains("typeof window.fetch === 'function'"),
            "hook JS must guard window.fetch before overwriting"
        );
    }

    #[test]
    fn hook_js_guards_missing_xhr() {
        let hook_js = r#"
        (function() {
            window._santh_requests = [];
            
            // Hook Fetch, guard against environments where fetch is undefined
            // (e.g. CSP-blocked or very old browsers).
            if (typeof window.fetch === 'function') {
                const oldFetch = window.fetch;
                window.fetch = function() {
                    window._santh_requests.push({ url: arguments[0], type: 'fetch' });
                    return oldFetch.apply(this, arguments);
                };
            }

            // Hook XHR (guard against missing XMLHttpRequest).
            if (typeof XMLHttpRequest === 'function') {
                const oldOpen = XMLHttpRequest.prototype.open;
                XMLHttpRequest.prototype.open = function() {
                    window._santh_requests.push({ url: arguments[1], type: 'xhr' });
                    return oldOpen.apply(this, arguments);
                };
            }
        })();
    "#;
        assert!(
            hook_js.contains("typeof XMLHttpRequest === 'function'"),
            "hook JS must guard XMLHttpRequest before overwriting"
        );
    }

    // ── URL parsing safety ────────────────────────────────────────────────

    #[test]
    fn web_target_url_parsing_roundtrips() {
        let t = web_target();
        if let Target::Web(asset) = t {
            assert_eq!(asset.url.host_str(), Some("example.com"));
            assert_eq!(asset.url.scheme(), "https");
        } else {
            panic!("expected Web target");
        }
    }

    // ── Tab cleanup contract (documented) ─────────────────────────────────

    #[test]
    fn page_close_is_called_in_all_branches() {
        // analyze_target closes the page with a timeout and logs failures.
        // This test documents the contract; full verification requires
        // browser integration tests which are gated behind --ignored.
        let js = analyze_target;
        // Simply assert the function symbol exists and has the expected signature.
        let _ = std::ptr::addr_of!(js);
    }

    #[tokio::test]
    #[ignore = "W3-F009: headless Chromium launch >60s; run with cargo test -- --ignored"]
    async fn headless_run_zero_concurrency_does_not_hang() {
        let scanner = HeadlessScanner;
        let mut config = Config::default();
        config.concurrency = 0;

        let (target_tx_in, target_rx_in) = tokio::sync::mpsc::channel::<Target>(64);
        let (live_tx, _live_rx) = tokio::sync::mpsc::channel::<gossan_core::Finding>(16384);
        let (target_tx, _target_rx) = tokio::sync::mpsc::channel::<Target>(64);
        let resolver = std::sync::Arc::new(gossan_core::net::build_resolver(&config).unwrap());
        let input = gossan_core::ScanInput {
            seed: "example.com".into(),
            target_rx: tokio::sync::Mutex::new(target_rx_in),
            live_tx,
            target_tx,
            resolver,
        };
        target_tx_in.send(web_target()).await.unwrap();
        drop(target_tx_in);

        let result = tokio::time::timeout(
            std::time::Duration::from_secs(120),
            scanner.run(input, &config),
        )
        .await;

        assert!(
            result.is_ok(),
            "HeadlessScanner::run with concurrency=0 should complete, not hang"
        );
    }
}