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
use crate::page::Page;
use crate::profiles::ChaserProfile;
use anyhow::{Result, anyhow};
use base64::{Engine, engine::general_purpose::STANDARD};
use chromiumoxide_cdp::cdp::browser_protocol::emulation::{
SetUserAgentOverrideParams as EmulationSetUserAgentOverrideParams, UserAgentBrandVersion,
UserAgentMetadata,
};
use chromiumoxide_cdp::cdp::browser_protocol::fetch::{
ContinueRequestParams, DisableParams as FetchDisableParams, EnableParams as FetchEnableParams,
FulfillRequestParams, HeaderEntry, RequestPattern,
};
use chromiumoxide_cdp::cdp::browser_protocol::input::{
DispatchKeyEventParams, DispatchKeyEventType,
};
use chromiumoxide_cdp::cdp::browser_protocol::network::ResourceType;
use chromiumoxide_cdp::cdp::browser_protocol::page::{
AddScriptToEvaluateOnNewDocumentParams, CreateIsolatedWorldParams,
};
use chromiumoxide_cdp::cdp::js_protocol::runtime::EvaluateParams;
use rand::Rng;
use serde_json::Value;
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone, Copy)]
pub struct Point {
pub x: f64,
pub y: f64,
}
/// Stealth browser page with human-like input simulation.
///
/// # Stealth JavaScript Execution
///
/// ```rust,ignore
/// // Safe - uses isolated world, no Runtime.enable leak
/// let title = chaser.evaluate("document.title").await?;
///
/// // Dangerous - only use raw_page().evaluate() if you know what you're doing
/// let val = chaser.raw_page().evaluate("...").await?; // Triggers Runtime.enable!
/// ```
///
/// All other `raw_page()` methods (get_cookies, screenshot, goto, etc.) are safe.
///
/// # Features
///
/// - Zero-footprint JS execution via `Page.createIsolatedWorld`
/// - Bezier curve mouse movements with jitter
/// - Realistic typing with variable delays
#[derive(Clone, Debug)]
pub struct ChaserPage {
page: Page,
mouse_pos: Arc<Mutex<Point>>,
}
impl ChaserPage {
/// Create a new ChaserPage wrapping the given Page.
pub fn new(page: Page) -> Self {
Self {
page,
mouse_pos: Arc::new(Mutex::new(Point { x: 0.0, y: 0.0 })),
}
}
// ========== SAFE PAGE ACCESS ==========
/// Access the underlying Page.
///
/// Most methods are safe, **except `raw_page().evaluate()`** which
/// triggers `Runtime.enable` detection. Use `chaser.evaluate()` instead.
#[doc(alias = "inner")]
pub fn raw_page(&self) -> &Page {
&self.page
}
/// Deprecated: Use `raw_page()` instead.
///
/// This method is kept for backwards compatibility but will be removed in a future version.
#[deprecated(since = "0.1.1", note = "Use `raw_page()` instead for clarity")]
pub fn inner(&self) -> &Page {
&self.page
}
// ========== STEALTH-SAFE PAGE OPERATIONS ==========
/// Navigate to a URL (stealth-safe).
///
/// This is equivalent to `raw_page().goto()` but provided for convenience.
pub async fn goto(&self, url: &str) -> Result<()> {
self.page.goto(url).await.map_err(|e| anyhow!("{}", e))?;
Ok(())
}
/// Get the page HTML content (stealth-safe).
pub async fn content(&self) -> Result<String> {
self.page.content().await.map_err(|e| anyhow!("{}", e))
}
/// Get the current page URL (stealth-safe).
pub async fn url(&self) -> Result<Option<String>> {
self.page.url().await.map_err(|e| anyhow!("{}", e))
}
/// Execute JavaScript using **stealth execution** (no Runtime.enable leak).
///
/// This is the safe way to run JavaScript on protected sites.
/// Under the hood, it uses `Page.createIsolatedWorld` to avoid detection.
///
/// # Example
///
/// ```rust,ignore
/// // Get page title
/// let title: String = chaser.evaluate("document.title").await?;
///
/// // Check a value
/// let ua: String = chaser.evaluate("navigator.userAgent").await?;
/// ```
pub async fn evaluate(&self, script: &str) -> Result<Option<Value>> {
self.evaluate_stealth(script).await
}
/// Apply a ChaserProfile to this page in one clean call.
///
/// This method:
/// 1. Sets the User-Agent HTTP header
/// 2. Injects the profile's bootstrap script for JS-level spoofing
///
/// **IMPORTANT:** Call this BEFORE navigating to the target site.
///
/// # Example
/// ```rust,ignore
/// let profile = ChaserProfile::windows().build();
/// let page = browser.new_page("about:blank").await?;
/// let chaser = ChaserPage::new(page);
/// chaser.apply_profile(&profile).await?;
/// chaser.inner().goto("https://example.com").await?;
/// ```
pub async fn apply_profile(&self, profile: &ChaserProfile) -> Result<()> {
let ver = profile.chrome_version().to_string();
let full_ver = format!("{}.0.0.0", ver);
let brand = |name: &str, v: &str| UserAgentBrandVersion {
brand: name.to_string(),
version: v.to_string(),
};
let metadata = UserAgentMetadata {
brands: Some(vec![
brand("Google Chrome", &ver),
brand("Chromium", &ver),
brand("Not=A?Brand", "24"),
]),
full_version_list: Some(vec![
brand("Google Chrome", &full_ver),
brand("Chromium", &full_ver),
brand("Not=A?Brand", "24.0.0.0"),
]),
platform: profile.os().hints_platform().to_string(),
platform_version: profile.os().platform_version().to_string(),
architecture: profile.os().architecture().to_string(),
model: String::new(),
mobile: false,
bitness: Some("64".to_string()),
wow64: Some(false),
form_factors: None,
};
// Set UA + Sec-CH-UA-* headers together so they're always consistent
self.page
.execute(
EmulationSetUserAgentOverrideParams::builder()
.user_agent(profile.user_agent())
.accept_language(profile.locale().to_string())
.platform(profile.os().platform().to_string())
.user_agent_metadata(metadata)
.build()
.map_err(|e| anyhow!("{}", e))?,
)
.await
.map_err(|e| anyhow!("{}", e))?;
// Inject the bootstrap script to run on every new document
self.page
.execute(AddScriptToEvaluateOnNewDocumentParams {
source: profile.bootstrap_script(),
world_name: None,
include_command_line_api: None,
run_immediately: None,
})
.await
.map_err(|e| anyhow!("{}", e))?;
Ok(())
}
/// Apply a profile derived from the actual running browser.
///
/// Reads the Chrome version from the connected browser via CDP so it's
/// always accurate — even when using chromiumoxide_fetcher's downloaded
/// binary whose version differs from any system Chrome installation.
/// OS and RAM are still detected from the host machine.
///
/// Call this BEFORE navigating to the target site.
pub async fn apply_native_profile(&self) -> Result<()> {
let ua = self.page.user_agent().await.map_err(|e| anyhow!("{}", e))?;
let chrome_version = parse_chrome_major(&ua).unwrap_or(131);
let profile = crate::profiles::ChaserProfile::native()
.chrome_version(chrome_version)
.build();
self.apply_profile(&profile).await
}
// ========== REQUEST INTERCEPTION API ==========
/// Enable request interception for specific URL patterns.
///
/// This uses the Fetch domain to intercept requests before they are sent.
/// After enabling, use `fulfill_request` or `continue_request` to handle
/// intercepted requests.
///
/// # Arguments
/// * `url_pattern` - Glob pattern to match URLs (e.g., "*", "https://example.com/*")
/// * `resource_type` - Optional resource type filter (Document, Script, etc.)
///
/// # Example
/// ```rust,ignore
/// // Intercept all document requests
/// chaser.enable_request_interception("*", Some(ResourceType::Document)).await?;
/// ```
pub async fn enable_request_interception(
&self,
url_pattern: &str,
resource_type: Option<ResourceType>,
) -> Result<()> {
let mut pattern_builder = RequestPattern::builder().url_pattern(url_pattern);
if let Some(rt) = resource_type {
pattern_builder = pattern_builder.resource_type(rt);
}
self.page
.execute(
FetchEnableParams::builder()
.handle_auth_requests(false)
.pattern(pattern_builder.build())
.build(),
)
.await
.map_err(|e| anyhow!("{}", e))?;
Ok(())
}
/// Disable request interception.
pub async fn disable_request_interception(&self) -> Result<()> {
self.page
.execute(FetchDisableParams::default())
.await
.map_err(|e| anyhow!("{}", e))?;
Ok(())
}
/// Fulfill an intercepted request with custom HTML content.
///
/// This is useful for Turnstile/captcha solving where you want to
/// serve a minimal page that only loads the challenge widget.
///
/// # Arguments
/// * `request_id` - The request ID from the EventRequestPaused event
/// * `html` - The HTML content to serve
/// * `status_code` - HTTP status code (usually 200)
///
/// # Example
/// ```rust,ignore
/// let fake_html = r#"
/// <!DOCTYPE html>
/// <html>
/// <head>
/// <script src="https://challenges.cloudflare.com/turnstile/v0/api.js"></script>
/// </head>
/// <body>
/// <div class="cf-turnstile" data-sitekey="your-sitekey"></div>
/// </body>
/// </html>
/// "#;
/// chaser.fulfill_request_html(request_id, fake_html, 200).await?;
/// ```
pub async fn fulfill_request_html(
&self,
request_id: impl Into<String>,
html: &str,
status_code: i64,
) -> Result<()> {
use chromiumoxide_cdp::cdp::browser_protocol::fetch::RequestId;
let body_base64 = STANDARD.encode(html);
self.page
.execute(
FulfillRequestParams::builder()
.request_id(RequestId::from(request_id.into()))
.response_code(status_code)
.body(body_base64)
.response_header(HeaderEntry {
name: "content-type".to_string(),
value: "text/html; charset=utf-8".to_string(),
})
.build()
.map_err(|e| anyhow!("{}", e))?,
)
.await
.map_err(|e| anyhow!("{}", e))?;
Ok(())
}
/// Continue an intercepted request without modification.
///
/// Use this when you intercept a request but decide not to modify it.
pub async fn continue_request(&self, request_id: impl Into<String>) -> Result<()> {
use chromiumoxide_cdp::cdp::browser_protocol::fetch::RequestId;
self.page
.execute(
ContinueRequestParams::builder()
.request_id(RequestId::from(request_id.into()))
.build()
.map_err(|e| anyhow!("{}", e))?,
)
.await
.map_err(|e| anyhow!("{}", e))?;
Ok(())
}
/// **THE REBROWSER METHOD: Absolute Stealth Execution**
///
/// This method achieves 100% stealth parity with Rebrowser by:
/// 1. Using `Page.createIsolatedWorld` to create a JS context
/// 2. Getting the `ExecutionContextId` directly from the response
/// 3. **Never calling `Runtime.enable`**
///
/// Site scripts cannot see your variables (isolated world).
/// Anti-bots cannot detect CDP activity (Runtime domain untouched).
pub async fn evaluate_stealth(&self, script: &str) -> Result<Option<Value>> {
// Get the main frame ID
let frame_id = self
.page
.mainframe()
.await
.map_err(|e| anyhow!("{}", e))?
.ok_or_else(|| anyhow!("No main frame available"))?;
// Create an isolated world - Chrome returns the Context ID in the response!
// This is the key insight: we get a context ID without touching Runtime domain
let isolated_world = self
.page
.execute(
CreateIsolatedWorldParams::builder()
.frame_id(frame_id)
.world_name("chaser") // Our stealth world
.grant_univeral_access(true) // Access to page DOM
.build()
.unwrap(),
)
.await
.map_err(|e| anyhow!("{}", e))?;
let ctx_id = isolated_world.result.execution_context_id;
// Execute in the isolated world using the captured context ID
let params = EvaluateParams::builder()
.expression(script)
.context_id(ctx_id)
.await_promise(true)
.return_by_value(true)
.build()
.unwrap();
let res = self
.page
.execute(params)
.await
.map_err(|e| anyhow!("{}", e))?;
Ok(res.result.result.value)
}
/// Moves the mouse to the target coordinates using a human-like Bezier curve path.
///
/// The path includes:
/// - Randomized control points for natural arcs
/// - 20% chance of slight overshoot
/// - Target jitter (±2px)
/// - Variable delays between movements (5-15ms)
pub async fn move_mouse_human(&self, x: f64, y: f64) -> Result<()> {
let start = { *self.mouse_pos.lock().unwrap() };
let end = Point { x, y };
// Target Selection Jitter: don't land exactly on the pixel
let jitter_x = rand::thread_rng().gen_range(-2.0..2.0);
let jitter_y = rand::thread_rng().gen_range(-2.0..2.0);
let target_with_jitter = Point {
x: end.x + jitter_x,
y: end.y + jitter_y,
};
let path = BezierPath::generate(start, target_with_jitter, 25);
for point in path {
self.page
.move_mouse(crate::layout::Point {
x: point.x,
y: point.y,
})
.await
.map_err(|e| anyhow!("{}", e))?;
*self.mouse_pos.lock().unwrap() = point;
// Tiny delay to simulate physical movement
let delay = rand::thread_rng().gen_range(5..15);
tokio::time::sleep(tokio::time::Duration::from_millis(delay)).await;
}
Ok(())
}
/// Perform a click at the current mouse position.
pub async fn click(&self) -> Result<()> {
let pos = { *self.mouse_pos.lock().unwrap() };
self.page
.click(crate::layout::Point { x: pos.x, y: pos.y })
.await
.map_err(|e| anyhow!("{}", e))?;
Ok(())
}
/// Move to target and click with full human-like behavior.
///
/// Combines Bezier curve mouse movement with a natural click, including:
/// - Human-like path to target
/// - Small random delay before clicking (50-150ms)
/// - Variable click duration
pub async fn click_human(&self, x: f64, y: f64) -> Result<()> {
// Move to target with bezier curve
self.move_mouse_human(x, y).await?;
// Small pause before clicking (humans don't click instantly after arriving)
let delay1 = rand::thread_rng().gen_range(50..150);
tokio::time::sleep(tokio::time::Duration::from_millis(delay1)).await;
// Click
self.click().await?;
// Small pause after clicking
let delay2 = rand::thread_rng().gen_range(30..80);
tokio::time::sleep(tokio::time::Duration::from_millis(delay2)).await;
Ok(())
}
/// Type text with human-like delays between keystrokes.
///
/// Simulates realistic typing with:
/// - Variable delay between keys (50-150ms by default)
/// - Occasional longer pauses (5% chance of 200-400ms pause)
pub async fn type_text(&self, text: &str) -> Result<()> {
self.type_text_with_delay(text, 50, 150).await
}
/// Type text with custom delay range (in milliseconds).
///
/// # Arguments
/// * `text` - The text to type
/// * `min_delay_ms` - Minimum delay between keystrokes
/// * `max_delay_ms` - Maximum delay between keystrokes
pub async fn type_text_with_delay(
&self,
text: &str,
min_delay_ms: u64,
max_delay_ms: u64,
) -> Result<()> {
for c in text.chars() {
// Send keyDown with the character
let key_down = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyDown)
.text(c.to_string())
.build()
.unwrap();
self.page
.execute(key_down)
.await
.map_err(|e| anyhow!("{}", e))?;
// Send keyUp
let key_up = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyUp)
.build()
.unwrap();
self.page
.execute(key_up)
.await
.map_err(|e| anyhow!("{}", e))?;
// Random delay between keystrokes
let delay = rand::thread_rng().gen_range(min_delay_ms..max_delay_ms);
// 5% chance of a longer "thinking" pause
let actual_delay = if rand::thread_rng().gen_bool(0.05) {
rand::thread_rng().gen_range(200..400)
} else {
delay
};
tokio::time::sleep(tokio::time::Duration::from_millis(actual_delay)).await;
}
Ok(())
}
/// Press a specific key (e.g., "Enter", "Tab", "Escape").
pub async fn press_key(&self, key: &str) -> Result<()> {
// Map common key names to their key codes
let (key_str, code) = match key {
"Enter" => ("Enter", "Enter"),
"Tab" => ("Tab", "Tab"),
"Escape" => ("Escape", "Escape"),
"Backspace" => ("Backspace", "Backspace"),
"Delete" => ("Delete", "Delete"),
"ArrowUp" => ("ArrowUp", "ArrowUp"),
"ArrowDown" => ("ArrowDown", "ArrowDown"),
"ArrowLeft" => ("ArrowLeft", "ArrowLeft"),
"ArrowRight" => ("ArrowRight", "ArrowRight"),
_ => (key, key),
};
let key_down = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::RawKeyDown)
.key(key_str)
.code(code)
.build()
.unwrap();
self.page
.execute(key_down)
.await
.map_err(|e| anyhow!("{}", e))?;
let key_up = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyUp)
.key(key_str)
.code(code)
.build()
.unwrap();
self.page
.execute(key_up)
.await
.map_err(|e| anyhow!("{}", e))?;
Ok(())
}
/// Press Enter key with a small random delay before pressing.
pub async fn press_enter(&self) -> Result<()> {
let mut rng = rand::thread_rng();
tokio::time::sleep(tokio::time::Duration::from_millis(rng.gen_range(100..300))).await;
self.press_key("Enter").await
}
/// Press Tab key to move to next field.
pub async fn press_tab(&self) -> Result<()> {
let mut rng = rand::thread_rng();
tokio::time::sleep(tokio::time::Duration::from_millis(rng.gen_range(50..150))).await;
self.press_key("Tab").await
}
/// Scroll the page with human-like physics (smooth, variable speed).
///
/// Simulates realistic scrolling with:
/// - Multiple small scroll steps rather than one jump
/// - Variable scroll distances per step
/// - Easing at start and end (deceleration)
///
/// # Arguments
/// * `delta_y` - Total pixels to scroll (positive = down, negative = up)
pub async fn scroll_human(&self, delta_y: i32) -> Result<()> {
use chromiumoxide_cdp::cdp::browser_protocol::input::{
DispatchMouseEventParams, DispatchMouseEventType, MouseButton,
};
let mut rng = rand::thread_rng();
let pos = { *self.mouse_pos.lock().unwrap() };
// Number of scroll steps (more steps = smoother)
let steps = (delta_y.abs() / 50).clamp(3, 15) as usize;
let mut remaining = delta_y;
for i in 0..steps {
// Ease-in/ease-out: scroll less at start and end
let progress = i as f64 / steps as f64;
let ease = if progress < 0.3 {
progress / 0.3 * 0.5 + 0.5
} else if progress > 0.7 {
(1.0 - progress) / 0.3 * 0.5 + 0.5
} else {
1.0
};
let base_step = remaining / (steps - i) as i32;
let jitter = rng.gen_range(-10..10);
let step = ((base_step as f64 * ease) as i32 + jitter).clamp(-200, 200);
if step == 0 {
continue;
}
let scroll = DispatchMouseEventParams::builder()
.r#type(DispatchMouseEventType::MouseWheel)
.x(pos.x)
.y(pos.y)
.button(MouseButton::None)
.delta_x(0.0)
.delta_y(step as f64)
.build()
.unwrap();
self.page
.execute(scroll)
.await
.map_err(|e| anyhow!("{}", e))?;
remaining -= step;
// Variable delay between scroll events (16-50ms for 60-20 FPS feel)
tokio::time::sleep(tokio::time::Duration::from_millis(rng.gen_range(16..50))).await;
}
Ok(())
}
/// Type text with occasional typos and corrections for ultra-realistic input.
///
/// This method has a small chance (~3%) of making a typo and then correcting it,
/// mimicking how real humans type.
pub async fn type_text_with_typos(&self, text: &str) -> Result<()> {
let mut rng = rand::thread_rng();
let typo_chars = ['q', 'w', 'e', 'r', 't', 'a', 's', 'd', 'f', 'g'];
for c in text.chars() {
// 3% chance of typo
if rng.gen_bool(0.03) && c.is_alphabetic() {
// Type wrong character
let typo = typo_chars[rng.gen_range(0..typo_chars.len())];
self.type_single_char(typo).await?;
// Brief pause to "notice" the mistake
tokio::time::sleep(tokio::time::Duration::from_millis(rng.gen_range(100..300)))
.await;
// Backspace to correct
self.press_key("Backspace").await?;
tokio::time::sleep(tokio::time::Duration::from_millis(rng.gen_range(30..80))).await;
}
// Type the correct character
self.type_single_char(c).await?;
// Random delay
let delay = rng.gen_range(50..150);
let actual_delay = if rng.gen_bool(0.05) {
rng.gen_range(200..400) // thinking pause
} else {
delay
};
tokio::time::sleep(tokio::time::Duration::from_millis(actual_delay)).await;
}
Ok(())
}
/// Helper to type a single character
async fn type_single_char(&self, c: char) -> Result<()> {
let key_down = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyDown)
.text(c.to_string())
.build()
.unwrap();
self.page
.execute(key_down)
.await
.map_err(|e| anyhow!("{}", e))?;
let key_up = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyUp)
.build()
.unwrap();
self.page
.execute(key_up)
.await
.map_err(|e| anyhow!("{}", e))?;
Ok(())
}
}
#[derive(Debug)]
pub struct BezierPath;
impl BezierPath {
/// Generates a path of points from start to end using a cubic Bezier curve.
///
/// The curve includes randomized control points to create natural, human-like arcs.
pub fn generate(start: Point, end: Point, steps: usize) -> Vec<Point> {
let mut rng = rand::thread_rng();
let mut path = Vec::with_capacity(steps);
// Calculate distance for offset scaling
let dist = ((end.x - start.x).powi(2) + (end.y - start.y).powi(2)).sqrt();
let offset_range = dist * 0.3;
// First control point (25% along the path with random offset)
let p1 = Point {
x: start.x + (end.x - start.x) * 0.25 + rng.gen_range(-offset_range..offset_range),
y: start.y + (end.y - start.y) * 0.25 + rng.gen_range(-offset_range..offset_range),
};
// Second control point (75% along the path with random offset)
// 20% chance of overshoot
let mut p2 = Point {
x: start.x + (end.x - start.x) * 0.75 + rng.gen_range(-offset_range..offset_range),
y: start.y + (end.y - start.y) * 0.75 + rng.gen_range(-offset_range..offset_range),
};
if rng.gen_bool(0.20) {
let overshoot_amt = dist * 0.05;
p2.x += if end.x > start.x {
overshoot_amt
} else {
-overshoot_amt
};
p2.y += if end.y > start.y {
overshoot_amt
} else {
-overshoot_amt
};
}
// Generate points along the Bezier curve
for i in 0..=steps {
let t = i as f64 / steps as f64;
// Cubic Bezier formula
let x = (1.0 - t).powi(3) * start.x
+ 3.0 * (1.0 - t).powi(2) * t * p1.x
+ 3.0 * (1.0 - t) * t.powi(2) * p2.x
+ t.powi(3) * end.x;
let y = (1.0 - t).powi(3) * start.y
+ 3.0 * (1.0 - t).powi(2) * t * p1.y
+ 3.0 * (1.0 - t) * t.powi(2) * p2.y
+ t.powi(3) * end.y;
path.push(Point { x, y });
}
path
}
}
/// Parse the Chrome major version out of a User-Agent string.
/// Works for both `Chrome/131.0.0.0` and `HeadlessChrome/131.0.0.0`.
fn parse_chrome_major(ua: &str) -> Option<u32> {
ua.split("Chrome/")
.nth(1)
.and_then(|s| s.split('.').next())
.and_then(|v| v.parse().ok())
}