Skip to main content

rightkit_browser/
page.rs

1use crate::cdp_ext::{
2    command_for, download_params, page_scale_params, parse_ax_tree, run_interceptor, summarize_ax,
3    AxNode, AxSummary, DownloadBehavior, InterceptDecision, InterceptFailure, InterceptedRequest,
4    PageException, PausedCommand, RequestInterceptor, INTERCEPTOR_TIMEOUT, MAX_EXCEPTIONS,
5};
6use crate::cookies::{self, NetscapeCookie};
7use crate::design_mode::{self, DesignModeBridge, DesignModeSession, NativeGestureLatch};
8use crate::error::{cdp, BrowserError, Result};
9use crate::keys::{self, KeyDef};
10use crate::policy::{ActionKind, AdmissionRequest, BlockedRequest, Guard, LifecycleKind};
11use chromiumoxide::cdp::browser_protocol::accessibility::GetFullAxTreeParams;
12use chromiumoxide::cdp::browser_protocol::dom::SetFileInputFilesParams;
13use chromiumoxide::cdp::browser_protocol::emulation::SetUserAgentOverrideParams;
14use chromiumoxide::cdp::browser_protocol::fetch::{
15    EnableParams as FetchEnableParams, EventRequestPaused, FailRequestParams, RequestPattern,
16};
17use chromiumoxide::cdp::browser_protocol::input::{
18    DispatchKeyEventParams, DispatchKeyEventType, DispatchMouseEventParams, DispatchMouseEventType,
19    MouseButton,
20};
21use chromiumoxide::cdp::browser_protocol::inspector::{
22    EnableParams as InspectorEnableParams, EventTargetCrashed,
23};
24use chromiumoxide::cdp::browser_protocol::network::{
25    ErrorReason, Headers, SetCookiesParams, SetExtraHttpHeadersParams,
26};
27use chromiumoxide::cdp::browser_protocol::page::CreateIsolatedWorldParams;
28use chromiumoxide::cdp::browser_protocol::page::{
29    CaptureScreenshotFormat, CaptureScreenshotParams, Viewport,
30};
31use chromiumoxide::cdp::js_protocol::runtime::{
32    AddBindingParams, EvaluateParams, EventBindingCalled, EventConsoleApiCalled,
33    EventExceptionThrown, ExecutionContextId,
34};
35use chromiumoxide::page::{Page, ScreenshotParams};
36use futures::StreamExt;
37use serde::{Deserialize, Serialize};
38use serde_json::Value;
39use std::collections::HashMap;
40use std::path::{Path, PathBuf};
41use std::sync::atomic::{AtomicBool, Ordering};
42use std::sync::{Arc, Mutex as StdMutex};
43use std::time::{Duration, Instant};
44use tokio::sync::{broadcast, Mutex};
45use tokio::task::JoinHandle;
46
47pub const MAX_CONSOLE_LINES: usize = 500;
48const MAX_UPLOAD_BYTES: u64 = 64 * 1024 * 1024;
49
50#[derive(Clone, Debug, Serialize)]
51pub struct ConsoleLine {
52    pub level: String,
53    pub text: String,
54}
55
56#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
57pub struct Rect {
58    pub x: f64,
59    pub y: f64,
60    pub width: f64,
61    pub height: f64,
62}
63
64#[derive(Clone, Debug, Serialize)]
65pub struct ObservedNode {
66    /// `r<epoch>.<n>`; valid only while the page stays unchanged.
67    pub node_ref: String,
68    pub role: String,
69    /// Masked (`••••••••`) when `sensitive` is true.
70    pub name: String,
71    pub tag: String,
72    pub selector: String,
73    pub visible: bool,
74    pub disabled: bool,
75    /// True for password-like fields (`type=password`, `current-password`, `new-password`).
76    /// Their name is masked; callers should mask any value they show.
77    pub sensitive: bool,
78    /// CDP frame id of the document the node was read from. An observation reads the main
79    /// document only (iframe contents are not enumerated, see the changelog), so this is the
80    /// main frame's id for every node; it does not make iframe controls observable.
81    pub frame_id: String,
82    /// Stable across consecutive observations of the same document for the same selector.
83    /// `0` when the node has no selector (such nodes cannot be targeted by ref either).
84    pub stable_id: u64,
85    pub bounds: Rect,
86}
87
88#[derive(Clone, Debug, Serialize)]
89pub struct Observation {
90    pub page_id: String,
91    pub epoch: u64,
92    pub url: String,
93    pub title: String,
94    pub viewport: Rect,
95    pub nodes: Vec<ObservedNode>,
96    /// Accessibility summary of the main frame, bounded to depth [`OBSERVE_AX_DEPTH`].
97    pub ax: Vec<AxSummary>,
98    pub console_errors: usize,
99    /// Refs/roles/names added, removed, or changed since the previous observation.
100    pub added: Vec<String>,
101    pub removed: Vec<String>,
102}
103
104/// Depth bound for the accessibility summary in an [`Observation`].
105pub const OBSERVE_AX_DEPTH: u32 = 12;
106
107/// How long a history traversal waits for a navigation event before returning. A traversal
108/// that fires no navigation (bfcache restore, same-document entry) must not hang the caller.
109const HISTORY_NAVIGATION_WAIT: Duration = Duration::from_secs(10);
110
111/// Longest accepted user-agent string, in bytes.
112pub const MAX_USER_AGENT_BYTES: usize = 1024;
113/// Most extra HTTP headers one [`BrowserPage::set_extra_headers`] call accepts.
114pub const MAX_EXTRA_HEADERS: usize = 32;
115/// Longest accepted extra-header value, in bytes.
116pub const MAX_HEADER_VALUE_BYTES: usize = 8192;
117
118/// Screenshot options for [`BrowserPage::screenshot_with`]. The default is the viewport as PNG.
119#[derive(Clone, Copy, Debug, Default, PartialEq)]
120pub struct ScreenshotOptions {
121    /// Capture with a transparent background (PNG only). Pair with
122    /// [`BrowserPage::set_transparent_background`] for a fully transparent page.
123    pub omit_background: bool,
124    /// Image format; PNG by default.
125    pub format: ScreenshotFormat,
126    /// Capture only this region, in CSS pixels of the page. `None` captures the visible viewport
127    /// (or, with a `scale`, the whole visual viewport).
128    pub clip: Option<ScreenshotClip>,
129    /// Output scale of the capture, a positive finite factor (`1.0` when `None`). Use it with
130    /// `clip` or alone to produce a smaller image, for example a 1280 px wide frame of a wider
131    /// viewport.
132    pub scale: Option<f64>,
133}
134
135/// Image format of a screenshot.
136#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
137pub enum ScreenshotFormat {
138    /// Lossless PNG.
139    #[default]
140    Png,
141    /// JPEG at `quality`, 1 to 100.
142    Jpeg { quality: u8 },
143}
144
145/// A capture region in CSS pixels of the page. `x` and `y` are at least zero; `width` and
146/// `height` are positive.
147#[derive(Clone, Copy, Debug, PartialEq)]
148pub struct ScreenshotClip {
149    pub x: f64,
150    pub y: f64,
151    pub width: f64,
152    pub height: f64,
153}
154
155impl ScreenshotClip {
156    fn validate(&self) -> Result<()> {
157        let finite = [self.x, self.y, self.width, self.height]
158            .iter()
159            .all(|v| v.is_finite());
160        if !finite || self.x < 0.0 || self.y < 0.0 || self.width <= 0.0 || self.height <= 0.0 {
161            return Err(BrowserError::Invalid(
162                "screenshot clip needs finite x and y of at least 0 and a positive width and height"
163                    .into(),
164            ));
165        }
166        Ok(())
167    }
168}
169
170/// RFC 9110 token characters, the only bytes a header name may contain.
171fn is_header_token(name: &str) -> bool {
172    !name.is_empty()
173        && name
174            .bytes()
175            .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
176}
177
178fn has_control(value: &str) -> bool {
179    value.chars().any(|c| c.is_control())
180}
181
182/// What an action addresses.
183#[derive(Clone, Debug)]
184pub enum Target {
185    /// Ref from [`BrowserPage::observe`]; checked for staleness.
186    Ref(String),
187    /// A CSS selector that must match exactly one element.
188    Selector(String),
189    /// Viewport coordinates.
190    Point(f64, f64),
191}
192
193impl Target {
194    pub fn css(s: impl Into<String>) -> Self {
195        Target::Selector(s.into())
196    }
197    pub fn node_ref(s: impl Into<String>) -> Self {
198        Target::Ref(s.into())
199    }
200}
201
202#[derive(Clone, Debug, Deserialize)]
203struct RawNode {
204    role: String,
205    name: String,
206    tag: String,
207    selector: String,
208    visible: bool,
209    disabled: bool,
210    #[serde(default)]
211    sensitive: bool,
212    bounds: Rect,
213}
214
215#[derive(Clone, Debug)]
216struct RefEntry {
217    selector: String,
218    tag: String,
219    role: String,
220    name: String,
221}
222
223#[derive(Default)]
224struct ObsState {
225    epoch: u64,
226    fingerprint: String,
227    refs: HashMap<String, RefEntry>,
228    previous: HashMap<String, String>,
229    /// Stable ids of the previous observation's selectors (bounded by its node count).
230    stable: HashMap<String, u64>,
231    next_stable: u64,
232}
233
234/// What the request-interception pump has done on one page. Reported when a navigation
235/// fails, so a timeout says how far the navigation got: no request paused (it never reached
236/// the network stage), paused but not answered (the policy check did not return), or
237/// continued (the request left the browser and the proxy or the server did not finish it).
238#[derive(Default)]
239struct InterceptStats {
240    paused: std::sync::atomic::AtomicUsize,
241    continued: std::sync::atomic::AtomicUsize,
242    fulfilled: std::sync::atomic::AtomicUsize,
243    refused: std::sync::atomic::AtomicUsize,
244    errors: std::sync::atomic::AtomicUsize,
245    last_error: StdMutex<Option<String>>,
246}
247
248impl InterceptStats {
249    fn summary(&self) -> String {
250        use std::sync::atomic::Ordering::Relaxed;
251        let mut text = format!(
252            "requests paused {}, continued {}, refused {}",
253            self.paused.load(Relaxed),
254            self.continued.load(Relaxed),
255            self.refused.load(Relaxed)
256        );
257        let fulfilled = self.fulfilled.load(Relaxed);
258        if fulfilled > 0 {
259            text.push_str(&format!(", fulfilled {fulfilled}"));
260        }
261        let errors = self.errors.load(Relaxed);
262        if errors > 0 {
263            let last = self.last_error.lock().unwrap().clone().unwrap_or_default();
264            text.push_str(&format!(", {errors} not answered: {last}"));
265        }
266        text
267    }
268}
269
270pub struct BrowserPage {
271    id: String,
272    /// CDP target id: the stable identity of the tab (`id` is the session's own sequence).
273    target_id: String,
274    inner: Page,
275    console: Arc<Mutex<Vec<ConsoleLine>>>,
276    obs: StdMutex<ObsState>,
277    mouse: StdMutex<(f64, f64)>,
278    buttons: StdMutex<i64>,
279    /// Serializes mutations so concurrent callers commit in order.
280    lane: Mutex<()>,
281    upload_root: Option<PathBuf>,
282    pumps: StdMutex<Vec<JoinHandle<()>>>,
283    guard: Arc<Guard>,
284    blocked: Arc<StdMutex<Vec<BlockedRequest>>>,
285    intercept: Arc<InterceptStats>,
286    /// Caller hook consulted after the network policy; see [`BrowserPage::set_request_interceptor`].
287    interceptor: Arc<StdMutex<Option<RequestInterceptor>>>,
288    /// True once this page's request-interception pump (and `Fetch.enable`) is running.
289    pump_running: AtomicBool,
290    /// The fixture session owns `Fetch` on this page; a caller hook cannot share it.
291    fixture_fetch_owner: bool,
292    exceptions: Arc<StdMutex<Vec<PageException>>>,
293    exception_tx: broadcast::Sender<PageException>,
294    /// Latest native input gesture (pointer press, key down) this page dispatched.
295    design_gesture: Arc<NativeGestureLatch>,
296    /// Isolated-world context of the design-mode picker, once enabled.
297    design_context: StdMutex<Option<ExecutionContextId>>,
298}
299
300/// Buffered capacity of an exception subscription; a slower receiver sees `Lagged`.
301const EXCEPTION_CHANNEL: usize = 64;
302
303impl BrowserPage {
304    pub(crate) async fn attach(
305        id: String,
306        inner: Page,
307        upload_root: Option<PathBuf>,
308        guard: Arc<Guard>,
309        fixture_fetch_owner: bool,
310    ) -> Result<Self> {
311        let console = Arc::new(Mutex::new(Vec::new()));
312        let mut pumps = Vec::new();
313        let mut ev = inner
314            .event_listener::<EventConsoleApiCalled>()
315            .await
316            .map_err(cdp)?;
317        let sink = console.clone();
318        pumps.push(tokio::spawn(async move {
319            while let Some(e) = ev.next().await {
320                let text = e
321                    .args
322                    .iter()
323                    .map(|a| match (&a.value, &a.description) {
324                        (Some(Value::String(s)), _) => s.clone(),
325                        (Some(v), _) => v.to_string(),
326                        (None, Some(d)) => d.clone(),
327                        _ => String::new(),
328                    })
329                    .collect::<Vec<_>>()
330                    .join(" ");
331                push_capped(
332                    &sink,
333                    ConsoleLine {
334                        level: format!("{:?}", e.r#type).to_lowercase(),
335                        text,
336                    },
337                )
338                .await;
339            }
340        }));
341        let mut ex = inner
342            .event_listener::<EventExceptionThrown>()
343            .await
344            .map_err(cdp)?;
345        let sink = console.clone();
346        let exceptions = Arc::new(StdMutex::new(Vec::new()));
347        let (exception_tx, _) = broadcast::channel(EXCEPTION_CHANNEL);
348        let (ex_log, ex_tx) = (exceptions.clone(), exception_tx.clone());
349        pumps.push(tokio::spawn(async move {
350            while let Some(e) = ex.next().await {
351                if let Some(parsed) = serde_json::to_value(&*e)
352                    .ok()
353                    .and_then(|v| PageException::from_cdp_value(&v))
354                {
355                    {
356                        let mut log = ex_log.lock().unwrap();
357                        if log.len() >= MAX_EXCEPTIONS {
358                            log.remove(0);
359                        }
360                        log.push(parsed.clone());
361                    }
362                    // No receiver is the normal case; the buffered list still has it.
363                    let _ = ex_tx.send(parsed);
364                }
365                let d = &e.exception_details;
366                let text = d
367                    .exception
368                    .as_ref()
369                    .and_then(|x| x.description.clone())
370                    .unwrap_or_else(|| d.text.clone());
371                push_capped(
372                    &sink,
373                    ConsoleLine {
374                        level: "exception".into(),
375                        text,
376                    },
377                )
378                .await;
379            }
380        }));
381        // Renderer crash -> `Crash` lifecycle event for this page.
382        let mut crashed = inner
383            .event_listener::<EventTargetCrashed>()
384            .await
385            .map_err(cdp)?;
386        let (g, page_id) = (guard.clone(), id.clone());
387        pumps.push(tokio::spawn(async move {
388            while crashed.next().await.is_some() {
389                g.emit_kind(LifecycleKind::Crash, "renderer crashed", |e| {
390                    e.page_id = Some(page_id.clone());
391                });
392            }
393        }));
394        inner
395            .execute(InspectorEnableParams::default())
396            .await
397            .map_err(cdp)?;
398        let blocked = Arc::new(StdMutex::new(Vec::new()));
399        let intercept = Arc::new(InterceptStats::default());
400        let interceptor = Arc::new(StdMutex::new(None));
401        let mut pump_running = false;
402        if !guard.network.unrestricted && !fixture_fetch_owner {
403            // Pause every request (document, redirect hops, subresources) and
404            // decide before it leaves the browser. Enabled before any navigation.
405            pumps.push(
406                start_intercept_pump(
407                    &inner,
408                    &id,
409                    &guard,
410                    blocked.clone(),
411                    intercept.clone(),
412                    interceptor.clone(),
413                )
414                .await?,
415            );
416            pump_running = true;
417        }
418        let target_id = inner.target_id().as_ref().to_string();
419        Ok(Self {
420            id,
421            target_id,
422            inner,
423            console,
424            obs: StdMutex::new(ObsState::default()),
425            mouse: StdMutex::new((0.0, 0.0)),
426            buttons: StdMutex::new(0),
427            lane: Mutex::new(()),
428            upload_root,
429            pumps: StdMutex::new(pumps),
430            guard,
431            blocked,
432            intercept,
433            interceptor,
434            pump_running: AtomicBool::new(pump_running),
435            fixture_fetch_owner,
436            exceptions,
437            exception_tx,
438            design_gesture: Arc::new(NativeGestureLatch::new()),
439            design_context: StdMutex::new(None),
440        })
441    }
442
443    pub fn id(&self) -> &str {
444        &self.id
445    }
446
447    /// The CDP target id of this tab. Unlike [`BrowserPage::id`], it is Chrome's own identity
448    /// for the tab and does not change when the session renumbers pages.
449    pub fn target_id(&self) -> &str {
450        &self.target_id
451    }
452
453    /// Frame ids of every frame in the page (CDP `Page.getFrameTree`), read-only.
454    pub async fn frames(&self) -> Result<Vec<String>> {
455        let frames = self.inner.frames().await.map_err(cdp)?;
456        Ok(frames.iter().map(|f| f.as_ref().to_string()).collect())
457    }
458
459    /// Install (or with `None`, remove) a caller hook that answers every request this page
460    /// makes: continue, continue with changes, fulfil from memory, or fail. Redirect hops arrive
461    /// as separate requests with [`InterceptedRequest::redirected_from`] set, so a hook that pins
462    /// an origin revalidates each hop.
463    ///
464    /// The session's network policy runs first and its refusals are final; the hook only
465    /// narrows what the policy allows. A hook that takes longer than 30 s fails the request.
466    /// Turns on `Fetch` interception for this page when the policy had not (an unrestricted
467    /// session); requests already in flight are not affected. Removing the hook lets requests
468    /// through unchanged but leaves interception running. Not available on a fixture page, whose
469    /// session owns `Fetch`: returns [`BrowserError::Invalid`].
470    pub async fn set_request_interceptor(&self, hook: Option<RequestInterceptor>) -> Result<()> {
471        if self.fixture_fetch_owner {
472            return Err(BrowserError::Invalid(
473                "a fixture page's session owns request interception".into(),
474            ));
475        }
476        let install = hook.is_some();
477        *self.interceptor.lock().unwrap() = hook;
478        if install && !self.pump_running.swap(true, Ordering::SeqCst) {
479            match start_intercept_pump(
480                &self.inner,
481                &self.id,
482                &self.guard,
483                self.blocked.clone(),
484                self.intercept.clone(),
485                self.interceptor.clone(),
486            )
487            .await
488            {
489                Ok(pump) => self.pumps.lock().unwrap().push(pump),
490                Err(e) => {
491                    self.pump_running.store(false, Ordering::SeqCst);
492                    *self.interceptor.lock().unwrap() = None;
493                    return Err(e);
494                }
495            }
496        }
497        Ok(())
498    }
499
500    /// The page's full accessibility tree (`Accessibility.getFullAXTree`), root frame, in CDP
501    /// order. Ignored nodes are included and flagged. Read-only.
502    pub async fn accessibility_tree(&self) -> Result<Vec<AxNode>> {
503        self.ax_tree(None).await
504    }
505
506    /// The accessibility tree cut off below `depth` (root is depth 0). Use it on heavy pages,
507    /// where the full tree costs too much. Read-only, like [`BrowserPage::accessibility_tree`].
508    pub async fn accessibility_tree_with(&self, depth: u32) -> Result<Vec<AxNode>> {
509        self.ax_tree(Some(depth)).await
510    }
511
512    async fn ax_tree(&self, depth: Option<u32>) -> Result<Vec<AxNode>> {
513        let params = GetFullAxTreeParams {
514            depth: depth.map(i64::from),
515            ..Default::default()
516        };
517        let r = self.inner.execute(params).await.map_err(cdp)?;
518        let wire = serde_json::to_value(&r.result).map_err(cdp)?;
519        Ok(parse_ax_tree(&wire))
520    }
521
522    /// Make the page background transparent (`Emulation.setDefaultBackgroundColorOverride`
523    /// with alpha 0), or restore Chrome's default with `false`. Pair with
524    /// [`BrowserPage::screenshot_with`] and `omit_background` to capture alpha. Like
525    /// [`BrowserPage::set_page_scale`], this changes rendering only and is not admitted.
526    pub async fn set_transparent_background(&self, transparent: bool) -> Result<()> {
527        use chromiumoxide::cdp::browser_protocol::dom::Rgba;
528        use chromiumoxide::cdp::browser_protocol::emulation::SetDefaultBackgroundColorOverrideParams;
529        let params = if transparent {
530            SetDefaultBackgroundColorOverrideParams::builder()
531                .color(Rgba {
532                    r: 0,
533                    g: 0,
534                    b: 0,
535                    a: Some(0.0),
536                })
537                .build()
538        } else {
539            SetDefaultBackgroundColorOverrideParams::builder().build()
540        };
541        self.inner.execute(params).await.map_err(cdp)?;
542        Ok(())
543    }
544
545    /// Uncaught exceptions and unhandled rejections seen so far (`Runtime.exceptionThrown`),
546    /// oldest first, at most [`MAX_EXCEPTIONS`](crate::MAX_EXCEPTIONS). Collected from the moment
547    /// the page exists, so nothing from its first navigation is missed.
548    pub fn exceptions(&self) -> Vec<PageException> {
549        self.exceptions.lock().unwrap().clone()
550    }
551
552    pub fn clear_exceptions(&self) {
553        self.exceptions.lock().unwrap().clear();
554    }
555
556    /// Live stream of exceptions from now on. The page exists before its first navigation, so a
557    /// subscriber taken before `goto` sees every exception it raises. A receiver that falls more
558    /// than 64 behind gets `RecvError::Lagged`; [`BrowserPage::exceptions`] still has them.
559    pub fn subscribe_exceptions(&self) -> broadcast::Receiver<PageException> {
560        self.exception_tx.subscribe()
561    }
562
563    /// Set the page scale factor (pinch zoom, `Emulation.setPageScaleFactor`). Must be positive
564    /// and finite. Distinct from the device scale factor of [`BrowserPage::set_viewport`].
565    pub async fn set_page_scale(&self, scale: f64) -> Result<()> {
566        self.inner
567            .execute(page_scale_params(scale)?)
568            .await
569            .map_err(cdp)?;
570        Ok(())
571    }
572
573    /// Choose what happens to downloads (`Browser.setDownloadBehavior`). `Allow` and
574    /// `AllowAndName` need an absolute, existing directory; downloads go nowhere else.
575    /// Admitted as an `Eval`-kind effect (detail `download_behavior ...`) because it lets pages
576    /// write files. Applies to the browser's default context, so it covers every page of a
577    /// session; a later call replaces an earlier one.
578    pub async fn set_download_behavior(&self, behavior: &DownloadBehavior) -> Result<()> {
579        let params = download_params(behavior)?;
580        self.admit(
581            ActionKind::Eval,
582            None,
583            None,
584            Some(format!("download_behavior {behavior:?}")),
585        )
586        .await?;
587        self.inner.execute(params).await.map_err(cdp)?;
588        Ok(())
589    }
590
591    /// Override the user agent of this page (`Emulation.setUserAgentOverride`), and optionally
592    /// its `Accept-Language`. Applies to this page's later requests and scripts. Admitted as an
593    /// `Eval`-kind effect (detail `user_agent`).
594    pub async fn set_user_agent(
595        &self,
596        user_agent: &str,
597        accept_language: Option<&str>,
598    ) -> Result<()> {
599        let ua = user_agent.trim();
600        if ua.is_empty() || ua.len() > MAX_USER_AGENT_BYTES || has_control(ua) {
601            return Err(BrowserError::Invalid(format!(
602                "user agent must be 1 to {MAX_USER_AGENT_BYTES} bytes without control characters"
603            )));
604        }
605        let mut builder = SetUserAgentOverrideParams::builder().user_agent(ua);
606        if let Some(lang) = accept_language {
607            let lang = lang.trim();
608            if lang.is_empty() || lang.len() > MAX_HEADER_VALUE_BYTES || has_control(lang) {
609                return Err(BrowserError::Invalid(
610                    "accept-language must be non-empty and free of control characters".into(),
611                ));
612            }
613            builder = builder.accept_language(lang);
614        }
615        let params = builder
616            .build()
617            .map_err(|e| BrowserError::Invalid(format!("user agent override: {e}")))?;
618        self.admit(ActionKind::Eval, None, None, Some("user_agent".into()))
619            .await?;
620        self.inner.execute(params).await.map_err(cdp)?;
621        Ok(())
622    }
623
624    /// Send `headers` with every later request of this page (`Network.setExtraHTTPHeaders`).
625    /// Each call replaces the previous set; an empty slice clears it. Names are case-insensitive
626    /// and must be unique; values may not contain control characters. Admitted as an `Eval`-kind
627    /// effect whose detail carries the count only: header values are never logged.
628    pub async fn set_extra_headers(&self, headers: &[(String, String)]) -> Result<()> {
629        if headers.len() > MAX_EXTRA_HEADERS {
630            return Err(BrowserError::Invalid(format!(
631                "set_extra_headers takes at most {MAX_EXTRA_HEADERS} headers"
632            )));
633        }
634        let mut map = serde_json::Map::new();
635        for (name, value) in headers {
636            if !is_header_token(name) {
637                return Err(BrowserError::Invalid(
638                    "extra header names must be non-empty HTTP tokens".into(),
639                ));
640            }
641            if value.len() > MAX_HEADER_VALUE_BYTES || value.contains(['\r', '\n', '\0']) {
642                return Err(BrowserError::Invalid(format!(
643                    "extra header value must be at most {MAX_HEADER_VALUE_BYTES} bytes without CR, LF or NUL"
644                )));
645            }
646            let key = name.to_ascii_lowercase();
647            if map.contains_key(&key) {
648                return Err(BrowserError::Invalid("duplicate extra header name".into()));
649            }
650            map.insert(key, Value::String(value.clone()));
651        }
652        self.admit(
653            ActionKind::Eval,
654            None,
655            None,
656            Some(format!("extra_headers {} names", headers.len())),
657        )
658        .await?;
659        self.inner
660            .execute(SetExtraHttpHeadersParams::new(Headers::new(Value::Object(
661                map,
662            ))))
663            .await
664            .map_err(cdp)?;
665        Ok(())
666    }
667
668    /// Set `cookies` in the browser profile this page belongs to (`Network.setCookies`) and
669    /// return how many were set. The cookies apply to the whole profile, not to this page, and
670    /// persist with a named or directory profile. A subdomain-matching cookie gets a leading dot
671    /// on its domain; a host-only cookie does not. Chrome rejects the whole batch if one cookie
672    /// is invalid (for example a `__Secure-` name without `secure`); the error then sets none
673    /// and its text never contains a cookie value.
674    ///
675    /// Domain filtering, user consent and file selection belong to the caller: this sets exactly
676    /// what it is given. Admitted as an `Eval`-kind effect (detail `import_cookies`, the count
677    /// and the distinct domains; never names or values). An empty slice returns `Ok(0)` without
678    /// contacting the browser; more than [`MAX_COOKIES`](crate::cookies::MAX_COOKIES) is refused.
679    pub async fn import_cookies(&self, cookies: &[NetscapeCookie]) -> Result<usize> {
680        if cookies.is_empty() {
681            return Ok(0);
682        }
683        if cookies.len() > cookies::MAX_COOKIES {
684            return Err(BrowserError::Invalid(format!(
685                "import_cookies takes at most {} cookies",
686                cookies::MAX_COOKIES
687            )));
688        }
689        self.admit(
690            ActionKind::Eval,
691            None,
692            None,
693            Some(cookies::admission_detail(cookies)),
694        )
695        .await?;
696        let _l = self.lane.lock().await;
697        let params = SetCookiesParams::new(cookies::to_cdp_params(cookies));
698        self.inner.execute(params).await.map_err(|e| {
699            BrowserError::Cdp(format!(
700                "Network.setCookies: {}",
701                cookies::scrub(&e.to_string(), cookies)
702            ))
703        })?;
704        Ok(cookies.len())
705    }
706
707    /// Requests the network policy refused on this page (redirect hops and subresources included).
708    pub fn blocked_requests(&self) -> Vec<BlockedRequest> {
709        self.blocked.lock().unwrap().clone()
710    }
711
712    /// Typed pre-effect admission. Reads no page state beyond the current URL.
713    async fn admit(
714        &self,
715        action: ActionKind,
716        url: Option<String>,
717        target: Option<String>,
718        detail: Option<String>,
719    ) -> Result<()> {
720        let url = match url {
721            Some(u) => Some(u),
722            None if self.guard.admission.is_some() => Some(self.url().await),
723            None => None,
724        };
725        self.guard
726            .admit(AdmissionRequest {
727                session_id: self.guard.session_id.clone(),
728                page_id: self.id.clone(),
729                action,
730                url,
731                target,
732                detail,
733            })
734            .await
735    }
736
737    /// Escape hatch to the underlying chromiumoxide page.
738    pub fn raw(&self) -> &Page {
739        &self.inner
740    }
741
742    pub(crate) fn abort_pumps(&self) {
743        if let Ok(mut p) = self.pumps.lock() {
744            for h in p.drain(..) {
745                h.abort();
746            }
747        }
748    }
749
750    pub(crate) async fn close_inner(&self) -> Result<()> {
751        self.abort_pumps();
752        self.inner.clone().close().await.map_err(cdp)
753    }
754
755    pub async fn bring_to_front(&self) -> Result<()> {
756        self.inner.bring_to_front().await.map_err(cdp)?;
757        Ok(())
758    }
759
760    // ---- navigation ------------------------------------------------------
761
762    fn invalidate(&self) {
763        let mut o = self.obs.lock().unwrap();
764        o.epoch += 1;
765        o.refs.clear();
766        o.fingerprint.clear();
767        // A navigation starts a new document: its selectors do not carry stable ids over.
768        o.stable.clear();
769    }
770
771    /// Waits until this new tab's own first navigation (to about:blank) has committed.
772    ///
773    /// A tab is created at about:blank and that navigation commits a little later. A
774    /// navigation sent before then is discarded by that commit: Chrome answers it with
775    /// `net::ERR_ABORTED` and no load ever follows, so the caller waits out its whole request
776    /// timeout. Seen on Windows, where a new tab's renderer starts more slowly.
777    ///
778    /// Before the commit the tab's committed history entry has an empty URL. The tab counts
779    /// as settled when that entry has a URL and the main frame's loader is the same on two
780    /// consecutive polls. Bounded at two seconds, and it stops at once if Chrome does not
781    /// answer, so a browser that behaves differently is not waited on.
782    pub(crate) async fn settle_initial_document(&self) {
783        use chromiumoxide::cdp::browser_protocol::page::{
784            GetFrameTreeParams, GetNavigationHistoryParams,
785        };
786        use std::time::{Duration, Instant};
787        let deadline = Instant::now() + Duration::from_secs(2);
788        let mut seen: Option<String> = None;
789        while Instant::now() < deadline {
790            let Ok(history) = self
791                .inner
792                .execute(GetNavigationHistoryParams::default())
793                .await
794            else {
795                return;
796            };
797            let Ok(tree) = self.inner.execute(GetFrameTreeParams::default()).await else {
798                return;
799            };
800            let committed = usize::try_from(history.result.current_index)
801                .ok()
802                .and_then(|index| history.result.entries.get(index))
803                .is_some_and(|entry| !entry.url.is_empty());
804            let loader = format!("{:?}", tree.result.frame_tree.frame.loader_id);
805            if !committed {
806                seen = None;
807            } else if seen.as_deref() == Some(loader.as_str()) {
808                return;
809            } else {
810                seen = Some(loader);
811            }
812            tokio::time::sleep(Duration::from_millis(10)).await;
813        }
814    }
815
816    pub async fn goto(&self, url: &str) -> Result<()> {
817        // EFF-001 order: policy, then approval; both before any side effect.
818        self.guard
819            .check_url(Some(&self.id), url, "Navigation")
820            .await?;
821        self.admit(ActionKind::Navigate, Some(url.to_string()), None, None)
822            .await?;
823        let _l = self.lane.lock().await;
824        self.inner.goto(url).await.map_err(|e| {
825            BrowserError::Cdp(format!(
826                "navigate '{url}': {e} ({})",
827                self.intercept.summary()
828            ))
829        })?;
830        self.inner.wait_for_navigation().await.map_err(cdp)?;
831        self.invalidate();
832        Ok(())
833    }
834
835    pub async fn reload(&self) -> Result<()> {
836        self.admit(ActionKind::Reload, None, None, None).await?;
837        let _l = self.lane.lock().await;
838        self.inner.reload().await.map_err(cdp)?;
839        self.inner.wait_for_navigation().await.map_err(cdp)?;
840        self.invalidate();
841        Ok(())
842    }
843
844    pub async fn history(&self, delta: i32) -> Result<()> {
845        self.admit(
846            ActionKind::History,
847            None,
848            None,
849            Some(format!("delta={delta}")),
850        )
851        .await?;
852        let _l = self.lane.lock().await;
853        self.inner
854            .evaluate(format!("history.go({delta})"))
855            .await
856            .map_err(cdp)?;
857        tokio::time::sleep(Duration::from_millis(150)).await;
858        // Bounded: a traversal that fires no navigation event (bfcache, same-document entry)
859        // returns once the wait elapses; the page is then read as it is.
860        if let Ok(waited) =
861            tokio::time::timeout(HISTORY_NAVIGATION_WAIT, self.inner.wait_for_navigation()).await
862        {
863            waited.map_err(cdp)?;
864        }
865        self.invalidate();
866        Ok(())
867    }
868
869    pub async fn url(&self) -> String {
870        self.inner.url().await.ok().flatten().unwrap_or_default()
871    }
872
873    pub async fn title(&self) -> String {
874        self.inner
875            .get_title()
876            .await
877            .ok()
878            .flatten()
879            .unwrap_or_default()
880    }
881
882    /// Rendered text (`document.body.innerText`).
883    pub async fn text(&self) -> Result<String> {
884        self.eval_internal("document.body ? document.body.innerText : ''")
885            .await
886            .map(|v| v.as_str().unwrap_or_default().to_string())
887    }
888
889    /// Evaluate a JS expression and return its JSON value. Script can navigate and
890    /// act, so it is admitted like any other effect.
891    pub async fn eval(&self, expr: &str) -> Result<Value> {
892        self.admit(
893            ActionKind::Eval,
894            None,
895            None,
896            Some(expr.chars().take(2000).collect()),
897        )
898        .await?;
899        self.eval_internal(expr).await
900    }
901
902    /// Runtime-owned evaluation (observation, geometry); never user script.
903    async fn eval_internal(&self, expr: &str) -> Result<Value> {
904        let r = self.inner.evaluate(expr).await.map_err(cdp)?;
905        Ok(r.value().cloned().unwrap_or(Value::Null))
906    }
907
908    pub async fn set_viewport(&self, width: u32, height: u32, scale: f64) -> Result<()> {
909        use chromiumoxide::cdp::browser_protocol::emulation::SetDeviceMetricsOverrideParams;
910        self.inner
911            .execute(SetDeviceMetricsOverrideParams::new(
912                i64::from(width),
913                i64::from(height),
914                scale,
915                false,
916            ))
917            .await
918            .map_err(cdp)?;
919        Ok(())
920    }
921
922    // ---- design mode -----------------------------------------------------
923
924    /// Enable the element picker for the current document. It runs in a fresh isolated world
925    /// and reports through a `Runtime.addBinding` function bound only to that world, so page
926    /// script can neither see nor forge picker messages. Prompt submissions are delivered only
927    /// when one native input gesture (a pointer press or key down this page dispatched)
928    /// authorizes them; see [`DesignModeBridge`]. Call once per document; navigation ends the
929    /// picker and requires a new call with a new nonce.
930    pub async fn enable_design_mode(&self, nonce: &str) -> Result<DesignModeSession> {
931        let script = design_mode::build_design_mode_script(nonce)?;
932        let mut bridge = DesignModeBridge::new(nonce)?;
933        let frame_id = self
934            .inner
935            .mainframe()
936            .await
937            .map_err(cdp)?
938            .ok_or_else(|| BrowserError::Invalid("no main frame".into()))?;
939        let mut events = self
940            .inner
941            .event_listener::<EventBindingCalled>()
942            .await
943            .map_err(cdp)?;
944        let mut add = AddBindingParams::new(bridge.binding_name());
945        add.execution_context_name = Some(bridge.world_name());
946        self.inner.execute(add).await.map_err(cdp)?;
947        let mut world = CreateIsolatedWorldParams::new(frame_id);
948        world.world_name = Some(bridge.world_name());
949        world.grant_univeral_access = Some(false);
950        let context = self
951            .inner
952            .execute(world)
953            .await
954            .map_err(cdp)?
955            .result
956            .execution_context_id;
957        *self.design_context.lock().unwrap() = Some(context);
958        let eval = EvaluateParams::builder()
959            .expression(script)
960            .context_id(context)
961            .build()
962            .map_err(BrowserError::Invalid)?;
963        self.inner.execute(eval).await.map_err(cdp)?;
964        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
965        let gesture = self.design_gesture.clone();
966        let pump = tokio::spawn(async move {
967            while let Some(e) = events.next().await {
968                let marker = bridge.accept(
969                    &e.name,
970                    &e.payload,
971                    e.execution_context_id == context,
972                    &gesture,
973                    design_mode::now_ms(),
974                );
975                if let Some(marker) = marker {
976                    if tx.send(marker).is_err() {
977                        break;
978                    }
979                }
980            }
981        });
982        self.pumps.lock().unwrap().push(pump);
983        Ok(DesignModeSession { events: rx })
984    }
985
986    /// Show the outcome of a submission in the picker popup (`window.__omniOnDesignResult`
987    /// in the picker's isolated world).
988    pub async fn design_mode_result(&self, id: u64, ok: bool, message: &str) -> Result<()> {
989        let context = (*self.design_context.lock().unwrap())
990            .ok_or_else(|| BrowserError::Invalid("design mode is not enabled".into()))?;
991        let arg = serde_json::json!({"id": id, "ok": ok, "message": message});
992        let eval = EvaluateParams::builder()
993            .expression(format!(
994                "window.__omniOnDesignResult && window.__omniOnDesignResult({arg})"
995            ))
996            .context_id(context)
997            .build()
998            .map_err(BrowserError::Invalid)?;
999        self.inner.execute(eval).await.map_err(cdp)?;
1000        Ok(())
1001    }
1002
1003    // ---- observation -----------------------------------------------------
1004
1005    pub async fn observe(&self) -> Result<Observation> {
1006        let _l = self.lane.lock().await;
1007        let frame_id = self
1008            .inner
1009            .mainframe()
1010            .await
1011            .map_err(cdp)?
1012            .map(|f| f.as_ref().to_string())
1013            .unwrap_or_default();
1014        let ax = summarize_ax(&self.ax_tree(Some(OBSERVE_AX_DEPTH)).await?);
1015        let raw: Vec<RawNode> = self
1016            .inner
1017            .evaluate(OBSERVE_JS)
1018            .await
1019            .map_err(cdp)?
1020            .into_value()
1021            .map_err(|e| BrowserError::Cdp(format!("decode observation: {e}")))?;
1022        let viewport: Rect = self
1023            .inner
1024            .evaluate("({x:0,y:0,width:window.innerWidth,height:window.innerHeight})")
1025            .await
1026            .map_err(cdp)?
1027            .into_value()
1028            .map_err(cdp)?;
1029        let fingerprint = raw
1030            .iter()
1031            .map(|n| {
1032                format!(
1033                    "{}|{}|{}|{}|{}",
1034                    n.selector, n.role, n.name, n.visible, n.disabled
1035                )
1036            })
1037            .collect::<Vec<_>>()
1038            .join("\n");
1039        let (epoch, nodes, added, removed) = {
1040            let mut o = self.obs.lock().unwrap();
1041            if o.fingerprint != fingerprint {
1042                o.epoch += 1;
1043                o.fingerprint = fingerprint;
1044            }
1045            let epoch = o.epoch;
1046            o.refs.clear();
1047            let mut cur = HashMap::new();
1048            let mut cur_stable: HashMap<String, u64> = HashMap::new();
1049            let mut nodes = Vec::new();
1050            for (i, n) in raw.into_iter().enumerate() {
1051                let name = if n.sensitive {
1052                    "••••••••".to_string()
1053                } else {
1054                    n.name.clone()
1055                };
1056                let node_ref = format!("r{epoch}.{}", i + 1);
1057                let stable_id = if n.selector.is_empty() {
1058                    0
1059                } else {
1060                    let existing = o.stable.get(&n.selector).copied();
1061                    let id = match existing {
1062                        Some(id) => id,
1063                        None => {
1064                            o.next_stable += 1;
1065                            o.next_stable
1066                        }
1067                    };
1068                    cur_stable.insert(n.selector.clone(), id);
1069                    id
1070                };
1071                if !n.selector.is_empty() {
1072                    o.refs.insert(
1073                        node_ref.clone(),
1074                        RefEntry {
1075                            selector: n.selector.clone(),
1076                            tag: n.tag.clone(),
1077                            role: n.role.clone(),
1078                            name: name.clone(),
1079                        },
1080                    );
1081                    cur.insert(n.selector.clone(), format!("{}|{}", n.role, name));
1082                }
1083                nodes.push(ObservedNode {
1084                    node_ref,
1085                    role: n.role,
1086                    name,
1087                    tag: n.tag,
1088                    selector: n.selector,
1089                    visible: n.visible,
1090                    disabled: n.disabled,
1091                    sensitive: n.sensitive,
1092                    frame_id: frame_id.clone(),
1093                    stable_id,
1094                    bounds: n.bounds,
1095                });
1096            }
1097            o.stable = cur_stable;
1098            let added = cur
1099                .keys()
1100                .filter(|k| !o.previous.contains_key(*k))
1101                .cloned()
1102                .collect();
1103            let removed = o
1104                .previous
1105                .keys()
1106                .filter(|k| !cur.contains_key(*k))
1107                .cloned()
1108                .collect();
1109            o.previous = cur;
1110            (epoch, nodes, added, removed)
1111        };
1112        let console_errors = self
1113            .console
1114            .lock()
1115            .await
1116            .iter()
1117            .filter(|l| matches!(l.level.as_str(), "error" | "exception"))
1118            .count();
1119        Ok(Observation {
1120            page_id: self.id.clone(),
1121            epoch,
1122            url: self.url().await,
1123            title: self.title().await,
1124            viewport,
1125            nodes,
1126            ax,
1127            console_errors,
1128            added,
1129            removed,
1130        })
1131    }
1132
1133    /// Resolve a target to a unique CSS selector, rejecting stale refs.
1134    async fn resolve(&self, target: &Target) -> Result<Option<String>> {
1135        match target {
1136            Target::Point(..) => Ok(None),
1137            Target::Selector(s) => {
1138                self.unique(s).await?;
1139                Ok(Some(s.clone()))
1140            }
1141            Target::Ref(r) => {
1142                let (entry, current_epoch) = {
1143                    let o = self.obs.lock().unwrap();
1144                    (o.refs.get(r).cloned(), o.epoch)
1145                };
1146                let entry = entry.ok_or_else(|| BrowserError::StaleRef(r.clone()))?;
1147                let ref_epoch: u64 = r
1148                    .trim_start_matches('r')
1149                    .split('.')
1150                    .next()
1151                    .and_then(|e| e.parse().ok())
1152                    .unwrap_or(0);
1153                if ref_epoch != current_epoch {
1154                    return Err(BrowserError::StaleRef(r.clone()));
1155                }
1156                // Identity check: the element behind the selector must still look
1157                // like what was observed, else the page changed under the ref.
1158                let sig = self
1159                    .eval(&format!(
1160                        "(()=>{{const l=document.querySelectorAll({s});if(l.length!==1)return null;const e=l[0];\
1161                         return {{tag:e.tagName.toLowerCase(),name:(e.getAttribute('aria-label')||e.innerText||e.value||e.getAttribute('placeholder')||'').trim().slice(0,160)}}}})()",
1162                        s = js(&entry.selector)
1163                    ))
1164                    .await?;
1165                let ok = sig.get("tag").and_then(Value::as_str) == Some(entry.tag.as_str())
1166                    && sig.get("name").and_then(Value::as_str) == Some(entry.name.as_str())
1167                    || (sig.get("tag").and_then(Value::as_str) == Some(entry.tag.as_str())
1168                        && matches!(entry.tag.as_str(), "input" | "textarea" | "select")); // value changes as the user types
1169                if !ok {
1170                    return Err(BrowserError::StaleRef(r.clone()));
1171                }
1172                let _ = &entry.role;
1173                Ok(Some(entry.selector))
1174            }
1175        }
1176    }
1177
1178    async fn unique(&self, selector: &str) -> Result<()> {
1179        let n = self
1180            .eval_internal(&format!(
1181                "document.querySelectorAll({}).length",
1182                js(selector)
1183            ))
1184            .await?
1185            .as_u64()
1186            .unwrap_or(0);
1187        match n {
1188            1 => Ok(()),
1189            0 => Err(BrowserError::NoElement(selector.into())),
1190            n => Err(BrowserError::Ambiguous(selector.into(), n)),
1191        }
1192    }
1193
1194    /// Scroll into view, return the centre point, and verify nothing covers it.
1195    async fn point_of(&self, target: &Target) -> Result<(f64, f64)> {
1196        if let Target::Point(x, y) = target {
1197            return Ok((*x, *y));
1198        }
1199        let sel = self.resolve(target).await?.expect("selector");
1200        let v = self
1201            .eval(&format!(
1202                "(()=>{{const e=document.querySelector({s});e.scrollIntoView({{block:'center',inline:'center'}});\
1203                 const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return null;\
1204                 const x=r.x+r.width/2,y=r.y+r.height/2;const t=document.elementFromPoint(x,y);\
1205                 const hit=!!t&&(t===e||e.contains(t)||t.contains(e));return {{x,y,hit}}}})()",
1206                s = js(&sel)
1207            ))
1208            .await?;
1209        if v.is_null() {
1210            return Err(BrowserError::NotInteractable(sel));
1211        }
1212        if v.get("hit").and_then(Value::as_bool) != Some(true) {
1213            return Err(BrowserError::NotInteractable(format!(
1214                "{sel} (covered by another element)"
1215            )));
1216        }
1217        Ok((
1218            v["x"].as_f64().unwrap_or(0.0),
1219            v["y"].as_f64().unwrap_or(0.0),
1220        ))
1221    }
1222
1223    // ---- real pointer input ----------------------------------------------
1224
1225    async fn mouse_event(
1226        &self,
1227        kind: DispatchMouseEventType,
1228        x: f64,
1229        y: f64,
1230        button: MouseButton,
1231        click_count: i64,
1232    ) -> Result<()> {
1233        if matches!(kind, DispatchMouseEventType::MousePressed) {
1234            self.design_gesture.stamp();
1235        }
1236        let mut p = DispatchMouseEventParams::new(kind.clone(), x, y);
1237        p.button = Some(button);
1238        p.click_count = Some(click_count);
1239        p.buttons = Some(match kind {
1240            DispatchMouseEventType::MousePressed => 1,
1241            DispatchMouseEventType::MouseReleased => 0,
1242            _ => *self.buttons.lock().unwrap(),
1243        });
1244        self.inner.execute(p).await.map_err(cdp)?;
1245        *self.mouse.lock().unwrap() = (x, y);
1246        Ok(())
1247    }
1248
1249    async fn move_to(&self, x: f64, y: f64) -> Result<()> {
1250        self.mouse_event(
1251            DispatchMouseEventType::MouseMoved,
1252            x,
1253            y,
1254            MouseButton::None,
1255            0,
1256        )
1257        .await
1258    }
1259
1260    pub async fn hover(&self, target: &Target) -> Result<()> {
1261        self.admit(ActionKind::Hover, None, Some(describe(target)), None)
1262            .await?;
1263        let _l = self.lane.lock().await;
1264        let (x, y) = self.point_of(target).await?;
1265        self.move_to(x, y).await
1266    }
1267
1268    pub async fn click(&self, target: &Target) -> Result<()> {
1269        self.admit(ActionKind::Click, None, Some(describe(target)), None)
1270            .await?;
1271        let _l = self.lane.lock().await;
1272        self.click_n(target, 1).await
1273    }
1274
1275    pub async fn double_click(&self, target: &Target) -> Result<()> {
1276        self.admit(ActionKind::DoubleClick, None, Some(describe(target)), None)
1277            .await?;
1278        let _l = self.lane.lock().await;
1279        self.click_n(target, 2).await
1280    }
1281
1282    /// Caller holds the lane.
1283    async fn click_n(&self, target: &Target, count: i64) -> Result<()> {
1284        let (x, y) = self.point_of(target).await?;
1285        self.move_to(x, y).await?;
1286        for n in 1..=count {
1287            self.mouse_event(
1288                DispatchMouseEventType::MousePressed,
1289                x,
1290                y,
1291                MouseButton::Left,
1292                n,
1293            )
1294            .await?;
1295            self.mouse_event(
1296                DispatchMouseEventType::MouseReleased,
1297                x,
1298                y,
1299                MouseButton::Left,
1300                n,
1301            )
1302            .await?;
1303        }
1304        Ok(())
1305    }
1306
1307    /// Press at `from`, move in `steps` increments, release at `to`.
1308    pub async fn drag(&self, from: &Target, to: &Target, steps: u32) -> Result<()> {
1309        self.admit(
1310            ActionKind::Drag,
1311            None,
1312            Some(format!("{} -> {}", describe(from), describe(to))),
1313            None,
1314        )
1315        .await?;
1316        let _l = self.lane.lock().await;
1317        let (x0, y0) = self.point_of(from).await?;
1318        let (x1, y1) = self.point_of(to).await?;
1319        self.move_to(x0, y0).await?;
1320        self.mouse_event(
1321            DispatchMouseEventType::MousePressed,
1322            x0,
1323            y0,
1324            MouseButton::Left,
1325            1,
1326        )
1327        .await?;
1328        *self.buttons.lock().unwrap() = 1;
1329        let steps = steps.max(1);
1330        for i in 1..=steps {
1331            let t = f64::from(i) / f64::from(steps);
1332            self.mouse_event(
1333                DispatchMouseEventType::MouseMoved,
1334                x0 + (x1 - x0) * t,
1335                y0 + (y1 - y0) * t,
1336                MouseButton::Left,
1337                0,
1338            )
1339            .await?;
1340        }
1341        *self.buttons.lock().unwrap() = 0;
1342        self.mouse_event(
1343            DispatchMouseEventType::MouseReleased,
1344            x1,
1345            y1,
1346            MouseButton::Left,
1347            1,
1348        )
1349        .await
1350    }
1351
1352    /// Mouse-wheel scroll at the target (or viewport centre when `None`).
1353    pub async fn wheel(&self, at: Option<&Target>, dx: f64, dy: f64) -> Result<()> {
1354        self.admit(
1355            ActionKind::Wheel,
1356            None,
1357            at.map(describe),
1358            Some(format!("dx={dx} dy={dy}")),
1359        )
1360        .await?;
1361        let _l = self.lane.lock().await;
1362        let (x, y) = match at {
1363            Some(t) => self.point_of(t).await?,
1364            None => {
1365                let v = self
1366                    .eval_internal("({x:innerWidth/2,y:innerHeight/2})")
1367                    .await?;
1368                (
1369                    v["x"].as_f64().unwrap_or(100.0),
1370                    v["y"].as_f64().unwrap_or(100.0),
1371                )
1372            }
1373        };
1374        let mut p = DispatchMouseEventParams::new(DispatchMouseEventType::MouseWheel, x, y);
1375        p.delta_x = Some(dx);
1376        p.delta_y = Some(dy);
1377        self.inner.execute(p).await.map_err(cdp)?;
1378        Ok(())
1379    }
1380
1381    /// Programmatic scroll (`scrollBy`) of the element at `target`, or of the window when
1382    /// `None`. Use it where a wheel event at the element's centre is wrong: a covered element,
1383    /// or one that is not scrollable under the pointer. Selectors and refs must resolve to one
1384    /// element; a point scrolls the element under it. No element at a point is an error.
1385    pub async fn scroll_by(&self, target: Option<&Target>, dx: f64, dy: f64) -> Result<()> {
1386        if !dx.is_finite() || !dy.is_finite() {
1387            return Err(BrowserError::Invalid(format!(
1388                "scroll offsets must be finite, got dx={dx} dy={dy}"
1389            )));
1390        }
1391        self.admit(
1392            ActionKind::Wheel,
1393            None,
1394            target.map(describe),
1395            Some(format!("scroll_by dx={dx} dy={dy}")),
1396        )
1397        .await?;
1398        let _l = self.lane.lock().await;
1399        let offset = format!("{{left:{dx},top:{dy}}}");
1400        let found = match target {
1401            None => {
1402                self.eval_internal(&format!(
1403                    "(()=>{{window.scrollBy({offset});return true}})()"
1404                ))
1405                .await?
1406            }
1407            Some(Target::Point(x, y)) => {
1408                if !x.is_finite() || !y.is_finite() {
1409                    return Err(BrowserError::Invalid(format!(
1410                        "scroll point must be finite, got {x},{y}"
1411                    )));
1412                }
1413                self.eval_internal(&format!(
1414                    "(()=>{{const e=document.elementFromPoint({x},{y});if(!e)return false;e.scrollBy({offset});return true}})()"
1415                ))
1416                .await?
1417            }
1418            Some(t) => {
1419                let sel = self.resolve(t).await?.expect("selector");
1420                self.eval_internal(&format!(
1421                    "(()=>{{const e=document.querySelector({});if(!e)return false;e.scrollBy({offset});return true}})()",
1422                    js(&sel)
1423                ))
1424                .await?
1425            }
1426        };
1427        if found.as_bool() != Some(true) {
1428            return Err(BrowserError::NoElement(
1429                target.map(describe).unwrap_or_default(),
1430            ));
1431        }
1432        Ok(())
1433    }
1434
1435    // ---- real keyboard input ---------------------------------------------
1436
1437    async fn key_event(
1438        &self,
1439        kind: DispatchKeyEventType,
1440        d: &KeyDef,
1441        mods: i64,
1442        with_text: bool,
1443    ) -> Result<()> {
1444        if matches!(
1445            kind,
1446            DispatchKeyEventType::KeyDown | DispatchKeyEventType::RawKeyDown
1447        ) {
1448            self.design_gesture.stamp();
1449        }
1450        let mut p = DispatchKeyEventParams::new(kind);
1451        p.modifiers = Some(mods);
1452        p.key = Some(d.key.clone());
1453        if !d.code.is_empty() {
1454            p.code = Some(d.code.clone());
1455        }
1456        p.windows_virtual_key_code = Some(d.vk);
1457        p.native_virtual_key_code = Some(d.vk);
1458        if with_text {
1459            p.text = d.text.clone();
1460            p.unmodified_text = d.text.clone();
1461        }
1462        self.inner.execute(p).await.map_err(cdp)?;
1463        Ok(())
1464    }
1465
1466    async fn press_locked(&self, spec: &str) -> Result<()> {
1467        let (mods, mod_keys, def) = keys::parse_chord(spec)?;
1468        for (_, m) in &mod_keys {
1469            self.key_event(DispatchKeyEventType::RawKeyDown, m, mods, false)
1470                .await?;
1471        }
1472        // Shortcut chords (Ctrl/Meta/Alt) carry no text.
1473        let text = mods & (keys::CTRL | keys::META | keys::ALT) == 0;
1474        let kind = if text && def.text.is_some() {
1475            DispatchKeyEventType::KeyDown
1476        } else {
1477            DispatchKeyEventType::RawKeyDown
1478        };
1479        self.key_event(kind, &def, mods, text).await?;
1480        self.key_event(DispatchKeyEventType::KeyUp, &def, mods, false)
1481            .await?;
1482        for (_, m) in mod_keys.iter().rev() {
1483            self.key_event(DispatchKeyEventType::KeyUp, m, 0, false)
1484                .await?;
1485        }
1486        Ok(())
1487    }
1488
1489    /// Press a key or chord (`Enter`, `Tab`, `Control+a`) on the focused element.
1490    pub async fn press(&self, spec: &str) -> Result<()> {
1491        self.admit(ActionKind::Press, None, Some(spec.to_string()), None)
1492            .await?;
1493        let _l = self.lane.lock().await;
1494        self.press_locked(spec).await
1495    }
1496
1497    /// Type text one key event at a time into the focused element.
1498    pub async fn type_text(&self, text: &str) -> Result<()> {
1499        self.admit(
1500            ActionKind::TypeText,
1501            None,
1502            None,
1503            Some(format!("chars={}", text.chars().count())),
1504        )
1505        .await?;
1506        let _l = self.lane.lock().await;
1507        self.type_locked(text).await
1508    }
1509
1510    async fn type_locked(&self, text: &str) -> Result<()> {
1511        for c in text.chars() {
1512            let d = keys::char_key(c);
1513            self.key_event(DispatchKeyEventType::KeyDown, &d, 0, true)
1514                .await?;
1515            self.key_event(DispatchKeyEventType::KeyUp, &d, 0, false)
1516                .await?;
1517        }
1518        Ok(())
1519    }
1520
1521    /// Click the target to focus it, then type.
1522    pub async fn fill(&self, target: &Target, text: &str, clear: bool) -> Result<()> {
1523        self.admit(
1524            ActionKind::Fill,
1525            None,
1526            Some(describe(target)),
1527            Some(format!("chars={} clear={clear}", text.chars().count())),
1528        )
1529        .await?;
1530        let _l = self.lane.lock().await;
1531        self.click_n(target, 1).await?;
1532        if clear {
1533            let sel_all = if cfg!(target_os = "macos") {
1534                "Meta+a"
1535            } else {
1536                "Control+a"
1537            };
1538            self.press_locked(sel_all).await?;
1539            self.press_locked("Backspace").await?;
1540        }
1541        self.type_locked(text).await
1542    }
1543
1544    // ---- other actions -----------------------------------------------------
1545
1546    /// Choose a `<select>` option by value/label. Native popups cannot be driven
1547    /// over CDP, so this sets the value and fires `input`/`change` (documented gap).
1548    pub async fn select_option(&self, target: &Target, value: &str) -> Result<()> {
1549        self.admit(
1550            ActionKind::Select,
1551            None,
1552            Some(describe(target)),
1553            Some(format!("value={value}")),
1554        )
1555        .await?;
1556        let _l = self.lane.lock().await;
1557        let sel = self
1558            .resolve(target)
1559            .await?
1560            .ok_or_else(|| BrowserError::Invalid("select needs an element".into()))?;
1561        let r = self
1562            .eval(&format!(
1563                "(()=>{{const e=document.querySelector({s});const w={v};\
1564                 const o=[...e.options].find(o=>o.value===w||o.label===w||o.text.trim()===w);if(!o)return 'nooption';\
1565                 e.value=o.value;e.dispatchEvent(new Event('input',{{bubbles:true}}));e.dispatchEvent(new Event('change',{{bubbles:true}}));return 'ok'}})()",
1566                s = js(&sel),
1567                v = js(value)
1568            ))
1569            .await?;
1570        if r.as_str() == Some("ok") {
1571            Ok(())
1572        } else {
1573            Err(BrowserError::Invalid(format!(
1574                "'{sel}' has no option '{value}'"
1575            )))
1576        }
1577    }
1578
1579    pub async fn upload(&self, target: &Target, file: &Path) -> Result<()> {
1580        self.admit(
1581            ActionKind::Upload,
1582            None,
1583            Some(describe(target)),
1584            Some(file.display().to_string()),
1585        )
1586        .await?;
1587        let _l = self.lane.lock().await;
1588        let file = file.canonicalize()?;
1589        if !file.is_file() {
1590            return Err(BrowserError::Invalid(
1591                "upload must be a regular file".into(),
1592            ));
1593        }
1594        if let Some(root) = &self.upload_root {
1595            if !file.starts_with(root.canonicalize()?) {
1596                return Err(BrowserError::Invalid(
1597                    "upload outside the configured upload root".into(),
1598                ));
1599            }
1600        }
1601        if std::fs::metadata(&file)?.len() > MAX_UPLOAD_BYTES {
1602            return Err(BrowserError::Invalid("upload exceeds 64 MiB".into()));
1603        }
1604        let sel = self
1605            .resolve(target)
1606            .await?
1607            .ok_or_else(|| BrowserError::Invalid("upload needs an element".into()))?;
1608        let el = self
1609            .inner
1610            .find_element(sel.as_str())
1611            .await
1612            .map_err(|_| BrowserError::NoElement(sel.clone()))?;
1613        let node = el.description().await.map_err(cdp)?;
1614        self.inner
1615            .execute(
1616                SetFileInputFilesParams::builder()
1617                    .file(file.to_string_lossy().to_string())
1618                    .backend_node_id(node.backend_node_id)
1619                    .build()
1620                    .map_err(BrowserError::Invalid)?,
1621            )
1622            .await
1623            .map_err(cdp)?;
1624        Ok(())
1625    }
1626
1627    pub async fn wait_for(&self, selector: &str, timeout: Duration) -> Result<()> {
1628        self.wait_eval(
1629            &format!("!!document.querySelector({})", js(selector)),
1630            timeout,
1631        )
1632        .await
1633    }
1634
1635    /// Poll a JS expression until truthy.
1636    pub async fn wait_eval(&self, expr: &str, timeout: Duration) -> Result<()> {
1637        self.admit(
1638            ActionKind::Eval,
1639            None,
1640            None,
1641            Some(expr.chars().take(2000).collect()),
1642        )
1643        .await?;
1644        let deadline = Instant::now() + timeout;
1645        loop {
1646            let v = self.eval_internal(expr).await?;
1647            if v.as_bool()
1648                .unwrap_or(!v.is_null() && v != Value::Bool(false))
1649            {
1650                return Ok(());
1651            }
1652            if Instant::now() >= deadline {
1653                return Err(BrowserError::Timeout(expr.to_string()));
1654            }
1655            tokio::time::sleep(Duration::from_millis(50)).await;
1656        }
1657    }
1658
1659    pub async fn screenshot(&self) -> Result<Vec<u8>> {
1660        self.screenshot_with(ScreenshotOptions::default()).await
1661    }
1662
1663    /// PNG screenshot of the viewport with options; `ScreenshotOptions::default()` matches
1664    /// [`BrowserPage::screenshot`].
1665    pub async fn screenshot_with(&self, options: ScreenshotOptions) -> Result<Vec<u8>> {
1666        let params = self.screenshot_params(&options).await?;
1667        self.inner.screenshot(params).await.map_err(cdp)
1668    }
1669
1670    /// Build the CDP capture request for `options`. A scale without a clip captures the visual
1671    /// viewport (`Page.getLayoutMetrics`) at that scale, so the output is `scale` times its CSS size.
1672    async fn screenshot_params(&self, options: &ScreenshotOptions) -> Result<ScreenshotParams> {
1673        let mut params_builder = CaptureScreenshotParams::builder();
1674        match options.format {
1675            ScreenshotFormat::Png => {
1676                params_builder = params_builder.format(CaptureScreenshotFormat::Png);
1677            }
1678            ScreenshotFormat::Jpeg { quality } => {
1679                if !(1..=100).contains(&quality) {
1680                    return Err(BrowserError::Invalid(
1681                        "JPEG screenshot quality must be 1 to 100".into(),
1682                    ));
1683                }
1684                if options.omit_background {
1685                    return Err(BrowserError::Invalid(
1686                        "omit_background needs a PNG screenshot".into(),
1687                    ));
1688                }
1689                params_builder = params_builder
1690                    .format(CaptureScreenshotFormat::Jpeg)
1691                    .quality(i64::from(quality));
1692            }
1693        }
1694        let scale = match options.scale {
1695            None => None,
1696            Some(s) if s.is_finite() && s > 0.0 => Some(s),
1697            Some(_) => {
1698                return Err(BrowserError::Invalid(
1699                    "screenshot scale must be positive and finite".into(),
1700                ))
1701            }
1702        };
1703        if let Some(region) = &options.clip {
1704            region.validate()?;
1705        }
1706        let clip = match (options.clip, scale) {
1707            (None, None) => None,
1708            (region, scale) => {
1709                let (x, y, width, height) = match region {
1710                    Some(r) => (r.x, r.y, r.width, r.height),
1711                    None => {
1712                        let metrics = self.inner.layout_metrics().await.map_err(cdp)?;
1713                        let v = metrics.css_visual_viewport;
1714                        (v.page_x, v.page_y, v.client_width, v.client_height)
1715                    }
1716                };
1717                Some(Viewport {
1718                    x,
1719                    y,
1720                    width,
1721                    height,
1722                    scale: scale.unwrap_or(1.0),
1723                })
1724            }
1725        };
1726        if let Some(clip) = clip {
1727            params_builder = params_builder.clip(clip);
1728        }
1729        Ok(ScreenshotParams {
1730            cdp_params: params_builder.build(),
1731            full_page: None,
1732            omit_background: Some(options.omit_background),
1733        })
1734    }
1735
1736    pub async fn screenshot_to(&self, path: &Path) -> Result<()> {
1737        std::fs::write(path, self.screenshot().await?)?;
1738        Ok(())
1739    }
1740
1741    pub async fn console(&self) -> Vec<ConsoleLine> {
1742        self.console.lock().await.clone()
1743    }
1744
1745    pub async fn clear_console(&self) {
1746        self.console.lock().await.clear();
1747    }
1748}
1749
1750/// Register the `Fetch.requestPaused` listener, then enable `Fetch` for every URL, in that
1751/// order so no request is paused without a listener. One short task per request: the network
1752/// policy first (its refusal is final), then the caller's hook when one is installed.
1753async fn start_intercept_pump(
1754    inner: &Page,
1755    page_id: &str,
1756    guard: &Arc<Guard>,
1757    sink: Arc<StdMutex<Vec<BlockedRequest>>>,
1758    stats: Arc<InterceptStats>,
1759    hook_slot: Arc<StdMutex<Option<RequestInterceptor>>>,
1760) -> Result<JoinHandle<()>> {
1761    let mut paused = inner
1762        .event_listener::<EventRequestPaused>()
1763        .await
1764        .map_err(cdp)?;
1765    let page = inner.clone();
1766    let g = guard.clone();
1767    let page_id = page_id.to_string();
1768    let pump = tokio::spawn(async move {
1769        use std::sync::atomic::Ordering::Relaxed;
1770        while let Some(e) = paused.next().await {
1771            let stats = stats.clone();
1772            stats.paused.fetch_add(1, Relaxed);
1773            let page = page.clone();
1774            let g = g.clone();
1775            let sink = sink.clone();
1776            let pid = page_id.clone();
1777            let hook_slot = hook_slot.clone();
1778            tokio::spawn(async move {
1779                let kind = format!("{:?}", e.resource_type);
1780                match g.check_request(&e.request.url, &kind).await {
1781                    Ok(()) => {
1782                        let hook = hook_slot.lock().unwrap().clone();
1783                        let decision = match hook {
1784                            None => InterceptDecision::Continue,
1785                            Some(hook) => {
1786                                match serde_json::to_value(&*e)
1787                                    .ok()
1788                                    .and_then(|v| InterceptedRequest::from_cdp_value(&v))
1789                                {
1790                                    Some(request) => {
1791                                        run_interceptor(&hook, request, INTERCEPTOR_TIMEOUT).await
1792                                    }
1793                                    None => InterceptDecision::Fail(InterceptFailure::Failed),
1794                                }
1795                            }
1796                        };
1797                        let hook_failed = matches!(decision, InterceptDecision::Fail(_));
1798                        let (counter, result) = match command_for(e.request_id.clone(), decision) {
1799                            PausedCommand::Continue(p) => {
1800                                (&stats.continued, page.execute(p).await.map(|_| ()))
1801                            }
1802                            PausedCommand::Fulfill(p) => {
1803                                (&stats.fulfilled, page.execute(p).await.map(|_| ()))
1804                            }
1805                            PausedCommand::Fail(p) => {
1806                                (&stats.refused, page.execute(p).await.map(|_| ()))
1807                            }
1808                        };
1809                        match result {
1810                            Ok(()) => {
1811                                counter.fetch_add(1, Relaxed);
1812                                if hook_failed {
1813                                    let mut b = sink.lock().unwrap();
1814                                    if b.len() < 500 {
1815                                        b.push(BlockedRequest {
1816                                            url: e.request.url.clone(),
1817                                            reason: "failed by the request interceptor".into(),
1818                                        });
1819                                    }
1820                                }
1821                            }
1822                            Err(error) => {
1823                                stats.errors.fetch_add(1, Relaxed);
1824                                *stats.last_error.lock().unwrap() = Some(error.to_string());
1825                            }
1826                        }
1827                    }
1828                    Err(reason) => {
1829                        let _ = page
1830                            .execute(FailRequestParams::new(
1831                                e.request_id.clone(),
1832                                ErrorReason::BlockedByClient,
1833                            ))
1834                            .await;
1835                        stats.refused.fetch_add(1, Relaxed);
1836                        g.denied_network(Some(&pid), &kind, &reason);
1837                        let mut b = sink.lock().unwrap();
1838                        if b.len() < 500 {
1839                            b.push(BlockedRequest {
1840                                url: e.request.url.clone(),
1841                                reason: reason.to_string(),
1842                            });
1843                        }
1844                    }
1845                }
1846            });
1847        }
1848    });
1849    let en = FetchEnableParams {
1850        patterns: Some(vec![RequestPattern {
1851            url_pattern: Some("*".into()),
1852            resource_type: None,
1853            request_stage: None,
1854        }]),
1855        ..Default::default()
1856    };
1857    if let Err(e) = inner.execute(en).await {
1858        pump.abort();
1859        return Err(cdp(e));
1860    }
1861    Ok(pump)
1862}
1863
1864async fn push_capped(sink: &Arc<Mutex<Vec<ConsoleLine>>>, line: ConsoleLine) {
1865    let mut g = sink.lock().await;
1866    if g.len() >= MAX_CONSOLE_LINES {
1867        g.remove(0);
1868    }
1869    g.push(line);
1870}
1871
1872fn describe(t: &Target) -> String {
1873    match t {
1874        Target::Ref(r) => format!("ref:{r}"),
1875        Target::Selector(s) => format!("css:{s}"),
1876        Target::Point(x, y) => format!("point:{x},{y}"),
1877    }
1878}
1879
1880fn js(s: &str) -> String {
1881    serde_json::to_string(s).unwrap_or_else(|_| "\"\"".into())
1882}
1883
1884const OBSERVE_JS: &str = r#"(() => {
1885  const esc = globalThis.CSS?.escape || (v => String(v).replace(/[^a-zA-Z0-9_-]/g, '\\$&'));
1886  const unique = c => { if (!c) return null; try { return document.querySelectorAll(c).length === 1 ? c : null; } catch (_) { return null; } };
1887  const selectorFor = el => {
1888    if (el.id) { const s = unique('#' + esc(el.id)); if (s) return s; }
1889    for (const a of ['data-testid', 'name', 'aria-label']) {
1890      const v = el.getAttribute(a);
1891      if (v) { const s = unique(el.tagName.toLowerCase() + '[' + a + '="' + esc(v) + '"]'); if (s) return s; }
1892    }
1893    const parts = [];
1894    for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
1895      let p = n.tagName.toLowerCase();
1896      const sib = n.parentElement ? [...n.parentElement.children].filter(x => x.tagName === n.tagName) : [];
1897      if (sib.length > 1) p += ':nth-of-type(' + (sib.indexOf(n) + 1) + ')';
1898      parts.unshift(p);
1899      const c = parts.join(' > ');
1900      if (unique(c)) return c;
1901    }
1902    return '';
1903  };
1904  const sel = 'a[href],button,input,select,textarea,[role],[tabindex],[contenteditable="true"],[onclick]';
1905  return [...document.querySelectorAll(sel)].slice(0, 300).map(el => {
1906    const r = el.getBoundingClientRect();
1907    const ac = (el.getAttribute('autocomplete') || '').trim().toLowerCase();
1908    const sensitive = (el instanceof HTMLInputElement && el.type.toLowerCase() === 'password') || ac === 'current-password' || ac === 'new-password';
1909    const visible = (() => {
1910      for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
1911        const s = getComputedStyle(n);
1912        if (n.hidden || n.getAttribute('aria-hidden') === 'true' || s.visibility === 'hidden' || s.display === 'none' || s.opacity === '0') return false;
1913      }
1914      return r.width > 0 && r.height > 0;
1915    })();
1916    return {
1917      role: el.getAttribute('role') || ({A:'link',BUTTON:'button',INPUT:'textbox',SELECT:'combobox',TEXTAREA:'textbox'}[el.tagName] || el.tagName.toLowerCase()),
1918      name: (el.getAttribute('aria-label') || el.innerText || el.value || el.getAttribute('placeholder') || '').trim().slice(0, 160),
1919      tag: el.tagName.toLowerCase(), selector: selectorFor(el), visible,
1920      disabled: !!el.disabled || el.getAttribute('aria-disabled') === 'true', sensitive,
1921      bounds: {x: r.x, y: r.y, width: r.width, height: r.height}
1922    };
1923  });
1924})()"#;