Skip to main content

rightkit_browser/
design_mode.rs

1//! Design-mode element-picker primitives: a trusted binding bridge with one-shot submit
2//! authentication, device-pixel capture geometry, and the picker script builder.
3//!
4//! The picker runs in an isolated world that [`BrowserPage::enable_design_mode`](crate::BrowserPage::enable_design_mode)
5//! creates. Page script cannot read that world, and the picker reports through a
6//! `Runtime.addBinding` function bound only to it, so page code can neither observe nor forge
7//! messages (console output is never trusted). A prompt submission becomes an automatic agent
8//! message only when it carries the enable nonce, comes from the isolated context, has an id
9//! above every earlier accepted submission, and consumes one native input gesture
10//! ([`NativeGestureLatch`]); one gesture authorizes exactly one submission.
11
12use crate::error::{BrowserError, Result};
13use serde::{Deserialize, Serialize};
14use serde_json::Value;
15use std::sync::Mutex;
16use std::time::Instant;
17
18/// How long after a native input event a prompt submission is still accepted.
19pub const DESIGN_MODE_GESTURE_WINDOW_MS: u64 = 1_500;
20
21/// The picker script template (see `design_mode_picker.js`); the binding and nonce tokens are
22/// replaced by [`build_design_mode_script`].
23const PICKER_TEMPLATE: &str = include_str!("design_mode_picker.js");
24
25/// Monotonic milliseconds, never zero (zero means "no gesture").
26pub fn now_ms() -> u64 {
27    static BASE: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
28    BASE.get_or_init(Instant::now).elapsed().as_millis() as u64 + 1
29}
30
31/// One-shot record of the latest native input gesture.
32#[derive(Debug, Default)]
33pub struct NativeGestureLatch(Mutex<u64>);
34
35impl NativeGestureLatch {
36    pub fn new() -> Self {
37        Self::default()
38    }
39
40    /// Record a native gesture at `now_ms`.
41    pub fn stamp_at(&self, now_ms: u64) {
42        *self.0.lock().unwrap() = now_ms;
43    }
44
45    pub fn stamp(&self) {
46        self.stamp_at(now_ms());
47    }
48
49    /// Consume the gesture: true once if one is recent at `now_ms`; the stamp is cleared either way.
50    pub fn take(&self, now_ms: u64) -> bool {
51        let mut at = self.0.lock().unwrap();
52        let recent = gesture_is_recent(*at, now_ms);
53        *at = 0;
54        recent
55    }
56}
57
58#[derive(Debug, Clone, PartialEq)]
59pub enum DesignModeMarker {
60    ElementSelected(Value),
61    PromptSubmitted(Value),
62    Dismissed,
63}
64
65/// Receiver of picker messages for one enable operation.
66pub struct DesignModeSession {
67    pub events: tokio::sync::mpsc::UnboundedReceiver<DesignModeMarker>,
68}
69
70/// Validates picker binding calls for one enable operation.
71#[derive(Debug, Clone)]
72pub struct DesignModeBridge {
73    nonce: String,
74    last_submit_id: u64,
75}
76
77fn check_nonce(nonce: &str) -> Result<()> {
78    if nonce.is_empty() || !nonce.chars().all(|c| c.is_ascii_alphanumeric()) {
79        return Err(BrowserError::Invalid(
80            "design-mode nonce must be non-empty ASCII alphanumeric".into(),
81        ));
82    }
83    Ok(())
84}
85
86/// Name of the `Runtime.addBinding` function for `nonce`.
87pub fn binding_name_for_nonce(nonce: &str) -> String {
88    format!("__omni_{nonce}_bridge__")
89}
90
91/// Name of the isolated world (and binding context) for `nonce`.
92pub fn world_name_for_nonce(nonce: &str) -> String {
93    format!("__omni_{nonce}_world__")
94}
95
96impl DesignModeBridge {
97    pub fn new(nonce: &str) -> Result<Self> {
98        check_nonce(nonce)?;
99        Ok(Self {
100            nonce: nonce.to_string(),
101            last_submit_id: 0,
102        })
103    }
104
105    pub fn binding_name(&self) -> String {
106        binding_name_for_nonce(&self.nonce)
107    }
108
109    pub fn world_name(&self) -> String {
110        world_name_for_nonce(&self.nonce)
111    }
112
113    /// Decode one `Runtime.bindingCalled` event. `trusted_context` is true only when the call
114    /// came from the isolated context this bridge created. Select and dismiss need the
115    /// binding, context and nonce; a submission also needs a fresh id and consumes one gesture
116    /// from `gesture`. A rejected submission does not advance the id or burn a later gesture.
117    pub fn accept(
118        &mut self,
119        binding: &str,
120        payload: &str,
121        trusted_context: bool,
122        gesture: &NativeGestureLatch,
123        now_ms: u64,
124    ) -> Option<DesignModeMarker> {
125        if !trusted_context || binding != self.binding_name() {
126            return None;
127        }
128        let v: Value = serde_json::from_str(payload).ok()?;
129        if v.get("nonce").and_then(Value::as_str) != Some(self.nonce.as_str()) {
130            return None;
131        }
132        let data = v.get("data").cloned().unwrap_or(Value::Null);
133        match v.get("kind").and_then(Value::as_str)? {
134            "select" => Some(DesignModeMarker::ElementSelected(data)),
135            "dismiss" => Some(DesignModeMarker::Dismissed),
136            "submit" => {
137                let id = data.get("id").and_then(Value::as_u64)?;
138                if id <= self.last_submit_id || !gesture.take(now_ms) {
139                    return None;
140                }
141                self.last_submit_id = id;
142                Some(DesignModeMarker::PromptSubmitted(data))
143            }
144            _ => None,
145        }
146    }
147}
148
149/// Native input types that establish the gesture gate (`Input.dispatch*Event` types).
150pub fn is_native_gesture_input(input_type: &str) -> bool {
151    matches!(input_type, "mouseDown" | "keyDown" | "rawKeyDown")
152}
153
154/// Whether a gesture stamped at `last_gesture_at_ms` is still inside the window at `now_ms`.
155/// A zero timestamp is never valid. `saturating_sub` keeps a clock step into the future from
156/// underflowing.
157pub fn gesture_is_recent(last_gesture_at_ms: u64, now_ms: u64) -> bool {
158    last_gesture_at_ms != 0
159        && now_ms.saturating_sub(last_gesture_at_ms) <= DESIGN_MODE_GESTURE_WINDOW_MS
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
163#[serde(rename_all = "camelCase")]
164pub struct ElementRect {
165    pub x: f64,
166    pub y: f64,
167    pub width: f64,
168    pub height: f64,
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
172#[serde(rename_all = "camelCase")]
173pub struct CaptureRect {
174    pub x: i64,
175    pub y: i64,
176    pub width: u64,
177    pub height: u64,
178}
179
180/// Convert CSS-pixel coordinates to device-pixel capture coordinates: all four values are
181/// multiplied by the device scale and rounded, so a crop stays aligned after zoom changes.
182/// Non-finite or non-positive rectangles are not capture requests and return `None`. A
183/// non-finite or non-positive scale is treated as 1.
184pub fn normalize_capture_rect(rect: ElementRect, device_scale: f64) -> Option<CaptureRect> {
185    if !rect.x.is_finite()
186        || !rect.y.is_finite()
187        || !rect.width.is_finite()
188        || !rect.height.is_finite()
189        || rect.width <= 0.0
190        || rect.height <= 0.0
191    {
192        return None;
193    }
194    let scale = if device_scale.is_finite() && device_scale > 0.0 {
195        device_scale
196    } else {
197        1.0
198    };
199    Some(CaptureRect {
200        x: (rect.x * scale).round() as i64,
201        y: (rect.y * scale).round() as i64,
202        width: (rect.width * scale).round().max(1.0) as u64,
203        height: (rect.height * scale).round().max(1.0) as u64,
204    })
205}
206
207/// Build the picker script for `nonce`. The nonce must be non-empty ASCII alphanumeric. Inject
208/// it only into the isolated world whose binding [`DesignModeBridge`] validates.
209pub fn build_design_mode_script(nonce: &str) -> Result<String> {
210    check_nonce(nonce)?;
211    Ok(PICKER_TEMPLATE
212        .replace(
213            "\"@@BINDING@@\"",
214            &js_string(&binding_name_for_nonce(nonce)),
215        )
216        .replace("\"@@NONCE@@\"", &js_string(nonce)))
217}
218
219fn js_string(s: &str) -> String {
220    serde_json::to_string(s).unwrap_or_else(|_| "\"\"".into())
221}