use crate::api_client::ApiClient;
use crate::credentials::Credentials;
fn is_headless() -> bool {
if std::env::var_os("TRACEVAULT_NO_BROWSER").is_some() {
return true;
}
if std::env::var_os("CI").is_some() || std::env::var_os("GITHUB_ACTIONS").is_some() {
return true;
}
if std::path::Path::new("/.dockerenv").exists() {
return true;
}
#[cfg(all(unix, not(target_os = "macos")))]
{
if std::env::var_os("DISPLAY").is_none() && std::env::var_os("WAYLAND_DISPLAY").is_none() {
return true;
}
}
false
}
fn print_url_banner(url: &str) {
println!();
println!(" Open this URL in a browser to finish logging in:");
println!();
println!(" {url}");
println!();
}
pub async fn login(server_url: &str, no_browser: bool) -> Result<(), Box<dyn std::error::Error>> {
let client = ApiClient::new(server_url, None);
let device = client.device_start().await?;
let full_url = format!(
"{}/auth/device?token={}",
server_url.trim_end_matches('/'),
device.token
);
print_url_banner(&full_url);
let skip_browser = no_browser || is_headless();
if skip_browser {
println!("Not attempting to auto-open a browser (headless environment detected or --no-browser set).");
} else {
println!("Attempting to open the URL in your default browser...");
if let Err(e) = open::that(&full_url) {
eprintln!("Could not open browser automatically: {e}");
eprintln!("Copy the URL above into a browser manually.");
}
}
print!("Waiting for authentication in the browser");
use std::io::Write;
let _ = std::io::stdout().flush();
let poll_interval = std::time::Duration::from_secs(3);
let max_attempts = 100; let mut consecutive_errors = 0u32;
let max_consecutive_errors = 5;
for _ in 0..max_attempts {
tokio::time::sleep(poll_interval).await;
print!(".");
let _ = std::io::stdout().flush();
match client.device_status(&device.token).await {
Ok(status) => {
consecutive_errors = 0;
if status.status == "approved" {
let token = status
.token
.ok_or("Server approved but did not return a session token")?;
let email = status
.email
.ok_or("Server approved but did not return an email")?;
println!(" done!");
println!();
println!("Logged in as {email}");
let creds = Credentials {
server_url: server_url.to_string(),
token,
email,
org_slug: None,
};
creds.save()?;
println!("Credentials saved to {}", Credentials::path().display());
return Ok(());
}
}
Err(e) => {
let msg = e.to_string();
if msg.contains("429") || msg.to_lowercase().contains("too many requests") {
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
continue;
}
consecutive_errors += 1;
if consecutive_errors >= max_consecutive_errors {
eprintln!("\nError polling status: {e}");
return Err(e);
}
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
}
}
}
Err("Authentication timed out after 5 minutes".into())
}
#[cfg(test)]
mod tests {
use super::is_headless;
#[test]
fn tracevault_no_browser_env_forces_headless() {
unsafe {
std::env::set_var("TRACEVAULT_NO_BROWSER", "1");
}
assert!(is_headless());
unsafe {
std::env::remove_var("TRACEVAULT_NO_BROWSER");
}
}
}