Skip to main content

brows3_lib/credentials/
mod.rs

1pub mod keychain;
2pub mod manager;
3
4pub use keychain::KeychainStorage;
5pub use manager::{CredentialType, Profile, ProfileManager};
6
7use crate::error::Result;
8use std::path::PathBuf;
9use std::sync::Arc;
10use tauri::{AppHandle, Manager};
11use tokio::sync::RwLock;
12
13pub(crate) fn write_private_file(path: &std::path::Path, content: &[u8]) -> Result<()> {
14    use std::io::Write;
15    let parent = path
16        .parent()
17        .ok_or_else(|| crate::error::AppError::IoError("Missing storage directory".to_string()))?;
18    std::fs::create_dir_all(parent)?;
19    let mut replacement = tempfile::NamedTempFile::new_in(parent)?;
20    replacement.write_all(content)?;
21    replacement.as_file().sync_all()?;
22    replacement
23        .persist(path)
24        .map_err(|error| crate::error::AppError::IoError(error.error.to_string()))?;
25    Ok(())
26}
27
28fn portable_data_dir() -> Option<PathBuf> {
29    let env_portable = std::env::var("BROWS3_PORTABLE")
30        .map(|value| matches!(value.to_ascii_lowercase().as_str(), "1" | "true" | "yes"))
31        .unwrap_or(false);
32
33    let exe_dir = std::env::current_exe()
34        .ok()
35        .and_then(|path| path.parent().map(|parent| parent.to_path_buf()))?;
36
37    if env_portable || exe_dir.join("brows3.portable").exists() {
38        Some(exe_dir.join("data"))
39    } else {
40        None
41    }
42}
43
44/// Initialize the credentials manager and register it as app state.
45/// This must happen during Tauri setup before frontend commands run.
46pub fn init<R: tauri::Runtime>(app: &AppHandle<R>) -> Result<PathBuf> {
47    // When both Linux backends are compiled, make the persistent desktop
48    // Secret Service selection explicit. Kernel keyutils is retained only so
49    // KeychainStorage can migrate credentials written by older Brows3 builds.
50    #[cfg(target_os = "linux")]
51    keyring::set_default_credential_builder(keyring::secret_service::default_credential_builder());
52
53    let portable_config_dir = portable_data_dir();
54    let force_secret_fallback = portable_config_dir.is_some();
55    let config_dir = match portable_config_dir {
56        Some(path) => path,
57        None => app
58            .path()
59            .app_config_dir()
60            .map_err(|e: tauri::Error| crate::error::AppError::ConfigError(e.to_string()))?,
61    };
62
63    // Ensure config directory exists
64    std::fs::create_dir_all(&config_dir)?;
65
66    let manager = ProfileManager::new(config_dir.clone(), force_secret_fallback)?;
67    let state = Arc::new(RwLock::new(manager));
68
69    app.manage(state);
70
71    log::info!(
72        "Credentials manager initialized{}",
73        if force_secret_fallback {
74            " in portable mode"
75        } else {
76            ""
77        }
78    );
79    Ok(config_dir)
80}