stygian-browser 0.14.0

Anti-detection browser automation library for Rust with CDP stealth features
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
#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing,
    clippy::missing_const_for_fn
)]
//! Anti-detection validation test suite for stygian-browser.
//!
//! Validates that stealth features successfully evade known detection systems
//! and browser fingerprinting tools.  All tests require a real Chrome/Chromium
//! binary **and** external network access; they are gated with `#[ignore]`.
//!
//! # Running
//!
//! ```sh
//! # Run all detection tests serially (avoids browser startup contention)
//! cargo test -p stygian-browser --test detection -- --ignored --test-threads=1
//!
//! # Run a single test
//! cargo test -p stygian-browser --test detection stealth_webdriver_not_present -- --ignored
//! ```
//!
//! Set `STYGIAN_CHROME_PATH` to override the browser binary path.

use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use stygian_browser::{BrowserConfig, BrowserInstance, WaitUntil};

// ─── Helpers ─────────────────────────────────────────────────────────────────

/// Returns a unique temp dir path per call, preventing Chrome's `SingletonLock`
/// from conflicting when multiple tests allocate browsers sequentially.
fn unique_user_data_dir() -> PathBuf {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let pid = std::process::id();
    std::env::temp_dir().join(format!("stygian-detect-{pid}-{n}"))
}

/// Returns a `BrowserConfig` suitable for detection tests:
/// headless, unique user-data-dir, generous timeouts.
fn test_config() -> BrowserConfig {
    let mut cfg = BrowserConfig::builder().headless(true).build();
    cfg.launch_timeout = Duration::from_secs(30);
    cfg.cdp_timeout = Duration::from_secs(15);
    cfg.user_data_dir = Some(unique_user_data_dir());

    if let Ok(p) = std::env::var("STYGIAN_CHROME_PATH") {
        cfg.chrome_path = Some(PathBuf::from(p));
    }
    cfg
}

// ─── Property-level stealth checks ───────────────────────────────────────────
// These tests use `about:blank` and pure JS evals — they are fast and reliable.

/// `navigator.webdriver` must be undefined/false after stealth injection.
///
/// This is the #1 signal every major anti-bot system checks (`Cloudflare`,
/// `DataDome`, `PerimeterX`).  A truthy value means immediate bot detection.
#[tokio::test]
#[ignore = "requires real Chrome binary and external network access"]
async fn stealth_webdriver_not_present() -> Result<(), Box<dyn std::error::Error>> {
    let instance = BrowserInstance::launch(test_config()).await?;

    let mut page = instance.new_page().await?;
    page.navigate(
        "about:blank",
        WaitUntil::Selector("body".to_string()),
        Duration::from_secs(10),
    )
    .await?;

    let hidden: bool = page
        .eval("typeof navigator.webdriver === 'undefined' || navigator.webdriver === false")
        .await?;

    assert!(
        hidden,
        "navigator.webdriver should be hidden after stealth injection"
    );

    page.close().await?;
    instance.shutdown().await?;
    Ok(())
}

/// `navigator.plugins` must not be empty.
///
/// Real browsers expose at least a few plugin entries.  An empty `PluginArray`
/// is a reliable headless/automation indicator.
#[tokio::test]
#[ignore = "requires real Chrome binary and external network access"]
async fn stealth_plugins_not_empty() -> Result<(), Box<dyn std::error::Error>> {
    let instance = BrowserInstance::launch(test_config()).await?;

    let mut page = instance.new_page().await?;
    page.navigate(
        "about:blank",
        WaitUntil::Selector("body".to_string()),
        Duration::from_secs(10),
    )
    .await?;

    let plugin_count: u32 = page.eval("navigator.plugins.length").await?;

    assert!(
        plugin_count > 0,
        "navigator.plugins should not be empty; got {plugin_count}"
    );

    page.close().await?;
    instance.shutdown().await?;
    Ok(())
}

/// The User-Agent must not contain `"HeadlessChrome"`.
///
/// The headless UA fingerprint is trivially detectable; stealth must replace it
/// with a plausible desktop UA that still contains `"Chrome/"`.
#[tokio::test]
#[ignore = "requires real Chrome binary and external network access"]
async fn stealth_user_agent_not_headless() -> Result<(), Box<dyn std::error::Error>> {
    let instance = BrowserInstance::launch(test_config()).await?;

    let mut page = instance.new_page().await?;
    page.navigate(
        "about:blank",
        WaitUntil::Selector("body".to_string()),
        Duration::from_secs(10),
    )
    .await?;

    let ua: String = page.eval("navigator.userAgent").await?;

    assert!(
        !ua.contains("HeadlessChrome"),
        "User-Agent must not contain 'HeadlessChrome'; got: {ua}"
    );
    assert!(
        ua.contains("Chrome/"),
        "User-Agent should contain 'Chrome/'; got: {ua}"
    );

    page.close().await?;
    instance.shutdown().await?;
    Ok(())
}

/// `window.chrome` must be defined.
///
/// Anti-bot systems verify the presence and structure of `window.chrome` as a
/// Chrome authenticity signal.  Headless Chrome omits this object by default.
#[tokio::test]
#[ignore = "requires real Chrome binary and external network access"]
async fn stealth_chrome_object_present() -> Result<(), Box<dyn std::error::Error>> {
    let instance = BrowserInstance::launch(test_config()).await?;

    let mut page = instance.new_page().await?;
    page.navigate(
        "about:blank",
        WaitUntil::Selector("body".to_string()),
        Duration::from_secs(10),
    )
    .await?;

    let chrome_defined: bool = page.eval("typeof window.chrome !== 'undefined'").await?;

    assert!(
        chrome_defined,
        "window.chrome should be defined after stealth injection"
    );

    page.close().await?;
    instance.shutdown().await?;
    Ok(())
}

/// CDP-injected automation properties (`$cdc_*`, `$chrome_asyncScriptInfo`) must
/// be absent from `window`.
///
/// `ChromeDriver` injects these globals and detection scripts check for them.
/// Our CDP protection mode should prevent their appearance.
#[tokio::test]
#[ignore = "requires real Chrome binary and external network access"]
async fn stealth_cdp_automation_properties_absent() -> Result<(), Box<dyn std::error::Error>> {
    let instance = BrowserInstance::launch(test_config()).await?;

    let mut page = instance.new_page().await?;
    page.navigate(
        "about:blank",
        WaitUntil::Selector("body".to_string()),
        Duration::from_secs(10),
    )
    .await?;

    // Scan all window keys for the two known ChromeDriver artifacts.
    let cdc_present: bool = page
        .eval(
            r"Object.keys(window).some(k =>
                k.startsWith('$cdc_') || k.startsWith('$chrome_asyncScript')
            )",
        )
        .await?;

    assert!(
        !cdc_present,
        "$cdc_* and $chrome_asyncScript* properties must be absent from window"
    );

    page.close().await?;
    instance.shutdown().await?;
    Ok(())
}

/// `navigator.permissions` must be present and functional.
///
/// Some anti-bot systems probe the Permissions API to distinguish real browsers
/// from headless environments that omit it.
#[tokio::test]
#[ignore = "requires real Chrome binary and external network access"]
async fn stealth_permissions_api_present() -> Result<(), Box<dyn std::error::Error>> {
    let instance = BrowserInstance::launch(test_config()).await?;

    let mut page = instance.new_page().await?;
    page.navigate(
        "about:blank",
        WaitUntil::Selector("body".to_string()),
        Duration::from_secs(10),
    )
    .await?;

    let api_present: bool = page
        .eval("typeof navigator.permissions !== 'undefined' && typeof navigator.permissions.query === 'function'")
        .await?;

    assert!(
        api_present,
        "navigator.permissions should be present and expose query()"
    );

    page.close().await?;
    instance.shutdown().await?;
    Ok(())
}

/// `navigator.language` and `navigator.vendor` must be non-empty strings.
///
/// Empty values are never present in real-user browsers and indicate an
/// improperly configured automation environment.
#[tokio::test]
#[ignore = "requires real Chrome binary and external network access"]
async fn stealth_language_and_vendor_not_empty() -> Result<(), Box<dyn std::error::Error>> {
    let instance = BrowserInstance::launch(test_config()).await?;

    let mut page = instance.new_page().await?;
    page.navigate(
        "about:blank",
        WaitUntil::Selector("body".to_string()),
        Duration::from_secs(10),
    )
    .await?;

    let language: String = page.eval("navigator.language || ''").await?;
    let vendor: String = page.eval("navigator.vendor || ''").await?;

    assert!(
        !language.is_empty(),
        "navigator.language should not be empty"
    );
    assert!(!vendor.is_empty(), "navigator.vendor should not be empty");

    page.close().await?;
    instance.shutdown().await?;
    Ok(())
}

// ─── Real-world detection site checks ────────────────────────────────────────
// These require external network access.  They validate the same properties as
// above but via third-party detection pages to catch regressions early.

/// Navigate to `bot.sannysoft.com` and verify critical bot signals pass.
///
/// The site renders a table of automated bot-detection tests.  Regardless of
/// the page layout, we validate the critical navigator properties directly.
#[tokio::test]
#[ignore = "requires real Chrome binary and external network access"]
async fn sannysoft_critical_signals_pass() -> Result<(), Box<dyn std::error::Error>> {
    let instance = BrowserInstance::launch(test_config()).await?;

    let mut page = instance.new_page().await?;
    page.navigate(
        "https://bot.sannysoft.com",
        WaitUntil::Selector("table".to_string()),
        Duration::from_secs(45),
    )
    .await?;

    let webdriver_hidden: bool = page
        .eval("typeof navigator.webdriver === 'undefined' || navigator.webdriver === false")
        .await?;

    let ua: String = page.eval("navigator.userAgent").await?;

    let plugins: u32 = page.eval("navigator.plugins.length").await?;

    assert!(
        webdriver_hidden,
        "sannysoft: navigator.webdriver should be hidden"
    );
    assert!(
        !ua.contains("HeadlessChrome"),
        "sannysoft: UA should not be headless; got: {ua}"
    );
    assert!(
        plugins > 0,
        "sannysoft: navigator.plugins should not be empty; got {plugins}"
    );

    page.close().await?;
    instance.shutdown().await?;
    Ok(())
}

/// Navigate to `browserleaks.com/javascript` and verify no automation signals.
///
/// `BrowserLeaks` displays navigator properties that fingerprinting scripts read.
/// Core properties must have plausible values (non-empty, non-headless).
#[tokio::test]
#[ignore = "requires real Chrome binary and external network access"]
async fn browserleaks_no_automation_signals() -> Result<(), Box<dyn std::error::Error>> {
    let instance = BrowserInstance::launch(test_config()).await?;

    let mut page = instance.new_page().await?;
    page.navigate(
        "https://browserleaks.com/javascript",
        WaitUntil::Selector("body".to_string()),
        Duration::from_secs(30),
    )
    .await?;

    let webdriver_hidden: bool = page
        .eval("typeof navigator.webdriver === 'undefined' || navigator.webdriver === false")
        .await?;

    let language: String = page.eval("navigator.language || ''").await?;

    let vendor: String = page.eval("navigator.vendor || ''").await?;

    assert!(
        webdriver_hidden,
        "browserleaks: navigator.webdriver must be hidden"
    );
    assert!(
        !language.is_empty(),
        "browserleaks: navigator.language must not be empty"
    );
    assert!(
        !vendor.is_empty(),
        "browserleaks: navigator.vendor must not be empty"
    );

    page.close().await?;
    instance.shutdown().await?;
    Ok(())
}

/// Navigate to `CreepJS` and confirm the page loads without a bot-crash.
///
/// `CreepJS` runs thorough fingerprinting; a blocked/error page would be
/// shorter than a few hundred bytes.  We also check the baseline properties.
#[tokio::test]
#[ignore = "requires real Chrome binary and external network access"]
async fn creepjs_page_loads_without_bot_crash() -> Result<(), Box<dyn std::error::Error>> {
    let instance = BrowserInstance::launch(test_config()).await?;

    let mut page = instance.new_page().await?;
    // CreepJS is JS-heavy; give it extra time.
    page.navigate(
        "https://abrahamjuliot.github.io/creepjs/",
        WaitUntil::Selector("body".to_string()),
        Duration::from_mins(1),
    )
    .await?;

    let html = page.content().await?;
    assert!(
        html.len() > 500,
        "page content too short — may have been blocked (got {} bytes)",
        html.len()
    );

    // Baseline signal: webdriver must still be hidden on this page.
    let webdriver_hidden: bool = page
        .eval("typeof navigator.webdriver === 'undefined' || navigator.webdriver === false")
        .await?;

    assert!(
        webdriver_hidden,
        "creepjs: navigator.webdriver must be hidden"
    );

    page.close().await?;
    instance.shutdown().await?;
    Ok(())
}