From f3235e37b4b3aaa32a18c98fecb518737e9b3182 Mon Sep 17 00:00:00 2001 From: Dixit Sabharwal Date: Mon, 2 Nov 2026 09:48:58 +0100 Subject: [PATCH 1/2] android: complete the two-factor login flow When an account has TOTP enabled the server answers the password login with code 203 (CodeNotFullySuccess) and a 2FA session id in `data`, expecting a follow-up POST /api/v4/session/token/2fa with {otp, session_id}. The app treated every non-zero code as a failed login, so turning on 2FA locked users out of the app entirely; the only way back in was the browser flow. - Decode the login response's `data` as JsonElement, since it is either a LoginResponse or the 2FA session id string. - On 203, keep the session id in UI state and show a 6-digit code step. - verify2FA() posts the code; a 404 means the ten-minute 2FA session expired and returns the user to the password form. - Back button abandons the challenge. --- .../org/cloudreve/android/api/ApiService.kt | 8 +- .../java/org/cloudreve/android/api/Dto.kt | 10 +++ .../cloudreve/android/ui/login/LoginScreen.kt | 56 +++++++++++++ .../android/ui/login/LoginViewModel.kt | 83 ++++++++++++++++--- 4 files changed, 146 insertions(+), 11 deletions(-) diff --git a/android/app/src/main/java/org/cloudreve/android/api/ApiService.kt b/android/app/src/main/java/org/cloudreve/android/api/ApiService.kt index 9201928f55..97de2ee899 100644 --- a/android/app/src/main/java/org/cloudreve/android/api/ApiService.kt +++ b/android/app/src/main/java/org/cloudreve/android/api/ApiService.kt @@ -1,5 +1,6 @@ package org.cloudreve.android.api +import kotlinx.serialization.json.JsonElement import okhttp3.RequestBody import okhttp3.ResponseBody import retrofit2.Response @@ -18,8 +19,13 @@ import retrofit2.http.Url interface ApiService { + // With 2FA enabled the server answers code 203 and `data` holds a 2FA session id + // (JSON string) instead of a LoginResponse; finish with [verify2FA]. @POST("api/v4/session/token") - suspend fun login(@Body request: PasswordLoginRequest): Response> + suspend fun login(@Body request: PasswordLoginRequest): Response> + + @POST("api/v4/session/token/2fa") + suspend fun verify2FA(@Body request: OtpLoginRequest): Response> // OAuth token exchange returns raw OAuth JSON, not the ApiResponse envelope. @FormUrlEncoded diff --git a/android/app/src/main/java/org/cloudreve/android/api/Dto.kt b/android/app/src/main/java/org/cloudreve/android/api/Dto.kt index 7881396815..54bcf443c8 100644 --- a/android/app/src/main/java/org/cloudreve/android/api/Dto.kt +++ b/android/app/src/main/java/org/cloudreve/android/api/Dto.kt @@ -40,6 +40,16 @@ data class PasswordLoginRequest( val password: String, ) +/** + * Second step of a password login when the account has two-factor auth enabled. + * [sessionId] is the value the server returned in `data` alongside code 203. + */ +@Serializable +data class OtpLoginRequest( + val otp: String, + @SerialName("session_id") val sessionId: String, +) + @Serializable data class RefreshTokenRequest( @SerialName("refresh_token") val refreshToken: String, diff --git a/android/app/src/main/java/org/cloudreve/android/ui/login/LoginScreen.kt b/android/app/src/main/java/org/cloudreve/android/ui/login/LoginScreen.kt index 74011b4da6..d7e27e3c0d 100644 --- a/android/app/src/main/java/org/cloudreve/android/ui/login/LoginScreen.kt +++ b/android/app/src/main/java/org/cloudreve/android/ui/login/LoginScreen.kt @@ -51,6 +51,13 @@ fun LoginScreen(viewModel: LoginViewModel, onLoggedIn: () -> Unit) { ) { Text("Cloudreve", style = MaterialTheme.typography.headlineLarge) Spacer(Modifier.height(8.dp)) + + // Password accepted, server is waiting for the authenticator code. + if (state.twoFactorSessionId != null) { + TwoFactorStep(state, viewModel) + return@Column + } + Text( "Sign in to your server", style = MaterialTheme.typography.bodyMedium, @@ -123,3 +130,52 @@ fun LoginScreen(viewModel: LoginViewModel, onLoggedIn: () -> Unit) { } } } + +/** + * Second step of a password login for accounts with two-factor authentication: + * the server has accepted the password and issued a short-lived 2FA session; + * the user types the 6-digit TOTP code to finish. + */ +@Composable +private fun TwoFactorStep(state: LoginUiState, viewModel: LoginViewModel) { + Text( + "Enter the 6-digit code from your authenticator app", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(32.dp)) + + OutlinedTextField( + value = state.otp, + onValueChange = viewModel::onOtpChange, + label = { Text("Verification code") }, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword), + modifier = Modifier.fillMaxWidth(), + ) + + state.error?.let { + Spacer(Modifier.height(12.dp)) + Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) + } + + Spacer(Modifier.height(24.dp)) + Button( + onClick = viewModel::verify2FA, + enabled = !state.loading && state.otp.length == 6, + modifier = Modifier.fillMaxWidth(), + ) { + if (state.loading) { + CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) + } else { + Text("Verify") + } + } + Spacer(Modifier.height(12.dp)) + androidx.compose.material3.TextButton( + onClick = viewModel::cancelTwoFactor, + enabled = !state.loading, + ) { + Text("Back") + } +} diff --git a/android/app/src/main/java/org/cloudreve/android/ui/login/LoginViewModel.kt b/android/app/src/main/java/org/cloudreve/android/ui/login/LoginViewModel.kt index 8de5ba4b28..67833d3687 100644 --- a/android/app/src/main/java/org/cloudreve/android/ui/login/LoginViewModel.kt +++ b/android/app/src/main/java/org/cloudreve/android/ui/login/LoginViewModel.kt @@ -5,7 +5,11 @@ import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonPrimitive import org.cloudreve.android.api.ApiClient +import org.cloudreve.android.api.LoginResponse +import org.cloudreve.android.api.OtpLoginRequest import org.cloudreve.android.api.PasswordLoginRequest import org.cloudreve.android.data.SessionManager import java.net.URLEncoder @@ -19,6 +23,9 @@ data class LoginUiState( val loading: Boolean = false, val error: String? = null, val loggedIn: Boolean = false, + /** Non-null once the server has accepted the password and is waiting for a TOTP code. */ + val twoFactorSessionId: String? = null, + val otp: String = "", ) class LoginViewModel( @@ -26,12 +33,23 @@ class LoginViewModel( private val api: ApiClient, ) : ViewModel() { + private companion object { + /** serializer.CodeNotFullySuccess: password accepted, 2FA code still required. */ + const val CODE_NOT_FULLY_SUCCESS = 203 + /** serializer.CodeNotFound: here, the 2FA session expired. */ + const val CODE_NOT_FOUND = 404 + } + private val _state = MutableStateFlow(LoginUiState()) val state: StateFlow = _state fun onServerUrlChange(v: String) = _state.value.let { _state.value = it.copy(serverUrl = v, error = null) } fun onEmailChange(v: String) = _state.value.let { _state.value = it.copy(email = v, error = null) } fun onPasswordChange(v: String) = _state.value.let { _state.value = it.copy(password = v, error = null) } + fun onOtpChange(v: String) = _state.value.let { _state.value = it.copy(otp = v.filter(Char::isDigit).take(6), error = null) } + + /** Abandon the pending 2FA challenge and return to the password form. */ + fun cancelTwoFactor() = _state.value.let { _state.value = it.copy(twoFactorSessionId = null, otp = "", error = null) } fun login() { val s = _state.value @@ -45,24 +63,69 @@ class LoginViewModel( session.saveServerUrl(s.serverUrl) val resp = api.service().login(PasswordLoginRequest(s.email, s.password)) val body = resp.body() - if (!resp.isSuccessful || body == null || body.code != 0 || body.data == null) { + if (!resp.isSuccessful || body == null || body.data == null) { throw Exception(body?.msg ?: "Login failed (HTTP ${resp.code()})") } - val login = body.data - session.saveSession( - accessToken = login.token.accessToken, - refreshToken = login.token.refreshToken, - accessExpiresAt = ApiClient.parseExpiresAt(login.token.accessExpires), - email = login.user.email, - nick = login.user.nickname, - ) - _state.value = _state.value.copy(loading = false, loggedIn = true) + when (body.code) { + // Password accepted; the server wants a TOTP code before issuing tokens. + // `data` is the 2FA session id, valid for ten minutes. + CODE_NOT_FULLY_SUCCESS -> { + val sessionId = (body.data as? JsonPrimitive)?.content + ?: throw Exception("Server requested 2FA without a session id") + _state.value = _state.value.copy(loading = false, twoFactorSessionId = sessionId, otp = "") + } + 0 -> completeLogin(Json.decodeFromJsonElement(LoginResponse.serializer(), body.data)) + else -> throw Exception(body.msg.ifBlank { "Login failed" }) + } } catch (e: Exception) { _state.value = _state.value.copy(loading = false, error = e.message ?: "Login failed") } } } + /** Second step of a password login: submit the TOTP code for the pending 2FA session. */ + fun verify2FA() { + val s = _state.value + val sessionId = s.twoFactorSessionId ?: return + if (s.otp.length != 6) { + _state.value = s.copy(error = "Enter the 6-digit code from your authenticator app") + return + } + _state.value = s.copy(loading = true, error = null) + viewModelScope.launch { + try { + val resp = api.service().verify2FA(OtpLoginRequest(otp = s.otp, sessionId = sessionId)) + val body = resp.body() + if (!resp.isSuccessful || body == null || body.code != 0 || body.data == null) { + // A 404 means the ten-minute 2FA session expired: start over. + val expired = body?.code == CODE_NOT_FOUND + _state.value = _state.value.copy( + loading = false, + twoFactorSessionId = if (expired) null else sessionId, + otp = "", + error = if (expired) "Sign-in timed out, please enter your password again" + else body?.msg?.ifBlank { null } ?: "Incorrect code (HTTP ${resp.code()})", + ) + return@launch + } + completeLogin(body.data) + } catch (e: Exception) { + _state.value = _state.value.copy(loading = false, otp = "", error = e.message ?: "Verification failed") + } + } + } + + private suspend fun completeLogin(login: LoginResponse) { + session.saveSession( + accessToken = login.token.accessToken, + refreshToken = login.token.refreshToken, + accessExpiresAt = ApiClient.parseExpiresAt(login.token.accessExpires), + email = login.user.email, + nick = login.user.nickname, + ) + _state.value = _state.value.copy(loading = false, loggedIn = true, twoFactorSessionId = null, otp = "") + } + /** * Builds the server-side authorize URL for browser sign-in and stashes * the PKCE verifier + state. The consent page bounces the code to the From c476ea88771d66b630ccdebe15058dd805a5fcc4 Mon Sep 17 00:00:00 2001 From: Dixit Sabharwal Date: Mon, 2 Nov 2026 09:50:26 +0100 Subject: [PATCH 2/2] android: fix unreadable login form in dark mode Nothing in the Compose tree painted a background: App() went CloudreveTheme -> NavHost -> LoginScreen -> Column with no Surface, so the window colour came from themes.xml, hard-coded to Theme.Material.Light, while CloudreveTheme followed the system and picked dark-scheme text colours. In dark mode that put light-grey text on a light window. - CloudreveTheme wraps content in a Surface painted with the scheme's background/onBackground, so Compose text always sits on Compose's own surface. - Set the full surface/background pairs with their on* colours in both schemes instead of overriding surface alone (every pair >= 4.5:1). - values-night/themes.xml gives the window a dark variant and a matching windowBackground, so the splash and edge-to-edge insets agree with the scheme too. --- .../org/cloudreve/android/ui/theme/Theme.kt | 33 +++++++++++++++++-- .../app/src/main/res/values-night/colors.xml | 5 +++ .../app/src/main/res/values-night/themes.xml | 6 ++++ android/app/src/main/res/values/colors.xml | 2 ++ android/app/src/main/res/values/themes.xml | 8 ++++- 5 files changed, 51 insertions(+), 3 deletions(-) create mode 100644 android/app/src/main/res/values-night/colors.xml create mode 100644 android/app/src/main/res/values-night/themes.xml diff --git a/android/app/src/main/java/org/cloudreve/android/ui/theme/Theme.kt b/android/app/src/main/java/org/cloudreve/android/ui/theme/Theme.kt index d315af030c..6e81392268 100644 --- a/android/app/src/main/java/org/cloudreve/android/ui/theme/Theme.kt +++ b/android/app/src/main/java/org/cloudreve/android/ui/theme/Theme.kt @@ -1,28 +1,57 @@ package org.cloudreve.android.ui.theme import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +// Every overridden surface sets its matching `on*` colour. Overriding `surface` alone +// leaves Material's defaults for text, which were tuned for a different surface and +// render as low-contrast grey on our near-black; typed text in OutlinedTextField uses +// onSurface and labels use onSurfaceVariant, so both must be set together. private val LightColors = lightColorScheme( primary = Color(0xFF4A6FA5), secondary = Color(0xFF6B8BB8), + background = Color(0xFFFAFBFD), + onBackground = Color(0xFF1A1C1E), surface = Color(0xFFFAFBFD), + onSurface = Color(0xFF1A1C1E), + surfaceVariant = Color(0xFFE2E6ED), + onSurfaceVariant = Color(0xFF444850), + outline = Color(0xFF757B86), ) private val DarkColors = darkColorScheme( primary = Color(0xFF9DB8DC), secondary = Color(0xFF8AA4CC), + background = Color(0xFF121417), + onBackground = Color(0xFFE3E5E8), surface = Color(0xFF121417), + onSurface = Color(0xFFE3E5E8), + surfaceVariant = Color(0xFF2A2E34), + onSurfaceVariant = Color(0xFFC2C6CD), + outline = Color(0xFF8B9099), ) @Composable fun CloudreveTheme(content: @Composable () -> Unit) { MaterialTheme( colorScheme = if (isSystemInDarkTheme()) DarkColors else LightColors, - content = content, - ) + ) { + // Paint the whole window with the scheme's background. Without this the + // Compose tree inherits the Activity window colour from themes.xml, which does + // not follow the colour scheme: in dark mode the text turned light while the + // window stayed light, leaving the login form light grey on white. + Surface( + modifier = Modifier.fillMaxSize(), + color = MaterialTheme.colorScheme.background, + contentColor = MaterialTheme.colorScheme.onBackground, + content = content, + ) + } } diff --git a/android/app/src/main/res/values-night/colors.xml b/android/app/src/main/res/values-night/colors.xml new file mode 100644 index 0000000000..5bfb7b1403 --- /dev/null +++ b/android/app/src/main/res/values-night/colors.xml @@ -0,0 +1,5 @@ + + + + #121417 + diff --git a/android/app/src/main/res/values-night/themes.xml b/android/app/src/main/res/values-night/themes.xml new file mode 100644 index 0000000000..f665d5ab6c --- /dev/null +++ b/android/app/src/main/res/values-night/themes.xml @@ -0,0 +1,6 @@ + + + + diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml index f42ada656e..b547bace92 100644 --- a/android/app/src/main/res/values/colors.xml +++ b/android/app/src/main/res/values/colors.xml @@ -1,4 +1,6 @@ #FFFFFF + + #FAFBFD diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml index d0b78d53c8..d9973606d3 100644 --- a/android/app/src/main/res/values/themes.xml +++ b/android/app/src/main/res/values/themes.xml @@ -1,4 +1,10 @@ -