crawlex 1.0.6

Stealth crawler with Chrome-perfect TLS/H2 fingerprint, render pool, hooks, persistent queue
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
//! Stealth shim template substitution.
//!
//! `stealth_shim.js` ships with `{{PLACEHOLDER}}` tokens where we used to
//! hardcode "Chrome/131", "America/Sao_Paulo", etc. At render time we
//! substitute them from the active `IdentityBundle` so the shim, the
//! Chromium launch flags, the `Network.setUserAgentOverride` and the HTTP
//! headers all tell the same story.

use crate::identity::IdentityBundle;
use crate::impersonate::Profile;

pub const STEALTH_SHIM_TEMPLATE: &str = include_str!("stealth_shim.js");

/// Slice 33 — values measured from an external CDP session's effective
/// browser fingerprint that should override the `IdentityBundle`-derived
/// defaults when rendering the stealth shim. Every field is optional;
/// only fields populated by an upstream calibration are applied, so the
/// stock (non-CDP) path keeps producing byte-identical output by passing
/// `None`.
///
/// The struct is intentionally decoupled from `crate::render::calibration`
/// so `stealth` stays buildable without the `cdp-backend` feature. The
/// caller (typically the render pool) is responsible for projecting an
/// `EffectiveFingerprint` into this shape.
#[derive(Debug, Clone, Default)]
pub struct CalibrationOverrides {
    pub user_agent: Option<String>,
    pub platform: Option<String>,
    pub locale: Option<String>,
    pub languages_json: Option<String>,
    pub timezone: Option<String>,
    pub tz_offset_min: Option<i32>,
    pub webgl_unmasked_vendor: Option<String>,
    pub webgl_unmasked_renderer: Option<String>,
    pub webgpu_adapter_description: Option<String>,
    pub heap_size_limit: Option<u64>,
    pub media_mic_count: Option<u8>,
    pub media_cam_count: Option<u8>,
    pub media_speaker_count: Option<u8>,
}

impl CalibrationOverrides {
    /// True when no override is set — used to short-circuit to the
    /// bundle-only render path so the stock branch produces unchanged
    /// output.
    pub fn is_empty(&self) -> bool {
        self.user_agent.is_none()
            && self.platform.is_none()
            && self.locale.is_none()
            && self.languages_json.is_none()
            && self.timezone.is_none()
            && self.tz_offset_min.is_none()
            && self.webgl_unmasked_vendor.is_none()
            && self.webgl_unmasked_renderer.is_none()
            && self.webgpu_adapter_description.is_none()
            && self.heap_size_limit.is_none()
            && self.media_mic_count.is_none()
            && self.media_cam_count.is_none()
            && self.media_speaker_count.is_none()
    }
}

/// Legacy shim vars driven by `Profile` + caller-supplied locale/timezone.
/// Retained for transition; prefer `render_shim_from_bundle`.
pub struct ShimVars<'a> {
    pub profile: Profile,
    pub locale: &'a str,
    pub languages_json: &'a str,
    pub timezone: &'a str,
    pub tz_offset_min: i32,
    pub platform: &'a str,
}

/// Token set the shim template expects. Centralised so the bundle-based
/// and profile-based paths can't drift on which placeholders they fill.
struct ShimSubstitutions<'a> {
    user_agent: &'a str,
    app_version: &'a str,
    ua_brands: &'a str,
    ua_full_version_list: &'a str,
    ua_full_version: &'a str,
    ua_major: &'a str,
    platform: &'a str,
    ua_platform: &'a str,
    locale: &'a str,
    languages_json: &'a str,
    timezone: &'a str,
    tz_offset_min: i32,
    /// Seed injected into `window.__crawlex_seed__` for deterministic
    /// canvas / audio / WebGL perturbation within a session. Truncated to
    /// the low 31 bits at substitution time so the JS integer literal
    /// stays within the safe bitwise-op range.
    canvas_seed: u32,
    /// WebGL unmasked vendor — also reused as the WebGPU adapter vendor so
    /// the two APIs never diverge on vendor string.
    webgl_unmasked_vendor: &'a str,
    /// WebGPU adapter description — must share the WebGL vendor keyword
    /// (validator enforces this). Defaults when absent keep the old
    /// profile-based path working.
    webgpu_adapter_description: &'a str,
    /// Wave1 coherence scalars — see `IdentityBundle` for the rationale
    /// on each. Kept as `&str` for integers too so `apply` stays one
    /// `.replace()` per placeholder and no ad-hoc conversions leak in.
    scrollbar_width: u32,
    heap_size_limit: u64,
    device_memory: u32,
    hardware_concurrency: u32,
    max_texture_size: u32,
    max_viewport_w: u32,
    max_viewport_h: u32,
    audio_sample_rate: u32,
    fonts_json: &'a str,
    gpu_vendor_keyword: &'a str,
    /// `navigator.mediaDevices.enumerateDevices()` surface counts (§23).
    /// 1/1/1 is a tell — desktops expose built-in +
    /// virtual/bluetooth. Per-persona counts carried in `IdentityBundle`.
    media_mic_count: u8,
    media_cam_count: u8,
    media_speaker_count: u8,
    /// Whether `navigator.getBattery` is exposed (mobile personas only).
    /// Desktop Chrome 103+ removed the Battery API; mobile Chrome still
    /// ships it. When `true`, Section 7 installs a deterministic 24h
    /// charge/discharge curve anchored to local midnight (via the
    /// timezone in this bundle), and Section 17 leaves the API alone.
    /// When `false`, the API is deleted (current behavior).
    expose_battery: bool,
}

/// JS string literal escape — the bundle-sourced strings land inside
/// single-quoted JS literals in the shim, so a stray `'` or `\` would break
/// the whole script. Only the characters that actually escape in that
/// context are handled.
fn js_str_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '\\' => out.push_str("\\\\"),
            '\'' => out.push_str("\\'"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            _ => out.push(c),
        }
    }
    out
}

fn apply(s: &ShimSubstitutions<'_>) -> String {
    apply_to(STEALTH_SHIM_TEMPLATE, s)
}

fn apply_to(template: &str, s: &ShimSubstitutions<'_>) -> String {
    template
        .replace("{{USER_AGENT}}", s.user_agent)
        .replace("{{APP_VERSION}}", s.app_version)
        .replace("{{UA_BRANDS}}", s.ua_brands)
        .replace("{{UA_FULL_VERSION_LIST}}", s.ua_full_version_list)
        .replace("{{UA_FULL_VERSION}}", s.ua_full_version)
        .replace("{{UA_MAJOR}}", s.ua_major)
        .replace("{{PLATFORM}}", s.platform)
        .replace("{{UA_PLATFORM}}", s.ua_platform)
        .replace("{{LOCALE}}", s.locale)
        .replace("{{LANGUAGES_JSON}}", s.languages_json)
        .replace("{{TIMEZONE}}", s.timezone)
        .replace("{{TZ_OFFSET_MIN}}", &s.tz_offset_min.to_string())
        .replace("{{CANVAS_SEED}}", &s.canvas_seed.to_string())
        .replace(
            "{{WEBGL_UNMASKED_VENDOR}}",
            &js_str_escape(s.webgl_unmasked_vendor),
        )
        .replace(
            "{{WEBGPU_ADAPTER_DESCRIPTION}}",
            &js_str_escape(s.webgpu_adapter_description),
        )
        .replace("{{SCROLLBAR_WIDTH}}", &s.scrollbar_width.to_string())
        .replace("{{HEAP_SIZE_LIMIT}}", &s.heap_size_limit.to_string())
        .replace("{{DEVICE_MEMORY}}", &s.device_memory.to_string())
        .replace("{{HW_CONCURRENCY}}", &s.hardware_concurrency.to_string())
        .replace("{{MAX_TEXTURE_SIZE}}", &s.max_texture_size.to_string())
        .replace("{{MAX_VIEWPORT_W}}", &s.max_viewport_w.to_string())
        .replace("{{MAX_VIEWPORT_H}}", &s.max_viewport_h.to_string())
        .replace("{{AUDIO_SAMPLE_RATE}}", &s.audio_sample_rate.to_string())
        .replace("{{FONTS_JSON}}", s.fonts_json)
        .replace(
            "{{GPU_VENDOR_KEYWORD}}",
            &js_str_escape(s.gpu_vendor_keyword),
        )
        .replace("{{MEDIA_MIC_COUNT}}", &s.media_mic_count.to_string())
        .replace("{{MEDIA_CAM_COUNT}}", &s.media_cam_count.to_string())
        .replace(
            "{{MEDIA_SPEAKER_COUNT}}",
            &s.media_speaker_count.to_string(),
        )
        .replace(
            "{{EXPOSE_BATTERY}}",
            if s.expose_battery { "true" } else { "false" },
        )
}

/// Derive the 31-bit JS-safe canvas/audio seed from the bundle's
/// `canvas_audio_seed`. Masking to 31 bits keeps the integer positive
/// when cast through JS `| 0` and avoids sign-bit surprises in the
/// bitwise ops used inside the shim.
/// Recover a short lowercase vendor keyword (intel/nvidia/amd/apple/adreno)
/// from a WebGL/WebGPU renderer string. Mirrors the validator's helper but
/// is local to this module to avoid plumbing the private enum across
/// crate boundaries. Falls back to `"intel"` so legacy callers produce
/// a coherent string even on exotic input.
fn gpu_keyword_from_renderer(r: &str) -> &'static str {
    let l = r.to_ascii_lowercase();
    if l.contains("apple") {
        "apple"
    } else if l.contains("nvidia") {
        "nvidia"
    } else if l.contains("amd") || l.contains("radeon") {
        "amd"
    } else if l.contains("adreno") || l.contains("qualcomm") {
        "adreno"
    } else {
        "intel"
    }
}

fn seed_u31(raw: u64) -> u32 {
    let mixed = raw ^ (raw >> 32);
    (mixed as u32) & 0x7fff_ffff
}

/// Legacy entry — kept so existing callers keep compiling while the render
/// pool migrates to the bundle-based path. Prefer [`render_shim_from_bundle`].
///
/// **Deprecated**: this path hardcodes the Intel WebGL/WebGPU persona.
/// A caller that ships an AMD/NVIDIA identity through this function
/// will silently inject Intel strings into the shim, re-introducing
/// the cross-field FP inconsistency the validator was added to catch.
/// New code must use [`render_shim_from_bundle`] so the GPU keyword
/// flows from the same [`IdentityBundle`] the validator inspected.
#[deprecated(
    note = "hardcodes Intel GPU strings; use render_shim_from_bundle with a validated IdentityBundle"
)]
pub fn render_shim(vars: &ShimVars<'_>) -> String {
    let ua = vars.profile.user_agent();
    let app_version = ua.strip_prefix("Mozilla/").unwrap_or(&ua).to_string();
    let ua_brands = vars.profile.ua_brands_json();
    let ua_full_version_list = vars.profile.fullversion_brands_json();
    let ua_full_version = vars.profile.ua_full_version();
    let ua_major = vars.profile.major_version().to_string();
    let ua_platform = vars
        .platform
        .split_whitespace()
        .next()
        .unwrap_or("Linux")
        .to_string();
    apply(&ShimSubstitutions {
        user_agent: &ua,
        app_version: &app_version,
        ua_brands: &ua_brands,
        ua_full_version_list: &ua_full_version_list,
        ua_full_version: &ua_full_version,
        ua_major: &ua_major,
        platform: vars.platform,
        ua_platform: &ua_platform,
        locale: vars.locale,
        languages_json: vars.languages_json,
        timezone: vars.timezone,
        tz_offset_min: vars.tz_offset_min,
        // Legacy path has no bundle; fall back to a deterministic seed
        // derived from TZ offset + profile major so the shim remains
        // internally coherent (no Date.now leakage).
        canvas_seed: seed_u31(
            (vars.tz_offset_min as i64 as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
                ^ (vars.profile.major_version() as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9),
        ),
        // Legacy callers don't plumb a bundle; keep the historical Intel
        // strings so the rendered shim remains valid JS. New code should
        // use `render_shim_from_bundle`.
        webgl_unmasked_vendor: "Google Inc. (Intel)",
        webgpu_adapter_description:
            "ANGLE (Intel, Mesa Intel(R) UHD Graphics 630 (CFL GT2), OpenGL 4.6)",
        scrollbar_width: 15,
        heap_size_limit: 2_147_483_648,
        device_memory: 8,
        hardware_concurrency: 8,
        max_texture_size: 16384,
        max_viewport_w: 32767,
        max_viewport_h: 32767,
        audio_sample_rate: 48000,
        fonts_json: r#"["DejaVu Sans","Liberation Sans","Noto Sans","Ubuntu"]"#,
        gpu_vendor_keyword: "intel",
        media_mic_count: 2,
        media_cam_count: 1,
        media_speaker_count: 2,
        // Legacy path defaults to desktop persona — Battery API hidden.
        expose_battery: false,
    })
}

/// Strip blocks delimited by `// @worker-skip-start` / `// @worker-skip-end`.
///
/// Workers expose a different global surface than DOM windows: no `document`,
/// no `HTMLCanvasElement`, no `screen`/`matchMedia`/`requestAnimationFrame`/
/// `speechSynthesis`. Sections of the shim that touch those APIs are wrapped
/// in marker comments so the worker variant can drop them without forking
/// the template into a second `.js` file. Markers must sit on their own line.
fn strip_worker_skip_blocks(src: &str) -> String {
    let mut out = String::with_capacity(src.len());
    let mut in_skip = false;
    for line in src.lines() {
        let trimmed = line.trim();
        if trimmed == "// @worker-skip-start" {
            in_skip = true;
            continue;
        }
        if trimmed == "// @worker-skip-end" {
            in_skip = false;
            continue;
        }
        if !in_skip {
            out.push_str(line);
            out.push('\n');
        }
    }
    out
}

fn build_subs<'a>(bundle: &'a IdentityBundle, scratch: &'a ShimScratch) -> ShimSubstitutions<'a> {
    ShimSubstitutions {
        user_agent: &bundle.ua,
        app_version: &scratch.app_version,
        ua_brands: &bundle.ua_brands,
        ua_full_version_list: &bundle.ua_full_version_list,
        ua_full_version: &bundle.ua_full_version,
        ua_major: &scratch.ua_major,
        platform: &bundle.platform,
        ua_platform: &scratch.ua_platform,
        locale: &bundle.locale,
        languages_json: &bundle.languages_json,
        timezone: &bundle.timezone,
        tz_offset_min: bundle.tz_offset_min,
        canvas_seed: seed_u31(bundle.canvas_audio_seed),
        webgl_unmasked_vendor: &bundle.webgl_unmasked_vendor,
        webgpu_adapter_description: &bundle.webgpu_adapter_description,
        scrollbar_width: bundle.scrollbar_width,
        heap_size_limit: bundle.heap_size_limit,
        device_memory: bundle.device_memory,
        hardware_concurrency: bundle.hardware_concurrency,
        max_texture_size: bundle.max_texture_size,
        max_viewport_w: bundle.max_viewport_w,
        max_viewport_h: bundle.max_viewport_h,
        audio_sample_rate: bundle.audio_sample_rate,
        fonts_json: &bundle.fonts_json,
        gpu_vendor_keyword: gpu_keyword_from_renderer(&bundle.webgl_renderer),
        media_mic_count: bundle.media_mic_count,
        media_cam_count: bundle.media_cam_count,
        media_speaker_count: bundle.media_speaker_count,
        // Mobile personas (Adreno/Qualcomm) still ship Battery API.
        // Desktop Chrome 103+ removed it; keep hidden on those.
        expose_battery: gpu_keyword_from_renderer(&bundle.webgl_renderer) == "adreno",
    }
}

struct ShimScratch {
    app_version: String,
    ua_major: String,
    ua_platform: String,
}

impl ShimScratch {
    fn from_bundle(bundle: &IdentityBundle) -> Self {
        Self {
            app_version: bundle
                .ua
                .strip_prefix("Mozilla/")
                .unwrap_or(&bundle.ua)
                .to_string(),
            ua_major: bundle.ua_major.to_string(),
            ua_platform: bundle.ua_platform.trim_matches('"').to_string(),
        }
    }
}

/// Owned strings produced when applying [`CalibrationOverrides`] to the
/// bundle. Held separately so [`ShimSubstitutions`] can borrow `&str`
/// from these fields while the bundle remains the fallback source.
#[derive(Default)]
struct OverrideScratch {
    user_agent: Option<String>,
    app_version: Option<String>,
    platform: Option<String>,
    ua_platform: Option<String>,
    locale: Option<String>,
    languages_json: Option<String>,
    timezone: Option<String>,
    webgl_unmasked_vendor: Option<String>,
    webgpu_adapter_description: Option<String>,
    gpu_vendor_keyword: Option<&'static str>,
}

impl OverrideScratch {
    fn from_overrides(o: &CalibrationOverrides) -> Self {
        let app_version = o
            .user_agent
            .as_deref()
            .map(|ua| ua.strip_prefix("Mozilla/").unwrap_or(ua).to_string());
        let gpu_vendor_keyword = o
            .webgl_unmasked_renderer
            .as_deref()
            .map(gpu_keyword_from_renderer);
        Self {
            user_agent: o.user_agent.clone(),
            app_version,
            platform: o.platform.clone(),
            // UA-CH platform token is the bare first word of `platform`
            // (e.g. "Linux x86_64" → "Linux"). Match the legacy path.
            ua_platform: o.platform.as_deref().map(|p| {
                p.split_whitespace()
                    .next()
                    .unwrap_or(p)
                    .trim_matches('"')
                    .to_string()
            }),
            locale: o.locale.clone(),
            languages_json: o.languages_json.clone(),
            timezone: o.timezone.clone(),
            webgl_unmasked_vendor: o.webgl_unmasked_vendor.clone(),
            webgpu_adapter_description: o.webgpu_adapter_description.clone(),
            gpu_vendor_keyword,
        }
    }
}

/// Layer [`CalibrationOverrides`] on top of a bundle-derived
/// substitution. Any unset field falls through to the bundle.
fn apply_overrides<'a>(
    subs: &mut ShimSubstitutions<'a>,
    overrides: &'a CalibrationOverrides,
    scratch: &'a OverrideScratch,
) {
    if let Some(s) = scratch.user_agent.as_deref() {
        subs.user_agent = s;
    }
    if let Some(s) = scratch.app_version.as_deref() {
        subs.app_version = s;
    }
    if let Some(s) = scratch.platform.as_deref() {
        subs.platform = s;
    }
    if let Some(s) = scratch.ua_platform.as_deref() {
        subs.ua_platform = s;
    }
    if let Some(s) = scratch.locale.as_deref() {
        subs.locale = s;
    }
    if let Some(s) = scratch.languages_json.as_deref() {
        subs.languages_json = s;
    }
    if let Some(s) = scratch.timezone.as_deref() {
        subs.timezone = s;
    }
    if let Some(n) = overrides.tz_offset_min {
        subs.tz_offset_min = n;
    }
    if let Some(s) = scratch.webgl_unmasked_vendor.as_deref() {
        subs.webgl_unmasked_vendor = s;
    }
    if let Some(s) = scratch.webgpu_adapter_description.as_deref() {
        subs.webgpu_adapter_description = s;
    }
    if let Some(n) = overrides.heap_size_limit {
        subs.heap_size_limit = n;
    }
    if let Some(kw) = scratch.gpu_vendor_keyword {
        subs.gpu_vendor_keyword = kw;
    }
    if let Some(n) = overrides.media_mic_count {
        subs.media_mic_count = n;
    }
    if let Some(n) = overrides.media_cam_count {
        subs.media_cam_count = n;
    }
    if let Some(n) = overrides.media_speaker_count {
        subs.media_speaker_count = n;
    }
}

/// Worker-scope variant of the stealth shim. Same persona substitutions, but
/// DOM-only sections (`@worker-skip-start`/`@worker-skip-end` blocks in
/// `stealth_shim.js`) are stripped so the script runs cleanly inside
/// dedicated/shared/service worker contexts where `document`,
/// `HTMLCanvasElement`, `window.matchMedia`, etc. don't exist.
///
/// Used by the CDP `Target.attachedToTarget` handler to inject persona
/// coherence into worker globals before any user script runs (
/// Sprint 3 S3.1).
pub fn render_worker_shim_from_bundle(bundle: &IdentityBundle) -> String {
    render_worker_shim_from_bundle_with_calibration(bundle, None)
}

/// Calibration-aware worker shim. When `overrides` is `None` this is
/// byte-identical to [`render_worker_shim_from_bundle`] so the stock
/// path is preserved. When set, the listed fields are taken from the
/// calibrated fingerprint and the rest fall through to `bundle`.
pub fn render_worker_shim_from_bundle_with_calibration(
    bundle: &IdentityBundle,
    overrides: Option<&CalibrationOverrides>,
) -> String {
    let stripped = strip_worker_skip_blocks(STEALTH_SHIM_TEMPLATE);
    let scratch = ShimScratch::from_bundle(bundle);
    let mut subs = build_subs(bundle, &scratch);
    let ov_scratch;
    if let Some(o) = overrides {
        if !o.is_empty() {
            ov_scratch = OverrideScratch::from_overrides(o);
            apply_overrides(&mut subs, o, &ov_scratch);
        }
    }
    apply_to(&stripped, &subs)
}

/// Build the shim from an `IdentityBundle`. Every placeholder is drawn
/// from the same struct, so (a) coherence is enforced by construction
/// and (b) the session-scoped `canvas_audio_seed` flows into the JS as
/// `window.__crawlex_seed__` via `{{TZ_OFFSET_MIN}}`-style substitution.
pub fn render_shim_from_bundle(bundle: &IdentityBundle) -> String {
    render_shim_from_bundle_with_calibration(bundle, None)
}

/// Calibration-aware variant. With `overrides=None` the output is
/// byte-identical to [`render_shim_from_bundle`] (stock path preserved).
/// When set, listed fields come from the calibrated fingerprint; every
/// other placeholder falls through to `bundle`.
pub fn render_shim_from_bundle_with_calibration(
    bundle: &IdentityBundle,
    overrides: Option<&CalibrationOverrides>,
) -> String {
    let scratch = ShimScratch::from_bundle(bundle);
    let mut subs = build_subs(bundle, &scratch);
    let ov_scratch;
    if let Some(o) = overrides {
        if !o.is_empty() {
            ov_scratch = OverrideScratch::from_overrides(o);
            apply_overrides(&mut subs, o, &ov_scratch);
        }
    }
    apply(&subs)
}

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

    #[test]
    fn bundle_substitutions_fill_every_placeholder() {
        let b = IdentityBundle::from_chromium(131, 42);
        let js = render_shim_from_bundle(&b);
        // No residual `{{...}}` tokens.
        assert!(
            !js.contains("{{"),
            "template has unsubstituted tokens: {}",
            js.lines().find(|l| l.contains("{{")).unwrap_or("")
        );
        // Spot-check some critical values.
        assert!(js.contains(&b.ua), "UA missing");
        assert!(js.contains(&b.timezone), "timezone missing");
        assert!(js.contains(&b.locale), "locale missing");
        assert!(js.contains(&b.ua_full_version), "full version missing");
    }

    #[test]
    fn canvas_seed_is_deterministic_for_same_bundle() {
        // Same session_seed → same shim canvas seed literal.
        let a = IdentityBundle::from_chromium(131, 0xdead_beef);
        let b = IdentityBundle::from_chromium(131, 0xdead_beef);
        let ja = render_shim_from_bundle(&a);
        let jb = render_shim_from_bundle(&b);
        // Extract the `window.__crawlex_seed__ = <N> >>> 0` literal.
        let needle = "window.__crawlex_seed__ = (";
        let ea = ja.find(needle).expect("seed literal present");
        let eb = jb.find(needle).expect("seed literal present");
        assert_eq!(&ja[ea..ea + 80], &jb[eb..eb + 80]);
    }

    #[test]
    fn canvas_seed_differs_across_sessions() {
        let a = IdentityBundle::from_chromium(131, 1);
        let b = IdentityBundle::from_chromium(131, 2);
        let ja = render_shim_from_bundle(&a);
        let jb = render_shim_from_bundle(&b);
        // Different session seeds must land different integer literals
        // in the rendered shim.
        assert_ne!(
            ja.split("window.__crawlex_seed__ = (").nth(1).unwrap_or(""),
            jb.split("window.__crawlex_seed__ = (").nth(1).unwrap_or(""),
        );
    }

    #[test]
    fn no_date_now_in_seed_block() {
        // Guard against a regression where Date.now() sneaks back into
        // the canvas seed initialization — that would make the seed
        // non-deterministic across page loads within a session and
        // break FingerprintJS double-render equality.
        let b = IdentityBundle::from_chromium(131, 42);
        let js = render_shim_from_bundle(&b);
        let seed_block = js
            .split("typeof window.__crawlex_seed__ !== 'number'")
            .nth(1)
            .expect("seed block present");
        // Only inspect the next ~200 chars — enough to cover the init
        // expression without dragging in later canvas hooks.
        let window = &seed_block[..seed_block.len().min(400)];
        assert!(
            !window.contains("Date.now"),
            "seed init must not depend on Date.now(): {}",
            window
        );
    }

    #[test]
    fn permissions_query_handles_notifications_and_push() {
        let b = IdentityBundle::from_chromium(131, 7);
        let js = render_shim_from_bundle(&b);
        // Both leaky names should be covered.
        assert!(js.contains("leaky = { notifications: 1, push: 1 }"));
        // Coercion default → prompt must be present.
        assert!(js.contains("s === 'default' ? 'prompt' : s"));
        // Must still delegate other permission names to the original impl.
        assert!(js.contains("return orig(p);"));
    }

    #[test]
    fn notification_request_permission_is_coerced() {
        // S.4: headless Chrome returns 'denied' from
        // Notification.requestPermission without any user gesture, which
        // contradicts permissions.query (see section 3). The shim must
        // coerce 'denied' → 'default' and preserve both the callback and
        // the Promise signatures.
        let b = IdentityBundle::from_chromium(131, 11);
        let js = render_shim_from_bundle(&b);

        // Override must be installed.
        assert!(
            js.contains("Notification.requestPermission = wrapped"),
            "Notification.requestPermission override missing"
        );
        // Coercion rule present — denied → default.
        assert!(
            js.contains("(raw === 'denied') ? 'default' : raw"),
            "denied → default coercion missing"
        );
        // Both signatures preserved: callback invocation + Promise return.
        assert!(
            js.contains("callback(result)"),
            "callback invocation path missing"
        );
        assert!(
            js.contains("Promise.resolve(result)"),
            "Promise return path missing"
        );
        // toString Proxy registration: the wrapped function must be
        // handed to the section-13 WeakSet so `.toString()` looks native.
        let notif_section = js
            .split("13b. Notification.requestPermission")
            .nth(1)
            .expect("notification section present");
        // Section 13b is long enough that a 2000-byte window cut off the
        // `lateReg(wrapped)` registration line that lives ~40 lines after
        // the header. 5 KiB covers the whole block without bleeding into
        // section 14 (WebGPU) in any reasonable shim layout.
        let notif_window = &notif_section[..notif_section.len().min(5000)];
        assert!(
            notif_window.contains("__crawlex_reg_target__"),
            "wrapped function not registered with toString proxy"
        );
        assert!(
            notif_window.contains("lateReg(wrapped)"),
            "registrar not called on wrapped ref"
        );
    }

    #[test]
    fn battery_hidden_for_desktop_personas() {
        // Default Linux/Intel persona (Row 0) — desktop, EXPOSE_BATTERY=false.
        // Section 7 must NOT install the realistic curve, Section 17 must
        // delete the API.
        let b = IdentityBundle::from_chromium(131, 99);
        let js = render_shim_from_bundle(&b);
        // Placeholder substituted to literal `false`.
        assert!(
            js.contains("const EXPOSE_BATTERY = false"),
            "EXPOSE_BATTERY should be false on desktop persona"
        );
        // Section 17 must run the delete branch — gate variable also false.
        assert!(
            js.contains("const EXPOSE_BATTERY_S17 = false"),
            "Section 17 gate should be false on desktop"
        );
    }

    #[test]
    fn battery_curve_present_in_template() {
        // Even though desktop personas don't activate it at runtime, the
        // curve code must exist in the rendered shim — otherwise mobile
        // personas would receive a useless template. Sanity-check the
        // curve constants are intact post-substitution.
        let b = IdentityBundle::from_chromium(131, 7);
        let js = render_shim_from_bundle(&b);
        // The 22h discharge / 2h charge anchors.
        assert!(
            js.contains("0.85 - (0.85 - 0.20) * t"),
            "discharging formula 85→20% missing"
        );
        assert!(
            js.contains("0.20 + (0.85 - 0.20) * t"),
            "charging formula 20→85% missing"
        );
        // Hard clamps so level never exceeds 85% nor falls below 20%.
        assert!(
            js.contains("if (level > 0.85) level = 0.85"),
            "upper clamp at 85% missing — must never expose 100%"
        );
        assert!(
            js.contains("if (level < 0.20) level = 0.20"),
            "lower clamp at 20% missing"
        );
        // Local-time anchoring via Section 6 overridden getTimezoneOffset.
        assert!(
            js.contains("new Date().getTimezoneOffset()"),
            "timezone anchoring missing — curve must follow local midnight"
        );
    }

    #[test]
    fn calibration_overrides_none_matches_stock_output() {
        // Slice 33: passing None must be byte-identical to the
        // bundle-only path so the stock branch is provably preserved.
        let b = IdentityBundle::from_chromium(131, 42);
        let stock = render_shim_from_bundle(&b);
        let via_calibration = render_shim_from_bundle_with_calibration(&b, None);
        assert_eq!(stock, via_calibration);
        // Empty (all-None) overrides also short-circuit.
        let empty = CalibrationOverrides::default();
        assert!(empty.is_empty());
        let via_empty = render_shim_from_bundle_with_calibration(&b, Some(&empty));
        assert_eq!(stock, via_empty);
    }

    #[test]
    fn calibration_overrides_reflected_in_shim() {
        let b = IdentityBundle::from_chromium(131, 42);
        let overrides = CalibrationOverrides {
            user_agent: Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 14_5) Chrome/149.0".into()),
            platform: Some("MacIntel".into()),
            locale: Some("pt-PT".into()),
            languages_json: Some(r#"["pt-PT","pt","en"]"#.into()),
            timezone: Some("Europe/Lisbon".into()),
            tz_offset_min: Some(-60),
            webgl_unmasked_vendor: Some("Apple Inc.".into()),
            webgl_unmasked_renderer: Some("Apple M2".into()),
            webgpu_adapter_description: Some("Apple M2 GPU".into()),
            heap_size_limit: Some(4_294_967_296),
            media_mic_count: Some(3),
            media_cam_count: Some(2),
            media_speaker_count: Some(4),
        };
        let js = render_shim_from_bundle_with_calibration(&b, Some(&overrides));
        assert!(!js.contains("{{"), "unsubstituted token leaked");
        // UA + derived app_version (UA without `Mozilla/` prefix).
        assert!(js.contains("Chrome/149.0"), "calibrated UA missing");
        // Platform + UA-CH platform token.
        assert!(js.contains("MacIntel"), "calibrated platform missing");
        // Locale, languages, timezone, tz offset.
        assert!(js.contains("pt-PT"), "calibrated locale missing");
        assert!(js.contains(r#"["pt-PT","pt","en"]"#));
        assert!(js.contains("Europe/Lisbon"));
        assert!(js.contains("-60"), "calibrated tz offset missing");
        // WebGL + WebGPU + GPU keyword (apple).
        assert!(js.contains("Apple Inc."), "calibrated WebGL vendor missing");
        assert!(
            js.contains("Apple M2 GPU"),
            "calibrated WebGPU adapter missing"
        );
        assert!(
            js.contains("'apple'") || js.contains("\"apple\""),
            "GPU keyword not derived from calibrated renderer"
        );
        // Heap limit + media counts.
        assert!(js.contains("4294967296"), "calibrated heap limit missing");
        assert!(js.contains("MIC_COUNT = 3"), "calibrated mic count missing");
    }

    #[test]
    fn partial_overrides_only_replace_listed_fields() {
        let b = IdentityBundle::from_chromium(131, 42);
        let stock = render_shim_from_bundle(&b);
        let mut overrides = CalibrationOverrides::default();
        overrides.timezone = Some("Asia/Tokyo".into());
        let mixed = render_shim_from_bundle_with_calibration(&b, Some(&overrides));
        // Only the timezone is allowed to differ; bundle UA and locale
        // must still be present.
        assert!(mixed.contains("Asia/Tokyo"));
        assert!(mixed.contains(&b.ua), "non-overridden UA dropped");
        assert!(mixed.contains(&b.locale), "non-overridden locale dropped");
        // The byte-string differs from stock because we changed timezone.
        assert_ne!(stock, mixed);
    }

    #[test]
    fn worker_shim_honours_calibration_overrides() {
        let b = IdentityBundle::from_chromium(131, 7);
        let stock = render_worker_shim_from_bundle(&b);
        let via_none = render_worker_shim_from_bundle_with_calibration(&b, None);
        assert_eq!(stock, via_none, "worker stock path must be preserved");
        let overrides = CalibrationOverrides {
            timezone: Some("Asia/Tokyo".into()),
            webgl_unmasked_vendor: Some("Apple Inc.".into()),
            webgl_unmasked_renderer: Some("Apple M2".into()),
            ..Default::default()
        };
        let calibrated = render_worker_shim_from_bundle_with_calibration(&b, Some(&overrides));
        assert!(calibrated.contains("Asia/Tokyo"));
        assert!(calibrated.contains("Apple Inc."));
        // Worker variant still has DOM-only sections stripped.
        assert!(!calibrated.contains("@worker-skip-start"));
    }

    #[test]
    #[allow(deprecated)] // intentionally exercises the legacy path
    fn legacy_profile_path_still_works() {
        let vars = ShimVars {
            profile: Profile::Chrome131Stable,
            locale: "en-US",
            languages_json: r#"["en-US","en"]"#,
            timezone: "UTC",
            tz_offset_min: 0,
            platform: "Linux x86_64",
        };
        let js = render_shim(&vars);
        assert!(!js.contains("{{"));
        assert!(js.contains("Linux"));
    }
}