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
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
use std::{future::Future, future::IntoFuture, marker::PhantomData, pin::Pin};

use super::Page;
use crate::cdp::RuntimeEvaluateResult;
use crate::error::{Error, Result};

const MAX_FUNCTION_BYTES: usize = 1_048_576;
const MAX_FRAME_SELECTOR_BYTES: usize = 4096;

#[derive(serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum JsonEvaluation {
    Value { value: serde_json::Value },
    TooLarge,
}

impl JsonEvaluation {
    fn expression(expression: &str, maximum_bytes: usize) -> Result<String> {
        Ok(format!(
            "({})({}, {maximum_bytes})",
            include_str!("json_evaluation.js"),
            serde_json::to_string(expression)?,
        ))
    }

    fn decode<T: serde::de::DeserializeOwned>(self, maximum_bytes: usize) -> Result<T> {
        match self {
            Self::Value { value } => Ok(serde_json::from_value(value)?),
            Self::TooLarge => Err(Error::too_large(maximum_bytes)),
        }
    }
}

fn evaluated_value(remote: crate::cdp::types::RemoteObject) -> Result<serde_json::Value> {
    match (
        remote.value,
        remote.r#type.as_str(),
        remote.subtype.as_deref(),
    ) {
        (Some(value), _, _) => Ok(value),
        (None, "object", Some("null")) => Ok(serde_json::Value::Null),
        _ => Err(Error::cdp_msg("No value returned from evaluate")),
    }
}

/// Check a JS evaluation result for exceptions.
pub(super) fn check_js_result(
    result: RuntimeEvaluateResult,
) -> Result<crate::cdp::types::RemoteObject> {
    if let Some(exception) = result.exception_details {
        return Err(Error::cdp_msg(exception.message()));
    }
    Ok(result.result)
}

/// Where [`Eval`] runs. Without [`Eval::frame`], code runs in the top frame's
/// main world, beside the page's own scripts and globals.
///
/// Either form runs in an eoka isolated world of the chosen frame, created
/// without `Runtime.enable`: the DOM is shared, page-owned JavaScript globals are
/// not. Cross-origin and out-of-process frames are routed through their own CDP
/// session; no parent-to-child `contentWindow` access is used.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Frame {
    /// A frame ID from [`Page::frames`], including nested out-of-process frames.
    /// Detached or unrelated IDs are rejected.
    Id(String),
    /// A CSS selector (at most 4096 bytes) that must match exactly one `iframe`
    /// or `frame` element in the top document. Frame URLs and numeric indices
    /// are not selectors; use [`Frame::Id`] for nested frames.
    Selector(String),
}

enum Source {
    Expression(String),
    /// A built function invocation, or the argument error it raises when awaited.
    Function(Result<String>),
}

#[derive(Debug, PartialEq)]
enum Decode {
    /// CDP `returnByValue`: `null` decodes, `undefined` is an error.
    Lenient,
    /// The strict JSON validator with an in-browser UTF-8 byte limit.
    Json(usize),
    /// Exceptions only; the value is never read.
    Discard,
}

#[derive(Debug)]
struct Prepared {
    expression: String,
    decode: Decode,
}

type EvalFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'a>>;

/// One JavaScript evaluation, run when awaited. Built by [`Page::eval`] and
/// [`Page::eval_fn`].
///
/// | Option | Effect |
/// |---|---|
/// | [`frame`](Self::frame) | Run in a frame's isolated world instead of the top frame's main world |
/// | [`no_await`](Self::no_await) | Return without awaiting a promise result |
/// | [`json`](Self::json) | Strict JSON result with a byte limit checked inside the browser |
/// | [`discard`](Self::discard) | Ignore the result; exceptions still fail |
///
/// Every combination is allowed except `json` (including [`Page::eval_fn`]'s
/// default JSON decoding) with `no_await` and without `discard`: strict JSON
/// validation awaits its value, so that combination fails with
/// `invalid_argument` before anything is sent. `discard` overrides `json`:
/// a discarded result is never validated.
///
/// Code is executed as written. Do not supply untrusted code.
#[must_use = "evaluations do nothing until awaited"]
pub struct Eval<'a, T> {
    page: &'a Page,
    source: Source,
    options: Options,
    output: PhantomData<fn() -> T>,
}

#[derive(Default)]
struct Options {
    frame: Option<Frame>,
    no_await: bool,
    maximum_bytes: Option<usize>,
    discard: bool,
}

impl<'a, T> Eval<'a, T> {
    fn new(page: &'a Page, source: Source) -> Self {
        Self {
            page,
            source,
            options: Options::default(),
            output: PhantomData,
        }
    }

    /// Run in a frame's isolated world instead of the top frame's main world.
    pub fn frame(mut self, frame: Frame) -> Self {
        self.options.frame = Some(frame);
        self
    }

    /// Don't await a promise result (CDP `awaitPromise: false`). Use when the
    /// page may hold unresolved promises that would block evaluation.
    pub fn no_await(mut self) -> Self {
        self.options.no_await = true;
        self
    }

    /// Reject non-JSON values before CDP can coerce them: `undefined`,
    /// non-finite or unsafe numbers, class instances, cycles, holes and symbol
    /// keys. The UTF-8 JSON result must fit `maximum_bytes`, checked inside the
    /// browser; a larger one fails with `result_too_large`. [`Page::eval_fn`]
    /// already decodes this way with a 1 MiB limit; this sets the limit.
    pub fn json(mut self, maximum_bytes: usize) -> Self {
        self.options.maximum_bytes = Some(maximum_bytes);
        self
    }
}

/// Turn a source and options into the expression to send and how to decode it.
fn prepare(source: Source, options: &Options) -> Result<Prepared> {
    let (source, function) = match source {
        Source::Expression(expression) => (expression, false),
        Source::Function(invocation) => (invocation?, true),
    };
    if let Some(Frame::Selector(selector)) = &options.frame {
        if selector.len() > MAX_FRAME_SELECTOR_BYTES {
            return Err(Error::invalid_argument("Frame selector exceeds 4096 bytes"));
        }
    }
    if options.discard {
        let expression = match (function, options.no_await) {
            (false, _) => source,
            (true, false) => format!("(async()=>{{await {source};}})()"),
            (true, true) => format!("void ({source})"),
        };
        return Ok(Prepared {
            expression,
            decode: Decode::Discard,
        });
    }
    let limit = options
        .maximum_bytes
        .or(function.then_some(MAX_FUNCTION_BYTES));
    let Some(limit) = limit else {
        return Ok(Prepared {
            expression: source,
            decode: Decode::Lenient,
        });
    };
    if options.no_await {
        return Err(Error::invalid_argument(
            "Strict JSON evaluation awaits its value; no_await requires discard",
        ));
    }
    Ok(Prepared {
        expression: JsonEvaluation::expression(&source, limit)?,
        decode: Decode::Json(limit),
    })
}

impl<'a> Eval<'a, ()> {
    /// Ignore the result: only exceptions fail. See [`Eval`] for how it
    /// combines with the other options.
    ///
    /// For [`Page::eval`] the expression's value must still be returnable by
    /// CDP. For [`Page::eval_fn`] the call is wrapped so its result is never
    /// returned; it is awaited unless [`no_await`](Self::no_await) is set.
    pub fn discard(mut self) -> Self {
        self.options.discard = true;
        self
    }
}

impl<'a, T: serde::de::DeserializeOwned + 'a> IntoFuture for Eval<'a, T> {
    type Output = Result<T>;
    type IntoFuture = EvalFuture<'a, T>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let prepared = prepare(self.source, &self.options)?;
            let await_promise = !self.options.no_await;
            let page = self.page;
            let result = match self.options.frame {
                None => {
                    page.session
                        .evaluate(&prepared.expression, await_promise)
                        .await?
                }
                Some(frame) => {
                    let frame_id = match frame {
                        Frame::Id(id) => id,
                        Frame::Selector(selector) => page.frame_id_for_selector(&selector).await?,
                    };
                    page.evaluate_in_frame_world(&frame_id, &prepared.expression, await_promise)
                        .await?
                }
            };
            decode(result, &prepared.decode)
        })
    }
}

fn decode<T: serde::de::DeserializeOwned>(
    result: RuntimeEvaluateResult,
    mode: &Decode,
) -> Result<T> {
    let remote = check_js_result(result)?;
    match *mode {
        // Only `Eval<'_, ()>` can discard, and `()` decodes from null.
        Decode::Discard => Ok(serde_json::from_value(serde_json::Value::Null)?),
        Decode::Lenient => Ok(serde_json::from_value(evaluated_value(remote)?)?),
        Decode::Json(limit) => {
            let evaluation: JsonEvaluation = serde_json::from_value(evaluated_value(remote)?)?;
            evaluation.decode(limit)
        }
    }
}

impl Page {
    /// Evaluate a JavaScript expression in the top frame's main world.
    ///
    /// The result is decoded leniently through CDP `returnByValue`: `null`
    /// is a value, `undefined` is an error. Promises are awaited. See [`Eval`]
    /// for frames, strict JSON, discarding the result and not awaiting.
    pub fn eval<T>(&self, expression: &str) -> Eval<'_, T> {
        Eval::new(self, Source::Expression(expression.to_string()))
    }

    /// Call a function once with JSON arguments in a fresh lexical scope.
    ///
    /// Arguments are passed as JSON, never spliced into source; they keep object
    /// keys, reject unsafe numbers and nesting beyond 64, and are limited to
    /// 1 MiB, as is the function. The result is strict JSON with a 1 MiB limit
    /// (see [`Eval::json`] to change it), and promises are awaited. Invalid
    /// arguments fail with `invalid_argument` when awaited, before anything is sent.
    pub fn eval_fn<T>(&self, function: &str, arguments: &[serde_json::Value]) -> Eval<'_, T> {
        Eval::new(
            self,
            Source::Function(function_expression(function, arguments)),
        )
    }
}

/// Build an explicit function invocation; arguments never become executable source.
fn function_expression(function: &str, arguments: &[serde_json::Value]) -> Result<String> {
    fn validate(value: &serde_json::Value, depth: usize) -> Result<()> {
        if depth > 64 {
            return Err(Error::invalid_argument(
                "JavaScript argument nesting exceeds 64",
            ));
        }
        match value {
            serde_json::Value::Number(n)
                if n.as_f64().is_none_or(|n| {
                    !n.is_finite() || (n.fract() == 0.0 && n.abs() > 9_007_199_254_740_991.0)
                }) =>
            {
                return Err(Error::invalid_argument(
                    "JavaScript argument contains an unsafe number",
                ))
            }
            serde_json::Value::Array(values) => {
                for value in values {
                    validate(value, depth + 1)?;
                }
            }
            serde_json::Value::Object(values) => {
                for value in values.values() {
                    validate(value, depth + 1)?;
                }
            }
            _ => {}
        }
        Ok(())
    }
    for value in arguments {
        validate(value, 0)?;
    }
    let args = serde_json::to_string(arguments)?;
    if args.len() > MAX_FUNCTION_BYTES || function.len() > MAX_FUNCTION_BYTES {
        return Err(Error::invalid_argument(
            "JavaScript function or arguments exceed 1 MiB",
        ));
    }
    let encoded = serde_json::to_string(&args)?;
    // The newline ends a trailing `//` comment in `function`.
    Ok(format!("({function}\n)(...JSON.parse({encoded}))"))
}

/// Check a raw evaluation result for exceptions and decode its value leniently.
pub(super) fn decode_lenient<T: serde::de::DeserializeOwned>(
    result: RuntimeEvaluateResult,
) -> Result<T> {
    decode(result, &Decode::Lenient)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn explicit_null_is_a_value_but_undefined_is_not() {
        let remote = serde_json::from_value(
            serde_json::json!({"type":"object", "subtype":"null", "value":null}),
        )
        .unwrap();
        let decoded: Option<String> =
            serde_json::from_value(evaluated_value(remote).unwrap()).unwrap();
        assert_eq!(decoded, None);
        let remote = serde_json::from_value(serde_json::json!({"type":"undefined"})).unwrap();
        assert!(evaluated_value(remote).is_err());
        for value in [
            serde_json::json!(0),
            serde_json::json!(false),
            serde_json::json!(""),
            serde_json::json!({"a":1}),
        ] {
            let remote = serde_json::from_value(serde_json::json!({"value":value})).unwrap();
            assert_eq!(evaluated_value(remote).unwrap(), value);
        }
    }

    fn options(
        frame: Option<Frame>,
        no_await: bool,
        json: Option<usize>,
        discard: bool,
    ) -> Options {
        Options {
            frame,
            no_await,
            maximum_bytes: json,
            discard,
        }
    }

    fn invocation() -> Source {
        Source::Function(function_expression("(a) => a", &[serde_json::json!(1)]))
    }

    #[test]
    fn expressions_default_to_lenient_decoding() {
        for no_await in [false, true] {
            let prepared = prepare(
                Source::Expression("1 + 1".into()),
                &options(None, no_await, None, false),
            )
            .unwrap();
            assert_eq!(prepared.expression, "1 + 1");
            assert_eq!(prepared.decode, Decode::Lenient);
        }
    }

    #[test]
    fn functions_default_to_strict_json_with_one_mebibyte() {
        let prepared = prepare(invocation(), &Options::default()).unwrap();
        assert_eq!(prepared.decode, Decode::Json(MAX_FUNCTION_BYTES));
        assert!(prepared
            .expression
            .ends_with(&format!(", {MAX_FUNCTION_BYTES})")));
        assert!(prepared.expression.contains("JSON.parse"));
        let prepared = prepare(invocation(), &options(None, false, Some(16), false)).unwrap();
        assert_eq!(prepared.decode, Decode::Json(16));
        let prepared = prepare(
            Source::Expression("x".into()),
            &options(None, false, Some(64), false),
        )
        .unwrap();
        assert_eq!(prepared.decode, Decode::Json(64));
        assert_eq!(
            prepared.expression,
            JsonEvaluation::expression("x", 64).unwrap()
        );
    }

    #[test]
    fn discard_overrides_json_and_keeps_the_await_wrapper() {
        let invocation_text = function_expression("(a) => a", &[serde_json::json!(1)]).unwrap();
        for json in [None, Some(8)] {
            let prepared = prepare(invocation(), &options(None, false, json, true)).unwrap();
            assert_eq!(prepared.decode, Decode::Discard);
            assert_eq!(
                prepared.expression,
                format!("(async()=>{{await {invocation_text};}})()")
            );
            let prepared = prepare(
                Source::Expression("x()".into()),
                &options(None, false, json, true),
            )
            .unwrap();
            assert_eq!(
                (prepared.expression.as_str(), prepared.decode),
                ("x()", Decode::Discard)
            );
        }
        let prepared = prepare(invocation(), &options(None, true, None, true)).unwrap();
        assert_eq!(prepared.expression, format!("void ({invocation_text})"));
        let prepared = prepare(
            Source::Expression("x()".into()),
            &options(None, true, Some(8), true),
        )
        .unwrap();
        assert_eq!(
            (prepared.expression.as_str(), prepared.decode),
            ("x()", Decode::Discard)
        );
    }

    #[test]
    fn strict_json_without_await_is_rejected_unless_discarded() {
        for source in [invocation(), Source::Expression("x".into())] {
            let error = prepare(source, &options(None, true, Some(8), false)).unwrap_err();
            assert_eq!(error.code(), crate::ErrorCode::InvalidArgument);
        }
        let error = prepare(invocation(), &options(None, true, None, false)).unwrap_err();
        assert_eq!(error.code(), crate::ErrorCode::InvalidArgument);
    }

    #[test]
    fn a_trailing_line_comment_does_not_swallow_the_call() {
        let invocation = function_expression("(a) => a // note", &[]).unwrap();
        assert_eq!(
            invocation,
            r#"((a) => a // note
)(...JSON.parse("[]"))"#
        );
    }

    #[test]
    fn argument_and_selector_errors_surface_before_dispatch() {
        let source = Source::Function(function_expression("f", &[serde_json::json!(f64::MAX)]));
        let error = prepare(source, &Options::default()).unwrap_err();
        assert_eq!(error.code(), crate::ErrorCode::InvalidArgument);
        let selector = "a".repeat(MAX_FRAME_SELECTOR_BYTES + 1);
        let error = prepare(
            Source::Expression("x".into()),
            &options(Some(Frame::Selector(selector)), false, None, false),
        )
        .unwrap_err();
        assert_eq!(error.code(), crate::ErrorCode::InvalidArgument);
        let selector = "a".repeat(MAX_FRAME_SELECTOR_BYTES);
        assert!(prepare(
            Source::Expression("x".into()),
            &options(Some(Frame::Selector(selector)), false, None, false),
        )
        .is_ok());
    }
}