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.
This commit is contained in:
vicrodh committed 2026-02-15 04:02:34 -06:00
1 parent 854088c3de
commit 58f1957a05
7 files changed
+317 -18

No files matched your search

+284 -5
View File
@@ -18,7 +18,7 @@ use crate::config::audio_settings::{AudioSettings, AudioSettingsState};
use crate::core_bridge::CoreBridgeState; use crate::core_bridge::CoreBridgeState;
use crate::offline_cache::OfflineCacheState; use crate::offline_cache::OfflineCacheState;
use crate::queue::QueueManager; use crate::queue::QueueManager;
use crate::runtime::{RuntimeManagerState, RuntimeStatus, RuntimeError, RuntimeEvent, RuntimeState, DegradedReason}; use crate::runtime::{RuntimeManagerState, RuntimeStatus, RuntimeError, RuntimeEvent, DegradedReason};
use crate::AppState; use crate::AppState;
// ==================== Helper Functions ==================== // ==================== Helper Functions ====================
@@ -218,11 +218,290 @@ pub async fn runtime_bootstrap(
Ok(status) Ok(status)
} }
/// Emit a runtime event (internal helper) /// Initialize the API client only (Phase 1 of runtime initialization)
fn emit_runtime_event(app: &tauri::AppHandle, event: RuntimeEvent) { ///
if let Err(e) = app.emit("runtime:event", &event) { /// This command:
log::warn!("[Runtime] Failed to emit event: {}", e); /// 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<RuntimeStatus, RuntimeError> {
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<String>,
pub user_id: Option<u64>,
pub subscription: Option<String>,
pub subscription_valid_until: Option<String>,
pub error: Option<String>,
pub error_code: Option<String>,
}
/// 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<V2LoginResponse, String> {
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<V2LoginResponse, String> {
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) ==================== // ==================== Prefetch (V2) ====================
+3
View File
@@ -1103,6 +1103,9 @@ pub fn run() {
commands_v2::v2_is_logged_in, commands_v2::v2_is_logged_in,
commands_v2::v2_login, commands_v2::v2_login,
commands_v2::v2_logout, commands_v2::v2_logout,
commands_v2::v2_init_client,
commands_v2::v2_auto_login,
commands_v2::v2_manual_login,
// Queue (V2) // Queue (V2)
commands_v2::v2_get_queue_state, commands_v2::v2_get_queue_state,
commands_v2::v2_set_repeat_mode, commands_v2::v2_set_repeat_mode,
+18 -9
View File
@@ -64,8 +64,9 @@
} }
}, LOGIN_TIMEOUT_MS); }, LOGIN_TIMEOUT_MS);
const result = await invoke<boolean>('init_client'); // Phase 1: Initialize client (V2 - extracts bundle tokens)
console.log('Client initialized:', result); 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) // Check if already logged in (in-memory session)
const loggedIn = await invoke<boolean>('is_logged_in'); const loggedIn = await invoke<boolean>('is_logged_in');
@@ -110,6 +111,7 @@
initStatus = 'Loading preferences...'; initStatus = 'Loading preferences...';
await loadTosAcceptance(); await loadTosAcceptance();
// Phase 2: Auto-login with V2 (blocking CoreBridge auth)
if (hasSavedCreds && get(qobuzTosAccepted)) { if (hasSavedCreds && get(qobuzTosAccepted)) {
initStatus = 'Logging in...'; initStatus = 'Logging in...';
const response = await invoke<{ const response = await invoke<{
@@ -120,11 +122,11 @@
subscription_valid_until?: string | null; subscription_valid_until?: string | null;
error?: string; error?: string;
error_code?: string; error_code?: string;
}>('auto_login'); }>('v2_auto_login');
if (response.success) { if (response.success) {
clearTimeoutTimer(); clearTimeoutTimer();
console.log('Auto-login successful'); console.log('[LoginView] v2_auto_login successful');
onLoginSuccess({ onLoginSuccess({
userName: response.user_name || 'User', userName: response.user_name || 'User',
userId: response.user_id || 0, userId: response.user_id || 0,
@@ -133,9 +135,13 @@
}); });
return; return;
} else { } else {
console.log('Auto-login failed:', response.error); console.log('[LoginView] v2_auto_login failed:', response.error);
if (response.error_code === 'ineligible_user') { if (response.error_code === 'ineligible_user') {
error = $t('auth.ineligibleSubscription'); 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 // Don't show error, just fall through to manual login
} }
@@ -183,6 +189,7 @@
error = null; error = null;
try { try {
// V2 manual login with blocking CoreBridge auth
const response = await invoke<{ const response = await invoke<{
success: boolean; success: boolean;
user_name?: string; user_name?: string;
@@ -191,13 +198,11 @@
subscription_valid_until?: string | null; subscription_valid_until?: string | null;
error?: string; error?: string;
error_code?: 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) { if (response.success) {
// V2 CoreBridge is now authenticated automatically by the backend login command
// Save credentials if "Remember me" is checked // Save credentials if "Remember me" is checked
if (rememberMe) { if (rememberMe) {
try { try {
@@ -218,6 +223,10 @@
} else { } else {
if (response.error_code === 'ineligible_user') { if (response.error_code === 'ineligible_user') {
error = $t('auth.ineligibleSubscription'); 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 { } else {
error = response.error || 'Login failed'; error = response.error || 'Login failed';
} }
+3 -1
View File
@@ -940,7 +940,9 @@
"loginError": "Anmeldung fehlgeschlagen. Bitte überprüfen Sie Ihre Anmeldedaten.", "loginError": "Anmeldung fehlgeschlagen. Bitte überprüfen Sie Ihre Anmeldedaten.",
"welcomeBack": "Willkommen zurück", "welcomeBack": "Willkommen zurück",
"rememberMe": "Angemeldet bleiben", "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": { "legal": {
"brandingLineSuffix": "", "brandingLineSuffix": "",
+3 -1
View File
@@ -998,7 +998,9 @@
"loginError": "Login failed. Please check your credentials.", "loginError": "Login failed. Please check your credentials.",
"welcomeBack": "Welcome back", "welcomeBack": "Welcome back",
"rememberMe": "Remember me", "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": { "legal": {
"brandingLineSuffix": "", "brandingLineSuffix": "",
+3 -1
View File
@@ -998,7 +998,9 @@
"loginError": "Error al iniciar sesión. Verifica tus credenciales.", "loginError": "Error al iniciar sesión. Verifica tus credenciales.",
"welcomeBack": "Bienvenido de nuevo", "welcomeBack": "Bienvenido de nuevo",
"rememberMe": "Recordarme", "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": { "legal": {
"brandingLineSuffix": "Esta aplicación usa la API de Qobuz™ pero no está certificada por Qobuz™.", "brandingLineSuffix": "Esta aplicación usa la API de Qobuz™ pero no está certificada por Qobuz™.",
+3 -1
View File
@@ -940,7 +940,9 @@
"loginError": "Échec de la connexion. Veuillez vérifier vos identifiants.", "loginError": "Échec de la connexion. Veuillez vérifier vos identifiants.",
"welcomeBack": "Bon retour", "welcomeBack": "Bon retour",
"rememberMe": "Se souvenir de moi", "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": { "legal": {
"brandingLineSuffix": "", "brandingLineSuffix": "",