BlueGit

ict rusty-teams

feat(settings): pick the Teams session browser in Settings

Replaces the RUSTY_TEAMS_SIGN_IN_BROWSER variable with a choice in
Settings > General. Automatic takes the system default browser when it
is Chromium- or Firefox-based, else the first one installed, so a Zen
user gets Zen without setup. The choice lives in a file beside the
browser profiles, since all orgs share them; changing it restarts the
app, which stops the old browser and starts the new one.

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

metis Michael Wallner · pushed by metis

Authored 2026-11-16 · 2 weeks ago

Hash
f47891c6ea9b8face087becc9d67f0a996fa0b18
Parent
c46900bf
8 files changed +393 −34
README.md +2 −2
@@ -90,8 +90,8 @@
90 90 | Platform | State |
91 91 |---|---|
92 92 | 🪟 Windows | Main target. Login through an embedded WebView2 |
93 | 🐧 Linux | Starts Google Chrome or Chromium on its own, or Firefox, Zen, LibreWolf or Floorp when no Chromium browser is installed (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. On start the app offers to install itself to `~/.local/share/rusty-teams/teams` (moved, or copied when started from a cargo `target` folder) and writes `~/.local/share/applications/rusty-teams.desktop`; starting a newer build offers to replace the installed one, and Settings > General can install, replace, remove or bring the question back. The installed copy of a release build looks for new GitHub releases (Settings > General > Automatic updates) and asks before it downloads and restarts. Tray icon through StatusNotifierItem (KDE Plasma natively, GNOME with the AppIndicator extension); with "Close to tray" the window closes and the app keeps running in the tray, which opens a new window. Built-in login without Chrome is planned |
94 | 🍎 macOS | Starts the first Chromium browser it finds (Google Chrome, Chromium, Microsoft Edge, Brave, Helium, Vivaldi), else the first Firefox browser (Firefox, Zen, LibreWolf, Floorp), on its own. `RUSTY_TEAMS_SIGN_IN_BROWSER=/path/to/executable` picks one explicitly, on Linux too (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
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, or Firefox, Zen, LibreWolf or Floorp when no Chromium browser is installed (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. On start the app offers to install itself to `~/.local/share/rusty-teams/teams` (moved, or copied when started from a cargo `target` folder) and writes `~/.local/share/applications/rusty-teams.desktop`; starting a newer build offers to replace the installed one, and Settings > General can install, replace, remove or bring the question back. The installed copy of a release build looks for new GitHub releases (Settings > General > Automatic updates) and asks before it downloads and restarts. Tray icon through StatusNotifierItem (KDE Plasma natively, GNOME with the AppIndicator extension); with "Close to tray" the window closes and the app keeps running in the tray, which opens a new window. Built-in login without Chrome is planned |
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), else the first Firefox browser (Firefox, Zen, LibreWolf, Floorp), on its own. `RUSTY_TEAMS_SIGN_IN_BROWSER=/path/to/executable` picks one explicitly, on Linux too (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
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
96The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
96The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
97
97
ROADMAP.md +1 −1
@@ -38,7 +38,7 @@ Feature parity with the Microsoft Teams desktop client.
38 38 | Sign in on Linux without starting Chrome by hand | Done | The app starts Chrome or Chromium headless with its own profile, shows the window for the login and hides it again afterwards; a watchdog restarts a dead or hung Chrome |
39 39 | Single instance, second start brings the window to front | Done | |
40 40 | Sign in on macOS without starting Chrome by hand | Done | Same managed browser as on Linux, profile in Application Support. Takes the first of Chrome, Chromium, Edge, Brave, Helium, Vivaldi; checked live with Helium |
41 | Sign in with a Firefox browser | Partial | Firefox, Zen, LibreWolf or Floorp over WebDriver BiDi when no Chromium browser is installed, or picked with `RUSTY_TEAMS_SIGN_IN_BROWSER`; own profile `rusty-teams-firefox` (ADR 0003). Checked live with Zen 1.24 on macOS: headless start, login window and back, page scripts and bindings, restart after a crashed app run. A full Teams sign-in and Linux not run yet |
41 | 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 |
42 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 |
43 43
44 44 ## Chat list
@@ -38,7 +38,7 @@ Feature parity with the Microsoft Teams desktop client.
38| Sign in on Linux without starting Chrome by hand | Done | The app starts Chrome or Chromium headless with its own profile, shows the window for the login and hides it again afterwards; a watchdog restarts a dead or hung Chrome |
38| Sign in on Linux without starting Chrome by hand | Done | The app starts Chrome or Chromium headless with its own profile, shows the window for the login and hides it again afterwards; a watchdog restarts a dead or hung Chrome |
39| Single instance, second start brings the window to front | Done | |
39| Single instance, second start brings the window to front | Done | |
40| Sign in on macOS without starting Chrome by hand | Done | Same managed browser as on Linux, profile in Application Support. Takes the first of Chrome, Chromium, Edge, Brave, Helium, Vivaldi; checked live with Helium |
40| Sign in on macOS without starting Chrome by hand | Done | Same managed browser as on Linux, profile in Application Support. Takes the first of Chrome, Chromium, Edge, Brave, Helium, Vivaldi; checked live with Helium |
41| Sign in with a Firefox browser | Partial | Firefox, Zen, LibreWolf or Floorp over WebDriver BiDi when no Chromium browser is installed, or picked with `RUSTY_TEAMS_SIGN_IN_BROWSER`; own profile `rusty-teams-firefox` (ADR 0003). Checked live with Zen 1.24 on macOS: headless start, login window and back, page scripts and bindings, restart after a crashed app run. A full Teams sign-in and Linux not run yet |
41| 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 |
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| 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 |
43
43
44## Chat list
44## Chat list
crates/app-base/locales/app.yml +11 −2
@@ -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 is a Chromium or Firefox browser such as Chrome, Edge, Helium, Firefox or Zen).
418 de: Ändert nicht den Browser der Teams-Sitzung (das ist ein Chromium- oder Firefox-Browser wie Chrome, Edge, Helium, Firefox oder Zen).
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
@@ -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 tray
411 en: The title bar X hides the window to the tray
412 de: Das X in der Titelleiste blendet das Fenster ins Infobereich-Symbol aus
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 external_browser:
422 external_browser:
414 en: Open links and Google sign-in with
423 en: Open links and Google sign-in with
415 de: Links und Google-Anmeldung öffnen mit
424 de: Links und Google-Anmeldung öffnen mit
416 external_browser_detail:
425 external_browser_detail:
417 en: Does not change the Teams session browser (that is a Chromium or Firefox browser such as Chrome, Edge, Helium, Firefox or Zen).
426 en: Does not change the Teams session browser.
418 de: Ändert nicht den Browser der Teams-Sitzung (das ist ein Chromium- oder Firefox-Browser wie Chrome, Edge, Helium, Firefox oder Zen).
427 de: Ändert nicht den Browser der Teams-Sitzung.
419 external_browser_system:
428 external_browser_system:
420 en: System default
429 en: System default
421 de: Systemstandard
430 de: Systemstandard
crates/app/src/settings/general.rs +79 −0
@@ -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 old
249/// browser on the way out and starts the new one.
250#[cfg(any(target_os = "linux", target_os = "macos"))]
251fn 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"))]
308fn 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
247fn translation_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
326fn 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() {
crates/browser/src/config.rs +20 −24
@@ -6,12 +6,10 @@ use crate::error::BrowserError;
6 6
7 7 pub const PROFILE_NAME: &str = "rusty-teams-chrome";
8 8 pub const FIREFOX_PROFILE_NAME: &str = "rusty-teams-firefox";
9 /// Path to the sign-in browser executable, overriding the search. Firefox-family names run over WebDriver BiDi.
10 pub const BROWSER_OVERRIDE_ENV: &str = "RUSTY_TEAMS_SIGN_IN_BROWSER";
11 9 pub const DEFAULT_PORT: u16 = 9222;
12 10 const CHROME_RELATIVE: &str = r"Google\Chrome\Application\chrome.exe";
13 11 const WINDOWS_VARIABLES: [&str; 4] = ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "TEMP"];
14 const LINUX_CHROME_NAMES: [&str; 5] = [
12 pub(crate) const LINUX_CHROME_NAMES: [&str; 5] = [
15 13 "google-chrome",
16 14 "google-chrome-stable",
17 15 "chromium",
@@ -21,7 +19,7 @@ const LINUX_CHROME_NAMES: [&str; 5] = [
21 19 const MACOS_CHROME_NAMES: [&str; 3] = ["google-chrome", "chromium", "chrome"];
22 20 /// Chromium-based browsers in order of preference; each one gets its own profile, so the user's
23 21 /// everyday browser stays untouched.
24 const MACOS_CHROME_APP_PATHS: [&str; 6] = [
22 pub(crate) const MACOS_CHROME_APP_PATHS: [&str; 6] = [
25 23 "Google Chrome.app/Contents/MacOS/Google Chrome",
26 24 "Chromium.app/Contents/MacOS/Chromium",
27 25 "Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
@@ -30,13 +28,14 @@ const MACOS_CHROME_APP_PATHS: [&str; 6] = [
30 28 "Vivaldi.app/Contents/MacOS/Vivaldi",
31 29 ];
32 30 /// Firefox-based browsers, tried only when no Chromium browser is installed.
33 const MACOS_FIREFOX_APP_PATHS: [&str; 4] = [
31 pub(crate) const MACOS_FIREFOX_APP_PATHS: [&str; 4] = [
34 32 "Firefox.app/Contents/MacOS/firefox",
35 33 "Zen.app/Contents/MacOS/zen",
36 34 "LibreWolf.app/Contents/MacOS/librewolf",
37 35 "Floorp.app/Contents/MacOS/floorp",
38 36 ];
39 const LINUX_FIREFOX_NAMES: [&str; 5] = ["firefox", "zen-browser", "zen", "librewolf", "floorp"];
37 pub(crate) const LINUX_FIREFOX_NAMES: [&str; 5] =
38 ["firefox", "zen-browser", "zen", "librewolf", "floorp"];
40 39
41 40 /// The protocol family of the sign-in browser: Chromium speaks CDP, Firefox WebDriver BiDi.
42 41 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -132,9 +131,6 @@ impl Config {
132 131 .collect(),
133 132 Platform::Wsl => wsl_windows_variables()?,
134 133 };
135 let override_path = std::env::var_os(BROWSER_OVERRIDE_ENV)
136 .filter(|value| !value.is_empty())
137 .map(PathBuf::from);
138 134 let base = directories::BaseDirs::new();
139 135 let linux_data_dir = base.as_ref().map(|dirs| dirs.data_dir().to_path_buf());
140 136 let home_dir = base.as_ref().map(|dirs| dirs.home_dir().to_path_buf());
@@ -155,24 +151,24 @@ impl Config {
155 151 },
156 152 )?;
157 153 let path_variable = std::env::var_os("PATH").unwrap_or_default();
158 Ok(config.select_browser(
159 override_path,
160 home_dir.as_deref(),
161 &path_variable,
162 &|path| path.is_file(),
163 ))
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 }),
159 )
164 160 }
165 161
166 /// Picks the sign-in browser: the override path, else the first Chromium browser, else the
167 /// first Firefox-based one on Linux and macOS. A Firefox browser gets its own profile.
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.
168 164 pub(crate) fn select_browser(
169 165 mut self,
170 override_path: Option<PathBuf>,
166 chosen: Option<PathBuf>,
171 167 home_dir: Option<&Path>,
172 168 path_variable: &std::ffi::OsStr,
173 169 exists: &dyn Fn(&Path) -> bool,
174 170 ) -> Config {
175 if let Some(path) = override_path {
171 if let Some(path) = chosen {
176 172 self.engine = Engine::of_executable(&path);
177 173 self.search = BrowserSearch::Files(vec![path]);
178 174 } else if find_browser(&self.search, path_variable, exists).is_err()
@@ -304,7 +300,7 @@ fn firefox_search(platform: Platform, home_dir: Option<&Path>) -> Option<Browser
304 300 }
305 301 }
306 302
307 fn application_roots(home_dir: Option<&Path>) -> impl Iterator<Item = PathBuf> {
303 pub(crate) fn application_roots(home_dir: Option<&Path>) -> impl Iterator<Item = PathBuf> {
308 304 std::iter::once(PathBuf::from("/Applications"))
309 305 .chain(home_dir.map(|home| home.join("Applications")))
310 306 }
@@ -689,9 +685,9 @@ mod tests {
689 685 Config::resolve(Platform::Macos, 9222, &inputs).unwrap()
690 686 }
691 687
692 fn select(installed: &[&str], override_path: Option<&str>) -> Config {
688 fn select(installed: &[&str], chosen: Option<&str>) -> Config {
693 689 macos_config().select_browser(
694 override_path.map(PathBuf::from),
690 chosen.map(PathBuf::from),
695 691 Some(Path::new("/Users/joe")),
696 692 &OsString::new(),
697 693 &|path| {
@@ -731,12 +727,12 @@ mod tests {
731 727 }
732 728
733 729 #[test]
734 fn the_override_picks_the_browser_and_its_engine() {
730 fn the_chosen_browser_sets_the_engine() {
735 731 let helium = "/Applications/Helium.app/Contents/MacOS/Helium";
736 732 let firefox = select(&[helium], Some("/opt/zen/zen"));
737 733 assert_eq!(firefox.engine, Engine::Firefox);
738 734 let BrowserSearch::Files(files) = &firefox.search else {
739 panic!("expected the override path")
735 panic!("expected the chosen path")
740 736 };
741 737 assert_eq!(files, &[PathBuf::from("/opt/zen/zen")]);
742 738 assert_eq!(select(&[], Some(helium)).engine, Engine::Chromium);
@@ -6,12 +6,10 @@ use crate::error::BrowserError;
6
6
7pub const PROFILE_NAME: &str = "rusty-teams-chrome";
7pub const PROFILE_NAME: &str = "rusty-teams-chrome";
8pub const FIREFOX_PROFILE_NAME: &str = "rusty-teams-firefox";
8pub const FIREFOX_PROFILE_NAME: &str = "rusty-teams-firefox";
9/// Path to the sign-in browser executable, overriding the search. Firefox-family names run over WebDriver BiDi.
10pub const BROWSER_OVERRIDE_ENV: &str = "RUSTY_TEAMS_SIGN_IN_BROWSER";
11pub const DEFAULT_PORT: u16 = 9222;
9pub const DEFAULT_PORT: u16 = 9222;
12const CHROME_RELATIVE: &str = r"Google\Chrome\Application\chrome.exe";
10const CHROME_RELATIVE: &str = r"Google\Chrome\Application\chrome.exe";
13const WINDOWS_VARIABLES: [&str; 4] = ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "TEMP"];
11const WINDOWS_VARIABLES: [&str; 4] = ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "TEMP"];
14const LINUX_CHROME_NAMES: [&str; 5] = [
12pub(crate) const LINUX_CHROME_NAMES: [&str; 5] = [
15 "google-chrome",
13 "google-chrome",
16 "google-chrome-stable",
14 "google-chrome-stable",
17 "chromium",
15 "chromium",
@@ -21,7 +19,7 @@ const LINUX_CHROME_NAMES: [&str; 5] = [
21const MACOS_CHROME_NAMES: [&str; 3] = ["google-chrome", "chromium", "chrome"];
19const MACOS_CHROME_NAMES: [&str; 3] = ["google-chrome", "chromium", "chrome"];
22/// Chromium-based browsers in order of preference; each one gets its own profile, so the user's
20/// Chromium-based browsers in order of preference; each one gets its own profile, so the user's
23/// everyday browser stays untouched.
21/// everyday browser stays untouched.
24const MACOS_CHROME_APP_PATHS: [&str; 6] = [
22pub(crate) const MACOS_CHROME_APP_PATHS: [&str; 6] = [
25 "Google Chrome.app/Contents/MacOS/Google Chrome",
23 "Google Chrome.app/Contents/MacOS/Google Chrome",
26 "Chromium.app/Contents/MacOS/Chromium",
24 "Chromium.app/Contents/MacOS/Chromium",
27 "Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
25 "Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
@@ -30,13 +28,14 @@ const MACOS_CHROME_APP_PATHS: [&str; 6] = [
30 "Vivaldi.app/Contents/MacOS/Vivaldi",
28 "Vivaldi.app/Contents/MacOS/Vivaldi",
31];
29];
32/// Firefox-based browsers, tried only when no Chromium browser is installed.
30/// Firefox-based browsers, tried only when no Chromium browser is installed.
33const MACOS_FIREFOX_APP_PATHS: [&str; 4] = [
31pub(crate) const MACOS_FIREFOX_APP_PATHS: [&str; 4] = [
34 "Firefox.app/Contents/MacOS/firefox",
32 "Firefox.app/Contents/MacOS/firefox",
35 "Zen.app/Contents/MacOS/zen",
33 "Zen.app/Contents/MacOS/zen",
36 "LibreWolf.app/Contents/MacOS/librewolf",
34 "LibreWolf.app/Contents/MacOS/librewolf",
37 "Floorp.app/Contents/MacOS/floorp",
35 "Floorp.app/Contents/MacOS/floorp",
38];
36];
39const LINUX_FIREFOX_NAMES: [&str; 5] = ["firefox", "zen-browser", "zen", "librewolf", "floorp"];
37pub(crate) const LINUX_FIREFOX_NAMES: [&str; 5] =
38 ["firefox", "zen-browser", "zen", "librewolf", "floorp"];
40
39
41/// The protocol family of the sign-in browser: Chromium speaks CDP, Firefox WebDriver BiDi.
40/// The protocol family of the sign-in browser: Chromium speaks CDP, Firefox WebDriver BiDi.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -132,9 +131,6 @@ impl Config {
132 .collect(),
131 .collect(),
133 Platform::Wsl => wsl_windows_variables()?,
132 Platform::Wsl => wsl_windows_variables()?,
134 };
133 };
135 let override_path = std::env::var_os(BROWSER_OVERRIDE_ENV)
136 .filter(|value| !value.is_empty())
137 .map(PathBuf::from);
138 let base = directories::BaseDirs::new();
134 let base = directories::BaseDirs::new();
139 let linux_data_dir = base.as_ref().map(|dirs| dirs.data_dir().to_path_buf());
135 let linux_data_dir = base.as_ref().map(|dirs| dirs.data_dir().to_path_buf());
140 let home_dir = base.as_ref().map(|dirs| dirs.home_dir().to_path_buf());
136 let home_dir = base.as_ref().map(|dirs| dirs.home_dir().to_path_buf());
@@ -155,24 +151,24 @@ impl Config {
155 },
151 },
156 )?;
152 )?;
157 let path_variable = std::env::var_os("PATH").unwrap_or_default();
153 let path_variable = std::env::var_os("PATH").unwrap_or_default();
158 Ok(config.select_browser(
154 let chosen = crate::sign_in_choice::chosen_executable(platform, home_dir.as_deref());
159 override_path,
155 Ok(
160 home_dir.as_deref(),
156 config.select_browser(chosen, home_dir.as_deref(), &path_variable, &|path| {
161 &path_variable,
157 path.is_file()
162 &|path| path.is_file(),
158 }),
163 ))
159 )
164 }
160 }
165
161
166 /// Picks the sign-in browser: the override path, else the first Chromium browser, else the
162 /// Uses `chosen` as the sign-in browser, else the first Chromium browser, else the first
167 /// first Firefox-based one on Linux and macOS. A Firefox browser gets its own profile.
163 /// Firefox-based one on Linux and macOS. A Firefox browser gets its own profile.
168 pub(crate) fn select_browser(
164 pub(crate) fn select_browser(
169 mut self,
165 mut self,
170 override_path: Option<PathBuf>,
166 chosen: Option<PathBuf>,
171 home_dir: Option<&Path>,
167 home_dir: Option<&Path>,
172 path_variable: &std::ffi::OsStr,
168 path_variable: &std::ffi::OsStr,
173 exists: &dyn Fn(&Path) -> bool,
169 exists: &dyn Fn(&Path) -> bool,
174 ) -> Config {
170 ) -> Config {
175 if let Some(path) = override_path {
171 if let Some(path) = chosen {
176 self.engine = Engine::of_executable(&path);
172 self.engine = Engine::of_executable(&path);
177 self.search = BrowserSearch::Files(vec![path]);
173 self.search = BrowserSearch::Files(vec![path]);
178 } else if find_browser(&self.search, path_variable, exists).is_err()
174 } else if find_browser(&self.search, path_variable, exists).is_err()
@@ -304,7 +300,7 @@ fn firefox_search(platform: Platform, home_dir: Option<&Path>) -> Option<Browser
304 }
300 }
305}
301}
306
302
307fn application_roots(home_dir: Option<&Path>) -> impl Iterator<Item = PathBuf> {
303pub(crate) fn application_roots(home_dir: Option<&Path>) -> impl Iterator<Item = PathBuf> {
308 std::iter::once(PathBuf::from("/Applications"))
304 std::iter::once(PathBuf::from("/Applications"))
309 .chain(home_dir.map(|home| home.join("Applications")))
305 .chain(home_dir.map(|home| home.join("Applications")))
310}
306}
@@ -689,9 +685,9 @@ mod tests {
689 Config::resolve(Platform::Macos, 9222, &inputs).unwrap()
685 Config::resolve(Platform::Macos, 9222, &inputs).unwrap()
690 }
686 }
691
687
692 fn select(installed: &[&str], override_path: Option<&str>) -> Config {
688 fn select(installed: &[&str], chosen: Option<&str>) -> Config {
693 macos_config().select_browser(
689 macos_config().select_browser(
694 override_path.map(PathBuf::from),
690 chosen.map(PathBuf::from),
695 Some(Path::new("/Users/joe")),
691 Some(Path::new("/Users/joe")),
696 &OsString::new(),
692 &OsString::new(),
697 &|path| {
693 &|path| {
@@ -731,12 +727,12 @@ mod tests {
731 }
727 }
732
728
733 #[test]
729 #[test]
734 fn the_override_picks_the_browser_and_its_engine() {
730 fn the_chosen_browser_sets_the_engine() {
735 let helium = "/Applications/Helium.app/Contents/MacOS/Helium";
731 let helium = "/Applications/Helium.app/Contents/MacOS/Helium";
736 let firefox = select(&[helium], Some("/opt/zen/zen"));
732 let firefox = select(&[helium], Some("/opt/zen/zen"));
737 assert_eq!(firefox.engine, Engine::Firefox);
733 assert_eq!(firefox.engine, Engine::Firefox);
738 let BrowserSearch::Files(files) = &firefox.search else {
734 let BrowserSearch::Files(files) = &firefox.search else {
739 panic!("expected the override path")
735 panic!("expected the chosen path")
740 };
736 };
741 assert_eq!(files, &[PathBuf::from("/opt/zen/zen")]);
737 assert_eq!(files, &[PathBuf::from("/opt/zen/zen")]);
742 assert_eq!(select(&[], Some(helium)).engine, Engine::Chromium);
738 assert_eq!(select(&[], Some(helium)).engine, Engine::Chromium);
crates/browser/src/lib.rs +4 −2
@@ -6,6 +6,7 @@ mod error;
6 6 mod http;
7 7 mod launch;
8 8 mod process;
9 mod sign_in_choice;
9 10 mod targets;
10 11 mod watchdog;
11 12
@@ -13,13 +14,14 @@ pub use bidi::{Bidi, Context, remote_value_to_json};
13 14 pub use bidi_transport::{BidiTransport, session_transport};
14 15 pub use browser::{Browser, RendererState, Status, Timeouts};
15 16 pub use config::{
16 BROWSER_OVERRIDE_ENV, Config, ConfigInputs, DEFAULT_PORT, Engine, FIREFOX_PROFILE_NAME,
17 PROFILE_NAME, Platform, windows_path_to_wsl,
17 Config, ConfigInputs, DEFAULT_PORT, Engine, FIREFOX_PROFILE_NAME, PROFILE_NAME, Platform,
18 windows_path_to_wsl,
18 19 };
19 20 pub use error::BrowserError;
20 21 pub use launch::{
21 22 ArgumentSpec, LaunchRequest, Launcher, SystemLauncher, chrome_arguments, firefox_arguments,
22 23 user_agent,
23 24 };
25 pub use sign_in_choice::{InstalledBrowser, SignInBrowser, automatic_browser, installed_browsers};
24 26 pub use targets::{APPS, App, LoginState, Mode, Tab};
25 27 pub use watchdog::{BrowserEvent, Watchdog, WatchdogConfig};
@@ -6,6 +6,7 @@ mod error;
6mod http;
6mod http;
7mod launch;
7mod launch;
8mod process;
8mod process;
9mod sign_in_choice;
9mod targets;
10mod targets;
10mod watchdog;
11mod watchdog;
11
12
@@ -13,13 +14,14 @@ pub use bidi::{Bidi, Context, remote_value_to_json};
13pub use bidi_transport::{BidiTransport, session_transport};
14pub use bidi_transport::{BidiTransport, session_transport};
14pub use browser::{Browser, RendererState, Status, Timeouts};
15pub use browser::{Browser, RendererState, Status, Timeouts};
15pub use config::{
16pub use config::{
16 BROWSER_OVERRIDE_ENV, Config, ConfigInputs, DEFAULT_PORT, Engine, FIREFOX_PROFILE_NAME,
17 Config, ConfigInputs, DEFAULT_PORT, Engine, FIREFOX_PROFILE_NAME, PROFILE_NAME, Platform,
17 PROFILE_NAME, Platform, windows_path_to_wsl,
18 windows_path_to_wsl,
18};
19};
19pub use error::BrowserError;
20pub use error::BrowserError;
20pub use launch::{
21pub use launch::{
21 ArgumentSpec, LaunchRequest, Launcher, SystemLauncher, chrome_arguments, firefox_arguments,
22 ArgumentSpec, LaunchRequest, Launcher, SystemLauncher, chrome_arguments, firefox_arguments,
22 user_agent,
23 user_agent,
23};
24};
25pub use sign_in_choice::{InstalledBrowser, SignInBrowser, automatic_browser, installed_browsers};
24pub use targets::{APPS, App, LoginState, Mode, Tab};
26pub use targets::{APPS, App, LoginState, Mode, Tab};
25pub use watchdog::{BrowserEvent, Watchdog, WatchdogConfig};
27pub use watchdog::{BrowserEvent, Watchdog, WatchdogConfig};
crates/browser/src/sign_in_choice.rs added +273 −0
@@ -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 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
5use std::path::{Path, PathBuf};
6use std::process::Command;
7
8use serde_json::Value;
9
10use crate::config::{
11 Engine, LINUX_CHROME_NAMES, LINUX_FIREFOX_NAMES, MACOS_CHROME_APP_PATHS,
12 MACOS_FIREFOX_APP_PATHS, Platform, application_roots,
13};
14
15const CHOICE_FILE: &str = "rusty-teams-sign-in-browser";
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum SignInBrowser {
19 Automatic,
20 Program(PathBuf),
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct InstalledBrowser {
25 pub name: String,
26 pub path: PathBuf,
27 pub engine: Engine,
28}
29
30fn choice_path() -> Option<PathBuf> {
31 directories::BaseDirs::new().map(|dirs| dirs.data_dir().join(CHOICE_FILE))
32}
33
34impl 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.
67pub 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.
79pub fn automatic_browser(installed: &[InstalledBrowser]) -> Option<&InstalledBrowser> {
80 automatic_in(Platform::detect(), installed)
81}
82
83fn 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.
88pub(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
102pub(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
142fn 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
161fn 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
170fn 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.
178fn 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`).
190fn 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`.
198fn 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)]
207mod 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}
docs/decisions/0003-sign-in-through-a-browser-session.md +3 −3
@@ -15,14 +15,14 @@ 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. Without a Chromium browser it does the same with a Firefox browser over WebDriver BiDi. The app finds Chrome in the usual install locations. Only that managed Chrome may be stopped via the debug port. A second launch brings the existing instance forward. The UI can paint from the local cache before the network answers.
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, or a Firefox browser. macOS takes the first Chromium browser it finds: Chrome, Chromium, Edge, Brave, Helium or Vivaldi. Each runs with the app's own profile, so the user's everyday profile is never touched.
25 - Without a Chromium browser, Linux and macOS start a Firefox browser instead (Firefox, Zen, LibreWolf, Floorp) with its own `rusty-teams-firefox` profile. `RUSTY_TEAMS_SIGN_IN_BROWSER` names an executable to use either way.
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 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 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 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.
@@ -15,14 +15,14 @@ Options were: a stored refresh token, an embedded engine per OS, or a real Chrom
15
15
16Windows keeps WebView2.
16Windows keeps WebView2.
17
17
18On Linux and macOS the app starts Chrome or Chromium with remote debugging and its own profile, shows it for login, and hides it again afterwards. Without a Chromium browser it does the same with a Firefox browser over WebDriver BiDi. The app finds Chrome in the usual install locations. Only that managed Chrome may be stopped via the debug port. A second launch brings the existing instance forward. The UI can paint from the local cache before the network answers.
18On Linux and macOS the app starts Chrome or Chromium with remote debugging and its own profile, shows it for login, and hides it again afterwards. 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
20Tokens are not written to disk. The browser profile holds the session.
20Tokens are not written to disk. The browser profile holds the session.
21
21
22## Consequences
22## Consequences
23
23
24- Linux needs a Chrome or Chromium install, or a Firefox browser. macOS takes the first Chromium browser it finds: Chrome, Chromium, Edge, Brave, Helium or Vivaldi. Each runs with the app's own profile, so the user's everyday profile is never touched.
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- Without a Chromium browser, Linux and macOS start a Firefox browser instead (Firefox, Zen, LibreWolf, Floorp) with its own `rusty-teams-firefox` profile. `RUSTY_TEAMS_SIGN_IN_BROWSER` names an executable to use either way.
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.
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.
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.
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.