eoka 0.17.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
use super::*;

#[test]
fn test_build_full_script() {
    let config = StealthConfig::default();
    let script = build_evasion_script(&config);
    // Chrome 154+ already reports these natively; no repair script ships.
    for gone in [
        "navigator.webdriver",
        "window.chrome",
        "supportedEntryTypes",
        "Notification.permission",
    ] {
        assert!(!script.contains(gone), "{gone}");
    }
    assert!(script.contains("WebGLRenderingContext"));
    assert!(script.contains("HTMLCanvasElement"));
    assert!(script.contains("AudioBuffer"));
    assert!(!script.contains("const documentProxy"));
}

#[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 worker_script_placeholders_are_filled() {
    let fp = Fingerprint::resolve(None, None);
    let script = build_worker_evasion_script(&StealthConfig::default(), &fp);
    assert!(
        !script.contains("__EOKA_"),
        "unresolved placeholder in worker script"
    );
    assert!(script.contains("WorkerNavigator"));
}

#[test]
fn worker_webgl_and_canvas_are_gated_by_fingerprint_spoofing() {
    let fp = Fingerprint::resolve(None, None);
    let on = build_worker_evasion_script(&StealthConfig::default(), &fp);
    assert!(on.contains("'getParameter'"));
    assert!(on.contains("'convertToBlob'"));
    let off = build_worker_evasion_script(
        &StealthConfig {
            fingerprint_spoofing: false,
            ..StealthConfig::default()
        },
        &fp,
    );
    assert!(!off.contains("'getParameter'"));
    assert!(!off.contains("'convertToBlob'"));
}

#[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 device memory flow from the fingerprint
    // (hardwareConcurrency comes from a CDP override, not the script).
    assert!(
        script.contains(&fp.webgl_renderer),
        "script must contain the fingerprint webgl_renderer: {}",
        fp.webgl_renderer
    );
    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: fingerprint 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 mut fp = Fingerprint::random();
    fp.languages = vec!["Foo'Bar".into()];
    let script = build_evasion_script_for(&StealthConfig::default(), &fp);
    assert!(
        script.contains(r"Foo\'Bar"),
        "language single quote must be escaped via escape_js_string"
    );
    assert!(
        !script.contains("'Foo'Bar'"),
        "unescaped single quote must not appear"
    );
}

// Audit regression: stock Linux Chrome has no `navigator.bluetooth`, so a Linux
// identity must not claim it. `navigator.deviceMemory` is different: Linux
// Chrome does expose it, but only in secure contexts, so the spoof is gated on
// the native attribute existing rather than on the platform. Assertions stay on
// single lines so CRLF checkouts (Windows CI) see the same script text.
#[test]
fn test_platform_gated_navigator_apis() {
    let linux_fp = Fingerprint::resolve(
        Some("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.7312.86 Safari/537.36"),
        None,
    );
    let script = build_evasion_script_for(&StealthConfig::default(), &linux_fp);
    assert!(
        script.contains(
            "if (!/Linux/i.test('Linux x86_64') && window.isSecureContext && !navigator.bluetooth)"
        ),
        "Linux script must leave navigator.bluetooth absent"
    );
    assert!(
        script.contains("deviceMemory: () => "),
        "Linux Chrome exposes deviceMemory, so the fingerprint value must replace the host's"
    );
    assert!(
        script.contains("if (!('deviceMemory' in Navigator.prototype))"),
        "deviceMemory must only be spoofed where the native [SecureContext] attribute exists"
    );

    let windows_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 windows_script = build_evasion_script_for(&StealthConfig::default(), &windows_fp);
    assert!(
        windows_script.contains(
            "if (!/Linux/i.test('Win32') && window.isSecureContext && !navigator.bluetooth)"
        ),
        "Windows script must fill a missing navigator.bluetooth"
    );
    assert!(
        windows_script.contains("deviceMemory: () => "),
        "Windows script must keep the deviceMemory claim"
    );
}

// Audit regression: the old matchMedia wrapper reported matches:false for
// BOTH prefers-reduced-motion variants — an impossible state (one always
// matches in real Chrome) — and returned a non-MediaQueryList object.
#[test]
fn test_match_media_is_not_wrapped() {
    let script = build_evasion_script(&StealthConfig::default());
    assert!(
        !script.contains("originalMatchMedia"),
        "matchMedia must not be wrapped: stock headless/new reports the correct pair"
    );
}

// Audit regression: fallback voices must match the claimed platform.
// Alex/Samantha are macOS-only; Microsoft David/Zira are Windows-only;
// stock Linux Chrome has no built-in voices (pass-through).
#[test]
fn test_speech_voices_match_platform() {
    let voices_for = |ua: &str| {
        let fp = Fingerprint::resolve(Some(ua), None);
        let script = build_evasion_script_for(&StealthConfig::default(), &fp);
        let start = script
            .find("const defaultVoices = ")
            .expect("voices array present")
            + "const defaultVoices = ".len();
        let end = script[start..]
            .find(".map(v =>")
            .expect("voices array terminated");
        script[start..start + end].trim().to_string()
    };

    let linux = voices_for("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36");
    assert_eq!(
        linux, "[]",
        "Linux identities must pass through with no voices"
    );

    let mac = voices_for("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36");
    let mac_json: serde_json::Value =
        serde_json::from_str(&mac).expect("macOS voices must be valid JSON");
    let mac_names: Vec<&str> = mac_json
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v["name"].as_str().unwrap())
        .collect();
    assert!(mac_names.contains(&"Alex"), "macOS list must contain Alex");
    assert!(!mac_names.iter().any(|n| n.starts_with("Microsoft")));

    let win = voices_for("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36");
    let win_json: serde_json::Value =
        serde_json::from_str(&win).expect("Windows voices must be valid JSON");
    let win_names: Vec<&str> = win_json
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v["name"].as_str().unwrap())
        .collect();
    assert!(
        win_names.iter().any(|n| n.starts_with("Microsoft David")),
        "Windows list must contain Microsoft David"
    );
    assert!(!win_names.contains(&"Alex"), "Alex is macOS-only");
}

// Audit regression: fake media-device IDs used to be one hardcoded
// constant shared by every eoka session, linking all identities. They are
// now fingerprint data (spec + noise seed), stable per identity and
// distinct across identities.
#[test]
fn test_media_device_ids_are_seeded_per_fingerprint() {
    let devices_json = |script: &str| -> serde_json::Value {
        let start = script
            .find("const fakeDevices = ")
            .expect("fake device list present")
            + "const fakeDevices = ".len();
        let end = script[start..].find(';').expect("device list terminated");
        serde_json::from_str(&script[start..start + end])
            .expect("media device list must be valid JSON")
    };

    let script = build_evasion_script(&StealthConfig::default());
    assert!(
        !script.contains("5f8b2c1e9a3d"),
        "hardcoded cross-session groupId must not reappear"
    );

    let devices = devices_json(&script).as_array().cloned().unwrap();
    assert!(!devices.is_empty());
    let mut ids: Vec<&str> = devices
        .iter()
        .map(|d| d["deviceId"].as_str().unwrap())
        .collect();
    let defaults = ids.iter().filter(|id| **id == "default").count();
    ids.retain(|id| *id != "default");
    assert_eq!(
        ids.len(),
        ids.iter().collect::<std::collections::HashSet<_>>().len(),
        "non-default device IDs must be unique within an identity"
    );
    assert!(
        ids.iter().all(|id| id.len() == 12),
        "device IDs must be 12 hex chars like real enumerated IDs"
    );
    assert!(defaults >= 2, "audio in/out pair should include 'default'");

    // Different fingerprints must present different hardware IDs. The
    // identity (and therefore the seed) is randomized per build.
    let fps_a = Fingerprint::random();
    let fps_b = Fingerprint::random();
    let ids_a =
        devices_json(&build_evasion_script_for(&StealthConfig::default(), &fps_a)).to_string();
    let ids_b =
        devices_json(&build_evasion_script_for(&StealthConfig::default(), &fps_b)).to_string();
    assert_ne!(
        ids_a, ids_b,
        "distinct identities must not share device IDs (linkability)"
    );
}

// Audit regression: canvas reads through getImageData must carry the same
// noise as toDataURL/toBlob, or a page comparing both flags the hook.
#[test]
fn test_get_image_data_is_noised_with_fingerprint_spoofing() {
    let on = build_evasion_script(&StealthConfig::default());
    assert!(
        on.contains("'CanvasRenderingContext2D'") && on.contains("'getImageData'"),
        "getImageData must be hooked when canvas spoofing is on"
    );

    let off = build_evasion_script(&StealthConfig {
        fingerprint_spoofing: false,
        ..StealthConfig::default()
    });
    assert!(
        !off.contains("getImageData"),
        "canvas hooks must be absent when fingerprint spoofing is off"
    );
}

// `fingerprint_spoofing` gates WebGL, canvas and audio together.
#[test]
fn test_fingerprint_spoofing_gates_webgl_canvas_and_audio() {
    let build = |fingerprint_spoofing| {
        build_evasion_script(&StealthConfig {
            fingerprint_spoofing,
            ..StealthConfig::default()
        })
    };
    let has = |script: &str| {
        (
            script.contains("'getParameter'"),
            script.contains("'getImageData'"),
            script.contains("'getChannelData'"),
        )
    };
    assert_eq!(has(&build(true)), (true, true, true));
    assert_eq!(has(&build(false)), (false, false, false));
}

// Regression: the timezone shim (month-based DST guess, Intl.DateTimeFormat
// replacement) and the RTCPeerConnection wrapper are gone. Timezone is native
// (Emulation.setTimezoneOverride) and WebRTC is a launch flag.
#[test]
fn test_no_timezone_or_webrtc_shims() {
    let script = build_evasion_script(&StealthConfig::default());
    for needle in [
        "getTimezoneOffset",
        "Intl.DateTimeFormat",
        "RTCPeerConnection",
        "iceServers",
    ] {
        assert!(!script.contains(needle), "{needle} must not be patched");
    }
}

// Regression: overrides used to be assigned on instances
// (`navigator.permissions.query = ...`) with constructible function
// expressions. Every patch must go through the prototype helpers.
#[test]
fn test_overrides_use_prototype_helpers() {
    let script = build_evasion_script(&StealthConfig::default());
    for instance_assignment in [
        "navigator.permissions.query =",
        "speechSynthesis.getVoices =",
        "navigator.mediaDevices.enumerateDevices =",
        "navigator.keyboard.getLayoutMap =",
        "document.fonts.check =",
        "navigator.userAgentData.getHighEntropyValues =",
        "Object.defineProperty(navigator.connection",
        ".prototype.getParameter =",
        ".prototype.toDataURL =",
        ".prototype.getImageData =",
        ".prototype.getChannelData =",
    ] {
        assert!(
            !script.contains(instance_assignment),
            "{instance_assignment} must use _eoka_patchMethod/_eoka_patchGetter"
        );
    }
    assert!(script.contains("const _eoka_patchMethod"));
    assert!(script.contains("const _eoka_patchGetter"));
    assert!(
        script.contains("const _eoka_languages = Object.freeze("),
        "navigator.languages must return one cached frozen array"
    );
}

#[test]
fn test_escape_js_string() {
    assert_eq!(escape_js_string("hello"), "hello");
    assert_eq!(escape_js_string("it's"), "it\\'s");
    assert_eq!(escape_js_string("line1\nline2"), "line1\\nline2");
    assert_eq!(escape_js_string("back\\slash"), "back\\\\slash");
    assert_eq!(escape_js_string("${var}"), "\\${var}");
    // Null byte escaped as \x00
    assert_eq!(escape_js_string("a\0b"), "a\\x00b");
    assert_eq!(escape_js_string("a\0"), "a\\x00");
    assert_eq!(escape_js_string("a\u{0}1"), "a\\x001");
    assert_eq!(escape_js_string("a\u{2028}b"), "a\\u2028b");
    assert_eq!(escape_js_string("a\u{2029}b"), "a\\u2029b");
}

#[test]
fn test_escape_js_string_null_is_hex_not_octal() {
    // '\0' must become the hex escape \x00, never the octal \0 (which
    // would be ambiguous when followed by a digit and could be parsed
    // as an octal escape by a JS engine).
    assert_eq!(escape_js_string("\0"), "\\x00");
    assert_ne!(escape_js_string("\0"), "\\0");
    // Followed by a digit: must stay "\x001", not "\01".
    assert_eq!(escape_js_string("a\u{0}1"), "a\\x001");
}

#[test]
fn test_escape_js_string_all_special_chars() {
    assert_eq!(escape_js_string("'"), "\\'");
    assert_eq!(escape_js_string("\""), "\\\"");
    assert_eq!(escape_js_string("`"), "\\`");
    assert_eq!(escape_js_string("\\"), "\\\\");
    assert_eq!(escape_js_string("\n"), "\\n");
    assert_eq!(escape_js_string("\r"), "\\r");
    assert_eq!(escape_js_string("${"), "\\${");
    assert_eq!(escape_js_string("\u{2028}"), "\\u2028");
    assert_eq!(escape_js_string("\u{2029}"), "\\u2029");
}

// Regression: the fonts and keyboard hooks must be present and driven by
// fingerprint data, with Linux keyboard passing through untouched.
#[test]
fn fonts_and_keyboard_hooks_are_fingerprint_driven() {
    let windows_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 windows_script = build_evasion_script_for(&StealthConfig::default(), &windows_fp);
    assert!(windows_script.contains("FontFaceSet.prototype, 'check'"));
    assert!(
        windows_script.contains(&serde_json::to_string(&windows_fp.fonts).unwrap()),
        "claimed font set must flow into the script"
    );
    assert!(windows_script.contains("getLayoutMap"));

    let linux_fp = Fingerprint::resolve(
        Some("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.7312.86 Safari/537.36"),
        None,
    );
    let linux_script = build_evasion_script_for(&StealthConfig::default(), &linux_fp);
    assert!(
        linux_script.contains("Keyboard.prototype.getLayoutMap && null)"),
        "Linux keyboard spoof must be inert"
    );
}