eoka 0.10.2

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
#![cfg(unix)]

use eoka::{Browser, StealthConfig};
use std::{
    os::unix::fs::PermissionsExt,
    path::{Path, PathBuf},
    process::Command,
};

struct Directory(PathBuf);
impl Directory {
    fn new() -> Self {
        let path = std::env::temp_dir().join(format!("eoka-rt-{:08x}", fastrand::u32(..)));
        std::fs::create_dir(&path).unwrap();
        Self(path)
    }
}
impl Drop for Directory {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

fn executable(path: &Path, body: &str) {
    std::fs::write(path, body).unwrap();
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).unwrap();
}

async fn failed_launch(root: &Path, sandbox: bool, caller_profile: bool) {
    let runtime = root.join("runtime");
    let profile = root.join("caller-profile");
    std::fs::create_dir_all(&profile).unwrap();
    std::fs::write(profile.join("keep"), "caller data").unwrap();
    if caller_profile {
        std::fs::write(
            profile.join("DevToolsActivePort"),
            "9\n/devtools/browser/stale\n",
        )
        .unwrap();
    }
    let source = root.join("chrome-fixture");
    let evidence = root.join("launch.txt");
    let body = format!("#!/bin/sh\nif [ \"$1\" = --version ]; then printf 'Chrome 155.0.8059.39\\n'; exit 0; fi\nprintf '%s\\n' \"$TMPDIR\" \"$TMP\" \"$TEMP\" \"$@\" > '{}'\nprintf 'fixture launch failure\\n' >&2\nexit 23\n", evidence.display());
    executable(&source, &body);
    let config = StealthConfig {
        chrome_path: Some(source.to_string_lossy().into_owned()),
        runtime_dir: Some(runtime.to_string_lossy().into_owned()),
        sandbox,
        patch_binary: false,
        user_data_dir: caller_profile.then(|| profile.to_string_lossy().into_owned()),
        ..Default::default()
    };
    let error = Browser::launch_with_config(config)
        .await
        .err()
        .expect("fixture must fail");
    assert!(
        error.to_string().contains("fixture launch failure"),
        "{error}"
    );
    let evidence = std::fs::read_to_string(evidence).unwrap();
    let lines: Vec<_> = evidence.lines().collect();
    let child = Path::new(lines[0]);
    assert_eq!(
        std::fs::canonicalize(child.parent().unwrap()).unwrap(),
        std::fs::canonicalize(&runtime).unwrap()
    );
    assert_eq!(lines[0], lines[1]);
    assert_eq!(lines[0], lines[2]);
    assert!(!child.exists(), "failed launch leaked runtime");
    assert_eq!(lines.contains(&"--no-sandbox"), !sandbox);
    let launched_profile = lines
        .iter()
        .find_map(|arg| arg.strip_prefix("--user-data-dir="))
        .unwrap();
    if caller_profile {
        assert_eq!(Path::new(launched_profile), profile);
    } else {
        assert_eq!(Path::new(launched_profile), child.join("profile"));
    }
    assert!(runtime.exists());
    assert_eq!(std::fs::read_to_string(source).unwrap(), body);
    assert_eq!(
        std::fs::read_to_string(profile.join("keep")).unwrap(),
        "caller data"
    );
}

#[tokio::test]
async fn failed_launch_preserves_caller_data_and_matches_sandbox_policy() {
    for sandbox in [false, true] {
        for caller_profile in [false, true] {
            let root = Directory::new();
            failed_launch(&root.0, sandbox, caller_profile).await;
        }
    }
}

#[tokio::test]
async fn failed_launch_preserves_aliased_runtime_parent() {
    let root = Directory::new();
    let alias = root.0.join("alias");
    std::os::unix::fs::symlink(&root.0, &alias).unwrap();
    failed_launch(&alias, false, true).await;
}

#[tokio::test]
async fn explicit_runtime_ignores_unusable_default_temp() {
    if let Some(root) = std::env::var_os("EOKA_RUNTIME_TEMP_FIXTURE") {
        failed_launch(Path::new(&root), false, false).await;
        return;
    }
    let root = Directory::new();
    let unusable = root.0.join("not-a-directory");
    std::fs::write(&unusable, "occupied").unwrap();
    let status = Command::new(std::env::current_exe().unwrap())
        .args([
            "--exact",
            "explicit_runtime_ignores_unusable_default_temp",
            "--nocapture",
        ])
        .env("EOKA_RUNTIME_TEMP_FIXTURE", &root.0)
        .env("TMPDIR", &unusable)
        .env("TMP", &unusable)
        .env("TEMP", &unusable)
        .status()
        .unwrap();
    assert!(status.success());
}

#[tokio::test]
async fn invalid_explicit_executables_do_not_create_runtime_or_touch_active_profile() {
    let root = Directory::new();
    let profile = root.0.join("profile");
    std::fs::create_dir(&profile).unwrap();
    std::os::unix::fs::symlink(
        format!("fixture-{}", std::process::id()),
        profile.join("SingletonLock"),
    )
    .unwrap();
    std::fs::write(profile.join("keep"), "keep").unwrap();
    let not_executable = root.0.join("not-executable");
    std::fs::write(&not_executable, "not a browser").unwrap();
    std::fs::set_permissions(&not_executable, std::fs::Permissions::from_mode(0o600)).unwrap();
    for path in [
        root.0.join("missing"),
        root.0.clone(),
        not_executable,
        PathBuf::from("relative-chrome"),
    ] {
        let runtime = root.0.join("runtime");
        let error = Browser::launch_with_config(StealthConfig {
            chrome_path: Some(path.to_string_lossy().into_owned()),
            runtime_dir: Some(runtime.to_string_lossy().into_owned()),
            user_data_dir: Some(profile.to_string_lossy().into_owned()),
            ..Default::default()
        })
        .await
        .err()
        .expect("explicit invalid executable must fail");
        assert!(!error.to_string().contains("already running"), "{error}");
        assert!(!runtime.exists());
        assert_eq!(
            std::fs::read_to_string(profile.join("keep")).unwrap(),
            "keep"
        );
        assert!(std::fs::symlink_metadata(profile.join("SingletonLock")).is_ok());
    }
}

#[tokio::test]
#[ignore = "requires Chrome; verifies explicit binary and owned runtime cleanup with a retained Page"]
async fn owned_close_and_drop_clean_runtime_with_live_page_handles() {
    let chrome = eoka::stealth::find_chrome().unwrap();
    let root = Directory::new();
    for close in [false, true] {
        let browser = Browser::launch_with_config(StealthConfig {
            chrome_path: Some(chrome.to_string_lossy().into_owned()),
            runtime_dir: Some(root.0.to_string_lossy().into_owned()),
            ..Default::default()
        })
        .await
        .unwrap();
        assert!(browser.owns_process());
        let page = browser.new_blank_page().await.unwrap();
        let children: Vec<_> = std::fs::read_dir(&root.0)
            .unwrap()
            .map(|entry| entry.unwrap().file_name())
            .collect();
        assert_eq!(children.len(), 1, "close={close}: {children:?}");
        if close {
            browser.close().await.unwrap();
        } else {
            drop(browser);
        }
        let left: Vec<_> = std::fs::read_dir(&root.0)
            .unwrap()
            .map(|entry| entry.unwrap().file_name())
            .collect();
        assert!(left.is_empty(), "close={close}: {left:?}");
        drop(page);
    }
}

#[tokio::test]
async fn explicit_policy_rejects_active_profile_and_sandbox_extra_args() {
    let root = Directory::new();
    let profile = root.0.join("profile");
    std::fs::create_dir(&profile).unwrap();
    std::os::unix::fs::symlink(
        format!("fixture-{}", std::process::id()),
        profile.join("SingletonLock"),
    )
    .unwrap();
    let source = root.0.join("chrome");
    executable(&source, "#!/bin/sh\nexit 99\n");
    for policy in 0..2 {
        let config = StealthConfig {
            chrome_path: (policy == 0).then(|| source.to_string_lossy().into_owned()),
            runtime_dir: (policy == 1)
                .then(|| root.0.join("runtime").to_string_lossy().into_owned()),
            user_data_dir: Some(profile.to_string_lossy().into_owned()),
            ..Default::default()
        };
        let error = Browser::launch_with_config(config)
            .await
            .err()
            .expect("active profile policy must fail");
        assert!(error.to_string().contains("already running"), "{error}");
        assert!(std::fs::symlink_metadata(profile.join("SingletonLock")).is_ok());
    }
}

#[cfg(target_os = "linux")]
#[tokio::test]
async fn sandboxed_default_borrows_only_verifiably_sandboxed_profiles() {
    assert!(StealthConfig::default().sandbox, "sandbox must default on");
    let root = Directory::new();
    let profile = root.0.join("profile");
    std::fs::create_dir(&profile).unwrap();
    let launch = || {
        Browser::launch_with_config(StealthConfig {
            user_data_dir: Some(profile.to_string_lossy().into_owned()),
            ..Default::default()
        })
    };
    let lock = |pid: u32| {
        // /proc/<pid>/cmdline is empty until execve sets up the new argv.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        while std::fs::read(format!("/proc/{pid}/cmdline"))
            .map_or(true, |raw| !raw.windows(10).any(|w| w == b"--headless"))
        {
            assert!(
                std::time::Instant::now() < deadline,
                "fixture argv never appeared"
            );
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        let _ = std::fs::remove_file(profile.join("SingletonLock"));
        std::os::unix::fs::symlink(format!("fixture-{pid}"), profile.join("SingletonLock"))
            .unwrap();
    };

    // An unsandboxed live process is never borrowed by a sandboxed launch.
    let mut unsandboxed = Command::new("sh")
        .args([
            "-c",
            "sleep 30; exit 0",
            "sh",
            "--headless=new",
            "--no-sandbox",
        ])
        .spawn()
        .unwrap();
    lock(unsandboxed.id());
    let error = launch().await.err().expect("unsandboxed reuse must fail");
    unsandboxed.kill().unwrap();
    unsandboxed.wait().unwrap();
    assert!(error.to_string().contains("verifiable sandbox"), "{error}");

    // A process without sandbox-disabling flags passes the sandbox check and
    // proceeds to normal attach (which fails here only for lack of a port).
    let mut sandboxed = Command::new("sh")
        .args(["-c", "sleep 30; exit 0", "sh", "--headless=new"])
        .spawn()
        .unwrap();
    lock(sandboxed.id());
    let error = launch().await.err().expect("fixture has no DevTools port");
    sandboxed.kill().unwrap();
    sandboxed.wait().unwrap();
    assert!(error.to_string().contains("debug port"), "{error}");
}

#[tokio::test]
async fn sandbox_extra_args_are_rejected() {
    let root = Directory::new();
    let source = root.0.join("chrome");
    executable(&source, "#!/bin/sh\nexit 99\n");
    for sandbox in [false, true] {
        let error = Browser::launch_with_config(StealthConfig {
            chrome_path: Some(source.to_string_lossy().into_owned()),
            runtime_dir: Some(root.0.join("unused-runtime").to_string_lossy().into_owned()),
            sandbox,
            extra_args: vec!["--no-sandbox".into()],
            ..Default::default()
        })
        .await
        .err()
        .expect("sandbox flags must not bypass config");
        assert!(
            error.to_string().contains("StealthConfig.sandbox"),
            "{error}"
        );
        assert!(!root.0.join("unused-runtime").exists());
    }
}

#[tokio::test]
async fn cancellation_cleans_process_and_runtime_before_and_during_websocket_handoff() {
    for phase in 0..3 {
        let websocket_handoff = phase == 2;
        let root = Directory::new();
        let runtime = root.0.join("runtime");
        let source = root.0.join("chrome");
        let pid_file = root.0.join("pid");
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let endpoint = if websocket_handoff {
            format!("printf 'DevTools listening on ws://127.0.0.1:{port}/devtools/browser/fixture\\n' >&2\n")
        } else {
            String::new()
        };
        let version_command = if phase == 0 {
            format!(
                "printf '%s\\n' \"$$\" > '{}'; exec /bin/sleep 30",
                pid_file.display()
            )
        } else {
            "printf 'Chrome 155.0.8059.39\\n'; exit 0".into()
        };
        executable(&source, &format!(
            "#!/bin/sh\nif [ \"$1\" = --version ]; then {}; fi\nprintf '%s\\n' \"$$\" > '{}'\n{}exec /bin/sleep 30\n",
            version_command, pid_file.display(), endpoint,
        ));
        let config = StealthConfig {
            chrome_path: Some(source.to_string_lossy().into_owned()),
            runtime_dir: Some(runtime.to_string_lossy().into_owned()),
            patch_binary: false,
            ..Default::default()
        };
        let launch = tokio::spawn(Browser::launch_with_config(config));
        tokio::time::timeout(std::time::Duration::from_secs(3), async {
            while !pid_file.exists() {
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }
        })
        .await
        .unwrap();
        let socket = if websocket_handoff {
            Some(
                tokio::time::timeout(std::time::Duration::from_secs(3), listener.accept())
                    .await
                    .unwrap()
                    .unwrap(),
            )
        } else {
            None
        };
        launch.abort();
        assert!(matches!(launch.await, Err(error) if error.is_cancelled()));
        tokio::time::timeout(std::time::Duration::from_secs(3), async {
            while std::fs::read_dir(&runtime).unwrap().next().is_some() {
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }
        })
        .await
        .unwrap();
        let pid = std::fs::read_to_string(pid_file).unwrap();
        let alive = Command::new("kill")
            .args(["-0", pid.trim()])
            .output()
            .unwrap()
            .status
            .success();
        assert!(!alive, "cancelled launch retained its owned process");
        drop(socket);
    }
}

#[tokio::test]
#[ignore = "requires Chrome; verifies simultaneous owned runtime and patch isolation"]
async fn concurrent_owned_launches_keep_independent_runtime_state() {
    let chrome = eoka::stealth::find_chrome().unwrap();
    let root = Directory::new();
    let config = StealthConfig {
        chrome_path: Some(chrome.to_string_lossy().into_owned()),
        runtime_dir: Some(root.0.to_string_lossy().into_owned()),
        ..Default::default()
    };
    let (first, second) = tokio::join!(
        Browser::launch_with_config(config.clone()),
        Browser::launch_with_config(config),
    );
    let first = first.unwrap();
    let second = second.unwrap();
    assert!(first.owns_process() && second.owns_process());
    assert_eq!(std::fs::read_dir(&root.0).unwrap().count(), 2);
    let page = second.new_blank_page().await.unwrap();
    first.close().await.unwrap();
    assert_eq!(std::fs::read_dir(&root.0).unwrap().count(), 1);
    assert_eq!(
        page.evaluate::<String>("'other-browser-still-usable'")
            .await
            .unwrap(),
        "other-browser-still-usable"
    );
    second.close().await.unwrap();
    assert_eq!(std::fs::read_dir(&root.0).unwrap().count(), 0);
}

#[tokio::test]
#[ignore = "requires headed Chrome and DISPLAY; verifies persistent profile restarts"]
async fn persistent_profile_restarts_preserve_storage_and_caller_files() {
    let chrome = eoka::stealth::find_chrome().unwrap();
    for headless in [true, false] {
        let root = Directory::new();
        let profile = root.0.join("profile");
        let runtime = root.0.join("runtime");
        let document = root.0.join("fixture.html");
        std::fs::create_dir(&profile).unwrap();
        std::fs::write(profile.join("keep"), "caller data").unwrap();
        std::fs::write(
            profile.join("DevToolsActivePort"),
            "9\n/devtools/browser/stale\n",
        )
        .unwrap();
        std::fs::write(&document, "<title>Persistent profile fixture</title>").unwrap();
        let config = StealthConfig {
            chrome_path: Some(chrome.to_string_lossy().into_owned()),
            runtime_dir: Some(runtime.to_string_lossy().into_owned()),
            user_data_dir: Some(profile.to_string_lossy().into_owned()),
            headless,
            ..Default::default()
        };
        for launch in 0..2 {
            let browser = Browser::launch_with_config(config.clone()).await.unwrap();
            assert!(browser.owns_process(), "restart must own a new Chrome");
            let page = browser
                .new_page(&format!("file://{}", document.display()))
                .await
                .unwrap();
            let retained = page
                .evaluate::<Option<String>>("localStorage.getItem('restart-marker')")
                .await
                .unwrap();
            assert_eq!(retained.as_deref(), (launch > 0).then_some("retained"));
            page.execute("localStorage.setItem('restart-marker', 'retained')")
                .await
                .unwrap();
            browser.close().await.unwrap();
            assert_eq!(
                std::fs::read_to_string(profile.join("keep")).unwrap(),
                "caller data"
            );
            assert_eq!(std::fs::read_dir(&runtime).unwrap().count(), 0);
        }
    }
}