zendriver 0.1.3

Async-first, undetectable browser automation via the Chrome DevTools Protocol
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
//! Keyboard types: [`Key`] / [`SpecialKey`] / [`KeyModifiers`].
//!
//! Pass these to [`crate::Element::press`] / [`crate::Element::press_with`]
//! to dispatch single keystrokes.

use bitflags::bitflags;

/// A single key dispatch target — either a typed character or a named
/// special key.
///
/// # Examples
///
/// ```
/// use zendriver::{Key, SpecialKey};
/// let _ = Key::Char('a');
/// let _ = Key::Special(SpecialKey::Enter);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Key {
    /// A typed character.
    Char(char),
    /// A named non-character key (Enter, Tab, F1, etc.).
    Special(SpecialKey),
}

/// Named non-character keys for [`crate::Element::press`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpecialKey {
    /// Return / Enter.
    Enter,
    /// Tab.
    Tab,
    /// Escape.
    Escape,
    /// Backspace.
    Backspace,
    /// Delete (forward delete).
    Delete,
    /// Space bar.
    Space,
    /// Up arrow.
    ArrowUp,
    /// Down arrow.
    ArrowDown,
    /// Left arrow.
    ArrowLeft,
    /// Right arrow.
    ArrowRight,
    /// Home.
    Home,
    /// End.
    End,
    /// Page Up.
    PageUp,
    /// Page Down.
    PageDown,
    /// F1.
    F1,
    /// F2.
    F2,
    /// F3.
    F3,
    /// F4.
    F4,
    /// F5.
    F5,
    /// F6.
    F6,
    /// F7.
    F7,
    /// F8.
    F8,
    /// F9.
    F9,
    /// F10.
    F10,
    /// F11.
    F11,
    /// F12.
    F12,
    /// Insert.
    Insert,
    /// Caps Lock.
    CapsLock,
    /// Num Lock.
    NumLock,
    /// Scroll Lock.
    ScrollLock,
    /// Print Screen.
    PrintScreen,
    /// Pause / Break.
    Pause,
    /// Context Menu / Application key.
    ContextMenu,
}

impl SpecialKey {
    /// Map to CDP `Input.dispatchKeyEvent` fields.
    ///
    /// Returns `(code, key, windowsVirtualKeyCode)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use zendriver::SpecialKey;
    /// let (code, key, vk) = SpecialKey::Enter.to_cdp();
    /// assert_eq!(code, "Enter");
    /// assert_eq!(key, "Enter");
    /// assert_eq!(vk, 13);
    /// ```
    #[must_use]
    pub fn to_cdp(self) -> (&'static str, &'static str, i32) {
        match self {
            SpecialKey::Enter => ("Enter", "Enter", 13),
            SpecialKey::Tab => ("Tab", "Tab", 9),
            SpecialKey::Escape => ("Escape", "Escape", 27),
            SpecialKey::Backspace => ("Backspace", "Backspace", 8),
            SpecialKey::Delete => ("Delete", "Delete", 46),
            SpecialKey::Space => ("Space", " ", 32),
            SpecialKey::ArrowUp => ("ArrowUp", "ArrowUp", 38),
            SpecialKey::ArrowDown => ("ArrowDown", "ArrowDown", 40),
            SpecialKey::ArrowLeft => ("ArrowLeft", "ArrowLeft", 37),
            SpecialKey::ArrowRight => ("ArrowRight", "ArrowRight", 39),
            SpecialKey::Home => ("Home", "Home", 36),
            SpecialKey::End => ("End", "End", 35),
            SpecialKey::PageUp => ("PageUp", "PageUp", 33),
            SpecialKey::PageDown => ("PageDown", "PageDown", 34),
            SpecialKey::F1 => ("F1", "F1", 112),
            SpecialKey::F2 => ("F2", "F2", 113),
            SpecialKey::F3 => ("F3", "F3", 114),
            SpecialKey::F4 => ("F4", "F4", 115),
            SpecialKey::F5 => ("F5", "F5", 116),
            SpecialKey::F6 => ("F6", "F6", 117),
            SpecialKey::F7 => ("F7", "F7", 118),
            SpecialKey::F8 => ("F8", "F8", 119),
            SpecialKey::F9 => ("F9", "F9", 120),
            SpecialKey::F10 => ("F10", "F10", 121),
            SpecialKey::F11 => ("F11", "F11", 122),
            SpecialKey::F12 => ("F12", "F12", 123),
            SpecialKey::Insert => ("Insert", "Insert", 45),
            SpecialKey::CapsLock => ("CapsLock", "CapsLock", 20),
            SpecialKey::NumLock => ("NumLock", "NumLock", 144),
            SpecialKey::ScrollLock => ("ScrollLock", "ScrollLock", 145),
            SpecialKey::PrintScreen => ("PrintScreen", "PrintScreen", 44),
            SpecialKey::Pause => ("Pause", "Pause", 19),
            SpecialKey::ContextMenu => ("ContextMenu", "ContextMenu", 93),
        }
    }
}

bitflags! {
    /// Composable keyboard modifier bits.
    ///
    /// Matches CDP modifier-bits encoding. Combine with `|`:
    ///
    /// ```
    /// use zendriver::KeyModifiers;
    /// let combo = KeyModifiers::CTRL | KeyModifiers::SHIFT;
    /// assert!(combo.contains(KeyModifiers::CTRL));
    /// ```
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    pub struct KeyModifiers: u8 {
        /// Alt key (Option on macOS).
        const ALT     = 0b0001;
        /// Control key.
        const CTRL    = 0b0010;
        /// Meta key (Command on macOS, Windows key on Windows).
        const META    = 0b0100;
        /// Shift key.
        const SHIFT   = 0b1000;
    }
}

impl KeyModifiers {
    /// Encode as the integer modifier bitmask CDP expects.
    ///
    /// # Examples
    ///
    /// ```
    /// use zendriver::KeyModifiers;
    /// assert_eq!(KeyModifiers::CTRL.cdp_bits(), 2);
    /// assert_eq!((KeyModifiers::CTRL | KeyModifiers::SHIFT).cdp_bits(), 10);
    /// ```
    #[must_use]
    pub fn cdp_bits(self) -> i32 {
        i32::from(self.bits())
    }
}

/// Returns a plausible nearby QWERTY key for `c`, or None for non-alphanumeric.
/// Used by realistic typing to inject occasional typos.
pub(crate) fn neighbor_key(c: char, rng: &mut impl rand::Rng) -> Option<char> {
    use rand::seq::SliceRandom;
    let lower = c.to_ascii_lowercase();
    let neighbors: &[char] = match lower {
        'q' => &['w', 'a', 's'],
        'w' => &['q', 'e', 'a', 's', 'd'],
        'e' => &['w', 'r', 's', 'd', 'f'],
        'r' => &['e', 't', 'd', 'f', 'g'],
        't' => &['r', 'y', 'f', 'g', 'h'],
        'y' => &['t', 'u', 'g', 'h', 'j'],
        'u' => &['y', 'i', 'h', 'j', 'k'],
        'i' => &['u', 'o', 'j', 'k', 'l'],
        'o' => &['i', 'p', 'k', 'l'],
        'p' => &['o', 'l'],
        'a' => &['q', 'w', 's', 'z'],
        's' => &['a', 'd', 'w', 'e', 'z', 'x'],
        'd' => &['s', 'f', 'e', 'r', 'x', 'c'],
        'f' => &['d', 'g', 'r', 't', 'c', 'v'],
        'g' => &['f', 'h', 't', 'y', 'v', 'b'],
        'h' => &['g', 'j', 'y', 'u', 'b', 'n'],
        'j' => &['h', 'k', 'u', 'i', 'n', 'm'],
        'k' => &['j', 'l', 'i', 'o', 'm'],
        'l' => &['k', 'o', 'p'],
        'z' => &['a', 's', 'x'],
        'x' => &['z', 'c', 's', 'd'],
        'c' => &['x', 'v', 'd', 'f'],
        'v' => &['c', 'b', 'f', 'g'],
        'b' => &['v', 'n', 'g', 'h'],
        'n' => &['b', 'm', 'h', 'j'],
        'm' => &['n', 'j', 'k'],
        _ => return None,
    };
    let pick = neighbors.choose(rng)?;
    if c.is_ascii_uppercase() {
        Some(pick.to_ascii_uppercase())
    } else {
        Some(*pick)
    }
}

#[cfg(test)]
#[allow(clippy::panic, clippy::unwrap_used)]
mod tests {
    use super::*;
    use rand::SeedableRng;

    #[test]
    fn modifiers_compose_with_bitor() {
        let m = KeyModifiers::CTRL | KeyModifiers::SHIFT;
        assert!(m.contains(KeyModifiers::CTRL));
        assert!(m.contains(KeyModifiers::SHIFT));
        assert!(!m.contains(KeyModifiers::ALT));
    }

    #[test]
    fn modifiers_cdp_bits_match_encoding() {
        assert_eq!(KeyModifiers::ALT.cdp_bits(), 1);
        assert_eq!(KeyModifiers::CTRL.cdp_bits(), 2);
        assert_eq!(KeyModifiers::META.cdp_bits(), 4);
        assert_eq!(KeyModifiers::SHIFT.cdp_bits(), 8);
        assert_eq!((KeyModifiers::CTRL | KeyModifiers::SHIFT).cdp_bits(), 10);
    }

    #[test]
    fn special_key_enter_maps_to_cdp_13() {
        let (code, key, vk) = SpecialKey::Enter.to_cdp();
        assert_eq!(code, "Enter");
        assert_eq!(key, "Enter");
        assert_eq!(vk, 13);
    }

    #[test]
    fn neighbor_key_returns_nearby_for_alpha() {
        let mut rng = rand::rngs::SmallRng::seed_from_u64(42);
        let n = neighbor_key('r', &mut rng).expect("r has neighbors");
        assert!(['e', 't', 'd', 'f', 'g'].contains(&n));
    }

    #[test]
    fn neighbor_key_preserves_case() {
        let mut rng = rand::rngs::SmallRng::seed_from_u64(42);
        let n = neighbor_key('R', &mut rng).expect("R has neighbors");
        assert!(n.is_ascii_uppercase());
    }

    #[test]
    fn neighbor_key_returns_none_for_non_alpha() {
        let mut rng = rand::rngs::SmallRng::seed_from_u64(42);
        assert!(neighbor_key('5', &mut rng).is_none());
        assert!(neighbor_key('!', &mut rng).is_none());
        assert!(neighbor_key(' ', &mut rng).is_none());
    }
}

use std::time::Duration;

use serde_json::json;

use crate::error::Result;
use crate::input::InputController;
use crate::tab::Tab;

/// Dispatch a single character via Input.dispatchKeyEvent (keyDown + keyUp).
pub(crate) async fn dispatch_char(tab: &Tab, c: char, modifier_bits: i32) -> Result<()> {
    let s = c.to_string();
    tab.session()
        .call(
            "Input.dispatchKeyEvent",
            json!({
                "type": "keyDown", "text": &s, "key": &s,
                "modifiers": modifier_bits,
            }),
        )
        .await?;
    tab.session()
        .call(
            "Input.dispatchKeyEvent",
            json!({
                "type": "keyUp", "text": &s, "key": &s,
                "modifiers": modifier_bits,
            }),
        )
        .await?;
    Ok(())
}

/// Dispatch a named special key (Enter, Tab, etc).
#[allow(dead_code)]
pub(crate) async fn dispatch_special(tab: &Tab, k: SpecialKey, modifier_bits: i32) -> Result<()> {
    let (code, key, vk) = k.to_cdp();
    tab.session()
        .call(
            "Input.dispatchKeyEvent",
            json!({
                "type": "rawKeyDown",
                "code": code, "key": key,
                "windowsVirtualKeyCode": vk,
                "modifiers": modifier_bits,
            }),
        )
        .await?;
    tab.session()
        .call(
            "Input.dispatchKeyEvent",
            json!({
                "type": "keyUp",
                "code": code, "key": key,
                "windowsVirtualKeyCode": vk,
                "modifiers": modifier_bits,
            }),
        )
        .await?;
    Ok(())
}

/// Type `text` with realistic per-character timing, occasional typos, and
/// inter-word "thinking" pauses pulled from the InputProfile.
#[allow(dead_code)]
pub(crate) async fn type_text_realistic(
    input: &InputController,
    tab: &Tab,
    text: &str,
) -> Result<()> {
    let profile = input.profile.clone();
    for ch in text.chars() {
        let (per_char_delay_ms, mods, do_typo, typo_char, thinking_pause_ms) = {
            let mut s = input.state.lock().await;
            let per_char = if profile.per_char_delay_ms_range.0 == 0
                && profile.per_char_delay_ms_range.1 == 0
            {
                0
            } else {
                rand::Rng::gen_range(
                    &mut s.rng,
                    profile.per_char_delay_ms_range.0..=profile.per_char_delay_ms_range.1,
                )
            };
            let do_typo =
                profile.typo_rate > 0.0 && rand::Rng::r#gen::<f32>(&mut s.rng) < profile.typo_rate;
            let typo_char = if do_typo {
                neighbor_key(ch, &mut s.rng)
            } else {
                None
            };
            let thinking = if ch == ' '
                && profile.thinking_pause_ms_range.0 > 0
                && rand::Rng::r#gen::<f32>(&mut s.rng) < 0.05
            {
                rand::Rng::gen_range(
                    &mut s.rng,
                    profile.thinking_pause_ms_range.0..=profile.thinking_pause_ms_range.1,
                )
            } else {
                0
            };
            (
                per_char,
                s.modifiers_held.cdp_bits(),
                do_typo,
                typo_char,
                thinking,
            )
        };
        if per_char_delay_ms > 0 {
            tokio::time::sleep(Duration::from_millis(per_char_delay_ms as u64)).await;
        }
        if thinking_pause_ms > 0 {
            tokio::time::sleep(Duration::from_millis(thinking_pause_ms as u64)).await;
        }
        if do_typo {
            if let Some(wrong) = typo_char {
                dispatch_char(tab, wrong, mods).await?;
                tokio::time::sleep(Duration::from_millis(80)).await;
                dispatch_special(tab, SpecialKey::Backspace, mods).await?;
            }
        }
        dispatch_char(tab, ch, mods).await?;
    }
    Ok(())
}

/// Type `text` as fast as possible — no delays, no typos.
#[allow(dead_code)]
pub(crate) async fn type_text_fast(input: &InputController, tab: &Tab, text: &str) -> Result<()> {
    let mods = input.state.lock().await.modifiers_held.cdp_bits();
    for ch in text.chars() {
        dispatch_char(tab, ch, mods).await?;
    }
    Ok(())
}

#[cfg(test)]
#[allow(clippy::panic, clippy::unwrap_used)]
mod dispatch_tests {
    use super::*;
    use serde_json::Value;
    use zendriver_stealth::InputProfile;
    use zendriver_transport::SessionHandle;
    use zendriver_transport::testing::MockConnection;

    #[tokio::test]
    async fn type_text_fast_emits_keydown_keyup_per_char() {
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let tab = Tab::new_for_test(sess);
        let input = InputController::new_with_seed(InputProfile::native(), 42);

        let fut = tokio::spawn({
            let input = input.clone();
            let tab = tab.clone();
            async move { type_text_fast(&input, &tab, "ab").await }
        });

        for ch in ['a', 'a', 'b', 'b'] {
            // 4 events: a-down a-up b-down b-up
            let id = mock.expect_cmd("Input.dispatchKeyEvent").await;
            let last = mock.last_sent();
            let text = last["params"]["text"].as_str().unwrap();
            assert_eq!(text, ch.to_string());
            mock.reply(id, Value::Null).await;
        }
        fut.await.unwrap().unwrap();
        conn.shutdown();
    }

    #[tokio::test]
    async fn dispatch_special_enter_emits_correct_cdp_fields() {
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let tab = Tab::new_for_test(sess);

        let fut = tokio::spawn({
            let tab = tab.clone();
            async move { dispatch_special(&tab, SpecialKey::Enter, 0).await }
        });

        let id = mock.expect_cmd("Input.dispatchKeyEvent").await;
        let last = mock.last_sent();
        assert_eq!(last["params"]["type"], "rawKeyDown");
        assert_eq!(last["params"]["key"], "Enter");
        assert_eq!(last["params"]["windowsVirtualKeyCode"], 13);
        mock.reply(id, Value::Null).await;

        let id = mock.expect_cmd("Input.dispatchKeyEvent").await;
        let last = mock.last_sent();
        assert_eq!(last["params"]["type"], "keyUp");
        mock.reply(id, Value::Null).await;
        fut.await.unwrap().unwrap();
        conn.shutdown();
    }
}