From 58f1957a0562fa5ed9e98b40151b4340d9c266c3 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 15 Feb 2026 04:02:34 -0600 Subject: [PATCH] feat(runtime): implement phased V2 login commands for runtime contract Add V2 commands that implement the ADR Runtime Session Contract: - v2_init_client: Phase 1 - init client only (bundle tokens) - v2_auto_login: Phase 2 - auto-login with blocking V2 auth - v2_manual_login: Manual login with blocking V2 auth This allows frontend to control ToS check between init and auth: 1. v2_init_client() -> InitializedNoAuth 2. activate_user_session() -> restore session 3. loadTosAcceptance() -> check ToS 4. v2_auto_login() or v2_manual_login() -> Ready V2 CoreBridge auth is now REQUIRED per ADR - login fails if V2 fails. Migrate LoginView.svelte to use new V2 commands: - Replace init_client with v2_init_client - Replace auto_login with v2_auto_login - Replace login with v2_manual_login Add i18n keys for V2 auth errors in all 4 locales. --- src-tauri/src/commands_v2.rs | 289 +++++++++++++++++++++- src-tauri/src/lib.rs | 3 + src/lib/components/views/LoginView.svelte | 27 +- src/lib/i18n/locales/de.json | 4 +- src/lib/i18n/locales/en.json | 4 +- src/lib/i18n/locales/es.json | 4 +- src/lib/i18n/locales/fr.json | 4 +- 7 files changed, 317 insertions(+), 18 deletions(-) diff --git a/src-tauri/src/commands_v2.rs b/src-tauri/src/commands_v2.rs index 915139a82..00ceddd03 100644 --- a/src-tauri/src/commands_v2.rs +++ b/src-tauri/src/commands_v2.rs @@ -18,7 +18,7 @@ use crate::config::audio_settings::{AudioSettings, AudioSettingsState}; use crate::core_bridge::CoreBridgeState; use crate::offline_cache::OfflineCacheState; use crate::queue::QueueManager; -use crate::runtime::{RuntimeManagerState, RuntimeStatus, RuntimeError, RuntimeEvent, RuntimeState, DegradedReason}; +use crate::runtime::{RuntimeManagerState, RuntimeStatus, RuntimeError, RuntimeEvent, DegradedReason}; use crate::AppState; // ==================== Helper Functions ==================== @@ -218,11 +218,290 @@ pub async fn runtime_bootstrap( Ok(status) } -/// Emit a runtime event (internal helper) -fn emit_runtime_event(app: &tauri::AppHandle, event: RuntimeEvent) { - if let Err(e) = app.emit("runtime:event", &event) { - log::warn!("[Runtime] Failed to emit event: {}", e); +/// Initialize the API client only (Phase 1 of runtime initialization) +/// +/// This command: +/// 1. Extracts bundle tokens from Qobuz +/// 2. Sets RuntimeManager state to InitializedNoAuth +/// +/// Call this first, then let frontend handle ToS check before calling v2_auto_login. +#[tauri::command] +pub async fn v2_init_client( + app: tauri::AppHandle, + runtime: State<'_, RuntimeManagerState>, + app_state: State<'_, AppState>, +) -> Result { + let manager = runtime.manager(); + + log::info!("[V2] v2_init_client starting..."); + + // Initialize API client (bundle tokens) + { + let client = app_state.client.read().await; + match client.init().await { + Ok(_) => { + log::info!("[V2] API client initialized (bundle tokens extracted)"); + manager.set_client_initialized(true).await; + let _ = app.emit("runtime:event", RuntimeEvent::RuntimeInitialized); + } + Err(e) => { + let reason = DegradedReason::BundleExtractionFailed(e.to_string()); + log::error!("[V2] Bundle extraction failed: {}", e); + manager.set_degraded(reason.clone()).await; + let _ = app.emit("runtime:event", RuntimeEvent::RuntimeDegraded { reason: reason.clone() }); + return Err(RuntimeError::RuntimeDegraded(reason)); + } + } } + + Ok(manager.get_status().await) +} + +/// Auto-login response matching legacy LoginResponse +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct V2LoginResponse { + pub success: bool, + pub user_name: Option, + pub user_id: Option, + pub subscription: Option, + pub subscription_valid_until: Option, + pub error: Option, + pub error_code: Option, +} + +/// Auto-login using saved credentials (Phase 2 of runtime initialization) +/// +/// This command: +/// 1. Loads saved credentials from keyring +/// 2. Authenticates with legacy client +/// 3. Authenticates with CoreBridge/V2 (BLOCKING - required per ADR) +/// 4. Updates RuntimeManager state +/// +/// V2 auth is REQUIRED - if it fails, the whole login fails. +#[tauri::command] +pub async fn v2_auto_login( + app: tauri::AppHandle, + runtime: State<'_, RuntimeManagerState>, + app_state: State<'_, AppState>, + core_bridge: State<'_, CoreBridgeState>, +) -> Result { + let manager = runtime.manager(); + + log::info!("[V2] v2_auto_login starting..."); + + // Load saved credentials + let creds = match crate::credentials::load_qobuz_credentials() { + Ok(Some(c)) => c, + Ok(None) => { + return Ok(V2LoginResponse { + success: false, + user_name: None, + user_id: None, + subscription: None, + subscription_valid_until: None, + error: Some("No saved credentials".to_string()), + error_code: Some("no_credentials".to_string()), + }); + } + Err(e) => { + return Ok(V2LoginResponse { + success: false, + user_name: None, + user_id: None, + subscription: None, + subscription_valid_until: None, + error: Some(e), + error_code: Some("credentials_error".to_string()), + }); + } + }; + + // Legacy auth + let client = app_state.client.read().await; + let session = match client.login(&creds.email, &creds.password).await { + Ok(s) => s, + Err(e) => { + let error_code = if matches!(e, crate::api::error::ApiError::IneligibleUser) { + Some("ineligible_user".to_string()) + } else { + None + }; + return Ok(V2LoginResponse { + success: false, + user_name: None, + user_id: None, + subscription: None, + subscription_valid_until: None, + error: Some(e.to_string()), + error_code, + }); + } + }; + drop(client); + + log::info!("[V2] Legacy auth successful for user {}", session.user_id); + manager.set_legacy_auth(true, Some(session.user_id)).await; + let _ = app.emit("runtime:event", RuntimeEvent::AuthChanged { + logged_in: true, + user_id: Some(session.user_id), + }); + + // V2 CoreBridge auth - REQUIRED per ADR Runtime Session Contract + if let Some(bridge) = core_bridge.try_get().await { + match bridge.login(&creds.email, &creds.password).await { + Ok(_) => { + log::info!("[V2] CoreBridge auth successful"); + manager.set_corebridge_auth(true).await; + } + Err(e) => { + log::error!("[V2] CoreBridge auth failed: {}", e); + let _ = app.emit("runtime:event", RuntimeEvent::CoreBridgeAuthFailed { + error: e.to_string(), + }); + // V2 auth failed - return failure per ADR + return Ok(V2LoginResponse { + success: false, + user_name: Some(session.display_name), + user_id: Some(session.user_id), + subscription: Some(session.subscription_label), + subscription_valid_until: session.subscription_valid_until, + error: Some(format!("V2 authentication failed: {}", e)), + error_code: Some("v2_auth_failed".to_string()), + }); + } + } + } else { + log::error!("[V2] CoreBridge not initialized - cannot complete auth"); + return Ok(V2LoginResponse { + success: false, + user_name: Some(session.display_name), + user_id: Some(session.user_id), + subscription: Some(session.subscription_label), + subscription_valid_until: session.subscription_valid_until, + error: Some("V2 CoreBridge not initialized".to_string()), + error_code: Some("v2_not_initialized".to_string()), + }); + } + + // Emit ready event + let _ = app.emit("runtime:event", RuntimeEvent::RuntimeReady { + user_id: session.user_id, + }); + + Ok(V2LoginResponse { + success: true, + user_name: Some(session.display_name), + user_id: Some(session.user_id), + subscription: Some(session.subscription_label), + subscription_valid_until: session.subscription_valid_until, + error: None, + error_code: None, + }) +} + +/// Manual login with email and password (V2 - with blocking CoreBridge auth) +/// +/// This command: +/// 1. Authenticates with legacy client +/// 2. Authenticates with CoreBridge/V2 (BLOCKING - required per ADR) +/// 3. Updates RuntimeManager state +/// +/// V2 auth is REQUIRED - if it fails, the whole login fails. +#[tauri::command] +pub async fn v2_manual_login( + email: String, + password: String, + app: tauri::AppHandle, + runtime: State<'_, RuntimeManagerState>, + app_state: State<'_, AppState>, + core_bridge: State<'_, CoreBridgeState>, +) -> Result { + let manager = runtime.manager(); + + log::info!("[V2] v2_manual_login starting..."); + + // Legacy auth + let client = app_state.client.read().await; + let session = match client.login(&email, &password).await { + Ok(s) => s, + Err(e) => { + let error_code = if matches!(e, crate::api::error::ApiError::IneligibleUser) { + Some("ineligible_user".to_string()) + } else { + None + }; + return Ok(V2LoginResponse { + success: false, + user_name: None, + user_id: None, + subscription: None, + subscription_valid_until: None, + error: Some(e.to_string()), + error_code, + }); + } + }; + drop(client); + + log::info!("[V2] Legacy auth successful for user {}", session.user_id); + manager.set_legacy_auth(true, Some(session.user_id)).await; + let _ = app.emit("runtime:event", RuntimeEvent::AuthChanged { + logged_in: true, + user_id: Some(session.user_id), + }); + + // V2 CoreBridge auth - REQUIRED per ADR Runtime Session Contract + if let Some(bridge) = core_bridge.try_get().await { + match bridge.login(&email, &password).await { + Ok(_) => { + log::info!("[V2] CoreBridge auth successful"); + manager.set_corebridge_auth(true).await; + } + Err(e) => { + log::error!("[V2] CoreBridge auth failed: {}", e); + let _ = app.emit("runtime:event", RuntimeEvent::CoreBridgeAuthFailed { + error: e.to_string(), + }); + // V2 auth failed - return failure per ADR + return Ok(V2LoginResponse { + success: false, + user_name: Some(session.display_name), + user_id: Some(session.user_id), + subscription: Some(session.subscription_label), + subscription_valid_until: session.subscription_valid_until, + error: Some(format!("V2 authentication failed: {}", e)), + error_code: Some("v2_auth_failed".to_string()), + }); + } + } + } else { + log::error!("[V2] CoreBridge not initialized - cannot complete auth"); + return Ok(V2LoginResponse { + success: false, + user_name: Some(session.display_name), + user_id: Some(session.user_id), + subscription: Some(session.subscription_label), + subscription_valid_until: session.subscription_valid_until, + error: Some("V2 CoreBridge not initialized".to_string()), + error_code: Some("v2_not_initialized".to_string()), + }); + } + + // Emit ready event + let _ = app.emit("runtime:event", RuntimeEvent::RuntimeReady { + user_id: session.user_id, + }); + + Ok(V2LoginResponse { + success: true, + user_name: Some(session.display_name), + user_id: Some(session.user_id), + subscription: Some(session.subscription_label), + subscription_valid_until: session.subscription_valid_until, + error: None, + error_code: None, + }) } // ==================== Prefetch (V2) ==================== diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index e0cf817b9..a9c45bfa6 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1103,6 +1103,9 @@ pub fn run() { commands_v2::v2_is_logged_in, commands_v2::v2_login, commands_v2::v2_logout, + commands_v2::v2_init_client, + commands_v2::v2_auto_login, + commands_v2::v2_manual_login, // Queue (V2) commands_v2::v2_get_queue_state, commands_v2::v2_set_repeat_mode, diff --git a/src/lib/components/views/LoginView.svelte b/src/lib/components/views/LoginView.svelte index 41be16db6..5638ff5b9 100644 --- a/src/lib/components/views/LoginView.svelte +++ b/src/lib/components/views/LoginView.svelte @@ -64,8 +64,9 @@ } }, LOGIN_TIMEOUT_MS); - const result = await invoke('init_client'); - console.log('Client initialized:', result); + // Phase 1: Initialize client (V2 - extracts bundle tokens) + const initResult = await invoke<{ state: string; client_initialized: boolean }>('v2_init_client'); + console.log('[LoginView] v2_init_client result:', initResult); // Check if already logged in (in-memory session) const loggedIn = await invoke('is_logged_in'); @@ -110,6 +111,7 @@ initStatus = 'Loading preferences...'; await loadTosAcceptance(); + // Phase 2: Auto-login with V2 (blocking CoreBridge auth) if (hasSavedCreds && get(qobuzTosAccepted)) { initStatus = 'Logging in...'; const response = await invoke<{ @@ -120,11 +122,11 @@ subscription_valid_until?: string | null; error?: string; error_code?: string; - }>('auto_login'); + }>('v2_auto_login'); if (response.success) { clearTimeoutTimer(); - console.log('Auto-login successful'); + console.log('[LoginView] v2_auto_login successful'); onLoginSuccess({ userName: response.user_name || 'User', userId: response.user_id || 0, @@ -133,9 +135,13 @@ }); return; } else { - console.log('Auto-login failed:', response.error); + console.log('[LoginView] v2_auto_login failed:', response.error); if (response.error_code === 'ineligible_user') { error = $t('auth.ineligibleSubscription'); + } else if (response.error_code === 'v2_auth_failed') { + error = $t('auth.v2AuthFailed'); + } else if (response.error_code === 'v2_not_initialized') { + error = $t('auth.v2NotInitialized'); } // Don't show error, just fall through to manual login } @@ -183,6 +189,7 @@ error = null; try { + // V2 manual login with blocking CoreBridge auth const response = await invoke<{ success: boolean; user_name?: string; @@ -191,13 +198,11 @@ subscription_valid_until?: string | null; error?: string; error_code?: string; - }>('login', { email, password }); + }>('v2_manual_login', { email, password }); - console.log('Login response:', response); + console.log('[LoginView] v2_manual_login response:', response); if (response.success) { - // V2 CoreBridge is now authenticated automatically by the backend login command - // Save credentials if "Remember me" is checked if (rememberMe) { try { @@ -218,6 +223,10 @@ } else { if (response.error_code === 'ineligible_user') { error = $t('auth.ineligibleSubscription'); + } else if (response.error_code === 'v2_auth_failed') { + error = $t('auth.v2AuthFailed'); + } else if (response.error_code === 'v2_not_initialized') { + error = $t('auth.v2NotInitialized'); } else { error = response.error || 'Login failed'; } diff --git a/src/lib/i18n/locales/de.json b/src/lib/i18n/locales/de.json index dbb9190aa..84f174951 100644 --- a/src/lib/i18n/locales/de.json +++ b/src/lib/i18n/locales/de.json @@ -940,7 +940,9 @@ "loginError": "Anmeldung fehlgeschlagen. Bitte überprüfen Sie Ihre Anmeldedaten.", "welcomeBack": "Willkommen zurück", "rememberMe": "Angemeldet bleiben", - "ineligibleSubscription": "Keine aktive Abonnement. QBZ wird nur im Offline-Modus ausgeführt." + "ineligibleSubscription": "Keine aktive Abonnement. QBZ wird nur im Offline-Modus ausgeführt.", + "v2AuthFailed": "Authentifizierung mit Qobuz fehlgeschlagen. Bitte versuchen Sie es erneut.", + "v2NotInitialized": "Verbindung zu Qobuz konnte nicht hergestellt werden. Bitte starten Sie die App neu." }, "legal": { "brandingLineSuffix": "", diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index ff38f202e..0522d908d 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -998,7 +998,9 @@ "loginError": "Login failed. Please check your credentials.", "welcomeBack": "Welcome back", "rememberMe": "Remember me", - "ineligibleSubscription": "No active subscription. QBZ will run in offline mode only." + "ineligibleSubscription": "No active subscription. QBZ will run in offline mode only.", + "v2AuthFailed": "Authentication with Qobuz failed. Please try again.", + "v2NotInitialized": "Could not connect to Qobuz. Please restart the app." }, "legal": { "brandingLineSuffix": "", diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index 130b225b2..b220cba1d 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -998,7 +998,9 @@ "loginError": "Error al iniciar sesión. Verifica tus credenciales.", "welcomeBack": "Bienvenido de nuevo", "rememberMe": "Recordarme", - "ineligibleSubscription": "No hay una suscripción activa. QBZ solo funcionará en modo offline." + "ineligibleSubscription": "No hay una suscripción activa. QBZ solo funcionará en modo offline.", + "v2AuthFailed": "La autenticación con Qobuz falló. Por favor, inténtalo de nuevo.", + "v2NotInitialized": "No se pudo conectar con Qobuz. Por favor, reinicia la aplicación." }, "legal": { "brandingLineSuffix": "Esta aplicación usa la API de Qobuz™ pero no está certificada por Qobuz™.", diff --git a/src/lib/i18n/locales/fr.json b/src/lib/i18n/locales/fr.json index 49255f8d1..50a1f06df 100644 --- a/src/lib/i18n/locales/fr.json +++ b/src/lib/i18n/locales/fr.json @@ -940,7 +940,9 @@ "loginError": "Échec de la connexion. Veuillez vérifier vos identifiants.", "welcomeBack": "Bon retour", "rememberMe": "Se souvenir de moi", - "ineligibleSubscription": "Aucun abonnement actif. QBZ fonctionnera uniquement en mode hors ligne." + "ineligibleSubscription": "Aucun abonnement actif. QBZ fonctionnera uniquement en mode hors ligne.", + "v2AuthFailed": "L'authentification avec Qobuz a échoué. Veuillez réessayer.", + "v2NotInitialized": "Impossible de se connecter à Qobuz. Veuillez redémarrer l'application." }, "legal": { "brandingLineSuffix": "",