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}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226    use serde_json::json;
227
228    fn call(nonce: &str, kind: &str, data: Value) -> String {
229        json!({"nonce": nonce, "kind": kind, "data": data}).to_string()
230    }
231
232    #[test]
233    fn bridge_rejects_wrong_binding_context_nonce_and_kind() {
234        let g = NativeGestureLatch::new();
235        let mut b = DesignModeBridge::new("abc123").unwrap();
236        let name = b.binding_name();
237        let sel = call("abc123", "select", json!({"tag": "button"}));
238        assert!(matches!(
239            b.accept(&name, &sel, true, &g, 10),
240            Some(DesignModeMarker::ElementSelected(_))
241        ));
242        assert!(b.accept(&name, &sel, false, &g, 10).is_none());
243        assert!(b
244            .accept("__omni_other_bridge__", &sel, true, &g, 10)
245            .is_none());
246        let forged = call("zzz", "select", json!({}));
247        assert!(b.accept(&name, &forged, true, &g, 10).is_none());
248        assert!(b.accept(&name, "not-json", true, &g, 10).is_none());
249        assert!(b
250            .accept(&name, &call("abc123", "bogus", Value::Null), true, &g, 10)
251            .is_none());
252        assert_eq!(
253            b.accept(&name, &call("abc123", "dismiss", Value::Null), true, &g, 10),
254            Some(DesignModeMarker::Dismissed)
255        );
256    }
257
258    #[test]
259    fn submit_needs_a_fresh_id_and_consumes_one_gesture() {
260        let g = NativeGestureLatch::new();
261        let mut b = DesignModeBridge::new("n").unwrap();
262        let name = b.binding_name();
263        let s1 = call("n", "submit", json!({"id": 1, "prompt": "x"}));
264        assert!(b.accept(&name, &s1, true, &g, 2_000).is_none());
265        g.stamp_at(1_000);
266        assert!(matches!(
267            b.accept(&name, &s1, true, &g, 2_000),
268            Some(DesignModeMarker::PromptSubmitted(_))
269        ));
270        // Replay of the same message, even with a new gesture, is rejected.
271        g.stamp_at(2_000);
272        assert!(b.accept(&name, &s1, true, &g, 2_100).is_none());
273        // One gesture authorizes one submission only.
274        g.stamp_at(3_000);
275        let s2 = call("n", "submit", json!({"id": 2}));
276        let s3 = call("n", "submit", json!({"id": 3}));
277        assert!(b.accept(&name, &s2, true, &g, 3_100).is_some());
278        assert!(b.accept(&name, &s3, true, &g, 3_100).is_none());
279        // An expired gesture is rejected and cleared.
280        g.stamp_at(1_000);
281        assert!(b.accept(&name, &s3, true, &g, 9_000).is_none());
282    }
283
284    #[test]
285    fn only_real_native_input_types_stamp_the_gesture() {
286        assert!(is_native_gesture_input("mouseDown"));
287        assert!(is_native_gesture_input("keyDown"));
288        assert!(is_native_gesture_input("rawKeyDown"));
289        assert!(!is_native_gesture_input("mouseUp"));
290        assert!(!is_native_gesture_input("wheel"));
291        assert!(!gesture_is_recent(0, 1_000));
292        assert!(gesture_is_recent(1_000, 2_500));
293        assert!(!gesture_is_recent(1_000, 2_501));
294    }
295
296    #[test]
297    fn capture_geometry_preserves_zoom_and_rejects_empty_rectangles() {
298        assert_eq!(
299            normalize_capture_rect(
300                ElementRect {
301                    x: 10.25,
302                    y: -2.25,
303                    width: 40.4,
304                    height: 20.4
305                },
306                2.0,
307            ),
308            Some(CaptureRect {
309                x: 21,
310                y: -5,
311                width: 81,
312                height: 41
313            })
314        );
315        assert_eq!(
316            normalize_capture_rect(
317                ElementRect {
318                    x: 0.0,
319                    y: 0.0,
320                    width: 0.0,
321                    height: 2.0
322                },
323                1.0
324            ),
325            None
326        );
327        assert_eq!(
328            normalize_capture_rect(
329                ElementRect {
330                    x: 0.0,
331                    y: 0.0,
332                    width: 1.0,
333                    height: 1.0
334                },
335                f64::NAN,
336            ),
337            Some(CaptureRect {
338                x: 0,
339                y: 0,
340                width: 1,
341                height: 1
342            })
343        );
344    }
345
346    #[test]
347    fn picker_script_uses_the_binding_not_the_console() {
348        let script = build_design_mode_script("abc123").unwrap();
349        assert!(script.contains("var __OMNI_BINDING = \"__omni_abc123_bridge__\";"));
350        assert!(script.contains("var __OMNI_NONCE = \"abc123\";"));
351        assert!(!script.contains("@@"));
352        assert!(!script.contains("console."));
353        assert!(script.contains("window.__omniDisableDesignMode"));
354        assert!(script.contains("split(/\\s+/)"));
355    }
356
357    #[test]
358    fn picker_script_rejects_unsafe_nonces() {
359        assert!(build_design_mode_script("").is_err());
360        assert!(build_design_mode_script("ab\"cd").is_err());
361        assert!(build_design_mode_script("ab_cd").is_err());
362    }
363}