security: improve credential encryption and CORS configurability
Security improvements based on code review: 1. Credential Encryption (Critical) - Replace XOR obfuscation with AES-256-GCM encryption - Derive key from machine ID (tied to specific machine) - Add migration support for legacy XOR format - Automatic re-encryption on first load of legacy credentials 2. HTTPS Default (Medium) - Change default `secure` setting to `true` for new installs - Existing users keep their current setting 3. Configurable CORS Origins (High) - Replace hardcoded domain whitelist with SQLite-backed storage - Default origins: vicrodh.github.io, control.qbz.lol - Add commands: get/add/remove origins, restore defaults - Origins can be customized for third-party clients - Server restarts automatically when origins change New dependencies: - aes-gcm: AES-256-GCM authenticated encryption - sha2: SHA-256 for key derivation
This commit is contained in:
1 parent
8e7d9de754
commit
2818ac4d29
6 files changed
+523
-38
No files matched your search
@@ -36,9 +36,11 @@ tower-http = { version = "0.5", features = ["cors"] }
|
|||||||
qrcode-generator = "4.1"
|
qrcode-generator = "4.1"
|
||||||
rcgen = "0.12"
|
rcgen = "0.12"
|
||||||
|
|
||||||
# Crypto (for API signatures)
|
# Crypto (for API signatures and credential encryption)
|
||||||
md-5 = "0.10"
|
md-5 = "0.10"
|
||||||
base64 = "0.22"
|
base64 = "0.22"
|
||||||
|
aes-gcm = "0.10"
|
||||||
|
sha2 = "0.10"
|
||||||
|
|
||||||
# Regex (for bundle parsing)
|
# Regex (for bundle parsing)
|
||||||
regex = "1"
|
regex = "1"
|
||||||
|
|||||||
@@ -191,7 +191,19 @@ impl ApiServerState {
|
|||||||
playback_tx: self.playback_tx.clone(),
|
playback_tx: self.playback_tx.clone(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let router = build_router(ctx);
|
// Load allowed origins for CORS
|
||||||
|
let allowed_origins = app_handle
|
||||||
|
.try_state::<crate::config::AllowedOriginsState>()
|
||||||
|
.map(|state| {
|
||||||
|
state.get_origins()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.into_iter()
|
||||||
|
.map(|o| o.origin)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let router = build_router(ctx, allowed_origins);
|
||||||
let bind_addr = SocketAddr::from(([0, 0, 0, 0], settings.port));
|
let bind_addr = SocketAddr::from(([0, 0, 0, 0], settings.port));
|
||||||
let handle = AxumHandle::<SocketAddr>::new();
|
let handle = AxumHandle::<SocketAddr>::new();
|
||||||
let make_service = router.into_make_service_with_connect_info::<SocketAddr>();
|
let make_service = router.into_make_service_with_connect_info::<SocketAddr>();
|
||||||
@@ -401,9 +413,61 @@ pub async fn sync_server(app: &AppHandle) -> Result<(), String> {
|
|||||||
api_state.apply_settings(app.clone(), settings).await
|
api_state.apply_settings(app.clone(), settings).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_router(ctx: ApiContext) -> Router {
|
// ============================================================================
|
||||||
|
// Allowed Origins Commands
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn remote_control_get_allowed_origins(
|
||||||
|
app: AppHandle,
|
||||||
|
) -> Result<Vec<crate::config::AllowedOrigin>, String> {
|
||||||
|
let state = app.state::<crate::config::AllowedOriginsState>();
|
||||||
|
state.get_origins()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn remote_control_add_allowed_origin(
|
||||||
|
origin: String,
|
||||||
|
app: AppHandle,
|
||||||
|
) -> Result<crate::config::AllowedOrigin, String> {
|
||||||
|
let state = app.state::<crate::config::AllowedOriginsState>();
|
||||||
|
let result = state.add_origin(&origin)?;
|
||||||
|
// Restart server to apply new CORS settings
|
||||||
|
sync_server(&app).await?;
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn remote_control_remove_allowed_origin(
|
||||||
|
id: i64,
|
||||||
|
app: AppHandle,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let state = app.state::<crate::config::AllowedOriginsState>();
|
||||||
|
state.remove_origin(id)?;
|
||||||
|
// Restart server to apply new CORS settings
|
||||||
|
sync_server(&app).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn remote_control_restore_default_origins(
|
||||||
|
app: AppHandle,
|
||||||
|
) -> Result<Vec<crate::config::AllowedOrigin>, String> {
|
||||||
|
let state = app.state::<crate::config::AllowedOriginsState>();
|
||||||
|
state.restore_defaults()?;
|
||||||
|
// Restart server to apply new CORS settings
|
||||||
|
sync_server(&app).await?;
|
||||||
|
state.get_origins()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_router(ctx: ApiContext, allowed_origins: Vec<String>) -> Router {
|
||||||
|
let allowed_origins = std::sync::Arc::new(allowed_origins);
|
||||||
|
let origins_clone = allowed_origins.clone();
|
||||||
|
|
||||||
let cors = CorsLayer::new()
|
let cors = CorsLayer::new()
|
||||||
.allow_origin(AllowOrigin::predicate(|origin, _| is_local_origin(origin)))
|
.allow_origin(AllowOrigin::predicate(move |origin, _| {
|
||||||
|
is_local_origin(origin, &origins_clone)
|
||||||
|
}))
|
||||||
.allow_methods([Method::GET, Method::POST, Method::OPTIONS])
|
.allow_methods([Method::GET, Method::POST, Method::OPTIONS])
|
||||||
.allow_headers([
|
.allow_headers([
|
||||||
header::CONTENT_TYPE,
|
header::CONTENT_TYPE,
|
||||||
@@ -1059,7 +1123,7 @@ fn is_local_addr(ip: IpAddr) -> bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_local_origin(origin: &header::HeaderValue) -> bool {
|
fn is_local_origin(origin: &header::HeaderValue, allowed_origins: &[String]) -> bool {
|
||||||
let origin_str = match origin.to_str() {
|
let origin_str = match origin.to_str() {
|
||||||
Ok(value) => value,
|
Ok(value) => value,
|
||||||
Err(_) => return false,
|
Err(_) => return false,
|
||||||
@@ -1079,14 +1143,17 @@ fn is_local_origin(origin: &header::HeaderValue) -> bool {
|
|||||||
None => return false,
|
None => return false,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Always allow localhost
|
||||||
if host == "localhost" {
|
if host == "localhost" {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if host == "vicrodh.github.io" || host == "control.qbz.lol" || host == "www.control.qbz.lol" {
|
// Check against configured allowed origins
|
||||||
|
if allowed_origins.iter().any(|o| o == host) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Allow local network IPs
|
||||||
match host.parse::<IpAddr>() {
|
match host.parse::<IpAddr>() {
|
||||||
Ok(ip) => is_local_addr(ip),
|
Ok(ip) => is_local_addr(ip),
|
||||||
Err(_) => false,
|
Err(_) => false,
|
||||||
|
|||||||
@@ -98,4 +98,6 @@ pub use legal_settings::{
|
|||||||
pub use remote_control_settings::{
|
pub use remote_control_settings::{
|
||||||
RemoteControlSettings,
|
RemoteControlSettings,
|
||||||
RemoteControlSettingsState,
|
RemoteControlSettingsState,
|
||||||
|
AllowedOrigin,
|
||||||
|
AllowedOriginsState,
|
||||||
};
|
};
|
||||||
@@ -24,7 +24,7 @@ impl Default for RemoteControlSettings {
|
|||||||
Self {
|
Self {
|
||||||
enabled: false,
|
enabled: false,
|
||||||
port: 8182,
|
port: 8182,
|
||||||
secure: false,
|
secure: true, // HTTPS by default for security
|
||||||
token: String::new(),
|
token: String::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -50,9 +50,9 @@ impl RemoteControlSettingsStore {
|
|||||||
conn.execute_batch(
|
conn.execute_batch(
|
||||||
"CREATE TABLE IF NOT EXISTS remote_control_settings (
|
"CREATE TABLE IF NOT EXISTS remote_control_settings (
|
||||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||||
enabled INTEGER NOT NULL DEFAULT 1,
|
enabled INTEGER NOT NULL DEFAULT 0,
|
||||||
port INTEGER NOT NULL DEFAULT 8182,
|
port INTEGER NOT NULL DEFAULT 8182,
|
||||||
secure INTEGER NOT NULL DEFAULT 0,
|
secure INTEGER NOT NULL DEFAULT 1,
|
||||||
token TEXT NOT NULL DEFAULT ''
|
token TEXT NOT NULL DEFAULT ''
|
||||||
);"
|
);"
|
||||||
).map_err(|e| format!("Failed to create remote control settings table: {}", e))?;
|
).map_err(|e| format!("Failed to create remote control settings table: {}", e))?;
|
||||||
@@ -224,3 +224,196 @@ fn ensure_secure_column(conn: &Connection) -> Result<(), String> {
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Allowed Origins for CORS
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// Default allowed origins for the PWA
|
||||||
|
const DEFAULT_ALLOWED_ORIGINS: &[&str] = &[
|
||||||
|
"vicrodh.github.io",
|
||||||
|
"control.qbz.lol",
|
||||||
|
"www.control.qbz.lol",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Allowed origin entry
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct AllowedOrigin {
|
||||||
|
pub id: i64,
|
||||||
|
pub origin: String,
|
||||||
|
pub is_default: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Store for allowed CORS origins
|
||||||
|
pub struct AllowedOriginsStore {
|
||||||
|
conn: Connection,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AllowedOriginsStore {
|
||||||
|
pub fn new() -> Result<Self, String> {
|
||||||
|
let data_dir = dirs::data_dir()
|
||||||
|
.ok_or("Could not determine data directory")?
|
||||||
|
.join("qbz");
|
||||||
|
|
||||||
|
std::fs::create_dir_all(&data_dir)
|
||||||
|
.map_err(|e| format!("Failed to create data directory: {}", e))?;
|
||||||
|
|
||||||
|
let db_path = data_dir.join("remote_control_settings.db");
|
||||||
|
let conn = Connection::open(&db_path)
|
||||||
|
.map_err(|e| format!("Failed to open allowed origins database: {}", e))?;
|
||||||
|
|
||||||
|
// Create allowed_origins table
|
||||||
|
conn.execute_batch(
|
||||||
|
"CREATE TABLE IF NOT EXISTS allowed_origins (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
origin TEXT NOT NULL UNIQUE,
|
||||||
|
is_default INTEGER NOT NULL DEFAULT 0
|
||||||
|
);"
|
||||||
|
).map_err(|e| format!("Failed to create allowed_origins table: {}", e))?;
|
||||||
|
|
||||||
|
// Insert default origins if table is empty
|
||||||
|
let count: i64 = conn.query_row(
|
||||||
|
"SELECT COUNT(*) FROM allowed_origins",
|
||||||
|
[],
|
||||||
|
|row| row.get(0)
|
||||||
|
).unwrap_or(0);
|
||||||
|
|
||||||
|
if count == 0 {
|
||||||
|
for origin in DEFAULT_ALLOWED_ORIGINS {
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR IGNORE INTO allowed_origins (origin, is_default) VALUES (?1, 1)",
|
||||||
|
params![origin],
|
||||||
|
).ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self { conn })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get all allowed origins
|
||||||
|
pub fn get_origins(&self) -> Result<Vec<AllowedOrigin>, String> {
|
||||||
|
let mut stmt = self.conn
|
||||||
|
.prepare("SELECT id, origin, is_default FROM allowed_origins ORDER BY is_default DESC, origin ASC")
|
||||||
|
.map_err(|e| format!("Failed to prepare query: {}", e))?;
|
||||||
|
|
||||||
|
let origins = stmt.query_map([], |row| {
|
||||||
|
Ok(AllowedOrigin {
|
||||||
|
id: row.get(0)?,
|
||||||
|
origin: row.get(1)?,
|
||||||
|
is_default: row.get::<_, i32>(2)? != 0,
|
||||||
|
})
|
||||||
|
}).map_err(|e| format!("Failed to query origins: {}", e))?;
|
||||||
|
|
||||||
|
origins.collect::<Result<Vec<_>, _>>()
|
||||||
|
.map_err(|e| format!("Failed to collect origins: {}", e))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if an origin is allowed
|
||||||
|
pub fn is_origin_allowed(&self, origin: &str) -> bool {
|
||||||
|
self.conn.query_row(
|
||||||
|
"SELECT 1 FROM allowed_origins WHERE origin = ?1",
|
||||||
|
params![origin],
|
||||||
|
|_| Ok(())
|
||||||
|
).is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a new allowed origin
|
||||||
|
pub fn add_origin(&self, origin: &str) -> Result<AllowedOrigin, String> {
|
||||||
|
// Normalize origin (lowercase, trim)
|
||||||
|
let normalized = origin.trim().to_lowercase();
|
||||||
|
|
||||||
|
if normalized.is_empty() {
|
||||||
|
return Err("Origin cannot be empty".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
self.conn.execute(
|
||||||
|
"INSERT INTO allowed_origins (origin, is_default) VALUES (?1, 0)",
|
||||||
|
params![normalized],
|
||||||
|
).map_err(|e| {
|
||||||
|
if e.to_string().contains("UNIQUE constraint") {
|
||||||
|
"Origin already exists".to_string()
|
||||||
|
} else {
|
||||||
|
format!("Failed to add origin: {}", e)
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let id = self.conn.last_insert_rowid();
|
||||||
|
Ok(AllowedOrigin {
|
||||||
|
id,
|
||||||
|
origin: normalized,
|
||||||
|
is_default: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove an allowed origin by ID
|
||||||
|
pub fn remove_origin(&self, id: i64) -> Result<(), String> {
|
||||||
|
let affected = self.conn.execute(
|
||||||
|
"DELETE FROM allowed_origins WHERE id = ?1",
|
||||||
|
params![id],
|
||||||
|
).map_err(|e| format!("Failed to remove origin: {}", e))?;
|
||||||
|
|
||||||
|
if affected == 0 {
|
||||||
|
return Err("Origin not found".to_string());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restore default origins (adds missing defaults back)
|
||||||
|
pub fn restore_defaults(&self) -> Result<(), String> {
|
||||||
|
for origin in DEFAULT_ALLOWED_ORIGINS {
|
||||||
|
self.conn.execute(
|
||||||
|
"INSERT OR IGNORE INTO allowed_origins (origin, is_default) VALUES (?1, 1)",
|
||||||
|
params![origin],
|
||||||
|
).ok();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Global state wrapper for thread-safe access to allowed origins
|
||||||
|
pub struct AllowedOriginsState {
|
||||||
|
store: Arc<Mutex<AllowedOriginsStore>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AllowedOriginsState {
|
||||||
|
pub fn new() -> Result<Self, String> {
|
||||||
|
Ok(Self {
|
||||||
|
store: Arc::new(Mutex::new(AllowedOriginsStore::new()?)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_origins(&self) -> Result<Vec<AllowedOrigin>, String> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|e| format!("Lock error: {}", e))?
|
||||||
|
.get_origins()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_origin_allowed(&self, origin: &str) -> bool {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map(|s| s.is_origin_allowed(origin))
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_origin(&self, origin: &str) -> Result<AllowedOrigin, String> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|e| format!("Lock error: {}", e))?
|
||||||
|
.add_origin(origin)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_origin(&self, id: i64) -> Result<(), String> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|e| format!("Lock error: {}", e))?
|
||||||
|
.remove_origin(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn restore_defaults(&self) -> Result<(), String> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|e| format!("Lock error: {}", e))?
|
||||||
|
.restore_defaults()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,23 +1,32 @@
|
|||||||
//! Secure credential storage with fallback
|
//! Secure credential storage with fallback
|
||||||
//!
|
//!
|
||||||
//! Tries system keyring first, falls back to file-based storage:
|
//! Tries system keyring first, falls back to encrypted file storage:
|
||||||
//! - Linux: Secret Service (GNOME Keyring, KWallet via D-Bus)
|
//! - Linux: Secret Service (GNOME Keyring, KWallet via D-Bus)
|
||||||
//! - macOS: Keychain
|
//! - macOS: Keychain
|
||||||
//! - Windows: Credential Manager
|
//! - Windows: Credential Manager
|
||||||
//! - Fallback: Obfuscated file in config directory
|
//! - Fallback: AES-256-GCM encrypted file in config directory
|
||||||
|
|
||||||
|
use aes_gcm::{
|
||||||
|
aead::{Aead, KeyInit},
|
||||||
|
Aes256Gcm, Nonce,
|
||||||
|
};
|
||||||
use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
|
use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
|
||||||
use keyring::Entry;
|
use keyring::Entry;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
const SERVICE_NAME: &str = "qbz";
|
const SERVICE_NAME: &str = "qbz";
|
||||||
const QOBUZ_CREDENTIALS_KEY: &str = "qobuz-credentials";
|
const QOBUZ_CREDENTIALS_KEY: &str = "qobuz-credentials";
|
||||||
const FALLBACK_FILE_NAME: &str = ".qbz-auth";
|
const FALLBACK_FILE_NAME: &str = ".qbz-auth";
|
||||||
|
const LEGACY_FALLBACK_FILE_NAME: &str = ".qbz-auth.legacy";
|
||||||
|
|
||||||
// Simple XOR key for obfuscation (not encryption, just to avoid plain text)
|
// Salt for key derivation (app-specific, not secret but adds uniqueness)
|
||||||
const OBFUSCATION_KEY: &[u8] = b"QbzNixAudiophile2024";
|
const KEY_DERIVATION_SALT: &[u8] = b"QbzNixCredentialEncryption2024";
|
||||||
|
|
||||||
|
// Legacy XOR key for migration (only used for reading old format)
|
||||||
|
const LEGACY_OBFUSCATION_KEY: &[u8] = b"QbzNixAudiophile2024";
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct QobuzCredentials {
|
pub struct QobuzCredentials {
|
||||||
@@ -25,20 +34,151 @@ pub struct QobuzCredentials {
|
|||||||
pub password: String,
|
pub password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Encrypted data format stored in file
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct EncryptedCredentials {
|
||||||
|
/// Version for future format changes
|
||||||
|
version: u8,
|
||||||
|
/// Base64-encoded nonce (12 bytes for AES-GCM)
|
||||||
|
nonce: String,
|
||||||
|
/// Base64-encoded ciphertext
|
||||||
|
ciphertext: String,
|
||||||
|
}
|
||||||
|
|
||||||
/// Get the fallback credentials file path
|
/// Get the fallback credentials file path
|
||||||
fn get_fallback_path() -> Option<PathBuf> {
|
fn get_fallback_path() -> Option<PathBuf> {
|
||||||
dirs::config_dir().map(|p| p.join("qbz").join(FALLBACK_FILE_NAME))
|
dirs::config_dir().map(|p| p.join("qbz").join(FALLBACK_FILE_NAME))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Simple XOR obfuscation (not secure, but avoids plain text)
|
/// Get the legacy fallback file path (for migration)
|
||||||
fn obfuscate(data: &[u8]) -> Vec<u8> {
|
fn get_legacy_fallback_path() -> Option<PathBuf> {
|
||||||
|
dirs::config_dir().map(|p| p.join("qbz").join(LEGACY_FALLBACK_FILE_NAME))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get machine-specific identifier for key derivation
|
||||||
|
fn get_machine_id() -> Vec<u8> {
|
||||||
|
// Try /etc/machine-id first (Linux)
|
||||||
|
if let Ok(id) = fs::read_to_string("/etc/machine-id") {
|
||||||
|
return id.trim().as_bytes().to_vec();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to hostname
|
||||||
|
if let Ok(hostname) = std::env::var("HOSTNAME") {
|
||||||
|
return hostname.as_bytes().to_vec();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Last resort: use username
|
||||||
|
if let Ok(user) = std::env::var("USER") {
|
||||||
|
return user.as_bytes().to_vec();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ultimate fallback (not great but better than nothing)
|
||||||
|
b"qbz-default-machine".to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Derive encryption key from machine ID
|
||||||
|
fn derive_key() -> [u8; 32] {
|
||||||
|
let machine_id = get_machine_id();
|
||||||
|
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
hasher.update(KEY_DERIVATION_SALT);
|
||||||
|
hasher.update(&machine_id);
|
||||||
|
hasher.update(KEY_DERIVATION_SALT); // Double salt for extra mixing
|
||||||
|
|
||||||
|
let result = hasher.finalize();
|
||||||
|
let mut key = [0u8; 32];
|
||||||
|
key.copy_from_slice(&result);
|
||||||
|
key
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encrypt credentials using AES-256-GCM
|
||||||
|
fn encrypt_credentials(credentials: &QobuzCredentials) -> Result<String, String> {
|
||||||
|
let key = derive_key();
|
||||||
|
let cipher = Aes256Gcm::new_from_slice(&key)
|
||||||
|
.map_err(|e| format!("Failed to create cipher: {}", e))?;
|
||||||
|
|
||||||
|
// Generate random nonce
|
||||||
|
let nonce_bytes: [u8; 12] = aes_gcm::aead::generic_array::GenericArray::from(
|
||||||
|
rand::random::<[u8; 12]>()
|
||||||
|
).into();
|
||||||
|
let nonce = Nonce::from_slice(&nonce_bytes);
|
||||||
|
|
||||||
|
let json = serde_json::to_string(credentials)
|
||||||
|
.map_err(|e| format!("Failed to serialize credentials: {}", e))?;
|
||||||
|
|
||||||
|
let ciphertext = cipher.encrypt(nonce, json.as_bytes())
|
||||||
|
.map_err(|e| format!("Encryption failed: {}", e))?;
|
||||||
|
|
||||||
|
let encrypted = EncryptedCredentials {
|
||||||
|
version: 1,
|
||||||
|
nonce: BASE64.encode(nonce_bytes),
|
||||||
|
ciphertext: BASE64.encode(ciphertext),
|
||||||
|
};
|
||||||
|
|
||||||
|
serde_json::to_string(&encrypted)
|
||||||
|
.map_err(|e| format!("Failed to serialize encrypted data: {}", e))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decrypt credentials using AES-256-GCM
|
||||||
|
fn decrypt_credentials(encrypted_json: &str) -> Result<QobuzCredentials, String> {
|
||||||
|
let encrypted: EncryptedCredentials = serde_json::from_str(encrypted_json)
|
||||||
|
.map_err(|e| format!("Failed to parse encrypted data: {}", e))?;
|
||||||
|
|
||||||
|
if encrypted.version != 1 {
|
||||||
|
return Err(format!("Unsupported encryption version: {}", encrypted.version));
|
||||||
|
}
|
||||||
|
|
||||||
|
let key = derive_key();
|
||||||
|
let cipher = Aes256Gcm::new_from_slice(&key)
|
||||||
|
.map_err(|e| format!("Failed to create cipher: {}", e))?;
|
||||||
|
|
||||||
|
let nonce_bytes = BASE64.decode(&encrypted.nonce)
|
||||||
|
.map_err(|e| format!("Failed to decode nonce: {}", e))?;
|
||||||
|
let nonce = Nonce::from_slice(&nonce_bytes);
|
||||||
|
|
||||||
|
let ciphertext = BASE64.decode(&encrypted.ciphertext)
|
||||||
|
.map_err(|e| format!("Failed to decode ciphertext: {}", e))?;
|
||||||
|
|
||||||
|
let plaintext = cipher.decrypt(nonce, ciphertext.as_ref())
|
||||||
|
.map_err(|_| "Decryption failed (wrong key or corrupted data)".to_string())?;
|
||||||
|
|
||||||
|
let json = String::from_utf8(plaintext)
|
||||||
|
.map_err(|e| format!("Failed to decode decrypted data: {}", e))?;
|
||||||
|
|
||||||
|
serde_json::from_str(&json)
|
||||||
|
.map_err(|e| format!("Failed to parse credentials: {}", e))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Legacy XOR deobfuscation (for migration only)
|
||||||
|
fn legacy_deobfuscate(data: &[u8]) -> Vec<u8> {
|
||||||
data.iter()
|
data.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.map(|(i, b)| b ^ OBFUSCATION_KEY[i % OBFUSCATION_KEY.len()])
|
.map(|(i, b)| b ^ LEGACY_OBFUSCATION_KEY[i % LEGACY_OBFUSCATION_KEY.len()])
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Save credentials to fallback file
|
/// Try to load credentials from legacy XOR format
|
||||||
|
fn load_legacy_credentials(path: &PathBuf) -> Result<Option<QobuzCredentials>, String> {
|
||||||
|
if !path.exists() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
let encoded = fs::read_to_string(path)
|
||||||
|
.map_err(|e| format!("Failed to read legacy file: {}", e))?;
|
||||||
|
|
||||||
|
let obfuscated = BASE64.decode(encoded.trim())
|
||||||
|
.map_err(|e| format!("Failed to decode legacy data: {}", e))?;
|
||||||
|
|
||||||
|
let json_bytes = legacy_deobfuscate(&obfuscated);
|
||||||
|
let json = String::from_utf8(json_bytes)
|
||||||
|
.map_err(|e| format!("Failed to decode legacy credentials: {}", e))?;
|
||||||
|
|
||||||
|
serde_json::from_str(&json)
|
||||||
|
.map_err(|e| format!("Failed to parse legacy credentials: {}", e))
|
||||||
|
.map(Some)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Save credentials to fallback file (AES-256-GCM encrypted)
|
||||||
fn save_to_fallback(credentials: &QobuzCredentials) -> Result<(), String> {
|
fn save_to_fallback(credentials: &QobuzCredentials) -> Result<(), String> {
|
||||||
let path = get_fallback_path().ok_or("Could not determine config directory")?;
|
let path = get_fallback_path().ok_or("Could not determine config directory")?;
|
||||||
|
|
||||||
@@ -48,16 +188,12 @@ fn save_to_fallback(credentials: &QobuzCredentials) -> Result<(), String> {
|
|||||||
.map_err(|e| format!("Failed to create config directory: {}", e))?;
|
.map_err(|e| format!("Failed to create config directory: {}", e))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let json = serde_json::to_string(credentials)
|
let encrypted = encrypt_credentials(credentials)?;
|
||||||
.map_err(|e| format!("Failed to serialize credentials: {}", e))?;
|
|
||||||
|
|
||||||
let obfuscated = obfuscate(json.as_bytes());
|
fs::write(&path, encrypted)
|
||||||
let encoded = BASE64.encode(&obfuscated);
|
|
||||||
|
|
||||||
fs::write(&path, encoded)
|
|
||||||
.map_err(|e| format!("Failed to write credentials file: {}", e))?;
|
.map_err(|e| format!("Failed to write credentials file: {}", e))?;
|
||||||
|
|
||||||
log::info!("Credentials saved to fallback file");
|
log::info!("Credentials saved to encrypted fallback file");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,24 +205,81 @@ fn load_from_fallback() -> Result<Option<QobuzCredentials>, String> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if !path.exists() {
|
if !path.exists() {
|
||||||
|
// Check for legacy file and migrate if found
|
||||||
|
if let Some(legacy_path) = get_legacy_fallback_path() {
|
||||||
|
if legacy_path.exists() {
|
||||||
|
log::info!("Found legacy credentials file, attempting migration...");
|
||||||
|
if let Ok(Some(creds)) = load_legacy_credentials(&legacy_path) {
|
||||||
|
// Save in new format
|
||||||
|
if save_to_fallback(&creds).is_ok() {
|
||||||
|
// Remove legacy file
|
||||||
|
let _ = fs::remove_file(&legacy_path);
|
||||||
|
log::info!("Successfully migrated credentials to new encrypted format");
|
||||||
|
return Ok(Some(creds));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also check if the current file is in legacy format (migration from old .qbz-auth)
|
||||||
|
let current_path = get_fallback_path();
|
||||||
|
if let Some(ref p) = current_path {
|
||||||
|
if p.exists() {
|
||||||
|
// Try reading as JSON first (new format)
|
||||||
|
if let Ok(content) = fs::read_to_string(p) {
|
||||||
|
if content.trim().starts_with('{') && content.contains("\"version\"") {
|
||||||
|
// It's the new format, will be handled below
|
||||||
|
} else {
|
||||||
|
// Might be legacy format
|
||||||
|
log::info!("Attempting to read legacy format from current file...");
|
||||||
|
if let Ok(Some(creds)) = load_legacy_credentials(p) {
|
||||||
|
// Save in new format
|
||||||
|
if save_to_fallback(&creds).is_ok() {
|
||||||
|
log::info!("Successfully migrated credentials to new encrypted format");
|
||||||
|
return Ok(Some(creds));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
|
|
||||||
let encoded = fs::read_to_string(&path)
|
let content = fs::read_to_string(&path)
|
||||||
.map_err(|e| format!("Failed to read credentials file: {}", e))?;
|
.map_err(|e| format!("Failed to read credentials file: {}", e))?;
|
||||||
|
|
||||||
let obfuscated = BASE64.decode(encoded.trim())
|
// Check if it's the new format or legacy
|
||||||
.map_err(|e| format!("Failed to decode credentials: {}", e))?;
|
if content.trim().starts_with('{') && content.contains("\"version\"") {
|
||||||
|
// New encrypted format
|
||||||
let json_bytes = obfuscate(&obfuscated);
|
match decrypt_credentials(&content) {
|
||||||
let json = String::from_utf8(json_bytes)
|
Ok(creds) => {
|
||||||
.map_err(|e| format!("Failed to decode credentials: {}", e))?;
|
log::info!("Credentials loaded from encrypted fallback file");
|
||||||
|
Ok(Some(creds))
|
||||||
let credentials: QobuzCredentials = serde_json::from_str(&json)
|
}
|
||||||
.map_err(|e| format!("Failed to parse credentials: {}", e))?;
|
Err(e) => {
|
||||||
|
log::warn!("Failed to decrypt credentials: {}", e);
|
||||||
log::info!("Credentials loaded from fallback file");
|
// Try legacy format as fallback
|
||||||
Ok(Some(credentials))
|
if let Ok(Some(creds)) = load_legacy_credentials(&path) {
|
||||||
|
log::info!("Loaded from legacy format, will re-encrypt on next save");
|
||||||
|
return Ok(Some(creds));
|
||||||
|
}
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Legacy format - try to load and migrate
|
||||||
|
log::info!("Found legacy format, migrating...");
|
||||||
|
if let Ok(Some(creds)) = load_legacy_credentials(&path) {
|
||||||
|
// Save in new format
|
||||||
|
if save_to_fallback(&creds).is_ok() {
|
||||||
|
log::info!("Successfully migrated credentials to new encrypted format");
|
||||||
|
}
|
||||||
|
return Ok(Some(creds));
|
||||||
|
}
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Clear fallback credentials file
|
/// Clear fallback credentials file
|
||||||
@@ -98,6 +291,12 @@ fn clear_fallback() -> Result<(), String> {
|
|||||||
log::info!("Fallback credentials file removed");
|
log::info!("Fallback credentials file removed");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Also clear legacy file if exists
|
||||||
|
if let Some(legacy_path) = get_legacy_fallback_path() {
|
||||||
|
if legacy_path.exists() {
|
||||||
|
let _ = fs::remove_file(&legacy_path);
|
||||||
|
}
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,7 +314,7 @@ pub fn save_qobuz_credentials(email: &str, password: &str) -> Result<(), String>
|
|||||||
password: password.to_string(),
|
password: password.to_string(),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Always save to file first (more reliable, especially in dev)
|
// Always save to encrypted file first (more reliable, especially in dev)
|
||||||
save_to_fallback(&credentials)?;
|
save_to_fallback(&credentials)?;
|
||||||
|
|
||||||
// Also try keyring as secondary (nice to have for desktop integration)
|
// Also try keyring as secondary (nice to have for desktop integration)
|
||||||
@@ -217,6 +416,20 @@ pub fn clear_qobuz_credentials() -> Result<(), String> {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_encryption_roundtrip() {
|
||||||
|
let credentials = QobuzCredentials {
|
||||||
|
email: "test@example.com".to_string(),
|
||||||
|
password: "testpass123".to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let encrypted = encrypt_credentials(&credentials).expect("Encryption failed");
|
||||||
|
let decrypted = decrypt_credentials(&encrypted).expect("Decryption failed");
|
||||||
|
|
||||||
|
assert_eq!(decrypted.email, credentials.email);
|
||||||
|
assert_eq!(decrypted.password, credentials.password);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_credentials_roundtrip() {
|
fn test_credentials_roundtrip() {
|
||||||
// Note: This test requires a working keyring service
|
// Note: This test requires a working keyring service
|
||||||
|
|||||||
@@ -209,6 +209,9 @@ pub fn run() {
|
|||||||
// Initialize remote control settings state
|
// Initialize remote control settings state
|
||||||
let remote_control_settings_state = config::remote_control_settings::RemoteControlSettingsState::new()
|
let remote_control_settings_state = config::remote_control_settings::RemoteControlSettingsState::new()
|
||||||
.expect("Failed to initialize remote control settings");
|
.expect("Failed to initialize remote control settings");
|
||||||
|
// Initialize allowed origins state for CORS
|
||||||
|
let allowed_origins_state = config::remote_control_settings::AllowedOriginsState::new()
|
||||||
|
.expect("Failed to initialize allowed origins");
|
||||||
// Initialize API server state for remote control
|
// Initialize API server state for remote control
|
||||||
let api_server_state = api_server::ApiServerState::new();
|
let api_server_state = api_server::ApiServerState::new();
|
||||||
// Initialize legal settings state (ToS acceptance persistence)
|
// Initialize legal settings state (ToS acceptance persistence)
|
||||||
@@ -496,6 +499,7 @@ pub fn run() {
|
|||||||
.manage(favorites_cache_state)
|
.manage(favorites_cache_state)
|
||||||
.manage(tray_settings_state)
|
.manage(tray_settings_state)
|
||||||
.manage(remote_control_settings_state)
|
.manage(remote_control_settings_state)
|
||||||
|
.manage(allowed_origins_state)
|
||||||
.manage(api_server_state)
|
.manage(api_server_state)
|
||||||
.manage(legal_settings_state)
|
.manage(legal_settings_state)
|
||||||
.manage(updates_state)
|
.manage(updates_state)
|
||||||
@@ -913,6 +917,10 @@ pub fn run() {
|
|||||||
api_server::remote_control_set_secure,
|
api_server::remote_control_set_secure,
|
||||||
api_server::remote_control_get_pairing_qr,
|
api_server::remote_control_get_pairing_qr,
|
||||||
api_server::remote_control_regenerate_token,
|
api_server::remote_control_regenerate_token,
|
||||||
|
api_server::remote_control_get_allowed_origins,
|
||||||
|
api_server::remote_control_add_allowed_origin,
|
||||||
|
api_server::remote_control_remove_allowed_origin,
|
||||||
|
api_server::remote_control_restore_default_origins,
|
||||||
// Legal settings commands
|
// Legal settings commands
|
||||||
config::legal_settings::get_legal_settings,
|
config::legal_settings::get_legal_settings,
|
||||||
config::legal_settings::get_qobuz_tos_accepted,
|
config::legal_settings::get_qobuz_tos_accepted,
|
||||||
|
|||||||
Reference in new issue
Block a user