fix(session): prevent false login state with userId=0
Addresses race condition and invalid state issues identified by Codex diagnostic:
1. CoreBridge: Add try_get() and is_initialized() methods to gracefully
handle uninitialized state instead of panicking
2. auth.rs: Use try_get() for V2 auth in login/auto_login/logout to
avoid panic if CoreBridge init is still in progress
3. LoginView.svelte: Reject userId=0 as fallback - if userInfo or userId
is missing/invalid, don't call onLoginSuccess (require re-login)
4. +page.svelte:
- Move get_audio_settings call to after sessionReady is set
- Add explicit userId > 0 check before activate_user_session
- Return early if activation fails to prevent sessionReady from
being set in broken state
These are tactical fixes aligned with ADR_RUNTIME_SESSION_CONTRACT.md
invariants. Full runtime state machine implementation to follow.
This commit is contained in:
1 parent
85757f186b
commit
c4b28e37ea
4 files changed
+52
-13
No files matched your search
@@ -92,12 +92,16 @@ pub async fn login(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Also authenticate V2 CoreBridge client for the new architecture
|
// Also authenticate V2 CoreBridge client for the new architecture
|
||||||
let bridge = core_bridge.get().await;
|
// Use try_get() to gracefully handle case where CoreBridge init is still in progress
|
||||||
|
if let Some(bridge) = core_bridge.try_get().await {
|
||||||
if let Err(e) = bridge.login(&email, &password).await {
|
if let Err(e) = bridge.login(&email, &password).await {
|
||||||
log::warn!("[Auth] V2 CoreBridge login failed (non-blocking): {}", e);
|
log::warn!("[Auth] V2 CoreBridge login failed (non-blocking): {}", e);
|
||||||
} else {
|
} else {
|
||||||
log::info!("[Auth] V2 CoreBridge authenticated successfully");
|
log::info!("[Auth] V2 CoreBridge authenticated successfully");
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
log::warn!("[Auth] V2 CoreBridge not yet initialized, skipping V2 auth");
|
||||||
|
}
|
||||||
|
|
||||||
Ok(LoginResponse {
|
Ok(LoginResponse {
|
||||||
success: true,
|
success: true,
|
||||||
@@ -168,11 +172,12 @@ pub async fn logout(
|
|||||||
let client = state.client.read().await;
|
let client = state.client.read().await;
|
||||||
client.logout().await;
|
client.logout().await;
|
||||||
|
|
||||||
// Also logout from V2 CoreBridge
|
// Also logout from V2 CoreBridge (if initialized)
|
||||||
let bridge = core_bridge.get().await;
|
if let Some(bridge) = core_bridge.try_get().await {
|
||||||
if let Err(e) = bridge.logout().await {
|
if let Err(e) = bridge.logout().await {
|
||||||
log::warn!("[Auth] V2 CoreBridge logout failed: {}", e);
|
log::warn!("[Auth] V2 CoreBridge logout failed: {}", e);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -263,12 +268,16 @@ pub async fn auto_login(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Also authenticate V2 CoreBridge client for the new architecture
|
// Also authenticate V2 CoreBridge client for the new architecture
|
||||||
let bridge = core_bridge.get().await;
|
// Use try_get() to gracefully handle case where CoreBridge init is still in progress
|
||||||
|
if let Some(bridge) = core_bridge.try_get().await {
|
||||||
if let Err(e) = bridge.login(&creds.email, &creds.password).await {
|
if let Err(e) = bridge.login(&creds.email, &creds.password).await {
|
||||||
log::warn!("[Auth/Auto] V2 CoreBridge login failed (non-blocking): {}", e);
|
log::warn!("[Auth/Auto] V2 CoreBridge login failed (non-blocking): {}", e);
|
||||||
} else {
|
} else {
|
||||||
log::info!("[Auth/Auto] V2 CoreBridge authenticated successfully");
|
log::info!("[Auth/Auto] V2 CoreBridge authenticated successfully");
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
log::warn!("[Auth/Auto] V2 CoreBridge not yet initialized, skipping V2 auth");
|
||||||
|
}
|
||||||
|
|
||||||
Ok(LoginResponse {
|
Ok(LoginResponse {
|
||||||
success: true,
|
success: true,
|
||||||
|
|||||||
@@ -239,6 +239,22 @@ impl CoreBridgeState {
|
|||||||
|opt| opt.as_ref().expect("CoreBridge not initialized")
|
|opt| opt.as_ref().expect("CoreBridge not initialized")
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Try to get the bridge, returns None if not initialized yet
|
||||||
|
/// Use this for operations that should gracefully handle uninitialized state
|
||||||
|
pub async fn try_get(&self) -> Option<impl std::ops::Deref<Target = CoreBridge> + '_> {
|
||||||
|
let guard = self.0.read().await;
|
||||||
|
if guard.is_some() {
|
||||||
|
Some(tokio::sync::RwLockReadGuard::map(guard, |opt| opt.as_ref().unwrap()))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if the bridge is initialized
|
||||||
|
pub async fn is_initialized(&self) -> bool {
|
||||||
|
self.0.read().await.is_some()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for CoreBridgeState {
|
impl Default for CoreBridgeState {
|
||||||
|
|||||||
@@ -73,7 +73,9 @@
|
|||||||
clearTimeoutTimer();
|
clearTimeoutTimer();
|
||||||
const userInfo = await invoke<{ user_name: string; subscription: string; subscription_valid_until?: string | null } | null>('get_user_info');
|
const userInfo = await invoke<{ user_name: string; subscription: string; subscription_valid_until?: string | null } | null>('get_user_info');
|
||||||
const userId = await invoke<number | null>('get_current_user_id');
|
const userId = await invoke<number | null>('get_current_user_id');
|
||||||
if (userInfo && userId) {
|
// CRITICAL: userId must be a valid positive number, never 0 or null
|
||||||
|
// If we can't get a valid userId, the session is broken and we need to re-login
|
||||||
|
if (userInfo && userId && userId > 0) {
|
||||||
onLoginSuccess({
|
onLoginSuccess({
|
||||||
userName: userInfo.user_name,
|
userName: userInfo.user_name,
|
||||||
userId,
|
userId,
|
||||||
@@ -81,7 +83,9 @@
|
|||||||
subscriptionValidUntil: userInfo.subscription_valid_until ?? null,
|
subscriptionValidUntil: userInfo.subscription_valid_until ?? null,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
onLoginSuccess({ userName: 'User', userId: userId || 0, subscription: 'Active' });
|
// Session is invalid - don't use userId=0 fallback, show login instead
|
||||||
|
console.warn('[LoginView] Session invalid: userInfo or userId missing/invalid, requiring re-login');
|
||||||
|
// Don't call onLoginSuccess with invalid userId - let the login flow continue
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-7
@@ -2301,12 +2301,19 @@
|
|||||||
|
|
||||||
// Activate per-user backend state (LoginView already did this for auto-login,
|
// Activate per-user backend state (LoginView already did this for auto-login,
|
||||||
// but we call again to ensure it's active for manual login too — it's idempotent)
|
// but we call again to ensure it's active for manual login too — it's idempotent)
|
||||||
if (info.userId) {
|
// CRITICAL: userId must be a valid positive number for activate_user_session
|
||||||
|
if (info.userId && info.userId > 0) {
|
||||||
try {
|
try {
|
||||||
await invoke('activate_user_session', { userId: info.userId });
|
await invoke('activate_user_session', { userId: info.userId });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[Session] Failed to activate user session:', err);
|
console.error('[Session] Failed to activate user session:', err);
|
||||||
|
// Don't set sessionReady if activation failed
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
console.error('[Session] Invalid userId received:', info.userId, '- cannot activate session');
|
||||||
|
// Don't set sessionReady - session is broken
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Signal that per-user backend stores are ready — the launch update
|
// Signal that per-user backend stores are ready — the launch update
|
||||||
@@ -2324,6 +2331,13 @@
|
|||||||
initBlacklistStore().catch(err => console.debug('[Blacklist] Init deferred:', err));
|
initBlacklistStore().catch(err => console.debug('[Blacklist] Init deferred:', err));
|
||||||
refreshUpdatePreferences().catch(err => console.debug('[Updates] Prefs refresh deferred:', err));
|
refreshUpdatePreferences().catch(err => console.debug('[Updates] Prefs refresh deferred:', err));
|
||||||
|
|
||||||
|
// Load audio settings (normalization state) now that session is active
|
||||||
|
invoke<{ normalization_enabled: boolean }>('get_audio_settings').then((settings) => {
|
||||||
|
normalizationEnabled = settings.normalization_enabled;
|
||||||
|
}).catch((err) => {
|
||||||
|
console.error('[AudioSettings] Failed to load:', err);
|
||||||
|
});
|
||||||
|
|
||||||
// Load favorites now that login is confirmed (sync with Qobuz)
|
// Load favorites now that login is confirmed (sync with Qobuz)
|
||||||
loadFavorites(); // Track favorites
|
loadFavorites(); // Track favorites
|
||||||
loadAlbumFavorites(); // Album favorites
|
loadAlbumFavorites(); // Album favorites
|
||||||
@@ -2637,12 +2651,8 @@
|
|||||||
// Ignore storage errors
|
// Ignore storage errors
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load normalization enabled state from audio settings
|
// NOTE: Audio settings are loaded AFTER session is ready (in handleLoginSuccess)
|
||||||
invoke<{ normalization_enabled: boolean }>('get_audio_settings').then((settings) => {
|
// to avoid "No active session" errors from per-user state
|
||||||
normalizationEnabled = settings.normalization_enabled;
|
|
||||||
}).catch((err) => {
|
|
||||||
console.error('Failed to load audio settings:', err);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Set up callback for cast disconnect handoff
|
// Set up callback for cast disconnect handoff
|
||||||
setOnAskContinueLocally(async (track, position) => {
|
setOnAskContinueLocally(async (track, position) => {
|
||||||
|
|||||||
Reference in new issue
Block a user