eoka 0.5.1

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
//! Evasion scripts to bypass bot detection
//!
//! These scripts are injected before any page content loads to patch
//! detectable browser properties.

use crate::page::escape_js_string;
use crate::stealth::fingerprint::Fingerprint;
use crate::StealthConfig;

/// Native-function masking: makes `_eoka_mark`ed functions report native code from `.toString()`.
pub const NATIVE_TOSTRING_EVASION: &str = r#"
const _eoka_spoofed = new WeakMap();
const _eoka_origToString = Function.prototype.toString;
const _eoka_mark = (fn, name) => {
    if (typeof fn === 'function') {
        _eoka_spoofed.set(fn, name || fn.name || '');
    }
    return fn;
};
const _eoka_toStringProxy = new Proxy(_eoka_origToString, {
    apply(target, thisArg, args) {
        if (typeof thisArg === 'function' && _eoka_spoofed.has(thisArg)) {
            const name = _eoka_spoofed.get(thisArg);
            return name ? 'function ' + name + '() { [native code] }'
                        : 'function () { [native code] }';
        }
        if (thisArg === _eoka_toStringProxy) {
            return 'function toString() { [native code] }';
        }
        return Reflect.apply(target, thisArg, args);
    }
});
Function.prototype.toString = _eoka_toStringProxy;
_eoka_mark(Function.prototype.toString, 'toString');

// Deterministic per-session PRNG (LCG), seeded from Rust.
const _eoka_lcg = (s) => (Math.imul(s >>> 0, 1664525) + 1013904223) >>> 0;
let _eoka_seed = (__EOKA_NOISE_SEED__ >>> 0) || 1;
const _eoka_rand = () => {
    _eoka_seed = _eoka_lcg(_eoka_seed);
    return _eoka_seed / 4294967296;
};
"#;

/// Core WebDriver evasion - define webdriver=false on prototype (more realistic)
pub const WEBDRIVER_EVASION: &str = r#"
const _eoka_webdriverGet = _eoka_mark(() => false, 'get webdriver');
Object.defineProperty(Object.getPrototypeOf(navigator), 'webdriver', {
    get: _eoka_webdriverGet,
    configurable: true,
    enumerable: true
});
try {
    Object.defineProperty(Navigator.prototype, 'webdriver', {
        get: _eoka_webdriverGet,
        configurable: true,
        enumerable: true
    });
} catch(e) {}

// Remove automation-related properties from window
const automationProps = [
    'callPhantom', '_phantom', 'phantom', '__nightmare', 'domAutomation',
    'domAutomationController', '_selenium', '_Selenium_IDE_Recorder',
    'callSelenium', '__webdriver_script_fn', '__driver_evaluate',
    '__webdriver_evaluate', '__fxdriver_evaluate', '__driver_unwrapped',
    '__webdriver_unwrapped', '__fxdriver_unwrapped', '__selenium_unwrapped',
    '_WEBDRIVER_ELEM_CACHE', 'ChromeDriverw', 'driver-evaluate',
    'webdriver-evaluate', 'selenium-evaluate', 'webdriverCommand',
    'webdriver-evaluate-response', '__webdriverFunc', '__lastWatirAlert',
    '__lastWatirConfirm', '__lastWatirPrompt', '$chrome_asyncScriptInfo',
    '__selenium_evaluate', '__webdriver_script_function'
];

automationProps.forEach(prop => {
    try {
        if (prop in window) delete window[prop];
    } catch(e) {}
});

// Fix for Chrome's runtime.bindingsCalled check
if (window.chrome && window.chrome.runtime) {
    try {
        delete window.chrome.runtime.bindingsCalled;
    } catch(e) {}
}
"#;

/// CDP marker cleanup - simple and effective approach from chaser-oxide
pub const CDP_EVASION: &str = r#"
// Pattern to match CDP/automation markers
const cdcPattern = /^cdc_|^\$cdc_|^__webdriver|^__selenium|^__driver|^\$chrome_|^\$wdc_/;

// Clean up CDP markers from window
const cleanupWindow = () => {
    for (const prop of Object.getOwnPropertyNames(window)) {
        if (cdcPattern.test(prop)) {
            try { delete window[prop]; } catch(e) {}
        }
    }
};

// Clean up CDP markers from document
const cleanupDocument = () => {
    for (const prop of Object.getOwnPropertyNames(document)) {
        if (cdcPattern.test(prop)) {
            try { delete document[prop]; } catch(e) {}
        }
    }
};

// Run cleanup immediately
cleanupWindow();
cleanupDocument();

// Override Object.getOwnPropertyNames to filter out CDP markers
const originalGetOwnPropertyNames = Object.getOwnPropertyNames;
Object.getOwnPropertyNames = _eoka_mark(function getOwnPropertyNames(obj) {
    const names = originalGetOwnPropertyNames.call(this, obj);
    if (obj === window || obj === document) {
        return names.filter(name => !cdcPattern.test(name));
    }
    return names;
}, 'getOwnPropertyNames');

// Override Object.keys to filter out CDP markers
const originalKeys = Object.keys;
Object.keys = _eoka_mark(function keys(obj) {
    const keys = originalKeys.call(this, obj);
    if (obj === window || obj === document) {
        return keys.filter(key => !cdcPattern.test(key));
    }
    return keys;
}, 'keys');

// Override hasOwnProperty to hide CDP markers
const originalHasOwnProperty = Object.prototype.hasOwnProperty;
Object.prototype.hasOwnProperty = _eoka_mark(function hasOwnProperty(prop) {
    if ((this === window || this === document) && cdcPattern.test(prop)) {
        return false;
    }
    return originalHasOwnProperty.call(this, prop);
}, 'hasOwnProperty');

// Override Object.getOwnPropertyDescriptor to hide CDP markers
const originalGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
Object.getOwnPropertyDescriptor = _eoka_mark(function getOwnPropertyDescriptor(obj, prop) {
    if ((obj === window || obj === document) && cdcPattern.test(prop)) {
        return undefined;
    }
    return originalGetOwnPropertyDescriptor.call(this, obj, prop);
}, 'getOwnPropertyDescriptor');

// Intercept direct property access on document using a Proxy (bound fns cached for stable identity).
const realDocument = document;
const _eoka_boundCache = new WeakMap();
try {
    const documentProxy = new Proxy(realDocument, {
        get(target, prop, receiver) {
            if (typeof prop === 'string' && cdcPattern.test(prop)) {
                return undefined;
            }
            const value = Reflect.get(target, prop, target);
            if (typeof value === 'function') {
                let cache = _eoka_boundCache.get(target);
                if (!cache) { cache = new Map(); _eoka_boundCache.set(target, cache); }
                if (!cache.has(prop)) cache.set(prop, value.bind(target));
                return cache.get(prop);
            }
            return value;
        },
        has(target, prop) {
            if (typeof prop === 'string' && cdcPattern.test(prop)) {
                return false;
            }
            return Reflect.has(target, prop);
        },
        getOwnPropertyDescriptor(target, prop) {
            if (typeof prop === 'string' && cdcPattern.test(prop)) {
                return undefined;
            }
            return Reflect.getOwnPropertyDescriptor(target, prop);
        },
        ownKeys(target) {
            return Reflect.ownKeys(target).filter(key =>
                typeof key !== 'string' || !cdcPattern.test(key)
            );
        }
    });

    Object.defineProperty(window, 'document', {
        get: _eoka_mark(() => documentProxy, 'get document'),
        configurable: true
    });
} catch(e) {
    let cleanupCount = 0;
    const cleanupTimer = setInterval(() => {
        cleanupWindow();
        cleanupDocument();
        if (++cleanupCount >= 10) clearInterval(cleanupTimer);
    }, 200);
}

// Clean up document element attributes
const cleanupDocAttributes = () => {
    const attrs = ['selenium', 'webdriver', 'driver'];
    const docElement = document.documentElement;
    if (docElement) {
        attrs.forEach(attr => {
            try {
                if (docElement.hasAttribute(attr)) {
                    docElement.removeAttribute(attr);
                }
            } catch(e) {}
        });
    }
};

if (document.documentElement) {
    cleanupDocAttributes();
}
document.addEventListener('DOMContentLoaded', cleanupDocAttributes);
"#;

/// Chrome runtime object
pub const CHROME_RUNTIME_EVASION: &str = r#"
window.chrome = {
    runtime: {
        onConnect: {
            addListener: function() {},
            removeListener: function() {}
        },
        onMessage: {
            addListener: function() {},
            removeListener: function() {}
        },
        connect: function() {
            return {
                onMessage: { addListener: function() {} },
                onDisconnect: { addListener: function() {} },
                postMessage: function() {}
            };
        },
        sendMessage: function() {},
        id: undefined
    },
    loadTimes: function() {
        return {
            commitLoadTime: Date.now() / 1000 - _eoka_rand() * 2,
            connectionInfo: "h2",
            finishDocumentLoadTime: Date.now() / 1000 - _eoka_rand(),
            finishLoadTime: Date.now() / 1000 - _eoka_rand() * 0.5,
            firstPaintAfterLoadTime: 0,
            firstPaintTime: Date.now() / 1000 - _eoka_rand() * 1.5,
            navigationType: "Other",
            npnNegotiatedProtocol: "h2",
            requestTime: Date.now() / 1000 - _eoka_rand() * 3,
            startLoadTime: Date.now() / 1000 - _eoka_rand() * 2.5,
            wasAlternateProtocolAvailable: false,
            wasFetchedViaSpdy: true,
            wasNpnNegotiated: true
        };
    },
    csi: function() {
        return {
            onloadT: Date.now(),
            pageT: _eoka_rand() * 1000 + 500,
            startE: Date.now() - _eoka_rand() * 3000,
            tran: 15
        };
    },
    app: {
        isInstalled: false,
        InstallState: { DISABLED: "disabled", INSTALLED: "installed", NOT_INSTALLED: "not_installed" },
        RunningState: { CANNOT_RUN: "cannot_run", READY_TO_RUN: "ready_to_run", RUNNING: "running" }
    }
};
"#;

/// Permissions API consistency fix
pub const PERMISSIONS_EVASION: &str = r#"
// Fix Notification/Permissions API consistency
const originalPermissionsQuery = navigator.permissions.query.bind(navigator.permissions);

try {
    Object.defineProperty(Notification, 'permission', {
        get: _eoka_mark(() => 'default', 'get permission'),
        configurable: true,
        enumerable: true
    });
} catch(e) {}

navigator.permissions.query = _eoka_mark(function query(parameters) {
    const name = parameters.name;

    if (name === 'notifications') {
        return Promise.resolve({
            state: 'prompt',
            name: 'notifications',
            onchange: null,
            addEventListener: function() {},
            removeEventListener: function() {},
            dispatchEvent: function() { return true; }
        });
    }

    if (name === 'clipboard-read' || name === 'clipboard-write') {
        return Promise.resolve({
            state: 'prompt',
            name: name,
            onchange: null,
            addEventListener: function() {},
            removeEventListener: function() {},
            dispatchEvent: function() { return true; }
        });
    }

    return originalPermissionsQuery(parameters).then(function(result) {
        return {
            state: result.state,
            name: result.name || name,
            onchange: result.onchange,
            addEventListener: result.addEventListener?.bind(result) || function() {},
            removeEventListener: result.removeEventListener?.bind(result) || function() {},
            dispatchEvent: result.dispatchEvent?.bind(result) || function() { return true; }
        };
    }).catch(function() {
        return {
            state: 'prompt',
            name: name,
            onchange: null,
            addEventListener: function() {},
            removeEventListener: function() {},
            dispatchEvent: function() { return true; }
        };
    });
}, 'query');
"#;

/// Plugins spoofing - defined on Navigator.prototype with a stable cached reference.
pub const PLUGINS_EVASION: &str = r#"
const _eoka_buildPlugins = () => {
    const plugins = [
        { name: 'PDF Viewer', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
        { name: 'Chrome PDF Viewer', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
        { name: 'Chromium PDF Viewer', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
        { name: 'Microsoft Edge PDF Viewer', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
        { name: 'WebKit built-in PDF', filename: 'internal-pdf-viewer', description: 'Portable Document Format' }
    ];

    const pluginArray = Object.create(PluginArray.prototype);
    plugins.forEach((p, i) => {
        const plugin = Object.create(Plugin.prototype);
        Object.defineProperties(plugin, {
            name: { value: p.name, enumerable: true },
            filename: { value: p.filename, enumerable: true },
            description: { value: p.description, enumerable: true },
            length: { value: 1, enumerable: true }
        });
        pluginArray[i] = plugin;
        pluginArray[p.name] = plugin;
    });

    Object.defineProperty(pluginArray, 'length', { value: plugins.length });
    pluginArray.item = _eoka_mark((i) => pluginArray[i] || null, 'item');
    pluginArray.namedItem = _eoka_mark((name) => pluginArray[name] || null, 'namedItem');
    pluginArray.refresh = _eoka_mark(() => {}, 'refresh');
    return pluginArray;
};

const _eoka_pluginArray = _eoka_buildPlugins();
Object.defineProperty(Navigator.prototype, 'plugins', {
    get: _eoka_mark(() => _eoka_pluginArray, 'get plugins'),
    configurable: true,
    enumerable: true
});
"#;

/// Navigator properties (languages, platform, hardware) filled from the fingerprint.
pub const NAVIGATOR_PROPS_EVASION: &str = r#"
const navProps = {
    languages: { get: () => Object.freeze(__EOKA_LANGUAGES__) },
    language: { get: () => '__EOKA_LANGUAGE__' },
    platform: { get: () => '__EOKA_PLATFORM__' },
    vendor: { get: () => 'Google Inc.' },
    hardwareConcurrency: { get: () => __EOKA_HW__ },
    deviceMemory: { get: () => __EOKA_MEM__ },
    maxTouchPoints: { get: () => 0 }
};
for (const [prop, desc] of Object.entries(navProps)) {
    _eoka_mark(desc.get, 'get ' + prop);
    Object.defineProperty(Navigator.prototype, prop, {
        ...desc,
        configurable: true,
        enumerable: true
    });
}
"#;

/// Headless detection bypass
pub const HEADLESS_EVASION: &str = r#"
// Fix screen properties
Object.defineProperty(screen, 'availWidth', { get: _eoka_mark(() => screen.width, 'get availWidth'), configurable: true });
Object.defineProperty(screen, 'availHeight', { get: _eoka_mark(() => screen.height - 40, 'get availHeight'), configurable: true });

// Mock window dimensions
Object.defineProperty(window, 'outerWidth', { get: _eoka_mark(() => window.innerWidth, 'get outerWidth'), configurable: true });
Object.defineProperty(window, 'outerHeight', { get: _eoka_mark(() => window.innerHeight + 85, 'get outerHeight'), configurable: true });

// Fix window.matchMedia
const originalMatchMedia = window.matchMedia;
if (originalMatchMedia) {
    window.matchMedia = _eoka_mark(function matchMedia(query) {
        const result = originalMatchMedia.call(window, query);
        if (query.includes('prefers-reduced-motion')) {
            return {
                matches: false,
                media: query,
                onchange: null,
                addListener: function() {},
                removeListener: function() {},
                addEventListener: function() {},
                removeEventListener: function() {},
                dispatchEvent: function() { return true; }
            };
        }
        return result;
    }, 'matchMedia');
}

// Ensure window.origin is correct
try {
    if (!window.origin || window.origin === 'null') {
        Object.defineProperty(window, 'origin', {
            get: _eoka_mark(function() { return window.location.origin; }, 'get origin'),
            configurable: true
        });
    }
} catch(e) {}
"#;

/// Battery API fix - Proxy over the real BatteryManager with spoofed values.
pub const BATTERY_EVASION: &str = r#"
const originalGetBattery = Navigator.prototype.getBattery;
if (originalGetBattery) {
    Object.defineProperty(Navigator.prototype, 'getBattery', {
        value: _eoka_mark(function getBattery() {
            return originalGetBattery.call(this).then(function(battery) {
                return new Proxy(battery, {
                    get(target, prop) {
                        switch (prop) {
                            case 'charging': return true;
                            case 'chargingTime': return 0;
                            case 'dischargingTime': return Infinity;
                            case 'level': return 1;
                        }
                        const v = target[prop];
                        return typeof v === 'function' ? v.bind(target) : v;
                    }
                });
            });
        }, 'getBattery'),
        configurable: true,
        writable: true
    });
}
"#;

/// Navigator connection + userAgentData hygiene
pub const NAVIGATOR_EXTRA_EVASION: &str = r#"
if (navigator.userAgentData) {
    const originalGetHighEntropyValues = navigator.userAgentData.getHighEntropyValues?.bind(navigator.userAgentData);
    if (originalGetHighEntropyValues) {
        navigator.userAgentData.getHighEntropyValues = _eoka_mark(function getHighEntropyValues(hints) {
            return originalGetHighEntropyValues(hints).then(function(data) {
                if (data.brands) {
                    data.brands = data.brands.filter(b =>
                        !b.brand.toLowerCase().includes('headless')
                    );
                }
                return data;
            });
        }, 'getHighEntropyValues');
    }
}

// Fix navigator.connection
if (navigator.connection) {
    try {
        const connectionProps = {
            downlink: 10,
            effectiveType: '4g',
            rtt: 50,
            saveData: false
        };

        for (const [key, value] of Object.entries(connectionProps)) {
            try {
                Object.defineProperty(navigator.connection, key, {
                    get: _eoka_mark(() => value, 'get ' + key),
                    configurable: true,
                    enumerable: true
                });
            } catch(e) {}
        }
    } catch(e) {}
}
"#;

/// Combined fingerprint evasion (WebGL + Canvas + Audio).
pub const FINGERPRINT_EVASION: &str = r#"
const _eoka_spoofWebGL = (proto) => {
    const orig = proto.getParameter;
    proto.getParameter = _eoka_mark(function getParameter(p) {
        if (p === 37445) return '__EOKA_WEBGL_VENDOR__';
        if (p === 37446) return '__EOKA_WEBGL_RENDERER__';
        return orig.call(this, p);
    }, 'getParameter');
};
_eoka_spoofWebGL(WebGLRenderingContext.prototype);
if (typeof WebGL2RenderingContext !== 'undefined') _eoka_spoofWebGL(WebGL2RenderingContext.prototype);

// Canvas noise — deterministic, applied on a temp copy.
const _eoka_noiseCanvas = (canvas) => {
    const w = canvas.width | 0, h = canvas.height | 0;
    if (w <= 0 || h <= 0) return canvas;
    try {
        const tmp = document.createElement('canvas');
        tmp.width = w; tmp.height = h;
        const tctx = tmp.getContext('2d');
        tctx.drawImage(canvas, 0, 0);
        const img = tctx.getImageData(0, 0, w, h);
        const data = img.data;
        let s = (__EOKA_NOISE_SEED__ >>> 0) || 1;
        for (let i = 0; i < data.length; i += 4) {
            s = _eoka_lcg(s);
            data[i] = data[i] ^ (s & 1);
        }
        tctx.putImageData(img, 0, 0);
        return tmp;
    } catch(e) {
        return canvas;
    }
};

const origToDataURL = HTMLCanvasElement.prototype.toDataURL;
HTMLCanvasElement.prototype.toDataURL = _eoka_mark(function toDataURL(...args) {
    return origToDataURL.apply(_eoka_noiseCanvas(this), args);
}, 'toDataURL');

const origToBlob = HTMLCanvasElement.prototype.toBlob;
if (origToBlob) {
    HTMLCanvasElement.prototype.toBlob = _eoka_mark(function toBlob(...args) {
        return origToBlob.apply(_eoka_noiseCanvas(this), args);
    }, 'toBlob');
}

// Audio noise — deterministic, applied once per channel buffer.
const origGetChannelData = AudioBuffer.prototype.getChannelData;
const _eoka_audioSeen = new WeakSet();
AudioBuffer.prototype.getChannelData = _eoka_mark(function getChannelData(ch) {
    const d = origGetChannelData.call(this, ch);
    if (!_eoka_audioSeen.has(d)) {
        let s = ((__EOKA_NOISE_SEED__ >>> 0) ^ (ch >>> 0)) >>> 0 || 1;
        for (let i = 0; i < d.length; i += 100) {
            s = _eoka_lcg(s);
            d[i] += (s / 4294967296 - 0.5) * 0.0001;
        }
        _eoka_audioSeen.add(d);
    }
    return d;
}, 'getChannelData');
"#;

/// WebRTC leak protection - prevent real IP from leaking via public STUN.
pub const WEBRTC_EVASION: &str = r#"
if (typeof RTCPeerConnection !== 'undefined') {
    const origRTCPeerConnection = RTCPeerConnection;

    const _eoka_filterServers = (config) => {
        if (config && config.iceServers) {
            config.iceServers = config.iceServers.filter(server => {
                const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
                return !urls.some(url =>
                    /^stuns?:/i.test(url) || /^turns?:/i.test(url)
                );
            });
        }
        return config;
    };

    window.RTCPeerConnection = _eoka_mark(function RTCPeerConnection(config, constraints) {
        return new origRTCPeerConnection(_eoka_filterServers(config), constraints);
    }, 'RTCPeerConnection');

    window.RTCPeerConnection.prototype = origRTCPeerConnection.prototype;
    Object.keys(origRTCPeerConnection).forEach(key => {
        window.RTCPeerConnection[key] = origRTCPeerConnection[key];
    });
}

if (typeof webkitRTCPeerConnection !== 'undefined') {
    window.webkitRTCPeerConnection = window.RTCPeerConnection;
}
"#;

/// Speech synthesis - headless Chrome has 0 voices, real Chrome has many
pub const SPEECH_EVASION: &str = r#"
if (typeof speechSynthesis !== 'undefined') {
    const defaultVoices = [
        { name: 'Alex', lang: 'en-US', localService: true, default: true, voiceURI: 'Alex' },
        { name: 'Samantha', lang: 'en-US', localService: true, default: false, voiceURI: 'Samantha' },
        { name: 'Victoria', lang: 'en-US', localService: true, default: false, voiceURI: 'Victoria' },
        { name: 'Daniel', lang: 'en-GB', localService: true, default: false, voiceURI: 'Daniel' },
        { name: 'Google US English', lang: 'en-US', localService: false, default: false, voiceURI: 'Google US English' }
    ].map(v => {
        const voice = Object.create(SpeechSynthesisVoice.prototype);
        Object.defineProperties(voice, {
            name: { value: v.name, enumerable: true },
            lang: { value: v.lang, enumerable: true },
            localService: { value: v.localService, enumerable: true },
            default: { value: v.default, enumerable: true },
            voiceURI: { value: v.voiceURI, enumerable: true }
        });
        return voice;
    });

    const origGetVoices = speechSynthesis.getVoices.bind(speechSynthesis);
    speechSynthesis.getVoices = _eoka_mark(function getVoices() {
        const voices = origGetVoices();
        return voices.length > 0 ? voices : defaultVoices;
    }, 'getVoices');
}
"#;

/// Media devices - headless returns empty array
pub const MEDIA_DEVICES_EVASION: &str = r#"
if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
    const origEnumerateDevices = navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);

    navigator.mediaDevices.enumerateDevices = _eoka_mark(async function enumerateDevices() {
        const devices = await origEnumerateDevices();
        if (devices.length === 0) {
            const fake = [
                { deviceId: 'default', groupId: '5f8b2c1e9a3d', kind: 'audioinput', label: '' },
                { deviceId: 'default', groupId: '5f8b2c1e9a3d', kind: 'audiooutput', label: '' },
                { deviceId: 'e2d4a6c8b0f1', groupId: '9c3e7a1d4b6f', kind: 'videoinput', label: '' }
            ];
            return fake.map(d => {
                const device = Object.create(MediaDeviceInfo.prototype);
                Object.defineProperties(device, {
                    deviceId: { value: d.deviceId, enumerable: true },
                    groupId: { value: d.groupId, enumerable: true },
                    kind: { value: d.kind, enumerable: true },
                    label: { value: d.label, enumerable: true },
                    toJSON: { value: _eoka_mark(() => d, 'toJSON') }
                });
                return device;
            });
        }
        return devices;
    }, 'enumerateDevices');
}
"#;

/// Bluetooth API - headless throws error, real Chrome returns object
pub const BLUETOOTH_EVASION: &str = r#"
if (!navigator.bluetooth) {
    Object.defineProperty(Navigator.prototype, 'bluetooth', {
        get: _eoka_mark(() => ({
            getAvailability: () => Promise.resolve(false),
            requestDevice: () => Promise.reject(new DOMException('User cancelled', 'NotFoundError')),
            getDevices: () => Promise.resolve([]),
            addEventListener: () => {},
            removeEventListener: () => {},
            dispatchEvent: () => true
        }), 'get bluetooth'),
        configurable: true,
        enumerable: true
    });
}
"#;

/// Timezone consistency - ensure Date timezone matches claimed location.
/// The `__EOKA_TIMEZONE__` placeholder is replaced at build time with the
/// actual IANA timezone from StealthConfig.
pub const TIMEZONE_EVASION: &str = r#"
// Ensure Intl.DateTimeFormat returns consistent timezone
const targetTimezone = '__EOKA_TIMEZONE__';
const origDateTimeFormat = Intl.DateTimeFormat;

Intl.DateTimeFormat = _eoka_mark(function DateTimeFormat(locales, options) {
    if (!options) options = {};
    if (!options.timeZone) options.timeZone = targetTimezone;
    return new origDateTimeFormat(locales, options);
}, 'DateTimeFormat');
Intl.DateTimeFormat.prototype = origDateTimeFormat.prototype;
Intl.DateTimeFormat.supportedLocalesOf = origDateTimeFormat.supportedLocalesOf;

// Override Date.prototype.getTimezoneOffset to match the target timezone.
// Precompute offsets for Jan and Jul to handle DST, avoiding per-call
// toLocaleString() which is ~10x slower than native and timing-detectable.
{
    const _origGetTZO = Date.prototype.getTimezoneOffset;
    function _calcOffset(date) {
        const utcStr = date.toLocaleString('en-US', { timeZone: 'UTC' });
        const tzStr = date.toLocaleString('en-US', { timeZone: targetTimezone });
        return (new Date(utcStr) - new Date(tzStr)) / 60000;
    }
    const year = new Date().getFullYear();
    const janOffset = _calcOffset(new Date(year, 0, 15));
    const julOffset = _calcOffset(new Date(year, 6, 15));
    // Standard offset is the larger value (more positive = further west)
    const stdOffset = Math.max(janOffset, julOffset);
    const dstOffset = Math.min(janOffset, julOffset);
    // If offsets differ, this timezone observes DST
    const hasDST = janOffset !== julOffset;
    // Which months are DST depends on hemisphere: if Jul is the smaller
    // offset, DST is northern-hemisphere (Mar-Nov); otherwise southern.
    const dstIsJul = julOffset < janOffset;

    Date.prototype.getTimezoneOffset = _eoka_mark(function getTimezoneOffset() {
        if (!hasDST) return stdOffset;
        // Quick month-based check — accurate for the vast majority of dates.
        const m = this.getUTCMonth();
        const isDST = dstIsJul ? (m >= 2 && m <= 10) : (m <= 2 || m >= 10);
        return isDST ? dstOffset : stdOffset;
    }, 'getTimezoneOffset');
}
"#;

/// Common timezones for random selection (balanced across regions)
pub(crate) const COMMON_TIMEZONES: &[&str] = &[
    // Americas (4)
    "America/New_York",
    "America/Chicago",
    "America/Los_Angeles",
    "America/Sao_Paulo",
    // Europe (4)
    "Europe/London",
    "Europe/Paris",
    "Europe/Berlin",
    "Europe/Moscow",
    // Asia-Pacific (4)
    "Asia/Tokyo",
    "Asia/Shanghai",
    "Asia/Kolkata",
    "Australia/Sydney",
];

/// Build the complete evasion script for the given config and fingerprint.
pub fn build_evasion_script_for(config: &StealthConfig, fp: &Fingerprint) -> String {
    let timezone = config
        .timezone
        .clone()
        .unwrap_or_else(|| fp.timezone.clone());

    let mut scripts = vec![
        NATIVE_TOSTRING_EVASION, // must be first: defines _eoka_mark / _eoka_rand
        WEBDRIVER_EVASION,
        CDP_EVASION,
        CHROME_RUNTIME_EVASION,
        PERMISSIONS_EVASION,
        PLUGINS_EVASION,
        NAVIGATOR_PROPS_EVASION,
        HEADLESS_EVASION,
        BATTERY_EVASION,
        NAVIGATOR_EXTRA_EVASION,
        WEBRTC_EVASION,
        SPEECH_EVASION,
        MEDIA_DEVICES_EVASION,
        BLUETOOTH_EVASION,
        TIMEZONE_EVASION,
    ];

    if config.webgl_spoof || config.canvas_spoof || config.audio_spoof {
        scripts.push(FINGERPRINT_EVASION);
    }

    let languages_json = format!(
        "[{}]",
        fp.languages
            .iter()
            .map(|l| format!("'{}'", escape_js_string(l)))
            .collect::<Vec<_>>()
            .join(",")
    );
    let language = fp.languages.first().cloned().unwrap_or_default();
    let noise_seed = fastrand::u32(1..=u32::MAX);

    let script = format!("(function(){{{}}})();", scripts.join("\n"));
    script
        .replace("__EOKA_TIMEZONE__", &escape_js_string(&timezone))
        .replace("__EOKA_PLATFORM__", &escape_js_string(fp.nav_platform()))
        .replace("__EOKA_LANGUAGES__", &languages_json)
        .replace("__EOKA_LANGUAGE__", &escape_js_string(&language))
        .replace("__EOKA_HW__", &fp.hardware_concurrency.to_string())
        .replace("__EOKA_MEM__", &fp.device_memory.to_string())
        .replace("__EOKA_WEBGL_VENDOR__", &escape_js_string(&fp.webgl_vendor))
        .replace(
            "__EOKA_WEBGL_RENDERER__",
            &escape_js_string(&fp.webgl_renderer),
        )
        .replace("__EOKA_NOISE_SEED__", &noise_seed.to_string())
}

/// Build the complete evasion script based on config.
pub fn build_evasion_script(config: &StealthConfig) -> String {
    let fp = Fingerprint::resolve(config.user_agent.as_deref(), config.timezone.as_deref());
    build_evasion_script_for(config, &fp)
}

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

    #[test]
    fn test_build_full_script() {
        let config = StealthConfig::default();
        let script = build_evasion_script(&config);
        assert!(script.contains("webdriver"));
        assert!(script.contains("WebGLRenderingContext"));
        assert!(script.contains("HTMLCanvasElement"));
        assert!(script.contains("AudioBuffer"));
    }

    #[test]
    fn test_placeholders_are_filled() {
        let script = build_evasion_script(&StealthConfig::default());
        assert!(
            !script.contains("__EOKA_"),
            "unresolved placeholder in script"
        );
        assert!(script.contains("_eoka_mark"));
    }

    #[test]
    fn test_script_is_wrapped_in_iife() {
        let config = StealthConfig::default();
        let script = build_evasion_script(&config);
        assert!(script.starts_with("(function()"));
        assert!(script.ends_with("})();"));
    }

    // Regression: the script must be driven by the fingerprint, not by old
    // hardcoded values. Build for a known Windows fingerprint and assert the
    // Windows-specific fields flow through while the old Mac constants and
    // removed features do not.
    #[test]
    fn test_build_script_for_known_windows_fp() {
        let fp = Fingerprint::resolve(
            Some("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.7312.86 Safari/537.36"),
            None,
        );
        let config = StealthConfig::default();
        let script = build_evasion_script_for(&config, &fp);

        // navigator.platform comes from the fingerprint (Win32), and the old
        // hardcoded MacIntel must be gone.
        assert!(
            script.contains("'Win32'"),
            "script must contain the fingerprint nav_platform 'Win32'"
        );
        assert!(
            !script.contains("'MacIntel'"),
            "script must not contain the old hardcoded 'MacIntel'"
        );

        // WebGL renderer and hardware values flow from the fingerprint.
        assert!(
            script.contains(&fp.webgl_renderer),
            "script must contain the fingerprint webgl_renderer: {}",
            fp.webgl_renderer
        );
        assert!(
            script.contains(&fp.hardware_concurrency.to_string()),
            "script must contain hardware_concurrency"
        );
        assert!(
            script.contains(&fp.device_memory.to_string()),
            "script must contain device_memory"
        );

        // toString-masking machinery is present.
        assert!(script.contains("_eoka_mark"));
        assert!(script.contains("[native code]"));

        // No leftover placeholders, and the removed beacon must be gone.
        assert!(
            !script.contains("__EOKA_"),
            "script must not contain unresolved placeholders"
        );
        assert!(
            !script.contains("__eoka_pending_requests"),
            "removed request-beacon must not reappear"
        );
    }

    // Escaping regression: config values with a single quote must be routed
    // through escape_js_string, producing an escaped `\'` in the output.
    #[test]
    fn test_config_values_are_js_escaped() {
        let config = StealthConfig {
            timezone: Some("Foo'Bar".into()),
            ..StealthConfig::default()
        };
        let script = build_evasion_script(&config);
        assert!(
            script.contains(r"Foo\'Bar"),
            "timezone single quote must be escaped via escape_js_string"
        );
        assert!(
            !script.contains("'Foo'Bar'"),
            "unescaped single quote must not appear"
        );
    }
}