Skip to main content

rightkit_browser/
cdp_ext.rs

1//! Caller-facing CDP surface added in 0.4.0: request interception, the accessibility tree,
2//! exception events, page scale and per-page download behaviour.
3//!
4//! Everything here that decodes or builds a CDP message is a pure function over JSON or over the
5//! generated parameter types, so the unit tests feed recorded wire messages through it without a
6//! browser. The `BrowserPage` methods in `page.rs` only send what these functions build.
7
8use crate::error::{BrowserError, Result};
9use chromiumoxide::cdp::browser_protocol::browser::{
10    SetDownloadBehaviorBehavior, SetDownloadBehaviorParams,
11};
12use chromiumoxide::cdp::browser_protocol::emulation::SetPageScaleFactorParams;
13use chromiumoxide::cdp::browser_protocol::fetch::{
14    ContinueRequestParams, FailRequestParams, FulfillRequestParams, HeaderEntry, RequestId,
15};
16use chromiumoxide::cdp::browser_protocol::network::ErrorReason;
17use futures::future::BoxFuture;
18use serde::Serialize;
19use serde_json::Value;
20use std::path::PathBuf;
21use std::sync::Arc;
22use std::time::Duration;
23
24/// How long an interceptor may take before the request is failed (fail closed).
25pub(crate) const INTERCEPTOR_TIMEOUT: Duration = Duration::from_secs(30);
26
27/// Structured exceptions kept per page (oldest dropped first).
28pub const MAX_EXCEPTIONS: usize = 200;
29
30// ---- request interception ------------------------------------------------------------------
31
32/// Which stage a paused request is at.
33#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
34pub enum InterceptStage {
35    /// Before the request leaves the browser. Redirect hops arrive here too.
36    Request,
37    /// After response headers arrived (only when response-stage patterns are enabled).
38    Response,
39}
40
41/// One `Fetch.requestPaused` event, decoded.
42#[derive(Clone, Debug, PartialEq, Serialize)]
43pub struct InterceptedRequest {
44    /// CDP fetch request id (what the answer is addressed to).
45    pub request_id: String,
46    pub url: String,
47    pub method: String,
48    /// Request headers, in the order CDP reported them.
49    pub headers: Vec<(String, String)>,
50    /// CDP resource type, e.g. `Document`, `XHR`, `Image`.
51    pub resource_type: String,
52    /// CDP frame id of the frame that issued the request.
53    pub frame_id: String,
54    pub has_post_data: bool,
55    /// Set when this request is a redirect hop: the id of the request whose redirect caused it.
56    /// Revalidate the new `url` here (origin pin) exactly as for a first request.
57    pub redirected_from: Option<String>,
58    pub stage: InterceptStage,
59    pub response_status: Option<i64>,
60    pub response_headers: Vec<(String, String)>,
61}
62
63impl InterceptedRequest {
64    /// True for a request created by following a redirect.
65    pub fn is_redirect(&self) -> bool {
66        self.redirected_from.is_some()
67    }
68
69    /// First header value with this name (case-insensitive).
70    pub fn header(&self, name: &str) -> Option<&str> {
71        self.headers
72            .iter()
73            .find(|(k, _)| k.eq_ignore_ascii_case(name))
74            .map(|(_, v)| v.as_str())
75    }
76
77    /// Decode the params of a `Fetch.requestPaused` event (CDP wire form).
78    pub fn from_cdp_value(v: &Value) -> Option<Self> {
79        let request = v.get("request")?;
80        let text = |o: &Value, k: &str| o.get(k).and_then(Value::as_str).map(str::to_string);
81        let response_status = v.get("responseStatusCode").and_then(Value::as_i64);
82        let stage = if response_status.is_some() || v.get("responseErrorReason").is_some() {
83            InterceptStage::Response
84        } else {
85            InterceptStage::Request
86        };
87        Some(Self {
88            request_id: text(v, "requestId")?,
89            url: text(request, "url")?,
90            method: text(request, "method").unwrap_or_else(|| "GET".into()),
91            headers: request
92                .get("headers")
93                .map(header_object)
94                .unwrap_or_default(),
95            resource_type: text(v, "resourceType").unwrap_or_default(),
96            frame_id: text(v, "frameId").unwrap_or_default(),
97            has_post_data: request
98                .get("hasPostData")
99                .and_then(Value::as_bool)
100                .unwrap_or(false),
101            redirected_from: text(v, "redirectedRequestId"),
102            stage,
103            response_status,
104            response_headers: v
105                .get("responseHeaders")
106                .map(header_entries)
107                .unwrap_or_default(),
108        })
109    }
110}
111
112/// Overrides for a continued request. Anything left `None` is unchanged.
113#[derive(Clone, Debug, Default, PartialEq)]
114pub struct ContinueOverrides {
115    /// Rewrites the URL without the page seeing it. Not re-checked against the network policy.
116    pub url: Option<String>,
117    pub method: Option<String>,
118    /// Replaces the request headers entirely.
119    pub headers: Option<Vec<(String, String)>>,
120    pub post_data: Option<Vec<u8>>,
121}
122
123/// Why a request is failed; maps to the CDP `Network.ErrorReason` the page sees.
124#[derive(Clone, Copy, Debug, Eq, PartialEq)]
125pub enum InterceptFailure {
126    Failed,
127    Aborted,
128    AccessDenied,
129    ConnectionRefused,
130    NameNotResolved,
131    BlockedByClient,
132}
133
134impl InterceptFailure {
135    fn reason(self) -> ErrorReason {
136        match self {
137            Self::Failed => ErrorReason::Failed,
138            Self::Aborted => ErrorReason::Aborted,
139            Self::AccessDenied => ErrorReason::AccessDenied,
140            Self::ConnectionRefused => ErrorReason::ConnectionRefused,
141            Self::NameNotResolved => ErrorReason::NameNotResolved,
142            Self::BlockedByClient => ErrorReason::BlockedByClient,
143        }
144    }
145}
146
147/// The answer to one paused request.
148#[derive(Clone, Debug, PartialEq)]
149pub enum InterceptDecision {
150    /// Let it through unchanged.
151    Continue,
152    /// Let it through with changes.
153    ContinueWith(ContinueOverrides),
154    /// Answer it from here; nothing reaches the network.
155    Fulfill {
156        status: u16,
157        headers: Vec<(String, String)>,
158        body: Vec<u8>,
159        phrase: Option<String>,
160    },
161    /// Fail it with a network error.
162    Fail(InterceptFailure),
163}
164
165/// Caller-supplied hook, consulted for every request the page makes (redirect hops included).
166///
167/// It runs after the session's [`crate::NetworkPolicy`]: a request the policy refuses is failed
168/// without the hook seeing it, so a hook can only narrow what the policy allows. A hook that
169/// takes longer than 30 s fails the request.
170pub type RequestInterceptor =
171    Arc<dyn Fn(InterceptedRequest) -> BoxFuture<'static, InterceptDecision> + Send + Sync>;
172
173/// The CDP command that answers a paused request.
174#[derive(Debug)]
175pub(crate) enum PausedCommand {
176    Continue(ContinueRequestParams),
177    Fulfill(FulfillRequestParams),
178    Fail(FailRequestParams),
179}
180
181pub(crate) fn command_for(id: RequestId, decision: InterceptDecision) -> PausedCommand {
182    match decision {
183        InterceptDecision::Continue => PausedCommand::Continue(ContinueRequestParams::new(id)),
184        InterceptDecision::ContinueWith(o) => {
185            let mut p = ContinueRequestParams::new(id);
186            p.url = o.url;
187            p.method = o.method;
188            p.headers = o.headers.map(header_entries_out);
189            p.post_data = o.post_data.map(|b| base64(&b).into());
190            PausedCommand::Continue(p)
191        }
192        InterceptDecision::Fulfill {
193            status,
194            headers,
195            body,
196            phrase,
197        } => {
198            let mut p = FulfillRequestParams::new(id, i64::from(status));
199            p.response_headers = Some(header_entries_out(headers));
200            if !body.is_empty() {
201                p.body = Some(base64(&body).into());
202            }
203            p.response_phrase = phrase;
204            PausedCommand::Fulfill(p)
205        }
206        InterceptDecision::Fail(f) => PausedCommand::Fail(FailRequestParams::new(id, f.reason())),
207    }
208}
209
210/// Ask the hook, failing the request when it does not answer in `limit`.
211pub(crate) async fn run_interceptor(
212    hook: &RequestInterceptor,
213    request: InterceptedRequest,
214    limit: Duration,
215) -> InterceptDecision {
216    match tokio::time::timeout(limit, hook(request)).await {
217        Ok(d) => d,
218        Err(_) => InterceptDecision::Fail(InterceptFailure::Failed),
219    }
220}
221
222// ---- accessibility tree --------------------------------------------------------------------
223
224/// One node of `Accessibility.getFullAXTree`.
225#[derive(Clone, Debug, PartialEq, Serialize)]
226pub struct AxNode {
227    pub node_id: String,
228    pub ignored: bool,
229    pub role: Option<String>,
230    pub name: Option<String>,
231    pub description: Option<String>,
232    /// The node's value (text fields, sliders). Chrome masks password values itself.
233    pub value: Option<Value>,
234    /// Other AX properties (`focused`, `disabled`, `level`, ...) as name and raw value.
235    pub properties: Vec<(String, Value)>,
236    pub parent_id: Option<String>,
237    pub child_ids: Vec<String>,
238    /// Backend DOM node id, usable with `DOM.resolveNode`.
239    pub backend_dom_node_id: Option<i64>,
240    pub frame_id: Option<String>,
241}
242
243impl AxNode {
244    /// Property by name.
245    pub fn property(&self, name: &str) -> Option<&Value> {
246        self.properties
247            .iter()
248            .find(|(k, _)| k == name)
249            .map(|(_, v)| v)
250    }
251}
252
253/// One non-ignored node of an accessibility tree that has a role, as carried by an observation.
254#[derive(Clone, Debug, PartialEq, Serialize)]
255pub struct AxSummary {
256    pub role: String,
257    /// Accessible name; empty when the node has none.
258    pub name: String,
259    /// CDP frame id of the node's document (empty when Chrome reports none).
260    pub frame_id: String,
261}
262
263/// Summarize an accessibility tree: ignored nodes and nodes without a role are dropped.
264pub(crate) fn summarize_ax(nodes: &[AxNode]) -> Vec<AxSummary> {
265    nodes
266        .iter()
267        .filter(|n| !n.ignored)
268        .filter_map(|n| {
269            let role = n.role.as_ref().filter(|r| !r.is_empty())?;
270            Some(AxSummary {
271                role: role.clone(),
272                name: n.name.clone().unwrap_or_default(),
273                frame_id: n.frame_id.clone().unwrap_or_default(),
274            })
275        })
276        .collect()
277}
278
279/// Decode the result of `Accessibility.getFullAXTree` (`{"nodes":[...]}`).
280pub(crate) fn parse_ax_tree(result: &Value) -> Vec<AxNode> {
281    let ax_value =
282        |n: &Value, k: &str| -> Option<Value> { n.get(k).and_then(|x| x.get("value")).cloned() };
283    let ax_text = |n: &Value, k: &str| -> Option<String> {
284        ax_value(n, k).and_then(|v| match v {
285            Value::String(s) => Some(s),
286            Value::Null => None,
287            other => Some(other.to_string()),
288        })
289    };
290    result
291        .get("nodes")
292        .and_then(Value::as_array)
293        .map(|nodes| {
294            nodes
295                .iter()
296                .filter_map(|n| {
297                    Some(AxNode {
298                        node_id: n.get("nodeId").and_then(Value::as_str)?.to_string(),
299                        ignored: n.get("ignored").and_then(Value::as_bool).unwrap_or(false),
300                        role: ax_text(n, "role"),
301                        name: ax_text(n, "name"),
302                        description: ax_text(n, "description"),
303                        value: ax_value(n, "value"),
304                        properties: n
305                            .get("properties")
306                            .and_then(Value::as_array)
307                            .map(|ps| {
308                                ps.iter()
309                                    .filter_map(|p| {
310                                        Some((
311                                            p.get("name")?.as_str()?.to_string(),
312                                            p.get("value")
313                                                .and_then(|v| v.get("value"))
314                                                .cloned()
315                                                .unwrap_or(Value::Null),
316                                        ))
317                                    })
318                                    .collect()
319                            })
320                            .unwrap_or_default(),
321                        parent_id: n
322                            .get("parentId")
323                            .and_then(Value::as_str)
324                            .map(str::to_string),
325                        child_ids: n
326                            .get("childIds")
327                            .and_then(Value::as_array)
328                            .map(|c| {
329                                c.iter()
330                                    .filter_map(Value::as_str)
331                                    .map(str::to_string)
332                                    .collect()
333                            })
334                            .unwrap_or_default(),
335                        backend_dom_node_id: n.get("backendDOMNodeId").and_then(Value::as_i64),
336                        frame_id: n.get("frameId").and_then(Value::as_str).map(str::to_string),
337                    })
338                })
339                .collect()
340        })
341        .unwrap_or_default()
342}
343
344// ---- exceptions ----------------------------------------------------------------------------
345
346/// One frame of an exception's stack.
347#[derive(Clone, Debug, PartialEq, Serialize)]
348pub struct ExceptionFrame {
349    pub function_name: String,
350    pub url: String,
351    /// Zero-based, as CDP reports it.
352    pub line: i64,
353    pub column: i64,
354}
355
356/// One `Runtime.exceptionThrown` event: an uncaught exception or unhandled rejection.
357#[derive(Clone, Debug, PartialEq, Serialize)]
358pub struct PageException {
359    /// `exceptionDetails.text`, usually `Uncaught`.
360    pub text: String,
361    /// The thrown value's description (`Error: boom\n    at ...`) when CDP gave one.
362    pub description: Option<String>,
363    pub url: Option<String>,
364    pub line: i64,
365    pub column: i64,
366    /// Milliseconds since the epoch, as CDP reports it.
367    pub timestamp_ms: f64,
368    pub stack: Vec<ExceptionFrame>,
369}
370
371impl PageException {
372    /// Best single-line-or-more message: the description, else the text.
373    pub fn message(&self) -> &str {
374        self.description.as_deref().unwrap_or(&self.text)
375    }
376
377    /// Decode the params of a `Runtime.exceptionThrown` event (CDP wire form).
378    pub fn from_cdp_value(v: &Value) -> Option<Self> {
379        let d = v.get("exceptionDetails")?;
380        Some(Self {
381            text: d.get("text").and_then(Value::as_str)?.to_string(),
382            description: d
383                .get("exception")
384                .and_then(|e| e.get("description"))
385                .and_then(Value::as_str)
386                .map(str::to_string),
387            url: d.get("url").and_then(Value::as_str).map(str::to_string),
388            line: d.get("lineNumber").and_then(Value::as_i64).unwrap_or(0),
389            column: d.get("columnNumber").and_then(Value::as_i64).unwrap_or(0),
390            timestamp_ms: v.get("timestamp").and_then(Value::as_f64).unwrap_or(0.0),
391            stack: d
392                .get("stackTrace")
393                .and_then(|s| s.get("callFrames"))
394                .and_then(Value::as_array)
395                .map(|frames| {
396                    frames
397                        .iter()
398                        .map(|f| ExceptionFrame {
399                            function_name: f
400                                .get("functionName")
401                                .and_then(Value::as_str)
402                                .unwrap_or_default()
403                                .to_string(),
404                            url: f
405                                .get("url")
406                                .and_then(Value::as_str)
407                                .unwrap_or_default()
408                                .to_string(),
409                            line: f.get("lineNumber").and_then(Value::as_i64).unwrap_or(0),
410                            column: f.get("columnNumber").and_then(Value::as_i64).unwrap_or(0),
411                        })
412                        .collect()
413                })
414                .unwrap_or_default(),
415        })
416    }
417}
418
419// ---- page scale and downloads ----------------------------------------------------------------
420
421/// Validated `Emulation.setPageScaleFactor` parameters.
422pub(crate) fn page_scale_params(scale: f64) -> Result<SetPageScaleFactorParams> {
423    if !scale.is_finite() || scale <= 0.0 {
424        return Err(BrowserError::Invalid(format!(
425            "page scale must be a positive finite number, got {scale}"
426        )));
427    }
428    Ok(SetPageScaleFactorParams::new(scale))
429}
430
431/// What the page does with a download.
432#[derive(Clone, Debug, Eq, PartialEq)]
433pub enum DownloadBehavior {
434    /// Refuse every download.
435    Deny,
436    /// Save under the file's own name into `dir`.
437    Allow { dir: PathBuf },
438    /// Save into `dir` named by the download's GUID (no name collisions, no caller-controlled names).
439    AllowAndName { dir: PathBuf },
440    /// Chrome's default behaviour.
441    Default,
442}
443
444/// Validated `Browser.setDownloadBehavior` parameters. A directory must be absolute and exist.
445pub(crate) fn download_params(behavior: &DownloadBehavior) -> Result<SetDownloadBehaviorParams> {
446    let dir_text = |dir: &PathBuf| -> Result<String> {
447        if !dir.is_absolute() {
448            return Err(BrowserError::Invalid(format!(
449                "download directory must be absolute: {}",
450                dir.display()
451            )));
452        }
453        if !dir.is_dir() {
454            return Err(BrowserError::Invalid(format!(
455                "download directory does not exist: {}",
456                dir.display()
457            )));
458        }
459        Ok(dir.to_string_lossy().into_owned())
460    };
461    Ok(match behavior {
462        DownloadBehavior::Deny => SetDownloadBehaviorParams::new(SetDownloadBehaviorBehavior::Deny),
463        DownloadBehavior::Default => {
464            SetDownloadBehaviorParams::new(SetDownloadBehaviorBehavior::Default)
465        }
466        DownloadBehavior::Allow { dir } => {
467            let mut p = SetDownloadBehaviorParams::new(SetDownloadBehaviorBehavior::Allow);
468            p.download_path = Some(dir_text(dir)?);
469            p
470        }
471        DownloadBehavior::AllowAndName { dir } => {
472            let mut p = SetDownloadBehaviorParams::new(SetDownloadBehaviorBehavior::AllowAndName);
473            p.download_path = Some(dir_text(dir)?);
474            p
475        }
476    })
477}
478
479// ---- helpers ---------------------------------------------------------------------------------
480
481/// `Network.Headers`: a JSON object of name to value.
482fn header_object(v: &Value) -> Vec<(String, String)> {
483    v.as_object()
484        .map(|o| {
485            o.iter()
486                .map(|(k, v)| {
487                    (
488                        k.clone(),
489                        v.as_str()
490                            .map(str::to_string)
491                            .unwrap_or_else(|| v.to_string()),
492                    )
493                })
494                .collect()
495        })
496        .unwrap_or_default()
497}
498
499/// `Fetch.HeaderEntry` array.
500fn header_entries(v: &Value) -> Vec<(String, String)> {
501    v.as_array()
502        .map(|a| {
503            a.iter()
504                .filter_map(|h| {
505                    Some((
506                        h.get("name")?.as_str()?.to_string(),
507                        h.get("value")?.as_str()?.to_string(),
508                    ))
509                })
510                .collect()
511        })
512        .unwrap_or_default()
513}
514
515fn header_entries_out(h: Vec<(String, String)>) -> Vec<HeaderEntry> {
516    h.into_iter().map(|(n, v)| HeaderEntry::new(n, v)).collect()
517}
518
519/// Standard base64 with padding (CDP `binary`).
520pub(crate) fn base64(bytes: &[u8]) -> String {
521    const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
522    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
523    for c in bytes.chunks(3) {
524        let n = (u32::from(c[0]) << 16)
525            | (u32::from(*c.get(1).unwrap_or(&0)) << 8)
526            | u32::from(*c.get(2).unwrap_or(&0));
527        out.push(T[(n >> 18) as usize & 63] as char);
528        out.push(T[(n >> 12) as usize & 63] as char);
529        out.push(if c.len() > 1 {
530            T[(n >> 6) as usize & 63] as char
531        } else {
532            '='
533        });
534        out.push(if c.len() > 2 {
535            T[n as usize & 63] as char
536        } else {
537            '='
538        });
539    }
540    out
541}