bun_runtime 0.1.0

Bao runtime integration — JS engine + Bun API + event loop
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
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
// @trace REQ-STL-001 [entity:StealthHttpAgent] REQ-STL-002
// Stealth-aware HTTP request configuration.
// Applies HTTP/2 header ordering and User-Agent injection from StealthProfile.
// Actual HTTP execution is delegated to crate::http_client::http_request().

// Re-export StealthProfile so callers can refer to it as
// `crate::stealth_http::StealthProfile`, matching the public surface of this
// module (whose functions already take `&Option<StealthProfile>`).
// @trace REQ-STL-001 [entity:StealthProfile re-export]
pub use bao_stealth::StealthProfile;
use bao_stealth::{Http2Fingerprint, PriorityFrameMode, TlsFingerprint, TlsFingerprintConfig};
use bun_http::Method;
use bun_http::ssl_config::SSLConfig;
use bytes::Bytes;
use compact_str::CompactString;
use smallvec::SmallVec;

/// Configuration for a stealth-aware HTTP request.
/// Produced by `create_stealth_request()`, consumed by callers that
/// delegate to `crate::http_client::http_request()`.
pub struct StealthRequestConfig {
    pub method: Method,
    pub url: String,
    pub headers: Vec<(String, String)>,
    pub body: Option<Vec<u8>>,
    pub user_agent: Option<String>,
}

/// Create a stealth-aware request configuration.
/// Applies HTTP/2 header ordering from the profile and injects User-Agent.
pub fn create_stealth_request(
    profile: &Option<StealthProfile>,
    method: Method,
    url: &str,
    headers: &[(String, String)],
    body: Option<&[u8]>,
) -> StealthRequestConfig {
    let ordered = ordered_headers(profile, headers);
    let mut final_headers: Vec<(String, String)> = ordered
        .into_iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();

    let user_agent = profile.as_ref().map(|p| {
        let ua = p.navigator.user_agent.clone();
        final_headers.push(("user-agent".to_string(), ua.clone()));
        ua
    });

    StealthRequestConfig {
        method,
        url: url.to_string(),
        headers: final_headers,
        body: body.map(|b| b.to_vec()),
        user_agent,
    }
}

/// Owned HTTP response from a stealth-aware request.
pub struct StealthSyncResult {
    pub status_code: u32,
    pub status_text: CompactString,
    pub headers: SmallVec<[(CompactString, CompactString); 8]>,
    pub body: Bytes,
}

/// Perform a synchronous HTTP request with optional stealth fingerprint injection.
// @trace REQ-STL-001 REQ-STL-002
pub fn stealth_http_request(
    profile: &Option<StealthProfile>,
    method: Method,
    url: &str,
    headers: &[(String, String)],
    body: Option<&[u8]>,
) -> Result<StealthSyncResult, String> {
    let config = create_stealth_request(profile, method, url, headers, body);
    let result = crate::http_client::http_request(
        config.method,
        &config.url,
        &config.headers,
        config.body.as_deref(),
    )?;
    Ok(StealthSyncResult {
        status_code: result.status_code,
        status_text: result.status_text,
        headers: result.headers,
        body: result.body,
    })
}

// ---------------------------------------------------------------------------
// TLS fingerprint helpers (pure, no network I/O)
// ---------------------------------------------------------------------------

/// Build an `SSLConfig` with TLS fingerprint fields populated from a `StealthProfile`.
/// Returns a default `SSLConfig` (no fingerprint) when profile is `None`.
///
/// The caller owns the returned `SSLConfig`. To get h2 connection coalescing
/// / keep-alive pool reuse, wrap it with `ssl_config::GlobalRegistry::intern`
/// (not `SharedPtr::new`) — bun_http pool keys compare the interned config
/// pointer, so a fresh allocation per request defeats connection reuse.
/// When the config is dropped, its C-string fields are freed via `deinit`.
// @trace REQ-STL-001
pub fn stealth_profile_to_ssl_config(profile: &Option<StealthProfile>) -> SSLConfig {
    let mut config = SSLConfig::default();
    if let Some(p) = profile {
        let tls_cfg = TlsFingerprintConfig::from_fingerprint(&p.tls);
        config.tls12_cipher_list = bun_core::dupe_z(tls_cfg.tls12_cipher_list.as_bytes());
        config.tls13_cipher_suites = bun_core::dupe_z(tls_cfg.tls13_cipher_suites.as_bytes());
        config.tls_curves_list = bun_core::dupe_z(tls_cfg.curves_list.as_bytes());
        config.tls_sigalgs_list = bun_core::dupe_z(tls_cfg.sigalgs_list.as_bytes());
        // HTTP/2 fingerprint: binary wire format SETTINGS + window size
        // Flows through SSLConfig → ClientSession → write_preface() naturally
        config.h2_settings_payload = Some(h2_settings_wire_format(&p.http2).into_boxed_slice());
        config.h2_initial_window_size = p.http2.initial_window_size;
        // REQ-STL-002: pseudo-header wire order (Firefox/Chrome differ) and
        // REQ-STL-002-C3: connection-setup PRIORITY frames (Firefox-only).
        // Same SSLConfig → ClientSession channel as the SETTINGS payload.
        config.h2_pseudo_header_order = Some(
            p.http2
                .pseudo_header_order
                .iter()
                .map(|name| name.to_string().into_boxed_str())
                .collect(),
        );
        config.h2_priority_frames = Some(
            p.http2
                .priority_frames
                .iter()
                .map(|f| bun_http::ssl_config::H2PriorityFrame {
                    stream_id: f.stream_id,
                    stream_dependency: f.stream_dependency,
                    exclusive: f.exclusive,
                    weight: f.weight,
                })
                .collect(),
        );
    }
    config
}

// IANA→OpenSSL cipher name resolution lives in `bao_stealth::tls` (single
// source of truth) — the former local `tls_cipher_name`/`cipher_list_string`
// copies here had diverged (wrong names for 0xC009/0x0033/0x0067) and were
// removed; use `bao_stealth::{cipher_suite_openssl_name,
// boringssl_cipher_list_string}` instead.

#[allow(dead_code)]
fn alpn_wire_format(fp: &TlsFingerprint) -> Vec<u8> {
    let mut wire = Vec::new();
    for proto in &fp.alpn_protocols {
        let len = proto.len().min(255) as u8;
        wire.push(len);
        wire.extend_from_slice(&proto[..len as usize]);
    }
    wire
}

// ---------------------------------------------------------------------------
// HTTP/2 fingerprint helpers
// ---------------------------------------------------------------------------

/// Determine ALPN offer preference from HTTP/2 fingerprint.
// @trace REQ-STL-002
pub fn h2_alpn_offer(fp: &Http2Fingerprint) -> &'static str {
    if fp.pseudo_header_order.is_empty() {
        "http/1.1"
    } else {
        "h2,http/1.1"
    }
}

#[allow(dead_code)]
fn h2_settings_wire_format(fp: &Http2Fingerprint) -> Vec<u8> {
    let settings = fp.settings_frame_payload();
    let mut wire = Vec::with_capacity(settings.len() * 6);
    for (id, value) in &settings {
        wire.extend_from_slice(&id.to_be_bytes());
        wire.extend_from_slice(&value.to_be_bytes());
    }
    wire
}

// ---------------------------------------------------------------------------
// Diagnostic helpers (pure, no network I/O)
// ---------------------------------------------------------------------------

pub fn ordered_headers<'a>(
    profile: &Option<StealthProfile>,
    headers: &'a [(String, String)],
) -> Vec<(&'a str, &'a str)> {
    let refs: Vec<(&'a str, &'a str)> = headers
        .iter()
        .map(|(k, v)| (k.as_str(), v.as_str()))
        .collect();
    match profile {
        Some(p) => p.http2.ordered_headers(&refs),
        None => refs,
    }
}

pub fn ja3_hash(profile: &Option<StealthProfile>) -> Option<String> {
    profile.as_ref().map(|p| p.tls.compute_ja3())
}

pub fn akamai_fingerprint(profile: &Option<StealthProfile>) -> Option<String> {
    profile.as_ref().map(|p| p.http2.akamai_fingerprint())
}

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

    #[test]
    fn test_create_stealth_request_no_profile() {
        let config = create_stealth_request(&None, Method::GET, "https://example.com", &[], None);
        assert_eq!(config.method.as_str(), "GET");
        assert!(config.user_agent.is_none());
    }

    #[test]
    fn test_create_stealth_request_firefox() {
        let profile = StealthProfile::firefox_default();
        let config = create_stealth_request(
            &Some(profile),
            Method::POST,
            "https://example.com",
            &[],
            Some(b"test"),
        );
        assert_eq!(config.method.as_str(), "POST");
        assert!(config.user_agent.is_some());
    }

    #[test]
    fn test_create_stealth_request_chrome() {
        let profile = StealthProfile::chrome_default();
        let config = create_stealth_request(
            &Some(profile),
            Method::GET,
            "https://example.com",
            &[],
            None,
        );
        assert!(config.user_agent.is_some());
    }

    #[test]
    fn test_ordered_headers_no_profile() {
        let headers = vec![
            ("content-type".to_string(), "text/html".to_string()),
            (":method".to_string(), "GET".to_string()),
        ];
        let ordered = ordered_headers(&None, &headers);
        assert_eq!(ordered.len(), 2);
        assert_eq!(ordered[0].0, "content-type");
    }

    #[test]
    fn test_ordered_headers_firefox_pseudo_first() {
        let profile = StealthProfile::firefox_default();
        let headers = vec![
            ("content-length".to_string(), "100".to_string()),
            (":method".to_string(), "GET".to_string()),
            (":path".to_string(), "/".to_string()),
            (":authority".to_string(), "example.com".to_string()),
            (":scheme".to_string(), "https".to_string()),
        ];
        let ordered = ordered_headers(&Some(profile), &headers);
        assert!(ordered[0].0.starts_with(':'));
        assert!(ordered[1].0.starts_with(':'));
    }

    #[test]
    fn test_ordered_headers_chrome_order() {
        let profile = StealthProfile::chrome_default();
        let headers = vec![
            ("accept".to_string(), "*/*".to_string()),
            (":method".to_string(), "GET".to_string()),
            (":authority".to_string(), "example.com".to_string()),
            (":scheme".to_string(), "https".to_string()),
            (":path".to_string(), "/".to_string()),
        ];
        let ordered = ordered_headers(&Some(profile), &headers);
        assert_eq!(ordered[0].0, ":method");
        assert_eq!(ordered[1].0, ":authority");
        assert_eq!(ordered[2].0, ":scheme");
        assert_eq!(ordered[3].0, ":path");
    }

    #[test]
    fn test_ja3_hash_none() {
        assert!(ja3_hash(&None).is_none());
    }

    #[test]
    fn test_ja3_hash_firefox() {
        let profile = StealthProfile::firefox_default();
        let hash = ja3_hash(&Some(profile)).unwrap();
        assert!(hash.starts_with("771,"));
    }

    #[test]
    fn test_ja3_hash_chrome() {
        let profile = StealthProfile::chrome_default();
        let hash = ja3_hash(&Some(profile)).unwrap();
        assert!(hash.starts_with("771,"));
    }

    #[test]
    fn test_akamai_fingerprint_none() {
        assert!(akamai_fingerprint(&None).is_none());
    }

    #[test]
    fn test_akamai_fingerprint_firefox() {
        let profile = StealthProfile::firefox_default();
        let fp = akamai_fingerprint(&Some(profile)).unwrap();
        let parts: Vec<&str> = fp.split(':').collect();
        assert_eq!(parts.len(), 6);
    }

    #[test]
    fn test_akamai_fingerprint_chrome() {
        let profile = StealthProfile::chrome_default();
        let fp = akamai_fingerprint(&Some(profile)).unwrap();
        let parts: Vec<&str> = fp.split(':').collect();
        assert_eq!(parts.len(), 6);
    }

    #[test]
    fn test_profiles_different_ja3() {
        let ff = StealthProfile::firefox_default();
        let ch = StealthProfile::chrome_default();
        assert_ne!(ja3_hash(&Some(ff)).unwrap(), ja3_hash(&Some(ch)).unwrap());
    }

    #[test]
    fn test_profiles_different_akamai() {
        let ff = StealthProfile::firefox_default();
        let ch = StealthProfile::chrome_default();
        assert_ne!(
            akamai_fingerprint(&Some(ff)).unwrap(),
            akamai_fingerprint(&Some(ch)).unwrap()
        );
    }

    #[test]
    fn test_h2_alpn_offer_with_h2() {
        let profile = StealthProfile::firefox_default();
        let offer = h2_alpn_offer(&profile.http2);
        assert!(offer.contains("h2"));
    }

    #[test]
    fn test_h2_alpn_offer_without_h2() {
        let empty_fp = Http2Fingerprint {
            header_table_size: 65536,
            enable_push: false,
            max_concurrent_streams: 100,
            initial_window_size: 65535,
            max_frame_size: 16384,
            max_header_list_size: 65536,
            window_update_size: 65535,
            pseudo_header_order: vec![],
            priority_frame_mode: PriorityFrameMode::None,
            priority_frames: vec![],
        };
        let offer = h2_alpn_offer(&empty_fp);
        assert_eq!(offer, "http/1.1");
    }

    #[test]
    fn test_alpn_wire_firefox() {
        let profile = StealthProfile::firefox_default();
        let wire = alpn_wire_format(&profile.tls);
        assert!(!wire.is_empty());
    }

    #[test]
    fn test_h2_settings_wire_firefox() {
        let profile = StealthProfile::firefox_default();
        let wire = h2_settings_wire_format(&profile.http2);
        assert_eq!(wire.len(), 36);
    }

    #[test]
    fn test_h2_settings_wire_chrome() {
        let profile = StealthProfile::chrome_default();
        let wire = h2_settings_wire_format(&profile.http2);
        assert_eq!(wire.len(), 36);
    }

    // ─── stealth_http extended edge case tests ────────────────
    // @trace REQ-STL-001 [req:REQ-STL-001] [level:unit]

    #[test]
    fn test_create_stealth_request_with_headers() {
        let config = create_stealth_request(
            &None,
            Method::POST,
            "https://api.example.com",
            &[("content-type".into(), "application/json".into())],
            Some(b"{}"),
        );
        assert_eq!(config.headers.len(), 1);
        assert_eq!(config.headers[0].0, "content-type");
        assert_eq!(config.body.as_deref(), Some(b"{}" as &[u8]));
    }

    #[test]
    fn test_create_stealth_request_firefox_adds_ua() {
        let profile = StealthProfile::firefox_default();
        let config =
            create_stealth_request(&Some(profile), Method::GET, "https://x.com", &[], None);
        // Should have the user-agent appended to headers
        let has_ua = config.headers.iter().any(|(k, _)| k == "user-agent");
        assert!(has_ua, "Firefox profile must add user-agent header");
        assert!(config.user_agent.is_some());
    }

    #[test]
    fn test_create_stealth_request_chrome_adds_ua() {
        let profile = StealthProfile::chrome_default();
        let config =
            create_stealth_request(&Some(profile), Method::GET, "https://x.com", &[], None);
        let has_ua = config.headers.iter().any(|(k, _)| k == "user-agent");
        assert!(has_ua, "Chrome profile must add user-agent header");
    }

    #[test]
    fn test_ordered_headers_empty() {
        let ordered = ordered_headers(&None, &[]);
        assert!(ordered.is_empty());
    }

    #[test]
    fn test_ordered_headers_no_profile_preserves_order() {
        let headers = vec![
            ("z-header".to_string(), "last".to_string()),
            ("a-header".to_string(), "first".to_string()),
        ];
        let ordered = ordered_headers(&None, &headers);
        assert_eq!(ordered.len(), 2);
        assert_eq!(ordered[0].0, "z-header"); // no reorder without profile
        assert_eq!(ordered[1].0, "a-header");
    }

    #[test]
    fn test_stealth_sync_result_construction() {
        let result = StealthSyncResult {
            status_code: 200,
            status_text: CompactString::new("OK"),
            headers: smallvec::smallvec![("content-type".into(), "text/html".into())],
            body: Bytes::from_static(b"<html>"),
        };
        assert_eq!(result.status_code, 200);
        assert_eq!(result.status_text, "OK");
        assert_eq!(result.headers.len(), 1);
        assert_eq!(&result.body[..], b"<html>");
    }

    #[test]
    fn test_stealth_sync_result_empty() {
        let result = StealthSyncResult {
            status_code: 204,
            status_text: CompactString::new("No Content"),
            headers: SmallVec::new(),
            body: Bytes::new(),
        };
        assert!(result.headers.is_empty());
        assert!(result.body.is_empty());
    }

    #[test]
    fn test_h2_alpn_offer_firefox() {
        let profile = StealthProfile::firefox_default();
        let offer = h2_alpn_offer(&profile.http2);
        assert!(offer.contains("h2"), "Firefox should offer h2");
        assert!(
            offer.contains("http/1.1"),
            "Firefox should fallback to http/1.1"
        );
    }

    #[test]
    fn test_h2_alpn_offer_chrome() {
        let profile = StealthProfile::chrome_default();
        let offer = h2_alpn_offer(&profile.http2);
        assert!(offer.contains("h2"), "Chrome should offer h2");
    }

    #[test]
    fn test_ja3_hash_firefox_chrome_differ() {
        let ff_hash = ja3_hash(&Some(StealthProfile::firefox_default())).unwrap();
        let ch_hash = ja3_hash(&Some(StealthProfile::chrome_default())).unwrap();
        assert_ne!(ff_hash, ch_hash, "Firefox and Chrome JA3 must differ");
    }

    // ─── single-source cipher mapping through the live SSLConfig path ──
    // @trace REQ-STL-001 [req:REQ-STL-001] [level:unit]

    #[test]
    fn test_ssl_config_tls12_list_matches_single_source() {
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile.clone()));
        let expected = bao_stealth::boringssl_cipher_list_string(&profile.tls.cipher_suites);
        let got = unsafe { std::ffi::CStr::from_ptr(config.tls12_cipher_list) }
            .to_str()
            .expect("utf8");
        assert_eq!(got, expected);
        // No DHE names (entry prefix — "DHE-" is also a substring of
        // "ECDHE-...") and no TLS 1.3 names reach the BoringSSL cipher list.
        assert!(!got.split(':').any(|n| n.starts_with("DHE-")));
        assert!(!got.contains("TLS_AES"));
    }

    #[test]
    fn test_ssl_config_curves_list_excludes_ffdhe() {
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let curves = unsafe { std::ffi::CStr::from_ptr(config.tls_curves_list) }
            .to_str()
            .expect("utf8");
        assert_eq!(curves, "X25519:P-256:P-384:P-521");
        assert!(!curves.contains("ffdhe"));
    }

    #[test]
    fn test_alpn_wire_format_structure() {
        let profile = StealthProfile::firefox_default();
        let wire = alpn_wire_format(&profile.tls);
        // Each ALPN entry is: 1 byte length + N bytes protocol
        // Firefox has ["h2", "http/1.1"]
        // h2: 0x02 + b"h2" = 3 bytes
        // http/1.1: 0x08 + b"http/1.1" = 9 bytes
        // Total: 12 bytes
        assert_eq!(wire.len(), 12);
    }

    #[test]
    fn test_alpn_wire_chrome_structure() {
        let profile = StealthProfile::chrome_default();
        let wire = alpn_wire_format(&profile.tls);
        assert_eq!(wire.len(), 12); // same ALPN as Firefox
    }

    #[test]
    fn test_h2_settings_wire_has_6_entries() {
        // Each settings entry is 6 bytes (2 byte ID + 4 byte value)
        // Firefox has 6 settings → 36 bytes
        let profile = StealthProfile::firefox_default();
        let wire = h2_settings_wire_format(&profile.http2);
        assert_eq!(wire.len() % 6, 0, "wire length must be multiple of 6");
    }

    // ─── stealth_profile_to_ssl_config bridge tests ────────────
    // @trace REQ-STL-001 [req:REQ-STL-001] [level:unit]

    #[test]
    fn test_ssl_config_no_profile_is_default() {
        let config = stealth_profile_to_ssl_config(&None);
        assert!(config.tls12_cipher_list.is_null());
        assert!(config.tls13_cipher_suites.is_null());
        assert!(config.tls_curves_list.is_null());
        assert!(config.tls_sigalgs_list.is_null());
    }

    #[test]
    fn test_ssl_config_firefox_has_fingerprint_fields() {
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        assert!(
            !config.tls12_cipher_list.is_null(),
            "tls12_cipher_list should be set"
        );
        assert!(
            !config.tls13_cipher_suites.is_null(),
            "tls13_cipher_suites should be set"
        );
        assert!(
            !config.tls_curves_list.is_null(),
            "tls_curves_list should be set"
        );
        assert!(
            !config.tls_sigalgs_list.is_null(),
            "tls_sigalgs_list should be set"
        );
    }

    #[test]
    fn test_ssl_config_chrome_has_fingerprint_fields() {
        let profile = StealthProfile::chrome_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        assert!(!config.tls12_cipher_list.is_null());
        assert!(!config.tls13_cipher_suites.is_null());
        assert!(!config.tls_curves_list.is_null());
        assert!(!config.tls_sigalgs_list.is_null());
    }

    #[test]
    fn test_ssl_config_firefox_tls12_cipher_content() {
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let s = unsafe { std::ffi::CStr::from_ptr(config.tls12_cipher_list) }
            .to_str()
            .unwrap();
        assert!(
            s.contains("ECDHE"),
            "TLS 1.2 ciphers should contain ECDHE: {}",
            s
        );
    }

    #[test]
    fn test_ssl_config_firefox_tls13_cipher_content() {
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let s = unsafe { std::ffi::CStr::from_ptr(config.tls13_cipher_suites) }
            .to_str()
            .unwrap();
        assert!(
            s.contains("TLS_AES_128_GCM_SHA256"),
            "TLS 1.3 should contain AES-128: {}",
            s
        );
    }

    #[test]
    fn test_ssl_config_firefox_curves_content() {
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let s = unsafe { std::ffi::CStr::from_ptr(config.tls_curves_list) }
            .to_str()
            .unwrap();
        assert!(s.contains("X25519"), "Curves should contain X25519: {}", s);
    }

    #[test]
    fn test_ssl_config_firefox_sigalgs_content() {
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let s = unsafe { std::ffi::CStr::from_ptr(config.tls_sigalgs_list) }
            .to_str()
            .unwrap();
        assert!(
            s.contains("ecdsa_secp256r1_sha256"),
            "Sigalgs should contain ECDSA P-256: {}",
            s
        );
    }

    #[test]
    fn test_ssl_config_firefox_chrome_tls12_converge_curves_differ() {
        // Firefox/Chrome TLS 1.2 sets differ only in DHE suites, which
        // BoringSSL cannot offer — the lists exposed to BoringSSL converge
        // (design result, see bao_stealth/src/tls.rs DHE-filter comment and
        // the profile suite counts: FF 4 DHE / Chrome 2 DHE → both offer 8).
        // Fingerprint differentiation comes from offered groups (Firefox
        // keeps P-521), sigalgs, extensions and H2 SETTINGS instead.
        let ff = StealthProfile::firefox_default();
        let ch = StealthProfile::chrome_default();
        let ff_config = stealth_profile_to_ssl_config(&Some(ff));
        let ch_config = stealth_profile_to_ssl_config(&Some(ch));
        let ff_s = unsafe { std::ffi::CStr::from_ptr(ff_config.tls12_cipher_list) }
            .to_str()
            .unwrap();
        let ch_s = unsafe { std::ffi::CStr::from_ptr(ch_config.tls12_cipher_list) }
            .to_str()
            .unwrap();
        // Both lists converge AND each equals its profile's DHE-filtered set.
        assert_eq!(
            ff_s, ch_s,
            "Firefox/Chrome TLS 1.2 lists must converge after DHE filtering"
        );
        assert_eq!(
            ff_s,
            TlsFingerprint::firefox().tls12_cipher_list_string(),
            "exposed list must equal Firefox DHE-filtered set"
        );
        assert_eq!(
            ch_s,
            TlsFingerprint::chrome().tls12_cipher_list_string(),
            "exposed list must equal Chrome DHE-filtered set"
        );
        // Differentiation survives via offered groups (Firefox keeps P-521),
        // mirroring the bao_stealth-side profile distinction test.
        let ff_c = unsafe { std::ffi::CStr::from_ptr(ff_config.tls_curves_list) }
            .to_str()
            .unwrap();
        let ch_c = unsafe { std::ffi::CStr::from_ptr(ch_config.tls_curves_list) }
            .to_str()
            .unwrap();
        assert_ne!(ff_c, ch_c, "Firefox/Chrome curves must differ (P-521)");
    }

    #[test]
    fn test_ssl_config_drop_does_not_leak() {
        // Create and drop to verify no double-free or leak
        let profile = StealthProfile::firefox_default();
        let _config = stealth_profile_to_ssl_config(&Some(profile));
        // drop happens here — if deinit works correctly, no UB
    }

    // ─── H2 fingerprint injection tests ──────────────────────
    // @trace REQ-STL-002 [req:REQ-STL-002] [level:unit]

    #[test]
    fn test_ssl_config_no_profile_h2_fields_default() {
        let config = stealth_profile_to_ssl_config(&None);
        assert!(
            config.h2_settings_payload.is_none(),
            "no profile → None h2_settings_payload"
        );
        assert_eq!(
            config.h2_initial_window_size, 0,
            "no profile → h2_initial_window_size=0"
        );
        assert!(
            config.h2_pseudo_header_order.is_none(),
            "no profile → None h2_pseudo_header_order"
        );
        assert!(
            config.h2_priority_frames.is_none(),
            "no profile → None h2_priority_frames"
        );
    }

    // ─── REQ-STL-002: pseudo-header order + PRIORITY frame injection ──

    #[test]
    fn test_ssl_config_firefox_h2_pseudo_header_order() {
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let order = config
            .h2_pseudo_header_order
            .as_deref()
            .expect("Firefox profile must set h2_pseudo_header_order");
        let names: Vec<&str> = order.iter().map(|s| &**s).collect();
        assert_eq!(
            names,
            vec![":method", ":path", ":authority", ":scheme"],
            "Firefox pseudo-header wire order"
        );
    }

    #[test]
    fn test_ssl_config_chrome_h2_pseudo_header_order() {
        let profile = StealthProfile::chrome_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let order = config
            .h2_pseudo_header_order
            .as_deref()
            .expect("Chrome profile must set h2_pseudo_header_order");
        let names: Vec<&str> = order.iter().map(|s| &**s).collect();
        assert_eq!(
            names,
            vec![":method", ":authority", ":scheme", ":path"],
            "Chrome pseudo-header wire order"
        );
    }

    #[test]
    fn test_ssl_config_firefox_h2_priority_frames() {
        // REQ-STL-002-C3: Firefox reserves its dependency-tree streams
        // (3/5/7/11, weights 40/109/138/255, root dependency, non-exclusive).
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let frames = config
            .h2_priority_frames
            .as_deref()
            .expect("Firefox profile must set h2_priority_frames");
        assert_eq!(frames.len(), 4, "Firefox reserves 4 priority-tree streams");
        let expected = [
            (3u32, 0u32, false, 40u8),
            (5, 0, false, 109),
            (7, 0, false, 138),
            (11, 0, false, 255),
        ];
        for (frame, want) in frames.iter().zip(expected.iter()) {
            assert_eq!(
                (frame.stream_id, frame.stream_dependency, frame.exclusive, frame.weight),
                *want
            );
        }
    }

    #[test]
    fn test_ssl_config_chrome_h2_priority_frames_empty() {
        // REQ-STL-002-C3: Chrome v106+ dropped PRIORITY frames.
        let profile = StealthProfile::chrome_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let frames = config
            .h2_priority_frames
            .as_deref()
            .expect("Chrome profile must set h2_priority_frames (possibly empty)");
        assert!(frames.is_empty(), "Chrome sends no PRIORITY frames");
    }

    #[test]
    fn test_ssl_config_firefox_h2_settings_payload_set() {
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let payload = config
            .h2_settings_payload
            .as_deref()
            .expect("Firefox profile must set h2_settings_payload");
        // Binary wire format: 6 settings × 6 bytes = 36 bytes
        assert_eq!(
            payload.len(),
            36,
            "Firefox H2 SETTINGS payload = 6 settings × 6 bytes = 36"
        );
    }

    #[test]
    fn test_ssl_config_chrome_h2_settings_payload_set() {
        let profile = StealthProfile::chrome_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let payload = config
            .h2_settings_payload
            .as_deref()
            .expect("Chrome profile must set h2_settings_payload");
        assert_eq!(
            payload.len(),
            36,
            "Chrome H2 SETTINGS payload = 6 settings × 6 bytes = 36"
        );
    }

    #[test]
    fn test_ssl_config_firefox_h2_initial_window_size() {
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        assert_eq!(
            config.h2_initial_window_size, 131072,
            "Firefox initial_window_size=131072"
        );
    }

    #[test]
    fn test_ssl_config_chrome_h2_initial_window_size() {
        let profile = StealthProfile::chrome_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        assert_eq!(
            config.h2_initial_window_size, 6291456,
            "Chrome initial_window_size=6291456"
        );
    }

    #[test]
    fn test_ssl_config_h2_settings_firefox_chrome_differ() {
        let ff = StealthProfile::firefox_default();
        let ch = StealthProfile::chrome_default();
        let ff_config = stealth_profile_to_ssl_config(&Some(ff));
        let ch_config = stealth_profile_to_ssl_config(&Some(ch));
        let ff_payload = ff_config.h2_settings_payload.as_deref().unwrap();
        let ch_payload = ch_config.h2_settings_payload.as_deref().unwrap();
        assert_ne!(
            ff_payload, ch_payload,
            "Firefox and Chrome H2 SETTINGS binary must differ"
        );
    }

    #[test]
    fn test_h2_settings_wire_format_firefox_first_setting() {
        let profile = StealthProfile::firefox_default();
        let wire = h2_settings_wire_format(&profile.http2);
        // First setting: HEADER_TABLE_SIZE (0x01) = 65536
        assert_eq!(wire[0..2], [0x00, 0x01], "first setting ID = 0x0001");
        let value = u32::from_be_bytes([wire[2], wire[3], wire[4], wire[5]]);
        assert_eq!(value, 65536, "Firefox HEADER_TABLE_SIZE = 65536");
    }

    #[test]
    fn test_h2_settings_wire_format_chrome_window_size() {
        let profile = StealthProfile::chrome_default();
        let wire = h2_settings_wire_format(&profile.http2);
        // Find INITIAL_WINDOW_SIZE (0x04) in the wire format
        let mut found_iws = false;
        for i in (0..wire.len()).step_by(6) {
            let id = u16::from_be_bytes([wire[i], wire[i + 1]]);
            if id == 0x04 {
                let value =
                    u32::from_be_bytes([wire[i + 2], wire[i + 3], wire[i + 4], wire[i + 5]]);
                assert_eq!(value, 6291456, "Chrome INITIAL_WINDOW_SIZE = 6291456");
                found_iws = true;
                break;
            }
        }
        assert!(found_iws, "INITIAL_WINDOW_SIZE setting must be present");
    }

    #[test]
    fn test_h2_settings_wire_format_firefox_enable_push_zero() {
        let profile = StealthProfile::firefox_default();
        let wire = h2_settings_wire_format(&profile.http2);
        for i in (0..wire.len()).step_by(6) {
            let id = u16::from_be_bytes([wire[i], wire[i + 1]]);
            if id == 0x02 {
                let value =
                    u32::from_be_bytes([wire[i + 2], wire[i + 3], wire[i + 4], wire[i + 5]]);
                assert_eq!(value, 0, "ENABLE_PUSH must be 0");
                return;
            }
        }
        panic!("ENABLE_PUSH setting not found");
    }

    #[test]
    fn test_h2_settings_wire_format_chrome_max_concurrent() {
        let profile = StealthProfile::chrome_default();
        let wire = h2_settings_wire_format(&profile.http2);
        for i in (0..wire.len()).step_by(6) {
            let id = u16::from_be_bytes([wire[i], wire[i + 1]]);
            // RFC 7540 §6.5.2: 0x03 = SETTINGS_MAX_CONCURRENT_STREAMS
            if id == 0x03 {
                let value =
                    u32::from_be_bytes([wire[i + 2], wire[i + 3], wire[i + 4], wire[i + 5]]);
                assert_eq!(value, 1000, "Chrome MAX_CONCURRENT_STREAMS = 1000");
                return;
            }
        }
        panic!("MAX_CONCURRENT_STREAMS setting not found");
    }

    #[test]
    fn test_ssl_config_h2_binary_roundtrip() {
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile.clone()));
        let payload = config.h2_settings_payload.as_deref().unwrap();
        let original = h2_settings_wire_format(&profile.http2);
        assert_eq!(
            payload,
            &original[..],
            "binary roundtrip must match original wire format"
        );
    }

    // ─── H2 fingerprint pipeline integration tests ──────────────
    // @trace REQ-STL-002 [req:REQ-STL-002] [level:unit]
    // Verifies the full data path: StealthProfile.http2 → h2_settings_wire_format()
    // → SSLConfig.h2_settings_payload (Option<Box<[u8]>>) → write_preface/replenish_window

    #[test]
    fn test_h2_payload_preserves_nul_bytes() {
        // The original bug: CStrPtr truncated at first \0 byte. Binary format
        // MUST preserve NUL bytes (value 0x00000000 is a valid settings value).
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let payload = config.h2_settings_payload.as_deref().unwrap();
        // Wire format contains ENABLE_PUSH=0 which encodes as [0x00, 0x03, 0x00, 0x00, 0x00, 0x00]
        // — the last 4 bytes are all NUL. Verify they're present.
        assert!(
            payload.contains(&0u8),
            "binary payload must contain NUL bytes (ENABLE_PUSH value = 0)"
        );
        // Verify no truncation: 6 settings × 6 bytes = 36
        assert_eq!(
            payload.len(),
            36,
            "payload must not be truncated at NUL bytes"
        );
    }

    #[test]
    fn test_h2_payload_chrome_preserves_nul_bytes() {
        let profile = StealthProfile::chrome_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let payload = config.h2_settings_payload.as_deref().unwrap();
        // Chrome also has ENABLE_PUSH=0 → NUL bytes
        assert!(
            payload.contains(&0u8),
            "Chrome payload must contain NUL bytes"
        );
        assert_eq!(payload.len(), 36, "Chrome payload must be 36 bytes");
    }

    #[test]
    fn test_h2_firefox_wire_all_settings_big_endian() {
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let payload = config.h2_settings_payload.as_deref().unwrap();
        // Decode all 6 settings from binary wire format
        let decoded: Vec<(u16, u32)> = (0..payload.len())
            .step_by(6)
            .map(|i| {
                let id = u16::from_be_bytes([payload[i], payload[i + 1]]);
                let value = u32::from_be_bytes([
                    payload[i + 2],
                    payload[i + 3],
                    payload[i + 4],
                    payload[i + 5],
                ]);
                (id, value)
            })
            .collect();
        assert_eq!(decoded.len(), 6, "Firefox must have exactly 6 settings");
        // Verify specific Firefox values
        let ht = decoded.iter().find(|(id, _)| *id == 0x01);
        assert_eq!(
            ht.map(|(_, v)| *v),
            Some(65536),
            "Firefox HEADER_TABLE_SIZE = 65536"
        );
        // RFC 7540 §6.5.2: 0x02 = SETTINGS_ENABLE_PUSH,
        // 0x03 = SETTINGS_MAX_CONCURRENT_STREAMS,
        // 0x04 = SETTINGS_INITIAL_WINDOW_SIZE
        let ep = decoded.iter().find(|(id, _)| *id == 0x02);
        assert_eq!(ep.map(|(_, v)| *v), Some(0), "Firefox ENABLE_PUSH = 0");
        let mcs = decoded.iter().find(|(id, _)| *id == 0x03);
        assert_eq!(
            mcs.map(|(_, v)| *v),
            Some(100),
            "Firefox MAX_CONCURRENT_STREAMS = 100"
        );
        let iws = decoded.iter().find(|(id, _)| *id == 0x04);
        assert_eq!(
            iws.map(|(_, v)| *v),
            Some(131072),
            "Firefox INITIAL_WINDOW_SIZE = 131072"
        );
        let mfs = decoded.iter().find(|(id, _)| *id == 0x05);
        assert_eq!(
            mfs.map(|(_, v)| *v),
            Some(16384),
            "Firefox MAX_FRAME_SIZE = 16384"
        );
        let mhl = decoded.iter().find(|(id, _)| *id == 0x06);
        assert_eq!(
            mhl.map(|(_, v)| *v),
            Some(262144),
            "Firefox MAX_HEADER_LIST_SIZE = 262144"
        );
    }

    #[test]
    fn test_h2_chrome_wire_all_settings_big_endian() {
        let profile = StealthProfile::chrome_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        let payload = config.h2_settings_payload.as_deref().unwrap();
        let decoded: Vec<(u16, u32)> = (0..payload.len())
            .step_by(6)
            .map(|i| {
                let id = u16::from_be_bytes([payload[i], payload[i + 1]]);
                let value = u32::from_be_bytes([
                    payload[i + 2],
                    payload[i + 3],
                    payload[i + 4],
                    payload[i + 5],
                ]);
                (id, value)
            })
            .collect();
        assert_eq!(decoded.len(), 6, "Chrome must have exactly 6 settings");
        // Chrome-specific values (RFC 7540 §6.5.2:
        // 0x03 = MAX_CONCURRENT_STREAMS, 0x04 = INITIAL_WINDOW_SIZE)
        let mcs = decoded.iter().find(|(id, _)| *id == 0x03);
        assert_eq!(
            mcs.map(|(_, v)| *v),
            Some(1000),
            "Chrome MAX_CONCURRENT_STREAMS = 1000"
        );
        let iws = decoded.iter().find(|(id, _)| *id == 0x04);
        assert_eq!(
            iws.map(|(_, v)| *v),
            Some(6291456),
            "Chrome INITIAL_WINDOW_SIZE = 6291456"
        );
    }

    #[test]
    fn test_h2_window_size_firefox_pipeline() {
        // Verify initial_window_size flows through SSLConfig correctly
        let profile = StealthProfile::firefox_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        assert_eq!(
            config.h2_initial_window_size, 131072,
            "Firefox window size must be 131072 (128 KiB)"
        );
    }

    #[test]
    fn test_h2_window_size_chrome_pipeline() {
        let profile = StealthProfile::chrome_default();
        let config = stealth_profile_to_ssl_config(&Some(profile));
        assert_eq!(
            config.h2_initial_window_size, 6291456,
            "Chrome window size must be 6291456 (6 MiB)"
        );
    }

    #[test]
    fn test_h2_window_size_default_pipeline() {
        // No profile → h2_initial_window_size = 0 → write_preface uses LOCAL_INITIAL_WINDOW_SIZE
        let config = stealth_profile_to_ssl_config(&None);
        assert_eq!(
            config.h2_initial_window_size, 0,
            "no profile → window size 0 (use LOCAL_INITIAL_WINDOW_SIZE)"
        );
    }

    #[test]
    fn test_h2_firefox_chrome_payloads_differ_in_all_bytes() {
        let ff = StealthProfile::firefox_default();
        let ch = StealthProfile::chrome_default();
        let ff_config = stealth_profile_to_ssl_config(&Some(ff));
        let ch_config = stealth_profile_to_ssl_config(&Some(ch));
        let ff_payload = ff_config.h2_settings_payload.as_deref().unwrap();
        let ch_payload = ch_config.h2_settings_payload.as_deref().unwrap();
        // Payloads should differ (different setting values)
        assert_ne!(
            ff_payload, ch_payload,
            "Firefox and Chrome H2 SETTINGS payloads must differ"
        );
    }

    #[test]
    fn test_h2_no_profile_has_none_payload() {
        let config = stealth_profile_to_ssl_config(&None);
        assert!(
            config.h2_settings_payload.is_none(),
            "no profile → h2_settings_payload must be None"
        );
    }

    #[test]
    fn test_h2_payload_byte_level_identity_with_wire_format() {
        // Verify byte-for-byte identity between h2_settings_wire_format output
        // and what's stored in SSLConfig.h2_settings_payload
        for profile_fn in [
            StealthProfile::firefox_default,
            StealthProfile::chrome_default,
        ] {
            let profile = profile_fn();
            let wire = h2_settings_wire_format(&profile.http2);
            let config = stealth_profile_to_ssl_config(&Some(profile));
            let payload = config.h2_settings_payload.clone().unwrap();
            assert_eq!(
                &payload[..],
                &wire,
                "SSLConfig payload must exactly match wire format bytes"
            );
        }
    }
}