BlueGit

ict rusty-teams

feat(browser): sign in with Firefox, Zen, LibreWolf or Floorp

Linux and macOS without a Chromium browser now start a Firefox-family
browser for sign-in, with its own rusty-teams-firefox profile.
RUSTY_TEAMS_SIGN_IN_BROWSER picks an executable either way.

Firefox dropped CDP, so it runs over WebDriver BiDi. A BiDi transport
answers the CDP calls the session layer and the realtime worker send
(evaluate, bindings, injected scripts, navigate, reload), so nothing
above the transport changes.

Firefox allows one BiDi session and keeps it after the socket closes,
so the app shares one connection and restarts the managed browser when a
crashed run left its session behind. It stops Firefox with SIGTERM,
since browser.close leaves the process and profile lock alive on macOS,
and turns off Safe Mode, which hard stops trigger and which hangs a
headless start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Michael Wallner · pushed by metis

Authored 2026-11-16 · 2 weeks ago

Hash
c46900bf4d075d6ae3c6d119dacac9fef7f1a46b
Parent
d921608d
16 files changed +1182 −79
Cargo.lock +1 −0
@@ -1098,6 +1098,7 @@ dependencies = [
1098 1098 "futures-util",
1099 1099 "serde",
1100 1100 "serde_json",
1101 "session",
1101 1102 "tempfile",
1102 1103 "thiserror 2.0.21",
1103 1104 "tokio",
@@ -1098,6 +1098,7 @@ dependencies = [
1098 "futures-util",
1098 "futures-util",
1099 "serde",
1099 "serde",
1100 "serde_json",
1100 "serde_json",
1101 "session",
1101 "tempfile",
1102 "tempfile",
1102 "thiserror 2.0.21",
1103 "thiserror 2.0.21",
1103 "tokio",
1104 "tokio",
README.md +2 −2
@@ -90,8 +90,8 @@
90 90 | Platform | State |
91 91 |---|---|
92 92 | 🪟 Windows | Main target. Login through an embedded WebView2 |
93 | 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. On start the app offers to install itself to `~/.local/share/rusty-teams/teams` (moved, or copied when started from a cargo `target` folder) and writes `~/.local/share/applications/rusty-teams.desktop`; starting a newer build offers to replace the installed one, and Settings > General can install, replace, remove or bring the question back. The installed copy of a release build looks for new GitHub releases (Settings > General > Automatic updates) and asks before it downloads and restarts. Tray icon through StatusNotifierItem (KDE Plasma natively, GNOME with the AppIndicator extension); with "Close to tray" the window closes and the app keeps running in the tray, which opens a new window. Built-in login without Chrome is planned |
94 | 🍎 macOS | Starts the first Chromium browser it finds (Google Chrome, Chromium, Microsoft Edge, Brave, Helium, Vivaldi) on its own (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
93 | 🐧 Linux | Starts Google Chrome or Chromium on its own, or Firefox, Zen, LibreWolf or Floorp when no Chromium browser is installed (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. On start the app offers to install itself to `~/.local/share/rusty-teams/teams` (moved, or copied when started from a cargo `target` folder) and writes `~/.local/share/applications/rusty-teams.desktop`; starting a newer build offers to replace the installed one, and Settings > General can install, replace, remove or bring the question back. The installed copy of a release build looks for new GitHub releases (Settings > General > Automatic updates) and asks before it downloads and restarts. Tray icon through StatusNotifierItem (KDE Plasma natively, GNOME with the AppIndicator extension); with "Close to tray" the window closes and the app keeps running in the tray, which opens a new window. Built-in login without Chrome is planned |
94 | 🍎 macOS | Starts the first Chromium browser it finds (Google Chrome, Chromium, Microsoft Edge, Brave, Helium, Vivaldi), else the first Firefox browser (Firefox, Zen, LibreWolf, Floorp), on its own. `RUSTY_TEAMS_SIGN_IN_BROWSER=/path/to/executable` picks one explicitly, on Linux too (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
95 95
96 96 The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
97 97
@@ -90,8 +90,8 @@
90| Platform | State |
90| Platform | State |
91|---|---|
91|---|---|
92| 🪟 Windows | Main target. Login through an embedded WebView2 |
92| 🪟 Windows | Main target. Login through an embedded WebView2 |
93| 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. On start the app offers to install itself to `~/.local/share/rusty-teams/teams` (moved, or copied when started from a cargo `target` folder) and writes `~/.local/share/applications/rusty-teams.desktop`; starting a newer build offers to replace the installed one, and Settings > General can install, replace, remove or bring the question back. The installed copy of a release build looks for new GitHub releases (Settings > General > Automatic updates) and asks before it downloads and restarts. Tray icon through StatusNotifierItem (KDE Plasma natively, GNOME with the AppIndicator extension); with "Close to tray" the window closes and the app keeps running in the tray, which opens a new window. Built-in login without Chrome is planned |
93| 🐧 Linux | Starts Google Chrome or Chromium on its own, or Firefox, Zen, LibreWolf or Floorp when no Chromium browser is installed (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. On start the app offers to install itself to `~/.local/share/rusty-teams/teams` (moved, or copied when started from a cargo `target` folder) and writes `~/.local/share/applications/rusty-teams.desktop`; starting a newer build offers to replace the installed one, and Settings > General can install, replace, remove or bring the question back. The installed copy of a release build looks for new GitHub releases (Settings > General > Automatic updates) and asks before it downloads and restarts. Tray icon through StatusNotifierItem (KDE Plasma natively, GNOME with the AppIndicator extension); with "Close to tray" the window closes and the app keeps running in the tray, which opens a new window. Built-in login without Chrome is planned |
94| 🍎 macOS | Starts the first Chromium browser it finds (Google Chrome, Chromium, Microsoft Edge, Brave, Helium, Vivaldi) on its own (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
94| 🍎 macOS | Starts the first Chromium browser it finds (Google Chrome, Chromium, Microsoft Edge, Brave, Helium, Vivaldi), else the first Firefox browser (Firefox, Zen, LibreWolf, Floorp), on its own. `RUSTY_TEAMS_SIGN_IN_BROWSER=/path/to/executable` picks one explicitly, on Linux too (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
95
95
96The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
96The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
97
97
ROADMAP.md +1 −0
@@ -38,6 +38,7 @@ Feature parity with the Microsoft Teams desktop client.
38 38 | Sign in on Linux without starting Chrome by hand | Done | The app starts Chrome or Chromium headless with its own profile, shows the window for the login and hides it again afterwards; a watchdog restarts a dead or hung Chrome |
39 39 | Single instance, second start brings the window to front | Done | |
40 40 | Sign in on macOS without starting Chrome by hand | Done | Same managed browser as on Linux, profile in Application Support. Takes the first of Chrome, Chromium, Edge, Brave, Helium, Vivaldi; checked live with Helium |
41 | Sign in with a Firefox browser | Partial | Firefox, Zen, LibreWolf or Floorp over WebDriver BiDi when no Chromium browser is installed, or picked with `RUSTY_TEAMS_SIGN_IN_BROWSER`; own profile `rusty-teams-firefox` (ADR 0003). Checked live with Zen 1.24 on macOS: headless start, login window and back, page scripts and bindings, restart after a crashed app run. A full Teams sign-in and Linux not run yet |
41 42 | Guest orgs (one account, several tenants) | Partial | Account menu lists the orgs, the open one checked; picking another restarts on it with its own cache (ADR 0017). Orgs that are not open stay live: toast per new chat message from others, count of chats with new messages in the menu, click switches and opens the chat. Guest org sync checked live; the background toast not run live yet. Calls stay on the home tenant; Outlook calendar is unavailable for a guest |
42 43
43 44 ## Chat list
@@ -38,6 +38,7 @@ Feature parity with the Microsoft Teams desktop client.
38| Sign in on Linux without starting Chrome by hand | Done | The app starts Chrome or Chromium headless with its own profile, shows the window for the login and hides it again afterwards; a watchdog restarts a dead or hung Chrome |
38| Sign in on Linux without starting Chrome by hand | Done | The app starts Chrome or Chromium headless with its own profile, shows the window for the login and hides it again afterwards; a watchdog restarts a dead or hung Chrome |
39| Single instance, second start brings the window to front | Done | |
39| Single instance, second start brings the window to front | Done | |
40| Sign in on macOS without starting Chrome by hand | Done | Same managed browser as on Linux, profile in Application Support. Takes the first of Chrome, Chromium, Edge, Brave, Helium, Vivaldi; checked live with Helium |
40| Sign in on macOS without starting Chrome by hand | Done | Same managed browser as on Linux, profile in Application Support. Takes the first of Chrome, Chromium, Edge, Brave, Helium, Vivaldi; checked live with Helium |
41| Sign in with a Firefox browser | Partial | Firefox, Zen, LibreWolf or Floorp over WebDriver BiDi when no Chromium browser is installed, or picked with `RUSTY_TEAMS_SIGN_IN_BROWSER`; own profile `rusty-teams-firefox` (ADR 0003). Checked live with Zen 1.24 on macOS: headless start, login window and back, page scripts and bindings, restart after a crashed app run. A full Teams sign-in and Linux not run yet |
41| Guest orgs (one account, several tenants) | Partial | Account menu lists the orgs, the open one checked; picking another restarts on it with its own cache (ADR 0017). Orgs that are not open stay live: toast per new chat message from others, count of chats with new messages in the menu, click switches and opens the chat. Guest org sync checked live; the background toast not run live yet. Calls stay on the home tenant; Outlook calendar is unavailable for a guest |
42| Guest orgs (one account, several tenants) | Partial | Account menu lists the orgs, the open one checked; picking another restarts on it with its own cache (ADR 0017). Orgs that are not open stay live: toast per new chat message from others, count of chats with new messages in the menu, click switches and opens the chat. Guest org sync checked live; the background toast not run live yet. Calls stay on the home tenant; Outlook calendar is unavailable for a guest |
42
43
43## Chat list
44## Chat list
crates/app-base/locales/app.yml +4 −4
@@ -414,8 +414,8 @@ settings:
414 414 en: Open links and Google sign-in with
415 415 de: Links und Google-Anmeldung öffnen mit
416 416 external_browser_detail:
417 en: Does not change the Teams session browser (that needs a Chromium browser such as Chrome, Edge, Brave or Helium).
418 de: Ändert nicht den Browser der Teams-Sitzung (dafür bleibt ein Chromium-Browser wie Chrome, Edge, Brave oder Helium nötig).
417 en: Does not change the Teams session browser (that is a Chromium or Firefox browser such as Chrome, Edge, Helium, Firefox or Zen).
418 de: Ändert nicht den Browser der Teams-Sitzung (das ist ein Chromium- oder Firefox-Browser wie Chrome, Edge, Helium, Firefox oder Zen).
419 419 external_browser_system:
420 420 en: System default
421 421 de: Systemstandard
@@ -1623,8 +1623,8 @@ auth:
1623 1623 en: Finishing sign-in…
1624 1624 de: Anmeldung wird abgeschlossen…
1625 1625 browser_failed:
1626 en: Could not open a Chromium browser (Chrome, Edge, Brave, Helium)
1627 de: Kein Chromium-Browser konnte geöffnet werden (Chrome, Edge, Brave, Helium)
1626 en: Could not open a browser for sign-in (Chrome, Edge, Brave, Helium, Firefox, Zen)
1627 de: Kein Browser für die Anmeldung konnte geöffnet werden (Chrome, Edge, Brave, Helium, Firefox, Zen)
1628 1628 browser_still_loading_hint:
1629 1629 en: The Teams logo in the browser means the login page is still loading
1630 1630 de: Das Teams-Logo im Browser heisst, die Anmeldeseite lädt noch
@@ -414,8 +414,8 @@ settings:
414 en: Open links and Google sign-in with
414 en: Open links and Google sign-in with
415 de: Links und Google-Anmeldung öffnen mit
415 de: Links und Google-Anmeldung öffnen mit
416 external_browser_detail:
416 external_browser_detail:
417 en: Does not change the Teams session browser (that needs a Chromium browser such as Chrome, Edge, Brave or Helium).
417 en: Does not change the Teams session browser (that is a Chromium or Firefox browser such as Chrome, Edge, Helium, Firefox or Zen).
418 de: Ändert nicht den Browser der Teams-Sitzung (dafür bleibt ein Chromium-Browser wie Chrome, Edge, Brave oder Helium nötig).
418 de: Ändert nicht den Browser der Teams-Sitzung (das ist ein Chromium- oder Firefox-Browser wie Chrome, Edge, Helium, Firefox oder Zen).
419 external_browser_system:
419 external_browser_system:
420 en: System default
420 en: System default
421 de: Systemstandard
421 de: Systemstandard
@@ -1623,8 +1623,8 @@ auth:
1623 en: Finishing sign-in…
1623 en: Finishing sign-in…
1624 de: Anmeldung wird abgeschlossen…
1624 de: Anmeldung wird abgeschlossen…
1625 browser_failed:
1625 browser_failed:
1626 en: Could not open a Chromium browser (Chrome, Edge, Brave, Helium)
1626 en: Could not open a browser for sign-in (Chrome, Edge, Brave, Helium, Firefox, Zen)
1627 de: Kein Chromium-Browser konnte geöffnet werden (Chrome, Edge, Brave, Helium)
1627 de: Kein Browser für die Anmeldung konnte geöffnet werden (Chrome, Edge, Brave, Helium, Firefox, Zen)
1628 browser_still_loading_hint:
1628 browser_still_loading_hint:
1629 en: The Teams logo in the browser means the login page is still loading
1629 en: The Teams logo in the browser means the login page is still loading
1630 de: Das Teams-Logo im Browser heisst, die Anmeldeseite lädt noch
1630 de: Das Teams-Logo im Browser heisst, die Anmeldeseite lädt noch
crates/app/src/linux_browser.rs +2 −2
@@ -225,7 +225,7 @@ pub fn stop() {
225 225 }
226 226
227 227 struct LinuxTransport {
228 inner: session::CdpTransport,
228 inner: Arc<dyn session::Transport>,
229 229 browser: browser::Browser,
230 230 init_done: watch::Receiver<bool>,
231 231 headless_notify: Arc<Notify>,
@@ -239,7 +239,7 @@ impl LinuxTransport {
239 239 headless_notify: Arc<Notify>,
240 240 ) -> Self {
241 241 LinuxTransport {
242 inner: session::CdpTransport::new(endpoint),
242 inner: browser::session_transport(&browser, endpoint),
243 243 browser,
244 244 init_done,
245 245 headless_notify,
@@ -225,7 +225,7 @@ pub fn stop() {
225}
225}
226
226
227struct LinuxTransport {
227struct LinuxTransport {
228 inner: session::CdpTransport,
228 inner: Arc<dyn session::Transport>,
229 browser: browser::Browser,
229 browser: browser::Browser,
230 init_done: watch::Receiver<bool>,
230 init_done: watch::Receiver<bool>,
231 headless_notify: Arc<Notify>,
231 headless_notify: Arc<Notify>,
@@ -239,7 +239,7 @@ impl LinuxTransport {
239 headless_notify: Arc<Notify>,
239 headless_notify: Arc<Notify>,
240 ) -> Self {
240 ) -> Self {
241 LinuxTransport {
241 LinuxTransport {
242 inner: session::CdpTransport::new(endpoint),
242 inner: browser::session_transport(&browser, endpoint),
243 browser,
243 browser,
244 init_done,
244 init_done,
245 headless_notify,
245 headless_notify,
crates/browser/Cargo.toml +1 −0
@@ -10,6 +10,7 @@ directories.workspace = true
10 10 futures-util.workspace = true
11 11 serde.workspace = true
12 12 serde_json.workspace = true
13 session.workspace = true
13 14 thiserror.workspace = true
14 15 tokio.workspace = true
15 16 tokio-tungstenite.workspace = true
@@ -10,6 +10,7 @@ directories.workspace = true
10futures-util.workspace = true
10futures-util.workspace = true
11serde.workspace = true
11serde.workspace = true
12serde_json.workspace = true
12serde_json.workspace = true
13session.workspace = true
13thiserror.workspace = true
14thiserror.workspace = true
14tokio.workspace = true
15tokio.workspace = true
15tokio-tungstenite.workspace = true
16tokio-tungstenite.workspace = true
crates/browser/src/bidi.rs added +353 −0
@@ -0,0 +1,353 @@
1 //! One WebDriver BiDi session for the whole app. Firefox allows a single session per browser and
2 //! keeps it after the socket closes, so every caller shares this connection.
3
4 use std::collections::HashMap;
5 use std::sync::Arc;
6 use std::time::Duration;
7
8 use futures_util::{SinkExt, StreamExt};
9 use serde_json::{Map, Value, json};
10 use tokio::sync::{Mutex, broadcast, mpsc, oneshot};
11 use tokio_tungstenite::tungstenite::Message;
12
13 use crate::error::BrowserError;
14 use crate::targets::{self, Tab};
15
16 const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
17 const EVENT_BUFFER: usize = 1024;
18 /// Subscribed once per session; tab channels filter by context.
19 const EVENTS: [&str; 2] = ["script.message", "browsingContext.load"];
20
21 struct Call {
22 method: String,
23 params: Value,
24 reply: oneshot::Sender<Result<Value, BrowserError>>,
25 }
26
27 /// A BiDi event as `{method, params}`.
28 pub type Event = Value;
29
30 #[derive(Clone)]
31 pub struct Bidi {
32 port: u16,
33 connection: Arc<Mutex<Option<Connection>>>,
34 }
35
36 struct Connection {
37 commands: mpsc::UnboundedSender<Call>,
38 /// Kept only to hand out receivers. The pump owns the sender, so receivers close with the socket.
39 events: broadcast::Receiver<Event>,
40 }
41
42 /// A top-level browsing context, the BiDi word for a tab.
43 #[derive(Debug, Clone, PartialEq, Eq)]
44 pub struct Context {
45 pub id: String,
46 pub url: String,
47 }
48
49 impl Bidi {
50 pub fn new(port: u16) -> Bidi {
51 Bidi {
52 port,
53 connection: Arc::new(Mutex::new(None)),
54 }
55 }
56
57 /// Events of every tab on the current connection, from the moment of the call. The stream
58 /// ends when the connection does, for example when the browser restarts.
59 pub async fn events(&self) -> Result<broadcast::Receiver<Event>, BrowserError> {
60 self.connected(|connection| connection.events.resubscribe())
61 .await
62 }
63
64 pub async fn call(&self, method: &str, params: Value) -> Result<Value, BrowserError> {
65 let commands = self
66 .connected(|connection| connection.commands.clone())
67 .await?;
68 send(&commands, method, params).await
69 }
70
71 /// Opens the session if there is none. [`BrowserError::SessionTaken`] when a session another
72 /// process left behind blocks it: only a browser restart frees that.
73 pub async fn connect(&self) -> Result<(), BrowserError> {
74 self.connected(|_| ()).await
75 }
76
77 async fn connected<T>(&self, read: impl FnOnce(&Connection) -> T) -> Result<T, BrowserError> {
78 let mut connection = self.connection.lock().await;
79 if let Some(open) = connection
80 .as_ref()
81 .filter(|open| !open.commands.is_closed())
82 {
83 return Ok(read(open));
84 }
85 *connection = None;
86 let url = format!("ws://127.0.0.1:{}/session", self.port);
87 let (stream, _) =
88 tokio::time::timeout(CONNECT_TIMEOUT, tokio_tungstenite::connect_async(&url))
89 .await
90 .map_err(|_| BrowserError::NoBrowser(format!("{url}: connect timed out")))?
91 .map_err(|error| BrowserError::NoBrowser(format!("{url}: {error}")))?;
92 let (commands, receiver) = mpsc::unbounded_channel();
93 let (events_sender, events) = broadcast::channel(EVENT_BUFFER);
94 tokio::spawn(pump(stream, receiver, events_sender));
95 let opened = tokio::time::timeout(
96 CONNECT_TIMEOUT,
97 send(&commands, "session.new", json!({"capabilities": {}})),
98 )
99 .await
100 .map_err(|_| BrowserError::Cdp("session.new timed out".into()))?;
101 match opened {
102 Err(BrowserError::Cdp(text)) if text.contains("session not created") => {
103 return Err(BrowserError::SessionTaken(self.port));
104 }
105 outcome => outcome?,
106 };
107 send(&commands, "session.subscribe", json!({"events": EVENTS})).await?;
108 let open = Connection { commands, events };
109 let value = read(&open);
110 *connection = Some(open);
111 Ok(value)
112 }
113
114 pub async fn contexts(&self) -> Result<Vec<Context>, BrowserError> {
115 let tree = self
116 .call("browsingContext.getTree", json!({"maxDepth": 0}))
117 .await?;
118 Ok(contexts_of(&tree))
119 }
120
121 pub async fn tabs(&self) -> Result<Vec<Tab>, BrowserError> {
122 Ok(self
123 .contexts()
124 .await?
125 .into_iter()
126 .map(|context| targets::tab_from_url(context.id, &context.url))
127 .collect())
128 }
129
130 /// Evaluates `expression` in the tab and answers its value as JSON.
131 pub async fn evaluate(&self, context: &str, expression: &str) -> Result<Value, BrowserError> {
132 let params = json!({
133 "expression": expression,
134 "target": {"context": context},
135 "awaitPromise": true,
136 "resultOwnership": "none",
137 });
138 let result = self.call("script.evaluate", params).await?;
139 evaluation_value(&result).map_err(BrowserError::Cdp)
140 }
141
142 pub async fn navigate(&self, context: &str, url: &str) -> Result<(), BrowserError> {
143 let params = json!({"context": context, "url": url, "wait": "none"});
144 self.call("browsingContext.navigate", params)
145 .await
146 .map(drop)
147 }
148
149 pub async fn open_tab(&self, url: &str) -> Result<(), BrowserError> {
150 let created = self
151 .call("browsingContext.create", json!({"type": "tab"}))
152 .await?;
153 let context = created["context"].as_str().unwrap_or_default().to_owned();
154 self.navigate(&context, url).await
155 }
156
157 pub async fn close_tab(&self, context: &str) -> Result<(), BrowserError> {
158 self.call("browsingContext.close", json!({"context": context}))
159 .await
160 .map(drop)
161 }
162 }
163
164 async fn send(
165 commands: &mpsc::UnboundedSender<Call>,
166 method: &str,
167 params: Value,
168 ) -> Result<Value, BrowserError> {
169 let (reply, answer) = oneshot::channel();
170 let closed = || BrowserError::Cdp(format!("{method}: BiDi connection closed"));
171 commands
172 .send(Call {
173 method: method.to_owned(),
174 params,
175 reply,
176 })
177 .map_err(|_| closed())?;
178 answer.await.map_err(|_| closed())?
179 }
180
181 async fn pump<S>(
182 mut stream: S,
183 mut commands: mpsc::UnboundedReceiver<Call>,
184 events: broadcast::Sender<Event>,
185 ) where
186 S: futures_util::Stream<Item = Result<Message, tokio_tungstenite::tungstenite::Error>>
187 + futures_util::Sink<Message>
188 + Unpin,
189 {
190 let mut pending: HashMap<u64, (String, oneshot::Sender<Result<Value, BrowserError>>)> =
191 HashMap::new();
192 let mut next_id: u64 = 1;
193 loop {
194 tokio::select! {
195 call = commands.recv() => {
196 let Some(call) = call else { break };
197 let id = next_id;
198 next_id += 1;
199 let frame = json!({"id": id, "method": call.method, "params": call.params});
200 if stream.send(Message::text(frame.to_string())).await.is_err() {
201 let _ = call.reply.send(Err(BrowserError::Cdp("BiDi send failed".into())));
202 break;
203 }
204 pending.insert(id, (call.method, call.reply));
205 }
206 message = stream.next() => {
207 let Some(Ok(message)) = message else { break };
208 let Message::Text(text) = message else {
209 if matches!(message, Message::Close(_)) {
210 break;
211 }
212 continue;
213 };
214 let Ok(frame) = serde_json::from_str::<Value>(text.as_str()) else { continue };
215 if let Some(id) = frame.get("id").and_then(Value::as_u64) {
216 if let Some((method, reply)) = pending.remove(&id) {
217 let _ = reply.send(answer_of(&method, &frame));
218 }
219 } else if frame["type"] == "event" {
220 let _ = events.send(json!({"method": frame["method"], "params": frame["params"]}));
221 }
222 }
223 }
224 }
225 for (method, reply) in pending.into_values() {
226 let _ = reply.send(Err(BrowserError::Cdp(format!(
227 "{method}: BiDi connection closed"
228 ))));
229 }
230 }
231
232 fn answer_of(method: &str, frame: &Value) -> Result<Value, BrowserError> {
233 if frame["type"] == "error" {
234 let error = frame["error"].as_str().unwrap_or("error");
235 let message = frame["message"].as_str().unwrap_or_default();
236 return Err(BrowserError::Cdp(format!("{method}: {error}: {message}")));
237 }
238 Ok(frame.get("result").cloned().unwrap_or(Value::Null))
239 }
240
241 pub(crate) fn contexts_of(tree: &Value) -> Vec<Context> {
242 tree["contexts"]
243 .as_array()
244 .into_iter()
245 .flatten()
246 .filter_map(|context| {
247 Some(Context {
248 id: context["context"].as_str()?.to_owned(),
249 url: context["url"].as_str().unwrap_or_default().to_owned(),
250 })
251 })
252 .collect()
253 }
254
255 /// The value of a `script.evaluate` result, or the exception text.
256 pub fn evaluation_value(result: &Value) -> Result<Value, String> {
257 if result["type"] == "exception" {
258 let text = result
259 .pointer("/exceptionDetails/text")
260 .and_then(Value::as_str)
261 .unwrap_or("unknown");
262 return Err(text.to_owned());
263 }
264 Ok(remote_value_to_json(&result["result"]))
265 }
266
267 /// Turns a BiDi remote value into the JSON CDP's `returnByValue` would give. Values JSON cannot
268 /// hold (NaN, functions, nodes) become null.
269 pub fn remote_value_to_json(remote: &Value) -> Value {
270 let value = &remote["value"];
271 match remote["type"].as_str().unwrap_or_default() {
272 "string" | "boolean" => value.clone(),
273 "number" if value.is_number() => value.clone(),
274 "number" if value == "-0" => json!(0),
275 "bigint" | "date" => value.clone(),
276 "array" | "set" => Value::Array(
277 value
278 .as_array()
279 .into_iter()
280 .flatten()
281 .map(remote_value_to_json)
282 .collect(),
283 ),
284 "object" | "map" => Value::Object(
285 value
286 .as_array()
287 .into_iter()
288 .flatten()
289 .filter_map(|pair| {
290 let key = match &pair[0] {
291 Value::String(key) => key.clone(),
292 other => remote_value_to_json(other).as_str()?.to_owned(),
293 };
294 Some((key, remote_value_to_json(&pair[1])))
295 })
296 .collect::<Map<String, Value>>(),
297 ),
298 _ => Value::Null,
299 }
300 }
301
302 #[cfg(test)]
303 mod tests {
304 use super::*;
305
306 #[test]
307 fn remote_values_become_plain_json() {
308 let remote = json!({"type": "object", "value": [
309 ["a", {"type": "array", "value": [
310 {"type": "number", "value": 1},
311 {"type": "number", "value": "NaN"},
312 {"type": "undefined"},
313 {"type": "string", "value": "x"},
314 ]}],
315 ["b", {"type": "object", "value": [["c", {"type": "boolean", "value": true}]]}],
316 ["d", {"type": "null"}],
317 ["e", {"type": "function"}],
318 ]});
319 assert_eq!(
320 remote_value_to_json(&remote),
321 json!({"a": [1, null, null, "x"], "b": {"c": true}, "d": null, "e": null})
322 );
323 }
324
325 #[test]
326 fn evaluation_answers_value_or_exception_text() {
327 let success = json!({"type": "success", "result": {"type": "number", "value": 2}});
328 assert_eq!(evaluation_value(&success), Ok(json!(2)));
329 let exception = json!({"type": "exception", "exceptionDetails": {"text": "Error: boom"}});
330 assert_eq!(evaluation_value(&exception), Err("Error: boom".to_owned()));
331 }
332
333 #[test]
334 fn reads_top_level_contexts() {
335 let tree = json!({"contexts": [
336 {"context": "a", "url": "about:blank", "children": []},
337 {"context": "b", "url": "https://teams.cloud.microsoft/", "children": []},
338 ]});
339 assert_eq!(
340 contexts_of(&tree),
341 [
342 Context {
343 id: "a".into(),
344 url: "about:blank".into()
345 },
346 Context {
347 id: "b".into(),
348 url: "https://teams.cloud.microsoft/".into()
349 },
350 ]
351 );
352 }
353 }
@@ -0,0 +1,353 @@
1//! One WebDriver BiDi session for the whole app. Firefox allows a single session per browser and
2//! keeps it after the socket closes, so every caller shares this connection.
3
4use std::collections::HashMap;
5use std::sync::Arc;
6use std::time::Duration;
7
8use futures_util::{SinkExt, StreamExt};
9use serde_json::{Map, Value, json};
10use tokio::sync::{Mutex, broadcast, mpsc, oneshot};
11use tokio_tungstenite::tungstenite::Message;
12
13use crate::error::BrowserError;
14use crate::targets::{self, Tab};
15
16const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
17const EVENT_BUFFER: usize = 1024;
18/// Subscribed once per session; tab channels filter by context.
19const EVENTS: [&str; 2] = ["script.message", "browsingContext.load"];
20
21struct Call {
22 method: String,
23 params: Value,
24 reply: oneshot::Sender<Result<Value, BrowserError>>,
25}
26
27/// A BiDi event as `{method, params}`.
28pub type Event = Value;
29
30#[derive(Clone)]
31pub struct Bidi {
32 port: u16,
33 connection: Arc<Mutex<Option<Connection>>>,
34}
35
36struct Connection {
37 commands: mpsc::UnboundedSender<Call>,
38 /// Kept only to hand out receivers. The pump owns the sender, so receivers close with the socket.
39 events: broadcast::Receiver<Event>,
40}
41
42/// A top-level browsing context, the BiDi word for a tab.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct Context {
45 pub id: String,
46 pub url: String,
47}
48
49impl Bidi {
50 pub fn new(port: u16) -> Bidi {
51 Bidi {
52 port,
53 connection: Arc::new(Mutex::new(None)),
54 }
55 }
56
57 /// Events of every tab on the current connection, from the moment of the call. The stream
58 /// ends when the connection does, for example when the browser restarts.
59 pub async fn events(&self) -> Result<broadcast::Receiver<Event>, BrowserError> {
60 self.connected(|connection| connection.events.resubscribe())
61 .await
62 }
63
64 pub async fn call(&self, method: &str, params: Value) -> Result<Value, BrowserError> {
65 let commands = self
66 .connected(|connection| connection.commands.clone())
67 .await?;
68 send(&commands, method, params).await
69 }
70
71 /// Opens the session if there is none. [`BrowserError::SessionTaken`] when a session another
72 /// process left behind blocks it: only a browser restart frees that.
73 pub async fn connect(&self) -> Result<(), BrowserError> {
74 self.connected(|_| ()).await
75 }
76
77 async fn connected<T>(&self, read: impl FnOnce(&Connection) -> T) -> Result<T, BrowserError> {
78 let mut connection = self.connection.lock().await;
79 if let Some(open) = connection
80 .as_ref()
81 .filter(|open| !open.commands.is_closed())
82 {
83 return Ok(read(open));
84 }
85 *connection = None;
86 let url = format!("ws://127.0.0.1:{}/session", self.port);
87 let (stream, _) =
88 tokio::time::timeout(CONNECT_TIMEOUT, tokio_tungstenite::connect_async(&url))
89 .await
90 .map_err(|_| BrowserError::NoBrowser(format!("{url}: connect timed out")))?
91 .map_err(|error| BrowserError::NoBrowser(format!("{url}: {error}")))?;
92 let (commands, receiver) = mpsc::unbounded_channel();
93 let (events_sender, events) = broadcast::channel(EVENT_BUFFER);
94 tokio::spawn(pump(stream, receiver, events_sender));
95 let opened = tokio::time::timeout(
96 CONNECT_TIMEOUT,
97 send(&commands, "session.new", json!({"capabilities": {}})),
98 )
99 .await
100 .map_err(|_| BrowserError::Cdp("session.new timed out".into()))?;
101 match opened {
102 Err(BrowserError::Cdp(text)) if text.contains("session not created") => {
103 return Err(BrowserError::SessionTaken(self.port));
104 }
105 outcome => outcome?,
106 };
107 send(&commands, "session.subscribe", json!({"events": EVENTS})).await?;
108 let open = Connection { commands, events };
109 let value = read(&open);
110 *connection = Some(open);
111 Ok(value)
112 }
113
114 pub async fn contexts(&self) -> Result<Vec<Context>, BrowserError> {
115 let tree = self
116 .call("browsingContext.getTree", json!({"maxDepth": 0}))
117 .await?;
118 Ok(contexts_of(&tree))
119 }
120
121 pub async fn tabs(&self) -> Result<Vec<Tab>, BrowserError> {
122 Ok(self
123 .contexts()
124 .await?
125 .into_iter()
126 .map(|context| targets::tab_from_url(context.id, &context.url))
127 .collect())
128 }
129
130 /// Evaluates `expression` in the tab and answers its value as JSON.
131 pub async fn evaluate(&self, context: &str, expression: &str) -> Result<Value, BrowserError> {
132 let params = json!({
133 "expression": expression,
134 "target": {"context": context},
135 "awaitPromise": true,
136 "resultOwnership": "none",
137 });
138 let result = self.call("script.evaluate", params).await?;
139 evaluation_value(&result).map_err(BrowserError::Cdp)
140 }
141
142 pub async fn navigate(&self, context: &str, url: &str) -> Result<(), BrowserError> {
143 let params = json!({"context": context, "url": url, "wait": "none"});
144 self.call("browsingContext.navigate", params)
145 .await
146 .map(drop)
147 }
148
149 pub async fn open_tab(&self, url: &str) -> Result<(), BrowserError> {
150 let created = self
151 .call("browsingContext.create", json!({"type": "tab"}))
152 .await?;
153 let context = created["context"].as_str().unwrap_or_default().to_owned();
154 self.navigate(&context, url).await
155 }
156
157 pub async fn close_tab(&self, context: &str) -> Result<(), BrowserError> {
158 self.call("browsingContext.close", json!({"context": context}))
159 .await
160 .map(drop)
161 }
162}
163
164async fn send(
165 commands: &mpsc::UnboundedSender<Call>,
166 method: &str,
167 params: Value,
168) -> Result<Value, BrowserError> {
169 let (reply, answer) = oneshot::channel();
170 let closed = || BrowserError::Cdp(format!("{method}: BiDi connection closed"));
171 commands
172 .send(Call {
173 method: method.to_owned(),
174 params,
175 reply,
176 })
177 .map_err(|_| closed())?;
178 answer.await.map_err(|_| closed())?
179}
180
181async fn pump<S>(
182 mut stream: S,
183 mut commands: mpsc::UnboundedReceiver<Call>,
184 events: broadcast::Sender<Event>,
185) where
186 S: futures_util::Stream<Item = Result<Message, tokio_tungstenite::tungstenite::Error>>
187 + futures_util::Sink<Message>
188 + Unpin,
189{
190 let mut pending: HashMap<u64, (String, oneshot::Sender<Result<Value, BrowserError>>)> =
191 HashMap::new();
192 let mut next_id: u64 = 1;
193 loop {
194 tokio::select! {
195 call = commands.recv() => {
196 let Some(call) = call else { break };
197 let id = next_id;
198 next_id += 1;
199 let frame = json!({"id": id, "method": call.method, "params": call.params});
200 if stream.send(Message::text(frame.to_string())).await.is_err() {
201 let _ = call.reply.send(Err(BrowserError::Cdp("BiDi send failed".into())));
202 break;
203 }
204 pending.insert(id, (call.method, call.reply));
205 }
206 message = stream.next() => {
207 let Some(Ok(message)) = message else { break };
208 let Message::Text(text) = message else {
209 if matches!(message, Message::Close(_)) {
210 break;
211 }
212 continue;
213 };
214 let Ok(frame) = serde_json::from_str::<Value>(text.as_str()) else { continue };
215 if let Some(id) = frame.get("id").and_then(Value::as_u64) {
216 if let Some((method, reply)) = pending.remove(&id) {
217 let _ = reply.send(answer_of(&method, &frame));
218 }
219 } else if frame["type"] == "event" {
220 let _ = events.send(json!({"method": frame["method"], "params": frame["params"]}));
221 }
222 }
223 }
224 }
225 for (method, reply) in pending.into_values() {
226 let _ = reply.send(Err(BrowserError::Cdp(format!(
227 "{method}: BiDi connection closed"
228 ))));
229 }
230}
231
232fn answer_of(method: &str, frame: &Value) -> Result<Value, BrowserError> {
233 if frame["type"] == "error" {
234 let error = frame["error"].as_str().unwrap_or("error");
235 let message = frame["message"].as_str().unwrap_or_default();
236 return Err(BrowserError::Cdp(format!("{method}: {error}: {message}")));
237 }
238 Ok(frame.get("result").cloned().unwrap_or(Value::Null))
239}
240
241pub(crate) fn contexts_of(tree: &Value) -> Vec<Context> {
242 tree["contexts"]
243 .as_array()
244 .into_iter()
245 .flatten()
246 .filter_map(|context| {
247 Some(Context {
248 id: context["context"].as_str()?.to_owned(),
249 url: context["url"].as_str().unwrap_or_default().to_owned(),
250 })
251 })
252 .collect()
253}
254
255/// The value of a `script.evaluate` result, or the exception text.
256pub fn evaluation_value(result: &Value) -> Result<Value, String> {
257 if result["type"] == "exception" {
258 let text = result
259 .pointer("/exceptionDetails/text")
260 .and_then(Value::as_str)
261 .unwrap_or("unknown");
262 return Err(text.to_owned());
263 }
264 Ok(remote_value_to_json(&result["result"]))
265}
266
267/// Turns a BiDi remote value into the JSON CDP's `returnByValue` would give. Values JSON cannot
268/// hold (NaN, functions, nodes) become null.
269pub fn remote_value_to_json(remote: &Value) -> Value {
270 let value = &remote["value"];
271 match remote["type"].as_str().unwrap_or_default() {
272 "string" | "boolean" => value.clone(),
273 "number" if value.is_number() => value.clone(),
274 "number" if value == "-0" => json!(0),
275 "bigint" | "date" => value.clone(),
276 "array" | "set" => Value::Array(
277 value
278 .as_array()
279 .into_iter()
280 .flatten()
281 .map(remote_value_to_json)
282 .collect(),
283 ),
284 "object" | "map" => Value::Object(
285 value
286 .as_array()
287 .into_iter()
288 .flatten()
289 .filter_map(|pair| {
290 let key = match &pair[0] {
291 Value::String(key) => key.clone(),
292 other => remote_value_to_json(other).as_str()?.to_owned(),
293 };
294 Some((key, remote_value_to_json(&pair[1])))
295 })
296 .collect::<Map<String, Value>>(),
297 ),
298 _ => Value::Null,
299 }
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305
306 #[test]
307 fn remote_values_become_plain_json() {
308 let remote = json!({"type": "object", "value": [
309 ["a", {"type": "array", "value": [
310 {"type": "number", "value": 1},
311 {"type": "number", "value": "NaN"},
312 {"type": "undefined"},
313 {"type": "string", "value": "x"},
314 ]}],
315 ["b", {"type": "object", "value": [["c", {"type": "boolean", "value": true}]]}],
316 ["d", {"type": "null"}],
317 ["e", {"type": "function"}],
318 ]});
319 assert_eq!(
320 remote_value_to_json(&remote),
321 json!({"a": [1, null, null, "x"], "b": {"c": true}, "d": null, "e": null})
322 );
323 }
324
325 #[test]
326 fn evaluation_answers_value_or_exception_text() {
327 let success = json!({"type": "success", "result": {"type": "number", "value": 2}});
328 assert_eq!(evaluation_value(&success), Ok(json!(2)));
329 let exception = json!({"type": "exception", "exceptionDetails": {"text": "Error: boom"}});
330 assert_eq!(evaluation_value(&exception), Err("Error: boom".to_owned()));
331 }
332
333 #[test]
334 fn reads_top_level_contexts() {
335 let tree = json!({"contexts": [
336 {"context": "a", "url": "about:blank", "children": []},
337 {"context": "b", "url": "https://teams.cloud.microsoft/", "children": []},
338 ]});
339 assert_eq!(
340 contexts_of(&tree),
341 [
342 Context {
343 id: "a".into(),
344 url: "about:blank".into()
345 },
346 Context {
347 id: "b".into(),
348 url: "https://teams.cloud.microsoft/".into()
349 },
350 ]
351 );
352 }
353}
crates/browser/src/bidi_transport.rs added +368 −0
@@ -0,0 +1,368 @@
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.origins().iter().any(|origin| url.starts_with(origin))
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 check(&self) -> BoxFuture<'_, Result<()>> {
71 Box::pin(async move { self.contexts().await.map(drop) })
72 }
73
74 fn open(&self, app: App, with_events: bool) -> BoxFuture<'_, Result<Option<OpenedTab>>> {
75 Box::pin(async move {
76 let Some(context) = self.app_context(app).await? else {
77 return Ok(None);
78 };
79 let events = match with_events {
80 true => Some(self.bidi.events().await.map_err(no_browser)?),
81 false => None,
82 };
83 let channel = TabChannel::new(with_events);
84 tokio::spawn(serve(
85 self.bidi.clone(),
86 context.id,
87 channel.commands,
88 events,
89 channel.event_sink,
90 ));
91 Ok(Some((channel.control, channel.events)))
92 })
93 }
94
95 fn wake(&self, app: App) -> BoxFuture<'_, Result<()>> {
96 Box::pin(async move {
97 let Some(context) = self.app_context(app).await? else {
98 return Ok(());
99 };
100 if app.is_park_url(&context.url) {
101 self.bidi.navigate(&context.id, app.start_url()).await
102 } else {
103 let params = json!({"context": context.id, "wait": "none"});
104 self.bidi
105 .call("browsingContext.reload", params)
106 .await
107 .map(drop)
108 }
109 .map_err(protocol)
110 })
111 }
112
113 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {
114 Box::pin(async move {
115 let contexts = self.contexts().await?;
116 Ok(Diagnosis {
117 login_pending: contexts.iter().any(|context| is_login_url(&context.url)),
118 app_tab_open: App::ALL
119 .iter()
120 .any(|&app| contexts.iter().any(|context| is_app_url(app, &context.url))),
121 })
122 })
123 }
124 }
125
126 /// What one tab channel registered, so it can map messages back and clean up after itself:
127 /// unlike CDP, BiDi keeps preload scripts after the channel is gone.
128 #[derive(Default)]
129 struct ChannelState {
130 /// BiDi channel id to the CDP binding name.
131 bindings: HashMap<String, String>,
132 scripts: HashSet<String>,
133 }
134
135 type Shared = Arc<Mutex<ChannelState>>;
136
137 async fn serve(
138 bidi: Bidi,
139 context: String,
140 mut commands: mpsc::UnboundedReceiver<TabCommand>,
141 mut events: Option<broadcast::Receiver<Event>>,
142 sink: Option<mpsc::UnboundedSender<TabEvent>>,
143 ) {
144 let state = Shared::default();
145 let mut commands_open = true;
146 loop {
147 tokio::select! {
148 command = commands.recv(), if commands_open => match command {
149 Some(command) => {
150 let (bidi, context, state) = (bidi.clone(), context.clone(), state.clone());
151 tokio::spawn(async move {
152 let outcome =
153 translate(&bidi, &context, &state, &command.method, &command.params).await;
154 command.respond(outcome);
155 });
156 }
157 None if sink.is_none() => break,
158 None => commands_open = false,
159 },
160 event = next_event(&mut events) => match event {
161 Ok(event) => {
162 let Some(sink) = &sink else { break };
163 let mapped = tab_event(&context, &state.lock().expect("channel state").bindings, &event);
164 if let Some(mapped) = mapped
165 && sink.send(mapped).is_err()
166 {
167 break;
168 }
169 }
170 Err(broadcast::error::RecvError::Lagged(_)) => {}
171 Err(broadcast::error::RecvError::Closed) => break,
172 },
173 _ = sink_closed(&sink) => break,
174 }
175 }
176 let scripts = std::mem::take(&mut state.lock().expect("channel state").scripts);
177 for script in scripts {
178 let _ = bidi
179 .call("script.removePreloadScript", json!({"script": script}))
180 .await;
181 }
182 }
183
184 async fn next_event(
185 events: &mut Option<broadcast::Receiver<Event>>,
186 ) -> std::result::Result<Event, broadcast::error::RecvError> {
187 match events {
188 Some(receiver) => receiver.recv().await,
189 None => std::future::pending().await,
190 }
191 }
192
193 async fn sink_closed(sink: &Option<mpsc::UnboundedSender<TabEvent>>) {
194 match sink {
195 Some(sink) => sink.closed().await,
196 None => std::future::pending().await,
197 }
198 }
199
200 /// A function that installs `name` on the page as a binding that posts to its channel argument.
201 fn binding_declaration(name: &str) -> String {
202 let name = Value::from(name);
203 format!("(send) => {{ globalThis[{name}] = (payload) => send(String(payload)); }}")
204 }
205
206 async fn translate(
207 bidi: &Bidi,
208 context: &str,
209 state: &Shared,
210 method: &str,
211 params: &Value,
212 ) -> Result<Value> {
213 let text = |key: &str| params[key].as_str().unwrap_or_default();
214 match method {
215 "Runtime.enable" | "Runtime.disable" | "Page.enable" | "Page.disable" => Ok(json!({})),
216 "Runtime.evaluate" => {
217 let request = json!({
218 "expression": text("expression"),
219 "target": {"context": context},
220 "awaitPromise": params["awaitPromise"].as_bool().unwrap_or(false),
221 "resultOwnership": "none",
222 });
223 let result = bidi
224 .call("script.evaluate", request)
225 .await
226 .map_err(protocol)?;
227 Ok(match evaluation_value(&result) {
228 Ok(value) => json!({"result": {"value": value}}),
229 Err(text) => json!({"exceptionDetails": {"text": text}}),
230 })
231 }
232 "Runtime.addBinding" => {
233 let name = text("name");
234 let channel = format!("{name}#{}", NEXT_CHANNEL.fetch_add(1, Ordering::Relaxed));
235 let declaration = binding_declaration(name);
236 let arguments = json!([{"type": "channel", "value": {"channel": channel}}]);
237 state
238 .lock()
239 .expect("channel state")
240 .bindings
241 .insert(channel, name.to_owned());
242 let preload = json!({
243 "functionDeclaration": declaration,
244 "arguments": arguments,
245 "contexts": [context],
246 });
247 add_preload(bidi, state, preload).await?;
248 let now = json!({
249 "functionDeclaration": declaration,
250 "arguments": arguments,
251 "target": {"context": context},
252 "awaitPromise": false,
253 });
254 bidi.call("script.callFunction", now)
255 .await
256 .map_err(protocol)?;
257 Ok(json!({}))
258 }
259 "Page.addScriptToEvaluateOnNewDocument" => {
260 let preload = json!({
261 "functionDeclaration": format!("() => {{\n{}\n}}", text("source")),
262 "contexts": [context],
263 });
264 let identifier = add_preload(bidi, state, preload).await?;
265 Ok(json!({"identifier": identifier}))
266 }
267 "Page.removeScriptToEvaluateOnNewDocument" => {
268 let script = text("identifier");
269 state.lock().expect("channel state").scripts.remove(script);
270 bidi.call("script.removePreloadScript", json!({"script": script}))
271 .await
272 .map(|_| json!({}))
273 .map_err(protocol)
274 }
275 "Page.navigate" => bidi
276 .navigate(context, text("url"))
277 .await
278 .map(|_| json!({}))
279 .map_err(protocol),
280 "Page.reload" => bidi
281 .call(
282 "browsingContext.reload",
283 json!({"context": context, "wait": "none"}),
284 )
285 .await
286 .map(|_| json!({}))
287 .map_err(protocol),
288 other => Err(Error::Cdp(format!(
289 "{other} is not available over WebDriver BiDi"
290 ))),
291 }
292 }
293
294 async fn add_preload(bidi: &Bidi, state: &Shared, params: Value) -> Result<String> {
295 let added = bidi
296 .call("script.addPreloadScript", params)
297 .await
298 .map_err(protocol)?;
299 let script = added["script"].as_str().unwrap_or_default().to_owned();
300 state
301 .lock()
302 .expect("channel state")
303 .scripts
304 .insert(script.clone());
305 Ok(script)
306 }
307
308 /// The CDP event a BiDi event stands for in this tab. Binding calls match by channel, so they also
309 /// arrive from the tab's frames, as CDP bindings do.
310 fn tab_event(context: &str, bindings: &HashMap<String, String>, event: &Event) -> Option<TabEvent> {
311 let params = &event["params"];
312 match event["method"].as_str()? {
313 "script.message" => {
314 let name = bindings.get(params["channel"].as_str()?)?;
315 let payload = params.pointer("/data/value")?.as_str()?;
316 Some(TabEvent {
317 method: "Runtime.bindingCalled".into(),
318 params: json!({"name": name, "payload": payload}),
319 })
320 }
321 "browsingContext.load" if params["context"] == context => Some(TabEvent {
322 method: "Page.frameNavigated".into(),
323 params: json!({"frame": {"id": context, "url": params["url"]}}),
324 }),
325 _ => None,
326 }
327 }
328
329 #[cfg(test)]
330 mod tests {
331 use super::*;
332
333 fn bindings() -> HashMap<String, String> {
334 HashMap::from([("sink#1".to_owned(), "sink".to_owned())])
335 }
336
337 #[test]
338 fn channel_messages_become_binding_calls() {
339 let message = json!({"method": "script.message", "params": {
340 "channel": "sink#1",
341 "data": {"type": "string", "value": "{\"a\":1}"},
342 "source": {"context": "frame"},
343 }});
344 let event = tab_event("tab", &bindings(), &message).unwrap();
345 assert_eq!(event.binding_payload("sink"), Some("{\"a\":1}"));
346 let foreign = json!({"method": "script.message", "params": {
347 "channel": "other#2", "data": {"type": "string", "value": "x"},
348 }});
349 assert!(tab_event("tab", &bindings(), &foreign).is_none());
350 }
351
352 #[test]
353 fn only_this_tabs_load_is_a_main_frame_navigation() {
354 let load = |context: &str| json!({"method": "browsingContext.load", "params": {"context": context, "url": "https://teams.cloud.microsoft/"}});
355 let event = tab_event("tab", &bindings(), &load("tab")).unwrap();
356 assert_eq!(event.method, "Page.frameNavigated");
357 assert!(event.params.pointer("/frame/parentId").is_none());
358 assert!(tab_event("tab", &bindings(), &load("other")).is_none());
359 }
360
361 #[test]
362 fn binding_declaration_quotes_the_name() {
363 assert_eq!(
364 binding_declaration("a'b"),
365 r#"(send) => { globalThis["a'b"] = (payload) => send(String(payload)); }"#
366 );
367 }
368 }
@@ -0,0 +1,368 @@
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
5use std::collections::{HashMap, HashSet};
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::sync::{Arc, Mutex};
8
9use serde_json::{Value, json};
10use session::{
11 App, BoxFuture, Diagnosis, Error, OpenedTab, Result, TabChannel, TabCommand, TabEvent,
12 Transport, is_login_url,
13};
14use tokio::sync::{broadcast, mpsc};
15
16use crate::bidi::{Bidi, Context, Event, evaluation_value};
17use crate::browser::Browser;
18use crate::error::BrowserError;
19
20const ENDPOINT_NAME: &str = "WebDriver BiDi";
21
22static NEXT_CHANNEL: AtomicU64 = AtomicU64::new(1);
23
24/// The transport that fits the browser: BiDi for Firefox, the CDP endpoint otherwise.
25pub 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
32pub struct BidiTransport {
33 bidi: Bidi,
34}
35
36impl 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
54fn is_app_url(app: App, url: &str) -> bool {
55 app.origins().iter().any(|origin| url.starts_with(origin))
56}
57
58fn no_browser(error: BrowserError) -> Error {
59 Error::NoBrowser {
60 endpoint: ENDPOINT_NAME.into(),
61 reason: error.to_string(),
62 }
63}
64
65fn protocol(error: BrowserError) -> Error {
66 Error::Cdp(error.to_string())
67}
68
69impl Transport for BidiTransport {
70 fn check(&self) -> BoxFuture<'_, Result<()>> {
71 Box::pin(async move { self.contexts().await.map(drop) })
72 }
73
74 fn open(&self, app: App, with_events: bool) -> BoxFuture<'_, Result<Option<OpenedTab>>> {
75 Box::pin(async move {
76 let Some(context) = self.app_context(app).await? else {
77 return Ok(None);
78 };
79 let events = match with_events {
80 true => Some(self.bidi.events().await.map_err(no_browser)?),
81 false => None,
82 };
83 let channel = TabChannel::new(with_events);
84 tokio::spawn(serve(
85 self.bidi.clone(),
86 context.id,
87 channel.commands,
88 events,
89 channel.event_sink,
90 ));
91 Ok(Some((channel.control, channel.events)))
92 })
93 }
94
95 fn wake(&self, app: App) -> BoxFuture<'_, Result<()>> {
96 Box::pin(async move {
97 let Some(context) = self.app_context(app).await? else {
98 return Ok(());
99 };
100 if app.is_park_url(&context.url) {
101 self.bidi.navigate(&context.id, app.start_url()).await
102 } else {
103 let params = json!({"context": context.id, "wait": "none"});
104 self.bidi
105 .call("browsingContext.reload", params)
106 .await
107 .map(drop)
108 }
109 .map_err(protocol)
110 })
111 }
112
113 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {
114 Box::pin(async move {
115 let contexts = self.contexts().await?;
116 Ok(Diagnosis {
117 login_pending: contexts.iter().any(|context| is_login_url(&context.url)),
118 app_tab_open: App::ALL
119 .iter()
120 .any(|&app| contexts.iter().any(|context| is_app_url(app, &context.url))),
121 })
122 })
123 }
124}
125
126/// What one tab channel registered, so it can map messages back and clean up after itself:
127/// unlike CDP, BiDi keeps preload scripts after the channel is gone.
128#[derive(Default)]
129struct ChannelState {
130 /// BiDi channel id to the CDP binding name.
131 bindings: HashMap<String, String>,
132 scripts: HashSet<String>,
133}
134
135type Shared = Arc<Mutex<ChannelState>>;
136
137async fn serve(
138 bidi: Bidi,
139 context: String,
140 mut commands: mpsc::UnboundedReceiver<TabCommand>,
141 mut events: Option<broadcast::Receiver<Event>>,
142 sink: Option<mpsc::UnboundedSender<TabEvent>>,
143) {
144 let state = Shared::default();
145 let mut commands_open = true;
146 loop {
147 tokio::select! {
148 command = commands.recv(), if commands_open => match command {
149 Some(command) => {
150 let (bidi, context, state) = (bidi.clone(), context.clone(), state.clone());
151 tokio::spawn(async move {
152 let outcome =
153 translate(&bidi, &context, &state, &command.method, &command.params).await;
154 command.respond(outcome);
155 });
156 }
157 None if sink.is_none() => break,
158 None => commands_open = false,
159 },
160 event = next_event(&mut events) => match event {
161 Ok(event) => {
162 let Some(sink) = &sink else { break };
163 let mapped = tab_event(&context, &state.lock().expect("channel state").bindings, &event);
164 if let Some(mapped) = mapped
165 && sink.send(mapped).is_err()
166 {
167 break;
168 }
169 }
170 Err(broadcast::error::RecvError::Lagged(_)) => {}
171 Err(broadcast::error::RecvError::Closed) => break,
172 },
173 _ = sink_closed(&sink) => break,
174 }
175 }
176 let scripts = std::mem::take(&mut state.lock().expect("channel state").scripts);
177 for script in scripts {
178 let _ = bidi
179 .call("script.removePreloadScript", json!({"script": script}))
180 .await;
181 }
182}
183
184async fn next_event(
185 events: &mut Option<broadcast::Receiver<Event>>,
186) -> std::result::Result<Event, broadcast::error::RecvError> {
187 match events {
188 Some(receiver) => receiver.recv().await,
189 None => std::future::pending().await,
190 }
191}
192
193async fn sink_closed(sink: &Option<mpsc::UnboundedSender<TabEvent>>) {
194 match sink {
195 Some(sink) => sink.closed().await,
196 None => std::future::pending().await,
197 }
198}
199
200/// A function that installs `name` on the page as a binding that posts to its channel argument.
201fn binding_declaration(name: &str) -> String {
202 let name = Value::from(name);
203 format!("(send) => {{ globalThis[{name}] = (payload) => send(String(payload)); }}")
204}
205
206async fn translate(
207 bidi: &Bidi,
208 context: &str,
209 state: &Shared,
210 method: &str,
211 params: &Value,
212) -> Result<Value> {
213 let text = |key: &str| params[key].as_str().unwrap_or_default();
214 match method {
215 "Runtime.enable" | "Runtime.disable" | "Page.enable" | "Page.disable" => Ok(json!({})),
216 "Runtime.evaluate" => {
217 let request = json!({
218 "expression": text("expression"),
219 "target": {"context": context},
220 "awaitPromise": params["awaitPromise"].as_bool().unwrap_or(false),
221 "resultOwnership": "none",
222 });
223 let result = bidi
224 .call("script.evaluate", request)
225 .await
226 .map_err(protocol)?;
227 Ok(match evaluation_value(&result) {
228 Ok(value) => json!({"result": {"value": value}}),
229 Err(text) => json!({"exceptionDetails": {"text": text}}),
230 })
231 }
232 "Runtime.addBinding" => {
233 let name = text("name");
234 let channel = format!("{name}#{}", NEXT_CHANNEL.fetch_add(1, Ordering::Relaxed));
235 let declaration = binding_declaration(name);
236 let arguments = json!([{"type": "channel", "value": {"channel": channel}}]);
237 state
238 .lock()
239 .expect("channel state")
240 .bindings
241 .insert(channel, name.to_owned());
242 let preload = json!({
243 "functionDeclaration": declaration,
244 "arguments": arguments,
245 "contexts": [context],
246 });
247 add_preload(bidi, state, preload).await?;
248 let now = json!({
249 "functionDeclaration": declaration,
250 "arguments": arguments,
251 "target": {"context": context},
252 "awaitPromise": false,
253 });
254 bidi.call("script.callFunction", now)
255 .await
256 .map_err(protocol)?;
257 Ok(json!({}))
258 }
259 "Page.addScriptToEvaluateOnNewDocument" => {
260 let preload = json!({
261 "functionDeclaration": format!("() => {{\n{}\n}}", text("source")),
262 "contexts": [context],
263 });
264 let identifier = add_preload(bidi, state, preload).await?;
265 Ok(json!({"identifier": identifier}))
266 }
267 "Page.removeScriptToEvaluateOnNewDocument" => {
268 let script = text("identifier");
269 state.lock().expect("channel state").scripts.remove(script);
270 bidi.call("script.removePreloadScript", json!({"script": script}))
271 .await
272 .map(|_| json!({}))
273 .map_err(protocol)
274 }
275 "Page.navigate" => bidi
276 .navigate(context, text("url"))
277 .await
278 .map(|_| json!({}))
279 .map_err(protocol),
280 "Page.reload" => bidi
281 .call(
282 "browsingContext.reload",
283 json!({"context": context, "wait": "none"}),
284 )
285 .await
286 .map(|_| json!({}))
287 .map_err(protocol),
288 other => Err(Error::Cdp(format!(
289 "{other} is not available over WebDriver BiDi"
290 ))),
291 }
292}
293
294async fn add_preload(bidi: &Bidi, state: &Shared, params: Value) -> Result<String> {
295 let added = bidi
296 .call("script.addPreloadScript", params)
297 .await
298 .map_err(protocol)?;
299 let script = added["script"].as_str().unwrap_or_default().to_owned();
300 state
301 .lock()
302 .expect("channel state")
303 .scripts
304 .insert(script.clone());
305 Ok(script)
306}
307
308/// The CDP event a BiDi event stands for in this tab. Binding calls match by channel, so they also
309/// arrive from the tab's frames, as CDP bindings do.
310fn tab_event(context: &str, bindings: &HashMap<String, String>, event: &Event) -> Option<TabEvent> {
311 let params = &event["params"];
312 match event["method"].as_str()? {
313 "script.message" => {
314 let name = bindings.get(params["channel"].as_str()?)?;
315 let payload = params.pointer("/data/value")?.as_str()?;
316 Some(TabEvent {
317 method: "Runtime.bindingCalled".into(),
318 params: json!({"name": name, "payload": payload}),
319 })
320 }
321 "browsingContext.load" if params["context"] == context => Some(TabEvent {
322 method: "Page.frameNavigated".into(),
323 params: json!({"frame": {"id": context, "url": params["url"]}}),
324 }),
325 _ => None,
326 }
327}
328
329#[cfg(test)]
330mod tests {
331 use super::*;
332
333 fn bindings() -> HashMap<String, String> {
334 HashMap::from([("sink#1".to_owned(), "sink".to_owned())])
335 }
336
337 #[test]
338 fn channel_messages_become_binding_calls() {
339 let message = json!({"method": "script.message", "params": {
340 "channel": "sink#1",
341 "data": {"type": "string", "value": "{\"a\":1}"},
342 "source": {"context": "frame"},
343 }});
344 let event = tab_event("tab", &bindings(), &message).unwrap();
345 assert_eq!(event.binding_payload("sink"), Some("{\"a\":1}"));
346 let foreign = json!({"method": "script.message", "params": {
347 "channel": "other#2", "data": {"type": "string", "value": "x"},
348 }});
349 assert!(tab_event("tab", &bindings(), &foreign).is_none());
350 }
351
352 #[test]
353 fn only_this_tabs_load_is_a_main_frame_navigation() {
354 let load = |context: &str| json!({"method": "browsingContext.load", "params": {"context": context, "url": "https://teams.cloud.microsoft/"}});
355 let event = tab_event("tab", &bindings(), &load("tab")).unwrap();
356 assert_eq!(event.method, "Page.frameNavigated");
357 assert!(event.params.pointer("/frame/parentId").is_none());
358 assert!(tab_event("tab", &bindings(), &load("other")).is_none());
359 }
360
361 #[test]
362 fn binding_declaration_quotes_the_name() {
363 assert_eq!(
364 binding_declaration("a'b"),
365 r#"(send) => { globalThis["a'b"] = (payload) => send(String(payload)); }"#
366 );
367 }
368}
crates/browser/src/browser.rs +86 −8
@@ -8,7 +8,8 @@ use serde_json::{Value, json};
8 8 use tokio::sync::Mutex;
9 9 use tokio_tungstenite::tungstenite::Message;
10 10
11 use crate::config::Config;
11 use crate::bidi::Bidi;
12 use crate::config::{Config, Engine};
12 13 use crate::error::BrowserError;
13 14 use crate::http;
14 15 use crate::launch::{LaunchRequest, Launcher, SystemLauncher};
@@ -74,6 +75,8 @@ struct Inner {
74 75 timeouts: Timeouts,
75 76 operation: Mutex<()>,
76 77 wanted: AtomicBool,
78 /// Set for a Firefox browser, which speaks WebDriver BiDi instead of CDP.
79 bidi: Option<Bidi>,
77 80 }
78 81
79 82 #[derive(Clone)]
@@ -114,8 +117,10 @@ impl Browser {
114 117 launcher: Arc<dyn Launcher>,
115 118 timeouts: Timeouts,
116 119 ) -> Browser {
120 let bidi = (config.engine == Engine::Firefox).then(|| Bidi::new(config.port));
117 121 Browser {
118 122 inner: Arc::new(Inner {
123 bidi,
119 124 config,
120 125 launcher,
121 126 timeouts,
@@ -129,15 +134,20 @@ impl Browser {
129 134 &self.inner.config
130 135 }
131 136
137 /// The shared BiDi session of a Firefox browser; `None` for Chromium.
138 pub fn bidi(&self) -> Option<&Bidi> {
139 self.inner.bidi.as_ref()
140 }
141
132 142 pub async fn status(&self) -> Result<Status, BrowserError> {
133 let Some(_) = self.version().await else {
143 if !self.is_running().await {
134 144 return Ok(Status {
135 145 running: false,
136 146 mode: Mode::Visible,
137 147 tabs: Vec::new(),
138 148 login_state: LoginState::Unknown,
139 149 });
140 };
150 }
141 151 let tabs = self.tabs().await?;
142 152 Ok(Status {
143 153 running: true,
@@ -148,7 +158,12 @@ impl Browser {
148 158 }
149 159
150 160 pub async fn is_running(&self) -> bool {
151 self.version().await.is_some()
161 if self.inner.bidi.is_none() {
162 return self.version().await.is_some();
163 }
164 http::request(self.inner.config.port, "GET", "/", Duration::from_secs(2))
165 .await
166 .is_ok_and(|response| response.status == 200)
152 167 }
153 168
154 169 pub async fn probe_renderer(&self) -> RendererState {
@@ -158,6 +173,14 @@ impl Browser {
158 173 let Some(tab) = targets::app_tab(&tabs, App::Teams) else {
159 174 return RendererState::NoTab;
160 175 };
176 if let Some(bidi) = &self.inner.bidi {
177 let probe =
178 tokio::time::timeout(self.inner.timeouts.probe, bidi.evaluate(&tab.id, "1+1"));
179 return match probe.await {
180 Ok(Ok(_)) => RendererState::Ok,
181 _ => RendererState::Hung,
182 };
183 }
161 184 let url = format!(
162 185 "ws://127.0.0.1:{}/devtools/page/{}",
163 186 self.inner.config.port, tab.id
@@ -177,6 +200,9 @@ impl Browser {
177 200 }
178 201
179 202 pub async fn tabs(&self) -> Result<Vec<Tab>, BrowserError> {
203 if let Some(bidi) = &self.inner.bidi {
204 return bidi.tabs().await;
205 }
180 206 let response =
181 207 http::request(self.inner.config.port, "GET", "/json/list", HTTP_TIMEOUT).await?;
182 208 targets::parse_tabs(&response.body)
@@ -186,6 +212,7 @@ impl Browser {
186 212 let _guard = self.inner.operation.lock().await;
187 213 self.inner.wanted.store(true, Ordering::SeqCst);
188 214 if self.is_running().await {
215 self.adopt_session_locked().await?;
189 216 return self.ensure_tabs_locked().await;
190 217 }
191 218 match self.launch_locked(true).await {
@@ -208,6 +235,12 @@ impl Browser {
208 235 else {
209 236 return self.open_tab(app).await;
210 237 };
238 if let Some(bidi) = &self.inner.bidi {
239 let navigate = bidi.navigate(&tab.id, app.start_url());
240 return tokio::time::timeout(CDP_TIMEOUT, navigate)
241 .await
242 .map_err(|_| BrowserError::Cdp("browsingContext.navigate timed out".into()))?;
243 }
211 244 let url = format!(
212 245 "ws://127.0.0.1:{}/devtools/page/{}",
213 246 self.inner.config.port, tab.id
@@ -241,11 +274,18 @@ impl Browser {
241 274 if tab.parked {
242 275 return false;
243 276 }
277 let expression = "(() => { let access = false, refresh = false; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i) || ''; if (key.includes('accesstoken')) access = true; if (key.includes('refreshtoken')) refresh = true; } return access && refresh; })()";
278 if let Some(bidi) = &self.inner.bidi {
279 let evaluate = tokio::time::timeout(
280 self.inner.timeouts.probe,
281 bidi.evaluate(&tab.id, expression),
282 );
283 return matches!(evaluate.await, Ok(Ok(Value::Bool(true))));
284 }
244 285 let url = format!(
245 286 "ws://127.0.0.1:{}/devtools/page/{}",
246 287 self.inner.config.port, tab.id
247 288 );
248 let expression = "(() => { let access = false, refresh = false; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i) || ''; if (key.includes('accesstoken')) access = true; if (key.includes('refreshtoken')) refresh = true; } return access && refresh; })()";
249 289 let params = json!({ "expression": expression, "returnByValue": true });
250 290 cdp_call(&url, "Runtime.evaluate", params, self.inner.timeouts.probe)
251 291 .await
@@ -339,6 +379,12 @@ impl Browser {
339 379
340 380 async fn try_dedupe_app_tabs(&self) -> Result<(), BrowserError> {
341 381 let tabs = self.tabs().await?;
382 if let Some(bidi) = &self.inner.bidi {
383 for id in targets::closable_tab_ids(&tabs, &Default::default()) {
384 bidi.close_tab(&id).await?;
385 }
386 return Ok(());
387 }
342 388 let info = self
343 389 .version()
344 390 .await
@@ -359,6 +405,11 @@ impl Browser {
359 405 }
360 406
361 407 async fn open_tab(&self, app: App) -> Result<(), BrowserError> {
408 if let Some(bidi) = &self.inner.bidi {
409 return tokio::time::timeout(OPEN_TAB_TIMEOUT, bidi.open_tab(app.start_url()))
410 .await
411 .map_err(|_| BrowserError::Cdp("opening the app tab timed out".into()))?;
412 }
362 413 let path = format!("/json/new?{}", app.start_url());
363 414 let response =
364 415 http::request(self.inner.config.port, "PUT", &path, OPEN_TAB_TIMEOUT).await?;
@@ -427,11 +478,38 @@ impl Browser {
427 478 })
428 479 }
429 480
430 async fn stop_locked(&self, kill_fallback: bool) -> Result<(), BrowserError> {
431 let Some(info) = self.version().await else {
481 /// A Firefox that still holds the session of an earlier, crashed app run cannot be driven;
482 /// restart it so this process gets the session.
483 async fn adopt_session_locked(&self) -> Result<(), BrowserError> {
484 let Some(bidi) = &self.inner.bidi else {
432 485 return Ok(());
433 486 };
434 close_over_cdp(&info.websocket_url).await;
487 match bidi.connect().await {
488 Err(BrowserError::SessionTaken(_)) => {
489 self.stop_locked(true).await?;
490 self.launch_locked(true).await
491 }
492 outcome => outcome,
493 }
494 }
495
496 /// Asks the browser to quit: Chromium over CDP, Firefox with SIGTERM, which also works while
497 /// another process holds its BiDi session.
498 async fn close_gracefully(&self) {
499 if self.inner.bidi.is_some() {
500 let launcher = self.inner.launcher.clone();
501 let port = self.inner.config.port;
502 let _ = tokio::task::spawn_blocking(move || launcher.terminate_listener(port)).await;
503 } else if let Some(info) = self.version().await {
504 close_over_cdp(&info.websocket_url).await;
505 }
506 }
507
508 async fn stop_locked(&self, kill_fallback: bool) -> Result<(), BrowserError> {
509 if !self.is_running().await {
510 return Ok(());
511 }
512 self.close_gracefully().await;
435 513 let timeouts = &self.inner.timeouts;
436 514 if !self.wait_until_stopped().await && kill_fallback {
437 515 let launcher = self.inner.launcher.clone();
@@ -8,7 +8,8 @@ use serde_json::{Value, json};
8use tokio::sync::Mutex;
8use tokio::sync::Mutex;
9use tokio_tungstenite::tungstenite::Message;
9use tokio_tungstenite::tungstenite::Message;
10
10
11use crate::config::Config;
11use crate::bidi::Bidi;
12use crate::config::{Config, Engine};
12use crate::error::BrowserError;
13use crate::error::BrowserError;
13use crate::http;
14use crate::http;
14use crate::launch::{LaunchRequest, Launcher, SystemLauncher};
15use crate::launch::{LaunchRequest, Launcher, SystemLauncher};
@@ -74,6 +75,8 @@ struct Inner {
74 timeouts: Timeouts,
75 timeouts: Timeouts,
75 operation: Mutex<()>,
76 operation: Mutex<()>,
76 wanted: AtomicBool,
77 wanted: AtomicBool,
78 /// Set for a Firefox browser, which speaks WebDriver BiDi instead of CDP.
79 bidi: Option<Bidi>,
77}
80}
78
81
79#[derive(Clone)]
82#[derive(Clone)]
@@ -114,8 +117,10 @@ impl Browser {
114 launcher: Arc<dyn Launcher>,
117 launcher: Arc<dyn Launcher>,
115 timeouts: Timeouts,
118 timeouts: Timeouts,
116 ) -> Browser {
119 ) -> Browser {
120 let bidi = (config.engine == Engine::Firefox).then(|| Bidi::new(config.port));
117 Browser {
121 Browser {
118 inner: Arc::new(Inner {
122 inner: Arc::new(Inner {
123 bidi,
119 config,
124 config,
120 launcher,
125 launcher,
121 timeouts,
126 timeouts,
@@ -129,15 +134,20 @@ impl Browser {
129 &self.inner.config
134 &self.inner.config
130 }
135 }
131
136
137 /// The shared BiDi session of a Firefox browser; `None` for Chromium.
138 pub fn bidi(&self) -> Option<&Bidi> {
139 self.inner.bidi.as_ref()
140 }
141
132 pub async fn status(&self) -> Result<Status, BrowserError> {
142 pub async fn status(&self) -> Result<Status, BrowserError> {
133 let Some(_) = self.version().await else {
143 if !self.is_running().await {
134 return Ok(Status {
144 return Ok(Status {
135 running: false,
145 running: false,
136 mode: Mode::Visible,
146 mode: Mode::Visible,
137 tabs: Vec::new(),
147 tabs: Vec::new(),
138 login_state: LoginState::Unknown,
148 login_state: LoginState::Unknown,
139 });
149 });
140 };
150 }
141 let tabs = self.tabs().await?;
151 let tabs = self.tabs().await?;
142 Ok(Status {
152 Ok(Status {
143 running: true,
153 running: true,
@@ -148,7 +158,12 @@ impl Browser {
148 }
158 }
149
159
150 pub async fn is_running(&self) -> bool {
160 pub async fn is_running(&self) -> bool {
151 self.version().await.is_some()
161 if self.inner.bidi.is_none() {
162 return self.version().await.is_some();
163 }
164 http::request(self.inner.config.port, "GET", "/", Duration::from_secs(2))
165 .await
166 .is_ok_and(|response| response.status == 200)
152 }
167 }
153
168
154 pub async fn probe_renderer(&self) -> RendererState {
169 pub async fn probe_renderer(&self) -> RendererState {
@@ -158,6 +173,14 @@ impl Browser {
158 let Some(tab) = targets::app_tab(&tabs, App::Teams) else {
173 let Some(tab) = targets::app_tab(&tabs, App::Teams) else {
159 return RendererState::NoTab;
174 return RendererState::NoTab;
160 };
175 };
176 if let Some(bidi) = &self.inner.bidi {
177 let probe =
178 tokio::time::timeout(self.inner.timeouts.probe, bidi.evaluate(&tab.id, "1+1"));
179 return match probe.await {
180 Ok(Ok(_)) => RendererState::Ok,
181 _ => RendererState::Hung,
182 };
183 }
161 let url = format!(
184 let url = format!(
162 "ws://127.0.0.1:{}/devtools/page/{}",
185 "ws://127.0.0.1:{}/devtools/page/{}",
163 self.inner.config.port, tab.id
186 self.inner.config.port, tab.id
@@ -177,6 +200,9 @@ impl Browser {
177 }
200 }
178
201
179 pub async fn tabs(&self) -> Result<Vec<Tab>, BrowserError> {
202 pub async fn tabs(&self) -> Result<Vec<Tab>, BrowserError> {
203 if let Some(bidi) = &self.inner.bidi {
204 return bidi.tabs().await;
205 }
180 let response =
206 let response =
181 http::request(self.inner.config.port, "GET", "/json/list", HTTP_TIMEOUT).await?;
207 http::request(self.inner.config.port, "GET", "/json/list", HTTP_TIMEOUT).await?;
182 targets::parse_tabs(&response.body)
208 targets::parse_tabs(&response.body)
@@ -186,6 +212,7 @@ impl Browser {
186 let _guard = self.inner.operation.lock().await;
212 let _guard = self.inner.operation.lock().await;
187 self.inner.wanted.store(true, Ordering::SeqCst);
213 self.inner.wanted.store(true, Ordering::SeqCst);
188 if self.is_running().await {
214 if self.is_running().await {
215 self.adopt_session_locked().await?;
189 return self.ensure_tabs_locked().await;
216 return self.ensure_tabs_locked().await;
190 }
217 }
191 match self.launch_locked(true).await {
218 match self.launch_locked(true).await {
@@ -208,6 +235,12 @@ impl Browser {
208 else {
235 else {
209 return self.open_tab(app).await;
236 return self.open_tab(app).await;
210 };
237 };
238 if let Some(bidi) = &self.inner.bidi {
239 let navigate = bidi.navigate(&tab.id, app.start_url());
240 return tokio::time::timeout(CDP_TIMEOUT, navigate)
241 .await
242 .map_err(|_| BrowserError::Cdp("browsingContext.navigate timed out".into()))?;
243 }
211 let url = format!(
244 let url = format!(
212 "ws://127.0.0.1:{}/devtools/page/{}",
245 "ws://127.0.0.1:{}/devtools/page/{}",
213 self.inner.config.port, tab.id
246 self.inner.config.port, tab.id
@@ -241,11 +274,18 @@ impl Browser {
241 if tab.parked {
274 if tab.parked {
242 return false;
275 return false;
243 }
276 }
277 let expression = "(() => { let access = false, refresh = false; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i) || ''; if (key.includes('accesstoken')) access = true; if (key.includes('refreshtoken')) refresh = true; } return access && refresh; })()";
278 if let Some(bidi) = &self.inner.bidi {
279 let evaluate = tokio::time::timeout(
280 self.inner.timeouts.probe,
281 bidi.evaluate(&tab.id, expression),
282 );
283 return matches!(evaluate.await, Ok(Ok(Value::Bool(true))));
284 }
244 let url = format!(
285 let url = format!(
245 "ws://127.0.0.1:{}/devtools/page/{}",
286 "ws://127.0.0.1:{}/devtools/page/{}",
246 self.inner.config.port, tab.id
287 self.inner.config.port, tab.id
247 );
288 );
248 let expression = "(() => { let access = false, refresh = false; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i) || ''; if (key.includes('accesstoken')) access = true; if (key.includes('refreshtoken')) refresh = true; } return access && refresh; })()";
249 let params = json!({ "expression": expression, "returnByValue": true });
289 let params = json!({ "expression": expression, "returnByValue": true });
250 cdp_call(&url, "Runtime.evaluate", params, self.inner.timeouts.probe)
290 cdp_call(&url, "Runtime.evaluate", params, self.inner.timeouts.probe)
251 .await
291 .await
@@ -339,6 +379,12 @@ impl Browser {
339
379
340 async fn try_dedupe_app_tabs(&self) -> Result<(), BrowserError> {
380 async fn try_dedupe_app_tabs(&self) -> Result<(), BrowserError> {
341 let tabs = self.tabs().await?;
381 let tabs = self.tabs().await?;
382 if let Some(bidi) = &self.inner.bidi {
383 for id in targets::closable_tab_ids(&tabs, &Default::default()) {
384 bidi.close_tab(&id).await?;
385 }
386 return Ok(());
387 }
342 let info = self
388 let info = self
343 .version()
389 .version()
344 .await
390 .await
@@ -359,6 +405,11 @@ impl Browser {
359 }
405 }
360
406
361 async fn open_tab(&self, app: App) -> Result<(), BrowserError> {
407 async fn open_tab(&self, app: App) -> Result<(), BrowserError> {
408 if let Some(bidi) = &self.inner.bidi {
409 return tokio::time::timeout(OPEN_TAB_TIMEOUT, bidi.open_tab(app.start_url()))
410 .await
411 .map_err(|_| BrowserError::Cdp("opening the app tab timed out".into()))?;
412 }
362 let path = format!("/json/new?{}", app.start_url());
413 let path = format!("/json/new?{}", app.start_url());
363 let response =
414 let response =
364 http::request(self.inner.config.port, "PUT", &path, OPEN_TAB_TIMEOUT).await?;
415 http::request(self.inner.config.port, "PUT", &path, OPEN_TAB_TIMEOUT).await?;
@@ -427,11 +478,38 @@ impl Browser {
427 })
478 })
428 }
479 }
429
480
430 async fn stop_locked(&self, kill_fallback: bool) -> Result<(), BrowserError> {
481 /// A Firefox that still holds the session of an earlier, crashed app run cannot be driven;
431 let Some(info) = self.version().await else {
482 /// restart it so this process gets the session.
483 async fn adopt_session_locked(&self) -> Result<(), BrowserError> {
484 let Some(bidi) = &self.inner.bidi else {
432 return Ok(());
485 return Ok(());
433 };
486 };
434 close_over_cdp(&info.websocket_url).await;
487 match bidi.connect().await {
488 Err(BrowserError::SessionTaken(_)) => {
489 self.stop_locked(true).await?;
490 self.launch_locked(true).await
491 }
492 outcome => outcome,
493 }
494 }
495
496 /// Asks the browser to quit: Chromium over CDP, Firefox with SIGTERM, which also works while
497 /// another process holds its BiDi session.
498 async fn close_gracefully(&self) {
499 if self.inner.bidi.is_some() {
500 let launcher = self.inner.launcher.clone();
501 let port = self.inner.config.port;
502 let _ = tokio::task::spawn_blocking(move || launcher.terminate_listener(port)).await;
503 } else if let Some(info) = self.version().await {
504 close_over_cdp(&info.websocket_url).await;
505 }
506 }
507
508 async fn stop_locked(&self, kill_fallback: bool) -> Result<(), BrowserError> {
509 if !self.is_running().await {
510 return Ok(());
511 }
512 self.close_gracefully().await;
435 let timeouts = &self.inner.timeouts;
513 let timeouts = &self.inner.timeouts;
436 if !self.wait_until_stopped().await && kill_fallback {
514 if !self.wait_until_stopped().await && kill_fallback {
437 let launcher = self.inner.launcher.clone();
515 let launcher = self.inner.launcher.clone();
crates/browser/src/config.rs +182 −36
@@ -5,6 +5,9 @@ use std::process::Command;
5 5 use crate::error::BrowserError;
6 6
7 7 pub const PROFILE_NAME: &str = "rusty-teams-chrome";
8 pub const FIREFOX_PROFILE_NAME: &str = "rusty-teams-firefox";
9 /// Path to the sign-in browser executable, overriding the search. Firefox-family names run over WebDriver BiDi.
10 pub const BROWSER_OVERRIDE_ENV: &str = "RUSTY_TEAMS_SIGN_IN_BROWSER";
8 11 pub const DEFAULT_PORT: u16 = 9222;
9 12 const CHROME_RELATIVE: &str = r"Google\Chrome\Application\chrome.exe";
10 13 const WINDOWS_VARIABLES: [&str; 4] = ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "TEMP"];
@@ -26,6 +29,31 @@ const MACOS_CHROME_APP_PATHS: [&str; 6] = [
26 29 "Helium.app/Contents/MacOS/Helium",
27 30 "Vivaldi.app/Contents/MacOS/Vivaldi",
28 31 ];
32 /// Firefox-based browsers, tried only when no Chromium browser is installed.
33 const MACOS_FIREFOX_APP_PATHS: [&str; 4] = [
34 "Firefox.app/Contents/MacOS/firefox",
35 "Zen.app/Contents/MacOS/zen",
36 "LibreWolf.app/Contents/MacOS/librewolf",
37 "Floorp.app/Contents/MacOS/floorp",
38 ];
39 const LINUX_FIREFOX_NAMES: [&str; 5] = ["firefox", "zen-browser", "zen", "librewolf", "floorp"];
40
41 /// The protocol family of the sign-in browser: Chromium speaks CDP, Firefox WebDriver BiDi.
42 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
43 pub enum Engine {
44 Chromium,
45 Firefox,
46 }
47
48 impl Engine {
49 pub fn of_executable(path: &Path) -> Engine {
50 if crate::process::is_firefox_image(&path.to_string_lossy()) {
51 Engine::Firefox
52 } else {
53 Engine::Chromium
54 }
55 }
56 }
29 57
30 58 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
31 59 pub enum Platform {
@@ -60,7 +88,7 @@ impl Platform {
60 88 }
61 89
62 90 #[derive(Debug, Clone)]
63 pub(crate) enum ChromeSearch {
91 pub(crate) enum BrowserSearch {
64 92 Files(Vec<PathBuf>),
65 93 Named(Vec<String>),
66 94 /// Absolute install paths first, then PATH names (macOS Application bundles + CLI).
@@ -73,12 +101,13 @@ pub(crate) enum ChromeSearch {
73 101 #[derive(Debug, Clone)]
74 102 pub struct Config {
75 103 pub platform: Platform,
104 pub engine: Engine,
76 105 pub port: u16,
77 106 pub profile: String,
78 107 pub mode_file: PathBuf,
79 108 profile_parent: String,
80 109 mode_parent: PathBuf,
81 pub(crate) chrome_search: ChromeSearch,
110 pub(crate) search: BrowserSearch,
82 111 }
83 112
84 113 pub struct ConfigInputs<'a> {
@@ -103,6 +132,9 @@ impl Config {
103 132 .collect(),
104 133 Platform::Wsl => wsl_windows_variables()?,
105 134 };
135 let override_path = std::env::var_os(BROWSER_OVERRIDE_ENV)
136 .filter(|value| !value.is_empty())
137 .map(PathBuf::from);
106 138 let base = directories::BaseDirs::new();
107 139 let linux_data_dir = base.as_ref().map(|dirs| dirs.data_dir().to_path_buf());
108 140 let home_dir = base.as_ref().map(|dirs| dirs.home_dir().to_path_buf());
@@ -112,16 +144,48 @@ impl Config {
112 144 }
113 145 _ => windows_path.to_owned(),
114 146 };
115 Config::resolve(
147 let config = Config::resolve(
116 148 platform,
117 149 DEFAULT_PORT,
118 150 &ConfigInputs {
119 151 windows_variables,
120 152 linux_data_dir,
121 home_dir,
153 home_dir: home_dir.clone(),
122 154 to_local: &to_local,
123 155 },
124 )
156 )?;
157 let path_variable = std::env::var_os("PATH").unwrap_or_default();
158 Ok(config.select_browser(
159 override_path,
160 home_dir.as_deref(),
161 &path_variable,
162 &|path| path.is_file(),
163 ))
164 }
165
166 /// Picks the sign-in browser: the override path, else the first Chromium browser, else the
167 /// first Firefox-based one on Linux and macOS. A Firefox browser gets its own profile.
168 pub(crate) fn select_browser(
169 mut self,
170 override_path: Option<PathBuf>,
171 home_dir: Option<&Path>,
172 path_variable: &std::ffi::OsStr,
173 exists: &dyn Fn(&Path) -> bool,
174 ) -> Config {
175 if let Some(path) = override_path {
176 self.engine = Engine::of_executable(&path);
177 self.search = BrowserSearch::Files(vec![path]);
178 } else if find_browser(&self.search, path_variable, exists).is_err()
179 && let Some(search) = firefox_search(self.platform, home_dir)
180 && find_browser(&search, path_variable, exists).is_ok()
181 {
182 self.engine = Engine::Firefox;
183 self.search = search;
184 }
185 if self.engine == Engine::Firefox {
186 self = self.with_profile_name(FIREFOX_PROFILE_NAME);
187 }
188 self
125 189 }
126 190
127 191 pub fn resolve(
@@ -139,6 +203,7 @@ impl Config {
139 203 .ok_or_else(|| BrowserError::Environment("no XDG data directory".into()))?;
140 204 Config {
141 205 platform,
206 engine: Engine::Chromium,
142 207 port,
143 208 // Built with the platform's '/' like with_profile_name, not the
144 209 // host's separator: the string is a Linux path whoever builds it.
@@ -146,7 +211,7 @@ impl Config {
146 211 mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
147 212 profile_parent: path_text(&data_dir),
148 213 mode_parent: data_dir,
149 chrome_search: ChromeSearch::Named(
214 search: BrowserSearch::Named(
150 215 LINUX_CHROME_NAMES
151 216 .iter()
152 217 .map(|name| (*name).to_owned())
@@ -158,23 +223,18 @@ impl Config {
158 223 let data_dir = inputs.linux_data_dir.clone().ok_or_else(|| {
159 224 BrowserError::Environment("no Application Support directory".into())
160 225 })?;
161 let mut files = Vec::new();
162 for root in [PathBuf::from("/Applications")]
163 .into_iter()
164 .chain(inputs.home_dir.iter().map(|home| home.join("Applications")))
165 {
166 for relative in MACOS_CHROME_APP_PATHS {
167 files.push(root.join(relative));
168 }
169 }
226 let files = application_roots(inputs.home_dir.as_deref())
227 .flat_map(|root| MACOS_CHROME_APP_PATHS.map(|relative| root.join(relative)))
228 .collect();
170 229 Config {
171 230 platform,
231 engine: Engine::Chromium,
172 232 port,
173 233 profile: format!("{}/{}", path_text(&data_dir), PROFILE_NAME),
174 234 mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
175 235 profile_parent: path_text(&data_dir),
176 236 mode_parent: data_dir,
177 chrome_search: ChromeSearch::FilesThenNamed {
237 search: BrowserSearch::FilesThenNamed {
178 238 files,
179 239 names: MACOS_CHROME_NAMES
180 240 .iter()
@@ -195,12 +255,13 @@ impl Config {
195 255 .collect();
196 256 Config {
197 257 platform,
258 engine: Engine::Chromium,
198 259 port,
199 260 profile: format!("{local}\\{PROFILE_NAME}"),
200 261 mode_file: PathBuf::from(to_local(&format!("{local}\\{PROFILE_NAME}.mode"))),
201 262 profile_parent: local.clone(),
202 263 mode_parent: PathBuf::from(to_local(local)),
203 chrome_search: ChromeSearch::Files(candidates),
264 search: BrowserSearch::Files(candidates),
204 265 }
205 266 }
206 267 };
@@ -223,12 +284,31 @@ impl Config {
223 284 self
224 285 }
225 286
226 pub fn chrome_executable(&self) -> Result<PathBuf, BrowserError> {
287 pub fn executable(&self) -> Result<PathBuf, BrowserError> {
227 288 let path_variable = std::env::var_os("PATH").unwrap_or_default();
228 find_chrome(&self.chrome_search, &path_variable, &|path| path.is_file())
289 find_browser(&self.search, &path_variable, &|path| path.is_file())
229 290 }
230 291 }
231 292
293 fn firefox_search(platform: Platform, home_dir: Option<&Path>) -> Option<BrowserSearch> {
294 let names = || LINUX_FIREFOX_NAMES.iter().map(|name| (*name).to_owned());
295 match platform {
296 Platform::Linux => Some(BrowserSearch::Named(names().collect())),
297 Platform::Macos => Some(BrowserSearch::FilesThenNamed {
298 files: application_roots(home_dir)
299 .flat_map(|root| MACOS_FIREFOX_APP_PATHS.map(|relative| root.join(relative)))
300 .collect(),
301 names: names().collect(),
302 }),
303 Platform::Windows | Platform::Wsl => None,
304 }
305 }
306
307 fn application_roots(home_dir: Option<&Path>) -> impl Iterator<Item = PathBuf> {
308 std::iter::once(PathBuf::from("/Applications"))
309 .chain(home_dir.map(|home| home.join("Applications")))
310 }
311
232 312 fn path_text(path: &Path) -> String {
233 313 path.to_string_lossy().into_owned()
234 314 }
@@ -243,32 +323,33 @@ fn find_named_chrome(
243 323 .find(|candidate| exists(candidate))
244 324 }
245 325
246 pub(crate) fn find_chrome(
247 search: &ChromeSearch,
326 pub(crate) fn find_browser(
327 search: &BrowserSearch,
248 328 path_variable: &std::ffi::OsStr,
249 329 exists: &dyn Fn(&Path) -> bool,
250 330 ) -> Result<PathBuf, BrowserError> {
251 331 match search {
252 ChromeSearch::Files(candidates) => candidates
332 BrowserSearch::Files(candidates) => candidates
253 333 .iter()
254 334 .find(|candidate| exists(candidate))
255 335 .cloned()
256 336 .ok_or_else(|| {
257 337 BrowserError::ChromeNotFound("not under Program Files or LocalAppData".into())
258 338 }),
259 ChromeSearch::Named(names) => {
339 BrowserSearch::Named(names) => {
260 340 find_named_chrome(names, path_variable, exists).ok_or_else(|| {
261 341 BrowserError::ChromeNotFound(format!("none of {} on PATH", names.join(", ")))
262 342 })
263 343 }
264 ChromeSearch::FilesThenNamed { files, names } => files
344 BrowserSearch::FilesThenNamed { files, names } => files
265 345 .iter()
266 346 .find(|candidate| exists(candidate))
267 347 .cloned()
268 348 .or_else(|| find_named_chrome(names, path_variable, exists))
269 349 .ok_or_else(|| {
270 350 BrowserError::ChromeNotFound(
271 "no Chrome, Chromium, Edge, Brave, Helium or Vivaldi under /Applications, ~/Applications, or PATH".into(),
351 "no Chromium or Firefox browser under /Applications, ~/Applications, or PATH"
352 .into(),
272 353 )
273 354 }),
274 355 }
@@ -388,7 +469,7 @@ mod tests {
388 469 config.mode_file,
389 470 PathBuf::from("/mnt/c/Users/me/AppData/Local/rusty-teams-chrome.mode")
390 471 );
391 let ChromeSearch::Files(files) = &config.chrome_search else {
472 let BrowserSearch::Files(files) = &config.search else {
392 473 panic!("expected files")
393 474 };
394 475 assert_eq!(
@@ -416,7 +497,7 @@ mod tests {
416 497 config.profile,
417 498 r"C:\Users\me\AppData\Local\rusty-teams-chrome"
418 499 );
419 let ChromeSearch::Files(files) = &config.chrome_search else {
500 let BrowserSearch::Files(files) = &config.search else {
420 501 panic!("expected files")
421 502 };
422 503 let expected = [
@@ -443,7 +524,7 @@ mod tests {
443 524 to_local: &to_local,
444 525 };
445 526 let config = Config::resolve(Platform::Windows, 9222, &inputs).unwrap();
446 let ChromeSearch::Files(files) = &config.chrome_search else {
527 let BrowserSearch::Files(files) = &config.search else {
447 528 panic!("expected files")
448 529 };
449 530 assert_eq!(
@@ -496,7 +577,7 @@ mod tests {
496 577 config.mode_file,
497 578 PathBuf::from("/Users/joe/Library/Application Support/rusty-teams-chrome.mode")
498 579 );
499 let ChromeSearch::FilesThenNamed { files, names } = &config.chrome_search else {
580 let BrowserSearch::FilesThenNamed { files, names } = &config.search else {
500 581 panic!("expected files then named")
501 582 };
502 583 assert_eq!(
@@ -531,7 +612,7 @@ mod tests {
531 612
532 613 #[test]
533 614 fn finds_macos_chrome_under_applications_before_path() {
534 let search = ChromeSearch::FilesThenNamed {
615 let search = BrowserSearch::FilesThenNamed {
535 616 files: vec![
536 617 "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".into(),
537 618 "/Users/joe/Applications/Chromium.app/Contents/MacOS/Chromium".into(),
@@ -539,7 +620,7 @@ mod tests {
539 620 names: vec!["google-chrome".into()],
540 621 };
541 622 let path = std::env::join_paths(["/usr/local/bin"]).unwrap();
542 let found = find_chrome(&search, &path, &|candidate| {
623 let found = find_browser(&search, &path, &|candidate| {
543 624 candidate.ends_with("Google Chrome") || candidate.ends_with("google-chrome")
544 625 })
545 626 .unwrap();
@@ -577,22 +658,87 @@ mod tests {
577 658
578 659 #[test]
579 660 fn finds_first_existing_candidate() {
580 let search = ChromeSearch::Files(vec!["/a/chrome.exe".into(), "/b/chrome.exe".into()]);
581 let found = find_chrome(&search, &OsString::new(), &|path| path.starts_with("/b")).unwrap();
661 let search = BrowserSearch::Files(vec!["/a/chrome.exe".into(), "/b/chrome.exe".into()]);
662 let found =
663 find_browser(&search, &OsString::new(), &|path| path.starts_with("/b")).unwrap();
582 664 assert_eq!(found, PathBuf::from("/b/chrome.exe"));
583 assert!(find_chrome(&search, &OsString::new(), &|_| false).is_err());
665 assert!(find_browser(&search, &OsString::new(), &|_| false).is_err());
584 666 }
585 667
586 668 #[test]
587 669 fn finds_named_chrome_on_path_in_name_priority_per_directory() {
588 let search = ChromeSearch::Named(vec!["google-chrome".into(), "chromium".into()]);
670 let search = BrowserSearch::Named(vec!["google-chrome".into(), "chromium".into()]);
589 671 // join_paths picks the host's PATH separator so split_paths splits it here too.
590 672 let path = std::env::join_paths(["/usr/local/bin", "/usr/bin"]).unwrap();
591 let found = find_chrome(&search, &path, &|candidate| {
673 let found = find_browser(&search, &path, &|candidate| {
592 674 candidate == Path::new("/usr/bin/chromium")
593 675 || candidate == Path::new("/usr/bin/google-chrome")
594 676 })
595 677 .unwrap();
596 678 assert_eq!(found, PathBuf::from("/usr/bin/google-chrome"));
597 679 }
680
681 fn macos_config() -> Config {
682 let to_local = |path: &str| path.to_owned();
683 let inputs = ConfigInputs {
684 windows_variables: HashMap::new(),
685 linux_data_dir: Some(PathBuf::from("/Users/joe/Library/Application Support")),
686 home_dir: Some(PathBuf::from("/Users/joe")),
687 to_local: &to_local,
688 };
689 Config::resolve(Platform::Macos, 9222, &inputs).unwrap()
690 }
691
692 fn select(installed: &[&str], override_path: Option<&str>) -> Config {
693 macos_config().select_browser(
694 override_path.map(PathBuf::from),
695 Some(Path::new("/Users/joe")),
696 &OsString::new(),
697 &|path| {
698 installed
699 .iter()
700 .any(|installed| path == Path::new(installed))
701 },
702 )
703 }
704
705 #[test]
706 fn a_chromium_browser_wins_over_firefox() {
707 let config = select(
708 &[
709 "/Applications/Helium.app/Contents/MacOS/Helium",
710 "/Applications/Zen.app/Contents/MacOS/zen",
711 ],
712 None,
713 );
714 assert_eq!(config.engine, Engine::Chromium);
715 assert!(config.profile.ends_with(PROFILE_NAME));
716 }
717
718 #[test]
719 fn firefox_is_the_fallback_with_its_own_profile() {
720 let zen = "/Users/joe/Applications/Zen.app/Contents/MacOS/zen";
721 let config = select(&[zen], None);
722 assert_eq!(config.engine, Engine::Firefox);
723 assert_eq!(
724 config.profile,
725 "/Users/joe/Library/Application Support/rusty-teams-firefox"
726 );
727 let found = find_browser(&config.search, &OsString::new(), &|path| {
728 path == Path::new(zen)
729 });
730 assert_eq!(found.unwrap(), PathBuf::from(zen));
731 }
732
733 #[test]
734 fn the_override_picks_the_browser_and_its_engine() {
735 let helium = "/Applications/Helium.app/Contents/MacOS/Helium";
736 let firefox = select(&[helium], Some("/opt/zen/zen"));
737 assert_eq!(firefox.engine, Engine::Firefox);
738 let BrowserSearch::Files(files) = &firefox.search else {
739 panic!("expected the override path")
740 };
741 assert_eq!(files, &[PathBuf::from("/opt/zen/zen")]);
742 assert_eq!(select(&[], Some(helium)).engine, Engine::Chromium);
743 }
598 744 }
@@ -5,6 +5,9 @@ use std::process::Command;
5use crate::error::BrowserError;
5use crate::error::BrowserError;
6
6
7pub const PROFILE_NAME: &str = "rusty-teams-chrome";
7pub const PROFILE_NAME: &str = "rusty-teams-chrome";
8pub const FIREFOX_PROFILE_NAME: &str = "rusty-teams-firefox";
9/// Path to the sign-in browser executable, overriding the search. Firefox-family names run over WebDriver BiDi.
10pub const BROWSER_OVERRIDE_ENV: &str = "RUSTY_TEAMS_SIGN_IN_BROWSER";
8pub const DEFAULT_PORT: u16 = 9222;
11pub const DEFAULT_PORT: u16 = 9222;
9const CHROME_RELATIVE: &str = r"Google\Chrome\Application\chrome.exe";
12const CHROME_RELATIVE: &str = r"Google\Chrome\Application\chrome.exe";
10const WINDOWS_VARIABLES: [&str; 4] = ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "TEMP"];
13const WINDOWS_VARIABLES: [&str; 4] = ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "TEMP"];
@@ -26,6 +29,31 @@ const MACOS_CHROME_APP_PATHS: [&str; 6] = [
26 "Helium.app/Contents/MacOS/Helium",
29 "Helium.app/Contents/MacOS/Helium",
27 "Vivaldi.app/Contents/MacOS/Vivaldi",
30 "Vivaldi.app/Contents/MacOS/Vivaldi",
28];
31];
32/// Firefox-based browsers, tried only when no Chromium browser is installed.
33const MACOS_FIREFOX_APP_PATHS: [&str; 4] = [
34 "Firefox.app/Contents/MacOS/firefox",
35 "Zen.app/Contents/MacOS/zen",
36 "LibreWolf.app/Contents/MacOS/librewolf",
37 "Floorp.app/Contents/MacOS/floorp",
38];
39const LINUX_FIREFOX_NAMES: [&str; 5] = ["firefox", "zen-browser", "zen", "librewolf", "floorp"];
40
41/// The protocol family of the sign-in browser: Chromium speaks CDP, Firefox WebDriver BiDi.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum Engine {
44 Chromium,
45 Firefox,
46}
47
48impl Engine {
49 pub fn of_executable(path: &Path) -> Engine {
50 if crate::process::is_firefox_image(&path.to_string_lossy()) {
51 Engine::Firefox
52 } else {
53 Engine::Chromium
54 }
55 }
56}
29
57
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Platform {
59pub enum Platform {
@@ -60,7 +88,7 @@ impl Platform {
60}
88}
61
89
62#[derive(Debug, Clone)]
90#[derive(Debug, Clone)]
63pub(crate) enum ChromeSearch {
91pub(crate) enum BrowserSearch {
64 Files(Vec<PathBuf>),
92 Files(Vec<PathBuf>),
65 Named(Vec<String>),
93 Named(Vec<String>),
66 /// Absolute install paths first, then PATH names (macOS Application bundles + CLI).
94 /// Absolute install paths first, then PATH names (macOS Application bundles + CLI).
@@ -73,12 +101,13 @@ pub(crate) enum ChromeSearch {
73#[derive(Debug, Clone)]
101#[derive(Debug, Clone)]
74pub struct Config {
102pub struct Config {
75 pub platform: Platform,
103 pub platform: Platform,
104 pub engine: Engine,
76 pub port: u16,
105 pub port: u16,
77 pub profile: String,
106 pub profile: String,
78 pub mode_file: PathBuf,
107 pub mode_file: PathBuf,
79 profile_parent: String,
108 profile_parent: String,
80 mode_parent: PathBuf,
109 mode_parent: PathBuf,
81 pub(crate) chrome_search: ChromeSearch,
110 pub(crate) search: BrowserSearch,
82}
111}
83
112
84pub struct ConfigInputs<'a> {
113pub struct ConfigInputs<'a> {
@@ -103,6 +132,9 @@ impl Config {
103 .collect(),
132 .collect(),
104 Platform::Wsl => wsl_windows_variables()?,
133 Platform::Wsl => wsl_windows_variables()?,
105 };
134 };
135 let override_path = std::env::var_os(BROWSER_OVERRIDE_ENV)
136 .filter(|value| !value.is_empty())
137 .map(PathBuf::from);
106 let base = directories::BaseDirs::new();
138 let base = directories::BaseDirs::new();
107 let linux_data_dir = base.as_ref().map(|dirs| dirs.data_dir().to_path_buf());
139 let linux_data_dir = base.as_ref().map(|dirs| dirs.data_dir().to_path_buf());
108 let home_dir = base.as_ref().map(|dirs| dirs.home_dir().to_path_buf());
140 let home_dir = base.as_ref().map(|dirs| dirs.home_dir().to_path_buf());
@@ -112,16 +144,48 @@ impl Config {
112 }
144 }
113 _ => windows_path.to_owned(),
145 _ => windows_path.to_owned(),
114 };
146 };
115 Config::resolve(
147 let config = Config::resolve(
116 platform,
148 platform,
117 DEFAULT_PORT,
149 DEFAULT_PORT,
118 &ConfigInputs {
150 &ConfigInputs {
119 windows_variables,
151 windows_variables,
120 linux_data_dir,
152 linux_data_dir,
121 home_dir,
153 home_dir: home_dir.clone(),
122 to_local: &to_local,
154 to_local: &to_local,
123 },
155 },
124 )
156 )?;
157 let path_variable = std::env::var_os("PATH").unwrap_or_default();
158 Ok(config.select_browser(
159 override_path,
160 home_dir.as_deref(),
161 &path_variable,
162 &|path| path.is_file(),
163 ))
164 }
165
166 /// Picks the sign-in browser: the override path, else the first Chromium browser, else the
167 /// first Firefox-based one on Linux and macOS. A Firefox browser gets its own profile.
168 pub(crate) fn select_browser(
169 mut self,
170 override_path: Option<PathBuf>,
171 home_dir: Option<&Path>,
172 path_variable: &std::ffi::OsStr,
173 exists: &dyn Fn(&Path) -> bool,
174 ) -> Config {
175 if let Some(path) = override_path {
176 self.engine = Engine::of_executable(&path);
177 self.search = BrowserSearch::Files(vec![path]);
178 } else if find_browser(&self.search, path_variable, exists).is_err()
179 && let Some(search) = firefox_search(self.platform, home_dir)
180 && find_browser(&search, path_variable, exists).is_ok()
181 {
182 self.engine = Engine::Firefox;
183 self.search = search;
184 }
185 if self.engine == Engine::Firefox {
186 self = self.with_profile_name(FIREFOX_PROFILE_NAME);
187 }
188 self
125 }
189 }
126
190
127 pub fn resolve(
191 pub fn resolve(
@@ -139,6 +203,7 @@ impl Config {
139 .ok_or_else(|| BrowserError::Environment("no XDG data directory".into()))?;
203 .ok_or_else(|| BrowserError::Environment("no XDG data directory".into()))?;
140 Config {
204 Config {
141 platform,
205 platform,
206 engine: Engine::Chromium,
142 port,
207 port,
143 // Built with the platform's '/' like with_profile_name, not the
208 // Built with the platform's '/' like with_profile_name, not the
144 // host's separator: the string is a Linux path whoever builds it.
209 // host's separator: the string is a Linux path whoever builds it.
@@ -146,7 +211,7 @@ impl Config {
146 mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
211 mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
147 profile_parent: path_text(&data_dir),
212 profile_parent: path_text(&data_dir),
148 mode_parent: data_dir,
213 mode_parent: data_dir,
149 chrome_search: ChromeSearch::Named(
214 search: BrowserSearch::Named(
150 LINUX_CHROME_NAMES
215 LINUX_CHROME_NAMES
151 .iter()
216 .iter()
152 .map(|name| (*name).to_owned())
217 .map(|name| (*name).to_owned())
@@ -158,23 +223,18 @@ impl Config {
158 let data_dir = inputs.linux_data_dir.clone().ok_or_else(|| {
223 let data_dir = inputs.linux_data_dir.clone().ok_or_else(|| {
159 BrowserError::Environment("no Application Support directory".into())
224 BrowserError::Environment("no Application Support directory".into())
160 })?;
225 })?;
161 let mut files = Vec::new();
226 let files = application_roots(inputs.home_dir.as_deref())
162 for root in [PathBuf::from("/Applications")]
227 .flat_map(|root| MACOS_CHROME_APP_PATHS.map(|relative| root.join(relative)))
163 .into_iter()
228 .collect();
164 .chain(inputs.home_dir.iter().map(|home| home.join("Applications")))
165 {
166 for relative in MACOS_CHROME_APP_PATHS {
167 files.push(root.join(relative));
168 }
169 }
170 Config {
229 Config {
171 platform,
230 platform,
231 engine: Engine::Chromium,
172 port,
232 port,
173 profile: format!("{}/{}", path_text(&data_dir), PROFILE_NAME),
233 profile: format!("{}/{}", path_text(&data_dir), PROFILE_NAME),
174 mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
234 mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
175 profile_parent: path_text(&data_dir),
235 profile_parent: path_text(&data_dir),
176 mode_parent: data_dir,
236 mode_parent: data_dir,
177 chrome_search: ChromeSearch::FilesThenNamed {
237 search: BrowserSearch::FilesThenNamed {
178 files,
238 files,
179 names: MACOS_CHROME_NAMES
239 names: MACOS_CHROME_NAMES
180 .iter()
240 .iter()
@@ -195,12 +255,13 @@ impl Config {
195 .collect();
255 .collect();
196 Config {
256 Config {
197 platform,
257 platform,
258 engine: Engine::Chromium,
198 port,
259 port,
199 profile: format!("{local}\\{PROFILE_NAME}"),
260 profile: format!("{local}\\{PROFILE_NAME}"),
200 mode_file: PathBuf::from(to_local(&format!("{local}\\{PROFILE_NAME}.mode"))),
261 mode_file: PathBuf::from(to_local(&format!("{local}\\{PROFILE_NAME}.mode"))),
201 profile_parent: local.clone(),
262 profile_parent: local.clone(),
202 mode_parent: PathBuf::from(to_local(local)),
263 mode_parent: PathBuf::from(to_local(local)),
203 chrome_search: ChromeSearch::Files(candidates),
264 search: BrowserSearch::Files(candidates),
204 }
265 }
205 }
266 }
206 };
267 };
@@ -223,12 +284,31 @@ impl Config {
223 self
284 self
224 }
285 }
225
286
226 pub fn chrome_executable(&self) -> Result<PathBuf, BrowserError> {
287 pub fn executable(&self) -> Result<PathBuf, BrowserError> {
227 let path_variable = std::env::var_os("PATH").unwrap_or_default();
288 let path_variable = std::env::var_os("PATH").unwrap_or_default();
228 find_chrome(&self.chrome_search, &path_variable, &|path| path.is_file())
289 find_browser(&self.search, &path_variable, &|path| path.is_file())
229 }
290 }
230}
291}
231
292
293fn firefox_search(platform: Platform, home_dir: Option<&Path>) -> Option<BrowserSearch> {
294 let names = || LINUX_FIREFOX_NAMES.iter().map(|name| (*name).to_owned());
295 match platform {
296 Platform::Linux => Some(BrowserSearch::Named(names().collect())),
297 Platform::Macos => Some(BrowserSearch::FilesThenNamed {
298 files: application_roots(home_dir)
299 .flat_map(|root| MACOS_FIREFOX_APP_PATHS.map(|relative| root.join(relative)))
300 .collect(),
301 names: names().collect(),
302 }),
303 Platform::Windows | Platform::Wsl => None,
304 }
305}
306
307fn application_roots(home_dir: Option<&Path>) -> impl Iterator<Item = PathBuf> {
308 std::iter::once(PathBuf::from("/Applications"))
309 .chain(home_dir.map(|home| home.join("Applications")))
310}
311
232fn path_text(path: &Path) -> String {
312fn path_text(path: &Path) -> String {
233 path.to_string_lossy().into_owned()
313 path.to_string_lossy().into_owned()
234}
314}
@@ -243,32 +323,33 @@ fn find_named_chrome(
243 .find(|candidate| exists(candidate))
323 .find(|candidate| exists(candidate))
244}
324}
245
325
246pub(crate) fn find_chrome(
326pub(crate) fn find_browser(
247 search: &ChromeSearch,
327 search: &BrowserSearch,
248 path_variable: &std::ffi::OsStr,
328 path_variable: &std::ffi::OsStr,
249 exists: &dyn Fn(&Path) -> bool,
329 exists: &dyn Fn(&Path) -> bool,
250) -> Result<PathBuf, BrowserError> {
330) -> Result<PathBuf, BrowserError> {
251 match search {
331 match search {
252 ChromeSearch::Files(candidates) => candidates
332 BrowserSearch::Files(candidates) => candidates
253 .iter()
333 .iter()
254 .find(|candidate| exists(candidate))
334 .find(|candidate| exists(candidate))
255 .cloned()
335 .cloned()
256 .ok_or_else(|| {
336 .ok_or_else(|| {
257 BrowserError::ChromeNotFound("not under Program Files or LocalAppData".into())
337 BrowserError::ChromeNotFound("not under Program Files or LocalAppData".into())
258 }),
338 }),
259 ChromeSearch::Named(names) => {
339 BrowserSearch::Named(names) => {
260 find_named_chrome(names, path_variable, exists).ok_or_else(|| {
340 find_named_chrome(names, path_variable, exists).ok_or_else(|| {
261 BrowserError::ChromeNotFound(format!("none of {} on PATH", names.join(", ")))
341 BrowserError::ChromeNotFound(format!("none of {} on PATH", names.join(", ")))
262 })
342 })
263 }
343 }
264 ChromeSearch::FilesThenNamed { files, names } => files
344 BrowserSearch::FilesThenNamed { files, names } => files
265 .iter()
345 .iter()
266 .find(|candidate| exists(candidate))
346 .find(|candidate| exists(candidate))
267 .cloned()
347 .cloned()
268 .or_else(|| find_named_chrome(names, path_variable, exists))
348 .or_else(|| find_named_chrome(names, path_variable, exists))
269 .ok_or_else(|| {
349 .ok_or_else(|| {
270 BrowserError::ChromeNotFound(
350 BrowserError::ChromeNotFound(
271 "no Chrome, Chromium, Edge, Brave, Helium or Vivaldi under /Applications, ~/Applications, or PATH".into(),
351 "no Chromium or Firefox browser under /Applications, ~/Applications, or PATH"
352 .into(),
272 )
353 )
273 }),
354 }),
274 }
355 }
@@ -388,7 +469,7 @@ mod tests {
388 config.mode_file,
469 config.mode_file,
389 PathBuf::from("/mnt/c/Users/me/AppData/Local/rusty-teams-chrome.mode")
470 PathBuf::from("/mnt/c/Users/me/AppData/Local/rusty-teams-chrome.mode")
390 );
471 );
391 let ChromeSearch::Files(files) = &config.chrome_search else {
472 let BrowserSearch::Files(files) = &config.search else {
392 panic!("expected files")
473 panic!("expected files")
393 };
474 };
394 assert_eq!(
475 assert_eq!(
@@ -416,7 +497,7 @@ mod tests {
416 config.profile,
497 config.profile,
417 r"C:\Users\me\AppData\Local\rusty-teams-chrome"
498 r"C:\Users\me\AppData\Local\rusty-teams-chrome"
418 );
499 );
419 let ChromeSearch::Files(files) = &config.chrome_search else {
500 let BrowserSearch::Files(files) = &config.search else {
420 panic!("expected files")
501 panic!("expected files")
421 };
502 };
422 let expected = [
503 let expected = [
@@ -443,7 +524,7 @@ mod tests {
443 to_local: &to_local,
524 to_local: &to_local,
444 };
525 };
445 let config = Config::resolve(Platform::Windows, 9222, &inputs).unwrap();
526 let config = Config::resolve(Platform::Windows, 9222, &inputs).unwrap();
446 let ChromeSearch::Files(files) = &config.chrome_search else {
527 let BrowserSearch::Files(files) = &config.search else {
447 panic!("expected files")
528 panic!("expected files")
448 };
529 };
449 assert_eq!(
530 assert_eq!(
@@ -496,7 +577,7 @@ mod tests {
496 config.mode_file,
577 config.mode_file,
497 PathBuf::from("/Users/joe/Library/Application Support/rusty-teams-chrome.mode")
578 PathBuf::from("/Users/joe/Library/Application Support/rusty-teams-chrome.mode")
498 );
579 );
499 let ChromeSearch::FilesThenNamed { files, names } = &config.chrome_search else {
580 let BrowserSearch::FilesThenNamed { files, names } = &config.search else {
500 panic!("expected files then named")
581 panic!("expected files then named")
501 };
582 };
502 assert_eq!(
583 assert_eq!(
@@ -531,7 +612,7 @@ mod tests {
531
612
532 #[test]
613 #[test]
533 fn finds_macos_chrome_under_applications_before_path() {
614 fn finds_macos_chrome_under_applications_before_path() {
534 let search = ChromeSearch::FilesThenNamed {
615 let search = BrowserSearch::FilesThenNamed {
535 files: vec![
616 files: vec![
536 "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".into(),
617 "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".into(),
537 "/Users/joe/Applications/Chromium.app/Contents/MacOS/Chromium".into(),
618 "/Users/joe/Applications/Chromium.app/Contents/MacOS/Chromium".into(),
@@ -539,7 +620,7 @@ mod tests {
539 names: vec!["google-chrome".into()],
620 names: vec!["google-chrome".into()],
540 };
621 };
541 let path = std::env::join_paths(["/usr/local/bin"]).unwrap();
622 let path = std::env::join_paths(["/usr/local/bin"]).unwrap();
542 let found = find_chrome(&search, &path, &|candidate| {
623 let found = find_browser(&search, &path, &|candidate| {
543 candidate.ends_with("Google Chrome") || candidate.ends_with("google-chrome")
624 candidate.ends_with("Google Chrome") || candidate.ends_with("google-chrome")
544 })
625 })
545 .unwrap();
626 .unwrap();
@@ -577,22 +658,87 @@ mod tests {
577
658
578 #[test]
659 #[test]
579 fn finds_first_existing_candidate() {
660 fn finds_first_existing_candidate() {
580 let search = ChromeSearch::Files(vec!["/a/chrome.exe".into(), "/b/chrome.exe".into()]);
661 let search = BrowserSearch::Files(vec!["/a/chrome.exe".into(), "/b/chrome.exe".into()]);
581 let found = find_chrome(&search, &OsString::new(), &|path| path.starts_with("/b")).unwrap();
662 let found =
663 find_browser(&search, &OsString::new(), &|path| path.starts_with("/b")).unwrap();
582 assert_eq!(found, PathBuf::from("/b/chrome.exe"));
664 assert_eq!(found, PathBuf::from("/b/chrome.exe"));
583 assert!(find_chrome(&search, &OsString::new(), &|_| false).is_err());
665 assert!(find_browser(&search, &OsString::new(), &|_| false).is_err());
584 }
666 }
585
667
586 #[test]
668 #[test]
587 fn finds_named_chrome_on_path_in_name_priority_per_directory() {
669 fn finds_named_chrome_on_path_in_name_priority_per_directory() {
588 let search = ChromeSearch::Named(vec!["google-chrome".into(), "chromium".into()]);
670 let search = BrowserSearch::Named(vec!["google-chrome".into(), "chromium".into()]);
589 // join_paths picks the host's PATH separator so split_paths splits it here too.
671 // join_paths picks the host's PATH separator so split_paths splits it here too.
590 let path = std::env::join_paths(["/usr/local/bin", "/usr/bin"]).unwrap();
672 let path = std::env::join_paths(["/usr/local/bin", "/usr/bin"]).unwrap();
591 let found = find_chrome(&search, &path, &|candidate| {
673 let found = find_browser(&search, &path, &|candidate| {
592 candidate == Path::new("/usr/bin/chromium")
674 candidate == Path::new("/usr/bin/chromium")
593 || candidate == Path::new("/usr/bin/google-chrome")
675 || candidate == Path::new("/usr/bin/google-chrome")
594 })
676 })
595 .unwrap();
677 .unwrap();
596 assert_eq!(found, PathBuf::from("/usr/bin/google-chrome"));
678 assert_eq!(found, PathBuf::from("/usr/bin/google-chrome"));
597 }
679 }
680
681 fn macos_config() -> Config {
682 let to_local = |path: &str| path.to_owned();
683 let inputs = ConfigInputs {
684 windows_variables: HashMap::new(),
685 linux_data_dir: Some(PathBuf::from("/Users/joe/Library/Application Support")),
686 home_dir: Some(PathBuf::from("/Users/joe")),
687 to_local: &to_local,
688 };
689 Config::resolve(Platform::Macos, 9222, &inputs).unwrap()
690 }
691
692 fn select(installed: &[&str], override_path: Option<&str>) -> Config {
693 macos_config().select_browser(
694 override_path.map(PathBuf::from),
695 Some(Path::new("/Users/joe")),
696 &OsString::new(),
697 &|path| {
698 installed
699 .iter()
700 .any(|installed| path == Path::new(installed))
701 },
702 )
703 }
704
705 #[test]
706 fn a_chromium_browser_wins_over_firefox() {
707 let config = select(
708 &[
709 "/Applications/Helium.app/Contents/MacOS/Helium",
710 "/Applications/Zen.app/Contents/MacOS/zen",
711 ],
712 None,
713 );
714 assert_eq!(config.engine, Engine::Chromium);
715 assert!(config.profile.ends_with(PROFILE_NAME));
716 }
717
718 #[test]
719 fn firefox_is_the_fallback_with_its_own_profile() {
720 let zen = "/Users/joe/Applications/Zen.app/Contents/MacOS/zen";
721 let config = select(&[zen], None);
722 assert_eq!(config.engine, Engine::Firefox);
723 assert_eq!(
724 config.profile,
725 "/Users/joe/Library/Application Support/rusty-teams-firefox"
726 );
727 let found = find_browser(&config.search, &OsString::new(), &|path| {
728 path == Path::new(zen)
729 });
730 assert_eq!(found.unwrap(), PathBuf::from(zen));
731 }
732
733 #[test]
734 fn the_override_picks_the_browser_and_its_engine() {
735 let helium = "/Applications/Helium.app/Contents/MacOS/Helium";
736 let firefox = select(&[helium], Some("/opt/zen/zen"));
737 assert_eq!(firefox.engine, Engine::Firefox);
738 let BrowserSearch::Files(files) = &firefox.search else {
739 panic!("expected the override path")
740 };
741 assert_eq!(files, &[PathBuf::from("/opt/zen/zen")]);
742 assert_eq!(select(&[], Some(helium)).engine, Engine::Chromium);
743 }
598}
744}
crates/browser/src/error.rs +2 −0
@@ -14,6 +14,8 @@ pub enum BrowserError {
14 14 StartTimeout { port: u16, seconds: u64 },
15 15 #[error("chrome on port {port} did not close within {seconds}s")]
16 16 StopTimeout { port: u16, seconds: u64 },
17 #[error("the browser on port {0} holds a WebDriver session of another process")]
18 SessionTaken(u16),
17 19 #[error("http: {0}")]
18 20 Http(String),
19 21 #[error("devtools: {0}")]
@@ -14,6 +14,8 @@ pub enum BrowserError {
14 StartTimeout { port: u16, seconds: u64 },
14 StartTimeout { port: u16, seconds: u64 },
15 #[error("chrome on port {port} did not close within {seconds}s")]
15 #[error("chrome on port {port} did not close within {seconds}s")]
16 StopTimeout { port: u16, seconds: u64 },
16 StopTimeout { port: u16, seconds: u64 },
17 #[error("the browser on port {0} holds a WebDriver session of another process")]
18 SessionTaken(u16),
17 #[error("http: {0}")]
19 #[error("http: {0}")]
18 Http(String),
20 Http(String),
19 #[error("devtools: {0}")]
21 #[error("devtools: {0}")]
crates/browser/src/launch.rs +92 −13
@@ -1,7 +1,7 @@
1 1 use std::path::Path;
2 2 use std::process::{Command, Stdio};
3 3
4 use crate::config::{Config, Platform};
4 use crate::config::{Config, Engine, Platform};
5 5 use crate::error::BrowserError;
6 6
7 7 #[derive(Debug, Clone)]
@@ -13,6 +13,11 @@ pub struct LaunchRequest {
13 13 pub trait Launcher: Send + Sync {
14 14 fn spawn(&self, request: &LaunchRequest) -> Result<(), BrowserError>;
15 15 fn kill_listener(&self, port: u16) -> Result<(), BrowserError>;
16
17 /// Lets the browser on `port` quit cleanly and returns once it is gone.
18 fn terminate_listener(&self, port: u16) -> Result<(), BrowserError> {
19 self.kill_listener(port)
20 }
16 21 }
17 22
18 23 pub struct ArgumentSpec<'a> {
@@ -55,6 +60,42 @@ pub fn chrome_arguments(spec: &ArgumentSpec) -> Vec<String> {
55 60 arguments
56 61 }
57 62
63 /// Firefox keeps its own user agent: headless Firefox does not mark itself, so Microsoft accepts it.
64 pub fn firefox_arguments(spec: &ArgumentSpec) -> Vec<String> {
65 let mut arguments = vec![
66 format!("--remote-debugging-port={}", spec.port),
67 "--profile".into(),
68 spec.profile.into(),
69 "--no-remote".into(),
70 ];
71 if spec.headless {
72 arguments.extend(["--headless".into(), "--window-size=1400,1000".into()]);
73 }
74 arguments.extend(spec.start_urls.iter().cloned());
75 arguments
76 }
77
78 /// Prefs for the app's own Firefox profile: no first-run pages, no restored tabs, no quit prompts,
79 /// no Safe Mode.
80 const FIREFOX_PREFS: &str = r#"user_pref("browser.shell.checkDefaultBrowser", false);
81 user_pref("browser.startup.homepage_override.mstone", "ignore");
82 user_pref("browser.startup.page", 0);
83 user_pref("browser.aboutwelcome.enabled", false);
84 user_pref("browser.sessionstore.resume_from_crash", false);
85 user_pref("browser.tabs.warnOnClose", false);
86 user_pref("browser.warnOnQuit", false);
87 user_pref("datareporting.policy.dataSubmissionPolicyBypassNotification", true);
88 user_pref("toolkit.telemetry.reportingpolicy.firstRun", false);
89 // A browser the app stopped hard counts as a startup crash; Safe Mode would hang a headless start.
90 user_pref("toolkit.startup.max_resumed_crashes", -1);
91 user_pref("zen.welcome-screen.seen", true);
92 "#;
93
94 fn write_firefox_prefs(profile: &str) -> std::io::Result<()> {
95 std::fs::create_dir_all(profile)?;
96 std::fs::write(Path::new(profile).join("user.js"), FIREFOX_PREFS)
97 }
98
58 99 pub fn user_agent(platform: Platform, major: u32) -> String {
59 100 let system = match platform {
60 101 Platform::Linux => "X11; Linux x86_64",
@@ -147,18 +188,32 @@ impl SystemLauncher {
147 188
148 189 impl Launcher for SystemLauncher {
149 190 fn spawn(&self, request: &LaunchRequest) -> Result<(), BrowserError> {
150 let executable = self.config.chrome_executable()?;
151 let agent = user_agent(
152 self.config.platform,
153 chrome_major(self.config.platform, &executable),
154 );
155 let arguments = chrome_arguments(&ArgumentSpec {
156 port: self.config.port,
157 profile: &self.config.profile,
158 headless: request.headless,
159 user_agent: &agent,
160 start_urls: &request.start_urls,
161 });
191 let executable = self.config.executable()?;
192 let arguments = match self.config.engine {
193 Engine::Chromium => {
194 let agent = user_agent(
195 self.config.platform,
196 chrome_major(self.config.platform, &executable),
197 );
198 chrome_arguments(&ArgumentSpec {
199 port: self.config.port,
200 profile: &self.config.profile,
201 headless: request.headless,
202 user_agent: &agent,
203 start_urls: &request.start_urls,
204 })
205 }
206 Engine::Firefox => {
207 write_firefox_prefs(&self.config.profile)?;
208 firefox_arguments(&ArgumentSpec {
209 port: self.config.port,
210 profile: &self.config.profile,
211 headless: request.headless,
212 user_agent: "",
213 start_urls: &request.start_urls,
214 })
215 }
216 };
162 217 let mut command = Command::new(&executable);
163 218 strip_app_fontconfig(&mut command);
164 219 command
@@ -180,6 +235,10 @@ impl Launcher for SystemLauncher {
180 235 fn kill_listener(&self, port: u16) -> Result<(), BrowserError> {
181 236 crate::process::kill_listener(self.config.platform, port)
182 237 }
238
239 fn terminate_listener(&self, port: u16) -> Result<(), BrowserError> {
240 crate::process::terminate_listener(self.config.platform, port)
241 }
183 242 }
184 243
185 244 #[cfg(unix)]
@@ -247,6 +306,26 @@ mod tests {
247 306 assert_eq!(&arguments[4..], ["https://a/", "https://b/"]);
248 307 }
249 308
309 #[test]
310 fn firefox_arguments_use_bidi_port_own_profile_and_no_user_agent() {
311 let urls = vec!["https://teams.cloud.microsoft/".to_owned()];
312 let headless = firefox_arguments(&spec(true, &urls));
313 assert_eq!(
314 headless,
315 [
316 "--remote-debugging-port=9222",
317 "--profile",
318 r"C:\p\rusty-teams-chrome",
319 "--no-remote",
320 "--headless",
321 "--window-size=1400,1000",
322 "https://teams.cloud.microsoft/",
323 ]
324 );
325 let visible = firefox_arguments(&spec(false, &urls));
326 assert!(!visible.iter().any(|argument| argument.contains("headless")));
327 }
328
250 329 #[test]
251 330 fn user_agents_per_platform() {
252 331 assert!(user_agent(Platform::Wsl, 154).contains("Windows NT 10.0; Win64; x64"));
@@ -1,7 +1,7 @@
1use std::path::Path;
1use std::path::Path;
2use std::process::{Command, Stdio};
2use std::process::{Command, Stdio};
3
3
4use crate::config::{Config, Platform};
4use crate::config::{Config, Engine, Platform};
5use crate::error::BrowserError;
5use crate::error::BrowserError;
6
6
7#[derive(Debug, Clone)]
7#[derive(Debug, Clone)]
@@ -13,6 +13,11 @@ pub struct LaunchRequest {
13pub trait Launcher: Send + Sync {
13pub trait Launcher: Send + Sync {
14 fn spawn(&self, request: &LaunchRequest) -> Result<(), BrowserError>;
14 fn spawn(&self, request: &LaunchRequest) -> Result<(), BrowserError>;
15 fn kill_listener(&self, port: u16) -> Result<(), BrowserError>;
15 fn kill_listener(&self, port: u16) -> Result<(), BrowserError>;
16
17 /// Lets the browser on `port` quit cleanly and returns once it is gone.
18 fn terminate_listener(&self, port: u16) -> Result<(), BrowserError> {
19 self.kill_listener(port)
20 }
16}
21}
17
22
18pub struct ArgumentSpec<'a> {
23pub struct ArgumentSpec<'a> {
@@ -55,6 +60,42 @@ pub fn chrome_arguments(spec: &ArgumentSpec) -> Vec<String> {
55 arguments
60 arguments
56}
61}
57
62
63/// Firefox keeps its own user agent: headless Firefox does not mark itself, so Microsoft accepts it.
64pub fn firefox_arguments(spec: &ArgumentSpec) -> Vec<String> {
65 let mut arguments = vec![
66 format!("--remote-debugging-port={}", spec.port),
67 "--profile".into(),
68 spec.profile.into(),
69 "--no-remote".into(),
70 ];
71 if spec.headless {
72 arguments.extend(["--headless".into(), "--window-size=1400,1000".into()]);
73 }
74 arguments.extend(spec.start_urls.iter().cloned());
75 arguments
76}
77
78/// Prefs for the app's own Firefox profile: no first-run pages, no restored tabs, no quit prompts,
79/// no Safe Mode.
80const FIREFOX_PREFS: &str = r#"user_pref("browser.shell.checkDefaultBrowser", false);
81user_pref("browser.startup.homepage_override.mstone", "ignore");
82user_pref("browser.startup.page", 0);
83user_pref("browser.aboutwelcome.enabled", false);
84user_pref("browser.sessionstore.resume_from_crash", false);
85user_pref("browser.tabs.warnOnClose", false);
86user_pref("browser.warnOnQuit", false);
87user_pref("datareporting.policy.dataSubmissionPolicyBypassNotification", true);
88user_pref("toolkit.telemetry.reportingpolicy.firstRun", false);
89// A browser the app stopped hard counts as a startup crash; Safe Mode would hang a headless start.
90user_pref("toolkit.startup.max_resumed_crashes", -1);
91user_pref("zen.welcome-screen.seen", true);
92"#;
93
94fn write_firefox_prefs(profile: &str) -> std::io::Result<()> {
95 std::fs::create_dir_all(profile)?;
96 std::fs::write(Path::new(profile).join("user.js"), FIREFOX_PREFS)
97}
98
58pub fn user_agent(platform: Platform, major: u32) -> String {
99pub fn user_agent(platform: Platform, major: u32) -> String {
59 let system = match platform {
100 let system = match platform {
60 Platform::Linux => "X11; Linux x86_64",
101 Platform::Linux => "X11; Linux x86_64",
@@ -147,18 +188,32 @@ impl SystemLauncher {
147
188
148impl Launcher for SystemLauncher {
189impl Launcher for SystemLauncher {
149 fn spawn(&self, request: &LaunchRequest) -> Result<(), BrowserError> {
190 fn spawn(&self, request: &LaunchRequest) -> Result<(), BrowserError> {
150 let executable = self.config.chrome_executable()?;
191 let executable = self.config.executable()?;
151 let agent = user_agent(
192 let arguments = match self.config.engine {
152 self.config.platform,
193 Engine::Chromium => {
153 chrome_major(self.config.platform, &executable),
194 let agent = user_agent(
154 );
195 self.config.platform,
155 let arguments = chrome_arguments(&ArgumentSpec {
196 chrome_major(self.config.platform, &executable),
156 port: self.config.port,
197 );
157 profile: &self.config.profile,
198 chrome_arguments(&ArgumentSpec {
158 headless: request.headless,
199 port: self.config.port,
159 user_agent: &agent,
200 profile: &self.config.profile,
160 start_urls: &request.start_urls,
201 headless: request.headless,
161 });
202 user_agent: &agent,
203 start_urls: &request.start_urls,
204 })
205 }
206 Engine::Firefox => {
207 write_firefox_prefs(&self.config.profile)?;
208 firefox_arguments(&ArgumentSpec {
209 port: self.config.port,
210 profile: &self.config.profile,
211 headless: request.headless,
212 user_agent: "",
213 start_urls: &request.start_urls,
214 })
215 }
216 };
162 let mut command = Command::new(&executable);
217 let mut command = Command::new(&executable);
163 strip_app_fontconfig(&mut command);
218 strip_app_fontconfig(&mut command);
164 command
219 command
@@ -180,6 +235,10 @@ impl Launcher for SystemLauncher {
180 fn kill_listener(&self, port: u16) -> Result<(), BrowserError> {
235 fn kill_listener(&self, port: u16) -> Result<(), BrowserError> {
181 crate::process::kill_listener(self.config.platform, port)
236 crate::process::kill_listener(self.config.platform, port)
182 }
237 }
238
239 fn terminate_listener(&self, port: u16) -> Result<(), BrowserError> {
240 crate::process::terminate_listener(self.config.platform, port)
241 }
183}
242}
184
243
185#[cfg(unix)]
244#[cfg(unix)]
@@ -247,6 +306,26 @@ mod tests {
247 assert_eq!(&arguments[4..], ["https://a/", "https://b/"]);
306 assert_eq!(&arguments[4..], ["https://a/", "https://b/"]);
248 }
307 }
249
308
309 #[test]
310 fn firefox_arguments_use_bidi_port_own_profile_and_no_user_agent() {
311 let urls = vec!["https://teams.cloud.microsoft/".to_owned()];
312 let headless = firefox_arguments(&spec(true, &urls));
313 assert_eq!(
314 headless,
315 [
316 "--remote-debugging-port=9222",
317 "--profile",
318 r"C:\p\rusty-teams-chrome",
319 "--no-remote",
320 "--headless",
321 "--window-size=1400,1000",
322 "https://teams.cloud.microsoft/",
323 ]
324 );
325 let visible = firefox_arguments(&spec(false, &urls));
326 assert!(!visible.iter().any(|argument| argument.contains("headless")));
327 }
328
250 #[test]
329 #[test]
251 fn user_agents_per_platform() {
330 fn user_agents_per_platform() {
252 assert!(user_agent(Platform::Wsl, 154).contains("Windows NT 10.0; Win64; x64"));
331 assert!(user_agent(Platform::Wsl, 154).contains("Windows NT 10.0; Win64; x64"));
crates/browser/src/lib.rs +10 −2
@@ -1,3 +1,5 @@
1 mod bidi;
2 mod bidi_transport;
1 3 mod browser;
2 4 mod config;
3 5 mod error;
@@ -7,11 +9,17 @@ mod process;
7 9 mod targets;
8 10 mod watchdog;
9 11
12 pub use bidi::{Bidi, Context, remote_value_to_json};
13 pub use bidi_transport::{BidiTransport, session_transport};
10 14 pub use browser::{Browser, RendererState, Status, Timeouts};
11 pub use config::{Config, ConfigInputs, DEFAULT_PORT, PROFILE_NAME, Platform, windows_path_to_wsl};
15 pub use config::{
16 BROWSER_OVERRIDE_ENV, Config, ConfigInputs, DEFAULT_PORT, Engine, FIREFOX_PROFILE_NAME,
17 PROFILE_NAME, Platform, windows_path_to_wsl,
18 };
12 19 pub use error::BrowserError;
13 20 pub use launch::{
14 ArgumentSpec, LaunchRequest, Launcher, SystemLauncher, chrome_arguments, user_agent,
21 ArgumentSpec, LaunchRequest, Launcher, SystemLauncher, chrome_arguments, firefox_arguments,
22 user_agent,
15 23 };
16 24 pub use targets::{APPS, App, LoginState, Mode, Tab};
17 25 pub use watchdog::{BrowserEvent, Watchdog, WatchdogConfig};
@@ -1,3 +1,5 @@
1mod bidi;
2mod bidi_transport;
1mod browser;
3mod browser;
2mod config;
4mod config;
3mod error;
5mod error;
@@ -7,11 +9,17 @@ mod process;
7mod targets;
9mod targets;
8mod watchdog;
10mod watchdog;
9
11
12pub use bidi::{Bidi, Context, remote_value_to_json};
13pub use bidi_transport::{BidiTransport, session_transport};
10pub use browser::{Browser, RendererState, Status, Timeouts};
14pub use browser::{Browser, RendererState, Status, Timeouts};
11pub use config::{Config, ConfigInputs, DEFAULT_PORT, PROFILE_NAME, Platform, windows_path_to_wsl};
15pub use config::{
16 BROWSER_OVERRIDE_ENV, Config, ConfigInputs, DEFAULT_PORT, Engine, FIREFOX_PROFILE_NAME,
17 PROFILE_NAME, Platform, windows_path_to_wsl,
18};
12pub use error::BrowserError;
19pub use error::BrowserError;
13pub use launch::{
20pub use launch::{
14 ArgumentSpec, LaunchRequest, Launcher, SystemLauncher, chrome_arguments, user_agent,
21 ArgumentSpec, LaunchRequest, Launcher, SystemLauncher, chrome_arguments, firefox_arguments,
22 user_agent,
15};
23};
16pub use targets::{APPS, App, LoginState, Mode, Tab};
24pub use targets::{APPS, App, LoginState, Mode, Tab};
17pub use watchdog::{BrowserEvent, Watchdog, WatchdogConfig};
25pub use watchdog::{BrowserEvent, Watchdog, WatchdogConfig};
crates/browser/src/process.rs +70 −8
@@ -1,4 +1,5 @@
1 1 use std::process::Command;
2 use std::time::{Duration, Instant};
2 3
3 4 use crate::config::Platform;
4 5 use crate::error::BrowserError;
@@ -54,16 +55,27 @@ fn listener_pid(platform: Platform, port: u16) -> Result<u32, BrowserError> {
54 55 pid.ok_or_else(|| BrowserError::Cdp(format!("no process listens on port {port}")))
55 56 }
56 57
57 pub(crate) fn is_chrome_image(image_name: &str) -> bool {
58 // macOS `ps -o comm=` may return a full path; match on the basename.
58 /// Lowercased basename: macOS `ps -o comm=` may return a full path.
59 fn image_base(image_name: &str) -> String {
59 60 let trimmed = image_name.trim().trim_matches('"');
60 61 let base = trimmed.rsplit(['/', '\\']).next().unwrap_or(trimmed).trim();
61 let lowered = base.to_ascii_lowercase();
62 base.to_ascii_lowercase()
63 }
64
65 pub(crate) fn is_chrome_image(image_name: &str) -> bool {
66 let lowered = image_base(image_name);
62 67 lowered.starts_with("chrome")
63 68 || lowered.starts_with("google chrome")
64 69 || lowered.starts_with("chromium")
65 70 }
66 71
72 pub(crate) fn is_firefox_image(image_name: &str) -> bool {
73 let lowered = image_base(image_name);
74 ["firefox", "zen", "librewolf", "floorp"]
75 .iter()
76 .any(|name| lowered.starts_with(name))
77 }
78
67 79 fn process_image_name(platform: Platform, pid: &str) -> Result<String, BrowserError> {
68 80 let filter = format!("PID eq {pid}");
69 81 let csv_arguments = ["/FI", filter.as_str(), "/FO", "CSV", "/NH"];
@@ -76,18 +88,56 @@ fn process_image_name(platform: Platform, pid: &str) -> Result<String, BrowserEr
76 88 Ok(output.split(',').next().unwrap_or_default().to_owned())
77 89 }
78 90
91 const EXIT_WAIT: Duration = Duration::from_secs(10);
92 const EXIT_POLL: Duration = Duration::from_millis(100);
93
94 /// Asks the browser holding `port` to quit with SIGTERM and waits until the process is gone, so
95 /// its profile is free again. Firefox on macOS keeps running after WebDriver BiDi `browser.close`.
96 pub(crate) fn terminate_listener(platform: Platform, port: u16) -> Result<(), BrowserError> {
97 let pid = browser_listener_pid(platform, port)?;
98 if !platform.uses_unix_paths() {
99 return kill_pid(platform, &pid);
100 }
101 Command::new("kill").args(["-TERM", &pid]).output()?;
102 let deadline = Instant::now() + EXIT_WAIT;
103 while Instant::now() < deadline {
104 let alive = Command::new("kill")
105 .args(["-0", &pid])
106 .output()?
107 .status
108 .success();
109 if !alive {
110 return Ok(());
111 }
112 std::thread::sleep(EXIT_POLL);
113 }
114 Err(BrowserError::Cdp(format!(
115 "pid {pid} did not exit after SIGTERM"
116 )))
117 }
118
79 119 pub(crate) fn kill_listener(platform: Platform, port: u16) -> Result<(), BrowserError> {
120 let pid = browser_listener_pid(platform, port)?;
121 kill_pid(platform, &pid)
122 }
123
124 /// The PID listening on `port`, only when it is a browser: never signal anything else.
125 fn browser_listener_pid(platform: Platform, port: u16) -> Result<String, BrowserError> {
80 126 let pid = listener_pid(platform, port)?.to_string();
81 127 let image_name = process_image_name(platform, &pid)?;
82 if !is_chrome_image(&image_name) {
128 if !is_chrome_image(&image_name) && !is_firefox_image(&image_name) {
83 129 return Err(BrowserError::Cdp(format!(
84 "port {port} is held by a non-Chrome process, not killing it"
130 "port {port} is held by a process that is no known browser, not killing it"
85 131 )));
86 132 }
133 Ok(pid)
134 }
135
136 fn kill_pid(platform: Platform, pid: &str) -> Result<(), BrowserError> {
87 137 let (program, arguments): (&str, Vec<&str>) = match platform {
88 Platform::Linux | Platform::Macos => ("kill", vec!["-KILL", &pid]),
89 Platform::Windows => ("taskkill", vec!["/PID", &pid, "/T", "/F"]),
90 Platform::Wsl => ("taskkill.exe", vec!["/PID", &pid, "/T", "/F"]),
138 Platform::Linux | Platform::Macos => ("kill", vec!["-KILL", pid]),
139 Platform::Windows => ("taskkill", vec!["/PID", pid, "/T", "/F"]),
140 Platform::Wsl => ("taskkill.exe", vec!["/PID", pid, "/T", "/F"]),
91 141 };
92 142 let status = Command::new(program).args(arguments).output()?.status;
93 143 if status.success() {
@@ -125,6 +175,18 @@ mod tests {
125 175 assert!(!is_chrome_image(""));
126 176 }
127 177
178 #[test]
179 fn firefox_family_images_are_recognised() {
180 assert!(is_firefox_image(
181 "/Applications/Firefox.app/Contents/MacOS/firefox"
182 ));
183 assert!(is_firefox_image("/Applications/Zen.app/Contents/MacOS/zen"));
184 assert!(is_firefox_image("zen-browser\n"));
185 assert!(is_firefox_image("librewolf"));
186 assert!(!is_firefox_image("/usr/bin/chromium"));
187 assert!(!is_firefox_image(""));
188 }
189
128 190 #[test]
129 191 fn reads_pid_from_netstat() {
130 192 let table = " TCP 127.0.0.1:19222 0.0.0.0:0 LISTENING 111\r\n TCP 127.0.0.1:9222 0.0.0.0:0 LISTENING 5150\r\n TCP 127.0.0.1:9222 127.0.0.1:50000 ESTABLISHED 5150\r\n";
@@ -1,4 +1,5 @@
1use std::process::Command;
1use std::process::Command;
2use std::time::{Duration, Instant};
2
3
3use crate::config::Platform;
4use crate::config::Platform;
4use crate::error::BrowserError;
5use crate::error::BrowserError;
@@ -54,16 +55,27 @@ fn listener_pid(platform: Platform, port: u16) -> Result<u32, BrowserError> {
54 pid.ok_or_else(|| BrowserError::Cdp(format!("no process listens on port {port}")))
55 pid.ok_or_else(|| BrowserError::Cdp(format!("no process listens on port {port}")))
55}
56}
56
57
57pub(crate) fn is_chrome_image(image_name: &str) -> bool {
58/// Lowercased basename: macOS `ps -o comm=` may return a full path.
58 // macOS `ps -o comm=` may return a full path; match on the basename.
59fn image_base(image_name: &str) -> String {
59 let trimmed = image_name.trim().trim_matches('"');
60 let trimmed = image_name.trim().trim_matches('"');
60 let base = trimmed.rsplit(['/', '\\']).next().unwrap_or(trimmed).trim();
61 let base = trimmed.rsplit(['/', '\\']).next().unwrap_or(trimmed).trim();
61 let lowered = base.to_ascii_lowercase();
62 base.to_ascii_lowercase()
63}
64
65pub(crate) fn is_chrome_image(image_name: &str) -> bool {
66 let lowered = image_base(image_name);
62 lowered.starts_with("chrome")
67 lowered.starts_with("chrome")
63 || lowered.starts_with("google chrome")
68 || lowered.starts_with("google chrome")
64 || lowered.starts_with("chromium")
69 || lowered.starts_with("chromium")
65}
70}
66
71
72pub(crate) fn is_firefox_image(image_name: &str) -> bool {
73 let lowered = image_base(image_name);
74 ["firefox", "zen", "librewolf", "floorp"]
75 .iter()
76 .any(|name| lowered.starts_with(name))
77}
78
67fn process_image_name(platform: Platform, pid: &str) -> Result<String, BrowserError> {
79fn process_image_name(platform: Platform, pid: &str) -> Result<String, BrowserError> {
68 let filter = format!("PID eq {pid}");
80 let filter = format!("PID eq {pid}");
69 let csv_arguments = ["/FI", filter.as_str(), "/FO", "CSV", "/NH"];
81 let csv_arguments = ["/FI", filter.as_str(), "/FO", "CSV", "/NH"];
@@ -76,18 +88,56 @@ fn process_image_name(platform: Platform, pid: &str) -> Result<String, BrowserEr
76 Ok(output.split(',').next().unwrap_or_default().to_owned())
88 Ok(output.split(',').next().unwrap_or_default().to_owned())
77}
89}
78
90
91const EXIT_WAIT: Duration = Duration::from_secs(10);
92const EXIT_POLL: Duration = Duration::from_millis(100);
93
94/// Asks the browser holding `port` to quit with SIGTERM and waits until the process is gone, so
95/// its profile is free again. Firefox on macOS keeps running after WebDriver BiDi `browser.close`.
96pub(crate) fn terminate_listener(platform: Platform, port: u16) -> Result<(), BrowserError> {
97 let pid = browser_listener_pid(platform, port)?;
98 if !platform.uses_unix_paths() {
99 return kill_pid(platform, &pid);
100 }
101 Command::new("kill").args(["-TERM", &pid]).output()?;
102 let deadline = Instant::now() + EXIT_WAIT;
103 while Instant::now() < deadline {
104 let alive = Command::new("kill")
105 .args(["-0", &pid])
106 .output()?
107 .status
108 .success();
109 if !alive {
110 return Ok(());
111 }
112 std::thread::sleep(EXIT_POLL);
113 }
114 Err(BrowserError::Cdp(format!(
115 "pid {pid} did not exit after SIGTERM"
116 )))
117}
118
79pub(crate) fn kill_listener(platform: Platform, port: u16) -> Result<(), BrowserError> {
119pub(crate) fn kill_listener(platform: Platform, port: u16) -> Result<(), BrowserError> {
120 let pid = browser_listener_pid(platform, port)?;
121 kill_pid(platform, &pid)
122}
123
124/// The PID listening on `port`, only when it is a browser: never signal anything else.
125fn browser_listener_pid(platform: Platform, port: u16) -> Result<String, BrowserError> {
80 let pid = listener_pid(platform, port)?.to_string();
126 let pid = listener_pid(platform, port)?.to_string();
81 let image_name = process_image_name(platform, &pid)?;
127 let image_name = process_image_name(platform, &pid)?;
82 if !is_chrome_image(&image_name) {
128 if !is_chrome_image(&image_name) && !is_firefox_image(&image_name) {
83 return Err(BrowserError::Cdp(format!(
129 return Err(BrowserError::Cdp(format!(
84 "port {port} is held by a non-Chrome process, not killing it"
130 "port {port} is held by a process that is no known browser, not killing it"
85 )));
131 )));
86 }
132 }
133 Ok(pid)
134}
135
136fn kill_pid(platform: Platform, pid: &str) -> Result<(), BrowserError> {
87 let (program, arguments): (&str, Vec<&str>) = match platform {
137 let (program, arguments): (&str, Vec<&str>) = match platform {
88 Platform::Linux | Platform::Macos => ("kill", vec!["-KILL", &pid]),
138 Platform::Linux | Platform::Macos => ("kill", vec!["-KILL", pid]),
89 Platform::Windows => ("taskkill", vec!["/PID", &pid, "/T", "/F"]),
139 Platform::Windows => ("taskkill", vec!["/PID", pid, "/T", "/F"]),
90 Platform::Wsl => ("taskkill.exe", vec!["/PID", &pid, "/T", "/F"]),
140 Platform::Wsl => ("taskkill.exe", vec!["/PID", pid, "/T", "/F"]),
91 };
141 };
92 let status = Command::new(program).args(arguments).output()?.status;
142 let status = Command::new(program).args(arguments).output()?.status;
93 if status.success() {
143 if status.success() {
@@ -125,6 +175,18 @@ mod tests {
125 assert!(!is_chrome_image(""));
175 assert!(!is_chrome_image(""));
126 }
176 }
127
177
178 #[test]
179 fn firefox_family_images_are_recognised() {
180 assert!(is_firefox_image(
181 "/Applications/Firefox.app/Contents/MacOS/firefox"
182 ));
183 assert!(is_firefox_image("/Applications/Zen.app/Contents/MacOS/zen"));
184 assert!(is_firefox_image("zen-browser\n"));
185 assert!(is_firefox_image("librewolf"));
186 assert!(!is_firefox_image("/usr/bin/chromium"));
187 assert!(!is_firefox_image(""));
188 }
189
128 #[test]
190 #[test]
129 fn reads_pid_from_netstat() {
191 fn reads_pid_from_netstat() {
130 let table = " TCP 127.0.0.1:19222 0.0.0.0:0 LISTENING 111\r\n TCP 127.0.0.1:9222 0.0.0.0:0 LISTENING 5150\r\n TCP 127.0.0.1:9222 127.0.0.1:50000 ESTABLISHED 5150\r\n";
192 let table = " TCP 127.0.0.1:19222 0.0.0.0:0 LISTENING 111\r\n TCP 127.0.0.1:9222 0.0.0.0:0 LISTENING 5150\r\n TCP 127.0.0.1:9222 127.0.0.1:50000 ESTABLISHED 5150\r\n";
crates/browser/src/targets.rs +1 −1
@@ -120,7 +120,7 @@ fn https_host(url: &str) -> Option<String> {
120 120 (parsed.scheme() == "https").then(|| parsed.host_str().map(str::to_owned))?
121 121 }
122 122
123 fn tab_from_url(id: String, url: &str) -> Tab {
123 pub(crate) fn tab_from_url(id: String, url: &str) -> Tab {
124 124 let host = Url::parse(url)
125 125 .ok()
126 126 .and_then(|parsed| parsed.host_str().map(str::to_owned));
@@ -120,7 +120,7 @@ fn https_host(url: &str) -> Option<String> {
120 (parsed.scheme() == "https").then(|| parsed.host_str().map(str::to_owned))?
120 (parsed.scheme() == "https").then(|| parsed.host_str().map(str::to_owned))?
121}
121}
122
122
123fn tab_from_url(id: String, url: &str) -> Tab {
123pub(crate) fn tab_from_url(id: String, url: &str) -> Tab {
124 let host = Url::parse(url)
124 let host = Url::parse(url)
125 .ok()
125 .ok()
126 .and_then(|parsed| parsed.host_str().map(str::to_owned));
126 .and_then(|parsed| parsed.host_str().map(str::to_owned));
docs/decisions/0003-sign-in-through-a-browser-session.md +7 −3
@@ -15,13 +15,17 @@ Options were: a stored refresh token, an embedded engine per OS, or a real Chrom
15 15
16 16 Windows keeps WebView2.
17 17
18 On Linux and macOS the app starts Chrome or Chromium with remote debugging and its own profile, shows it for login, and hides it again afterwards. The app finds Chrome in the usual install locations. Only that managed Chrome may be stopped via the debug port. A second launch brings the existing instance forward. The UI can paint from the local cache before the network answers.
18 On Linux and macOS the app starts Chrome or Chromium with remote debugging and its own profile, shows it for login, and hides it again afterwards. Without a Chromium browser it does the same with a Firefox browser over WebDriver BiDi. The app finds Chrome in the usual install locations. Only that managed Chrome may be stopped via the debug port. A second launch brings the existing instance forward. The UI can paint from the local cache before the network answers.
19 19
20 20 Tokens are not written to disk. The browser profile holds the session.
21 21
22 22 ## Consequences
23 23
24 - Linux needs a Chrome or Chromium install. macOS takes the first Chromium browser it finds: Chrome, Chromium, Edge, Brave, Helium or Vivaldi. Each runs with the app's own profile, so the user's everyday profile is never touched.
24 - Linux needs a Chrome or Chromium install, or a Firefox browser. macOS takes the first Chromium browser it finds: Chrome, Chromium, Edge, Brave, Helium or Vivaldi. Each runs with the app's own profile, so the user's everyday profile is never touched.
25 - Without a Chromium browser, Linux and macOS start a Firefox browser instead (Firefox, Zen, LibreWolf, Floorp) with its own `rusty-teams-firefox` profile. `RUSTY_TEAMS_SIGN_IN_BROWSER` names an executable to use either way.
26 - Firefox has no CDP any more, so it runs over WebDriver BiDi. Its transport answers the few CDP calls the session layer sends (evaluate, bindings, injected scripts, navigate, reload) with BiDi commands, so nothing above the transport knows the difference.
27 - Firefox allows one BiDi session per browser and keeps it after the socket closes. The app holds one shared connection; when a crashed earlier run left its session behind, the app restarts the managed Firefox.
28 - Firefox stops with SIGTERM: BiDi `browser.close` leaves the process and its profile lock alive on macOS. Its profile turns off Safe Mode, which hard stops would trigger and which hangs a headless start.
25 29 - Forks print their own version in `--version` (`Helium 0.21.3.1 (Chromium 157.0.8103.78)`), so the user agent takes the highest major in that line.
26 30 - Sign-in bugs are browser and profile bugs, not a second token store to rotate.
27 - The headless user agent must look like desktop Chrome on that OS, or Microsoft rejects the session.
31 - Headless Chromium's user agent must look like desktop Chrome on that OS, or Microsoft rejects the session. Headless Firefox keeps its normal user agent.
@@ -15,13 +15,17 @@ Options were: a stored refresh token, an embedded engine per OS, or a real Chrom
15
15
16Windows keeps WebView2.
16Windows keeps WebView2.
17
17
18On Linux and macOS the app starts Chrome or Chromium with remote debugging and its own profile, shows it for login, and hides it again afterwards. The app finds Chrome in the usual install locations. Only that managed Chrome may be stopped via the debug port. A second launch brings the existing instance forward. The UI can paint from the local cache before the network answers.
18On Linux and macOS the app starts Chrome or Chromium with remote debugging and its own profile, shows it for login, and hides it again afterwards. Without a Chromium browser it does the same with a Firefox browser over WebDriver BiDi. The app finds Chrome in the usual install locations. Only that managed Chrome may be stopped via the debug port. A second launch brings the existing instance forward. The UI can paint from the local cache before the network answers.
19
19
20Tokens are not written to disk. The browser profile holds the session.
20Tokens are not written to disk. The browser profile holds the session.
21
21
22## Consequences
22## Consequences
23
23
24- Linux needs a Chrome or Chromium install. macOS takes the first Chromium browser it finds: Chrome, Chromium, Edge, Brave, Helium or Vivaldi. Each runs with the app's own profile, so the user's everyday profile is never touched.
24- Linux needs a Chrome or Chromium install, or a Firefox browser. macOS takes the first Chromium browser it finds: Chrome, Chromium, Edge, Brave, Helium or Vivaldi. Each runs with the app's own profile, so the user's everyday profile is never touched.
25- Without a Chromium browser, Linux and macOS start a Firefox browser instead (Firefox, Zen, LibreWolf, Floorp) with its own `rusty-teams-firefox` profile. `RUSTY_TEAMS_SIGN_IN_BROWSER` names an executable to use either way.
26- Firefox has no CDP any more, so it runs over WebDriver BiDi. Its transport answers the few CDP calls the session layer sends (evaluate, bindings, injected scripts, navigate, reload) with BiDi commands, so nothing above the transport knows the difference.
27- Firefox allows one BiDi session per browser and keeps it after the socket closes. The app holds one shared connection; when a crashed earlier run left its session behind, the app restarts the managed Firefox.
28- Firefox stops with SIGTERM: BiDi `browser.close` leaves the process and its profile lock alive on macOS. Its profile turns off Safe Mode, which hard stops would trigger and which hangs a headless start.
25- Forks print their own version in `--version` (`Helium 0.21.3.1 (Chromium 157.0.8103.78)`), so the user agent takes the highest major in that line.
29- Forks print their own version in `--version` (`Helium 0.21.3.1 (Chromium 157.0.8103.78)`), so the user agent takes the highest major in that line.
26- Sign-in bugs are browser and profile bugs, not a second token store to rotate.
30- Sign-in bugs are browser and profile bugs, not a second token store to rotate.
27- The headless user agent must look like desktop Chrome on that OS, or Microsoft rejects the session.
31- Headless Chromium's user agent must look like desktop Chrome on that OS, or Microsoft rejects the session. Headless Firefox keeps its normal user agent.