ghostwire 1.1.0

A Rust library to bypass Cloudflare anti-bot protections
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
//! Integration tests for ghostwire.
//!
//! These tests use `wiremock` to simulate Cloudflare challenge pages locally
//! without making real network requests.

use ghostwire::{
    Ghostwire, GhostwireBuilder,
    challenge::{
        JsInterpreter,
        turnstile::CloudflareTurnstile,
        v1::{CloudflareV1, V1ChallengeKind},
        v2::CloudflareV2,
        v3::{CloudflareV3, V3ChallengeData},
    },
    proxy_manager::{ProxyManager, RotationStrategy},
    stealth::{StealthConfig, StealthState},
    user_agent::{Browser, UserAgent, UserAgentOptions},
};

// ── User-Agent tests ──────────────────────────────────────────────────────────

#[test]
fn ua_chrome_desktop() {
    let opts = UserAgentOptions {
        browser: Some(Browser::Chrome),
        desktop: true,
        mobile: false,
        ..Default::default()
    };
    let ua = UserAgent::new(&opts).expect("Should build Chrome UA");
    assert!(
        ua.user_agent_string.contains("Chrome") || ua.user_agent_string.contains("Chromium"),
        "UA string should mention Chrome: {}",
        ua.user_agent_string
    );
    assert!(!ua.cipher_suite.is_empty(), "Should have cipher suites");
}

#[test]
fn ua_firefox_desktop() {
    let opts = UserAgentOptions {
        browser: Some(Browser::Firefox),
        desktop: true,
        mobile: false,
        ..Default::default()
    };
    let ua = UserAgent::new(&opts).expect("Should build Firefox UA");
    assert!(
        ua.user_agent_string.contains("Firefox"),
        "UA string should mention Firefox: {}",
        ua.user_agent_string
    );
}

#[test]
fn ua_custom_string() {
    let custom = "MyCustomBot/1.0".to_string();
    let opts = UserAgentOptions {
        custom: Some(custom.clone()),
        desktop: true,
        mobile: true,
        ..Default::default()
    };
    let ua = UserAgent::new(&opts).expect("Should build custom UA");
    assert_eq!(ua.user_agent_string, custom);
}

#[test]
fn ua_no_brotli_stripped() {
    let opts = UserAgentOptions {
        browser: Some(Browser::Chrome),
        desktop: true,
        mobile: false,
        allow_brotli: false,
        ..Default::default()
    };
    let ua = UserAgent::new(&opts).expect("Should build UA");
    assert!(
        !ua.headers.accept_encoding.contains("br"),
        "Accept-Encoding should not contain 'br' when allow_brotli=false: {}",
        ua.headers.accept_encoding
    );
}

#[test]
fn ua_brotli_kept_when_allowed() {
    let opts = UserAgentOptions {
        browser: Some(Browser::Chrome),
        desktop: true,
        mobile: false,
        allow_brotli: true,
        ..Default::default()
    };
    let ua = UserAgent::new(&opts).expect("Should build UA");
    assert!(
        ua.headers.accept_encoding.contains("br"),
        "Accept-Encoding should contain 'br' when allow_brotli=true: {}",
        ua.headers.accept_encoding
    );
}

// ── Proxy Manager tests ───────────────────────────────────────────────────────

#[test]
fn proxy_manager_sequential() {
    let mut pm = ProxyManager::new(
        vec![
            "http://proxy1:8080".to_string(),
            "http://proxy2:8080".to_string(),
            "http://proxy3:8080".to_string(),
        ],
        RotationStrategy::Sequential,
        300,
    );

    let p1 = pm.next_proxy().unwrap();
    let p2 = pm.next_proxy().unwrap();
    let _p3 = pm.next_proxy().unwrap();
    let p4 = pm.next_proxy().unwrap(); // wraps around

    assert_ne!(p1, p2);
    assert_eq!(p1, p4); // wrapped back to first
}

#[test]
fn proxy_manager_ban_and_recover() {
    let mut pm = ProxyManager::new(
        vec!["http://proxy1:8080".to_string()],
        RotationStrategy::Sequential,
        0, // ban duration 0 secs = effectively instant recovery
    );

    pm.report_failure("http://proxy1:8080");
    // With ban_secs=0 the proxy should be available immediately.
    let proxy = pm.next_proxy();
    assert!(
        proxy.is_some(),
        "Should recover immediately with 0 ban duration"
    );
}

#[test]
fn proxy_manager_empty() {
    let mut pm = ProxyManager::new(vec![], RotationStrategy::Sequential, 300);
    assert!(!pm.has_proxies());
    assert!(pm.next_proxy().is_none());
}

#[test]
fn proxy_format_roundtrip() {
    let proxy = ProxyManager::format_proxy("http://user:pass@host:8080");
    assert!(proxy.is_ok());
}

// ── Challenge detection tests ─────────────────────────────────────────────────

const CLOUDFLARE_SERVER: &str = "cloudflare";

fn cf_iuam_body() -> &'static str {
    r#"
    <html>
    <body>
    <img src="/cdn-cgi/images/trace/jsch/transparent.gif"/>
    <form id="challenge-form" action="/abc123/__cf_chl_f_tk=token456">
    <input name="r" value="token"/>
    <input name="jschl_vc" value="vc"/>
    <input name="pass" value="pass"/>
    </form>
    <script>
    setTimeout(function(){
    document.getElementById('challenge-form').submit();
    }, 4000);
    </script>
    </body>
    </html>
    "#
}

fn cf_captcha_body() -> &'static str {
    r#"
    <html>
    <body>
    <img src="/cdn-cgi/images/trace/captcha/transparent.gif"/>
    <form id="challenge-form" action="/abc123/__cf_chl_f_tk=token456">
    <input name="r" value="rtoken"/>
    <div class="h-captcha" data-sitekey="abc123def456ghi789jkl0123456789mnop4567"></div>
    </form>
    </body>
    </html>
    "#
}

fn cf_turnstile_body() -> &'static str {
    r#"
    <html>
    <body>
    <div class="cf-turnstile" data-sitekey="0x4AAAAAAADnPIDROrmt1Wwj"></div>
    <script src="https://challenges.cloudflare.com/turnstile/v0/api.js"></script>
    </body>
    </html>
    "#
}

fn cf_firewall_body() -> &'static str {
    r#"
    <html><body>
    <span class="cf-error-code">1020</span>
    </body></html>
    "#
}

#[test]
fn detect_iuam_challenge() {
    assert!(CloudflareV1::is_iuam_challenge(
        503,
        CLOUDFLARE_SERVER,
        cf_iuam_body()
    ));
    assert!(!CloudflareV1::is_iuam_challenge(
        200,
        CLOUDFLARE_SERVER,
        "<html></html>"
    ));
    assert!(!CloudflareV1::is_iuam_challenge(
        503,
        "nginx",
        cf_iuam_body()
    ));
}

#[test]
fn detect_captcha_challenge() {
    assert!(CloudflareV1::is_captcha_challenge(
        403,
        CLOUDFLARE_SERVER,
        cf_captcha_body()
    ));
    assert!(!CloudflareV1::is_captcha_challenge(
        200,
        CLOUDFLARE_SERVER,
        "<html></html>"
    ));
}

#[test]
fn detect_firewall_blocked() {
    assert!(CloudflareV1::is_firewall_blocked(
        403,
        CLOUDFLARE_SERVER,
        cf_firewall_body()
    ));
    assert!(!CloudflareV1::is_firewall_blocked(
        200,
        CLOUDFLARE_SERVER,
        "<html></html>"
    ));
}

#[test]
fn classify_returns_firewall_first() {
    let kind = CloudflareV1::classify(403, CLOUDFLARE_SERVER, cf_firewall_body());
    assert_eq!(kind, Some(V1ChallengeKind::Firewall1020));
}

#[test]
fn classify_returns_none_for_clean_page() {
    let kind = CloudflareV1::classify(200, "nginx", "<html><body>Hello</body></html>");
    assert!(kind.is_none());
}

#[test]
fn detect_turnstile_challenge() {
    assert!(CloudflareTurnstile::is_turnstile_challenge(
        403,
        CLOUDFLARE_SERVER,
        cf_turnstile_body()
    ));
    assert!(!CloudflareTurnstile::is_turnstile_challenge(
        200,
        "nginx",
        "<html></html>"
    ));
}

#[test]
fn extract_turnstile_site_key() {
    let key = CloudflareTurnstile::extract_site_key(cf_turnstile_body()).unwrap();
    assert_eq!(key, "0x4AAAAAAADnPIDROrmt1Wwj");
}

#[test]
fn extract_iuam_delay() {
    let delay = CloudflareV1::extract_delay(cf_iuam_body());
    assert_eq!(delay, Some(4.0));
}

#[test]
fn v2_detection() {
    let body = r#"cpo.src = '/cdn-cgi/challenge-platform/h/b/orchestrate/jsch/v1?ray=abc';"#;
    assert!(CloudflareV2::is_v2_js_challenge(
        503,
        CLOUDFLARE_SERVER,
        body
    ));
}

#[test]
fn v3_detection() {
    let body = r#"window._cf_chl_ctx = {"cvId": "abc"};"#;
    assert!(CloudflareV3::is_v3_challenge(503, CLOUDFLARE_SERVER, body));
}

// ── Builder / scraper construction tests ─────────────────────────────────────

#[test]
fn build_default_scraper() {
    let ghostwire = Ghostwire::new();
    assert!(
        ghostwire.is_ok(),
        "Default ghostwire should build successfully"
    );
}

#[test]
fn build_with_custom_ua() {
    let opts = UserAgentOptions {
        custom: Some("TestBot/1.0".to_string()),
        desktop: true,
        mobile: true,
        ..Default::default()
    };
    let ghostwire = GhostwireBuilder::new().user_agent_opts(opts).build();
    assert!(ghostwire.is_ok());
}

#[test]
fn build_with_stealth_disabled() {
    let stealth = StealthConfig {
        enabled: false,
        ..Default::default()
    };
    let ghostwire = GhostwireBuilder::new().stealth(stealth).build();
    assert!(ghostwire.is_ok());
}

// ── Stealth mode tests ────────────────────────────────────────────────────────

#[test]
fn stealth_adds_chrome_quirk_headers() {
    use reqwest::header::HeaderMap;
    let config = StealthConfig {
        enabled: true,
        browser_quirks: true,
        ..Default::default()
    };
    let state = StealthState::new(config);
    let ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0";
    let mut headers = HeaderMap::new();
    state.apply_to_headers(&mut headers, ua);
    assert!(
        headers.contains_key("sec-ch-ua"),
        "Should inject sec-ch-ua for Chrome UA"
    );
}

#[test]
fn stealth_adds_firefox_quirk_headers() {
    use reqwest::header::HeaderMap;
    let config = StealthConfig {
        enabled: true,
        browser_quirks: true,
        ..Default::default()
    };
    let state = StealthState::new(config);
    let ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0";
    let mut headers = HeaderMap::new();
    state.apply_to_headers(&mut headers, ua);
    assert!(
        headers.contains_key("upgrade-insecure-requests"),
        "Should inject Upgrade-Insecure-Requests for Firefox UA"
    );
}

#[test]
fn stealth_disabled_no_headers_added() {
    use reqwest::header::HeaderMap;
    let config = StealthConfig {
        enabled: false,
        ..Default::default()
    };
    let state = StealthState::new(config);
    let mut headers = HeaderMap::new();
    state.apply_to_headers(&mut headers, "SomeBot/1.0");
    assert!(
        headers.is_empty(),
        "Disabled stealth should not add any headers"
    );
}

// ── V3 challenge data extraction tests ───────────────────────────────────────

fn cf_v3_body_full() -> &'static str {
    r#"
    <html><head></head><body>
    <script>
    cpo.src = '/cdn-cgi/challenge-platform/h/b/orchestrate/jsch/v3?ray=abc';
    </script>
    <script>
    window._cf_chl_ctx = {"cvId":"cv-abc-123","chType":"jsch","cZone":"example.com"};
    window._cf_chl_opt = {"chlPageData":"page-data-xyz","cvId":"cv-abc-123"};
    </script>
    <form id="challenge-form" action="/cdn-cgi/challenge-platform/h/b/flow/ov1/0123456789/__cf_chl_rt_tk=TOKEN123">
    <input type="hidden" name="r" value="r-token-value"/>
    <input type="hidden" name="cf_chl_seq_df" value="seq-value"/>
    </form>
    <script>
    window._cf_chl_enter = function(){};
    window._cf_chl_answer = '42';
    </script>
    </body></html>
    "#
}

fn cf_v3_body_ctx_only() -> &'static str {
    r#"
    <html><body>
    <script>window._cf_chl_ctx = {"cvId":"ctx-only-id"};</script>
    <form id="challenge-form" action="/challenge?__cf_chl_rt_tk=TOK">
    <input name="r" value="r-val"/>
    </form>
    </body></html>
    "#
}

fn cf_v3_body_platform() -> &'static str {
    r#"
    <html><body>
    <script>cpo.src = '/cdn-cgi/challenge-platform/h/b/orchestrate/jsch/v3?ray=xyz';</script>
    <form id="challenge-form" action="/cf?__cf_chl_rt_tk=T">
    <input name="r" value="rv"/>
    </form>
    </body></html>
    "#
}

#[test]
fn v3_detection_via_ctx() {
    assert!(CloudflareV3::is_v3_challenge(
        503,
        CLOUDFLARE_SERVER,
        cf_v3_body_ctx_only()
    ));
}

#[test]
fn v3_detection_via_platform_script() {
    assert!(CloudflareV3::is_v3_challenge(
        503,
        CLOUDFLARE_SERVER,
        cf_v3_body_platform()
    ));
}

#[test]
fn v3_detection_via_form_rt_tk() {
    let body = r#"<form id="challenge-form" action="/x?__cf_chl_rt_tk=T"><input name="r" value="v"/></form>"#;
    assert!(CloudflareV3::is_v3_challenge(403, CLOUDFLARE_SERVER, body));
}

#[test]
fn v3_not_detected_on_clean_page() {
    assert!(!CloudflareV3::is_v3_challenge(
        200,
        CLOUDFLARE_SERVER,
        "<html><body>Hello</body></html>"
    ));
}

#[test]
fn v3_not_detected_on_non_cloudflare_server() {
    assert!(!CloudflareV3::is_v3_challenge(
        503,
        "nginx",
        cf_v3_body_ctx_only()
    ));
}

#[test]
fn v3_extract_ctx_json() {
    let data = CloudflareV3::extract_challenge_data(cf_v3_body_full());
    assert_eq!(
        data.ctx.get("cvId").and_then(|v| v.as_str()),
        Some("cv-abc-123")
    );
    assert_eq!(
        data.ctx.get("chType").and_then(|v| v.as_str()),
        Some("jsch")
    );
}

#[test]
fn v3_extract_opt_json() {
    let data = CloudflareV3::extract_challenge_data(cf_v3_body_full());
    assert_eq!(
        data.opt.get("chlPageData").and_then(|v| v.as_str()),
        Some("page-data-xyz")
    );
}

#[test]
fn v3_extract_form_action() {
    let data = CloudflareV3::extract_challenge_data(cf_v3_body_full());
    assert!(
        data.form_action
            .as_deref()
            .unwrap_or("")
            .contains("__cf_chl_rt_tk"),
        "form_action should contain the rt_tk token"
    );
}

#[test]
fn v3_extract_vm_script() {
    let data = CloudflareV3::extract_challenge_data(cf_v3_body_full());
    assert!(
        data.vm_script.is_some(),
        "should extract the VM script block"
    );
    assert!(
        data.vm_script.as_deref().unwrap().contains("_cf_chl_enter"),
        "vm_script should contain _cf_chl_enter"
    );
}

#[test]
fn v3_extract_missing_ctx_defaults_to_null() {
    let body = r#"<form id="challenge-form" action="/x?__cf_chl_rt_tk=T"></form>"#;
    let data = CloudflareV3::extract_challenge_data(body);
    assert!(
        data.ctx.is_null(),
        "missing ctx should default to JSON null"
    );
}

#[test]
fn v3_build_payload_extracts_r_token() {
    let payload = CloudflareV3::build_payload(cf_v3_body_full(), "test-answer")
        .expect("build_payload should succeed");
    let r = payload
        .iter()
        .find(|(k, _)| k == "r")
        .map(|(_, v)| v.as_str());
    assert_eq!(r, Some("r-token-value"));
}

#[test]
fn v3_build_payload_contains_answer() {
    let payload = CloudflareV3::build_payload(cf_v3_body_full(), "my-answer")
        .expect("build_payload should succeed");
    let answer = payload
        .iter()
        .find(|(k, _)| k == "jschl_answer")
        .map(|(_, v)| v.as_str());
    assert_eq!(answer, Some("my-answer"));
}

#[test]
fn v3_build_payload_includes_extra_inputs() {
    let payload = CloudflareV3::build_payload(cf_v3_body_full(), "ans")
        .expect("build_payload should succeed");
    let has_seq = payload
        .iter()
        .any(|(k, v)| k == "cf_chl_seq_df" && v == "seq-value");
    assert!(has_seq, "payload should include extra hidden inputs");
}

#[test]
fn v3_build_payload_missing_r_token_errors() {
    let body = "<html><body>no form here</body></html>";
    assert!(
        CloudflareV3::build_payload(body, "ans").is_err(),
        "missing r token should return an error"
    );
}

#[test]
fn v3_resolve_url_absolute_passthrough() {
    let resolved =
        CloudflareV3::resolve_url("https://example.com/page", "https://other.com/challenge")
            .unwrap();
    assert_eq!(resolved, "https://other.com/challenge");
}

#[test]
fn v3_resolve_url_relative_action() {
    let resolved = CloudflareV3::resolve_url(
        "https://example.com/page",
        "/cdn-cgi/challenge-platform/flow?__cf_chl_rt_tk=T",
    )
    .unwrap();
    assert!(
        resolved.starts_with("https://example.com"),
        "resolved URL should use original scheme+host: {resolved}"
    );
    assert!(resolved.contains("__cf_chl_rt_tk"));
}

// ── V3 fallback answer tests ──────────────────────────────────────────────────

#[test]
fn v3_fallback_uses_page_data_hash() {
    let mut data = V3ChallengeData::default();
    data.opt = serde_json::json!({"chlPageData": "some-page-data"});
    let a1 = CloudflareV3::generate_fallback_answer(&data);
    let a2 = CloudflareV3::generate_fallback_answer(&data);
    // Same input → same deterministic output.
    assert_eq!(
        a1, a2,
        "fallback should be deterministic for same page data"
    );
    // Result must be purely numeric.
    assert!(
        a1.chars().all(|c| c.is_ascii_digit()),
        "answer must be numeric: {a1}"
    );
}

#[test]
fn v3_fallback_uses_cv_id_when_no_page_data() {
    let mut data = V3ChallengeData::default();
    data.ctx = serde_json::json!({"cvId": "some-cv-id"});
    let a = CloudflareV3::generate_fallback_answer(&data);
    assert!(
        a.chars().all(|c| c.is_ascii_digit()),
        "answer must be numeric: {a}"
    );
}

#[test]
fn v3_fallback_random_when_no_data() {
    let data = V3ChallengeData::default();
    let a = CloudflareV3::generate_fallback_answer(&data);
    // Should be a 6-digit number (100000–999999).
    assert!(
        a.chars().all(|c| c.is_ascii_digit()),
        "answer must be numeric: {a}"
    );
    let n: u64 = a.parse().unwrap();
    assert!(
        (100_000..=999_999).contains(&n),
        "random fallback should be 6 digits: {n}"
    );
}

#[test]
fn v3_fallback_page_data_beats_cv_id() {
    // When both are present, chlPageData takes priority.
    let mut data = V3ChallengeData::default();
    data.opt = serde_json::json!({"chlPageData": "pd"});
    data.ctx = serde_json::json!({"cvId": "cv"});
    let with_both = CloudflareV3::generate_fallback_answer(&data);

    let mut only_page = V3ChallengeData::default();
    only_page.opt = serde_json::json!({"chlPageData": "pd"});
    let with_page_only = CloudflareV3::generate_fallback_answer(&only_page);

    assert_eq!(
        with_both, with_page_only,
        "chlPageData should take priority over cvId"
    );
}

// ── V3 execute_vm_challenge tests ─────────────────────────────────────────────

/// Returns true when the named binary exists somewhere in PATH.
fn have_binary(bin: &str) -> bool {
    std::env::var_os("PATH")
        .map(|p| std::env::split_paths(&p).any(|dir| dir.join(bin).is_file()))
        .unwrap_or(false)
}

#[test]
fn v3_execute_vm_falls_back_when_no_vm_script() {
    // No vm_script → must fall back to heuristic, never panic.
    let mut data = V3ChallengeData::default();
    data.ctx = serde_json::json!({"cvId": "fallback-cv"});
    let answer = CloudflareV3::execute_vm_challenge(&data, "example.com", &JsInterpreter::None);
    assert!(
        answer.chars().all(|c| c.is_ascii_digit()),
        "fallback answer must be numeric: {answer}"
    );
}

#[test]
fn v3_execute_vm_interp_none_uses_fallback() {
    let mut data = V3ChallengeData::default();
    data.vm_script = Some("window._cf_chl_answer = 'should-not-appear';".into());
    data.ctx = serde_json::json!({"cvId": "cv-id-here"});
    // JsInterpreter::None → skips JS → falls back to cvId hash.
    let answer = CloudflareV3::execute_vm_challenge(&data, "example.com", &JsInterpreter::None);
    assert!(
        answer.chars().all(|c| c.is_ascii_digit()),
        "with None interpreter answer must be numeric: {answer}"
    );
}

#[test]
fn v3_execute_vm_with_node() {
    if !have_binary("node") {
        eprintln!("skipping v3_execute_vm_with_node: node not in PATH");
        return;
    }
    let mut data = V3ChallengeData::default();
    // vm_script sets the answer directly so we know what to expect.
    data.vm_script = Some("window._cf_chl_answer = 'node-vm-42';".into());
    data.ctx = serde_json::json!({});
    data.opt = serde_json::json!({});
    let answer = CloudflareV3::execute_vm_challenge(&data, "example.com", &JsInterpreter::Node);
    assert_eq!(answer, "node-vm-42", "node should extract the VM answer");
}

#[test]
fn v3_execute_vm_with_bun() {
    if !have_binary("bun") {
        eprintln!("skipping v3_execute_vm_with_bun: bun not in PATH");
        return;
    }
    let mut data = V3ChallengeData::default();
    data.vm_script = Some("window._cf_chl_answer = 'bun-vm-99';".into());
    data.ctx = serde_json::json!({});
    data.opt = serde_json::json!({});
    let answer = CloudflareV3::execute_vm_challenge(&data, "example.com", &JsInterpreter::Bun);
    assert_eq!(answer, "bun-vm-99", "bun should extract the VM answer");
}

#[cfg(feature = "js-boa")]
#[test]
fn v3_execute_vm_with_boa() {
    let mut data = V3ChallengeData::default();
    data.vm_script = Some("window._cf_chl_answer = 'boa-vm-7';".into());
    data.ctx = serde_json::json!({});
    data.opt = serde_json::json!({});
    let answer = CloudflareV3::execute_vm_challenge(&data, "example.com", &JsInterpreter::Boa);
    assert_eq!(answer, "boa-vm-7", "boa should extract the VM answer");
}

#[cfg(feature = "js-v8")]
#[test]
fn v3_execute_vm_with_v8() {
    let mut data = V3ChallengeData::default();
    data.vm_script = Some("window._cf_chl_answer = 'v8-vm-3';".into());
    data.ctx = serde_json::json!({});
    data.opt = serde_json::json!({});
    let answer = CloudflareV3::execute_vm_challenge(&data, "example.com", &JsInterpreter::V8);
    assert_eq!(answer, "v8-vm-3", "v8 should extract the VM answer");
}

#[test]
fn v3_execute_vm_ctx_accessible_from_script() {
    if !have_binary("node") {
        eprintln!("skipping: node not in PATH");
        return;
    }
    let mut data = V3ChallengeData::default();
    // The script reads back the injected cvId from window._cf_chl_ctx.
    data.vm_script = Some("window._cf_chl_answer = window._cf_chl_ctx.cvId;".into());
    data.ctx = serde_json::json!({"cvId": "injected-cv-id"});
    data.opt = serde_json::json!({});
    let answer = CloudflareV3::execute_vm_challenge(&data, "example.com", &JsInterpreter::Node);
    assert_eq!(
        answer, "injected-cv-id",
        "ctx should be accessible from the VM script"
    );
}

#[test]
fn v3_execute_vm_opt_accessible_from_script() {
    if !have_binary("node") {
        eprintln!("skipping: node not in PATH");
        return;
    }
    let mut data = V3ChallengeData::default();
    data.vm_script = Some("window._cf_chl_answer = window._cf_chl_opt.chlPageData;".into());
    data.ctx = serde_json::json!({});
    data.opt = serde_json::json!({"chlPageData": "injected-page-data"});
    let answer = CloudflareV3::execute_vm_challenge(&data, "example.com", &JsInterpreter::Node);
    assert_eq!(
        answer, "injected-page-data",
        "opt should be accessible from the VM script"
    );
}

#[test]
fn v3_execute_vm_crashing_script_falls_back() {
    if !have_binary("node") {
        eprintln!("skipping: node not in PATH");
        return;
    }
    let mut data = V3ChallengeData::default();
    // Deliberately broken JS that will cause node to exit non-zero.
    data.vm_script = Some("this is not valid javascript !!!".into());
    data.ctx = serde_json::json!({"cvId": "crash-cv"});
    data.opt = serde_json::json!({});
    // Must not panic; must return a numeric heuristic answer.
    let answer = CloudflareV3::execute_vm_challenge(&data, "example.com", &JsInterpreter::Node);
    assert!(
        answer.chars().all(|c| c.is_ascii_digit()),
        "crashing script should fall back to numeric heuristic: {answer}"
    );
}

// ── GhostwireBuilder js_interpreter field ────────────────────────────────────

#[test]
fn builder_default_interpreter_is_auto() {
    // Confirm the default is Auto so existing users are unaffected.
    let b = GhostwireBuilder::new();
    assert_eq!(b.js_interpreter, JsInterpreter::Auto);
}

#[test]
fn builder_interpreter_can_be_set() {
    for interp in [
        JsInterpreter::None,
        JsInterpreter::Node,
        JsInterpreter::Bun,
        JsInterpreter::Boa,
        JsInterpreter::V8,
        JsInterpreter::Auto,
    ] {
        let b = GhostwireBuilder::new().js_interpreter(interp.clone());
        assert_eq!(b.js_interpreter, interp);
    }
}

#[test]
fn build_with_node_interpreter() {
    let g = GhostwireBuilder::new()
        .js_interpreter(JsInterpreter::Node)
        .build();
    assert!(g.is_ok(), "should build with Node interpreter");
}

#[test]
fn build_with_none_interpreter() {
    let g = GhostwireBuilder::new()
        .js_interpreter(JsInterpreter::None)
        .build();
    assert!(g.is_ok(), "should build with None interpreter");
}