Merge pull request #54: feat(browser): sign in with Firefox or Zen instead of Chrome
@@ -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",@@ -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 your default browser on its own when it is Chromium- or Firefox-based (Chrome, Chromium, Firefox, Zen, LibreWolf, Floorp), else the first one installed; Settings > General > Teams session browser picks another (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 your default browser on its own when it is Chromium- or Firefox-based (Google Chrome, Chromium, Microsoft Edge, Brave, Helium, Vivaldi, Firefox, Zen, LibreWolf, Floorp), else the first one installed; Settings > General > Teams session browser picks another (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 your default browser on its own when it is Chromium- or Firefox-based (Chrome, Chromium, Firefox, Zen, LibreWolf, Floorp), else the first one installed; Settings > General > Teams session browser picks another (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 your default browser on its own when it is Chromium- or Firefox-based (Google Chrome, Chromium, Microsoft Edge, Brave, Helium, Vivaldi, Firefox, Zen, LibreWolf, Floorp), else the first one installed; Settings > General > Teams session browser picks another (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
The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).96
The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).97
97
@@ -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. Settings > General > Teams session browser picks the browser; Automatic takes the default browser when it is supported, else the first installed; 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. Settings > General > Teams session browser picks the browser; Automatic takes the default browser when it is supported, else the first installed; 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 list44
## Chat list@@ -410,12 +410,21 @@ settings:
410
410
close_to_tray_detail:
411
411
en: The title bar X hides the window to the tray
412
412
de: Das X in der Titelleiste blendet das Fenster ins Infobereich-Symbol aus
413
sign_in_browser:
414
en: Teams session browser
415
de: Browser der Teams-Sitzung
416
sign_in_browser_detail:
417
en: Teams runs in its own profile of this browser, hidden after sign-in. Automatic takes your default browser if it is Chromium- or Firefox-based. Changing it restarts the app.
418
de: Teams läuft in einem eigenen Profil dieses Browsers, nach der Anmeldung verborgen. Automatisch nimmt Ihren Standardbrowser, wenn er auf Chromium oder Firefox basiert. Eine Änderung startet die App neu.
419
sign_in_browser_automatic:
420
en: Automatic
421
de: Automatisch
413
422
external_browser:
414
423
en: Open links and Google sign-in with
415
424
de: Links und Google-Anmeldung öffnen mit
416
425
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).
426
en: Does not change the Teams session browser.
427
de: Ändert nicht den Browser der Teams-Sitzung.
419
428
external_browser_system:
420
429
en: System default
421
430
de: Systemstandard
@@ -1623,8 +1632,8 @@ auth:
1623
1632
en: Finishing sign-in…
1624
1633
de: Anmeldung wird abgeschlossen…
1625
1634
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)
1635
en: Could not open a browser for sign-in (Chrome, Edge, Brave, Helium, Firefox, Zen)
1636
de: Kein Browser für die Anmeldung konnte geöffnet werden (Chrome, Edge, Brave, Helium, Firefox, Zen)
1628
1637
browser_still_loading_hint:
1629
1638
en: The Teams logo in the browser means the login page is still loading
1630
1639
de: Das Teams-Logo im Browser heisst, die Anmeldeseite lädt noch
@@ -410,12 +410,21 @@ settings:410
close_to_tray_detail:410
close_to_tray_detail:411
en: The title bar X hides the window to the tray411
en: The title bar X hides the window to the tray412
de: Das X in der Titelleiste blendet das Fenster ins Infobereich-Symbol aus412
de: Das X in der Titelleiste blendet das Fenster ins Infobereich-Symbol aus413
sign_in_browser:414
en: Teams session browser415
de: Browser der Teams-Sitzung416
sign_in_browser_detail:417
en: Teams runs in its own profile of this browser, hidden after sign-in. Automatic takes your default browser if it is Chromium- or Firefox-based. Changing it restarts the app.418
de: Teams läuft in einem eigenen Profil dieses Browsers, nach der Anmeldung verborgen. Automatisch nimmt Ihren Standardbrowser, wenn er auf Chromium oder Firefox basiert. Eine Änderung startet die App neu.419
sign_in_browser_automatic:420
en: Automatic421
de: Automatisch413
external_browser:422
external_browser:414
en: Open links and Google sign-in with423
en: Open links and Google sign-in with415
de: Links und Google-Anmeldung öffnen mit424
de: Links und Google-Anmeldung öffnen mit416
external_browser_detail:425
external_browser_detail:417
en: Does not change the Teams session browser (that needs a Chromium browser such as Chrome, Edge, Brave or Helium).426
en: Does not change the Teams session browser.418
de: Ändert nicht den Browser der Teams-Sitzung (dafür bleibt ein Chromium-Browser wie Chrome, Edge, Brave oder Helium nötig).427
de: Ändert nicht den Browser der Teams-Sitzung.419
external_browser_system:428
external_browser_system:420
en: System default429
en: System default421
de: Systemstandard430
de: Systemstandard@@ -1623,8 +1632,8 @@ auth:1623
en: Finishing sign-in…1632
en: Finishing sign-in…1624
de: Anmeldung wird abgeschlossen…1633
de: Anmeldung wird abgeschlossen…1625
browser_failed:1634
browser_failed:1626
en: Could not open a Chromium browser (Chrome, Edge, Brave, Helium)1635
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)1636
de: Kein Browser für die Anmeldung konnte geöffnet werden (Chrome, Edge, Brave, Helium, Firefox, Zen)1628
browser_still_loading_hint:1637
browser_still_loading_hint:1629
en: The Teams logo in the browser means the login page is still loading1638
en: The Teams logo in the browser means the login page is still loading1630
de: Das Teams-Logo im Browser heisst, die Anmeldeseite lädt noch1639
de: Das Teams-Logo im Browser heisst, die Anmeldeseite lädt noch@@ -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
227
struct LinuxTransport {227
struct 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,@@ -234,6 +234,7 @@ fn external_browser_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
234
234
.collect();
235
235
vec![
236
236
caption(tr("settings.caption.browser")).into_any_element(),
237
sign_in_browser_row(),
237
238
control_row(
238
239
tr("settings.general.external_browser"),
239
240
tr("settings.general.external_browser_detail"),
@@ -244,6 +245,84 @@ fn external_browser_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
244
245
}
245
246
}
246
247
248
/// The browser the Teams session runs in. Changing it restarts the app, which stops the old
249
/// browser on the way out and starts the new one.
250
#[cfg(any(target_os = "linux", target_os = "macos"))]
251
fn sign_in_browser_row() -> AnyElement {
252
use std::sync::LazyLock;
253
254
use browser::{InstalledBrowser, SignInBrowser};
255
256
static INSTALLED: LazyLock<Vec<InstalledBrowser>> = LazyLock::new(browser::installed_browsers);
257
static AUTOMATIC: LazyLock<Option<String>> = LazyLock::new(|| {
258
browser::automatic_browser(&INSTALLED).map(|browser| browser.name.clone())
259
});
260
261
let saved = SignInBrowser::load();
262
let automatic_label = match AUTOMATIC.as_deref() {
263
Some(name) => format!(
264
"{} ({name})",
265
tr("settings.general.sign_in_browser_automatic")
266
),
267
None => tr("settings.general.sign_in_browser_automatic"),
268
};
269
let options = std::iter::once((SignInBrowser::Automatic, automatic_label)).chain(
270
INSTALLED.iter().map(|browser| {
271
(
272
SignInBrowser::Program(browser.path.clone()),
273
browser.name.clone(),
274
)
275
}),
276
);
277
let mut current_label = None;
278
let choices: Vec<Choice> = options
279
.map(|(option, label)| {
280
let is_selected = option == saved;
281
if is_selected {
282
current_label = Some(label.clone());
283
}
284
Choice::new(label, is_selected, move |cx| {
285
if is_selected {
286
return;
287
}
288
match option.save() {
289
Ok(()) => restart_app(cx),
290
Err(error) => {
291
app_base::diagnostics::record(format!("sign-in browser not saved: {error}"))
292
}
293
}
294
})
295
})
296
.collect();
297
let current_label =
298
current_label.unwrap_or_else(|| tr("settings.general.sign_in_browser_automatic"));
299
control_row(
300
tr("settings.general.sign_in_browser"),
301
tr("settings.general.sign_in_browser_detail"),
302
select("settings-sign-in-browser", current_label, false, choices),
303
)
304
.into_any_element()
305
}
306
307
#[cfg(any(target_os = "linux", target_os = "macos"))]
308
fn restart_app(cx: &mut App) {
309
let spawned = std::env::current_exe().and_then(|exe| {
310
std::process::Command::new(exe)
311
.args(std::env::args_os().skip(1))
312
.env(
313
app_base::updater::RELAUNCH_ENV,
314
std::process::id().to_string(),
315
)
316
.spawn()
317
});
318
match spawned {
319
Ok(_) => cx.quit(),
320
Err(error) => app_base::diagnostics::record(format!(
321
"restart for the sign-in browser failed: {error}"
322
)),
323
}
324
}
325
247
326
fn translation_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
248
327
let state = app.read(cx);
249
328
if state.translation.settings.is_none() {
@@ -234,6 +234,7 @@ fn external_browser_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {234
.collect();234
.collect();235
vec![235
vec![236
caption(tr("settings.caption.browser")).into_any_element(),236
caption(tr("settings.caption.browser")).into_any_element(),237
sign_in_browser_row(),237
control_row(238
control_row(238
tr("settings.general.external_browser"),239
tr("settings.general.external_browser"),239
tr("settings.general.external_browser_detail"),240
tr("settings.general.external_browser_detail"),@@ -244,6 +245,84 @@ fn external_browser_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {244
}245
}245
}246
}246
247
248
/// The browser the Teams session runs in. Changing it restarts the app, which stops the old249
/// browser on the way out and starts the new one.250
#[cfg(any(target_os = "linux", target_os = "macos"))]251
fn sign_in_browser_row() -> AnyElement {252
use std::sync::LazyLock;253
254
use browser::{InstalledBrowser, SignInBrowser};255
256
static INSTALLED: LazyLock<Vec<InstalledBrowser>> = LazyLock::new(browser::installed_browsers);257
static AUTOMATIC: LazyLock<Option<String>> = LazyLock::new(|| {258
browser::automatic_browser(&INSTALLED).map(|browser| browser.name.clone())259
});260
261
let saved = SignInBrowser::load();262
let automatic_label = match AUTOMATIC.as_deref() {263
Some(name) => format!(264
"{} ({name})",265
tr("settings.general.sign_in_browser_automatic")266
),267
None => tr("settings.general.sign_in_browser_automatic"),268
};269
let options = std::iter::once((SignInBrowser::Automatic, automatic_label)).chain(270
INSTALLED.iter().map(|browser| {271
(272
SignInBrowser::Program(browser.path.clone()),273
browser.name.clone(),274
)275
}),276
);277
let mut current_label = None;278
let choices: Vec<Choice> = options279
.map(|(option, label)| {280
let is_selected = option == saved;281
if is_selected {282
current_label = Some(label.clone());283
}284
Choice::new(label, is_selected, move |cx| {285
if is_selected {286
return;287
}288
match option.save() {289
Ok(()) => restart_app(cx),290
Err(error) => {291
app_base::diagnostics::record(format!("sign-in browser not saved: {error}"))292
}293
}294
})295
})296
.collect();297
let current_label =298
current_label.unwrap_or_else(|| tr("settings.general.sign_in_browser_automatic"));299
control_row(300
tr("settings.general.sign_in_browser"),301
tr("settings.general.sign_in_browser_detail"),302
select("settings-sign-in-browser", current_label, false, choices),303
)304
.into_any_element()305
}306
307
#[cfg(any(target_os = "linux", target_os = "macos"))]308
fn restart_app(cx: &mut App) {309
let spawned = std::env::current_exe().and_then(|exe| {310
std::process::Command::new(exe)311
.args(std::env::args_os().skip(1))312
.env(313
app_base::updater::RELAUNCH_ENV,314
std::process::id().to_string(),315
)316
.spawn()317
});318
match spawned {319
Ok(_) => cx.quit(),320
Err(error) => app_base::diagnostics::record(format!(321
"restart for the sign-in browser failed: {error}"322
)),323
}324
}325
247
fn translation_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {326
fn translation_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {248
let state = app.read(cx);327
let state = app.read(cx);249
if state.translation.settings.is_none() {328
if state.translation.settings.is_none() {@@ -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 = true10
futures-util.workspace = true10
futures-util.workspace = true11
serde.workspace = true11
serde.workspace = true12
serde_json.workspace = true12
serde_json.workspace = true13
session.workspace = true13
thiserror.workspace = true14
thiserror.workspace = true14
tokio.workspace = true15
tokio.workspace = true15
tokio-tungstenite.workspace = true16
tokio-tungstenite.workspace = true@@ -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 and2
//! 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 stream58
/// 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
.await62
}63
64
pub async fn call(&self, method: &str, params: Value) -> Result<Value, BrowserError> {65
let commands = self66
.connected(|connection| connection.commands.clone())67
.await?;68
send(&commands, method, params).await69
}70
71
/// Opens the session if there is none. [`BrowserError::SessionTaken`] when a session another72
/// process left behind blocks it: only a browser restart frees that.73
pub async fn connect(&self) -> Result<(), BrowserError> {74
self.connected(|_| ()).await75
}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) = connection80
.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
.await90
.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
.await100
.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 = self116
.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(self123
.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
.await146
.map(drop)147
}148
149
pub async fn open_tab(&self, url: &str) -> Result<(), BrowserError> {150
let created = self151
.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).await155
}156
157
pub async fn close_tab(&self, context: &str) -> Result<(), BrowserError> {158
self.call("browsingContext.close", json!({"context": context}))159
.await160
.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
commands172
.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
) where186
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 = result259
.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 cannot268
/// 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
value278
.as_array()279
.into_iter()280
.flatten()281
.map(remote_value_to_json)282
.collect(),283
),284
"object" | "map" => Value::Object(285
value286
.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,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 the2
//! 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(self47
.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()).await102
} else {103
let params = json!({"context": context.id, "wait": "none"});104
self.bidi105
.call("browsingContext.reload", params)106
.await107
.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::ALL119
.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) = mapped165
&& 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 _ = bidi179
.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 = bidi224
.call("script.evaluate", request)225
.await226
.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
state238
.lock()239
.expect("channel state")240
.bindings241
.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
.await256
.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
.await272
.map(|_| json!({}))273
.map_err(protocol)274
}275
"Page.navigate" => bidi276
.navigate(context, text("url"))277
.await278
.map(|_| json!({}))279
.map_err(protocol),280
"Page.reload" => bidi281
.call(282
"browsingContext.reload",283
json!({"context": context, "wait": "none"}),284
)285
.await286
.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 = bidi296
.call("script.addPreloadScript", params)297
.await298
.map_err(protocol)?;299
let script = added["script"].as_str().unwrap_or_default().to_owned();300
state301
.lock()302
.expect("channel state")303
.scripts304
.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 also309
/// 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
}@@ -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};8
use tokio::sync::Mutex;8
use tokio::sync::Mutex;9
use tokio_tungstenite::tungstenite::Message;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
use crate::error::BrowserError;13
use crate::error::BrowserError;13
use crate::http;14
use crate::http;14
use crate::launch::{LaunchRequest, Launcher, SystemLauncher};15
use 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.config134
&self.inner.config130
}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
.await166
.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.id186
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
.await242
.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.id246
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.id287
self.inner.config.port, tab.id247
);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
.await291
.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 = self388
let info = self343
.version()389
.version()344
.await390
.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
.await411
.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).await491
}492
outcome => outcome,493
}494
}495
496
/// Asks the browser to quit: Chromium over CDP, Firefox with SIGTERM, which also works while497
/// 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();@@ -5,10 +5,11 @@ 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";
8
9
pub const DEFAULT_PORT: u16 = 9222;
9
10
const CHROME_RELATIVE: &str = r"Google\Chrome\Application\chrome.exe";
10
11
const WINDOWS_VARIABLES: [&str; 4] = ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "TEMP"];
11
const LINUX_CHROME_NAMES: [&str; 5] = [
12
pub(crate) const LINUX_CHROME_NAMES: [&str; 5] = [
12
13
"google-chrome",
13
14
"google-chrome-stable",
14
15
"chromium",
@@ -18,7 +19,7 @@ const LINUX_CHROME_NAMES: [&str; 5] = [
18
19
const MACOS_CHROME_NAMES: [&str; 3] = ["google-chrome", "chromium", "chrome"];
19
20
/// Chromium-based browsers in order of preference; each one gets its own profile, so the user's
20
21
/// everyday browser stays untouched.
21
const MACOS_CHROME_APP_PATHS: [&str; 6] = [
22
pub(crate) const MACOS_CHROME_APP_PATHS: [&str; 6] = [
22
23
"Google Chrome.app/Contents/MacOS/Google Chrome",
23
24
"Chromium.app/Contents/MacOS/Chromium",
24
25
"Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
@@ -26,6 +27,32 @@ const MACOS_CHROME_APP_PATHS: [&str; 6] = [
26
27
"Helium.app/Contents/MacOS/Helium",
27
28
"Vivaldi.app/Contents/MacOS/Vivaldi",
28
29
];
30
/// Firefox-based browsers, tried only when no Chromium browser is installed.
31
pub(crate) const MACOS_FIREFOX_APP_PATHS: [&str; 4] = [
32
"Firefox.app/Contents/MacOS/firefox",
33
"Zen.app/Contents/MacOS/zen",
34
"LibreWolf.app/Contents/MacOS/librewolf",
35
"Floorp.app/Contents/MacOS/floorp",
36
];
37
pub(crate) const LINUX_FIREFOX_NAMES: [&str; 5] =
38
["firefox", "zen-browser", "zen", "librewolf", "floorp"];
39
40
/// The protocol family of the sign-in browser: Chromium speaks CDP, Firefox WebDriver BiDi.
41
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42
pub enum Engine {
43
Chromium,
44
Firefox,
45
}
46
47
impl Engine {
48
pub fn of_executable(path: &Path) -> Engine {
49
if crate::process::is_firefox_image(&path.to_string_lossy()) {
50
Engine::Firefox
51
} else {
52
Engine::Chromium
53
}
54
}
55
}
29
56
30
57
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31
58
pub enum Platform {
@@ -60,7 +87,7 @@ impl Platform {
60
87
}
61
88
62
89
#[derive(Debug, Clone)]
63
pub(crate) enum ChromeSearch {
90
pub(crate) enum BrowserSearch {
64
91
Files(Vec<PathBuf>),
65
92
Named(Vec<String>),
66
93
/// Absolute install paths first, then PATH names (macOS Application bundles + CLI).
@@ -73,12 +100,13 @@ pub(crate) enum ChromeSearch {
73
100
#[derive(Debug, Clone)]
74
101
pub struct Config {
75
102
pub platform: Platform,
103
pub engine: Engine,
76
104
pub port: u16,
77
105
pub profile: String,
78
106
pub mode_file: PathBuf,
79
107
profile_parent: String,
80
108
mode_parent: PathBuf,
81
pub(crate) chrome_search: ChromeSearch,
109
pub(crate) search: BrowserSearch,
82
110
}
83
111
84
112
pub struct ConfigInputs<'a> {
@@ -112,18 +140,50 @@ impl Config {
112
140
}
113
141
_ => windows_path.to_owned(),
114
142
};
115
Config::resolve(
143
let config = Config::resolve(
116
144
platform,
117
145
DEFAULT_PORT,
118
146
&ConfigInputs {
119
147
windows_variables,
120
148
linux_data_dir,
121
home_dir,
149
home_dir: home_dir.clone(),
122
150
to_local: &to_local,
123
151
},
152
)?;
153
let path_variable = std::env::var_os("PATH").unwrap_or_default();
154
let chosen = crate::sign_in_choice::chosen_executable(platform, home_dir.as_deref());
155
Ok(
156
config.select_browser(chosen, home_dir.as_deref(), &path_variable, &|path| {
157
path.is_file()
158
}),
124
159
)
125
160
}
126
161
162
/// Uses `chosen` as the sign-in browser, else the first Chromium browser, else the first
163
/// Firefox-based one on Linux and macOS. A Firefox browser gets its own profile.
164
pub(crate) fn select_browser(
165
mut self,
166
chosen: Option<PathBuf>,
167
home_dir: Option<&Path>,
168
path_variable: &std::ffi::OsStr,
169
exists: &dyn Fn(&Path) -> bool,
170
) -> Config {
171
if let Some(path) = chosen {
172
self.engine = Engine::of_executable(&path);
173
self.search = BrowserSearch::Files(vec![path]);
174
} else if find_browser(&self.search, path_variable, exists).is_err()
175
&& let Some(search) = firefox_search(self.platform, home_dir)
176
&& find_browser(&search, path_variable, exists).is_ok()
177
{
178
self.engine = Engine::Firefox;
179
self.search = search;
180
}
181
if self.engine == Engine::Firefox {
182
self = self.with_profile_name(FIREFOX_PROFILE_NAME);
183
}
184
self
185
}
186
127
187
pub fn resolve(
128
188
platform: Platform,
129
189
port: u16,
@@ -139,6 +199,7 @@ impl Config {
139
199
.ok_or_else(|| BrowserError::Environment("no XDG data directory".into()))?;
140
200
Config {
141
201
platform,
202
engine: Engine::Chromium,
142
203
port,
143
204
// Built with the platform's '/' like with_profile_name, not the
144
205
// host's separator: the string is a Linux path whoever builds it.
@@ -146,7 +207,7 @@ impl Config {
146
207
mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
147
208
profile_parent: path_text(&data_dir),
148
209
mode_parent: data_dir,
149
chrome_search: ChromeSearch::Named(
210
search: BrowserSearch::Named(
150
211
LINUX_CHROME_NAMES
151
212
.iter()
152
213
.map(|name| (*name).to_owned())
@@ -158,23 +219,18 @@ impl Config {
158
219
let data_dir = inputs.linux_data_dir.clone().ok_or_else(|| {
159
220
BrowserError::Environment("no Application Support directory".into())
160
221
})?;
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
}
222
let files = application_roots(inputs.home_dir.as_deref())
223
.flat_map(|root| MACOS_CHROME_APP_PATHS.map(|relative| root.join(relative)))
224
.collect();
170
225
Config {
171
226
platform,
227
engine: Engine::Chromium,
172
228
port,
173
229
profile: format!("{}/{}", path_text(&data_dir), PROFILE_NAME),
174
230
mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
175
231
profile_parent: path_text(&data_dir),
176
232
mode_parent: data_dir,
177
chrome_search: ChromeSearch::FilesThenNamed {
233
search: BrowserSearch::FilesThenNamed {
178
234
files,
179
235
names: MACOS_CHROME_NAMES
180
236
.iter()
@@ -195,12 +251,13 @@ impl Config {
195
251
.collect();
196
252
Config {
197
253
platform,
254
engine: Engine::Chromium,
198
255
port,
199
256
profile: format!("{local}\\{PROFILE_NAME}"),
200
257
mode_file: PathBuf::from(to_local(&format!("{local}\\{PROFILE_NAME}.mode"))),
201
258
profile_parent: local.clone(),
202
259
mode_parent: PathBuf::from(to_local(local)),
203
chrome_search: ChromeSearch::Files(candidates),
260
search: BrowserSearch::Files(candidates),
204
261
}
205
262
}
206
263
};
@@ -223,12 +280,31 @@ impl Config {
223
280
self
224
281
}
225
282
226
pub fn chrome_executable(&self) -> Result<PathBuf, BrowserError> {
283
pub fn executable(&self) -> Result<PathBuf, BrowserError> {
227
284
let path_variable = std::env::var_os("PATH").unwrap_or_default();
228
find_chrome(&self.chrome_search, &path_variable, &|path| path.is_file())
285
find_browser(&self.search, &path_variable, &|path| path.is_file())
229
286
}
230
287
}
231
288
289
fn firefox_search(platform: Platform, home_dir: Option<&Path>) -> Option<BrowserSearch> {
290
let names = || LINUX_FIREFOX_NAMES.iter().map(|name| (*name).to_owned());
291
match platform {
292
Platform::Linux => Some(BrowserSearch::Named(names().collect())),
293
Platform::Macos => Some(BrowserSearch::FilesThenNamed {
294
files: application_roots(home_dir)
295
.flat_map(|root| MACOS_FIREFOX_APP_PATHS.map(|relative| root.join(relative)))
296
.collect(),
297
names: names().collect(),
298
}),
299
Platform::Windows | Platform::Wsl => None,
300
}
301
}
302
303
pub(crate) fn application_roots(home_dir: Option<&Path>) -> impl Iterator<Item = PathBuf> {
304
std::iter::once(PathBuf::from("/Applications"))
305
.chain(home_dir.map(|home| home.join("Applications")))
306
}
307
232
308
fn path_text(path: &Path) -> String {
233
309
path.to_string_lossy().into_owned()
234
310
}
@@ -243,32 +319,33 @@ fn find_named_chrome(
243
319
.find(|candidate| exists(candidate))
244
320
}
245
321
246
pub(crate) fn find_chrome(
247
search: &ChromeSearch,
322
pub(crate) fn find_browser(
323
search: &BrowserSearch,
248
324
path_variable: &std::ffi::OsStr,
249
325
exists: &dyn Fn(&Path) -> bool,
250
326
) -> Result<PathBuf, BrowserError> {
251
327
match search {
252
ChromeSearch::Files(candidates) => candidates
328
BrowserSearch::Files(candidates) => candidates
253
329
.iter()
254
330
.find(|candidate| exists(candidate))
255
331
.cloned()
256
332
.ok_or_else(|| {
257
333
BrowserError::ChromeNotFound("not under Program Files or LocalAppData".into())
258
334
}),
259
ChromeSearch::Named(names) => {
335
BrowserSearch::Named(names) => {
260
336
find_named_chrome(names, path_variable, exists).ok_or_else(|| {
261
337
BrowserError::ChromeNotFound(format!("none of {} on PATH", names.join(", ")))
262
338
})
263
339
}
264
ChromeSearch::FilesThenNamed { files, names } => files
340
BrowserSearch::FilesThenNamed { files, names } => files
265
341
.iter()
266
342
.find(|candidate| exists(candidate))
267
343
.cloned()
268
344
.or_else(|| find_named_chrome(names, path_variable, exists))
269
345
.ok_or_else(|| {
270
346
BrowserError::ChromeNotFound(
271
"no Chrome, Chromium, Edge, Brave, Helium or Vivaldi under /Applications, ~/Applications, or PATH".into(),
347
"no Chromium or Firefox browser under /Applications, ~/Applications, or PATH"
348
.into(),
272
349
)
273
350
}),
274
351
}
@@ -388,7 +465,7 @@ mod tests {
388
465
config.mode_file,
389
466
PathBuf::from("/mnt/c/Users/me/AppData/Local/rusty-teams-chrome.mode")
390
467
);
391
let ChromeSearch::Files(files) = &config.chrome_search else {
468
let BrowserSearch::Files(files) = &config.search else {
392
469
panic!("expected files")
393
470
};
394
471
assert_eq!(
@@ -416,7 +493,7 @@ mod tests {
416
493
config.profile,
417
494
r"C:\Users\me\AppData\Local\rusty-teams-chrome"
418
495
);
419
let ChromeSearch::Files(files) = &config.chrome_search else {
496
let BrowserSearch::Files(files) = &config.search else {
420
497
panic!("expected files")
421
498
};
422
499
let expected = [
@@ -443,7 +520,7 @@ mod tests {
443
520
to_local: &to_local,
444
521
};
445
522
let config = Config::resolve(Platform::Windows, 9222, &inputs).unwrap();
446
let ChromeSearch::Files(files) = &config.chrome_search else {
523
let BrowserSearch::Files(files) = &config.search else {
447
524
panic!("expected files")
448
525
};
449
526
assert_eq!(
@@ -496,7 +573,7 @@ mod tests {
496
573
config.mode_file,
497
574
PathBuf::from("/Users/joe/Library/Application Support/rusty-teams-chrome.mode")
498
575
);
499
let ChromeSearch::FilesThenNamed { files, names } = &config.chrome_search else {
576
let BrowserSearch::FilesThenNamed { files, names } = &config.search else {
500
577
panic!("expected files then named")
501
578
};
502
579
assert_eq!(
@@ -531,7 +608,7 @@ mod tests {
531
608
532
609
#[test]
533
610
fn finds_macos_chrome_under_applications_before_path() {
534
let search = ChromeSearch::FilesThenNamed {
611
let search = BrowserSearch::FilesThenNamed {
535
612
files: vec![
536
613
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".into(),
537
614
"/Users/joe/Applications/Chromium.app/Contents/MacOS/Chromium".into(),
@@ -539,7 +616,7 @@ mod tests {
539
616
names: vec!["google-chrome".into()],
540
617
};
541
618
let path = std::env::join_paths(["/usr/local/bin"]).unwrap();
542
let found = find_chrome(&search, &path, &|candidate| {
619
let found = find_browser(&search, &path, &|candidate| {
543
620
candidate.ends_with("Google Chrome") || candidate.ends_with("google-chrome")
544
621
})
545
622
.unwrap();
@@ -577,22 +654,87 @@ mod tests {
577
654
578
655
#[test]
579
656
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();
657
let search = BrowserSearch::Files(vec!["/a/chrome.exe".into(), "/b/chrome.exe".into()]);
658
let found =
659
find_browser(&search, &OsString::new(), &|path| path.starts_with("/b")).unwrap();
582
660
assert_eq!(found, PathBuf::from("/b/chrome.exe"));
583
assert!(find_chrome(&search, &OsString::new(), &|_| false).is_err());
661
assert!(find_browser(&search, &OsString::new(), &|_| false).is_err());
584
662
}
585
663
586
664
#[test]
587
665
fn finds_named_chrome_on_path_in_name_priority_per_directory() {
588
let search = ChromeSearch::Named(vec!["google-chrome".into(), "chromium".into()]);
666
let search = BrowserSearch::Named(vec!["google-chrome".into(), "chromium".into()]);
589
667
// join_paths picks the host's PATH separator so split_paths splits it here too.
590
668
let path = std::env::join_paths(["/usr/local/bin", "/usr/bin"]).unwrap();
591
let found = find_chrome(&search, &path, &|candidate| {
669
let found = find_browser(&search, &path, &|candidate| {
592
670
candidate == Path::new("/usr/bin/chromium")
593
671
|| candidate == Path::new("/usr/bin/google-chrome")
594
672
})
595
673
.unwrap();
596
674
assert_eq!(found, PathBuf::from("/usr/bin/google-chrome"));
597
675
}
676
677
fn macos_config() -> Config {
678
let to_local = |path: &str| path.to_owned();
679
let inputs = ConfigInputs {
680
windows_variables: HashMap::new(),
681
linux_data_dir: Some(PathBuf::from("/Users/joe/Library/Application Support")),
682
home_dir: Some(PathBuf::from("/Users/joe")),
683
to_local: &to_local,
684
};
685
Config::resolve(Platform::Macos, 9222, &inputs).unwrap()
686
}
687
688
fn select(installed: &[&str], chosen: Option<&str>) -> Config {
689
macos_config().select_browser(
690
chosen.map(PathBuf::from),
691
Some(Path::new("/Users/joe")),
692
&OsString::new(),
693
&|path| {
694
installed
695
.iter()
696
.any(|installed| path == Path::new(installed))
697
},
698
)
699
}
700
701
#[test]
702
fn a_chromium_browser_wins_over_firefox() {
703
let config = select(
704
&[
705
"/Applications/Helium.app/Contents/MacOS/Helium",
706
"/Applications/Zen.app/Contents/MacOS/zen",
707
],
708
None,
709
);
710
assert_eq!(config.engine, Engine::Chromium);
711
assert!(config.profile.ends_with(PROFILE_NAME));
712
}
713
714
#[test]
715
fn firefox_is_the_fallback_with_its_own_profile() {
716
let zen = "/Users/joe/Applications/Zen.app/Contents/MacOS/zen";
717
let config = select(&[zen], None);
718
assert_eq!(config.engine, Engine::Firefox);
719
assert_eq!(
720
config.profile,
721
"/Users/joe/Library/Application Support/rusty-teams-firefox"
722
);
723
let found = find_browser(&config.search, &OsString::new(), &|path| {
724
path == Path::new(zen)
725
});
726
assert_eq!(found.unwrap(), PathBuf::from(zen));
727
}
728
729
#[test]
730
fn the_chosen_browser_sets_the_engine() {
731
let helium = "/Applications/Helium.app/Contents/MacOS/Helium";
732
let firefox = select(&[helium], Some("/opt/zen/zen"));
733
assert_eq!(firefox.engine, Engine::Firefox);
734
let BrowserSearch::Files(files) = &firefox.search else {
735
panic!("expected the chosen path")
736
};
737
assert_eq!(files, &[PathBuf::from("/opt/zen/zen")]);
738
assert_eq!(select(&[], Some(helium)).engine, Engine::Chromium);
739
}
598
740
}
@@ -5,10 +5,11 @@ use std::process::Command;5
use crate::error::BrowserError;5
use crate::error::BrowserError;6
6
7
pub const PROFILE_NAME: &str = "rusty-teams-chrome";7
pub const PROFILE_NAME: &str = "rusty-teams-chrome";8
pub const FIREFOX_PROFILE_NAME: &str = "rusty-teams-firefox";8
pub const DEFAULT_PORT: u16 = 9222;9
pub const DEFAULT_PORT: u16 = 9222;9
const CHROME_RELATIVE: &str = r"Google\Chrome\Application\chrome.exe";10
const CHROME_RELATIVE: &str = r"Google\Chrome\Application\chrome.exe";10
const WINDOWS_VARIABLES: [&str; 4] = ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "TEMP"];11
const WINDOWS_VARIABLES: [&str; 4] = ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "TEMP"];11
const LINUX_CHROME_NAMES: [&str; 5] = [12
pub(crate) const LINUX_CHROME_NAMES: [&str; 5] = [12
"google-chrome",13
"google-chrome",13
"google-chrome-stable",14
"google-chrome-stable",14
"chromium",15
"chromium",@@ -18,7 +19,7 @@ const LINUX_CHROME_NAMES: [&str; 5] = [18
const MACOS_CHROME_NAMES: [&str; 3] = ["google-chrome", "chromium", "chrome"];19
const MACOS_CHROME_NAMES: [&str; 3] = ["google-chrome", "chromium", "chrome"];19
/// Chromium-based browsers in order of preference; each one gets its own profile, so the user's20
/// Chromium-based browsers in order of preference; each one gets its own profile, so the user's20
/// everyday browser stays untouched.21
/// everyday browser stays untouched.21
const MACOS_CHROME_APP_PATHS: [&str; 6] = [22
pub(crate) const MACOS_CHROME_APP_PATHS: [&str; 6] = [22
"Google Chrome.app/Contents/MacOS/Google Chrome",23
"Google Chrome.app/Contents/MacOS/Google Chrome",23
"Chromium.app/Contents/MacOS/Chromium",24
"Chromium.app/Contents/MacOS/Chromium",24
"Microsoft Edge.app/Contents/MacOS/Microsoft Edge",25
"Microsoft Edge.app/Contents/MacOS/Microsoft Edge",@@ -26,6 +27,32 @@ const MACOS_CHROME_APP_PATHS: [&str; 6] = [26
"Helium.app/Contents/MacOS/Helium",27
"Helium.app/Contents/MacOS/Helium",27
"Vivaldi.app/Contents/MacOS/Vivaldi",28
"Vivaldi.app/Contents/MacOS/Vivaldi",28
];29
];30
/// Firefox-based browsers, tried only when no Chromium browser is installed.31
pub(crate) const MACOS_FIREFOX_APP_PATHS: [&str; 4] = [32
"Firefox.app/Contents/MacOS/firefox",33
"Zen.app/Contents/MacOS/zen",34
"LibreWolf.app/Contents/MacOS/librewolf",35
"Floorp.app/Contents/MacOS/floorp",36
];37
pub(crate) const LINUX_FIREFOX_NAMES: [&str; 5] =38
["firefox", "zen-browser", "zen", "librewolf", "floorp"];39
40
/// The protocol family of the sign-in browser: Chromium speaks CDP, Firefox WebDriver BiDi.41
#[derive(Debug, Clone, Copy, PartialEq, Eq)]42
pub enum Engine {43
Chromium,44
Firefox,45
}46
47
impl Engine {48
pub fn of_executable(path: &Path) -> Engine {49
if crate::process::is_firefox_image(&path.to_string_lossy()) {50
Engine::Firefox51
} else {52
Engine::Chromium53
}54
}55
}29
56
30
#[derive(Debug, Clone, Copy, PartialEq, Eq)]57
#[derive(Debug, Clone, Copy, PartialEq, Eq)]31
pub enum Platform {58
pub enum Platform {@@ -60,7 +87,7 @@ impl Platform {60
}87
}61
88
62
#[derive(Debug, Clone)]89
#[derive(Debug, Clone)]63
pub(crate) enum ChromeSearch {90
pub(crate) enum BrowserSearch {64
Files(Vec<PathBuf>),91
Files(Vec<PathBuf>),65
Named(Vec<String>),92
Named(Vec<String>),66
/// Absolute install paths first, then PATH names (macOS Application bundles + CLI).93
/// Absolute install paths first, then PATH names (macOS Application bundles + CLI).@@ -73,12 +100,13 @@ pub(crate) enum ChromeSearch {73
#[derive(Debug, Clone)]100
#[derive(Debug, Clone)]74
pub struct Config {101
pub struct Config {75
pub platform: Platform,102
pub platform: Platform,103
pub engine: Engine,76
pub port: u16,104
pub port: u16,77
pub profile: String,105
pub profile: String,78
pub mode_file: PathBuf,106
pub mode_file: PathBuf,79
profile_parent: String,107
profile_parent: String,80
mode_parent: PathBuf,108
mode_parent: PathBuf,81
pub(crate) chrome_search: ChromeSearch,109
pub(crate) search: BrowserSearch,82
}110
}83
111
84
pub struct ConfigInputs<'a> {112
pub struct ConfigInputs<'a> {@@ -112,18 +140,50 @@ impl Config {112
}140
}113
_ => windows_path.to_owned(),141
_ => windows_path.to_owned(),114
};142
};115
Config::resolve(143
let config = Config::resolve(116
platform,144
platform,117
DEFAULT_PORT,145
DEFAULT_PORT,118
&ConfigInputs {146
&ConfigInputs {119
windows_variables,147
windows_variables,120
linux_data_dir,148
linux_data_dir,121
home_dir,149
home_dir: home_dir.clone(),122
to_local: &to_local,150
to_local: &to_local,123
},151
},152
)?;153
let path_variable = std::env::var_os("PATH").unwrap_or_default();154
let chosen = crate::sign_in_choice::chosen_executable(platform, home_dir.as_deref());155
Ok(156
config.select_browser(chosen, home_dir.as_deref(), &path_variable, &|path| {157
path.is_file()158
}),124
)159
)125
}160
}126
161
162
/// Uses `chosen` as the sign-in browser, else the first Chromium browser, else the first163
/// Firefox-based one on Linux and macOS. A Firefox browser gets its own profile.164
pub(crate) fn select_browser(165
mut self,166
chosen: Option<PathBuf>,167
home_dir: Option<&Path>,168
path_variable: &std::ffi::OsStr,169
exists: &dyn Fn(&Path) -> bool,170
) -> Config {171
if let Some(path) = chosen {172
self.engine = Engine::of_executable(&path);173
self.search = BrowserSearch::Files(vec![path]);174
} else if find_browser(&self.search, path_variable, exists).is_err()175
&& let Some(search) = firefox_search(self.platform, home_dir)176
&& find_browser(&search, path_variable, exists).is_ok()177
{178
self.engine = Engine::Firefox;179
self.search = search;180
}181
if self.engine == Engine::Firefox {182
self = self.with_profile_name(FIREFOX_PROFILE_NAME);183
}184
self185
}186
127
pub fn resolve(187
pub fn resolve(128
platform: Platform,188
platform: Platform,129
port: u16,189
port: u16,@@ -139,6 +199,7 @@ impl Config {139
.ok_or_else(|| BrowserError::Environment("no XDG data directory".into()))?;199
.ok_or_else(|| BrowserError::Environment("no XDG data directory".into()))?;140
Config {200
Config {141
platform,201
platform,202
engine: Engine::Chromium,142
port,203
port,143
// Built with the platform's '/' like with_profile_name, not the204
// Built with the platform's '/' like with_profile_name, not the144
// host's separator: the string is a Linux path whoever builds it.205
// host's separator: the string is a Linux path whoever builds it.@@ -146,7 +207,7 @@ impl Config {146
mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),207
mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),147
profile_parent: path_text(&data_dir),208
profile_parent: path_text(&data_dir),148
mode_parent: data_dir,209
mode_parent: data_dir,149
chrome_search: ChromeSearch::Named(210
search: BrowserSearch::Named(150
LINUX_CHROME_NAMES211
LINUX_CHROME_NAMES151
.iter()212
.iter()152
.map(|name| (*name).to_owned())213
.map(|name| (*name).to_owned())@@ -158,23 +219,18 @@ impl Config {158
let data_dir = inputs.linux_data_dir.clone().ok_or_else(|| {219
let data_dir = inputs.linux_data_dir.clone().ok_or_else(|| {159
BrowserError::Environment("no Application Support directory".into())220
BrowserError::Environment("no Application Support directory".into())160
})?;221
})?;161
let mut files = Vec::new();222
let files = application_roots(inputs.home_dir.as_deref())162
for root in [PathBuf::from("/Applications")]223
.flat_map(|root| MACOS_CHROME_APP_PATHS.map(|relative| root.join(relative)))163
.into_iter()224
.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 {225
Config {171
platform,226
platform,227
engine: Engine::Chromium,172
port,228
port,173
profile: format!("{}/{}", path_text(&data_dir), PROFILE_NAME),229
profile: format!("{}/{}", path_text(&data_dir), PROFILE_NAME),174
mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),230
mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),175
profile_parent: path_text(&data_dir),231
profile_parent: path_text(&data_dir),176
mode_parent: data_dir,232
mode_parent: data_dir,177
chrome_search: ChromeSearch::FilesThenNamed {233
search: BrowserSearch::FilesThenNamed {178
files,234
files,179
names: MACOS_CHROME_NAMES235
names: MACOS_CHROME_NAMES180
.iter()236
.iter()@@ -195,12 +251,13 @@ impl Config {195
.collect();251
.collect();196
Config {252
Config {197
platform,253
platform,254
engine: Engine::Chromium,198
port,255
port,199
profile: format!("{local}\\{PROFILE_NAME}"),256
profile: format!("{local}\\{PROFILE_NAME}"),200
mode_file: PathBuf::from(to_local(&format!("{local}\\{PROFILE_NAME}.mode"))),257
mode_file: PathBuf::from(to_local(&format!("{local}\\{PROFILE_NAME}.mode"))),201
profile_parent: local.clone(),258
profile_parent: local.clone(),202
mode_parent: PathBuf::from(to_local(local)),259
mode_parent: PathBuf::from(to_local(local)),203
chrome_search: ChromeSearch::Files(candidates),260
search: BrowserSearch::Files(candidates),204
}261
}205
}262
}206
};263
};@@ -223,12 +280,31 @@ impl Config {223
self280
self224
}281
}225
282
226
pub fn chrome_executable(&self) -> Result<PathBuf, BrowserError> {283
pub fn executable(&self) -> Result<PathBuf, BrowserError> {227
let path_variable = std::env::var_os("PATH").unwrap_or_default();284
let path_variable = std::env::var_os("PATH").unwrap_or_default();228
find_chrome(&self.chrome_search, &path_variable, &|path| path.is_file())285
find_browser(&self.search, &path_variable, &|path| path.is_file())229
}286
}230
}287
}231
288
289
fn firefox_search(platform: Platform, home_dir: Option<&Path>) -> Option<BrowserSearch> {290
let names = || LINUX_FIREFOX_NAMES.iter().map(|name| (*name).to_owned());291
match platform {292
Platform::Linux => Some(BrowserSearch::Named(names().collect())),293
Platform::Macos => Some(BrowserSearch::FilesThenNamed {294
files: application_roots(home_dir)295
.flat_map(|root| MACOS_FIREFOX_APP_PATHS.map(|relative| root.join(relative)))296
.collect(),297
names: names().collect(),298
}),299
Platform::Windows | Platform::Wsl => None,300
}301
}302
303
pub(crate) fn application_roots(home_dir: Option<&Path>) -> impl Iterator<Item = PathBuf> {304
std::iter::once(PathBuf::from("/Applications"))305
.chain(home_dir.map(|home| home.join("Applications")))306
}307
232
fn path_text(path: &Path) -> String {308
fn path_text(path: &Path) -> String {233
path.to_string_lossy().into_owned()309
path.to_string_lossy().into_owned()234
}310
}@@ -243,32 +319,33 @@ fn find_named_chrome(243
.find(|candidate| exists(candidate))319
.find(|candidate| exists(candidate))244
}320
}245
321
246
pub(crate) fn find_chrome(322
pub(crate) fn find_browser(247
search: &ChromeSearch,323
search: &BrowserSearch,248
path_variable: &std::ffi::OsStr,324
path_variable: &std::ffi::OsStr,249
exists: &dyn Fn(&Path) -> bool,325
exists: &dyn Fn(&Path) -> bool,250
) -> Result<PathBuf, BrowserError> {326
) -> Result<PathBuf, BrowserError> {251
match search {327
match search {252
ChromeSearch::Files(candidates) => candidates328
BrowserSearch::Files(candidates) => candidates253
.iter()329
.iter()254
.find(|candidate| exists(candidate))330
.find(|candidate| exists(candidate))255
.cloned()331
.cloned()256
.ok_or_else(|| {332
.ok_or_else(|| {257
BrowserError::ChromeNotFound("not under Program Files or LocalAppData".into())333
BrowserError::ChromeNotFound("not under Program Files or LocalAppData".into())258
}),334
}),259
ChromeSearch::Named(names) => {335
BrowserSearch::Named(names) => {260
find_named_chrome(names, path_variable, exists).ok_or_else(|| {336
find_named_chrome(names, path_variable, exists).ok_or_else(|| {261
BrowserError::ChromeNotFound(format!("none of {} on PATH", names.join(", ")))337
BrowserError::ChromeNotFound(format!("none of {} on PATH", names.join(", ")))262
})338
})263
}339
}264
ChromeSearch::FilesThenNamed { files, names } => files340
BrowserSearch::FilesThenNamed { files, names } => files265
.iter()341
.iter()266
.find(|candidate| exists(candidate))342
.find(|candidate| exists(candidate))267
.cloned()343
.cloned()268
.or_else(|| find_named_chrome(names, path_variable, exists))344
.or_else(|| find_named_chrome(names, path_variable, exists))269
.ok_or_else(|| {345
.ok_or_else(|| {270
BrowserError::ChromeNotFound(346
BrowserError::ChromeNotFound(271
"no Chrome, Chromium, Edge, Brave, Helium or Vivaldi under /Applications, ~/Applications, or PATH".into(),347
"no Chromium or Firefox browser under /Applications, ~/Applications, or PATH"348
.into(),272
)349
)273
}),350
}),274
}351
}@@ -388,7 +465,7 @@ mod tests {388
config.mode_file,465
config.mode_file,389
PathBuf::from("/mnt/c/Users/me/AppData/Local/rusty-teams-chrome.mode")466
PathBuf::from("/mnt/c/Users/me/AppData/Local/rusty-teams-chrome.mode")390
);467
);391
let ChromeSearch::Files(files) = &config.chrome_search else {468
let BrowserSearch::Files(files) = &config.search else {392
panic!("expected files")469
panic!("expected files")393
};470
};394
assert_eq!(471
assert_eq!(@@ -416,7 +493,7 @@ mod tests {416
config.profile,493
config.profile,417
r"C:\Users\me\AppData\Local\rusty-teams-chrome"494
r"C:\Users\me\AppData\Local\rusty-teams-chrome"418
);495
);419
let ChromeSearch::Files(files) = &config.chrome_search else {496
let BrowserSearch::Files(files) = &config.search else {420
panic!("expected files")497
panic!("expected files")421
};498
};422
let expected = [499
let expected = [@@ -443,7 +520,7 @@ mod tests {443
to_local: &to_local,520
to_local: &to_local,444
};521
};445
let config = Config::resolve(Platform::Windows, 9222, &inputs).unwrap();522
let config = Config::resolve(Platform::Windows, 9222, &inputs).unwrap();446
let ChromeSearch::Files(files) = &config.chrome_search else {523
let BrowserSearch::Files(files) = &config.search else {447
panic!("expected files")524
panic!("expected files")448
};525
};449
assert_eq!(526
assert_eq!(@@ -496,7 +573,7 @@ mod tests {496
config.mode_file,573
config.mode_file,497
PathBuf::from("/Users/joe/Library/Application Support/rusty-teams-chrome.mode")574
PathBuf::from("/Users/joe/Library/Application Support/rusty-teams-chrome.mode")498
);575
);499
let ChromeSearch::FilesThenNamed { files, names } = &config.chrome_search else {576
let BrowserSearch::FilesThenNamed { files, names } = &config.search else {500
panic!("expected files then named")577
panic!("expected files then named")501
};578
};502
assert_eq!(579
assert_eq!(@@ -531,7 +608,7 @@ mod tests {531
608
532
#[test]609
#[test]533
fn finds_macos_chrome_under_applications_before_path() {610
fn finds_macos_chrome_under_applications_before_path() {534
let search = ChromeSearch::FilesThenNamed {611
let search = BrowserSearch::FilesThenNamed {535
files: vec![612
files: vec![536
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".into(),613
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".into(),537
"/Users/joe/Applications/Chromium.app/Contents/MacOS/Chromium".into(),614
"/Users/joe/Applications/Chromium.app/Contents/MacOS/Chromium".into(),@@ -539,7 +616,7 @@ mod tests {539
names: vec!["google-chrome".into()],616
names: vec!["google-chrome".into()],540
};617
};541
let path = std::env::join_paths(["/usr/local/bin"]).unwrap();618
let path = std::env::join_paths(["/usr/local/bin"]).unwrap();542
let found = find_chrome(&search, &path, &|candidate| {619
let found = find_browser(&search, &path, &|candidate| {543
candidate.ends_with("Google Chrome") || candidate.ends_with("google-chrome")620
candidate.ends_with("Google Chrome") || candidate.ends_with("google-chrome")544
})621
})545
.unwrap();622
.unwrap();@@ -577,22 +654,87 @@ mod tests {577
654
578
#[test]655
#[test]579
fn finds_first_existing_candidate() {656
fn finds_first_existing_candidate() {580
let search = ChromeSearch::Files(vec!["/a/chrome.exe".into(), "/b/chrome.exe".into()]);657
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();658
let found =659
find_browser(&search, &OsString::new(), &|path| path.starts_with("/b")).unwrap();582
assert_eq!(found, PathBuf::from("/b/chrome.exe"));660
assert_eq!(found, PathBuf::from("/b/chrome.exe"));583
assert!(find_chrome(&search, &OsString::new(), &|_| false).is_err());661
assert!(find_browser(&search, &OsString::new(), &|_| false).is_err());584
}662
}585
663
586
#[test]664
#[test]587
fn finds_named_chrome_on_path_in_name_priority_per_directory() {665
fn finds_named_chrome_on_path_in_name_priority_per_directory() {588
let search = ChromeSearch::Named(vec!["google-chrome".into(), "chromium".into()]);666
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.667
// 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();668
let path = std::env::join_paths(["/usr/local/bin", "/usr/bin"]).unwrap();591
let found = find_chrome(&search, &path, &|candidate| {669
let found = find_browser(&search, &path, &|candidate| {592
candidate == Path::new("/usr/bin/chromium")670
candidate == Path::new("/usr/bin/chromium")593
|| candidate == Path::new("/usr/bin/google-chrome")671
|| candidate == Path::new("/usr/bin/google-chrome")594
})672
})595
.unwrap();673
.unwrap();596
assert_eq!(found, PathBuf::from("/usr/bin/google-chrome"));674
assert_eq!(found, PathBuf::from("/usr/bin/google-chrome"));597
}675
}676
677
fn macos_config() -> Config {678
let to_local = |path: &str| path.to_owned();679
let inputs = ConfigInputs {680
windows_variables: HashMap::new(),681
linux_data_dir: Some(PathBuf::from("/Users/joe/Library/Application Support")),682
home_dir: Some(PathBuf::from("/Users/joe")),683
to_local: &to_local,684
};685
Config::resolve(Platform::Macos, 9222, &inputs).unwrap()686
}687
688
fn select(installed: &[&str], chosen: Option<&str>) -> Config {689
macos_config().select_browser(690
chosen.map(PathBuf::from),691
Some(Path::new("/Users/joe")),692
&OsString::new(),693
&|path| {694
installed695
.iter()696
.any(|installed| path == Path::new(installed))697
},698
)699
}700
701
#[test]702
fn a_chromium_browser_wins_over_firefox() {703
let config = select(704
&[705
"/Applications/Helium.app/Contents/MacOS/Helium",706
"/Applications/Zen.app/Contents/MacOS/zen",707
],708
None,709
);710
assert_eq!(config.engine, Engine::Chromium);711
assert!(config.profile.ends_with(PROFILE_NAME));712
}713
714
#[test]715
fn firefox_is_the_fallback_with_its_own_profile() {716
let zen = "/Users/joe/Applications/Zen.app/Contents/MacOS/zen";717
let config = select(&[zen], None);718
assert_eq!(config.engine, Engine::Firefox);719
assert_eq!(720
config.profile,721
"/Users/joe/Library/Application Support/rusty-teams-firefox"722
);723
let found = find_browser(&config.search, &OsString::new(), &|path| {724
path == Path::new(zen)725
});726
assert_eq!(found.unwrap(), PathBuf::from(zen));727
}728
729
#[test]730
fn the_chosen_browser_sets_the_engine() {731
let helium = "/Applications/Helium.app/Contents/MacOS/Helium";732
let firefox = select(&[helium], Some("/opt/zen/zen"));733
assert_eq!(firefox.engine, Engine::Firefox);734
let BrowserSearch::Files(files) = &firefox.search else {735
panic!("expected the chosen path")736
};737
assert_eq!(files, &[PathBuf::from("/opt/zen/zen")]);738
assert_eq!(select(&[], Some(helium)).engine, Engine::Chromium);739
}598
}740
}@@ -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}")]@@ -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 @@1
use std::path::Path;1
use std::path::Path;2
use std::process::{Command, Stdio};2
use std::process::{Command, Stdio};3
3
4
use crate::config::{Config, Platform};4
use crate::config::{Config, Engine, Platform};5
use crate::error::BrowserError;5
use crate::error::BrowserError;6
6
7
#[derive(Debug, Clone)]7
#[derive(Debug, Clone)]@@ -13,6 +13,11 @@ pub struct LaunchRequest {13
pub trait Launcher: Send + Sync {13
pub 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
18
pub struct ArgumentSpec<'a> {23
pub struct ArgumentSpec<'a> {@@ -55,6 +60,42 @@ pub fn chrome_arguments(spec: &ArgumentSpec) -> Vec<String> {55
arguments60
arguments56
}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
arguments76
}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
pub fn user_agent(platform: Platform, major: u32) -> String {99
pub 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
148
impl Launcher for SystemLauncher {189
impl 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
command219
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"));@@ -1,17 +1,27 @@
1
mod bidi;
2
mod bidi_transport;
1
3
mod browser;
2
4
mod config;
3
5
mod error;
4
6
mod http;
5
7
mod launch;
6
8
mod process;
9
mod sign_in_choice;
7
10
mod targets;
8
11
mod watchdog;
9
12
13
pub use bidi::{Bidi, Context, remote_value_to_json};
14
pub use bidi_transport::{BidiTransport, session_transport};
10
15
pub use browser::{Browser, RendererState, Status, Timeouts};
11
pub use config::{Config, ConfigInputs, DEFAULT_PORT, PROFILE_NAME, Platform, windows_path_to_wsl};
16
pub use config::{
17
Config, ConfigInputs, DEFAULT_PORT, Engine, FIREFOX_PROFILE_NAME, PROFILE_NAME, Platform,
18
windows_path_to_wsl,
19
};
12
20
pub use error::BrowserError;
13
21
pub use launch::{
14
ArgumentSpec, LaunchRequest, Launcher, SystemLauncher, chrome_arguments, user_agent,
22
ArgumentSpec, LaunchRequest, Launcher, SystemLauncher, chrome_arguments, firefox_arguments,
23
user_agent,
15
24
};
25
pub use sign_in_choice::{InstalledBrowser, SignInBrowser, automatic_browser, installed_browsers};
16
26
pub use targets::{APPS, App, LoginState, Mode, Tab};
17
27
pub use watchdog::{BrowserEvent, Watchdog, WatchdogConfig};
@@ -1,17 +1,27 @@1
mod bidi;2
mod bidi_transport;1
mod browser;3
mod browser;2
mod config;4
mod config;3
mod error;5
mod error;4
mod http;6
mod http;5
mod launch;7
mod launch;6
mod process;8
mod process;9
mod sign_in_choice;7
mod targets;10
mod targets;8
mod watchdog;11
mod watchdog;9
12
13
pub use bidi::{Bidi, Context, remote_value_to_json};14
pub use bidi_transport::{BidiTransport, session_transport};10
pub use browser::{Browser, RendererState, Status, Timeouts};15
pub use browser::{Browser, RendererState, Status, Timeouts};11
pub use config::{Config, ConfigInputs, DEFAULT_PORT, PROFILE_NAME, Platform, windows_path_to_wsl};16
pub use config::{17
Config, ConfigInputs, DEFAULT_PORT, Engine, FIREFOX_PROFILE_NAME, PROFILE_NAME, Platform,18
windows_path_to_wsl,19
};12
pub use error::BrowserError;20
pub use error::BrowserError;13
pub use launch::{21
pub use launch::{14
ArgumentSpec, LaunchRequest, Launcher, SystemLauncher, chrome_arguments, user_agent,22
ArgumentSpec, LaunchRequest, Launcher, SystemLauncher, chrome_arguments, firefox_arguments,23
user_agent,15
};24
};25
pub use sign_in_choice::{InstalledBrowser, SignInBrowser, automatic_browser, installed_browsers};16
pub use targets::{APPS, App, LoginState, Mode, Tab};26
pub use targets::{APPS, App, LoginState, Mode, Tab};17
pub use watchdog::{BrowserEvent, Watchdog, WatchdogConfig};27
pub use watchdog::{BrowserEvent, Watchdog, WatchdogConfig};@@ -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 @@1
use std::process::Command;1
use std::process::Command;2
use std::time::{Duration, Instant};2
3
3
use crate::config::Platform;4
use crate::config::Platform;4
use crate::error::BrowserError;5
use 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
57
pub(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.59
fn 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
65
pub(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
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
fn process_image_name(platform: Platform, pid: &str) -> Result<String, BrowserError> {79
fn 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, BrowserEr76
Ok(output.split(',').next().unwrap_or_default().to_owned())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, so95
/// 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
.status108
.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
pub(crate) fn kill_listener(platform: Platform, port: u16) -> Result<(), BrowserError> {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
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
136
fn 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";@@ -0,0 +1,273 @@
1
//! Which browser the app signs in with. The user picks one in Settings; Automatic takes the
2
//! system's default browser when it is Chromium- or Firefox-based, else the first one installed.
3
//! The choice lives in a file beside the browser profiles, since every org shares them.
4
5
use std::path::{Path, PathBuf};
6
use std::process::Command;
7
8
use serde_json::Value;
9
10
use crate::config::{
11
Engine, LINUX_CHROME_NAMES, LINUX_FIREFOX_NAMES, MACOS_CHROME_APP_PATHS,
12
MACOS_FIREFOX_APP_PATHS, Platform, application_roots,
13
};
14
15
const CHOICE_FILE: &str = "rusty-teams-sign-in-browser";
16
17
#[derive(Debug, Clone, PartialEq, Eq)]
18
pub enum SignInBrowser {
19
Automatic,
20
Program(PathBuf),
21
}
22
23
#[derive(Debug, Clone, PartialEq, Eq)]
24
pub struct InstalledBrowser {
25
pub name: String,
26
pub path: PathBuf,
27
pub engine: Engine,
28
}
29
30
fn choice_path() -> Option<PathBuf> {
31
directories::BaseDirs::new().map(|dirs| dirs.data_dir().join(CHOICE_FILE))
32
}
33
34
impl SignInBrowser {
35
pub fn load() -> SignInBrowser {
36
choice_path()
37
.and_then(|path| std::fs::read_to_string(path).ok())
38
.map(|text| SignInBrowser::parse(&text))
39
.unwrap_or(SignInBrowser::Automatic)
40
}
41
42
pub fn save(&self) -> std::io::Result<()> {
43
let path = choice_path().ok_or_else(|| std::io::Error::other("no data directory"))?;
44
match self {
45
SignInBrowser::Automatic => match std::fs::remove_file(&path) {
46
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
47
_ => Ok(()),
48
},
49
SignInBrowser::Program(program) => {
50
if let Some(parent) = path.parent() {
51
std::fs::create_dir_all(parent)?;
52
}
53
std::fs::write(&path, program.to_string_lossy().as_bytes())
54
}
55
}
56
}
57
58
fn parse(text: &str) -> SignInBrowser {
59
match text.trim() {
60
"" => SignInBrowser::Automatic,
61
path => SignInBrowser::Program(PathBuf::from(path)),
62
}
63
}
64
}
65
66
/// Chromium and Firefox browsers on this machine, Chromium first.
67
pub fn installed_browsers() -> Vec<InstalledBrowser> {
68
let home = directories::BaseDirs::new().map(|dirs| dirs.home_dir().to_path_buf());
69
let path_variable = std::env::var_os("PATH").unwrap_or_default();
70
installed_in(
71
Platform::detect(),
72
home.as_deref(),
73
&path_variable,
74
&|path| path.is_file(),
75
)
76
}
77
78
/// The browser Automatic stands for.
79
pub fn automatic_browser(installed: &[InstalledBrowser]) -> Option<&InstalledBrowser> {
80
automatic_in(Platform::detect(), installed)
81
}
82
83
fn automatic_in(platform: Platform, installed: &[InstalledBrowser]) -> Option<&InstalledBrowser> {
84
system_default(platform, installed).or(installed.first())
85
}
86
87
/// The executable to sign in with: the saved choice while it is installed, else Automatic.
88
pub(crate) fn chosen_executable(platform: Platform, home: Option<&Path>) -> Option<PathBuf> {
89
if !platform.uses_unix_paths() {
90
return None;
91
}
92
if let SignInBrowser::Program(path) = SignInBrowser::load()
93
&& path.is_file()
94
{
95
return Some(path);
96
}
97
let path_variable = std::env::var_os("PATH").unwrap_or_default();
98
let installed = installed_in(platform, home, &path_variable, &|path| path.is_file());
99
automatic_in(platform, &installed).map(|browser| browser.path.clone())
100
}
101
102
pub(crate) fn installed_in(
103
platform: Platform,
104
home: Option<&Path>,
105
path_variable: &std::ffi::OsStr,
106
exists: &dyn Fn(&Path) -> bool,
107
) -> Vec<InstalledBrowser> {
108
let found: Vec<(String, PathBuf)> = match platform {
109
Platform::Macos => MACOS_CHROME_APP_PATHS
110
.iter()
111
.chain(&MACOS_FIREFOX_APP_PATHS)
112
.filter_map(|relative| {
113
let path = application_roots(home)
114
.map(|root| root.join(relative))
115
.find(|path| exists(path))?;
116
let name = relative.split(".app/").next().unwrap_or(relative);
117
Some((name.to_owned(), path))
118
})
119
.collect(),
120
Platform::Linux => LINUX_CHROME_NAMES
121
.iter()
122
.chain(&LINUX_FIREFOX_NAMES)
123
.filter_map(|name| {
124
let path = std::env::split_paths(path_variable)
125
.map(|directory| directory.join(name))
126
.find(|path| exists(path))?;
127
Some(((*name).to_owned(), path))
128
})
129
.collect(),
130
Platform::Windows | Platform::Wsl => Vec::new(),
131
};
132
found
133
.into_iter()
134
.map(|(name, path)| InstalledBrowser {
135
engine: Engine::of_executable(&path),
136
name,
137
path,
138
})
139
.collect()
140
}
141
142
fn system_default(platform: Platform, installed: &[InstalledBrowser]) -> Option<&InstalledBrowser> {
143
match platform {
144
Platform::Macos => {
145
let wanted = macos_default_bundle_id()?;
146
installed.iter().find(|browser| {
147
bundle_id(&browser.path).is_some_and(|id| id.eq_ignore_ascii_case(&wanted))
148
})
149
}
150
Platform::Linux => {
151
let output = Command::new("xdg-settings")
152
.args(["get", "default-web-browser"])
153
.output()
154
.ok()?;
155
desktop_entry_match(&String::from_utf8_lossy(&output.stdout), installed)
156
}
157
Platform::Windows | Platform::Wsl => None,
158
}
159
}
160
161
fn plist_json(path: &Path) -> Option<Value> {
162
let output = Command::new("plutil")
163
.args(["-convert", "json", "-o", "-"])
164
.arg(path)
165
.output()
166
.ok()?;
167
serde_json::from_slice(&output.stdout).ok()
168
}
169
170
fn macos_default_bundle_id() -> Option<String> {
171
let home = directories::BaseDirs::new()?.home_dir().to_path_buf();
172
let handlers = home
173
.join("Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist");
174
handler_bundle_id(&plist_json(&handlers)?)
175
}
176
177
/// The app LaunchServices opens https links with, falling back to http.
178
fn handler_bundle_id(handlers: &Value) -> Option<String> {
179
let entries = handlers["LSHandlers"].as_array()?;
180
["https", "http"].iter().find_map(|scheme| {
181
entries
182
.iter()
183
.find(|entry| entry["LSHandlerURLScheme"] == *scheme)?["LSHandlerRoleAll"]
184
.as_str()
185
.map(str::to_owned)
186
})
187
}
188
189
/// `CFBundleIdentifier` of the app bundle holding `executable` (`X.app/Contents/MacOS/x`).
190
fn bundle_id(executable: &Path) -> Option<String> {
191
let info = executable.parent()?.parent()?.join("Info.plist");
192
plist_json(&info)?["CFBundleIdentifier"]
193
.as_str()
194
.map(str::to_owned)
195
}
196
197
/// The installed browser named like the desktop entry `xdg-settings` reports, as in `firefox.desktop`.
198
fn desktop_entry_match<'a>(
199
entry: &str,
200
installed: &'a [InstalledBrowser],
201
) -> Option<&'a InstalledBrowser> {
202
let stem = entry.trim().trim_end_matches(".desktop");
203
installed.iter().find(|browser| browser.name == stem)
204
}
205
206
#[cfg(test)]
207
mod tests {
208
use std::ffi::OsString;
209
210
use serde_json::json;
211
212
use super::*;
213
214
#[test]
215
fn finds_installed_browsers_chromium_first_once_each() {
216
let installed = [
217
"/Applications/Zen.app/Contents/MacOS/zen",
218
"/Users/joe/Applications/Zen.app/Contents/MacOS/zen",
219
"/Users/joe/Applications/Helium.app/Contents/MacOS/Helium",
220
];
221
let found = installed_in(
222
Platform::Macos,
223
Some(Path::new("/Users/joe")),
224
&OsString::new(),
225
&|path| installed.iter().any(|known| path == Path::new(known)),
226
);
227
let names: Vec<(&str, Engine)> = found
228
.iter()
229
.map(|browser| (browser.name.as_str(), browser.engine))
230
.collect();
231
assert_eq!(
232
names,
233
[("Helium", Engine::Chromium), ("Zen", Engine::Firefox)]
234
);
235
assert_eq!(found[1].path, PathBuf::from(installed[0]));
236
}
237
238
#[test]
239
fn reads_the_https_handler() {
240
let handlers = json!({"LSHandlers": [
241
{"LSHandlerContentType": "public.html", "LSHandlerRoleAll": "com.apple.safari"},
242
{"LSHandlerURLScheme": "http", "LSHandlerRoleAll": "org.mozilla.firefox"},
243
{"LSHandlerURLScheme": "https", "LSHandlerRoleAll": "app.zen-browser.zen"},
244
]});
245
assert_eq!(
246
handler_bundle_id(&handlers).as_deref(),
247
Some("app.zen-browser.zen")
248
);
249
assert_eq!(handler_bundle_id(&json!({"LSHandlers": []})), None);
250
}
251
252
#[test]
253
fn matches_the_linux_desktop_entry_by_name() {
254
let installed = installed_in(
255
Platform::Linux,
256
None,
257
&std::env::join_paths(["/usr/bin"]).unwrap(),
258
&|path| path == Path::new("/usr/bin/chromium") || path == Path::new("/usr/bin/firefox"),
259
);
260
let found = desktop_entry_match("firefox.desktop\n", &installed).unwrap();
261
assert_eq!(found.engine, Engine::Firefox);
262
assert!(desktop_entry_match("org.gnome.Epiphany.desktop", &installed).is_none());
263
}
264
265
#[test]
266
fn parses_the_saved_choice() {
267
assert_eq!(SignInBrowser::parse(" \n"), SignInBrowser::Automatic);
268
assert_eq!(
269
SignInBrowser::parse("/Applications/Zen.app/Contents/MacOS/zen\n"),
270
SignInBrowser::Program(PathBuf::from("/Applications/Zen.app/Contents/MacOS/zen"))
271
);
272
}
273
}
@@ -0,0 +1,273 @@1
//! Which browser the app signs in with. The user picks one in Settings; Automatic takes the2
//! system's default browser when it is Chromium- or Firefox-based, else the first one installed.3
//! The choice lives in a file beside the browser profiles, since every org shares them.4
5
use std::path::{Path, PathBuf};6
use std::process::Command;7
8
use serde_json::Value;9
10
use crate::config::{11
Engine, LINUX_CHROME_NAMES, LINUX_FIREFOX_NAMES, MACOS_CHROME_APP_PATHS,12
MACOS_FIREFOX_APP_PATHS, Platform, application_roots,13
};14
15
const CHOICE_FILE: &str = "rusty-teams-sign-in-browser";16
17
#[derive(Debug, Clone, PartialEq, Eq)]18
pub enum SignInBrowser {19
Automatic,20
Program(PathBuf),21
}22
23
#[derive(Debug, Clone, PartialEq, Eq)]24
pub struct InstalledBrowser {25
pub name: String,26
pub path: PathBuf,27
pub engine: Engine,28
}29
30
fn choice_path() -> Option<PathBuf> {31
directories::BaseDirs::new().map(|dirs| dirs.data_dir().join(CHOICE_FILE))32
}33
34
impl SignInBrowser {35
pub fn load() -> SignInBrowser {36
choice_path()37
.and_then(|path| std::fs::read_to_string(path).ok())38
.map(|text| SignInBrowser::parse(&text))39
.unwrap_or(SignInBrowser::Automatic)40
}41
42
pub fn save(&self) -> std::io::Result<()> {43
let path = choice_path().ok_or_else(|| std::io::Error::other("no data directory"))?;44
match self {45
SignInBrowser::Automatic => match std::fs::remove_file(&path) {46
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),47
_ => Ok(()),48
},49
SignInBrowser::Program(program) => {50
if let Some(parent) = path.parent() {51
std::fs::create_dir_all(parent)?;52
}53
std::fs::write(&path, program.to_string_lossy().as_bytes())54
}55
}56
}57
58
fn parse(text: &str) -> SignInBrowser {59
match text.trim() {60
"" => SignInBrowser::Automatic,61
path => SignInBrowser::Program(PathBuf::from(path)),62
}63
}64
}65
66
/// Chromium and Firefox browsers on this machine, Chromium first.67
pub fn installed_browsers() -> Vec<InstalledBrowser> {68
let home = directories::BaseDirs::new().map(|dirs| dirs.home_dir().to_path_buf());69
let path_variable = std::env::var_os("PATH").unwrap_or_default();70
installed_in(71
Platform::detect(),72
home.as_deref(),73
&path_variable,74
&|path| path.is_file(),75
)76
}77
78
/// The browser Automatic stands for.79
pub fn automatic_browser(installed: &[InstalledBrowser]) -> Option<&InstalledBrowser> {80
automatic_in(Platform::detect(), installed)81
}82
83
fn automatic_in(platform: Platform, installed: &[InstalledBrowser]) -> Option<&InstalledBrowser> {84
system_default(platform, installed).or(installed.first())85
}86
87
/// The executable to sign in with: the saved choice while it is installed, else Automatic.88
pub(crate) fn chosen_executable(platform: Platform, home: Option<&Path>) -> Option<PathBuf> {89
if !platform.uses_unix_paths() {90
return None;91
}92
if let SignInBrowser::Program(path) = SignInBrowser::load()93
&& path.is_file()94
{95
return Some(path);96
}97
let path_variable = std::env::var_os("PATH").unwrap_or_default();98
let installed = installed_in(platform, home, &path_variable, &|path| path.is_file());99
automatic_in(platform, &installed).map(|browser| browser.path.clone())100
}101
102
pub(crate) fn installed_in(103
platform: Platform,104
home: Option<&Path>,105
path_variable: &std::ffi::OsStr,106
exists: &dyn Fn(&Path) -> bool,107
) -> Vec<InstalledBrowser> {108
let found: Vec<(String, PathBuf)> = match platform {109
Platform::Macos => MACOS_CHROME_APP_PATHS110
.iter()111
.chain(&MACOS_FIREFOX_APP_PATHS)112
.filter_map(|relative| {113
let path = application_roots(home)114
.map(|root| root.join(relative))115
.find(|path| exists(path))?;116
let name = relative.split(".app/").next().unwrap_or(relative);117
Some((name.to_owned(), path))118
})119
.collect(),120
Platform::Linux => LINUX_CHROME_NAMES121
.iter()122
.chain(&LINUX_FIREFOX_NAMES)123
.filter_map(|name| {124
let path = std::env::split_paths(path_variable)125
.map(|directory| directory.join(name))126
.find(|path| exists(path))?;127
Some(((*name).to_owned(), path))128
})129
.collect(),130
Platform::Windows | Platform::Wsl => Vec::new(),131
};132
found133
.into_iter()134
.map(|(name, path)| InstalledBrowser {135
engine: Engine::of_executable(&path),136
name,137
path,138
})139
.collect()140
}141
142
fn system_default(platform: Platform, installed: &[InstalledBrowser]) -> Option<&InstalledBrowser> {143
match platform {144
Platform::Macos => {145
let wanted = macos_default_bundle_id()?;146
installed.iter().find(|browser| {147
bundle_id(&browser.path).is_some_and(|id| id.eq_ignore_ascii_case(&wanted))148
})149
}150
Platform::Linux => {151
let output = Command::new("xdg-settings")152
.args(["get", "default-web-browser"])153
.output()154
.ok()?;155
desktop_entry_match(&String::from_utf8_lossy(&output.stdout), installed)156
}157
Platform::Windows | Platform::Wsl => None,158
}159
}160
161
fn plist_json(path: &Path) -> Option<Value> {162
let output = Command::new("plutil")163
.args(["-convert", "json", "-o", "-"])164
.arg(path)165
.output()166
.ok()?;167
serde_json::from_slice(&output.stdout).ok()168
}169
170
fn macos_default_bundle_id() -> Option<String> {171
let home = directories::BaseDirs::new()?.home_dir().to_path_buf();172
let handlers = home173
.join("Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist");174
handler_bundle_id(&plist_json(&handlers)?)175
}176
177
/// The app LaunchServices opens https links with, falling back to http.178
fn handler_bundle_id(handlers: &Value) -> Option<String> {179
let entries = handlers["LSHandlers"].as_array()?;180
["https", "http"].iter().find_map(|scheme| {181
entries182
.iter()183
.find(|entry| entry["LSHandlerURLScheme"] == *scheme)?["LSHandlerRoleAll"]184
.as_str()185
.map(str::to_owned)186
})187
}188
189
/// `CFBundleIdentifier` of the app bundle holding `executable` (`X.app/Contents/MacOS/x`).190
fn bundle_id(executable: &Path) -> Option<String> {191
let info = executable.parent()?.parent()?.join("Info.plist");192
plist_json(&info)?["CFBundleIdentifier"]193
.as_str()194
.map(str::to_owned)195
}196
197
/// The installed browser named like the desktop entry `xdg-settings` reports, as in `firefox.desktop`.198
fn desktop_entry_match<'a>(199
entry: &str,200
installed: &'a [InstalledBrowser],201
) -> Option<&'a InstalledBrowser> {202
let stem = entry.trim().trim_end_matches(".desktop");203
installed.iter().find(|browser| browser.name == stem)204
}205
206
#[cfg(test)]207
mod tests {208
use std::ffi::OsString;209
210
use serde_json::json;211
212
use super::*;213
214
#[test]215
fn finds_installed_browsers_chromium_first_once_each() {216
let installed = [217
"/Applications/Zen.app/Contents/MacOS/zen",218
"/Users/joe/Applications/Zen.app/Contents/MacOS/zen",219
"/Users/joe/Applications/Helium.app/Contents/MacOS/Helium",220
];221
let found = installed_in(222
Platform::Macos,223
Some(Path::new("/Users/joe")),224
&OsString::new(),225
&|path| installed.iter().any(|known| path == Path::new(known)),226
);227
let names: Vec<(&str, Engine)> = found228
.iter()229
.map(|browser| (browser.name.as_str(), browser.engine))230
.collect();231
assert_eq!(232
names,233
[("Helium", Engine::Chromium), ("Zen", Engine::Firefox)]234
);235
assert_eq!(found[1].path, PathBuf::from(installed[0]));236
}237
238
#[test]239
fn reads_the_https_handler() {240
let handlers = json!({"LSHandlers": [241
{"LSHandlerContentType": "public.html", "LSHandlerRoleAll": "com.apple.safari"},242
{"LSHandlerURLScheme": "http", "LSHandlerRoleAll": "org.mozilla.firefox"},243
{"LSHandlerURLScheme": "https", "LSHandlerRoleAll": "app.zen-browser.zen"},244
]});245
assert_eq!(246
handler_bundle_id(&handlers).as_deref(),247
Some("app.zen-browser.zen")248
);249
assert_eq!(handler_bundle_id(&json!({"LSHandlers": []})), None);250
}251
252
#[test]253
fn matches_the_linux_desktop_entry_by_name() {254
let installed = installed_in(255
Platform::Linux,256
None,257
&std::env::join_paths(["/usr/bin"]).unwrap(),258
&|path| path == Path::new("/usr/bin/chromium") || path == Path::new("/usr/bin/firefox"),259
);260
let found = desktop_entry_match("firefox.desktop\n", &installed).unwrap();261
assert_eq!(found.engine, Engine::Firefox);262
assert!(desktop_entry_match("org.gnome.Epiphany.desktop", &installed).is_none());263
}264
265
#[test]266
fn parses_the_saved_choice() {267
assert_eq!(SignInBrowser::parse(" \n"), SignInBrowser::Automatic);268
assert_eq!(269
SignInBrowser::parse("/Applications/Zen.app/Contents/MacOS/zen\n"),270
SignInBrowser::Program(PathBuf::from("/Applications/Zen.app/Contents/MacOS/zen"))271
);272
}273
}@@ -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
123
fn tab_from_url(id: String, url: &str) -> Tab {123
pub(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));@@ -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. A Firefox browser works the same way 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 and macOS need a Chromium or Firefox browser: Chrome, Chromium, Edge, Brave, Helium, Vivaldi, Firefox, Zen, LibreWolf or Floorp. Each runs with the app's own profile, so the user's everyday profile is never touched.
25
- Firefox browsers (Firefox, Zen, LibreWolf, Floorp) work as well, with their own `rusty-teams-firefox` profile. Settings > General > Teams session browser picks the browser. Automatic takes the system default browser when it is one of these, else the first installed, Chromium first. The choice sits in a file beside the profiles, since all orgs share them, and changing it restarts the app.
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 Chrom15
15
16
Windows keeps WebView2.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. A Firefox browser works the same way 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
Tokens are not written to disk. The browser profile holds the session.20
Tokens are not written to disk. The browser profile holds the session.21
21
22
## Consequences22
## Consequences23
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 and macOS need a Chromium or Firefox browser: Chrome, Chromium, Edge, Brave, Helium, Vivaldi, Firefox, Zen, LibreWolf or Floorp. Each runs with the app's own profile, so the user's everyday profile is never touched.25
- Firefox browsers (Firefox, Zen, LibreWolf, Floorp) work as well, with their own `rusty-teams-firefox` profile. Settings > General > Teams session browser picks the browser. Automatic takes the system default browser when it is one of these, else the first installed, Chromium first. The choice sits in a file beside the profiles, since all orgs share them, and changing it restarts the app.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.