| 1 | //! A [`session::Transport`] for Firefox. It answers the small CDP subset the session layer and the |
| 2 | //! realtime worker send (evaluate, bindings, injected scripts, navigate, reload) over WebDriver BiDi, |
| 3 | //! so everything above the transport stays protocol-agnostic. |
| 4 | |
| 5 | use std::collections::{HashMap, HashSet}; |
| 6 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 7 | use std::sync::{Arc, Mutex}; |
| 8 | |
| 9 | use serde_json::{Value, json}; |
| 10 | use session::{ |
| 11 | App, BoxFuture, Diagnosis, Error, OpenedTab, Result, TabChannel, TabCommand, TabEvent, |
| 12 | Transport, is_login_url, |
| 13 | }; |
| 14 | use tokio::sync::{broadcast, mpsc}; |
| 15 | |
| 16 | use crate::bidi::{Bidi, Context, Event, evaluation_value}; |
| 17 | use crate::browser::Browser; |
| 18 | use crate::error::BrowserError; |
| 19 | |
| 20 | const ENDPOINT_NAME: &str = "WebDriver BiDi"; |
| 21 | |
| 22 | static NEXT_CHANNEL: AtomicU64 = AtomicU64::new(1); |
| 23 | |
| 24 | /// The transport that fits the browser: BiDi for Firefox, the CDP endpoint otherwise. |
| 25 | pub fn session_transport(browser: &Browser, endpoint: &str) -> Arc<dyn Transport> { |
| 26 | match browser.bidi() { |
| 27 | Some(bidi) => Arc::new(BidiTransport::new(bidi.clone())), |
| 28 | None => Arc::new(session::CdpTransport::new(endpoint)), |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | pub struct BidiTransport { |
| 33 | bidi: Bidi, |
| 34 | } |
| 35 | |
| 36 | impl BidiTransport { |
| 37 | pub fn new(bidi: Bidi) -> Self { |
| 38 | BidiTransport { bidi } |
| 39 | } |
| 40 | |
| 41 | async fn contexts(&self) -> Result<Vec<Context>> { |
| 42 | self.bidi.contexts().await.map_err(no_browser) |
| 43 | } |
| 44 | |
| 45 | async fn app_context(&self, app: App) -> Result<Option<Context>> { |
| 46 | Ok(self |
| 47 | .contexts() |
| 48 | .await? |
| 49 | .into_iter() |
| 50 | .find(|context| is_app_url(app, &context.url))) |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | fn is_app_url(app: App, url: &str) -> bool { |
| 55 | app.is_app_url(url) |
| 56 | } |
| 57 | |
| 58 | fn no_browser(error: BrowserError) -> Error { |
| 59 | Error::NoBrowser { |
| 60 | endpoint: ENDPOINT_NAME.into(), |
| 61 | reason: error.to_string(), |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | fn protocol(error: BrowserError) -> Error { |
| 66 | Error::Cdp(error.to_string()) |
| 67 | } |
| 68 | |
| 69 | impl Transport for BidiTransport { |
| 70 | fn supports_cdp(&self) -> bool { |
| 71 | false |
| 72 | } |
| 73 | |
| 74 | fn check(&self) -> BoxFuture<'_, Result<()>> { |
| 75 | Box::pin(async move { self.contexts().await.map(drop) }) |
| 76 | } |
| 77 | |
| 78 | fn open(&self, app: App, with_events: bool) -> BoxFuture<'_, Result<Option<OpenedTab>>> { |
| 79 | Box::pin(async move { |
| 80 | let Some(context) = self.app_context(app).await? else { |
| 81 | return Ok(None); |
| 82 | }; |
| 83 | let events = match with_events { |
| 84 | true => Some(self.bidi.events().await.map_err(no_browser)?), |
| 85 | false => None, |
| 86 | }; |
| 87 | let channel = TabChannel::new(with_events); |
| 88 | tokio::spawn(serve( |
| 89 | self.bidi.clone(), |
| 90 | context.id, |
| 91 | channel.commands, |
| 92 | events, |
| 93 | channel.event_sink, |
| 94 | )); |
| 95 | Ok(Some((channel.control, channel.events))) |
| 96 | }) |
| 97 | } |
| 98 | |
| 99 | fn wake(&self, app: App) -> BoxFuture<'_, Result<()>> { |
| 100 | Box::pin(async move { |
| 101 | let Some(context) = self.app_context(app).await? else { |
| 102 | return Ok(()); |
| 103 | }; |
| 104 | if app.is_park_url(&context.url) { |
| 105 | self.bidi |
| 106 | .navigate(&context.id, app.start_url_like(&context.url)) |
| 107 | .await |
| 108 | } else { |
| 109 | let params = json!({"context": context.id, "wait": "none"}); |
| 110 | self.bidi |
| 111 | .call("browsingContext.reload", params) |
| 112 | .await |
| 113 | .map(drop) |
| 114 | } |
| 115 | .map_err(protocol) |
| 116 | }) |
| 117 | } |
| 118 | |
| 119 | fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> { |
| 120 | Box::pin(async move { |
| 121 | let contexts = self.contexts().await?; |
| 122 | Ok(Diagnosis { |
| 123 | login_pending: contexts.iter().any(|context| is_login_url(&context.url)), |
| 124 | app_tab_open: App::ALL |
| 125 | .iter() |
| 126 | .any(|&app| contexts.iter().any(|context| is_app_url(app, &context.url))), |
| 127 | }) |
| 128 | }) |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | /// What one tab channel registered, so it can map messages back and clean up after itself: |
| 133 | /// unlike CDP, BiDi keeps preload scripts after the channel is gone. |
| 134 | #[derive(Default)] |
| 135 | struct ChannelState { |
| 136 | /// BiDi channel id to the CDP binding name. |
| 137 | bindings: HashMap<String, String>, |
| 138 | scripts: HashSet<String>, |
| 139 | } |
| 140 | |
| 141 | type Shared = Arc<Mutex<ChannelState>>; |
| 142 | |
| 143 | async fn serve( |
| 144 | bidi: Bidi, |
| 145 | context: String, |
| 146 | mut commands: mpsc::UnboundedReceiver<TabCommand>, |
| 147 | mut events: Option<broadcast::Receiver<Event>>, |
| 148 | sink: Option<mpsc::UnboundedSender<TabEvent>>, |
| 149 | ) { |
| 150 | let state = Shared::default(); |
| 151 | let mut commands_open = true; |
| 152 | loop { |
| 153 | tokio::select! { |
| 154 | command = commands.recv(), if commands_open => match command { |
| 155 | Some(command) => { |
| 156 | let (bidi, context, state) = (bidi.clone(), context.clone(), state.clone()); |
| 157 | tokio::spawn(async move { |
| 158 | let outcome = |
| 159 | translate(&bidi, &context, &state, &command.method, &command.params).await; |
| 160 | command.respond(outcome); |
| 161 | }); |
| 162 | } |
| 163 | None if sink.is_none() => break, |
| 164 | None => commands_open = false, |
| 165 | }, |
| 166 | event = next_event(&mut events) => match event { |
| 167 | Ok(event) => { |
| 168 | let Some(sink) = &sink else { break }; |
| 169 | let mapped = tab_event(&context, &state.lock().expect("channel state").bindings, &event); |
| 170 | if let Some(mapped) = mapped |
| 171 | && sink.send(mapped).is_err() |
| 172 | { |
| 173 | break; |
| 174 | } |
| 175 | } |
| 176 | Err(broadcast::error::RecvError::Lagged(_)) => {} |
| 177 | Err(broadcast::error::RecvError::Closed) => break, |
| 178 | }, |
| 179 | _ = sink_closed(&sink) => break, |
| 180 | } |
| 181 | } |
| 182 | let scripts = std::mem::take(&mut state.lock().expect("channel state").scripts); |
| 183 | for script in scripts { |
| 184 | let _ = bidi |
| 185 | .call("script.removePreloadScript", json!({"script": script})) |
| 186 | .await; |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | async fn next_event( |
| 191 | events: &mut Option<broadcast::Receiver<Event>>, |
| 192 | ) -> std::result::Result<Event, broadcast::error::RecvError> { |
| 193 | match events { |
| 194 | Some(receiver) => receiver.recv().await, |
| 195 | None => std::future::pending().await, |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | async fn sink_closed(sink: &Option<mpsc::UnboundedSender<TabEvent>>) { |
| 200 | match sink { |
| 201 | Some(sink) => sink.closed().await, |
| 202 | None => std::future::pending().await, |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | /// A function that installs `name` on the page as a binding that posts to its channel argument. |
| 207 | fn binding_declaration(name: &str) -> String { |
| 208 | let name = Value::from(name); |
| 209 | format!("(send) => {{ globalThis[{name}] = (payload) => send(String(payload)); }}") |
| 210 | } |
| 211 | |
| 212 | async fn translate( |
| 213 | bidi: &Bidi, |
| 214 | context: &str, |
| 215 | state: &Shared, |
| 216 | method: &str, |
| 217 | params: &Value, |
| 218 | ) -> Result<Value> { |
| 219 | let text = |key: &str| params[key].as_str().unwrap_or_default(); |
| 220 | match method { |
| 221 | "Runtime.enable" | "Runtime.disable" | "Page.enable" | "Page.disable" => Ok(json!({})), |
| 222 | "Runtime.evaluate" => { |
| 223 | let request = json!({ |
| 224 | "expression": text("expression"), |
| 225 | "target": {"context": context}, |
| 226 | "awaitPromise": params["awaitPromise"].as_bool().unwrap_or(false), |
| 227 | "resultOwnership": "none", |
| 228 | }); |
| 229 | let result = bidi |
| 230 | .call("script.evaluate", request) |
| 231 | .await |
| 232 | .map_err(protocol)?; |
| 233 | Ok(match evaluation_value(&result) { |
| 234 | Ok(value) => json!({"result": {"value": value}}), |
| 235 | Err(text) => json!({"exceptionDetails": {"text": text}}), |
| 236 | }) |
| 237 | } |
| 238 | "Runtime.addBinding" => { |
| 239 | let name = text("name"); |
| 240 | let channel = format!("{name}#{}", NEXT_CHANNEL.fetch_add(1, Ordering::Relaxed)); |
| 241 | let declaration = binding_declaration(name); |
| 242 | let arguments = json!([{"type": "channel", "value": {"channel": channel}}]); |
| 243 | state |
| 244 | .lock() |
| 245 | .expect("channel state") |
| 246 | .bindings |
| 247 | .insert(channel, name.to_owned()); |
| 248 | let preload = json!({ |
| 249 | "functionDeclaration": declaration, |
| 250 | "arguments": arguments, |
| 251 | "contexts": [context], |
| 252 | }); |
| 253 | add_preload(bidi, state, preload).await?; |
| 254 | let now = json!({ |
| 255 | "functionDeclaration": declaration, |
| 256 | "arguments": arguments, |
| 257 | "target": {"context": context}, |
| 258 | "awaitPromise": false, |
| 259 | }); |
| 260 | bidi.call("script.callFunction", now) |
| 261 | .await |
| 262 | .map_err(protocol)?; |
| 263 | Ok(json!({})) |
| 264 | } |
| 265 | "Page.addScriptToEvaluateOnNewDocument" => { |
| 266 | let preload = json!({ |
| 267 | "functionDeclaration": format!("() => {{\n{}\n}}", text("source")), |
| 268 | "contexts": [context], |
| 269 | }); |
| 270 | let identifier = add_preload(bidi, state, preload).await?; |
| 271 | Ok(json!({"identifier": identifier})) |
| 272 | } |
| 273 | "Page.removeScriptToEvaluateOnNewDocument" => { |
| 274 | let script = text("identifier"); |
| 275 | state.lock().expect("channel state").scripts.remove(script); |
| 276 | bidi.call("script.removePreloadScript", json!({"script": script})) |
| 277 | .await |
| 278 | .map(|_| json!({})) |
| 279 | .map_err(protocol) |
| 280 | } |
| 281 | "Page.navigate" => bidi |
| 282 | .navigate(context, text("url")) |
| 283 | .await |
| 284 | .map(|_| json!({})) |
| 285 | .map_err(protocol), |
| 286 | "Page.reload" => bidi |
| 287 | .call( |
| 288 | "browsingContext.reload", |
| 289 | json!({"context": context, "wait": "none"}), |
| 290 | ) |
| 291 | .await |
| 292 | .map(|_| json!({})) |
| 293 | .map_err(protocol), |
| 294 | other => Err(Error::Cdp(format!( |
| 295 | "{other} is not available over WebDriver BiDi" |
| 296 | ))), |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | async fn add_preload(bidi: &Bidi, state: &Shared, params: Value) -> Result<String> { |
| 301 | let added = bidi |
| 302 | .call("script.addPreloadScript", params) |
| 303 | .await |
| 304 | .map_err(protocol)?; |
| 305 | let script = added["script"].as_str().unwrap_or_default().to_owned(); |
| 306 | state |
| 307 | .lock() |
| 308 | .expect("channel state") |
| 309 | .scripts |
| 310 | .insert(script.clone()); |
| 311 | Ok(script) |
| 312 | } |
| 313 | |
| 314 | /// The CDP event a BiDi event stands for in this tab. Binding calls match by channel, so they also |
| 315 | /// arrive from the tab's frames, as CDP bindings do. |
| 316 | fn tab_event(context: &str, bindings: &HashMap<String, String>, event: &Event) -> Option<TabEvent> { |
| 317 | let params = &event["params"]; |
| 318 | match event["method"].as_str()? { |
| 319 | "script.message" => { |
| 320 | let name = bindings.get(params["channel"].as_str()?)?; |
| 321 | let payload = params.pointer("/data/value")?.as_str()?; |
| 322 | Some(TabEvent { |
| 323 | method: "Runtime.bindingCalled".into(), |
| 324 | params: json!({"name": name, "payload": payload}), |
| 325 | }) |
| 326 | } |
| 327 | "browsingContext.load" if params["context"] == context => Some(TabEvent { |
| 328 | method: "Page.frameNavigated".into(), |
| 329 | params: json!({"frame": {"id": context, "url": params["url"]}}), |
| 330 | }), |
| 331 | _ => None, |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | #[cfg(test)] |
| 336 | mod tests { |
| 337 | use super::*; |
| 338 | |
| 339 | fn bindings() -> HashMap<String, String> { |
| 340 | HashMap::from([("sink#1".to_owned(), "sink".to_owned())]) |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn channel_messages_become_binding_calls() { |
| 345 | let message = json!({"method": "script.message", "params": { |
| 346 | "channel": "sink#1", |
| 347 | "data": {"type": "string", "value": "{\"a\":1}"}, |
| 348 | "source": {"context": "frame"}, |
| 349 | }}); |
| 350 | let event = tab_event("tab", &bindings(), &message).unwrap(); |
| 351 | assert_eq!(event.binding_payload("sink"), Some("{\"a\":1}")); |
| 352 | let foreign = json!({"method": "script.message", "params": { |
| 353 | "channel": "other#2", "data": {"type": "string", "value": "x"}, |
| 354 | }}); |
| 355 | assert!(tab_event("tab", &bindings(), &foreign).is_none()); |
| 356 | } |
| 357 | |
| 358 | #[test] |
| 359 | fn only_this_tabs_load_is_a_main_frame_navigation() { |
| 360 | let load = |context: &str| json!({"method": "browsingContext.load", "params": {"context": context, "url": "https://teams.cloud.microsoft/"}}); |
| 361 | let event = tab_event("tab", &bindings(), &load("tab")).unwrap(); |
| 362 | assert_eq!(event.method, "Page.frameNavigated"); |
| 363 | assert!(event.params.pointer("/frame/parentId").is_none()); |
| 364 | assert!(tab_event("tab", &bindings(), &load("other")).is_none()); |
| 365 | } |
| 366 | |
| 367 | #[test] |
| 368 | fn binding_declaration_quotes_the_name() { |
| 369 | assert_eq!( |
| 370 | binding_declaration("a'b"), |
| 371 | r#"(send) => { globalThis["a'b"] = (payload) => send(String(payload)); }"# |
| 372 | ); |
| 373 | } |
| 374 | } |