Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Remove Ensu backend API leftovers

Manav Rathi519a68f53818
diff --git a/mobile/native/android/apps/ensu/.gitignore b/mobile/native/android/apps/ensu/.gitignore
index d9b4b71eb2..1f75f49b8e 100644
--- a/mobile/native/android/apps/ensu/.gitignore
+++ b/mobile/native/android/apps/ensu/.gitignore
@@ -1,3 +1 @@
!debug.keystore
-
-crypto-auth-core/src/main/java/io/ente/ensu/crypto/core.kt
diff --git a/mobile/native/android/apps/ensu/README.md b/mobile/native/android/apps/ensu/README.md
index d175fb221d..a09196daed 100644
--- a/mobile/native/android/apps/ensu/README.md
+++ b/mobile/native/android/apps/ensu/README.md
@@ -29,8 +29,6 @@ That's it. Apart from the `cargo codegen`, this is a normal Android project. Gra
> (cd "$(git rev-parse --show-toplevel)/rust" && cargo codegen native)
> ```
-A custom endpoint can be baked into the build via `./gradlew :app-ui:installDebug -PENTE_API_ENDPOINT=http://localhost:8080`, or by exporting `ENTE_API_ENDPOINT` before running Gradle.
-
## Terminal builds
> [!NOTE]
@@ -69,7 +67,6 @@ Release builds use a debug keystore located at `debug.keystore`. For production
- `app-ui/` β€” Compose UI and app entry point.
- `domain/` β€” Business logic and state (pure Kotlin).
-- `data/` β€” Repositories, network, storage.
-- `crypto-auth-core/` β€” Cryptographic primitives (UniFFI-wrapped Rust).
+- `data/` β€” Repositories and storage.
The Rust glue for `db` / `inference` lives outside this app, at [`mobile/native/android/packages/rust/`](../../packages/rust/).
diff --git a/mobile/native/android/apps/ensu/app-ui/build.gradle.kts b/mobile/native/android/apps/ensu/app-ui/build.gradle.kts
index 681a43ebad..7a2b43a69e 100644
--- a/mobile/native/android/apps/ensu/app-ui/build.gradle.kts
+++ b/mobile/native/android/apps/ensu/app-ui/build.gradle.kts
@@ -10,17 +10,6 @@ configurations.configureEach {
exclude(group = "com.google.guava", module = "listenablefuture")
}
-val apiEndpointOverride = (System.getenv("ENTE_API_ENDPOINT")
- ?: project.findProperty("ENTE_API_ENDPOINT") as? String)
- ?.trim()
- .orEmpty()
-
-if (apiEndpointOverride.isNotBlank()) {
- println("ENTE_API_ENDPOINT set for build: $apiEndpointOverride")
-} else {
- println("ENTE_API_ENDPOINT not set; BuildConfig.API_ENDPOINT will be empty")
-}
-
val keystorePropsFile = rootProject.file("key.properties")
val keystoreProps = Properties()
val hasReleaseKeystore = keystorePropsFile.exists()
@@ -88,7 +77,6 @@ android {
targetSdk = 35
versionCode = (project.findProperty("versionCode") as? String)?.toInt() ?: 33
versionName = "0.1.18"
- buildConfigField("String", "API_ENDPOINT", "\"$apiEndpointOverride\"")
}
buildTypes {
@@ -109,7 +97,6 @@ android {
buildFeatures {
compose = true
- buildConfig = true
}
composeOptions {
@@ -162,7 +149,6 @@ dependencies {
implementation("com.google.accompanist:accompanist-navigation-animation:0.34.0")
implementation(project(":domain"))
implementation(project(":data"))
- implementation(project(":crypto-auth-core"))
implementation(project(":rust"))
implementation("com.github.gregcockroft:AndroidMath:v1.1.0") {
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt
index 0c99737dd3..b309569d73 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt
@@ -1,22 +1,20 @@
package io.ente.ensu
import android.app.Application
-import android.os.Build
import android.content.pm.PackageManager
+import android.os.Build
import android.os.Environment
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import io.ente.ensu.data.AdvancedSettingsDataStore
import io.ente.ensu.data.AdvancedSettingsSnapshot
import io.ente.ensu.data.AndroidDeviceCapabilityProvider
-import io.ente.ensu.data.EndpointPreferencesDataStore
import io.ente.ensu.data.SessionPreferencesDataStore
-import io.ente.ensu.data.auth.EnsuAuthService
+import io.ente.ensu.data.chat.RustChatRepository
import io.ente.ensu.data.llm.EnsuRustDefaults
+import io.ente.ensu.data.llm.InferenceRsProvider
import io.ente.ensu.data.logging.FileLogRepository
import io.ente.ensu.data.storage.CredentialStore
-import io.ente.ensu.data.llm.InferenceRsProvider
-import io.ente.ensu.data.chat.RustChatRepository
import io.ente.ensu.domain.model.LogLevel
import io.ente.ensu.domain.store.AppStore
import kotlinx.coroutines.flow.collectLatest
@@ -27,7 +25,6 @@ import java.io.File
class AppViewModel(application: Application) : AndroidViewModel(application) {
private val sessionPreferences = SessionPreferencesDataStore(application)
- private val endpointPreferences = EndpointPreferencesDataStore(application)
val advancedSettingsDataStore = AdvancedSettingsDataStore(application)
private val credentialStore = CredentialStore(application)
val appVersion = runCatching { getAppVersion(application) }.getOrDefault("unknown")
@@ -61,42 +58,10 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
ensuDefaults = ensuDefaults,
logRepository = logRepository
)
- val authService = EnsuAuthService(
- context = application,
- endpointPreferences = endpointPreferences,
- credentialStore = credentialStore,
- logRepository = logRepository
- )
-
- val currentEndpointFlow = authService.currentEndpointFlow
-
init {
val launchMessage = "App launched app=$appVersion device=${Build.MANUFACTURER} ${Build.MODEL} os=${Build.VERSION.RELEASE} (sdk=${Build.VERSION.SDK_INT})"
logRepository.log(LogLevel.Info, launchMessage, tag = "App")
- viewModelScope.launch {
- val endpoint = endpointPreferences.endpointFlow.first()
- val buildEndpoint = BuildConfig.API_ENDPOINT.trim()
- if (endpoint.isNullOrBlank()) {
- val fallback = "https://api.ente.com"
- val resolved = if (buildEndpoint.isNotBlank()) buildEndpoint else fallback
- endpointPreferences.setEndpoint(resolved)
- } else if (buildEndpoint.isNotBlank() && buildEndpoint != endpoint) {
- logRepository.log(
- LogLevel.Info,
- "Build endpoint ignored",
- details = "stored=$endpoint build=$buildEndpoint",
- tag = "App"
- )
- }
- }
-
- viewModelScope.launch {
- authService.storedEndpointFlow.collectLatest { endpoint ->
- authService.updateEndpoint(endpoint)
- }
- }
-
viewModelScope.launch {
val initialSettings = runCatching {
advancedSettingsDataStore.settingsFlow.first()
@@ -108,11 +73,6 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
store.hydrateModelDownloadRequested(sessionPreferences.modelDownloadRequested.first())
store.bootstrap(viewModelScope)
- val email = credentialStore.getEmail()
- if (credentialStore.isLoggedIn() && !email.isNullOrBlank()) {
- store.signIn(email)
- }
-
advancedSettingsDataStore.settingsFlow.drop(1).collectLatest { settings ->
store.applyPersistedSettings(
developerSettings = settings.developerSettings,
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/EnsuApp.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/EnsuApp.kt
index ee4cc6b198..92b16bfc28 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/EnsuApp.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/EnsuApp.kt
@@ -11,8 +11,6 @@ fun EnsuApp(appViewModel: AppViewModel) {
appState = appState,
store = appViewModel.store,
logRepository = appViewModel.logRepository,
- authService = appViewModel.authService,
- currentEndpointFlow = appViewModel.currentEndpointFlow,
advancedSettingsDataStore = appViewModel.advancedSettingsDataStore,
appVersion = appViewModel.appVersion,
ensuDefaults = appViewModel.ensuDefaults
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.kt
index 754b99a13e..b01788aafb 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.kt
@@ -35,18 +35,14 @@ import io.ente.ensu.domain.state.AppState
import io.ente.ensu.domain.store.AppStore
import io.ente.ensu.modelsettings.ModelSettingsScreen
import io.ente.ensu.settings.LogViewerScreen
-import io.ente.ensu.settings.DeveloperSettingsScreen
import io.ente.ensu.settings.SettingsScreen
import io.ente.ensu.settings.SystemPromptSettingsScreen
-import kotlinx.coroutines.flow.Flow
@Composable
internal fun HomeNavigation(
appState: AppState,
store: AppStore,
logRepository: io.ente.ensu.data.logging.FileLogRepository,
- authService: io.ente.ensu.data.auth.EnsuAuthService,
- currentEndpointFlow: Flow<String>,
advancedSettingsDataStore: AdvancedSettingsDataStore,
appVersion: String,
ensuDefaults: EnsuDefaults,
@@ -55,14 +51,12 @@ internal fun HomeNavigation(
currentRoute: String,
currentSession: io.ente.ensu.domain.model.ChatSession?,
onSignIn: () -> Unit,
- onSignOut: () -> Unit,
onOpenDrawer: () -> Unit,
onNewChat: () -> Unit,
onAttachmentDownloads: () -> Unit,
onShowLogShareDialog: () -> Unit,
onAttachmentSelected: (AttachmentType) -> Unit,
- onOpenAttachment: (Attachment) -> Unit,
- onDeleteAccount: () -> Unit
+ onOpenAttachment: (Attachment) -> Unit
) {
Scaffold(
containerColor = EnsuColor.backgroundBase(),
@@ -97,9 +91,6 @@ internal fun HomeNavigation(
HomeRoute.SystemPromptSettings -> {
SimpleTopBar(title = "System Prompt") { navController.popBackStack() }
}
- HomeRoute.EndpointSettings -> {
- SimpleTopBar(title = "Endpoint") { navController.popBackStack() }
- }
HomeRoute.Settings -> {
SimpleTopBar(title = "Settings") { navController.popBackStack() }
}
@@ -155,8 +146,6 @@ internal fun HomeNavigation(
) {
SettingsScreen(
buildVersion = appVersion,
- isLoggedIn = appState.auth.isLoggedIn,
- userEmail = appState.auth.email,
isAdvancedUnlocked = appState.developerSettings.isAdvancedUnlocked,
onOpenLogs = { navController.navigate(HomeRoute.Logs) },
onOpenModelSettings = { navController.navigate(HomeRoute.ModelSettings) },
@@ -165,9 +154,7 @@ internal fun HomeNavigation(
store.unlockAdvancedSettings()
advancedSettingsDataStore.persistUnlockAdvancedSettings()
},
- onSignOut = onSignOut,
- onSignIn = onSignIn,
- onDeleteAccount = onDeleteAccount
+ onSignIn = onSignIn
)
}
composable(
@@ -226,20 +213,6 @@ internal fun HomeNavigation(
}
)
}
- composable(
- route = HomeRoute.EndpointSettings,
- enterTransition = { forwardEnter() },
- exitTransition = { forwardExit() },
- popEnterTransition = { backEnter() },
- popExitTransition = { backExit() }
- ) {
- DeveloperSettingsScreen(
- authService = authService,
- currentEndpointFlow = currentEndpointFlow,
- onOpenModelSettings = { navController.navigate(HomeRoute.ModelSettings) },
- onSaved = { navController.popBackStack() }
- )
- }
}
}
}
@@ -251,7 +224,6 @@ internal object HomeRoute {
const val Logs = "logs"
const val ModelSettings = "model-settings"
const val SystemPromptSettings = "system-prompt-settings"
- const val EndpointSettings = "endpoint-settings"
}
internal fun AnimatedContentTransitionScope<NavBackStackEntry>.forwardEnter() =
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt
index e61eb21d0d..a60421d480 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt
@@ -1,4 +1,7 @@
-@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class, androidx.compose.animation.ExperimentalAnimationApi::class)
+@file:OptIn(
+ androidx.compose.animation.ExperimentalAnimationApi::class,
+ androidx.compose.material3.ExperimentalMaterial3Api::class
+)
package io.ente.ensu
@@ -13,12 +16,6 @@ import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
-import androidx.compose.animation.AnimatedVisibility
-import androidx.compose.animation.core.tween
-import androidx.compose.animation.fadeIn
-import androidx.compose.animation.fadeOut
-import androidx.compose.animation.slideInHorizontally
-import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
@@ -50,12 +47,10 @@ import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.navigation.compose.currentBackStackEntryAsState
import com.google.accompanist.navigation.animation.rememberAnimatedNavController
-import io.ente.ensu.auth.AuthFlowScreen
import io.ente.ensu.chat.SessionDrawer
import io.ente.ensu.components.ImageAttachmentPreviewDialog
import io.ente.ensu.components.NativeChoiceDialog
import io.ente.ensu.data.AdvancedSettingsDataStore
-import io.ente.ensu.data.auth.EnsuAuthService
import io.ente.ensu.data.logging.FileLogRepository
import io.ente.ensu.data.storage.FilePathManager
import io.ente.ensu.designsystem.EnsuColor
@@ -67,14 +62,12 @@ import io.ente.ensu.domain.model.EnsuDefaults
import io.ente.ensu.domain.model.MaxImageAttachmentsPerMessage
import io.ente.ensu.domain.state.AppState
import io.ente.ensu.domain.store.AppStore
-import io.ente.ensu.utils.EnsuFeatureFlags
import io.ente.ensu.whatsnew.PendingWhatsNew
import io.ente.ensu.whatsnew.WhatsNewDialog
import io.ente.ensu.whatsnew.WhatsNewService
import io.ente.labs.ensu_db.compressAttachmentImage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
-import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
@@ -86,8 +79,6 @@ fun HomeView(
appState: AppState,
store: AppStore,
logRepository: FileLogRepository,
- authService: EnsuAuthService,
- currentEndpointFlow: Flow<String>,
advancedSettingsDataStore: AdvancedSettingsDataStore,
appVersion: String,
ensuDefaults: EnsuDefaults
@@ -101,8 +92,6 @@ fun HomeView(
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route ?: HomeRoute.Chat
val isChatRoute = currentRoute == HomeRoute.Chat
- var isShowingAuth by remember { mutableStateOf(false) }
- var isShowingSignOutDialog by remember { mutableStateOf(false) }
var showAttachmentDownloads by remember { mutableStateOf(false) }
var deleteSessionTarget by remember { mutableStateOf<io.ente.ensu.domain.model.ChatSession?>(null) }
var showLogShareDialog by remember { mutableStateOf(false) }
@@ -111,13 +100,7 @@ fun HomeView(
val whatsNewService = remember(context) { WhatsNewService(context.applicationContext) }
var pendingWhatsNew by remember { mutableStateOf<PendingWhatsNew?>(null) }
- val handleSignInRequest: () -> Unit = handle@{
- if (!EnsuFeatureFlags.enableSignIn) {
- showSignInComingSoon = true
- return@handle
- }
- isShowingAuth = true
- }
+ val handleSignInRequest: () -> Unit = { showSignInComingSoon = true }
val imagePicker = rememberAttachmentPicker(
contract = ActivityResultContracts.GetContent(),
@@ -192,10 +175,6 @@ fun HomeView(
scope.launch { drawerState.close() }
}
- BackHandler(enabled = isShowingAuth) {
- isShowingAuth = false
- }
-
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
@@ -241,8 +220,6 @@ fun HomeView(
SessionDrawer(
sessions = appState.chat.sessions,
selectedSessionId = appState.chat.currentSessionId,
- isLoggedIn = appState.auth.isLoggedIn,
- userEmail = appState.auth.email,
onSelectSession = { session ->
// Same reason as above: just swap the session in-place.
store.selectSession(session.id)
@@ -267,8 +244,6 @@ fun HomeView(
appState = appState,
store = store,
logRepository = logRepository,
- authService = authService,
- currentEndpointFlow = currentEndpointFlow,
advancedSettingsDataStore = advancedSettingsDataStore,
appVersion = appVersion,
ensuDefaults = ensuDefaults,
@@ -277,7 +252,6 @@ fun HomeView(
currentRoute = currentRoute,
currentSession = currentSession,
onSignIn = handleSignInRequest,
- onSignOut = { isShowingSignOutDialog = true },
onOpenDrawer = openDrawer,
onNewChat = {
store.startNewSessionDraft()
@@ -292,8 +266,7 @@ fun HomeView(
} else {
openAttachment(context, attachment)
}
- },
- onDeleteAccount = { openDeleteAccountEmail(context) }
+ }
)
}
@@ -305,27 +278,6 @@ fun HomeView(
)
}
- AnimatedVisibility(
- visible = isShowingAuth,
- enter = slideInHorizontally(
- initialOffsetX = { fullWidth -> fullWidth },
- animationSpec = tween(220)
- ) + fadeIn(animationSpec = tween(90)),
- exit = slideOutHorizontally(
- targetOffsetX = { fullWidth -> fullWidth },
- animationSpec = tween(220)
- ) + fadeOut(animationSpec = tween(90))
- ) {
- AuthFlowScreen(
- authService = authService,
- onLoggedIn = { email ->
- store.signIn(email)
- isShowingAuth = false
- },
- onDismiss = { isShowingAuth = false }
- )
- }
-
if (showSignInComingSoon) {
ComingSoonDialog(
title = "Coming soon",
@@ -414,24 +366,6 @@ fun HomeView(
}
}
}
-
- if (isShowingSignOutDialog) {
- NativeChoiceDialog(
- title = "Sign Out",
- body = "Signing out will remove your account from this device. Local chats stay available.",
- firstButtonLabel = "Sign Out",
- secondButtonLabel = "Cancel",
- onFirst = {
- scope.launch {
- authService.clearCredentials()
- store.signOut()
- isShowingSignOutDialog = false
- }
- },
- onSecond = { isShowingSignOutDialog = false },
- onDismiss = { isShowingSignOutDialog = false }
- )
- }
}
@Composable
@@ -568,18 +502,6 @@ private fun openAttachment(context: Context, attachment: Attachment) {
}
}
-private fun openDeleteAccountEmail(context: Context) {
- val subject = Uri.encode("Request Deletion for Ente Account")
- val uri = Uri.parse("mailto:[email protected]?subject=$subject")
- val intent = Intent(Intent.ACTION_SENDTO, uri)
- val resolved = intent.resolveActivity(context.packageManager)
- if (resolved != null) {
- context.startActivity(intent)
- } else {
- Toast.makeText(context, "No email app available", Toast.LENGTH_SHORT).show()
- }
-}
-
private fun queryDisplayName(resolver: android.content.ContentResolver, uri: Uri): String? {
resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
if (cursor.moveToFirst()) {
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/RootView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/RootView.kt
index 18c3453634..2483709bd4 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/RootView.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/RootView.kt
@@ -7,20 +7,16 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import io.ente.ensu.data.AdvancedSettingsDataStore
import io.ente.ensu.designsystem.EnsuColor
-import io.ente.ensu.data.auth.EnsuAuthService
import io.ente.ensu.data.logging.FileLogRepository
import io.ente.ensu.domain.model.EnsuDefaults
import io.ente.ensu.domain.state.AppState
import io.ente.ensu.domain.store.AppStore
-import kotlinx.coroutines.flow.Flow
@Composable
fun RootView(
appState: AppState,
store: AppStore,
logRepository: FileLogRepository,
- authService: EnsuAuthService,
- currentEndpointFlow: Flow<String>,
advancedSettingsDataStore: AdvancedSettingsDataStore,
appVersion: String,
ensuDefaults: EnsuDefaults
@@ -34,8 +30,6 @@ fun RootView(
appState = appState,
store = store,
logRepository = logRepository,
- authService = authService,
- currentEndpointFlow = currentEndpointFlow,
advancedSettingsDataStore = advancedSettingsDataStore,
appVersion = appVersion,
ensuDefaults = ensuDefaults
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthComponents.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthComponents.kt
deleted file mode 100644
index 5bd4402594..0000000000
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthComponents.kt
+++ /dev/null
@@ -1,284 +0,0 @@
-@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
-
-package io.ente.ensu.auth
-
-import androidx.compose.foundation.background
-import androidx.compose.foundation.layout.Arrangement
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.PaddingValues
-import androidx.compose.foundation.layout.Row
-import androidx.compose.foundation.layout.Spacer
-import androidx.compose.foundation.layout.WindowInsets
-import androidx.compose.foundation.layout.fillMaxSize
-import androidx.compose.foundation.layout.fillMaxWidth
-import androidx.compose.foundation.layout.ime
-import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.layout.size
-import androidx.compose.foundation.layout.width
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.foundation.text.KeyboardOptions
-import androidx.compose.material3.Icon
-import androidx.compose.material3.IconButton
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.OutlinedTextField
-import androidx.compose.material3.Text
-import androidx.compose.material3.TextButton
-import androidx.compose.material3.TextFieldDefaults
-import androidx.compose.material3.CircularProgressIndicator
-import androidx.compose.runtime.Composable
-import androidx.compose.runtime.getValue
-import androidx.compose.runtime.mutableStateOf
-import androidx.compose.runtime.remember
-import androidx.compose.runtime.setValue
-import androidx.compose.ui.Alignment
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.platform.LocalDensity
-import androidx.compose.ui.text.TextStyle
-import androidx.compose.ui.text.font.FontWeight
-import androidx.compose.ui.text.input.KeyboardType
-import androidx.compose.ui.text.input.PasswordVisualTransformation
-import androidx.compose.ui.text.input.VisualTransformation
-import androidx.compose.ui.text.style.TextAlign
-import androidx.compose.ui.unit.dp
-import androidx.compose.ui.unit.sp
-import androidx.compose.ui.res.painterResource
-import io.ente.ensu.designsystem.EnsuColor
-import io.ente.ensu.designsystem.EnsuCornerRadius
-import io.ente.ensu.designsystem.HugeIcons
-import io.ente.ensu.designsystem.EnsuSpacing
-import io.ente.ensu.designsystem.EnsuTypography
-
-@Composable
-fun AuthHeader(title: String, subtitle: String? = null) {
- Column(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = EnsuSpacing.pageHorizontal.dp, vertical = EnsuSpacing.pageVertical.dp),
- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)
- ) {
- Text(text = title, style = EnsuTypography.h2Bold, color = EnsuColor.textPrimary())
- if (!subtitle.isNullOrBlank()) {
- Text(text = subtitle, style = EnsuTypography.body, color = EnsuColor.textMuted())
- }
- }
-}
-
-@Composable
-fun AuthSubtitle(text: String) {
- Text(
- text = text,
- style = EnsuTypography.body,
- color = EnsuColor.textMuted(),
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = EnsuSpacing.pageHorizontal.dp)
- )
-}
-
-@Composable
-fun LabeledTextField(
- label: String,
- hint: String,
- value: String,
- onValueChange: (String) -> Unit,
- keyboardType: KeyboardType = KeyboardType.Text,
- onSubmit: (() -> Unit)? = null
-) {
- Column(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = EnsuSpacing.pageHorizontal.dp),
- verticalArrangement = Arrangement.spacedBy(6.dp)
- ) {
- Text(text = label, style = EnsuTypography.small, color = EnsuColor.textMuted())
- OutlinedTextField(
- value = value,
- onValueChange = onValueChange,
- modifier = Modifier.fillMaxWidth(),
- textStyle = EnsuTypography.body,
- placeholder = { Text(text = hint, style = EnsuTypography.body) },
- singleLine = true,
- keyboardOptions = KeyboardOptions(keyboardType = keyboardType),
- colors = TextFieldDefaults.colors(
- focusedContainerColor = EnsuColor.fillFaint(),
- unfocusedContainerColor = EnsuColor.fillFaint(),
- focusedIndicatorColor = EnsuColor.fillFaint(),
- unfocusedIndicatorColor = EnsuColor.fillFaint(),
- cursorColor = EnsuColor.textPrimary()
- ),
- shape = RoundedCornerShape(EnsuCornerRadius.input.dp)
- )
- }
-}
-
-@Composable
-fun PasswordTextField(
- label: String,
- hint: String,
- value: String,
- onValueChange: (String) -> Unit,
- showPassword: Boolean,
- onTogglePassword: () -> Unit
-) {
- Column(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = EnsuSpacing.pageHorizontal.dp),
- verticalArrangement = Arrangement.spacedBy(6.dp)
- ) {
- Text(text = label, style = EnsuTypography.small, color = EnsuColor.textMuted())
- OutlinedTextField(
- value = value,
- onValueChange = onValueChange,
- modifier = Modifier.fillMaxWidth(),
- textStyle = EnsuTypography.body,
- placeholder = { Text(text = hint, style = EnsuTypography.body) },
- singleLine = true,
- visualTransformation = if (showPassword) VisualTransformation.None else PasswordVisualTransformation(),
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
- trailingIcon = {
- IconButton(onClick = onTogglePassword) {
- Icon(
- painter = painterResource(
- if (showPassword) HugeIcons.ViewOffSlashIcon else HugeIcons.ViewIcon
- ),
- contentDescription = if (showPassword) "Hide password" else "Show password",
- tint = EnsuColor.textMuted()
- )
- }
- },
- colors = TextFieldDefaults.colors(
- focusedContainerColor = EnsuColor.fillFaint(),
- unfocusedContainerColor = EnsuColor.fillFaint(),
- focusedIndicatorColor = EnsuColor.fillFaint(),
- unfocusedIndicatorColor = EnsuColor.fillFaint(),
- cursorColor = EnsuColor.textPrimary()
- ),
- shape = RoundedCornerShape(EnsuCornerRadius.input.dp)
- )
- }
-}
-
-@Composable
-fun CodeTextField(
- value: String,
- onValueChange: (String) -> Unit,
- maxLength: Int = 6,
- onComplete: ((String) -> Unit)? = null
-) {
- val filtered = value.filter { it.isDigit() }.take(maxLength)
- if (filtered != value) {
- onValueChange(filtered)
- }
-
- OutlinedTextField(
- value = filtered,
- onValueChange = {
- val digits = it.filter { char -> char.isDigit() }.take(maxLength)
- onValueChange(digits)
- if (digits.length == maxLength) {
- onComplete?.invoke(digits)
- }
- },
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = EnsuSpacing.pageHorizontal.dp),
- textStyle = TextStyle(
- fontSize = 28.sp,
- lineHeight = 32.sp,
- textAlign = TextAlign.Center,
- letterSpacing = 8.sp,
- color = EnsuColor.textPrimary()
- ),
- placeholder = {
- Text(
- text = "β€’ β€’ β€’ β€’ β€’ β€’",
- modifier = Modifier.fillMaxWidth(),
- style = TextStyle(
- fontSize = 28.sp,
- lineHeight = 32.sp,
- textAlign = TextAlign.Center,
- letterSpacing = 8.sp,
- color = EnsuColor.textMuted()
- )
- )
- },
- singleLine = true,
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
- colors = TextFieldDefaults.colors(
- focusedContainerColor = EnsuColor.fillFaint(),
- unfocusedContainerColor = EnsuColor.fillFaint(),
- focusedIndicatorColor = EnsuColor.fillFaint(),
- unfocusedIndicatorColor = EnsuColor.fillFaint(),
- cursorColor = EnsuColor.textPrimary()
- ),
- shape = RoundedCornerShape(EnsuCornerRadius.input.dp)
- )
-}
-
-@Composable
-fun PrimaryButton(
- text: String,
- isLoading: Boolean,
- isEnabled: Boolean,
- onClick: () -> Unit
-) {
- val buttonTextStyle = EnsuTypography.body.copy(fontSize = 18.sp, fontWeight = FontWeight.SemiBold)
- androidx.compose.material3.Button(
- onClick = onClick,
- modifier = Modifier.fillMaxWidth(),
- enabled = isEnabled,
- colors = androidx.compose.material3.ButtonDefaults.buttonColors(containerColor = EnsuColor.accent()),
- contentPadding = PaddingValues(vertical = EnsuSpacing.buttonVertical.dp),
- shape = RoundedCornerShape(EnsuCornerRadius.button.dp)
- ) {
- if (isLoading) {
- CircularProgressIndicator(
- modifier = Modifier.size(18.dp),
- color = MaterialTheme.colorScheme.onPrimary,
- strokeWidth = 2.dp
- )
- } else {
- Text(text = text, style = buttonTextStyle, color = MaterialTheme.colorScheme.onPrimary)
- }
- }
-}
-
-@Composable
-fun TextLink(text: String, onClick: () -> Unit) {
- TextButton(onClick = onClick) {
- Text(
- text = text,
- style = EnsuTypography.small,
- color = EnsuColor.action()
- )
- }
-}
-
-@Composable
-fun AuthScreen(
- content: @Composable () -> Unit,
- bottom: @Composable () -> Unit
-) {
- val density = LocalDensity.current
- val imeBottom = WindowInsets.ime.getBottom(density)
-
- Column(
- modifier = Modifier
- .fillMaxSize()
- .background(EnsuColor.backgroundBase())
- ) {
- content()
- Spacer(modifier = Modifier.weight(1f))
- if (imeBottom == 0) {
- Column(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = EnsuSpacing.pageHorizontal.dp)
- .padding(top = EnsuSpacing.md.dp, bottom = EnsuSpacing.pageVertical.dp)
- ) {
- bottom()
- }
- }
- }
-}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthFlowScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthFlowScreen.kt
deleted file mode 100644
index e815535411..0000000000
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthFlowScreen.kt
+++ /dev/null
@@ -1,168 +0,0 @@
-@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
-
-package io.ente.ensu.auth
-
-import androidx.compose.foundation.layout.Box
-import androidx.compose.foundation.layout.fillMaxSize
-import androidx.compose.foundation.layout.padding
-import androidx.compose.material3.CenterAlignedTopAppBar
-import androidx.compose.material3.Icon
-import androidx.compose.material3.IconButton
-import androidx.compose.material3.Scaffold
-import androidx.compose.material3.TopAppBarDefaults
-import androidx.compose.runtime.Composable
-import androidx.compose.runtime.mutableStateListOf
-import androidx.compose.runtime.remember
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.res.painterResource
-import androidx.compose.ui.unit.dp
-import io.ente.ensu.components.EnsuLogo
-import io.ente.ensu.data.auth.AuthResponsePayload
-import io.ente.ensu.data.auth.EnsuAuthService
-import io.ente.ensu.data.auth.KeyAttributes
-import io.ente.ensu.data.auth.SrpAttributes
-import io.ente.ensu.designsystem.EnsuColor
-import io.ente.ensu.designsystem.HugeIcons
-
-sealed class AuthRoute {
- data object EmailEntry : AuthRoute()
- data class Otp(val email: String, val srp: SrpAttributes) : AuthRoute()
- data class Password(val email: String, val srp: SrpAttributes) : AuthRoute()
- data class TwoFactor(
- val email: String,
- val srp: SrpAttributes,
- val sessionId: String,
- val password: String?
- ) : AuthRoute()
-
- data class Passkey(
- val email: String,
- val srp: SrpAttributes,
- val sessionId: String,
- val accountsUrl: String,
- val twoFactorSessionId: String?,
- val password: String?
- ) : AuthRoute()
-
- data class PasswordAfterMfa(
- val email: String,
- val srp: SrpAttributes,
- val userId: Long,
- val keyAttributes: KeyAttributes,
- val encryptedToken: String?,
- val token: String?
- ) : AuthRoute()
-
- data class PasskeyPasswordReentry(
- val email: String,
- val srp: SrpAttributes,
- val auth: AuthResponsePayload
- ) : AuthRoute()
-}
-
-@Composable
-fun AuthFlowScreen(
- authService: EnsuAuthService,
- onLoggedIn: (String) -> Unit,
- onDismiss: () -> Unit
-) {
- val backStack = remember { mutableStateListOf<AuthRoute>() }
- val currentRoute = backStack.lastOrNull() ?: AuthRoute.EmailEntry
- val canGoBack = backStack.isNotEmpty()
-
- Scaffold(
- containerColor = EnsuColor.backgroundBase(),
- topBar = {
- CenterAlignedTopAppBar(
- title = {
- EnsuLogo(height = 23.dp)
- },
- navigationIcon = {
- IconButton(onClick = {
- if (canGoBack) {
- backStack.removeAt(backStack.lastIndex)
- } else {
- onDismiss()
- }
- }) {
- Icon(
- painter = painterResource(HugeIcons.ArrowLeft01Icon),
- contentDescription = "Back"
- )
- }
- },
- actions = {},
- colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())
- )
- }
- ) { padding ->
- Box(
- modifier = Modifier
- .fillMaxSize()
- .padding(padding)
- ) {
- when (val route = currentRoute) {
- AuthRoute.EmailEntry -> EmailEntryView(
- authService = authService,
- onNavigate = { backStack.add(it) }
- )
-
- is AuthRoute.Otp -> OtpVerificationView(
- authService = authService,
- email = route.email,
- srpAttributes = route.srp,
- onNavigate = { backStack.add(it) }
- )
-
- is AuthRoute.Password -> PasswordView(
- authService = authService,
- email = route.email,
- srpAttributes = route.srp,
- onNavigate = { backStack.add(it) },
- onLoggedIn = { onLoggedIn(route.email) }
- )
-
- is AuthRoute.TwoFactor -> TwoFactorView(
- authService = authService,
- email = route.email,
- srpAttributes = route.srp,
- sessionId = route.sessionId,
- password = route.password,
- onNavigate = { backStack.add(it) },
- onLoggedIn = { onLoggedIn(route.email) }
- )
-
- is AuthRoute.Passkey -> PasskeyView(
- authService = authService,
- email = route.email,
- srpAttributes = route.srp,
- sessionId = route.sessionId,
- accountsUrl = route.accountsUrl,
- twoFactorSessionId = route.twoFactorSessionId,
- password = route.password,
- onNavigate = { backStack.add(it) },
- onLoggedIn = { onLoggedIn(route.email) }
- )
-
- is AuthRoute.PasswordAfterMfa -> PasswordAfterMfaView(
- authService = authService,
- email = route.email,
- srpAttributes = route.srp,
- userId = route.userId,
- keyAttributes = route.keyAttributes,
- encryptedToken = route.encryptedToken,
- token = route.token,
- onLoggedIn = { onLoggedIn(route.email) }
- )
-
- is AuthRoute.PasskeyPasswordReentry -> PasskeyPasswordReentryView(
- authService = authService,
- email = route.email,
- srpAttributes = route.srp,
- auth = route.auth,
- onLoggedIn = { onLoggedIn(route.email) }
- )
- }
- }
- }
-}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthSteps.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthSteps.kt
deleted file mode 100644
index 3fd03620d4..0000000000
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthSteps.kt
+++ /dev/null
@@ -1,654 +0,0 @@
-@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
-
-package io.ente.ensu.auth
-
-import android.content.Intent
-import android.net.Uri
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.Spacer
-import androidx.compose.foundation.layout.height
-import androidx.compose.foundation.layout.padding
-import androidx.compose.material3.Text
-import androidx.compose.runtime.Composable
-import androidx.compose.runtime.LaunchedEffect
-import androidx.compose.runtime.getValue
-import androidx.compose.runtime.mutableStateOf
-import androidx.compose.runtime.remember
-import androidx.compose.runtime.rememberCoroutineScope
-import androidx.compose.runtime.setValue
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.platform.LocalContext
-import androidx.compose.ui.text.input.KeyboardType
-import androidx.compose.ui.unit.dp
-import io.ente.ensu.data.auth.AuthResponsePayload
-import io.ente.ensu.data.auth.EnsuAuthService
-import io.ente.ensu.data.auth.KeyAttributes
-import io.ente.ensu.data.auth.PasskeySessionExpiredException
-import io.ente.ensu.data.auth.PasskeySessionNotVerifiedException
-import io.ente.ensu.data.auth.SrpAttributes
-import io.ente.ensu.data.auth.SrpLoginResult
-import io.ente.ensu.designsystem.EnsuColor
-import io.ente.ensu.designsystem.EnsuSpacing
-import io.ente.ensu.designsystem.EnsuTypography
-import kotlinx.coroutines.launch
-
-@Composable
-internal fun EmailEntryView(
- authService: EnsuAuthService,
- onNavigate: (AuthRoute) -> Unit
-) {
- var email by remember { mutableStateOf("") }
- val authState = rememberAuthActionState()
- val isEmailValid = email.trim().contains("@") && email.trim().contains(".") && email.trim().length >= 5
-
- AuthScreen(
- content = {
- AuthHeader(title = "Welcome back")
- Column(verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(EnsuSpacing.lg.dp)) {
- LabeledTextField(
- label = "Email",
- hint = "Enter your email",
- value = email,
- onValueChange = { email = it },
- keyboardType = KeyboardType.Email
- )
- if (authState.errorMessage != null) {
- Text(
- text = authState.errorMessage.orEmpty(),
- style = EnsuTypography.small,
- color = EnsuColor.error,
- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
- )
- }
- }
- },
- bottom = {
- PrimaryButton(
- text = "Log in",
- isLoading = authState.isLoading,
- isEnabled = isEmailValid && !authState.isLoading
- ) {
- authState.launch(onError = { error ->
- when (error) {
- is io.ente.ensu.data.auth.AccountNotFoundException ->
- "No account found for this email."
- else -> "Failed to get account info: ${error.message}"
- }
- }) {
- val trimmed = email.trim()
- val srpAttrs = authService.getSrpAttributes(trimmed)
- if (srpAttrs.isEmailMfaEnabled) {
- authService.sendOtp(trimmed)
- onNavigate(AuthRoute.Otp(trimmed, srpAttrs))
- } else {
- onNavigate(AuthRoute.Password(trimmed, srpAttrs))
- }
- }
- }
- }
- )
-}
-
-@Composable
-internal fun PasswordView(
- authService: EnsuAuthService,
- email: String,
- srpAttributes: SrpAttributes,
- onNavigate: (AuthRoute) -> Unit,
- onLoggedIn: () -> Unit
-) {
- var password by remember { mutableStateOf("") }
- var showPassword by remember { mutableStateOf(false) }
- val authState = rememberAuthActionState()
- val hasPassword = password.isNotBlank()
-
- AuthScreen(
- content = {
- AuthHeader(title = "Enter password")
- AuthSubtitle(text = email)
- Spacer(modifier = Modifier.height(EnsuSpacing.xxl.dp))
- PasswordTextField(
- label = "Password",
- hint = "Enter your password",
- value = password,
- onValueChange = { password = it },
- showPassword = showPassword,
- onTogglePassword = { showPassword = !showPassword }
- )
- if (authState.errorMessage != null) {
- Text(
- text = authState.errorMessage.orEmpty(),
- style = EnsuTypography.small,
- color = EnsuColor.error,
- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
- )
- }
- },
- bottom = {
- PrimaryButton(
- text = "Log in",
- isLoading = authState.isLoading,
- isEnabled = hasPassword && !authState.isLoading
- ) {
- authState.launch {
- val result = authService.loginWithSrp(email, password, srpAttributes)
- handleSrpResult(result, email, srpAttributes, password, onNavigate, onLoggedIn)
- }
- }
- }
- )
-}
-
-@Composable
-internal fun OtpVerificationView(
- authService: EnsuAuthService,
- email: String,
- srpAttributes: SrpAttributes,
- onNavigate: (AuthRoute) -> Unit
-) {
- var code by remember { mutableStateOf("") }
- val authState = rememberAuthActionState()
- val scope = rememberCoroutineScope()
- val hasValidCode = code.trim().length == 6
-
- fun submitOtp() {
- if (!hasValidCode || authState.isLoading) return
- authState.launch {
- val payload = authService.verifyOtp(email, code)
- val keyAttrs = payload.keyAttributes
- if (keyAttrs == null) {
- setError("New user signup not implemented. Please use an existing account.")
- } else if (payload.requiresPasskey) {
- onNavigate(
- AuthRoute.Passkey(
- email = email,
- srp = srpAttributes,
- sessionId = payload.passkeySessionId.orEmpty(),
- accountsUrl = payload.accountsUrl ?: "https://accounts.ente.com",
- twoFactorSessionId = payload.twoFactorSessionId,
- password = null
- )
- )
- } else if (payload.requiresTwoFactor) {
- onNavigate(
- AuthRoute.TwoFactor(
- email = email,
- srp = srpAttributes,
- sessionId = payload.twoFactorSessionId.orEmpty(),
- password = null
- )
- )
- } else {
- onNavigate(
- AuthRoute.PasswordAfterMfa(
- email = email,
- srp = srpAttributes,
- userId = payload.userId,
- keyAttributes = keyAttrs,
- encryptedToken = payload.encryptedToken,
- token = payload.token
- )
- )
- }
- }
- }
-
- LaunchedEffect(code) {
- if (code.trim().length == 6) {
- submitOtp()
- }
- }
-
- AuthScreen(
- content = {
- AuthHeader(title = "Verify email", subtitle = email)
- Column(verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(EnsuSpacing.lg.dp)) {
- CodeTextField(
- value = code,
- onValueChange = { code = it },
- onComplete = { value -> if (value.length == 6) code = value }
- )
- TextLink(text = "Resend code") {
- scope.launch {
- runCatching { authService.sendOtp(email) }
- .onFailure { authState.setError("Failed to resend code: ${it.message}") }
- }
- }
- if (authState.errorMessage != null) {
- Text(
- text = authState.errorMessage.orEmpty(),
- style = EnsuTypography.small,
- color = EnsuColor.error,
- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
- )
- }
- }
- },
- bottom = {
- PrimaryButton(
- text = "Verify",
- isLoading = authState.isLoading,
- isEnabled = hasValidCode && !authState.isLoading
- ) {
- submitOtp()
- }
- }
- )
-}
-
-@Composable
-internal fun TwoFactorView(
- authService: EnsuAuthService,
- email: String,
- srpAttributes: SrpAttributes,
- sessionId: String,
- password: String?,
- onNavigate: (AuthRoute) -> Unit,
- onLoggedIn: () -> Unit
-) {
- var code by remember { mutableStateOf("") }
- val authState = rememberAuthActionState()
- val hasValidCode = code.trim().length == 6
-
- fun submitTwoFactor() {
- if (!hasValidCode || authState.isLoading) return
- authState.launch {
- val payload = authService.verifyTwoFactor(sessionId, code)
- val keyAttrs = payload.keyAttributes
- if (keyAttrs == null) {
- setError("Invalid response")
- } else if (!password.isNullOrBlank()) {
- authService.loginAfterChallenge(
- email = email,
- password = password,
- srpAttributes = srpAttributes,
- userId = payload.userId,
- keyAttributes = keyAttrs,
- encryptedToken = payload.encryptedToken,
- token = payload.token
- )
- onLoggedIn()
- } else {
- onNavigate(
- AuthRoute.PasswordAfterMfa(
- email = email,
- srp = srpAttributes,
- userId = payload.userId,
- keyAttributes = keyAttrs,
- encryptedToken = payload.encryptedToken,
- token = payload.token
- )
- )
- }
- }
- }
-
- LaunchedEffect(code) {
- if (code.trim().length == 6) {
- submitTwoFactor()
- }
- }
-
- AuthScreen(
- content = {
- AuthHeader(
- title = "Two-factor authentication",
- subtitle = "Enter the code from your authenticator app"
- )
- Column(verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(EnsuSpacing.lg.dp)) {
- CodeTextField(
- value = code,
- onValueChange = { code = it },
- onComplete = { value -> if (value.length == 6) code = value }
- )
- if (authState.errorMessage != null) {
- Text(
- text = authState.errorMessage.orEmpty(),
- style = EnsuTypography.small,
- color = EnsuColor.error,
- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
- )
- }
- }
- },
- bottom = {
- PrimaryButton(
- text = "Verify",
- isLoading = authState.isLoading,
- isEnabled = hasValidCode && !authState.isLoading
- ) {
- submitTwoFactor()
- }
- }
- )
-}
-
-@Composable
-internal fun PasskeyView(
- authService: EnsuAuthService,
- email: String,
- srpAttributes: SrpAttributes,
- sessionId: String,
- accountsUrl: String,
- twoFactorSessionId: String?,
- password: String?,
- onNavigate: (AuthRoute) -> Unit,
- onLoggedIn: () -> Unit
-) {
- val context = LocalContext.current
- val authState = rememberAuthActionState()
-
- LaunchedEffect(sessionId) {
- launchPasskey(context, accountsUrl, sessionId)
- }
-
- AuthScreen(
- content = {
- AuthHeader(
- title = "Passkey verification",
- subtitle = "Complete passkey verification in browser"
- )
- Column(verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(EnsuSpacing.lg.dp)) {
- TextLink(text = "Open passkey again") {
- launchPasskey(context, accountsUrl, sessionId)
- }
-
- if (!twoFactorSessionId.isNullOrBlank()) {
- TextLink(text = "Use authenticator code") {
- onNavigate(
- AuthRoute.TwoFactor(
- email = email,
- srp = srpAttributes,
- sessionId = twoFactorSessionId,
- password = password
- )
- )
- }
- }
-
- if (authState.errorMessage != null) {
- Text(
- text = authState.errorMessage.orEmpty(),
- style = EnsuTypography.small,
- color = EnsuColor.textMuted(),
- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
- )
- }
- }
- },
- bottom = {
- PrimaryButton(
- text = "Check status",
- isLoading = authState.isLoading,
- isEnabled = !authState.isLoading
- ) {
- authState.launch(onError = { "Failed to check passkey status: ${it.message}" }) {
- try {
- val payload = authService.getTokenForPasskeySession(sessionId)
- handlePasskeyAuthResponse(
- authService = authService,
- payload = payload,
- email = email,
- srpAttributes = srpAttributes,
- password = password,
- onNavigate = onNavigate,
- onLoggedIn = onLoggedIn
- )
- } catch (error: PasskeySessionNotVerifiedException) {
- setError("Passkey verification is still pending.")
- } catch (error: PasskeySessionExpiredException) {
- setError("Login session expired.")
- }
- }
- }
- }
- )
-}
-
-@Composable
-internal fun PasswordAfterMfaView(
- authService: EnsuAuthService,
- email: String,
- srpAttributes: SrpAttributes,
- userId: Long,
- keyAttributes: KeyAttributes,
- encryptedToken: String?,
- token: String?,
- onLoggedIn: () -> Unit
-) {
- var password by remember { mutableStateOf("") }
- var showPassword by remember { mutableStateOf(false) }
- val authState = rememberAuthActionState()
-
- AuthScreen(
- content = {
- AuthHeader(title = "Enter password")
- AuthSubtitle(text = email)
- Spacer(modifier = Modifier.height(EnsuSpacing.xxl.dp))
- PasswordTextField(
- label = "Password",
- hint = "Enter your password",
- value = password,
- onValueChange = { password = it },
- showPassword = showPassword,
- onTogglePassword = { showPassword = !showPassword }
- )
- if (authState.errorMessage != null) {
- Text(
- text = authState.errorMessage.orEmpty(),
- style = EnsuTypography.small,
- color = EnsuColor.error,
- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
- )
- }
- },
- bottom = {
- PrimaryButton(
- text = "Continue",
- isLoading = authState.isLoading,
- isEnabled = password.isNotBlank() && !authState.isLoading
- ) {
- authState.launch(onError = { "Incorrect password: ${it.message}" }) {
- authService.loginAfterChallenge(
- email = email,
- password = password,
- srpAttributes = srpAttributes,
- userId = userId,
- keyAttributes = keyAttributes,
- encryptedToken = encryptedToken,
- token = token
- )
- onLoggedIn()
- }
- }
- }
- )
-}
-
-@Composable
-internal fun PasskeyPasswordReentryView(
- authService: EnsuAuthService,
- email: String,
- srpAttributes: SrpAttributes,
- auth: AuthResponsePayload,
- onLoggedIn: () -> Unit
-) {
- val keyAttributes = auth.keyAttributes
- if (keyAttributes == null) {
- AuthScreen(
- content = {
- AuthHeader(title = "Enter password")
- AuthSubtitle(text = email)
- Text(
- text = "Invalid passkey response",
- style = EnsuTypography.small,
- color = EnsuColor.error,
- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
- )
- },
- bottom = { }
- )
- return
- }
-
- var password by remember { mutableStateOf("") }
- var showPassword by remember { mutableStateOf(false) }
- val authState = rememberAuthActionState()
-
- AuthScreen(
- content = {
- AuthHeader(title = "Enter password")
- AuthSubtitle(text = email)
- Spacer(modifier = Modifier.height(EnsuSpacing.xxl.dp))
- PasswordTextField(
- label = "Password",
- hint = "Enter your password",
- value = password,
- onValueChange = { password = it },
- showPassword = showPassword,
- onTogglePassword = { showPassword = !showPassword }
- )
- if (authState.errorMessage != null) {
- Text(
- text = authState.errorMessage.orEmpty(),
- style = EnsuTypography.small,
- color = EnsuColor.error,
- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
- )
- }
- },
- bottom = {
- PrimaryButton(
- text = "Continue",
- isLoading = authState.isLoading,
- isEnabled = password.isNotBlank() && !authState.isLoading
- ) {
- authState.launch(onError = { "Incorrect password: ${it.message}" }) {
- authService.loginAfterChallenge(
- email = email,
- password = password,
- srpAttributes = srpAttributes,
- userId = auth.userId,
- keyAttributes = keyAttributes,
- encryptedToken = auth.encryptedToken,
- token = auth.token
- )
- onLoggedIn()
- }
- }
- }
- )
-}
-
-private class AuthActionState(private val scope: kotlinx.coroutines.CoroutineScope) {
- var isLoading by mutableStateOf(false)
- private set
- var errorMessage by mutableStateOf<String?>(null)
- private set
-
- fun setError(message: String?) {
- errorMessage = message
- }
-
- fun launch(
- onError: (Throwable) -> String? = { it.message },
- block: suspend AuthActionState.() -> Unit
- ) {
- if (isLoading) return
- scope.launch {
- if (isLoading) return@launch
- isLoading = true
- errorMessage = null
- try {
- block()
- } catch (error: Throwable) {
- errorMessage = onError(error)
- } finally {
- isLoading = false
- }
- }
- }
-}
-
-@Composable
-private fun rememberAuthActionState(): AuthActionState {
- val scope = rememberCoroutineScope()
- return remember(scope) { AuthActionState(scope) }
-}
-
-private fun handleSrpResult(
- result: SrpLoginResult,
- email: String,
- srpAttributes: SrpAttributes,
- password: String,
- onNavigate: (AuthRoute) -> Unit,
- onLoggedIn: () -> Unit
-) {
- if (result.requiresPasskey) {
- onNavigate(
- AuthRoute.Passkey(
- email = email,
- srp = srpAttributes,
- sessionId = result.passkeySessionId.orEmpty(),
- accountsUrl = result.accountsUrl ?: "https://accounts.ente.com",
- twoFactorSessionId = result.twoFactorSessionId,
- password = password
- )
- )
- return
- }
-
- if (result.requiresTwoFactor) {
- onNavigate(
- AuthRoute.TwoFactor(
- email = email,
- srp = srpAttributes,
- sessionId = result.twoFactorSessionId.orEmpty(),
- password = password
- )
- )
- return
- }
-
- onLoggedIn()
-}
-
-private suspend fun handlePasskeyAuthResponse(
- authService: EnsuAuthService,
- payload: AuthResponsePayload,
- email: String,
- srpAttributes: SrpAttributes,
- password: String?,
- onNavigate: (AuthRoute) -> Unit,
- onLoggedIn: () -> Unit
-) {
- val keyAttrs = payload.keyAttributes ?: return
- if (!password.isNullOrBlank()) {
- authService.loginAfterChallenge(
- email = email,
- password = password,
- srpAttributes = srpAttributes,
- userId = payload.userId,
- keyAttributes = keyAttrs,
- encryptedToken = payload.encryptedToken,
- token = payload.token
- )
- onLoggedIn()
- } else {
- onNavigate(AuthRoute.PasskeyPasswordReentry(email, srpAttributes, payload))
- }
-}
-
-private fun launchPasskey(context: android.content.Context, accountsUrl: String, sessionId: String) {
- val base = accountsUrl.trimEnd('/')
- val url = Uri.parse("$base/passkeys/verify")
- .buildUpon()
- .appendQueryParameter("passkeySessionID", sessionId)
- .appendQueryParameter("redirect", "enteensu://passkey")
- .appendQueryParameter("clientPackage", context.packageName)
- .build()
-
- val intent = Intent(Intent.ACTION_VIEW, url)
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- context.startActivity(intent)
-}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt
index e985a23698..f3e7df9ee8 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt
@@ -55,8 +55,6 @@ import kotlin.math.absoluteValue
fun SessionDrawer(
sessions: List<ChatSession>,
selectedSessionId: String?,
- isLoggedIn: Boolean,
- userEmail: String?,
onSelectSession: (ChatSession) -> Unit,
onDeleteSession: (ChatSession) -> Unit,
onOpenSettings: () -> Unit
@@ -102,8 +100,6 @@ fun SessionDrawer(
HorizontalDivider(color = EnsuColor.border())
DrawerFooter(
- isLoggedIn = isLoggedIn,
- userEmail = userEmail,
onOpenSettings = onOpenSettings
)
}
@@ -324,54 +320,28 @@ private fun SessionTile(
@Composable
private fun DrawerFooter(
- isLoggedIn: Boolean,
- userEmail: String?,
onOpenSettings: () -> Unit
) {
- if (isLoggedIn) {
- Row(
- modifier = Modifier
- .fillMaxWidth()
- .clickable(onClick = onOpenSettings)
- .padding(EnsuSpacing.lg.dp),
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)
- ) {
- Text(
- text = userEmail.orEmpty(),
- style = EnsuTypography.body,
- color = EnsuColor.textPrimary(),
- modifier = Modifier.weight(1f)
- )
- Icon(
- painter = painterResource(HugeIcons.ArrowRight01Icon),
- contentDescription = "Settings",
- modifier = Modifier.size(18.dp),
- tint = EnsuColor.textMuted()
- )
- }
- } else {
- Row(
- modifier = Modifier
- .fillMaxWidth()
- .clickable(onClick = onOpenSettings)
- .padding(EnsuSpacing.lg.dp),
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)
- ) {
- Text(
- text = "Settings",
- style = EnsuTypography.body,
- color = EnsuColor.textPrimary(),
- modifier = Modifier.weight(1f)
- )
- Icon(
- painter = painterResource(HugeIcons.ArrowRight01Icon),
- contentDescription = "Settings",
- modifier = Modifier.size(18.dp),
- tint = EnsuColor.textMuted()
- )
- }
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable(onClick = onOpenSettings)
+ .padding(EnsuSpacing.lg.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)
+ ) {
+ Text(
+ text = "Settings",
+ style = EnsuTypography.body,
+ color = EnsuColor.textPrimary(),
+ modifier = Modifier.weight(1f)
+ )
+ Icon(
+ painter = painterResource(HugeIcons.ArrowRight01Icon),
+ contentDescription = "Settings",
+ modifier = Modifier.size(18.dp),
+ tint = EnsuColor.textMuted()
+ )
}
}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ActionButtons.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ActionButtons.kt
index c39d8694a1..061917126d 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ActionButtons.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ActionButtons.kt
@@ -1,9 +1,16 @@
package io.ente.ensu.components
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
+import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@@ -12,8 +19,12 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.designsystem.EnsuCornerRadius
+import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
import io.ente.ensu.utils.rememberEnsuHaptics
@@ -78,3 +89,34 @@ fun TextActionButton(
Text(text = text, style = EnsuTypography.small, color = EnsuColor.textMuted())
}
}
+
+@Composable
+fun PrimaryButton(
+ text: String,
+ isLoading: Boolean,
+ isEnabled: Boolean,
+ onClick: () -> Unit
+) {
+ Button(
+ onClick = onClick,
+ modifier = Modifier.fillMaxWidth(),
+ enabled = isEnabled,
+ colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.accent()),
+ contentPadding = PaddingValues(vertical = EnsuSpacing.buttonVertical.dp),
+ shape = RoundedCornerShape(EnsuCornerRadius.button.dp)
+ ) {
+ if (isLoading) {
+ CircularProgressIndicator(
+ modifier = Modifier.size(18.dp),
+ color = MaterialTheme.colorScheme.onPrimary,
+ strokeWidth = 2.dp
+ )
+ } else {
+ Text(
+ text = text,
+ style = EnsuTypography.body.copy(fontSize = 18.sp, fontWeight = FontWeight.SemiBold),
+ color = MaterialTheme.colorScheme.onPrimary
+ )
+ }
+ }
+}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/DeveloperSettingsScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/DeveloperSettingsScreen.kt
deleted file mode 100644
index ab7ea53b77..0000000000
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/DeveloperSettingsScreen.kt
+++ /dev/null
@@ -1,152 +0,0 @@
-package io.ente.ensu.settings
-
-import androidx.compose.foundation.clickable
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.Row
-import androidx.compose.foundation.layout.Spacer
-import androidx.compose.foundation.layout.fillMaxSize
-import androidx.compose.foundation.layout.fillMaxWidth
-import androidx.compose.foundation.layout.height
-import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.layout.size
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.material3.Icon
-import androidx.compose.material3.OutlinedTextField
-import androidx.compose.material3.Text
-import androidx.compose.material3.TextFieldDefaults
-import androidx.compose.runtime.Composable
-import androidx.compose.runtime.collectAsState
-import androidx.compose.runtime.getValue
-import androidx.compose.runtime.mutableStateOf
-import androidx.compose.runtime.remember
-import androidx.compose.runtime.rememberCoroutineScope
-import androidx.compose.runtime.setValue
-import androidx.compose.ui.Alignment
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.res.painterResource
-import androidx.compose.ui.unit.dp
-import io.ente.ensu.auth.PrimaryButton
-import io.ente.ensu.data.auth.EnsuAuthService
-import io.ente.ensu.designsystem.EnsuColor
-import io.ente.ensu.designsystem.EnsuCornerRadius
-import io.ente.ensu.designsystem.EnsuSpacing
-import io.ente.ensu.designsystem.EnsuTypography
-import io.ente.ensu.designsystem.HugeIcons
-import io.ente.ensu.utils.EnsuFeatureFlags
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.launch
-
-@Composable
-fun DeveloperSettingsScreen(
- authService: EnsuAuthService,
- currentEndpointFlow: Flow<String>,
- onOpenModelSettings: () -> Unit,
- onSaved: () -> Unit
-) {
- val currentEndpoint by currentEndpointFlow.collectAsState(initial = "https://api.ente.com")
- var endpointInput by remember { mutableStateOf("") }
- var isSaving by remember { mutableStateOf(false) }
- var errorMessage by remember { mutableStateOf<String?>(null) }
- val scope = rememberCoroutineScope()
-
- val isSavable = endpointInput.trim().isNotEmpty() && !isSaving
-
- Column(
- modifier = Modifier
- .fillMaxSize()
- .padding(EnsuSpacing.pageHorizontal.dp)
- ) {
- if (EnsuFeatureFlags.enableModelSettings) {
- DeveloperSettingsRow(
- title = "Model settings",
- subtitle = "Model URL, mmproj, context length, max output",
- onClick = onOpenModelSettings
- )
-
- Spacer(modifier = Modifier.height(EnsuSpacing.xxl.dp))
- }
-
- Text(text = "Endpoint configuration", style = EnsuTypography.h3Bold, color = EnsuColor.textPrimary())
- Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
-
- Text(text = "Server endpoint", style = EnsuTypography.small, color = EnsuColor.textMuted())
- Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
- OutlinedTextField(
- value = endpointInput,
- onValueChange = { endpointInput = it },
- modifier = Modifier.fillMaxWidth(),
- placeholder = { Text(text = currentEndpoint, style = EnsuTypography.body) },
- singleLine = true,
- colors = TextFieldDefaults.colors(
- focusedContainerColor = EnsuColor.fillFaint(),
- unfocusedContainerColor = EnsuColor.fillFaint(),
- focusedIndicatorColor = EnsuColor.fillFaint(),
- unfocusedIndicatorColor = EnsuColor.fillFaint()
- ),
- shape = RoundedCornerShape(EnsuCornerRadius.input.dp)
- )
- Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
- Text(
- text = "Current endpoint: $currentEndpoint",
- style = EnsuTypography.mini,
- color = EnsuColor.textMuted()
- )
-
- if (errorMessage != null) {
- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
- Text(
- text = errorMessage.orEmpty(),
- style = EnsuTypography.small,
- color = EnsuColor.error
- )
- }
-
- Spacer(modifier = Modifier.height(EnsuSpacing.lg.dp))
-
- PrimaryButton(
- text = "Save",
- isLoading = isSaving,
- isEnabled = isSavable
- ) {
- scope.launch {
- if (isSaving) return@launch
- isSaving = true
- errorMessage = null
- val result = authService.setEndpoint(endpointInput)
- if (result.isSuccess) {
- endpointInput = ""
- onSaved()
- } else {
- errorMessage = "Unable to reach the server at the provided endpoint."
- }
- isSaving = false
- }
- }
- }
-}
-
-@Composable
-private fun DeveloperSettingsRow(
- title: String,
- subtitle: String,
- onClick: () -> Unit
-) {
- Row(
- modifier = Modifier
- .fillMaxWidth()
- .clickable(onClick = onClick)
- .padding(vertical = EnsuSpacing.sm.dp),
- verticalAlignment = Alignment.CenterVertically
- ) {
- Column(modifier = Modifier.weight(1f)) {
- Text(text = title, style = EnsuTypography.body, color = EnsuColor.textPrimary())
- Text(text = subtitle, style = EnsuTypography.small, color = EnsuColor.textMuted())
- }
- Icon(
- painter = painterResource(HugeIcons.ArrowRight01Icon),
- contentDescription = null,
- tint = EnsuColor.textMuted(),
- modifier = Modifier.size(18.dp)
- )
- }
-}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SettingsScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SettingsScreen.kt
index f446957063..7f76bd3ba7 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SettingsScreen.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SettingsScreen.kt
@@ -46,23 +46,19 @@ import io.ente.ensu.designsystem.HugeIcons
@Composable
fun SettingsScreen(
buildVersion: String,
- isLoggedIn: Boolean,
- userEmail: String?,
isAdvancedUnlocked: Boolean,
onOpenLogs: () -> Unit,
onOpenModelSettings: () -> Unit,
onOpenSystemPromptSettings: () -> Unit,
onUnlockAdvanced: () -> Unit,
- onSignOut: () -> Unit,
- onSignIn: () -> Unit,
- onDeleteAccount: () -> Unit
+ onSignIn: () -> Unit
) {
var query by remember { mutableStateOf("") }
var buildVersionTapCount by remember { mutableStateOf(0) }
var lastBuildVersionTapAt by remember { mutableStateOf<Long?>(null) }
val context = LocalContext.current
- val allItems = remember(context, onOpenLogs, onSignOut, onSignIn, onDeleteAccount, isLoggedIn) {
+ val allItems = remember(context, onOpenLogs, onSignIn) {
buildList {
add(
SettingsItem(
@@ -80,32 +76,13 @@ fun SettingsScreen(
)
)
- if (isLoggedIn) {
- add(
- SettingsItem(
- title = "Delete Account",
- iconRes = HugeIcons.Delete01Icon,
- onClick = onDeleteAccount,
- isDestructive = true
- )
- )
- add(
- SettingsItem(
- title = "Sign Out",
- iconRes = HugeIcons.Cancel01Icon,
- onClick = onSignOut,
- isDestructive = true
- )
- )
- } else {
- add(
- SettingsItem(
- title = "Sign In to Backup",
- iconRes = HugeIcons.Upload01Icon,
- onClick = onSignIn
- )
+ add(
+ SettingsItem(
+ title = "Sign In to Backup",
+ iconRes = HugeIcons.Upload01Icon,
+ onClick = onSignIn
)
- }
+ )
add(
SettingsItem(
@@ -166,28 +143,6 @@ fun SettingsScreen(
Spacer(modifier = Modifier.size(EnsuSpacing.lg.dp))
- if (isLoggedIn && !userEmail.isNullOrBlank()) {
- Column(
- modifier = Modifier
- .fillMaxWidth()
- .clip(RoundedCornerShape(EnsuCornerRadius.card.dp))
- .background(EnsuColor.fillFaint())
- .padding(EnsuSpacing.lg.dp)
- ) {
- Text(
- text = "Signed in as",
- style = EnsuTypography.small,
- color = EnsuColor.textMuted()
- )
- Text(
- text = userEmail,
- style = EnsuTypography.body,
- color = EnsuColor.textPrimary()
- )
- }
- Spacer(modifier = Modifier.size(EnsuSpacing.md.dp))
- }
-
LazyColumn(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {
items(filteredItems, key = { it.title }) { item ->
SettingsRow(item)
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.kt
index 03ed502ebb..63f912f9a9 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.kt
@@ -1,6 +1,5 @@
package io.ente.ensu.settings
-import io.ente.ensu.auth.PrimaryButton
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
@@ -21,6 +20,7 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.unit.dp
+import io.ente.ensu.components.PrimaryButton
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuCornerRadius
import io.ente.ensu.designsystem.EnsuSpacing
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/utils/FeatureFlags.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/utils/FeatureFlags.kt
index 507271977a..a23e20e6be 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/utils/FeatureFlags.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/utils/FeatureFlags.kt
@@ -1,8 +1,5 @@
package io.ente.ensu.utils
object EnsuFeatureFlags {
- const val enableSignIn = false
- const val enableDeveloperTools = false
const val enableImageUploads = true
- const val enableModelSettings = false
}
diff --git a/mobile/native/android/apps/ensu/crypto-auth-core/build.gradle.kts b/mobile/native/android/apps/ensu/crypto-auth-core/build.gradle.kts
deleted file mode 100644
index c6dacbb2b1..0000000000
--- a/mobile/native/android/apps/ensu/crypto-auth-core/build.gradle.kts
+++ /dev/null
@@ -1,27 +0,0 @@
-plugins {
- id("com.android.library")
- id("org.jetbrains.kotlin.android")
-}
-
-android {
- namespace = "io.ente.ensu.crypto"
- compileSdk = 34
-
- defaultConfig {
- minSdk = 24
- }
-
- compileOptions {
- sourceCompatibility = JavaVersion.VERSION_17
- targetCompatibility = JavaVersion.VERSION_17
- }
-
- kotlinOptions {
- jvmTarget = "17"
- }
-}
-
-dependencies {
- implementation(project(":domain"))
- implementation("net.java.dev.jna:jna:5.18.1@aar")
-}
diff --git a/mobile/native/android/apps/ensu/crypto-auth-core/src/main/java/io/ente/ensu/crypto/EnsuCryptoBridge.kt b/mobile/native/android/apps/ensu/crypto-auth-core/src/main/java/io/ente/ensu/crypto/EnsuCryptoBridge.kt
deleted file mode 100644
index 22c3992b75..0000000000
--- a/mobile/native/android/apps/ensu/crypto-auth-core/src/main/java/io/ente/ensu/crypto/EnsuCryptoBridge.kt
+++ /dev/null
@@ -1,49 +0,0 @@
-@file:OptIn(ExperimentalUnsignedTypes::class)
-
-package io.ente.ensu.crypto
-
-object EnsuCryptoBridge {
- init {
- uniffiEnsureInitialized()
- }
-
- fun init() {
- io.ente.ensu.crypto.initCrypto()
- }
-
- fun srpStart(password: String, attrs: SrpAttributes): SrpSessionResult {
- return io.ente.ensu.crypto.srpStart(password, attrs)
- }
-
- fun srpFinish(srpB: String): SrpVerifyResult {
- return io.ente.ensu.crypto.srpFinish(srpB)
- }
-
- fun srpClear() {
- io.ente.ensu.crypto.srpClear()
- }
-
- fun srpDecryptSecrets(
- srpM2: String,
- keyAttributes: KeyAttributes,
- encryptedToken: String?,
- plainToken: String?
- ): AuthSecrets {
- return io.ente.ensu.crypto.srpDecryptSecrets(srpM2, keyAttributes, encryptedToken, plainToken)
- }
-
- fun deriveKekForLogin(password: String, kekSalt: String, memLimit: Int, opsLimit: Int): ByteArray {
- val result = io.ente.ensu.crypto.deriveKekForLogin(password, kekSalt, memLimit.toUInt(), opsLimit.toUInt())
- return result.toUByteArray().toByteArray()
- }
-
- fun decryptSecretsWithKek(
- kek: ByteArray,
- keyAttributes: KeyAttributes,
- encryptedToken: String?,
- plainToken: String?
- ): AuthSecrets {
- val kekList = kek.toUByteArray().asList()
- return io.ente.ensu.crypto.decryptSecretsWithKek(kekList, keyAttributes, encryptedToken, plainToken)
- }
-}
diff --git a/mobile/native/android/apps/ensu/data/build.gradle.kts b/mobile/native/android/apps/ensu/data/build.gradle.kts
index 27673c539c..5a8f4e620c 100644
--- a/mobile/native/android/apps/ensu/data/build.gradle.kts
+++ b/mobile/native/android/apps/ensu/data/build.gradle.kts
@@ -24,7 +24,6 @@ android {
dependencies {
implementation(project(":domain"))
- implementation(project(":crypto-auth-core"))
implementation(project(":rust"))
implementation("androidx.core:core-ktx:1.12.0")
implementation("androidx.datastore:datastore-preferences:1.1.1")
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/EndpointPreferencesDataStore.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/EndpointPreferencesDataStore.kt
deleted file mode 100644
index 8a139324c6..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/EndpointPreferencesDataStore.kt
+++ /dev/null
@@ -1,29 +0,0 @@
-package io.ente.ensu.data
-
-import android.content.Context
-import androidx.datastore.preferences.core.edit
-import androidx.datastore.preferences.core.stringPreferencesKey
-import androidx.datastore.preferences.preferencesDataStore
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.map
-
-private val Context.endpointPreferences by preferencesDataStore("ensu_developer_settings")
-
-class EndpointPreferencesDataStore(private val context: Context) {
- private val endpointKey = stringPreferencesKey("custom_endpoint")
- private val legacyProductionEndpoint = "https://api.ente.io"
-
- val endpointFlow: Flow<String?> = context.endpointPreferences.data.map { prefs ->
- prefs[endpointKey]?.takeUnless { it == legacyProductionEndpoint }
- }
-
- suspend fun setEndpoint(endpoint: String?) {
- context.endpointPreferences.edit { prefs ->
- if (endpoint.isNullOrBlank()) {
- prefs.remove(endpointKey)
- } else {
- prefs[endpointKey] = endpoint
- }
- }
- }
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/AuthModels.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/AuthModels.kt
deleted file mode 100644
index 0f134280f6..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/AuthModels.kt
+++ /dev/null
@@ -1,43 +0,0 @@
-package io.ente.ensu.data.auth
-
-data class SrpAttributes(
- val srpUserId: String,
- val srpSalt: String,
- val kekSalt: String,
- val memLimit: Int,
- val opsLimit: Int,
- val isEmailMfaEnabled: Boolean
-)
-
-data class KeyAttributes(
- val kekSalt: String,
- val encryptedKey: String,
- val keyDecryptionNonce: String,
- val publicKey: String,
- val encryptedSecretKey: String,
- val secretKeyDecryptionNonce: String,
- val memLimit: Int? = null,
- val opsLimit: Int? = null
-)
-
-data class AuthResponsePayload(
- val userId: Long,
- val keyAttributes: KeyAttributes?,
- val encryptedToken: String?,
- val token: String?,
- val twoFactorSessionId: String?,
- val passkeySessionId: String?,
- val accountsUrl: String?
-) {
- val requiresTwoFactor: Boolean = !twoFactorSessionId.isNullOrBlank()
- val requiresPasskey: Boolean = !passkeySessionId.isNullOrBlank()
-}
-
-data class SrpLoginResult(
- val twoFactorSessionId: String?,
- val passkeySessionId: String?,
- val accountsUrl: String?
-) {
- val requiresTwoFactor: Boolean = !twoFactorSessionId.isNullOrBlank()
- val requiresPasskey: Boolean = !passkeySessionId.isNullOrBlank()
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthService.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthService.kt
deleted file mode 100644
index 14dd2e17dd..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthService.kt
+++ /dev/null
@@ -1,335 +0,0 @@
-@file:OptIn(ExperimentalUnsignedTypes::class)
-
-package io.ente.ensu.data.auth
-
-import android.content.Context
-import android.util.Base64
-import io.ente.ensu.crypto.AuthSecrets
-import io.ente.ensu.crypto.EnsuCryptoBridge
-import io.ente.ensu.crypto.KeyAttributes as CryptoKeyAttributes
-import io.ente.ensu.crypto.SrpAttributes as CryptoSrpAttributes
-import io.ente.ensu.data.EndpointPreferencesDataStore
-import io.ente.ensu.data.network.ApiException
-import io.ente.ensu.data.network.AuthorizationResponse
-import io.ente.ensu.data.network.NetworkConfiguration
-import io.ente.ensu.data.network.NetworkFactory
-import io.ente.ensu.data.storage.CredentialStore
-import io.ente.ensu.domain.logging.LogRepository
-import io.ente.ensu.domain.model.LogLevel
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.map
-import kotlinx.coroutines.withContext
-import okhttp3.HttpUrl
-import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
-import okhttp3.OkHttpClient
-import okhttp3.Request
-import org.json.JSONObject
-
-class EnsuAuthService(
- private val context: Context,
- private val endpointPreferences: EndpointPreferencesDataStore,
- private val credentialStore: CredentialStore,
- private val logRepository: LogRepository
-) {
- private val authTokenProvider = EnsuAuthTokenProvider(credentialStore)
- private val okHttpClient = OkHttpClient()
-
- private var networkFactory = NetworkFactory(
- context = context,
- configuration = NetworkConfiguration.default,
- authTokenProvider = authTokenProvider
- )
-
- val currentEndpointFlow: Flow<String> = endpointPreferences.endpointFlow.map { endpoint ->
- endpoint ?: NetworkConfiguration.default.apiEndpoint.toString()
- }
-
- val storedEndpointFlow: Flow<String?> = endpointPreferences.endpointFlow
-
- init {
- runCatching { EnsuCryptoBridge.init() }
- .onFailure { error ->
- logRepository.log(
- LogLevel.Error,
- "Crypto init failed",
- details = error.message,
- tag = "Auth",
- throwable = error
- )
- }
- .getOrThrow()
- }
-
- suspend fun updateEndpoint(endpoint: String?) {
- val url = endpoint?.toHttpUrlOrNull()
- updateEndpointUrl(url)
- }
-
- private suspend fun updateEndpointUrl(endpoint: HttpUrl?) {
- val config = if (endpoint != null) {
- NetworkConfiguration.selfHosted(endpoint)
- } else {
- NetworkConfiguration.default
- }
- networkFactory = NetworkFactory(
- context = context,
- configuration = config,
- authTokenProvider = authTokenProvider
- )
- }
-
- suspend fun setEndpoint(endpointInput: String): Result<String> {
- val normalized = normalize(endpointInput)
- val url = normalized.toHttpUrlOrNull()
- ?: return Result.failure(IllegalArgumentException("Invalid endpoint"))
-
- if (url.scheme != "http" && url.scheme != "https") {
- return Result.failure(IllegalArgumentException("Invalid endpoint"))
- }
-
- return try {
- pingEndpoint(url)
- endpointPreferences.setEndpoint(normalized)
- updateEndpointUrl(url)
- logRepository.log(LogLevel.Info, "Updated endpoint", details = normalized, tag = "Auth")
- Result.success(normalized)
- } catch (error: Exception) {
- logRepository.log(
- LogLevel.Error,
- "Endpoint update failed",
- details = error.message,
- tag = "Auth",
- throwable = error
- )
- Result.failure(error)
- }
- }
-
- suspend fun getSrpAttributes(email: String): SrpAttributes {
- val response = try {
- networkFactory.authentication.getSrpAttributes(email)
- } catch (error: ApiException) {
- if (error.code == 404) {
- throw AccountNotFoundException()
- }
- throw error
- }
- return SrpAttributes(
- srpUserId = response.attributes.srpUserId,
- srpSalt = response.attributes.srpSalt,
- kekSalt = response.attributes.kekSalt,
- memLimit = response.attributes.memLimit,
- opsLimit = response.attributes.opsLimit,
- isEmailMfaEnabled = response.attributes.isEmailMfaEnabled
- )
- }
-
- suspend fun sendOtp(email: String) {
- networkFactory.authentication.sendLoginOtp(email)
- }
-
- suspend fun verifyOtp(email: String, otp: String): AuthResponsePayload {
- val response = networkFactory.authentication.verifyEmail(email, otp)
- return response.toPayload()
- }
-
- suspend fun verifyTwoFactor(sessionId: String, code: String): AuthResponsePayload {
- val response = networkFactory.authentication.verifyTotp(sessionId, code)
- return response.toPayload()
- }
-
- suspend fun getTokenForPasskeySession(sessionId: String): AuthResponsePayload {
- return try {
- val response = networkFactory.authentication.getTokenForPasskeySession(sessionId)
- response.toPayload()
- } catch (error: ApiException) {
- if (error.code == 400) throw PasskeySessionNotVerifiedException()
- if (error.code == 404 || error.code == 410) throw PasskeySessionExpiredException()
- throw error
- }
- }
-
- suspend fun loginWithSrp(email: String, password: String, srpAttributes: SrpAttributes): SrpLoginResult {
- try {
- logRepository.log(LogLevel.Info, "SRP login started", tag = "Auth")
- val start = withContext(Dispatchers.Default) {
- EnsuCryptoBridge.srpStart(password, srpAttributes.toCrypto())
- }
-
- val session = networkFactory.authentication.createSrpSession(
- srpUserId = srpAttributes.srpUserId,
- clientPub = start.srpA
- )
-
- val verify = withContext(Dispatchers.Default) {
- EnsuCryptoBridge.srpFinish(session.srpB)
- }
-
- val response = networkFactory.authentication.verifySrpSession(
- srpUserId = srpAttributes.srpUserId,
- sessionId = session.sessionId,
- clientM1 = verify.srpM1
- )
-
- val payload = response.toPayload()
- val passkeySessionId = payload.passkeySessionId?.takeIf { it.isNotBlank() }
- val twoFactorSessionId = payload.twoFactorSessionId?.takeIf { it.isNotBlank() }
- if (passkeySessionId != null || twoFactorSessionId != null) {
- return SrpLoginResult(
- twoFactorSessionId = twoFactorSessionId,
- passkeySessionId = passkeySessionId,
- accountsUrl = payload.accountsUrl?.takeIf { it.isNotBlank() }
- ?: networkFactory.configuration.accountsEndpoint?.toString()
- )
- }
-
- val keyAttributes = payload.keyAttributes ?: throw IllegalStateException("Invalid response")
- val secrets = withContext(Dispatchers.Default) {
- EnsuCryptoBridge.srpDecryptSecrets(
- srpM2 = response.srpM2.orEmpty(),
- keyAttributes = keyAttributes.toCrypto(),
- encryptedToken = payload.encryptedToken,
- plainToken = payload.token
- )
- }
-
- storeSecrets(email, payload.userId, secrets)
- logRepository.log(LogLevel.Info, "SRP login success", tag = "Auth")
- return SrpLoginResult(null, null, null)
- } finally {
- EnsuCryptoBridge.srpClear()
- }
- }
-
- suspend fun loginAfterChallenge(
- email: String,
- password: String,
- srpAttributes: SrpAttributes,
- userId: Long,
- keyAttributes: KeyAttributes,
- encryptedToken: String?,
- token: String?
- ) {
- val kek = withContext(Dispatchers.Default) {
- EnsuCryptoBridge.deriveKekForLogin(
- password = password,
- kekSalt = srpAttributes.kekSalt,
- memLimit = srpAttributes.memLimit,
- opsLimit = srpAttributes.opsLimit
- )
- }
-
- val secrets = try {
- withContext(Dispatchers.Default) {
- EnsuCryptoBridge.decryptSecretsWithKek(
- kek = kek,
- keyAttributes = keyAttributes.toCrypto(),
- encryptedToken = encryptedToken,
- plainToken = token
- )
- }
- } finally {
- // Best-effort zeroing of sensitive material after use.
- kek.fill(0)
- }
-
- storeSecrets(email, userId, secrets)
- logRepository.log(LogLevel.Info, "Login after challenge success", tag = "Auth")
- }
-
- suspend fun clearCredentials() {
- credentialStore.clear()
- }
-
- private suspend fun pingEndpoint(endpoint: HttpUrl) {
- withContext(Dispatchers.IO) {
- val url = endpoint.newBuilder().addPathSegment("ping").build()
- val request = Request.Builder().url(url).get().build()
- okHttpClient.newCall(request).execute().use { response ->
- if (!response.isSuccessful) {
- throw IllegalStateException("Ping failed")
- }
- val body = response.body?.string().orEmpty()
- val json = JSONObject(body)
- if (json.optString("message") != "pong") {
- throw IllegalStateException("Invalid ping response")
- }
- }
- }
- }
-
- private suspend fun storeSecrets(email: String, userId: Long, secrets: AuthSecrets) {
- val masterKey = secrets.masterKey.toUByteArray().toByteArray()
- val secretKey = secrets.secretKey.toUByteArray().toByteArray()
- val tokenBytes = secrets.token.toUByteArray().toByteArray()
- val token = Base64.encodeToString(tokenBytes, Base64.NO_WRAP or Base64.URL_SAFE)
-
- credentialStore.save(email, userId, masterKey, secretKey, token)
-
- // Best-effort zeroing of sensitive material after persisting.
- masterKey.fill(0)
- secretKey.fill(0)
- tokenBytes.fill(0)
- }
-
- private fun normalize(value: String): String {
- var trimmed = value.trim()
- while (trimmed.endsWith("/")) {
- trimmed = trimmed.dropLast(1)
- }
- return trimmed
- }
-}
-
-class PasskeySessionNotVerifiedException : Exception()
-class PasskeySessionExpiredException : Exception()
-class AccountNotFoundException : Exception()
-
-private fun SrpAttributes.toCrypto(): CryptoSrpAttributes {
- return CryptoSrpAttributes(
- srpUserId = srpUserId,
- srpSalt = srpSalt,
- kekSalt = kekSalt,
- memLimit = memLimit.toUInt(),
- opsLimit = opsLimit.toUInt(),
- isEmailMfaEnabled = isEmailMfaEnabled
- )
-}
-
-private fun KeyAttributes.toCrypto(): CryptoKeyAttributes {
- return CryptoKeyAttributes(
- kekSalt = kekSalt,
- encryptedKey = encryptedKey,
- keyDecryptionNonce = keyDecryptionNonce,
- publicKey = publicKey,
- encryptedSecretKey = encryptedSecretKey,
- secretKeyDecryptionNonce = secretKeyDecryptionNonce,
- memLimit = memLimit?.toUInt(),
- opsLimit = opsLimit?.toUInt()
- )
-}
-
-private fun AuthorizationResponse.toPayload(): AuthResponsePayload {
- val attrs = keyAttributes?.let {
- KeyAttributes(
- kekSalt = it.kekSalt,
- encryptedKey = it.encryptedKey,
- keyDecryptionNonce = it.keyDecryptionNonce,
- publicKey = it.publicKey,
- encryptedSecretKey = it.encryptedSecretKey,
- secretKeyDecryptionNonce = it.secretKeyDecryptionNonce,
- memLimit = it.memLimit,
- opsLimit = it.opsLimit
- )
- }
- return AuthResponsePayload(
- userId = id,
- keyAttributes = attrs,
- encryptedToken = encryptedToken,
- token = token,
- twoFactorSessionId = effectiveTwoFactorSessionId,
- passkeySessionId = passkeySessionId,
- accountsUrl = accountsUrl
- )
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthTokenProvider.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthTokenProvider.kt
deleted file mode 100644
index 44e8ab5925..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthTokenProvider.kt
+++ /dev/null
@@ -1,8 +0,0 @@
-package io.ente.ensu.data.auth
-
-import io.ente.ensu.data.network.AuthTokenProvider
-import io.ente.ensu.data.storage.CredentialStore
-
-class EnsuAuthTokenProvider(private val credentialStore: CredentialStore) : AuthTokenProvider {
- override suspend fun getAuthToken(): String? = credentialStore.getToken()
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/ApiClient.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/ApiClient.kt
deleted file mode 100644
index 9881ab6ed4..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/ApiClient.kt
+++ /dev/null
@@ -1,32 +0,0 @@
-package io.ente.ensu.data.network
-
-import android.content.Context
-import kotlinx.serialization.KSerializer
-
-class ApiClient(
- context: Context,
- configuration: NetworkConfiguration,
- private val authTokenProvider: AuthTokenProvider? = null,
- private val httpClient: HttpClient = HttpClient()
-) {
- private val endpointResolver = EndpointResolver(configuration)
- private val headersManager = RequestHeadersManager(context)
-
- suspend fun <T> request(endpoint: ApiEndpoint, serializer: KSerializer<T>): T {
- val url = endpointResolver.resolve(endpoint)
- val headers = headersManager.buildHeaders(authTokenProvider).toMutableMap()
- endpoint.headers?.forEach { (key, value) -> headers.putIfAbsent(key, value) }
-
- return httpClient.request(
- url = url,
- method = endpoint.method,
- parameters = endpoint.parameters,
- headers = headers,
- responseSerializer = serializer
- )
- }
-
- suspend fun request(endpoint: ApiEndpoint) {
- request(endpoint, EmptyResponse.serializer())
- }
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/ApiDomain.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/ApiDomain.kt
deleted file mode 100644
index 8632fe00d9..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/ApiDomain.kt
+++ /dev/null
@@ -1,9 +0,0 @@
-package io.ente.ensu.data.network
-
-enum class ApiDomain {
- Api,
- Accounts,
- Cast,
- PublicAlbums,
- Family
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/ApiEndpoint.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/ApiEndpoint.kt
deleted file mode 100644
index 31405603ca..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/ApiEndpoint.kt
+++ /dev/null
@@ -1,51 +0,0 @@
-package io.ente.ensu.data.network
-
-interface ApiEndpoint {
- val domain: ApiDomain
- val path: String
- val method: HttpMethod
- val parameters: Map<String, Any?>?
- val headers: Map<String, String>?
-}
-
-sealed class AuthEndpoint : ApiEndpoint {
- data class GetSrpAttributes(val email: String) : AuthEndpoint()
- data class CreateSrpSession(val srpUserId: String, val clientPub: String) : AuthEndpoint()
- data class VerifySrpSession(val srpUserId: String, val sessionId: String, val clientM1: String) : AuthEndpoint()
- data class SendLoginOtp(val email: String, val purpose: String) : AuthEndpoint()
- data class VerifyEmail(val email: String, val otp: String) : AuthEndpoint()
- data class VerifyTotp(val sessionId: String, val otp: String) : AuthEndpoint()
- data class GetTokenForPasskeySession(val sessionId: String) : AuthEndpoint()
-
- override val domain: ApiDomain = ApiDomain.Api
-
- override val path: String
- get() = when (this) {
- is GetSrpAttributes -> "/users/srp/attributes"
- is CreateSrpSession -> "/users/srp/create-session"
- is VerifySrpSession -> "/users/srp/verify-session"
- is SendLoginOtp -> "/users/ott"
- is VerifyEmail -> "/users/verify-email"
- is VerifyTotp -> "/users/two-factor/verify"
- is GetTokenForPasskeySession -> "/users/two-factor/passkeys/get-token"
- }
-
- override val method: HttpMethod
- get() = when (this) {
- is GetSrpAttributes, is GetTokenForPasskeySession -> HttpMethod.GET
- is CreateSrpSession, is VerifySrpSession, is SendLoginOtp, is VerifyEmail, is VerifyTotp -> HttpMethod.POST
- }
-
- override val parameters: Map<String, Any?>?
- get() = when (this) {
- is GetSrpAttributes -> mapOf("email" to email)
- is CreateSrpSession -> mapOf("srpUserID" to srpUserId, "srpA" to clientPub)
- is VerifySrpSession -> mapOf("srpUserID" to srpUserId, "sessionID" to sessionId, "srpM1" to clientM1)
- is SendLoginOtp -> mapOf("email" to email, "purpose" to purpose)
- is VerifyEmail -> mapOf("email" to email, "ott" to otp)
- is VerifyTotp -> mapOf("sessionID" to sessionId, "code" to otp)
- is GetTokenForPasskeySession -> mapOf("sessionID" to sessionId)
- }
-
- override val headers: Map<String, String>? = null
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/AuthTokenProvider.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/AuthTokenProvider.kt
deleted file mode 100644
index 502b4ae107..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/AuthTokenProvider.kt
+++ /dev/null
@@ -1,5 +0,0 @@
-package io.ente.ensu.data.network
-
-interface AuthTokenProvider {
- suspend fun getAuthToken(): String?
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/AuthenticationGateway.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/AuthenticationGateway.kt
deleted file mode 100644
index 6234e37fa6..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/AuthenticationGateway.kt
+++ /dev/null
@@ -1,92 +0,0 @@
-package io.ente.ensu.data.network
-
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
-
-internal class AuthenticationGateway(private val client: ApiClient) {
- suspend fun getSrpAttributes(email: String): SrpAttributesResponse {
- return client.request(AuthEndpoint.GetSrpAttributes(email), SrpAttributesResponse.serializer())
- }
-
- suspend fun createSrpSession(srpUserId: String, clientPub: String): CreateSrpSessionResponse {
- return client.request(
- AuthEndpoint.CreateSrpSession(srpUserId, clientPub),
- CreateSrpSessionResponse.serializer()
- )
- }
-
- suspend fun verifySrpSession(srpUserId: String, sessionId: String, clientM1: String): AuthorizationResponse {
- return client.request(
- AuthEndpoint.VerifySrpSession(srpUserId, sessionId, clientM1),
- AuthorizationResponse.serializer()
- )
- }
-
- suspend fun sendLoginOtp(email: String, purpose: String = "login") {
- client.request(AuthEndpoint.SendLoginOtp(email, purpose))
- }
-
- suspend fun verifyEmail(email: String, otp: String): AuthorizationResponse {
- return client.request(AuthEndpoint.VerifyEmail(email, otp), AuthorizationResponse.serializer())
- }
-
- suspend fun verifyTotp(sessionId: String, otp: String): AuthorizationResponse {
- return client.request(AuthEndpoint.VerifyTotp(sessionId, otp), AuthorizationResponse.serializer())
- }
-
- suspend fun getTokenForPasskeySession(sessionId: String): AuthorizationResponse {
- return client.request(
- AuthEndpoint.GetTokenForPasskeySession(sessionId),
- AuthorizationResponse.serializer()
- )
- }
-}
-
-@Serializable
-internal data class SrpAttributesResponse(
- @SerialName("attributes") val attributes: SrpAttributesDto
-)
-
-@Serializable
-internal data class SrpAttributesDto(
- @SerialName("srpUserID") val srpUserId: String,
- @SerialName("srpSalt") val srpSalt: String,
- @SerialName("kekSalt") val kekSalt: String,
- @SerialName("memLimit") val memLimit: Int,
- @SerialName("opsLimit") val opsLimit: Int,
- @SerialName("isEmailMFAEnabled") val isEmailMfaEnabled: Boolean
-)
-
-@Serializable
-internal data class CreateSrpSessionResponse(
- @SerialName("sessionID") val sessionId: String,
- @SerialName("srpB") val srpB: String
-)
-
-@Serializable
-internal data class KeyAttributesDto(
- @SerialName("kekSalt") val kekSalt: String,
- @SerialName("encryptedKey") val encryptedKey: String,
- @SerialName("keyDecryptionNonce") val keyDecryptionNonce: String,
- @SerialName("publicKey") val publicKey: String,
- @SerialName("encryptedSecretKey") val encryptedSecretKey: String,
- @SerialName("secretKeyDecryptionNonce") val secretKeyDecryptionNonce: String,
- @SerialName("memLimit") val memLimit: Int? = null,
- @SerialName("opsLimit") val opsLimit: Int? = null
-)
-
-@Serializable
-internal data class AuthorizationResponse(
- @SerialName("keyAttributes") val keyAttributes: KeyAttributesDto? = null,
- @SerialName("encryptedToken") val encryptedToken: String? = null,
- @SerialName("token") val token: String? = null,
- @SerialName("srpM2") val srpM2: String? = null,
- @SerialName("twoFactorSessionID") val twoFactorSessionId: String? = null,
- @SerialName("twoFactorSessionIDV2") val twoFactorSessionIdV2: String? = null,
- @SerialName("passkeySessionID") val passkeySessionId: String? = null,
- @SerialName("accountsUrl") val accountsUrl: String? = null,
- @SerialName("id") val id: Long
-) {
- val effectiveTwoFactorSessionId: String?
- get() = twoFactorSessionIdV2 ?: twoFactorSessionId
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/EndpointResolver.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/EndpointResolver.kt
deleted file mode 100644
index f2d20869d5..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/EndpointResolver.kt
+++ /dev/null
@@ -1,20 +0,0 @@
-package io.ente.ensu.data.network
-
-import okhttp3.HttpUrl
-
-class EndpointResolver(private val configuration: NetworkConfiguration) {
- fun resolve(endpoint: ApiEndpoint): HttpUrl {
- val base = when (endpoint.domain) {
- ApiDomain.Api -> configuration.apiEndpoint
- ApiDomain.Accounts -> configuration.accountsEndpoint ?: configuration.apiEndpoint
- ApiDomain.Cast -> configuration.castEndpoint ?: configuration.apiEndpoint
- ApiDomain.PublicAlbums -> configuration.publicAlbumsEndpoint ?: configuration.apiEndpoint
- ApiDomain.Family -> configuration.familyEndpoint ?: configuration.apiEndpoint
- }
-
- val trimmedPath = endpoint.path.trimStart('/')
- return base.newBuilder()
- .addEncodedPathSegments(trimmedPath)
- .build()
- }
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/HttpClient.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/HttpClient.kt
deleted file mode 100644
index 77fe57503b..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/HttpClient.kt
+++ /dev/null
@@ -1,67 +0,0 @@
-package io.ente.ensu.data.network
-
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.withContext
-import kotlinx.serialization.KSerializer
-import kotlinx.serialization.json.Json
-import okhttp3.MediaType.Companion.toMediaType
-import okhttp3.OkHttpClient
-import okhttp3.Request
-import okhttp3.RequestBody.Companion.toRequestBody
-import org.json.JSONObject
-
-class HttpClient(
- private val client: OkHttpClient = OkHttpClient()
-) {
- private val json = Json { ignoreUnknownKeys = true }
- private val jsonMediaType = "application/json; charset=utf-8".toMediaType()
-
- suspend fun <T> request(
- url: okhttp3.HttpUrl,
- method: HttpMethod,
- parameters: Map<String, Any?>? = null,
- headers: Map<String, String>? = null,
- responseSerializer: KSerializer<T>
- ): T = withContext(Dispatchers.IO) {
- val finalUrl = if (method == HttpMethod.GET && parameters != null) {
- val builder = url.newBuilder()
- parameters.forEach { (key, value) ->
- builder.addQueryParameter(key, value?.toString())
- }
- builder.build()
- } else {
- url
- }
-
- val body = if (method == HttpMethod.POST || method == HttpMethod.PUT || method == HttpMethod.PATCH) {
- val payload = JSONObject(parameters ?: emptyMap<String, Any>()).toString()
- payload.toRequestBody(jsonMediaType)
- } else {
- null
- }
-
- val requestBuilder = Request.Builder().url(finalUrl).method(method.value, body)
- headers?.forEach { (key, value) -> requestBuilder.addHeader(key, value) }
-
- val response = client.newCall(requestBuilder.build()).execute()
- val responseBody = response.body?.string().orEmpty()
-
- if (!response.isSuccessful) {
- val message = runCatching {
- json.decodeFromString(ErrorResponse.serializer(), responseBody).message
- }.getOrNull()
- throw ApiException(response.code, message)
- }
-
- if (responseSerializer == EmptyResponse.serializer()) {
- @Suppress("UNCHECKED_CAST")
- return@withContext EmptyResponse as T
- }
-
- return@withContext try {
- json.decodeFromString(responseSerializer, responseBody)
- } catch (error: Exception) {
- throw InvalidResponseException(error.message ?: "Invalid response")
- }
- }
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/HttpMethod.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/HttpMethod.kt
deleted file mode 100644
index b645f1a747..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/HttpMethod.kt
+++ /dev/null
@@ -1,9 +0,0 @@
-package io.ente.ensu.data.network
-
-enum class HttpMethod(val value: String) {
- GET("GET"),
- POST("POST"),
- PUT("PUT"),
- DELETE("DELETE"),
- PATCH("PATCH")
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkConfiguration.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkConfiguration.kt
deleted file mode 100644
index 4d99b2ba12..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkConfiguration.kt
+++ /dev/null
@@ -1,34 +0,0 @@
-package io.ente.ensu.data.network
-
-import okhttp3.HttpUrl
-import okhttp3.HttpUrl.Companion.toHttpUrl
-
-
-data class NetworkConfiguration(
- val apiEndpoint: HttpUrl,
- val accountsEndpoint: HttpUrl? = null,
- val castEndpoint: HttpUrl? = null,
- val publicAlbumsEndpoint: HttpUrl? = null,
- val familyEndpoint: HttpUrl? = null
-) {
- companion object {
- fun selfHosted(baseUrl: HttpUrl): NetworkConfiguration {
- val normalized = baseUrl.newBuilder().build()
- return NetworkConfiguration(
- apiEndpoint = normalized,
- accountsEndpoint = normalized.newBuilder().addPathSegment("accounts").build(),
- castEndpoint = normalized.newBuilder().addPathSegment("cast").build(),
- publicAlbumsEndpoint = normalized.newBuilder().addPathSegment("public-albums").build(),
- familyEndpoint = normalized.newBuilder().addPathSegment("family").build()
- )
- }
-
- val default: NetworkConfiguration = NetworkConfiguration(
- apiEndpoint = "https://api.ente.com".toHttpUrl(),
- accountsEndpoint = "https://accounts.ente.com".toHttpUrl(),
- castEndpoint = "https://api.ente.com".toHttpUrl(),
- publicAlbumsEndpoint = "https://albums.ente.com".toHttpUrl(),
- familyEndpoint = "https://family.ente.io".toHttpUrl()
- )
- }
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkErrors.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkErrors.kt
deleted file mode 100644
index 1c275cfa04..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkErrors.kt
+++ /dev/null
@@ -1,5 +0,0 @@
-package io.ente.ensu.data.network
-
-class ApiException(val code: Int, message: String?) : Exception(message)
-
-class InvalidResponseException(message: String = "Invalid server response") : Exception(message)
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkFactory.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkFactory.kt
deleted file mode 100644
index 8aaf9db76e..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkFactory.kt
+++ /dev/null
@@ -1,17 +0,0 @@
-package io.ente.ensu.data.network
-
-import android.content.Context
-
-internal class NetworkFactory(
- context: Context,
- val configuration: NetworkConfiguration,
- authTokenProvider: AuthTokenProvider? = null
-) {
- private val client = ApiClient(
- context = context,
- configuration = configuration,
- authTokenProvider = authTokenProvider
- )
-
- val authentication: AuthenticationGateway = AuthenticationGateway(client)
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkResponses.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkResponses.kt
deleted file mode 100644
index c1bc4a0ffa..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkResponses.kt
+++ /dev/null
@@ -1,13 +0,0 @@
-package io.ente.ensu.data.network
-
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
-
-@Serializable
-object EmptyResponse
-
-@Serializable
-data class ErrorResponse(
- @SerialName("code") val code: String? = null,
- @SerialName("message") val message: String
-)
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/RequestHeadersManager.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/RequestHeadersManager.kt
deleted file mode 100644
index b0054df311..0000000000
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/RequestHeadersManager.kt
+++ /dev/null
@@ -1,27 +0,0 @@
-package io.ente.ensu.data.network
-
-import android.content.Context
-import java.util.UUID
-
-class RequestHeadersManager(private val context: Context) {
- suspend fun buildHeaders(authTokenProvider: AuthTokenProvider? = null): Map<String, String> {
- val headers = mutableMapOf<String, String>()
- headers["User-Agent"] = "EnteNative-Android"
- headers["X-Client-Package"] = context.packageName
- headers["x-request-id"] = UUID.randomUUID().toString()
-
- val versionName = runCatching {
- context.packageManager.getPackageInfo(context.packageName, 0).versionName
- }.getOrNull()
- if (!versionName.isNullOrBlank()) {
- headers["X-Client-Version"] = versionName
- }
-
- val token = authTokenProvider?.getAuthToken()
- if (!token.isNullOrBlank()) {
- headers["X-Auth-Token"] = token
- }
-
- return headers
- }
-}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/CredentialStore.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/CredentialStore.kt
index 878400e0d4..f8e76b3257 100644
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/CredentialStore.kt
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/CredentialStore.kt
@@ -18,62 +18,14 @@ class CredentialStore(context: Context) {
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
- fun save(email: String, userId: Long, masterKey: ByteArray, secretKey: ByteArray, token: String) {
- prefs.edit()
- .putString(KEY_EMAIL, email)
- .putLong(KEY_USER_ID, userId)
- .putString(KEY_MASTER_KEY, encode(masterKey))
- .putString(KEY_SECRET_KEY, encode(secretKey))
- .putString(KEY_TOKEN, token)
- .apply()
- }
-
- fun clear() {
- val chatDbKey = prefs.getString(KEY_CHAT_DB_KEY, null)
- val userId = getUserId()
- prefs.edit().clear().apply()
- val editor = prefs.edit()
- if (chatDbKey != null) {
- editor.putString(KEY_CHAT_DB_KEY, chatDbKey)
- }
- if (userId != null) {
- editor.putLong(KEY_LAST_USER_ID, userId)
- }
- editor.apply()
- }
-
- fun clearAll() {
- prefs.edit().clear().apply()
- }
-
- fun isSameUser(newUserId: Long): Boolean {
- val lastId = prefs.getLong(KEY_LAST_USER_ID, -1L)
- return lastId == -1L || lastId == newUserId
- }
-
- fun getEmail(): String? = prefs.getString(KEY_EMAIL, null)
-
- fun getToken(): String? = prefs.getString(KEY_TOKEN, null)
-
- fun getMasterKey(): ByteArray? = prefs.getString(KEY_MASTER_KEY, null)?.let(::decode)
-
- fun getSecretKey(): ByteArray? = prefs.getString(KEY_SECRET_KEY, null)?.let(::decode)
-
- /**
- * Returns a stable 32-byte key for encrypting the local chat DB.
- *
- * Rules:
- * - If already stored, reuse it.
- * - Else, if the account master key exists and is 32 bytes, pin it as the chat DB key.
- * - Else, generate a random 32-byte key and persist it.
- */
fun getOrCreateChatDbKey(): ByteArray {
prefs.getString(KEY_CHAT_DB_KEY, null)?.let { existing ->
val decoded = runCatching { decode(existing) }.getOrNull()
if (decoded != null && decoded.size == 32) return decoded
}
- val fromMaster = getMasterKey()
+ val fromMaster = prefs.getString(KEY_MASTER_KEY, null)
+ ?.let { runCatching { decode(it) }.getOrNull() }
if (fromMaster != null && fromMaster.size == 32) {
prefs.edit().putString(KEY_CHAT_DB_KEY, encode(fromMaster)).apply()
return fromMaster
@@ -85,14 +37,6 @@ class CredentialStore(context: Context) {
return generated
}
- fun getUserId(): Long? {
- val value = prefs.getLong(KEY_USER_ID, -1)
- return if (value == -1L) null else value
- }
-
- fun isLoggedIn(): Boolean =
- !getToken().isNullOrBlank() && !prefs.getString(KEY_MASTER_KEY, null).isNullOrBlank()
-
private fun encode(bytes: ByteArray): String {
return Base64.encodeToString(bytes, Base64.NO_WRAP or Base64.URL_SAFE)
}
@@ -102,12 +46,7 @@ class CredentialStore(context: Context) {
}
companion object {
- private const val KEY_EMAIL = "email"
- private const val KEY_USER_ID = "user_id"
private const val KEY_MASTER_KEY = "master_key"
- private const val KEY_SECRET_KEY = "secret_key"
- private const val KEY_TOKEN = "token"
private const val KEY_CHAT_DB_KEY = "chat_db_key"
- private const val KEY_LAST_USER_ID = "last_user_id"
}
}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/AuthState.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/AuthState.kt
deleted file mode 100644
index 62ebfed4f7..0000000000
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/AuthState.kt
+++ /dev/null
@@ -1,6 +0,0 @@
-package io.ente.ensu.domain.model
-
-data class AuthState(
- val isLoggedIn: Boolean = false,
- val email: String? = null
-)
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/AppState.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/AppState.kt
index 33b7af9159..9759dbdbcb 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/AppState.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/AppState.kt
@@ -1,10 +1,6 @@
package io.ente.ensu.domain.state
-import io.ente.ensu.domain.model.AuthState
-
-
data class AppState(
- val auth: AuthState = AuthState(),
val chat: ChatState = ChatState(),
val developerSettings: DeveloperSettingsState = DeveloperSettingsState(),
val modelSettings: ModelSettingsState = ModelSettingsState()
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt
index de272f16e9..88cfab8879 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt
@@ -49,8 +49,6 @@ class AppStore(
modelSettingsActions = modelSettingsActions,
ensuDefaults = ensuDefaults
)
- private val authActions = AuthStoreActions(_state, logRepository)
-
fun bootstrap(scope: CoroutineScope) {
chatActions.setScope(scope)
attachmentActions.setScope(scope)
@@ -181,13 +179,6 @@ class AppStore(
modelSettingsActions.hydratePersistedModelSettings(modelSettings)
}
- fun signIn(email: String) = authActions.signIn(email)
-
- fun signOut() {
- authActions.signOut()
- chatActions.handleLogout()
- }
-
fun cancelAttachmentDownload(attachmentId: String) =
attachmentActions.cancelAttachmentDownload(attachmentId)
}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AuthStoreActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AuthStoreActions.kt
deleted file mode 100644
index eb21c1559c..0000000000
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AuthStoreActions.kt
+++ /dev/null
@@ -1,28 +0,0 @@
-package io.ente.ensu.domain.store
-
-import io.ente.ensu.domain.logging.LogRepository
-import io.ente.ensu.domain.model.AuthState
-import io.ente.ensu.domain.model.LogLevel
-import io.ente.ensu.domain.state.AppState
-import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.update
-
-internal class AuthStoreActions(
- private val state: MutableStateFlow<AppState>,
- private val logRepository: LogRepository
-) {
- fun signIn(email: String) {
- state.update { appState ->
- appState.copy(auth = AuthState(isLoggedIn = true, email = email))
- }
- // Do not log PII like user email.
- logRepository.log(LogLevel.Info, "Signed in", tag = "Auth")
- }
-
- fun signOut() {
- state.update { appState ->
- appState.copy(auth = AuthState())
- }
- logRepository.log(LogLevel.Info, "Signed out", tag = "Auth")
- }
-}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt
index 3b4f91fedb..f1e6b866a0 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt
@@ -389,37 +389,6 @@ internal class ChatStoreActions(
resetGenerationState()
}
- fun handleLogout() {
- resetGenerationState()
- pendingOverflow = null
- overflowBypassMessageId = null
- streamingParentId = null
- messageStore.clear()
- branchSelections.clear()
- sessionAccessTimes.clear()
-
- state.update { appState ->
- appState.copy(
- chat = appState.chat.copy(
- sessions = emptyList(),
- currentSessionId = null,
- messages = emptyList(),
- branchSelections = emptyMap(),
- messageText = "",
- attachments = emptyList(),
- editingMessageId = null,
- isProcessingAttachments = false,
- attachmentDownloads = emptyList(),
- attachmentDownloadProgress = null,
- isAttachmentDownloadBlocked = false
- )
- )
- }
-
- attachmentActions.refreshAttachmentDownloadState()
- loadSessionsFromDb()
- }
-
fun loadSessionsFromDb() {
val scope = scope ?: return
scope.launch(Dispatchers.IO) {
diff --git a/mobile/native/android/apps/ensu/settings.gradle.kts b/mobile/native/android/apps/ensu/settings.gradle.kts
index b7473a2b63..aad9c73e73 100644
--- a/mobile/native/android/apps/ensu/settings.gradle.kts
+++ b/mobile/native/android/apps/ensu/settings.gradle.kts
@@ -16,6 +16,6 @@ dependencyResolutionManagement {
}
rootProject.name = "ensu"
-include(":app-ui", ":domain", ":data", ":crypto-auth-core", ":rust")
+include(":app-ui", ":domain", ":data", ":rust")
project(":rust").projectDir = file("../../packages/rust")
diff --git a/mobile/native/android/packages/rust/scripts/build-rust.sh b/mobile/native/android/packages/rust/scripts/build-rust.sh
index baf063b79c..ffb519c99e 100755
--- a/mobile/native/android/packages/rust/scripts/build-rust.sh
+++ b/mobile/native/android/packages/rust/scripts/build-rust.sh
@@ -11,7 +11,6 @@ TOOLCHAIN=""
OUT_DIR=""
CRATES=(
- bindings/uniffi/core
bindings/uniffi/ensu/db
bindings/uniffi/ensu/inference
bindings/uniffi/ensu/transcription
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu.xcodeproj/project.pbxproj b/mobile/native/darwin/Apps/Ensu/Ensu.xcodeproj/project.pbxproj
index ffd23feac7..0289e9184d 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu.xcodeproj/project.pbxproj
+++ b/mobile/native/darwin/Apps/Ensu/Ensu.xcodeproj/project.pbxproj
@@ -8,7 +8,7 @@
/* Begin PBXBuildFile section */
A10000012F11111100AA0001 /* InferenceIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A10000022F11111100AA0001 /* InferenceIntegrationTests.swift */; };
- DACC3DC92E618D6A00DAF993 /* EnteNetwork in Frameworks */ = {isa = PBXBuildFile; productRef = DACC3DC82E618D6A00DAF993 /* EnteNetwork */; };
+ DACC3DCA2E618D6A00DAF993 /* EnteCore in Frameworks */ = {isa = PBXBuildFile; productRef = DACC3DCB2E618D6A00DAF993 /* EnteCore */; };
DAF584672E61BB8300F8A08F /* ZIPFoundation in Frameworks */ = {isa = PBXBuildFile; productRef = DAF584662E61BB8300F8A08F /* ZIPFoundation */; };
DB9F1C3C2F9D123400ABCD02 /* Markdown in Frameworks */ = {isa = PBXBuildFile; productRef = DB9F1C3B2F9D123400ABCD02 /* Markdown */; };
DBA3E91C2F7A6B9000AA11BB /* SwiftMath in Frameworks */ = {isa = PBXBuildFile; productRef = DBA3E91B2F7A6B9000AA11BB /* SwiftMath */; };
@@ -64,7 +64,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
- DACC3DC92E618D6A00DAF993 /* EnteNetwork in Frameworks */,
+ DACC3DCA2E618D6A00DAF993 /* EnteCore in Frameworks */,
DAF584672E61BB8300F8A08F /* ZIPFoundation in Frameworks */,
DBA3E91C2F7A6B9000AA11BB /* SwiftMath in Frameworks */,
DB9F1C3C2F9D123400ABCD02 /* Markdown in Frameworks */,
@@ -136,7 +136,7 @@
isa = PBXNativeTarget;
buildConfigurationList = DA72BC872E5F87A100D128FF /* Build configuration list for PBXNativeTarget "Ensu" */;
buildPhases = (
- CC142736A470612F436ECF8E /* Build Rust (core/db/inference/transcription) */,
+ CC142736A470612F436ECF8E /* Build Rust (db/inference/transcription) */,
DA72BC5D2E5F87A000D128FF /* Sources */,
DA72BC5E2E5F87A000D128FF /* Frameworks */,
DA72BC5F2E5F87A000D128FF /* Resources */,
@@ -150,7 +150,7 @@
);
name = Ensu;
packageProductDependencies = (
- DACC3DC82E618D6A00DAF993 /* EnteNetwork */,
+ DACC3DCB2E618D6A00DAF993 /* EnteCore */,
DAF584662E61BB8300F8A08F /* ZIPFoundation */,
DBA3E91B2F7A6B9000AA11BB /* SwiftMath */,
DB9F1C3B2F9D123400ABCD02 /* Markdown */,
@@ -189,7 +189,7 @@
mainGroup = DA72BC582E5F87A000D128FF;
minimizedProjectReferenceProxies = 1;
packageReferences = (
- DACC3DC62E618D5300DAF993 /* XCLocalSwiftPackageReference "../../Packages/EnteNetwork" */,
+ DACC3DCC2E618D5300DAF993 /* XCLocalSwiftPackageReference "../../Packages/EnteCore" */,
DBA3E91A2F7A6B9000AA11BB /* XCRemoteSwiftPackageReference "SwiftMath" */,
DAF584652E61BB6300F8A08F /* XCRemoteSwiftPackageReference "ZIPFoundation" */,
DB9F1C3A2F9D123400ABCD02 /* XCRemoteSwiftPackageReference "swift-markdown" */,
@@ -224,24 +224,22 @@
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
- CC142736A470612F436ECF8E /* Build Rust (core/db/inference/transcription) */ = {
+ CC142736A470612F436ECF8E /* Build Rust (db/inference/transcription) */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
- name = "Build Rust (core/db/inference/transcription)";
+ name = "Build Rust (db/inference/transcription)";
outputPaths = (
- "$(TARGET_TEMP_DIR)/ensu_rust/libcore.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libdb.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libinference.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libtranscription.a",
- "$(SRCROOT)/Ensu/Generated/EndpointConfig.swift",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
- shellScript = "ENTE_API_ENDPOINT=\"${ENTE_API_ENDPOINT}\" bash \"${SRCROOT}/scripts/build-rust.sh\"\n";
+ shellScript = "bash \"${SRCROOT}/scripts/build-rust.sh\"\n";
};
/* End PBXShellScriptBuildPhase section */
@@ -287,7 +285,7 @@
);
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
MARKETING_VERSION = 0.1.18;
- OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/coreFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
+ OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu.tests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
@@ -313,7 +311,7 @@
);
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
MARKETING_VERSION = 0.1.18;
- OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/coreFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
+ OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu.tests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
@@ -459,7 +457,6 @@
DEVELOPMENT_TEAM = 6Z68YJY9Q2;
ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
- ENTE_API_ENDPOINT = "";
GENERATE_INFOPLIST_FILE = NO;
HEADER_SEARCH_PATHS = (
"$(inherited)",
@@ -488,13 +485,11 @@
Metal,
"-framework",
MetalKit,
- "-force_load",
- "$(TARGET_TEMP_DIR)/ensu_rust/libcore.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libdb.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libinference.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libtranscription.a",
);
- OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/coreFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
+ OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
@@ -517,7 +512,6 @@
DEVELOPMENT_TEAM = 6Z68YJY9Q2;
ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
- ENTE_API_ENDPOINT = "";
GENERATE_INFOPLIST_FILE = NO;
HEADER_SEARCH_PATHS = (
"$(inherited)",
@@ -546,13 +540,11 @@
Metal,
"-framework",
MetalKit,
- "-force_load",
- "$(TARGET_TEMP_DIR)/ensu_rust/libcore.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libdb.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libinference.a",
"$(TARGET_TEMP_DIR)/ensu_rust/libtranscription.a",
);
- OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/coreFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
+ OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/dbFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/inferenceFFI.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Ensu/Generated/transcriptionFFI.modulemap";
PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "$(APP_STORE_PROFILE_SPECIFIER)";
@@ -596,9 +588,9 @@
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
- DACC3DC62E618D5300DAF993 /* XCLocalSwiftPackageReference "../../Packages/EnteNetwork" */ = {
+ DACC3DCC2E618D5300DAF993 /* XCLocalSwiftPackageReference "../../Packages/EnteCore" */ = {
isa = XCLocalSwiftPackageReference;
- relativePath = ../../Packages/EnteNetwork;
+ relativePath = ../../Packages/EnteCore;
};
/* End XCLocalSwiftPackageReference section */
@@ -638,9 +630,9 @@
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
- DACC3DC82E618D6A00DAF993 /* EnteNetwork */ = {
+ DACC3DCB2E618D6A00DAF993 /* EnteCore */ = {
isa = XCSwiftPackageProductDependency;
- productName = EnteNetwork;
+ productName = EnteCore;
};
DAF584662E61BB8300F8A08F /* ZIPFoundation */ = {
isa = XCSwiftPackageProductDependency;
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/AuthFlowView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Auth/AuthFlowView.swift
deleted file mode 100644
index ba94dd67ff..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/AuthFlowView.swift
+++ /dev/null
@@ -1,244 +0,0 @@
-import SwiftUI
-
-#if canImport(EnteCore)
-enum AuthRoute: Hashable {
- case otp(email: String, srp: SrpAttributes)
- case password(email: String, srp: SrpAttributes)
-
- case twoFactor(email: String, srp: SrpAttributes, sessionId: String, password: String?)
- case passkey(email: String, srp: SrpAttributes, sessionId: String, accountsUrl: String, twoFactorSessionId: String?, password: String?)
-
- case passwordAfterMfa(email: String, srp: SrpAttributes, userId: Int64, keyAttributes: KeyAttributes, encryptedToken: String?, token: String?)
- case passkeyPasswordReentry(email: String, srp: SrpAttributes, auth: AuthResponsePayload)
-}
-
-struct AuthFlowView: View {
- @EnvironmentObject private var appState: EnsuAppState
- @Environment(\.dismiss) private var dismiss
-
- @State private var path: [AuthRoute] = []
-
- private var backButtonInset: CGFloat {
- EnsuSpacing.md
- }
-
- private var leadingPlacement: ToolbarItemPlacement {
- #if os(iOS)
- .navigationBarLeading
- #else
- .navigation
- #endif
- }
-
- private var trailingPlacement: ToolbarItemPlacement {
- #if os(iOS)
- .navigationBarTrailing
- #else
- .primaryAction
- #endif
- }
-
- var body: some View {
- Group {
- #if os(iOS)
- NavigationStack(path: $path) {
- rootView
- }
- #else
- macContent
- #endif
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
- .background(EnsuColor.backgroundBase.ignoresSafeArea())
- #if os(macOS)
- .safeAreaInset(edge: .top) {
- MacSheetHeader(
- leading: {
- if !path.isEmpty {
- Button {
- path.removeLast()
- } label: {
- HStack(spacing: 4) {
- Image("ArrowLeft01Icon")
- .resizable()
- .scaledToFit()
- .frame(width: 14, height: 14)
- Text("Back")
- }
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- }
- .buttonStyle(.plain)
- }
- },
- center: {
- EnsuLogo(height: 23)
- },
- trailing: {
- Button("Close") {
- dismiss()
- }
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- .buttonStyle(.plain)
- }
- )
- }
- #endif
- }
-
- @ViewBuilder
- private var rootView: some View {
- EmailEntryView { route in
- path.append(route)
- }
- .navigationDestination(for: AuthRoute.self) { route in
- destinationView(for: route)
- }
- .navigationTitle("")
- .platformNavigationBarStyle()
- #if os(iOS)
- .toolbar {
- ToolbarItem(placement: .principal) {
- EnsuLogo(height: 23)
- }
-
- ToolbarItem(placement: trailingPlacement) {
- Button("Close") {
- dismiss()
- }
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- }
- }
- #endif
- }
-
- @ViewBuilder
- private var macContent: some View {
- if let route = path.last {
- destinationView(for: route)
- } else {
- EmailEntryView { route in
- path.append(route)
- }
- }
- }
-
- @ViewBuilder
- private func destinationView(for route: AuthRoute) -> some View {
- switch route {
- case let .otp(email, srp):
- authDestination {
- OtpVerificationView(email: email, srpAttributes: srp) { next in
- path.append(next)
- }
- }
-
- case let .password(email, srp):
- authDestination {
- PasswordView(email: email, srpAttributes: srp) { next in
- path.append(next)
- } onLoggedIn: {
- appState.refreshLoginState()
- }
- }
-
- case let .twoFactor(email, srp, sessionId, password):
- authDestination {
- TwoFactorView(email: email, srpAttributes: srp, sessionId: sessionId, password: password) { next in
- path.append(next)
- } onLoggedIn: {
- appState.refreshLoginState()
- }
- }
-
- case let .passkey(email, srp, sessionId, accountsUrl, twoFactorSessionId, password):
- authDestination {
- PasskeyView(
- email: email,
- srpAttributes: srp,
- sessionId: sessionId,
- accountsUrl: accountsUrl,
- twoFactorSessionId: twoFactorSessionId,
- password: password
- ) { next in
- path.append(next)
- } onLoggedIn: {
- appState.refreshLoginState()
- }
- }
-
- case let .passwordAfterMfa(email, srp, userId, keyAttrs, encryptedToken, token):
- authDestination {
- PasswordAfterMfaView(
- email: email,
- srpAttributes: srp,
- userId: userId,
- keyAttributes: keyAttrs,
- encryptedToken: encryptedToken,
- token: token
- ) {
- appState.refreshLoginState()
- }
- }
-
- case let .passkeyPasswordReentry(email, srp, auth):
- authDestination {
- PasskeyPasswordReentryView(email: email, srpAttributes: srp, auth: auth) {
- appState.refreshLoginState()
- }
- }
- }
- }
-
- @ViewBuilder
- private func authDestination<Content: View>(@ViewBuilder _ content: () -> Content) -> some View {
- content()
- .platformBackButtonHidden(true)
- #if os(iOS)
- .toolbar {
- ToolbarItem(placement: leadingPlacement) {
- Button {
- guard !path.isEmpty else { return }
- path.removeLast()
- } label: {
- HStack(spacing: 4) {
- Image("ArrowLeft01Icon")
- .resizable()
- .scaledToFit()
- .frame(width: 14, height: 14)
- Text("Back")
- }
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- }
- .padding(.leading, backButtonInset)
- }
-
- ToolbarItem(placement: .principal) {
- EnsuLogo(height: 23)
- }
-
- ToolbarItem(placement: trailingPlacement) {
- Button("Close") {
- dismiss()
- }
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- }
- }
- #endif
- }
-}
-#else
-enum AuthRoute: Hashable {
- case unavailable
-}
-
-struct AuthFlowView: View {
- var body: some View {
- Text("Authentication unavailable")
- }
-}
-#endif
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/EmailEntryView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Auth/EmailEntryView.swift
deleted file mode 100644
index 8ebcb81acb..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/EmailEntryView.swift
+++ /dev/null
@@ -1,73 +0,0 @@
-import SwiftUI
-
-#if canImport(EnteCore)
-struct EmailEntryView: View {
- let onNavigate: (AuthRoute) -> Void
-
- @State private var email: String = ""
- @StateObject private var actionState = AuthActionState()
-
- private var isEmailValid: Bool {
- let trimmed = email.trimmingCharacters(in: .whitespacesAndNewlines)
- return trimmed.contains("@") && trimmed.contains(".") && trimmed.count >= 5
- }
-
- var body: some View {
- AuthScreen {
- AuthHeader(title: "Welcome back")
-
- VStack(spacing: EnsuSpacing.lg) {
- LabeledTextField(
- label: "Email",
- hint: "Enter your email",
- text: $email,
- keyboardType: .emailAddress,
- textContentType: .emailAddress,
- autocapitalization: .never,
- submitLabel: .next
- ) {
- Task { await continueTapped() }
- }
-
- if let errorMessage = actionState.errorMessage {
- AuthErrorText(message: errorMessage)
- }
- }
- } bottom: {
- PrimaryButton(
- text: "Log in",
- isLoading: actionState.isLoading,
- isEnabled: isEmailValid && !actionState.isLoading
- ) {
- Task { await continueTapped() }
- }
- }
- }
-
- @MainActor
- private func continueTapped() async {
- await actionState.run(onError: { error in
- if error is AccountNotFoundError {
- return "No account found for this email."
- }
- return "Failed to get account info: \(error.localizedDescription)"
- }) {
- let trimmedEmail = email.trimmingCharacters(in: .whitespacesAndNewlines)
- let srpAttrs = try await EnsuAuthService.shared.getSrpAttributes(email: trimmedEmail)
-
- if srpAttrs.isEmailMfaEnabled {
- try await EnsuAuthService.shared.sendOtp(email: trimmedEmail)
- onNavigate(.otp(email: trimmedEmail, srp: srpAttrs))
- } else {
- onNavigate(.password(email: trimmedEmail, srp: srpAttrs))
- }
- }
- }
-}
-#else
-struct EmailEntryView: View {
- var body: some View {
- Text("Authentication unavailable")
- }
-}
-#endif
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/OtpVerificationView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Auth/OtpVerificationView.swift
deleted file mode 100644
index 6f4f6021fb..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/OtpVerificationView.swift
+++ /dev/null
@@ -1,93 +0,0 @@
-import SwiftUI
-
-#if canImport(EnteCore)
-struct OtpVerificationView: View {
- let email: String
- let srpAttributes: SrpAttributes
- let onNavigate: (AuthRoute) -> Void
-
- @State private var code: String = ""
- @StateObject private var actionState = AuthActionState()
-
- var body: some View {
- VerificationCodeView(
- title: "Verify email",
- subtitle: email,
- code: $code,
- buttonText: "Verify",
- isLoading: actionState.isLoading,
- errorMessage: actionState.errorMessage,
- onSubmit: verifyTapped
- ) {
- TextLink(text: "Resend code") {
- Task { await resendTapped() }
- }
- .frame(maxWidth: .infinity)
- }
- }
-
- @MainActor
- private func verifyTapped() async {
- await actionState.run {
- let payload = try await EnsuAuthService.shared.verifyOtp(email: email, otp: code)
-
- guard let keyAttrs = payload.keyAttributes else {
- actionState.setError("New user signup not implemented. Please use an existing account.")
- return
- }
-
- if payload.requiresPasskey {
- onNavigate(
- .passkey(
- email: email,
- srp: srpAttributes,
- sessionId: payload.passkeySessionId!,
- accountsUrl: payload.accountsUrl ?? "https://accounts.ente.com",
- twoFactorSessionId: payload.twoFactorSessionId,
- password: nil
- )
- )
- return
- }
-
- if payload.requiresTwoFactor {
- onNavigate(
- .twoFactor(
- email: email,
- srp: srpAttributes,
- sessionId: payload.twoFactorSessionId!,
- password: nil
- )
- )
- return
- }
-
- onNavigate(
- .passwordAfterMfa(
- email: email,
- srp: srpAttributes,
- userId: payload.userId,
- keyAttributes: keyAttrs,
- encryptedToken: payload.encryptedToken,
- token: payload.token
- )
- )
- }
- }
-
- @MainActor
- private func resendTapped() async {
- do {
- try await EnsuAuthService.shared.sendOtp(email: email)
- } catch {
- actionState.setError("Failed to resend code: \(error.localizedDescription)")
- }
- }
-}
-#else
-struct OtpVerificationView: View {
- var body: some View {
- Text("Authentication unavailable")
- }
-}
-#endif
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/PasskeyPasswordReentryView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Auth/PasskeyPasswordReentryView.swift
deleted file mode 100644
index bd5cd9f2a2..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/PasskeyPasswordReentryView.swift
+++ /dev/null
@@ -1,56 +0,0 @@
-import SwiftUI
-
-#if canImport(EnteCore)
-struct PasskeyPasswordReentryView: View {
- let email: String
- let srpAttributes: SrpAttributes
- let auth: AuthResponsePayload
- let onLoggedIn: () -> Void
-
- @State private var password: String = ""
- @StateObject private var actionState = AuthActionState()
- @State private var showPassword = false
-
- var body: some View {
- PasswordEntryView(
- title: "Enter password",
- subtitle: email,
- buttonText: "Continue",
- password: $password,
- showPassword: $showPassword,
- isLoading: actionState.isLoading,
- errorMessage: actionState.errorMessage,
- onSubmit: continueTapped
- )
- }
-
- @MainActor
- private func continueTapped() async {
- await actionState.run(onError: { error in
- "Incorrect password: \(error.localizedDescription)"
- }) {
- guard let keyAttrs = auth.keyAttributes else {
- actionState.setError("Invalid passkey response.")
- return
- }
-
- try await EnsuAuthService.shared.loginAfterChallenge(
- email: email,
- password: password,
- srpAttributes: srpAttributes,
- userId: auth.userId,
- keyAttributes: keyAttrs,
- encryptedToken: auth.encryptedToken,
- token: auth.token
- )
- onLoggedIn()
- }
- }
-}
-#else
-struct PasskeyPasswordReentryView: View {
- var body: some View {
- Text("Authentication unavailable")
- }
-}
-#endif
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/PasskeyView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Auth/PasskeyView.swift
deleted file mode 100644
index b5725776e7..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/PasskeyView.swift
+++ /dev/null
@@ -1,245 +0,0 @@
-import SwiftUI
-
-#if canImport(EnteCore)
-struct PasskeyView: View {
- let email: String
- let srpAttributes: SrpAttributes
- let sessionId: String
- let accountsUrl: String
- let twoFactorSessionId: String?
- let password: String?
- let onNavigate: (AuthRoute) -> Void
- let onLoggedIn: () -> Void
-
- private static let redirectUrl = "enteensu://passkey"
- private static let clientPackage = "io.ente.ensu"
-
- @EnvironmentObject private var deepLinkRouter: DeepLinkRouter
- @Environment(\.openURL) private var openURL
-
- @State private var isChecking = false
- @State private var message: String?
-
- var body: some View {
- AuthScreen {
- AuthHeader(
- title: "Passkey verification",
- subtitle: "Complete passkey verification in browser"
- )
-
- VStack(spacing: EnsuSpacing.lg) {
- TextLink(text: "Open passkey again") {
- launchPasskey()
- }
- .frame(maxWidth: .infinity)
-
- if let twoFactorSessionId, !twoFactorSessionId.isEmpty {
- TextLink(text: "Use authenticator code") {
- onNavigate(
- .twoFactor(
- email: email,
- srp: srpAttributes,
- sessionId: twoFactorSessionId,
- password: password
- )
- )
- }
- .frame(maxWidth: .infinity)
- }
-
- if let message {
- Text(message)
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- .padding(.horizontal, EnsuSpacing.pageHorizontal)
- .frame(maxWidth: .infinity, alignment: .leading)
- }
- }
- } bottom: {
- PrimaryButton(
- text: "Check status",
- isLoading: isChecking,
- isEnabled: !isChecking
- ) {
- Task { await checkStatusTapped() }
- }
- }
- .onAppear {
- launchPasskey()
- }
- .onChange(of: deepLinkRouter.lastURL) { newValue in
- guard let url = newValue else { return }
- Task { await handleDeepLink(url) }
- }
- }
-
- private func launchPasskey() {
- guard var components = URLComponents(string: accountsUrl) else {
- message = "Invalid accounts URL"
- return
- }
-
- let base = components.url?.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/")) ?? accountsUrl
- guard var verifyComponents = URLComponents(string: base + "/passkeys/verify") else {
- message = "Invalid passkey URL"
- return
- }
-
- verifyComponents.queryItems = [
- URLQueryItem(name: "passkeySessionID", value: sessionId),
- URLQueryItem(name: "redirect", value: Self.redirectUrl),
- URLQueryItem(name: "clientPackage", value: Self.clientPackage),
- ]
-
- guard let url = verifyComponents.url else {
- message = "Invalid passkey URL"
- return
- }
-
- openURL(url)
- }
-
- @MainActor
- private func checkStatusTapped() async {
- guard !isChecking else { return }
- isChecking = true
- defer { isChecking = false }
-
- do {
- let payload = try await EnsuAuthService.shared.getTokenForPasskeySession(sessionId: sessionId)
- try await handleAuthResponse(payload)
- } catch is PasskeySessionNotVerifiedError {
- message = "Passkey verification is still pending."
- } catch is PasskeySessionExpiredError {
- message = "Login session expired."
- } catch {
- message = "Failed to check passkey status: \(error.localizedDescription)"
- }
- }
-
- @MainActor
- private func handleDeepLink(_ url: URL) async {
- guard url.scheme?.lowercased() == "enteensu" else { return }
- guard url.host?.lowercased() == "passkey" else { return }
-
- let params = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
- let qp: [String: String] = Dictionary(uniqueKeysWithValues: params.compactMap { item in
- guard let value = item.value else { return nil }
- return (item.name, value)
- })
-
- guard let sid = qp["passkeySessionID"], sid == sessionId else {
- message = "Session ID mismatch."
- return
- }
-
- guard let responseParam = qp["response"], !responseParam.isEmpty else {
- return
- }
-
- var base64 = responseParam
- while base64.count % 4 != 0 { base64.append("=") }
- guard let decodedData = Data(base64Encoded: base64) else {
- message = "Missing/invalid passkey response."
- return
- }
-
- do {
- let jsonAny = try JSONSerialization.jsonObject(with: decodedData)
- guard let json = jsonAny as? [String: Any] else {
- message = "Invalid passkey response."
- return
- }
-
- let payload = try parseAuthResponseJSON(json)
- try await handleAuthResponse(payload)
- } catch {
- message = "Failed to verify passkey."
- }
- }
-
- @MainActor
- private func handleAuthResponse(_ payload: AuthResponsePayload) async throws {
- guard let keyAttrs = payload.keyAttributes else {
- throw EnsuError.Message(reason: "Invalid passkey response")
- }
-
- if let password, !password.isEmpty {
- try await EnsuAuthService.shared.loginAfterChallenge(
- email: email,
- password: password,
- srpAttributes: srpAttributes,
- userId: payload.userId,
- keyAttributes: keyAttrs,
- encryptedToken: payload.encryptedToken,
- token: payload.token
- )
- onLoggedIn()
- return
- }
-
- onNavigate(.passkeyPasswordReentry(email: email, srp: srpAttributes, auth: payload))
- }
-
- private func parseAuthResponseJSON(_ json: [String: Any]) throws -> AuthResponsePayload {
- guard let id = json["id"] as? Int else {
- throw URLError(.badServerResponse)
- }
-
- let encryptedToken = json["encryptedToken"] as? String
- let token = json["token"] as? String
-
- let passkeySessionId = json["passkeySessionID"] as? String
-
- let twoFactorV2 = json["twoFactorSessionIDV2"] as? String
- let twoFactor = json["twoFactorSessionID"] as? String
- let twoFactorSessionId = (twoFactorV2?.isEmpty == false) ? twoFactorV2 : twoFactor
-
- let accountsUrl = json["accountsUrl"] as? String
-
- let keyAttrsDict = json["keyAttributes"] as? [String: Any]
- let keyAttrs = keyAttrsDict.flatMap { dict -> KeyAttributes? in
- guard
- let kekSalt = dict["kekSalt"] as? String,
- let encryptedKey = dict["encryptedKey"] as? String,
- let keyDecryptionNonce = dict["keyDecryptionNonce"] as? String,
- let publicKey = dict["publicKey"] as? String,
- let encryptedSecretKey = dict["encryptedSecretKey"] as? String,
- let secretKeyDecryptionNonce = dict["secretKeyDecryptionNonce"] as? String
- else {
- return nil
- }
-
- let memLimit = (dict["memLimit"] as? NSNumber).map { $0.uint32Value }
- let opsLimit = (dict["opsLimit"] as? NSNumber).map { $0.uint32Value }
-
- return KeyAttributes(
- kekSalt: kekSalt,
- encryptedKey: encryptedKey,
- keyDecryptionNonce: keyDecryptionNonce,
- publicKey: publicKey,
- encryptedSecretKey: encryptedSecretKey,
- secretKeyDecryptionNonce: secretKeyDecryptionNonce,
- memLimit: memLimit,
- opsLimit: opsLimit
- )
- }
-
- return AuthResponsePayload(
- userId: Int64(id),
- keyAttributes: keyAttrs,
- encryptedToken: encryptedToken,
- token: token,
- twoFactorSessionId: twoFactorSessionId,
- passkeySessionId: passkeySessionId,
- accountsUrl: accountsUrl
- )
- }
-}
-#else
-struct PasskeyView: View {
- var body: some View {
- Text("Authentication unavailable")
- }
-}
-#endif
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/PasswordAfterMfaView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Auth/PasswordAfterMfaView.swift
deleted file mode 100644
index 217bb2f6af..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/PasswordAfterMfaView.swift
+++ /dev/null
@@ -1,54 +0,0 @@
-import SwiftUI
-
-#if canImport(EnteCore)
-struct PasswordAfterMfaView: View {
- let email: String
- let srpAttributes: SrpAttributes
- let userId: Int64
- let keyAttributes: KeyAttributes
- let encryptedToken: String?
- let token: String?
- let onLoggedIn: () -> Void
-
- @State private var password: String = ""
- @StateObject private var actionState = AuthActionState()
- @State private var showPassword = false
-
- var body: some View {
- PasswordEntryView(
- title: "Enter password",
- subtitle: email,
- buttonText: "Continue",
- password: $password,
- showPassword: $showPassword,
- isLoading: actionState.isLoading,
- errorMessage: actionState.errorMessage,
- onSubmit: continueTapped
- )
- }
-
- @MainActor
- private func continueTapped() async {
- await actionState.run(onError: { error in
- "Incorrect password: \(error.localizedDescription)"
- }) {
- try await EnsuAuthService.shared.loginAfterChallenge(
- email: email,
- password: password,
- srpAttributes: srpAttributes,
- userId: userId,
- keyAttributes: keyAttributes,
- encryptedToken: encryptedToken,
- token: token
- )
- onLoggedIn()
- }
- }
-}
-#else
-struct PasswordAfterMfaView: View {
- var body: some View {
- Text("Authentication unavailable")
- }
-}
-#endif
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/PasswordView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Auth/PasswordView.swift
deleted file mode 100644
index 0adcdac62d..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/PasswordView.swift
+++ /dev/null
@@ -1,72 +0,0 @@
-import SwiftUI
-
-#if canImport(EnteCore)
-struct PasswordView: View {
- let email: String
- let srpAttributes: SrpAttributes
- let onNavigate: (AuthRoute) -> Void
- let onLoggedIn: () -> Void
-
- @State private var password: String = ""
- @StateObject private var actionState = AuthActionState()
- @State private var showPassword = false
-
- var body: some View {
- PasswordEntryView(
- title: "Enter password",
- subtitle: email,
- buttonText: "Log in",
- password: $password,
- showPassword: $showPassword,
- isLoading: actionState.isLoading,
- errorMessage: actionState.errorMessage,
- onSubmit: loginTapped
- )
- }
-
- @MainActor
- private func loginTapped() async {
- await actionState.run {
- let result = try await EnsuAuthService.shared.loginWithSrp(
- email: email,
- password: password,
- srpAttributes: srpAttributes
- )
-
- if result.requiresPasskey {
- onNavigate(
- .passkey(
- email: email,
- srp: srpAttributes,
- sessionId: result.passkeySessionId!,
- accountsUrl: result.accountsUrl ?? "https://accounts.ente.com",
- twoFactorSessionId: result.twoFactorSessionId,
- password: password
- )
- )
- return
- }
-
- if result.requiresTwoFactor {
- onNavigate(
- .twoFactor(
- email: email,
- srp: srpAttributes,
- sessionId: result.twoFactorSessionId!,
- password: password
- )
- )
- return
- }
-
- onLoggedIn()
- }
- }
-}
-#else
-struct PasswordView: View {
- var body: some View {
- Text("Authentication unavailable")
- }
-}
-#endif
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/TwoFactorView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Auth/TwoFactorView.swift
deleted file mode 100644
index 0705b0d032..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Auth/TwoFactorView.swift
+++ /dev/null
@@ -1,69 +0,0 @@
-import SwiftUI
-
-#if canImport(EnteCore)
-struct TwoFactorView: View {
- let email: String
- let srpAttributes: SrpAttributes
- let sessionId: String
- let password: String?
- let onNavigate: (AuthRoute) -> Void
- let onLoggedIn: () -> Void
-
- @State private var code: String = ""
- @StateObject private var actionState = AuthActionState()
-
- var body: some View {
- VerificationCodeView(
- title: "Two-factor authentication",
- subtitle: "Enter the code from your authenticator app",
- code: $code,
- buttonText: "Verify",
- isLoading: actionState.isLoading,
- errorMessage: actionState.errorMessage,
- onSubmit: verifyTapped
- )
- }
-
- @MainActor
- private func verifyTapped() async {
- await actionState.run {
- let payload = try await EnsuAuthService.shared.verifyTwoFactor(sessionId: sessionId, code: code)
- guard let keyAttrs = payload.keyAttributes else {
- actionState.setError("Invalid response")
- return
- }
-
- if let password, !password.isEmpty {
- try await EnsuAuthService.shared.loginAfterChallenge(
- email: email,
- password: password,
- srpAttributes: srpAttributes,
- userId: payload.userId,
- keyAttributes: keyAttrs,
- encryptedToken: payload.encryptedToken,
- token: payload.token
- )
- onLoggedIn()
- return
- }
-
- onNavigate(
- .passwordAfterMfa(
- email: email,
- srp: srpAttributes,
- userId: payload.userId,
- keyAttributes: keyAttrs,
- encryptedToken: payload.encryptedToken,
- token: payload.token
- )
- )
- }
- }
-}
-#else
-struct TwoFactorView: View {
- var body: some View {
- Text("Authentication unavailable")
- }
-}
-#endif
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatView.swift
index 7dc9970e99..528e243e88 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatView.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatView.swift
@@ -3,9 +3,7 @@ import SwiftUI
struct ChatView: View {
@ObservedObject var viewModel: ChatViewModel
- @Binding var isShowingAuth: Bool
- @EnvironmentObject private var appState: EnsuAppState
@Environment(\.scenePhase) private var scenePhase
@ObservedObject private var modelSettings = ModelSettingsStore.shared
@@ -151,16 +149,7 @@ struct ChatView: View {
}
.sheet(isPresented: $viewState.showSettings) {
SettingsView(
- isLoggedIn: appState.isLoggedIn,
- email: CredentialStore.shared.email,
- showsSignInOption: EnsuFeatureFlags.enableSignIn,
- onSignOut: {
- appState.logout()
- viewState.showSettings = false
- viewState.isDrawerOpen = false
- },
onSignIn: {
- guard EnsuFeatureFlags.enableSignIn else { return }
viewState.pendingSignInRequest = true
viewState.showSettings = false
}
@@ -172,7 +161,6 @@ struct ChatView: View {
isInputFocused = false
} else if viewState.pendingSignInRequest {
viewState.pendingSignInRequest = false
- guard EnsuFeatureFlags.enableSignIn else { return }
handleSignInRequest()
}
}
@@ -256,13 +244,12 @@ struct ChatView: View {
ChatAppBar(
sessionTitle: viewModel.currentSessionId.map { viewModel.sessionTitle(for: $0) } ?? "New chat",
showBrand: viewModel.messages.isEmpty,
- showSignIn: EnsuFeatureFlags.enableSignIn && !appState.isLoggedIn,
+ showSignIn: false,
showsMenuButton: showsMenuButton,
attachmentDownloadSummary: viewModel.attachmentDownloadSummary,
modelDownloadState: viewModel.downloadToast,
onMenu: { viewState.isDrawerOpen.toggle() },
onSignIn: {
- guard EnsuFeatureFlags.enableSignIn else { return }
handleSignInRequest()
},
onNewChat: {
@@ -433,8 +420,6 @@ struct ChatView: View {
let drawer = SessionDrawerView(
sessions: viewModel.sessions,
currentSessionId: viewModel.currentSessionId,
- isLoggedIn: appState.isLoggedIn,
- email: CredentialStore.shared.email,
onSelectSession: { session in
viewModel.selectSession(session)
viewState.isDrawerOpen = false
@@ -491,11 +476,7 @@ struct ChatView: View {
}
private func handleSignInRequest() {
- if EnsuFeatureFlags.enableSignIn {
- isShowingAuth = true
- } else {
- viewState.showSignInComingSoon = true
- }
+ viewState.showSignInComingSoon = true
}
private func markWhatsNewSeen() {
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift
index 029e5f00fc..7a84cb8fdb 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift
@@ -5,9 +5,6 @@ import EnteCore
#else
final class CredentialStore {
static let shared = CredentialStore()
- var hasConfiguredAccount: Bool { false }
- var token: String? { nil }
- var masterKey: Data? { nil }
func getOrCreateChatDbKey() -> Data {
Data()
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/SessionDrawerView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/SessionDrawerView.swift
index b215d47907..117255bf13 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/SessionDrawerView.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/SessionDrawerView.swift
@@ -4,8 +4,6 @@ import SwiftUI
struct SessionDrawerView: View {
let sessions: [ChatSession]
let currentSessionId: UUID?
- let isLoggedIn: Bool
- let email: String?
let onSelectSession: (ChatSession) -> Void
let onDeleteSession: (ChatSession) -> Void
let onOpenSettings: () -> Void
@@ -134,25 +132,14 @@ struct SessionDrawerView: View {
private var footer: some View {
HStack {
- if isLoggedIn {
- Button {
- hapticTap()
- onOpenSettings()
- } label: {
- footerButtonLabel(title: email ?? "")
- }
- .buttonStyle(.plain)
- .contentShape(Rectangle())
- } else {
- Button {
- hapticTap()
- onOpenSettings()
- } label: {
- footerButtonLabel(title: "Settings")
- }
- .buttonStyle(.plain)
- .contentShape(Rectangle())
+ Button {
+ hapticTap()
+ onOpenSettings()
+ } label: {
+ footerButtonLabel(title: "Settings")
}
+ .buttonStyle(.plain)
+ .contentShape(Rectangle())
Spacer(minLength: 0)
}
.padding(EnsuSpacing.lg)
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Components/AuthComponents.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Components/AuthComponents.swift
deleted file mode 100644
index c63e9c49f6..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Components/AuthComponents.swift
+++ /dev/null
@@ -1,385 +0,0 @@
-import SwiftUI
-
-#if canImport(EnteCore)
-struct AuthHeader: View {
- let title: String
- var subtitle: String? = nil
-
- var body: some View {
- VStack(alignment: .leading, spacing: EnsuSpacing.sm) {
- Text(title)
- .font(EnsuTypography.h2Bold)
- .foregroundStyle(EnsuColor.textPrimary)
- .lineSpacing(EnsuLineHeight.spacing(fontSize: 32, lineHeight: 1.2))
-
- if let subtitle {
- Text(subtitle)
- .font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textMuted)
- }
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding(.horizontal, EnsuSpacing.pageHorizontal)
- .padding(.vertical, EnsuSpacing.pageVertical)
- }
-}
-
-struct AuthSubtitle: View {
- let text: String
-
- var body: some View {
- Text(text)
- .font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textMuted)
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding(.horizontal, EnsuSpacing.pageHorizontal)
- }
-}
-
-struct AuthErrorText: View {
- let message: String
-
- var body: some View {
- Text(message)
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.error)
- .padding(.horizontal, EnsuSpacing.pageHorizontal)
- .frame(maxWidth: .infinity, alignment: .leading)
- }
-}
-
-@MainActor
-final class AuthActionState: ObservableObject {
- @Published var isLoading: Bool = false
- @Published var errorMessage: String?
-
- func setError(_ message: String?) {
- errorMessage = message
- }
-
- func run(
- onError: ((Error) -> String)? = nil,
- _ action: @escaping () async throws -> Void
- ) async {
- guard !isLoading else { return }
- errorMessage = nil
- isLoading = true
- defer { isLoading = false }
-
- do {
- try await action()
- } catch {
- errorMessage = onError?(error) ?? error.localizedDescription
- }
- }
-}
-
-struct StyledTextField: View {
- let hint: String
- @Binding var text: String
- var keyboardType: PlatformKeyboardType = .default
- var textContentType: PlatformTextContentType? = nil
- var autocapitalization: PlatformTextInputAutocapitalization = .never
- var isSecure: Bool = false
- var submitLabel: SubmitLabel = .done
- var onSubmit: (() -> Void)? = nil
-
- var body: some View {
- Group {
- if isSecure {
- SecureField(hint, text: $text)
- } else {
- TextField(hint, text: $text)
- }
- }
- .font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textPrimary)
- .platformTextFieldStyle()
- .platformTextInputAutocapitalization(autocapitalization)
- .autocorrectionDisabled()
- .platformKeyboardType(keyboardType)
- .platformTextContentType(textContentType)
- .submitLabel(submitLabel)
- .onSubmit {
- onSubmit?()
- }
- .padding(.horizontal, EnsuSpacing.inputHorizontal)
- .padding(.vertical, EnsuSpacing.inputVertical)
- .background(EnsuColor.fillFaint)
- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))
- }
-}
-
-struct LabeledTextField: View {
- let label: String
- let hint: String
- @Binding var text: String
- var keyboardType: PlatformKeyboardType = .default
- var textContentType: PlatformTextContentType? = nil
- var autocapitalization: PlatformTextInputAutocapitalization = .never
- var isSecure: Bool = false
- var submitLabel: SubmitLabel = .done
- var onSubmit: (() -> Void)? = nil
-
- var body: some View {
- VStack(alignment: .leading, spacing: 6) {
- Text(label)
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
-
- StyledTextField(
- hint: hint,
- text: $text,
- keyboardType: keyboardType,
- textContentType: textContentType,
- autocapitalization: autocapitalization,
- isSecure: isSecure,
- submitLabel: submitLabel,
- onSubmit: onSubmit
- )
- }
- .padding(.horizontal, EnsuSpacing.pageHorizontal)
- }
-}
-
-struct PasswordTextField: View {
- let label: String
- let hint: String
- @Binding var text: String
- @Binding var showPassword: Bool
- var submitLabel: SubmitLabel = .done
- var onSubmit: (() -> Void)? = nil
-
- var body: some View {
- VStack(alignment: .leading, spacing: 6) {
- Text(label)
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
-
- HStack(spacing: 8) {
- Group {
- if showPassword {
- TextField(hint, text: $text)
- } else {
- SecureField(hint, text: $text)
- }
- }
- .font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textPrimary)
- .platformTextFieldStyle()
- .platformTextInputAutocapitalization(.never)
- .autocorrectionDisabled()
- .platformTextContentType(.password)
- .submitLabel(submitLabel)
- .onSubmit {
- onSubmit?()
- }
-
- Button {
- showPassword.toggle()
- } label: {
- Image(showPassword ? "ViewOffSlashIcon" : "ViewIcon")
- .resizable()
- .scaledToFit()
- .frame(width: 18, height: 18)
- .foregroundStyle(EnsuColor.textMuted)
- }
- }
- .padding(.horizontal, EnsuSpacing.inputHorizontal)
- .padding(.vertical, EnsuSpacing.inputVertical)
- .background(EnsuColor.fillFaint)
- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))
- }
- .padding(.horizontal, EnsuSpacing.pageHorizontal)
- }
-}
-
-struct CodeTextField: View {
- @Binding var code: String
- var maxLength: Int = 6
- var onChange: ((String) -> Void)? = nil
-
- var body: some View {
- TextField("β€’ β€’ β€’ β€’ β€’ β€’", text: $code)
- .platformKeyboardType(.numberPad)
- .multilineTextAlignment(.center)
- .font(EnsuFont.ui(size: 28, weight: .medium))
- .foregroundStyle(EnsuColor.textPrimary)
- .platformTextFieldStyle()
- .tracking(8)
- .padding(.horizontal, EnsuSpacing.inputHorizontal)
- .padding(.vertical, EnsuSpacing.inputVertical)
- .background(EnsuColor.fillFaint)
- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))
- .padding(.horizontal, EnsuSpacing.pageHorizontal)
- .onChange(of: code) { newValue in
- var digits = newValue.filter { $0.isNumber }
- if digits.count > maxLength {
- digits = String(digits.prefix(maxLength))
- }
- if digits != newValue {
- code = digits
- }
- onChange?(digits)
- }
- }
-}
-
-struct PasswordEntryView: View {
- let title: String
- let subtitle: String
- let buttonText: String
- @Binding var password: String
- @Binding var showPassword: Bool
- let isLoading: Bool
- let errorMessage: String?
- var submitLabel: SubmitLabel = .go
- let onSubmit: () async -> Void
-
- private var hasPassword: Bool { !password.isEmpty }
-
- var body: some View {
- AuthScreen {
- AuthHeader(title: title)
- AuthSubtitle(text: subtitle)
-
- VStack(spacing: EnsuSpacing.xxl) {
- PasswordTextField(
- label: "Password",
- hint: "Enter your password",
- text: $password,
- showPassword: $showPassword,
- submitLabel: submitLabel
- ) {
- Task { await onSubmit() }
- }
-
- if let errorMessage {
- AuthErrorText(message: errorMessage)
- }
- }
- .padding(.top, EnsuSpacing.xxl)
- } bottom: {
- PrimaryButton(
- text: buttonText,
- isLoading: isLoading,
- isEnabled: hasPassword && !isLoading
- ) {
- Task { await onSubmit() }
- }
- }
- }
-}
-
-struct VerificationCodeView<Accessory: View>: View {
- let title: String
- let subtitle: String?
- @Binding var code: String
- let buttonText: String
- let isLoading: Bool
- let errorMessage: String?
- var autoSubmitLength: Int = 6
- let onSubmit: () async -> Void
- @ViewBuilder let accessory: () -> Accessory
-
- private var hasValidCode: Bool {
- code.trimmingCharacters(in: .whitespacesAndNewlines).count == autoSubmitLength
- }
-
- init(
- title: String,
- subtitle: String? = nil,
- code: Binding<String>,
- buttonText: String = "Verify",
- isLoading: Bool,
- errorMessage: String?,
- autoSubmitLength: Int = 6,
- onSubmit: @escaping () async -> Void,
- @ViewBuilder accessory: @escaping () -> Accessory
- ) {
- self.title = title
- self.subtitle = subtitle
- self._code = code
- self.buttonText = buttonText
- self.isLoading = isLoading
- self.errorMessage = errorMessage
- self.autoSubmitLength = autoSubmitLength
- self.accessory = accessory
- self.onSubmit = onSubmit
- }
-
- var body: some View {
- AuthScreen {
- AuthHeader(title: title, subtitle: subtitle)
-
- VStack(spacing: EnsuSpacing.lg) {
- CodeTextField(code: $code, maxLength: autoSubmitLength) { value in
- if value.count == autoSubmitLength {
- Task { await onSubmit() }
- }
- }
-
- accessory()
-
- if let errorMessage {
- AuthErrorText(message: errorMessage)
- }
- }
- } bottom: {
- PrimaryButton(
- text: buttonText,
- isLoading: isLoading,
- isEnabled: hasValidCode && !isLoading
- ) {
- Task { await onSubmit() }
- }
- }
- }
-}
-
-extension VerificationCodeView where Accessory == EmptyView {
- init(
- title: String,
- subtitle: String? = nil,
- code: Binding<String>,
- buttonText: String = "Verify",
- isLoading: Bool,
- errorMessage: String?,
- autoSubmitLength: Int = 6,
- onSubmit: @escaping () async -> Void
- ) {
- self.init(
- title: title,
- subtitle: subtitle,
- code: code,
- buttonText: buttonText,
- isLoading: isLoading,
- errorMessage: errorMessage,
- autoSubmitLength: autoSubmitLength,
- onSubmit: onSubmit,
- accessory: { EmptyView() }
- )
- }
-}
-
-struct AuthScreen<Content: View, Bottom: View>: View {
- @ViewBuilder let content: () -> Content
- @ViewBuilder let bottom: () -> Bottom
-
- @StateObject private var keyboard = KeyboardObserver()
-
- var body: some View {
- VStack(spacing: 0) {
- content()
- Spacer()
- if !keyboard.isVisible {
- bottom()
- .padding(.horizontal, EnsuSpacing.pageHorizontal)
- .padding(.top, EnsuSpacing.md)
- .padding(.bottom, EnsuSpacing.pageVertical)
- }
- }
- .background(EnsuColor.backgroundBase.ignoresSafeArea())
- }
-}
-#endif
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Components/EnsuComponents.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Components/EnsuComponents.swift
index 8308e91e7f..d7ae7f5c31 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Components/EnsuComponents.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Components/EnsuComponents.swift
@@ -45,6 +45,26 @@ private struct PrimaryButtonStyle: ButtonStyle {
}
}
+struct StyledTextField: View {
+ let hint: String
+ @Binding var text: String
+ var keyboardType: PlatformKeyboardType = .default
+
+ var body: some View {
+ TextField(hint, text: $text)
+ .font(EnsuTypography.body)
+ .foregroundStyle(EnsuColor.textPrimary)
+ .platformTextFieldStyle()
+ .platformTextInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ .platformKeyboardType(keyboardType)
+ .padding(.horizontal, EnsuSpacing.inputHorizontal)
+ .padding(.vertical, EnsuSpacing.inputVertical)
+ .background(EnsuColor.fillFaint)
+ .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))
+ }
+}
+
struct TextLink: View {
let text: String
let action: () -> Void
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/EnsuApp.swift b/mobile/native/darwin/Apps/Ensu/Ensu/EnsuApp.swift
index 7870166786..0fd27caeb0 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/EnsuApp.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/EnsuApp.swift
@@ -2,8 +2,6 @@ import SwiftUI
@main
struct EnsuApp: App {
- @StateObject private var appState = EnsuAppState()
- @StateObject private var deepLinkRouter = DeepLinkRouter()
#if os(iOS)
@UIApplicationDelegateAdaptor(EnsuAppDelegate.self) private var appDelegate
#endif
@@ -15,11 +13,6 @@ struct EnsuApp: App {
var body: some Scene {
WindowGroup {
RootView()
- .environmentObject(appState)
- .environmentObject(deepLinkRouter)
- .onOpenURL { url in
- deepLinkRouter.handle(url)
- }
}
}
}
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/FeatureFlags.swift b/mobile/native/darwin/Apps/Ensu/Ensu/FeatureFlags.swift
index 6b5c85fe1a..59e3ce39f0 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/FeatureFlags.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/FeatureFlags.swift
@@ -2,9 +2,6 @@
import Foundation
enum EnsuFeatureFlags {
- static let enableSignIn = false
- static let enableDeveloperTools = false
static let enableImageUploads = true
- static let enableModelSettings = false
}
#endif
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/HomeView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/HomeView.swift
index bb941d71fb..113c3af48c 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/HomeView.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/HomeView.swift
@@ -2,20 +2,10 @@
import SwiftUI
struct HomeView: View {
- @EnvironmentObject private var appState: EnsuAppState
@StateObject private var chatModel = ChatViewModel()
- @State private var isShowingAuth = false
var body: some View {
- ChatView(viewModel: chatModel, isShowingAuth: $isShowingAuth)
- .platformFullScreenCover(isPresented: $isShowingAuth) {
- AuthFlowView()
- }
- .onChange(of: appState.isLoggedIn) { isLoggedIn in
- if isLoggedIn {
- isShowingAuth = false
- }
- }
+ ChatView(viewModel: chatModel)
}
}
#else
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Services/CredentialStore.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Services/CredentialStore.swift
index 3d1aa7ffe7..798c38481c 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Services/CredentialStore.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Services/CredentialStore.swift
@@ -8,71 +8,11 @@ final class CredentialStore {
private let keychainService = "io.ente.ensu"
- private enum DefaultsKey {
- static let email = "ensu.email"
- static let userId = "ensu.userId"
- static let lastUserId = "ensu.lastUserId"
- }
-
private enum KeychainAccount {
- static let token = "ensu.token"
static let masterKey = "ensu.masterKey"
- static let secretKey = "ensu.secretKey"
static let chatDbKey = "ensu.chatDbKey"
}
- var email: String? {
- UserDefaults.standard.string(forKey: DefaultsKey.email)
- }
-
- var userId: Int64? {
- let value = UserDefaults.standard.object(forKey: DefaultsKey.userId) as? NSNumber
- return value?.int64Value
- }
-
- var token: String? {
- guard let data = try? KeychainStore.get(service: keychainService, account: KeychainAccount.token) else {
- return nil
- }
- guard let token = String(data: data, encoding: .utf8) else {
- return nil
- }
-
- // Normalize to the padded base64url form (Go's `base64.URLEncoding`).
- // Older Ensu builds stored the token without padding, which breaks server lookups.
- let remainder = token.count % 4
- if remainder == 0 {
- return token
- }
- return token + String(repeating: "=", count: 4 - remainder)
- }
-
- var masterKey: Data? {
- try? KeychainStore.get(service: keychainService, account: KeychainAccount.masterKey)
- }
-
- var hasConfiguredAccount: Bool {
- token?.isEmpty == false &&
- email?.isEmpty == false &&
- KeychainStore.exists(service: keychainService, account: KeychainAccount.masterKey) &&
- KeychainStore.exists(service: keychainService, account: KeychainAccount.secretKey)
- }
-
- func save(email: String, userId: Int64, masterKey: Data, secretKey: Data, token: String) throws {
- UserDefaults.standard.set(email, forKey: DefaultsKey.email)
- UserDefaults.standard.set(NSNumber(value: userId), forKey: DefaultsKey.userId)
-
- try KeychainStore.set(Data(token.utf8), service: keychainService, account: KeychainAccount.token)
- try KeychainStore.set(masterKey, service: keychainService, account: KeychainAccount.masterKey)
- try KeychainStore.set(secretKey, service: keychainService, account: KeychainAccount.secretKey)
- }
-
- /// Returns a stable 32-byte key for encrypting the local chat DB.
- ///
- /// Rules:
- /// - If already stored, reuse it.
- /// - Else, if the account master key exists and is 32 bytes, pin it as the chat DB key.
- /// - Else, generate a random 32-byte key and persist it.
func getOrCreateChatDbKey() -> Data {
if let existing = try? KeychainStore.get(service: keychainService, account: KeychainAccount.chatDbKey), existing.count == 32 {
return existing
@@ -86,42 +26,10 @@ final class CredentialStore {
var bytes = [UInt8](repeating: 0, count: 32)
let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
if status != errSecSuccess {
- // Fallback to less ideal randomness if SecRandom fails (shouldn't happen on iOS).
bytes = (0..<32).map { _ in UInt8.random(in: UInt8.min...UInt8.max) }
}
let data = Data(bytes)
try? KeychainStore.set(data, service: keychainService, account: KeychainAccount.chatDbKey)
return data
}
-
- func clear() {
- let currentUserId = userId
- UserDefaults.standard.removeObject(forKey: DefaultsKey.email)
- UserDefaults.standard.removeObject(forKey: DefaultsKey.userId)
- if let currentUserId {
- UserDefaults.standard.set(NSNumber(value: currentUserId), forKey: DefaultsKey.lastUserId)
- }
-
- try? KeychainStore.delete(service: keychainService, account: KeychainAccount.token)
- try? KeychainStore.delete(service: keychainService, account: KeychainAccount.masterKey)
- try? KeychainStore.delete(service: keychainService, account: KeychainAccount.secretKey)
- // Note: keep chatDbKey to preserve local chats across sign-out.
- }
-
- func clearAll() {
- UserDefaults.standard.removeObject(forKey: DefaultsKey.email)
- UserDefaults.standard.removeObject(forKey: DefaultsKey.userId)
- UserDefaults.standard.removeObject(forKey: DefaultsKey.lastUserId)
-
- try? KeychainStore.delete(service: keychainService, account: KeychainAccount.token)
- try? KeychainStore.delete(service: keychainService, account: KeychainAccount.masterKey)
- try? KeychainStore.delete(service: keychainService, account: KeychainAccount.secretKey)
- try? KeychainStore.delete(service: keychainService, account: KeychainAccount.chatDbKey)
- }
-
- func isSameUser(_ newUserId: Int64) -> Bool {
- let value = UserDefaults.standard.object(forKey: DefaultsKey.lastUserId) as? NSNumber
- let lastUserId = value?.int64Value
- return lastUserId == nil || lastUserId == newUserId
- }
}
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Services/DeepLinkRouter.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Services/DeepLinkRouter.swift
deleted file mode 100644
index 48ec538503..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Services/DeepLinkRouter.swift
+++ /dev/null
@@ -1,10 +0,0 @@
-import Foundation
-
-@MainActor
-final class DeepLinkRouter: ObservableObject {
- @Published var lastURL: URL?
-
- func handle(_ url: URL) {
- lastURL = url
- }
-}
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAppState.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAppState.swift
deleted file mode 100644
index 57e5d76598..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAppState.swift
+++ /dev/null
@@ -1,19 +0,0 @@
-import Foundation
-
-@MainActor
-final class EnsuAppState: ObservableObject {
- @Published private(set) var isLoggedIn: Bool
-
- init() {
- self.isLoggedIn = CredentialStore.shared.hasConfiguredAccount
- }
-
- func refreshLoginState() {
- isLoggedIn = CredentialStore.shared.hasConfiguredAccount
- }
-
- func logout() {
- CredentialStore.shared.clear()
- refreshLoginState()
- }
-}
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAuthService.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAuthService.swift
deleted file mode 100644
index c94aca5d2e..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAuthService.swift
+++ /dev/null
@@ -1,301 +0,0 @@
-import Foundation
-import EnteCore
-import EnteNetwork
-
-struct SrpLoginResult {
- let twoFactorSessionId: String?
- let passkeySessionId: String?
- let accountsUrl: String?
-
- var requiresTwoFactor: Bool { twoFactorSessionId?.isEmpty == false }
- var requiresPasskey: Bool { passkeySessionId?.isEmpty == false }
-}
-
-struct AuthResponsePayload: Hashable {
- let userId: Int64
- let keyAttributes: KeyAttributes?
- let encryptedToken: String?
- let token: String?
- let twoFactorSessionId: String?
- let passkeySessionId: String?
- let accountsUrl: String?
-
- var requiresTwoFactor: Bool { twoFactorSessionId?.isEmpty == false }
- var requiresPasskey: Bool { passkeySessionId?.isEmpty == false }
-}
-
-final class EnsuAuthService {
- static let shared = EnsuAuthService()
-
- private let logger = EnsuLogging.shared.logger("EnsuAuthService")
- private let tokenProvider = EnsuAuthTokenProvider()
-
- private var networkFactory: NetworkFactory
-
- private var accountsUrlFallback: String {
- networkFactory.configuration.accountsEndpoint?.absoluteString ?? "https://accounts.ente.com"
- }
-
- private init() {
- networkFactory = NetworkFactory(
- configuration: EnsuDeveloperSettings.networkConfiguration,
- app: .ensu,
- authTokenProvider: tokenProvider
- )
-
- // Initialise Rust crypto backend once (no-op for pure Rust, but keeps parity).
- do {
- try initCrypto()
- } catch {
- logger.error("Crypto init failed", error)
- }
- }
-
- // MARK: - Network
-
- func updateEndpoint(_ endpoint: URL?) {
- logger.info("Updated endpoint", details: endpoint?.absoluteString ?? "default")
- EnsuDeveloperSettings.setEndpoint(endpoint)
- networkFactory = NetworkFactory(
- configuration: EnsuDeveloperSettings.networkConfiguration,
- app: .ensu,
- authTokenProvider: tokenProvider
- )
- }
-
- func getSrpAttributes(email: String) async throws -> SrpAttributes {
- do {
- let attrs = try await networkFactory.authentication.getSRPAttributes(email: email)
- return SrpAttributes(
- srpUserId: attrs.srpUserID,
- srpSalt: attrs.srpSalt,
- kekSalt: attrs.kekSalt,
- memLimit: UInt32(attrs.memLimit),
- opsLimit: UInt32(attrs.opsLimit),
- isEmailMfaEnabled: attrs.isEmailMFAEnabled
- )
- } catch let error as EnteError {
- if case let .serverError(code, _) = error, code == 404 {
- throw AccountNotFoundError()
- }
- throw error
- }
- }
-
- func sendOtp(email: String) async throws {
- try await networkFactory.authentication.sendLoginOTP(email: email)
- }
-
- func verifyOtp(email: String, otp: String) async throws -> AuthResponsePayload {
- let response = try await networkFactory.authentication.verifyEmail(email: email, otp: otp)
- return AuthResponsePayload(from: response)
- }
-
- func verifyTwoFactor(sessionId: String, code: String) async throws -> AuthResponsePayload {
- let response = try await networkFactory.authentication.verifyTOTP(sessionID: sessionId, otp: code)
- return AuthResponsePayload(from: response)
- }
-
- func getTokenForPasskeySession(sessionId: String) async throws -> AuthResponsePayload {
- do {
- let response = try await networkFactory.authentication.getTokenForPasskeySession(sessionID: sessionId)
- return AuthResponsePayload(from: response)
- } catch let error as EnteError {
- // Mirror Flutter behavior:
- // - 400 => not verified
- // - 404/410 => expired
- if case let .serverError(code, _) = error {
- if code == 400 { throw PasskeySessionNotVerifiedError() }
- if code == 404 || code == 410 { throw PasskeySessionExpiredError() }
- }
- throw error
- }
- }
-
- // MARK: - SRP Login
-
- func loginWithSrp(email: String, password: String, srpAttributes: SrpAttributes) async throws -> SrpLoginResult {
- logger.info("SRP login started")
- defer { srpClear() }
-
- do {
- // 1) Start SRP (heavy crypto)
- let start = try await Task.detached(priority: .userInitiated) {
- try srpStart(password: password, srpAttrs: srpAttributes)
- }.value
-
- // 2) Create SRP session
- let session = try await networkFactory.authentication.createSRPSession(
- srpUserID: srpAttributes.srpUserId,
- clientPub: start.srpA
- )
-
- // 3) Finish SRP
- let verify = try await Task.detached(priority: .userInitiated) {
- try srpFinish(srpB: session.srpB)
- }.value
-
- // 4) Verify SRP session
- let authResponse = try await networkFactory.authentication.verifySRPSession(
- srpUserID: srpAttributes.srpUserId,
- sessionID: session.sessionID,
- clientM1: verify.srpM1
- )
-
- // If additional auth factors are required, return the session IDs.
- let passkeySessionId = (authResponse.passkeySessionID?.isEmpty == false) ? authResponse.passkeySessionID : nil
- let twoFactorSessionId = (authResponse.effectiveTwoFactorSessionID?.isEmpty == false) ? authResponse.effectiveTwoFactorSessionID : nil
- if passkeySessionId != nil || twoFactorSessionId != nil {
- logger.info(
- "SRP login requires additional auth",
- details: "2fa=\(twoFactorSessionId != nil) passkey=\(passkeySessionId != nil)"
- )
- return SrpLoginResult(
- twoFactorSessionId: twoFactorSessionId,
- passkeySessionId: passkeySessionId,
- accountsUrl: (authResponse.accountsUrl?.isEmpty == false) ? authResponse.accountsUrl : accountsUrlFallback
- )
- }
-
- // 5) Decrypt secrets using the KEK derived in srpStart
- guard let keyAttrsNet = authResponse.keyAttributes else {
- throw EnteError.invalidResponse
- }
-
- let keyAttrs = KeyAttributes(
- kekSalt: keyAttrsNet.kekSalt,
- encryptedKey: keyAttrsNet.encryptedKey,
- keyDecryptionNonce: keyAttrsNet.keyDecryptionNonce,
- publicKey: keyAttrsNet.publicKey,
- encryptedSecretKey: keyAttrsNet.encryptedSecretKey,
- secretKeyDecryptionNonce: keyAttrsNet.secretKeyDecryptionNonce,
- memLimit: UInt32(keyAttrsNet.memLimit),
- opsLimit: UInt32(keyAttrsNet.opsLimit)
- )
-
- let secrets = try await Task.detached(priority: .userInitiated) {
- try srpDecryptSecrets(
- srpM2: authResponse.srpM2 ?? "",
- keyAttrs: keyAttrs,
- encryptedToken: authResponse.encryptedToken,
- plainToken: authResponse.token
- )
- }.value
-
- try storeSecrets(
- email: email,
- userId: authResponse.id.rawValue,
- secrets: secrets
- )
-
- logger.info("SRP login success")
- return SrpLoginResult(twoFactorSessionId: nil, passkeySessionId: nil, accountsUrl: nil)
- } catch {
- logger.error("SRP login failed", error)
- throw error
- }
- }
-
- // MARK: - Continuation (email MFA / 2FA / passkeys)
-
- func loginAfterChallenge(
- email: String,
- password: String,
- srpAttributes: SrpAttributes,
- userId: Int64,
- keyAttributes: KeyAttributes,
- encryptedToken: String?,
- token: String?
- ) async throws {
- logger.info("Login after challenge started")
- var kek = try await Task.detached(priority: .userInitiated) {
- try deriveKekForLogin(
- password: password,
- kekSalt: srpAttributes.kekSalt,
- memLimit: srpAttributes.memLimit,
- opsLimit: srpAttributes.opsLimit
- )
- }.value
- defer {
- // Best-effort zeroing of sensitive material.
- for i in kek.indices { kek[i] = 0 }
- }
-
- let secrets = try await Task.detached(priority: .userInitiated) {
- try decryptSecretsWithKek(
- kek: kek,
- keyAttrs: keyAttributes,
- encryptedToken: encryptedToken,
- plainToken: token
- )
- }.value
-
- try storeSecrets(email: email, userId: userId, secrets: secrets)
- logger.info("Login after challenge success")
- }
-
- // MARK: - Storage
-
- private func storeSecrets(email: String, userId: Int64, secrets: AuthSecrets) throws {
- // Best-effort: avoid leaving key material in temporary buffers longer than necessary.
- var masterKeyBytes = secrets.masterKey
- var secretKeyBytes = secrets.secretKey
- var tokenBytes = secrets.token
- defer {
- for i in masterKeyBytes.indices { masterKeyBytes[i] = 0 }
- for i in secretKeyBytes.indices { secretKeyBytes[i] = 0 }
- for i in tokenBytes.indices { tokenBytes[i] = 0 }
- }
-
- let masterKey = Data(masterKeyBytes)
- let secretKey = Data(secretKeyBytes)
- let token = Data(tokenBytes).base64URLPaddedEncodedString()
-
- if !CredentialStore.shared.isSameUser(userId) {
- CredentialStore.shared.clear()
- }
-
- try CredentialStore.shared.save(
- email: email,
- userId: userId,
- masterKey: masterKey,
- secretKey: secretKey,
- token: token
- )
- }
-}
-
-// MARK: - Response mapping
-
-private extension AuthResponsePayload {
- init(from response: AuthorizationResponse) {
- let keyAttrs: KeyAttributes? = response.keyAttributes.map {
- KeyAttributes(
- kekSalt: $0.kekSalt,
- encryptedKey: $0.encryptedKey,
- keyDecryptionNonce: $0.keyDecryptionNonce,
- publicKey: $0.publicKey,
- encryptedSecretKey: $0.encryptedSecretKey,
- secretKeyDecryptionNonce: $0.secretKeyDecryptionNonce,
- memLimit: UInt32($0.memLimit),
- opsLimit: UInt32($0.opsLimit)
- )
- }
-
- self.init(
- userId: response.id.rawValue,
- keyAttributes: keyAttrs,
- encryptedToken: response.encryptedToken,
- token: response.token,
- twoFactorSessionId: response.effectiveTwoFactorSessionID,
- passkeySessionId: response.passkeySessionID,
- accountsUrl: response.accountsUrl
- )
- }
-}
-
-// MARK: - Passkey errors
-
-struct PasskeySessionNotVerifiedError: Error {}
-struct PasskeySessionExpiredError: Error {}
-struct AccountNotFoundError: Error {}
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAuthTokenProvider.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAuthTokenProvider.swift
deleted file mode 100644
index 67933ea49e..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuAuthTokenProvider.swift
+++ /dev/null
@@ -1,8 +0,0 @@
-import Foundation
-import EnteNetwork
-
-final class EnsuAuthTokenProvider: AuthTokenProvider {
- func getAuthToken() async throws -> String? {
- return CredentialStore.shared.token
- }
-}
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuDeveloperSettings.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuDeveloperSettings.swift
deleted file mode 100644
index 9af26aa29e..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Services/EnsuDeveloperSettings.swift
+++ /dev/null
@@ -1,75 +0,0 @@
-import Foundation
-#if canImport(EnteNetwork)
-import EnteNetwork
-#else
-struct NetworkConfiguration {
- let apiEndpoint: URL
-
- static var `default`: NetworkConfiguration {
- NetworkConfiguration(apiEndpoint: URL(string: "https://api.ente.com")!)
- }
-
- static func selfHosted(baseURL: URL) -> NetworkConfiguration {
- NetworkConfiguration(apiEndpoint: baseURL)
- }
-}
-#endif
-
-enum EnsuDeveloperSettings {
- private static let endpointKey = "ensu.customEndpoint"
- private static let legacyProductionEndpoint = "https://api.ente.io"
-
- static var currentEndpoint: URL? {
- if let envEndpoint = endpointURL(from: ProcessInfo.processInfo.environment["ENTE_API_ENDPOINT"]) {
- return envEndpoint
- }
- if let storedEndpoint = endpointURL(from: UserDefaults.standard.string(forKey: endpointKey)) {
- return storedEndpoint
- }
- return nil
- }
-
- static var currentEndpointString: String {
- if let currentEndpoint {
- return currentEndpoint.absoluteString
- }
- return NetworkConfiguration.default.apiEndpoint.absoluteString
- }
-
- static var networkConfiguration: NetworkConfiguration {
- if let endpoint = currentEndpoint {
- return NetworkConfiguration.selfHosted(baseURL: endpoint)
- }
- return .default
- }
-
- static func setEndpoint(_ url: URL?) {
- if let url {
- let normalized = normalize(url.absoluteString)
- if normalized == legacyProductionEndpoint {
- UserDefaults.standard.removeObject(forKey: endpointKey)
- } else {
- UserDefaults.standard.set(normalized, forKey: endpointKey)
- }
- } else {
- UserDefaults.standard.removeObject(forKey: endpointKey)
- }
- }
-
- private static func endpointURL(from value: String?) -> URL? {
- guard let value, !value.isEmpty else { return nil }
- let normalized = normalize(value)
- if normalized == legacyProductionEndpoint {
- return nil
- }
- return URL(string: normalized)
- }
-
- static func normalize(_ value: String) -> String {
- var trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
- while trimmed.hasSuffix("/") {
- trimmed.removeLast()
- }
- return trimmed
- }
-}
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Settings/DeveloperSettingsView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Settings/DeveloperSettingsView.swift
deleted file mode 100644
index 0b2fe438a6..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Settings/DeveloperSettingsView.swift
+++ /dev/null
@@ -1,211 +0,0 @@
-#if canImport(EnteCore)
-import SwiftUI
-import Foundation
-
-struct DeveloperSettingsView: View {
- @Environment(\.dismiss) private var dismiss
-
- var onSaved: ((String) -> Void)? = nil
-
- @State private var endpoint: String = ""
- @State private var currentEndpoint: String = EnsuDeveloperSettings.currentEndpointString
- @State private var isSaving = false
- @State private var alert: DeveloperSettingsAlert?
- @State private var showModelSettings = false
-
- var body: some View {
- Group {
- #if os(iOS)
- NavigationStack {
- content
- .navigationBarTitleDisplayMode(.inline)
- .toolbar {
- ToolbarItem(placement: .principal) {
- Text("Developer settings")
- .font(EnsuTypography.large)
- .foregroundStyle(EnsuColor.textPrimary)
- }
- ToolbarItem(placement: .primaryAction) {
- Button("Close") {
- dismiss()
- }
- }
- }
- }
- #else
- content
- #endif
- }
- .background(EnsuColor.backgroundBase.ignoresSafeArea())
- .alert(item: $alert) { alert in
- Alert(
- title: Text(alert.title),
- message: Text(alert.message),
- dismissButton: .default(Text("OK"))
- )
- }
- #if os(macOS)
- .sheet(isPresented: $showModelSettings) {
- ModelSettingsView(embeddedInNavigation: true)
- }
- .safeAreaInset(edge: .top) {
- MacSheetHeader(
- leading: {
- EmptyView()
- },
- center: {
- Text("Developer settings")
- .font(EnsuTypography.large)
- .foregroundStyle(EnsuColor.textPrimary)
- },
- trailing: {
- Button("Close") {
- dismiss()
- }
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- .buttonStyle(.plain)
- }
- )
- }
- #endif
- }
-
- private var content: some View {
- VStack(alignment: .leading, spacing: EnsuSpacing.xxl) {
- if EnsuFeatureFlags.enableModelSettings {
- #if os(iOS)
- NavigationLink {
- ModelSettingsView(embeddedInNavigation: true)
- } label: {
- settingsRow(title: "Model settings", subtitle: "Model URL, mmproj, context length")
- }
- .buttonStyle(.plain)
- #else
- Button {
- showModelSettings = true
- } label: {
- settingsRow(title: "Model settings", subtitle: "Model URL, mmproj, context length")
- }
- .buttonStyle(.plain)
- #endif
- }
-
- VStack(alignment: .leading, spacing: 6) {
- Text("Server endpoint")
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
-
- TextField(currentEndpoint, text: $endpoint)
- .font(EnsuTypography.body)
- .platformKeyboardType(.URL)
- .platformTextInputAutocapitalization(.never)
- .foregroundStyle(EnsuColor.textPrimary)
- .platformTextFieldStyle()
- .autocorrectionDisabled()
- .padding(.horizontal, EnsuSpacing.inputHorizontal)
- .padding(.vertical, EnsuSpacing.inputVertical)
- .background(EnsuColor.fillFaint)
- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))
-
- Text("Current endpoint: \(currentEndpoint)")
- .font(EnsuTypography.mini)
- .foregroundStyle(EnsuColor.textMuted)
- }
-
- PrimaryButton(text: "Save", isLoading: isSaving, isEnabled: isSavable) {
- Task { await saveTapped() }
- }
-
- Spacer()
- }
- .padding(EnsuSpacing.lg)
- }
-
- private func settingsRow(title: String, subtitle: String?) -> some View {
- HStack {
- VStack(alignment: .leading, spacing: 4) {
- Text(title)
- .font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textPrimary)
- if let subtitle {
- Text(subtitle)
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- }
- }
- Spacer()
- Image("ArrowRight01Icon")
- .resizable()
- .scaledToFit()
- .frame(width: 18, height: 18)
- .foregroundStyle(EnsuColor.textMuted)
- }
- .padding(EnsuSpacing.lg)
- .background(EnsuColor.fillFaint)
- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous))
- }
-
- private var isSavable: Bool {
- !endpoint.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !isSaving
- }
-
- @MainActor
- private func saveTapped() async {
- guard !isSaving else { return }
- let normalized = EnsuDeveloperSettings.normalize(endpoint)
- guard let url = URL(string: normalized),
- let scheme = url.scheme?.lowercased(),
- scheme == "http" || scheme == "https" else {
- alert = DeveloperSettingsAlert(
- title: "Invalid endpoint",
- message: "Please enter a valid server endpoint."
- )
- return
- }
-
- isSaving = true
- defer { isSaving = false }
-
- do {
- try await ping(endpoint: url)
- EnsuAuthService.shared.updateEndpoint(url)
- onSaved?("Endpoint updated")
- dismiss()
- } catch {
- alert = DeveloperSettingsAlert(
- title: "Invalid endpoint",
- message: "Unable to reach the server at the provided endpoint."
- )
- }
- }
-
- private func ping(endpoint: URL) async throws {
- let pingURL = endpoint.appendingPathComponent("ping")
- let (data, response) = try await URLSession.shared.data(from: pingURL)
- guard let httpResponse = response as? HTTPURLResponse,
- (200...299).contains(httpResponse.statusCode) else {
- throw URLError(.badServerResponse)
- }
- let json = try JSONSerialization.jsonObject(with: data)
- guard let payload = json as? [String: Any],
- payload["message"] as? String == "pong" else {
- throw URLError(.cannotParseResponse)
- }
- }
-}
-
-private struct DeveloperSettingsAlert: Identifiable {
- let id = UUID()
- let title: String
- let message: String
-}
-#else
-import SwiftUI
-
-struct DeveloperSettingsView: View {
- var body: some View {
- Text("Developer settings unavailable")
- }
-}
-#endif
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Settings/SettingsView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Settings/SettingsView.swift
index 6866e539ca..109c50fd7f 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Settings/SettingsView.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Settings/SettingsView.swift
@@ -3,17 +3,12 @@ import SwiftUI
import Foundation
struct SettingsView: View {
- let isLoggedIn: Bool
- let email: String?
- let showsSignInOption: Bool
- let onSignOut: () -> Void
let onSignIn: () -> Void
@Environment(\.dismiss) private var dismiss
@Environment(\.openURL) private var openURL
@State private var query: String = ""
- @State private var showSignOutConfirm = false
@State private var buildVersionTapCount = 0
@State private var lastBuildVersionTapAt: Date?
@State private var isAdvancedUnlocked = EnsuAdvancedSettings.isUnlocked
@@ -24,10 +19,6 @@ struct SettingsView: View {
NavigationStack {
ScrollView {
VStack(alignment: .leading, spacing: EnsuSpacing.lg) {
- if let email, isLoggedIn, trimmedQuery.isEmpty {
- signedInCard(email: email)
- }
-
if let aboutItem = filteredAboutItem {
Button(action: aboutItem.action) {
settingsCard(title: aboutItem.title, iconName: aboutItem.iconName, showsChevron: true)
@@ -44,13 +35,6 @@ struct SettingsView: View {
.buttonStyle(.plain)
}
- ForEach(filteredAccountItems) { item in
- Button(action: item.action) {
- settingsCard(title: item.title, iconName: item.iconName, showsChevron: true)
- }
- .buttonStyle(.plain)
- }
-
if shouldShowSignInRow {
Button(action: onSignIn) {
settingsCard(title: signInTitle, iconName: "Upload01Icon", showsChevron: true)
@@ -81,15 +65,6 @@ struct SettingsView: View {
}
}
- if let endpointInfoText {
- Text(endpointInfoText)
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- .multilineTextAlignment(.center)
- .frame(maxWidth: .infinity, alignment: .center)
- .padding(.vertical, 8)
- }
-
Button(action: handleBuildVersionTap) {
Text(buildVersionText)
.font(EnsuTypography.small)
@@ -119,14 +94,6 @@ struct SettingsView: View {
Button("Close") { dismiss() }
}
}
- .alert("Sign out of Ensu?", isPresented: $showSignOutConfirm) {
- Button("Sign Out", role: .destructive) {
- onSignOut()
- }
- Button("Cancel", role: .cancel) {}
- } message: {
- Text("Signing out will remove your online chats from this device. Offline chats stay available.")
- }
.overlay(alignment: .bottom) {
if let toastMessage {
ToastView(message: toastMessage)
@@ -177,30 +144,6 @@ struct SettingsView: View {
]
}
- private var accountItems: [SettingsActionItem] {
- guard isLoggedIn else { return [] }
- return [
- SettingsActionItem(
- title: "Delete Account",
- iconName: "Delete01Icon",
- action: { openDeleteAccountEmail() }
- ),
- SettingsActionItem(
- title: "Sign Out",
- iconName: "Cancel01Icon",
- action: { showSignOutConfirm = true }
- )
- ]
- }
-
- private var filteredAccountItems: [SettingsActionItem] {
- guard !trimmedQuery.isEmpty else { return accountItems }
- let q = trimmedQuery.lowercased()
- return accountItems.filter { item in
- item.title.lowercased().contains(q)
- }
- }
-
private var filteredAboutItem: SettingsActionItem? {
guard !trimmedQuery.isEmpty else { return aboutItem }
let q = trimmedQuery.lowercased()
@@ -216,8 +159,6 @@ struct SettingsView: View {
}
private var shouldShowSignInRow: Bool {
- guard showsSignInOption else { return false }
- guard !isLoggedIn else { return false }
guard !trimmedQuery.isEmpty else { return true }
let q = trimmedQuery.lowercased()
return signInTitle.lowercased().contains(q)
@@ -254,18 +195,6 @@ struct SettingsView: View {
isAdvancedUnlocked && !filteredAdvancedItems.isEmpty
}
- private var endpointInfoText: String? {
- guard trimmedQuery.isEmpty else { return nil }
-
- let defaultEndpoint = "https://api.ente.com"
- let endpoint = EnsuDeveloperSettings.currentEndpointString
- .trimmingCharacters(in: .whitespacesAndNewlines)
- .trimmingCharacters(in: CharacterSet(charactersIn: "/"))
-
- guard !endpoint.isEmpty, endpoint != defaultEndpoint else { return nil }
- return "Endpoint: \(endpoint)"
- }
-
private var trimmedQuery: String {
query.trimmingCharacters(in: .whitespacesAndNewlines)
}
@@ -277,13 +206,6 @@ struct SettingsView: View {
return "Build \(version) (\(build))"
}
- private func openDeleteAccountEmail() {
- let subject = "Request Deletion for Ente Account"
- let encoded = subject.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? subject
- guard let url = URL(string: "mailto:[email protected]?subject=\(encoded)") else { return }
- openURL(url)
- }
-
private func handleBuildVersionTap() {
guard !isAdvancedUnlocked else { return }
let now = Date()
@@ -307,22 +229,6 @@ struct SettingsView: View {
openURL(url)
}
- private func signedInCard(email: String) -> some View {
- VStack(alignment: .leading, spacing: 4) {
- Text("Signed in as")
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- Text(email)
- .font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textPrimary)
- .frame(maxWidth: .infinity, alignment: .leading)
- }
- .padding(EnsuSpacing.lg)
- .frame(maxWidth: .infinity, alignment: .leading)
- .background(EnsuColor.fillFaint)
- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous))
- }
-
private func settingsCard(title: String, iconName: String, showsChevron: Bool) -> some View {
HStack(spacing: EnsuSpacing.md) {
Image(iconName)
@@ -529,10 +435,6 @@ private struct SettingsActionItem: Identifiable {
import SwiftUI
struct SettingsView: View {
- let isLoggedIn: Bool
- let email: String?
- let showsSignInOption: Bool
- let onSignOut: () -> Void
let onSignIn: () -> Void
var body: some View {
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Utils/Base64URL.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Utils/Base64URL.swift
deleted file mode 100644
index d55109c4f0..0000000000
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Utils/Base64URL.swift
+++ /dev/null
@@ -1,36 +0,0 @@
-import Foundation
-
-extension Data {
- /// Encode data as URL-safe base64 (RFC 4648 Β§5), **without padding**.
- func base64URLEncodedString() -> String {
- let b64 = self.base64EncodedString()
- return b64
- .replacingOccurrences(of: "+", with: "-")
- .replacingOccurrences(of: "/", with: "_")
- .replacingOccurrences(of: "=", with: "")
- }
-
- /// Encode data as URL-safe base64 (RFC 4648 Β§5), **with padding**.
- ///
- /// Ente auth tokens are generated by the server using Go's `base64.URLEncoding`,
- /// which is URL-safe **and includes padding**. Clients must preserve padding
- /// when re-encoding token bytes.
- func base64URLPaddedEncodedString() -> String {
- let b64 = self.base64EncodedString()
- return b64
- .replacingOccurrences(of: "+", with: "-")
- .replacingOccurrences(of: "/", with: "_")
- }
-
- /// Decode a URL-safe base64 string (with or without padding).
- init?(base64URLString: String) {
- var s = base64URLString
- .replacingOccurrences(of: "-", with: "+")
- .replacingOccurrences(of: "_", with: "/")
- let remainder = s.count % 4
- if remainder != 0 {
- s.append(String(repeating: "=", count: 4 - remainder))
- }
- self.init(base64Encoded: s)
- }
-}
diff --git a/mobile/native/darwin/Apps/Ensu/README.md b/mobile/native/darwin/Apps/Ensu/README.md
index 345bbca1c7..4309b153bc 100644
--- a/mobile/native/darwin/Apps/Ensu/README.md
+++ b/mobile/native/darwin/Apps/Ensu/README.md
@@ -27,8 +27,6 @@ That's it. Apart from the `cargo codegen`, this is a normal iOS project. Xcode c
> (cd "$(git rev-parse --show-toplevel)/rust" && cargo codegen native)
> ```
-A custom endpoint can be baked into the build via `xcodebuild ENTE_API_ENDPOINT=http://localhost:8080 ...` or by editing the user-defined `ENTE_API_ENDPOINT` build setting in the `Ensu` target.
-
## Terminal builds
> [!NOTE]
diff --git a/mobile/native/darwin/Apps/Ensu/scripts/build-rust.sh b/mobile/native/darwin/Apps/Ensu/scripts/build-rust.sh
index f05d1e5651..9bf8db9fe4 100755
--- a/mobile/native/darwin/Apps/Ensu/scripts/build-rust.sh
+++ b/mobile/native/darwin/Apps/Ensu/scripts/build-rust.sh
@@ -20,7 +20,7 @@ for tool in cargo rustup cmake; do
command -v "$tool" >/dev/null || { echo "error: $tool not on PATH" >&2; exit 1; }
done
-for name in core db inference transcription; do
+for name in db inference transcription; do
for ext in .swift FFI.h FFI.modulemap; do
[[ -f "$GENERATED_DIR/$name$ext" ]] || {
echo "error: missing $GENERATED_DIR/$name$ext" >&2
@@ -30,22 +30,6 @@ for name in core db inference transcription; do
done
done
-# Bake ENTE_API_ENDPOINT into a generated Swift file.
-endpoint=$(printf '%s' "${ENTE_API_ENDPOINT:-}" | tr -d '\n\r' \
- | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
-if [[ -n "$endpoint" ]]; then
- escaped=${endpoint//\\/\\\\}; escaped=${escaped//\"/\\\"}
- literal="\"$escaped\""
-else
- literal="nil"
-fi
-cat >"$GENERATED_DIR/EndpointConfig.swift" <<EOF
-// Generated by scripts/build-rust.sh. Do not edit manually.
-enum BuildEndpointConfig {
- static let endpoint: String? = $literal
-}
-EOF
-
# Host build scripts compile against macOS; each target uses its own SDK below.
SDKROOT=$(xcrun --sdk macosx --show-sdk-path)
TARGET_SDKROOT=$(xcrun --sdk "$PLATFORM_NAME" --show-sdk-path)
@@ -120,7 +104,6 @@ build_crate() {
echo " -> $out"
}
-build_crate core "$REPO_ROOT/rust/bindings/uniffi/core" libcore.a
build_crate db "$REPO_ROOT/rust/bindings/uniffi/ensu/db" libdb.a
build_crate inference "$REPO_ROOT/rust/bindings/uniffi/ensu/inference" libinference.a
build_crate transcription "$REPO_ROOT/rust/bindings/uniffi/ensu/transcription" libtranscription.a
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index ce9b3641f0..aa747c3724 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -1366,17 +1366,6 @@ dependencies = [
"version_check",
]
-[[package]]
-name = "core"
-version = "0.0.0"
-dependencies = [
- "base64 0.22.1",
- "ente-core",
- "once_cell",
- "thiserror 1.0.69",
- "uniffi",
-]
-
[[package]]
name = "core-foundation"
version = "0.9.4"
@@ -9463,7 +9452,6 @@ dependencies = [
"anyhow",
"cargo_metadata 0.19.2",
"uniffi_bindgen",
- "uniffi_build",
"uniffi_core",
"uniffi_macros",
"uniffi_pipeline",
@@ -9495,17 +9483,6 @@ dependencies = [
"uniffi_udl",
]
-[[package]]
-name = "uniffi_build"
-version = "0.31.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b78fd9271a4c2e85bd2c266c5a9ede1fac676eb39fd77f636c27eaf67426fd5f"
-dependencies = [
- "anyhow",
- "camino",
- "uniffi_bindgen",
-]
-
[[package]]
name = "uniffi_core"
version = "0.31.0"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index c7f532f903..5df7aa68c2 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -7,7 +7,6 @@ members = [
"bindings/ffi/crypto",
"bindings/frb/ente-rust",
"bindings/frb/photos",
- "bindings/uniffi/core",
"bindings/uniffi/ensu/db",
"bindings/uniffi/ensu/inference",
"bindings/uniffi/ensu/transcription",
diff --git a/rust/apps/codegen/src/main.rs b/rust/apps/codegen/src/main.rs
index 809efac921..ea99746021 100644
--- a/rust/apps/codegen/src/main.rs
+++ b/rust/apps/codegen/src/main.rs
@@ -77,10 +77,6 @@ fn generate_native_ios() -> Result<(), DynError> {
fs::create_dir_all(&generated_dir)?;
let crates = [
- UniffiCrate {
- crate_name: "core",
- crate_dir: rust_root.join("bindings/uniffi/core"),
- },
UniffiCrate {
crate_name: "db",
crate_dir: rust_root.join("bindings/uniffi/ensu/db"),
@@ -114,22 +110,11 @@ fn generate_native_android() -> Result<(), DynError> {
let repo_root = rust_root
.parent()
.ok_or("failed to resolve repo root from rust/apps/codegen")?;
- let core_out_dir =
- repo_root.join("mobile/native/android/apps/ensu/crypto-auth-core/src/main/java");
let rust_out_dir = repo_root.join("mobile/native/android/packages/rust/src/main/kotlin");
- fs::create_dir_all(&core_out_dir)?;
fs::create_dir_all(&rust_out_dir)?;
let crates = [
- AndroidCrate {
- uniffi: UniffiCrate {
- crate_name: "core",
- crate_dir: rust_root.join("bindings/uniffi/core"),
- },
- out_dir: core_out_dir.clone(),
- stale_path: core_out_dir.join("io/ente/ensu/crypto/core.kt"),
- },
AndroidCrate {
uniffi: UniffiCrate {
crate_name: "db",
diff --git a/rust/apps/ensu/src-tauri/Cargo.toml b/rust/apps/ensu/src-tauri/Cargo.toml
index 9a52424362..1755885cd5 100644
--- a/rust/apps/ensu/src-tauri/Cargo.toml
+++ b/rust/apps/ensu/src-tauri/Cargo.toml
@@ -16,7 +16,7 @@ tauri-plugin-updater = "2.10.1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
ensu-db.workspace = true
-ente-core = { workspace = true, features = ["srp"] }
+ente-core.workspace = true
inference_rs.workspace = true
uuid = { version = "1", features = ["v4"] }
keyring = { version = "3", default-features = false, features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] }
diff --git a/rust/apps/ensu/src-tauri/src/commands.rs b/rust/apps/ensu/src-tauri/src/commands.rs
index 0fb3b59b51..c84f73f427 100644
--- a/rust/apps/ensu/src-tauri/src/commands.rs
+++ b/rust/apps/ensu/src-tauri/src/commands.rs
@@ -9,7 +9,7 @@ use std::time::{Duration, Instant};
use ensu_db::backend::sqlite::SqliteBackend;
use ensu_db::{EnsuDb, Error as DbError};
-use ente_core::{auth as core_auth, crypto as core_crypto};
+use ente_core::crypto as core_crypto;
use inference_rs as llm;
use serde::{Deserialize, Serialize};
use tauri::async_runtime;
@@ -18,11 +18,6 @@ use uuid::Uuid;
use crate::logging;
-#[derive(Default)]
-pub struct SrpState {
- sessions: Mutex<HashMap<String, core_auth::SrpSession>>,
-}
-
#[derive(Default)]
pub struct LlmState {
model: Mutex<Option<llm::ModelHandleRef>>,
@@ -256,26 +251,6 @@ fn total_memory_bytes() -> Option<u64> {
None
}
-impl From<core_auth::AuthError> for ApiError {
- fn from(e: core_auth::AuthError) -> Self {
- use core_auth::AuthError as E;
-
- let code = match &e {
- E::IncorrectPassword => "incorrect_password",
- E::IncorrectRecoveryKey => "incorrect_recovery_key",
- E::InvalidKeyAttributes => "invalid_key_attributes",
- E::InsufficientMemory => "insufficient_memory",
- E::MissingField(_) => "missing_field",
- E::Crypto(_) => "crypto",
- E::Decode(_) => "decode",
- E::InvalidKey(_) => "invalid_key",
- E::Srp(_) => "srp",
- };
-
- ApiError::new(code, e.to_string())
- }
-}
-
impl From<core_crypto::CryptoError> for ApiError {
fn from(e: core_crypto::CryptoError) -> Self {
use core_crypto::CryptoError as E;
@@ -337,25 +312,6 @@ impl From<DbError> for ApiError {
}
}
-#[derive(Serialize)]
-pub struct SrpCredentials {
- kek: String,
- login_key: String,
-}
-
-#[derive(Serialize)]
-pub struct DecryptedSecrets {
- master_key: String,
- secret_key: String,
- token: String,
-}
-
-#[derive(Serialize)]
-pub struct DecryptedKeys {
- master_key: String,
- secret_key: String,
-}
-
#[derive(Serialize)]
pub struct EncryptedBox {
encrypted_data: String,
@@ -368,56 +324,6 @@ pub struct EncryptedBlob {
decryption_header: String,
}
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SrpSessionNewInput {
- srp_user_id: String,
- srp_salt_b64: String,
- login_key_b64: String,
-}
-
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SrpSessionComputeInput {
- session_id: String,
- srp_b64: String,
-}
-
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SrpSessionVerifyInput {
- session_id: String,
- srp_m2_b64: String,
-}
-
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SrpSessionLookupInput {
- session_id: String,
-}
-
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DeriveSrpCredentialsInput {
- password: String,
- srp_attrs: core_auth::SrpAttributes,
-}
-
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DecryptSecretsInput {
- kek_b64: String,
- key_attrs: core_auth::KeyAttributes,
- encrypted_token_b64: String,
-}
-
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DecryptKeysInput {
- kek_b64: String,
- key_attrs: core_auth::KeyAttributes,
-}
-
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CryptoBoxInput {
@@ -509,123 +415,6 @@ pub fn crypto_decrypt_blob(input: CryptoBlobDecryptInput) -> Result<String, ApiE
Ok(core_crypto::encode_b64(&plaintext))
}
-#[tauri::command]
-pub fn auth_derive_srp_credentials(
- input: DeriveSrpCredentialsInput,
-) -> Result<SrpCredentials, ApiError> {
- let creds = core_auth::derive_srp_credentials(&input.password, &input.srp_attrs)?;
- Ok(SrpCredentials {
- kek: core_crypto::encode_b64(&creds.kek),
- login_key: core_crypto::encode_b64(&creds.login_key),
- })
-}
-
-#[tauri::command]
-pub fn auth_decrypt_secrets(input: DecryptSecretsInput) -> Result<DecryptedSecrets, ApiError> {
- let kek = core_crypto::decode_b64(&input.kek_b64)
- .map_err(|e| ApiError::new("decode", format!("kek: {}", e)))?;
-
- let secrets = core_auth::decrypt_secrets(&kek, &input.key_attrs, &input.encrypted_token_b64)?;
-
- Ok(DecryptedSecrets {
- master_key: core_crypto::encode_b64(&secrets.master_key),
- secret_key: core_crypto::encode_b64(&secrets.secret_key),
- token: core_crypto::encode_b64_url_safe(&secrets.token),
- })
-}
-
-#[tauri::command]
-pub fn auth_decrypt_keys_only(input: DecryptKeysInput) -> Result<DecryptedKeys, ApiError> {
- let kek = core_crypto::decode_b64(&input.kek_b64)
- .map_err(|e| ApiError::new("decode", format!("kek: {}", e)))?;
-
- let (master_key, secret_key) = core_auth::decrypt_keys_only(&kek, &input.key_attrs)?;
-
- Ok(DecryptedKeys {
- master_key: core_crypto::encode_b64(&master_key),
- secret_key: core_crypto::encode_b64(&secret_key),
- })
-}
-
-#[tauri::command]
-pub fn srp_session_new(
- state: State<SrpState>,
- input: SrpSessionNewInput,
-) -> Result<String, ApiError> {
- let srp_salt = core_crypto::decode_b64(&input.srp_salt_b64)
- .map_err(|e| ApiError::new("decode", format!("srp_salt: {}", e)))?;
- let login_key = core_crypto::decode_b64(&input.login_key_b64)
- .map_err(|e| ApiError::new("decode", format!("login_key: {}", e)))?;
-
- let session = core_auth::SrpSession::new(&input.srp_user_id, &srp_salt, &login_key)?;
-
- let session_id = Uuid::new_v4().to_string();
- let mut sessions = state
- .sessions
- .lock()
- .map_err(|_| ApiError::new("lock", "Failed to lock SRP session store"))?;
- sessions.insert(session_id.clone(), session);
-
- Ok(session_id)
-}
-
-#[tauri::command]
-pub fn srp_session_public_a(
- state: State<SrpState>,
- input: SrpSessionLookupInput,
-) -> Result<String, ApiError> {
- let sessions = state
- .sessions
- .lock()
- .map_err(|_| ApiError::new("lock", "Failed to lock SRP session store"))?;
- let session = sessions
- .get(&input.session_id)
- .ok_or_else(|| ApiError::new("srp_session_not_found", "SRP session not found"))?;
-
- Ok(core_crypto::encode_b64(&session.public_a()))
-}
-
-#[tauri::command]
-pub fn srp_session_compute_m1(
- state: State<SrpState>,
- input: SrpSessionComputeInput,
-) -> Result<String, ApiError> {
- let srp_b = core_crypto::decode_b64(&input.srp_b64)
- .map_err(|e| ApiError::new("decode", format!("srpB: {}", e)))?;
-
- let mut sessions = state
- .sessions
- .lock()
- .map_err(|_| ApiError::new("lock", "Failed to lock SRP session store"))?;
- let session = sessions
- .get_mut(&input.session_id)
- .ok_or_else(|| ApiError::new("srp_session_not_found", "SRP session not found"))?;
-
- let m1 = session.compute_m1(&srp_b)?;
- Ok(core_crypto::encode_b64(&m1))
-}
-
-#[tauri::command]
-pub fn srp_session_verify_m2(
- state: State<SrpState>,
- input: SrpSessionVerifyInput,
-) -> Result<(), ApiError> {
- let srp_m2 = core_crypto::decode_b64(&input.srp_m2_b64)
- .map_err(|e| ApiError::new("decode", format!("srpM2: {}", e)))?;
-
- let mut sessions = state
- .sessions
- .lock()
- .map_err(|_| ApiError::new("lock", "Failed to lock SRP session store"))?;
- let session = sessions
- .get(&input.session_id)
- .ok_or_else(|| ApiError::new("srp_session_not_found", "SRP session not found"))?;
-
- session.verify_m2(&srp_m2)?;
- sessions.remove(&input.session_id);
- Ok(())
-}
-
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatSessionDto {
diff --git a/rust/apps/ensu/src-tauri/src/main.rs b/rust/apps/ensu/src-tauri/src/main.rs
index 1806a8409d..7ba194e9da 100644
--- a/rust/apps/ensu/src-tauri/src/main.rs
+++ b/rust/apps/ensu/src-tauri/src/main.rs
@@ -15,7 +15,6 @@ fn main() {
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_updater::Builder::new().build())
- .manage(commands::SrpState::default())
.manage(commands::LlmState::default())
.manage(commands::LlmModelDownloadState::default())
.manage(commands::ChatDbState::default())
@@ -43,13 +42,6 @@ fn main() {
commands::secure_storage_get,
commands::secure_storage_set,
commands::secure_storage_delete,
- commands::auth_derive_srp_credentials,
- commands::auth_decrypt_secrets,
- commands::auth_decrypt_keys_only,
- commands::srp_session_new,
- commands::srp_session_public_a,
- commands::srp_session_compute_m1,
- commands::srp_session_verify_m2,
commands::chat_db_list_sessions,
commands::chat_db_list_sessions_with_preview,
commands::chat_db_get_session,
diff --git a/rust/bindings/uniffi/core/Cargo.toml b/rust/bindings/uniffi/core/Cargo.toml
deleted file mode 100644
index d11d0603c1..0000000000
--- a/rust/bindings/uniffi/core/Cargo.toml
+++ /dev/null
@@ -1,16 +0,0 @@
-[package]
-name = "core"
-edition = "2024"
-
-[lib]
-crate-type = ["cdylib", "staticlib"]
-
-[dependencies]
-base64 = "0.22"
-once_cell = "1.19"
-thiserror = "1.0"
-uniffi = "0.31.0"
-ente-core = { workspace = true, features = ["srp"] }
-
-[build-dependencies]
-uniffi = { version = "0.31.0", features = ["build"] }
diff --git a/rust/bindings/uniffi/core/build.rs b/rust/bindings/uniffi/core/build.rs
deleted file mode 100644
index 3ba6250208..0000000000
--- a/rust/bindings/uniffi/core/build.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-fn main() {
- uniffi::generate_scaffolding("./src/core.udl").unwrap();
-}
diff --git a/rust/bindings/uniffi/core/src/core.udl b/rust/bindings/uniffi/core/src/core.udl
deleted file mode 100644
index 9666b4f4cd..0000000000
--- a/rust/bindings/uniffi/core/src/core.udl
+++ /dev/null
@@ -1,60 +0,0 @@
-dictionary AuthSecrets {
- sequence<u8> master_key;
- sequence<u8> secret_key;
- sequence<u8> token;
-};
-
-dictionary KeyAttributes {
- string kek_salt;
- string encrypted_key;
- string key_decryption_nonce;
- string public_key;
- string encrypted_secret_key;
- string secret_key_decryption_nonce;
- u32? mem_limit;
- u32? ops_limit;
-};
-
-dictionary SrpAttributes {
- string srp_user_id;
- string srp_salt;
- string kek_salt;
- u32 mem_limit;
- u32 ops_limit;
- boolean is_email_mfa_enabled;
-};
-
-dictionary SrpSessionResult {
- string srp_a;
-};
-
-dictionary SrpVerifyResult {
- string srp_m1;
-};
-
-[Error]
-interface EnsuError {
- Message(string reason);
-};
-
-namespace core {
- [Throws=EnsuError]
- void init_crypto();
-
- [Throws=EnsuError]
- SrpSessionResult srp_start(string password, SrpAttributes srp_attrs);
-
- [Throws=EnsuError]
- SrpVerifyResult srp_finish(string srp_b);
-
- void srp_clear();
-
- [Throws=EnsuError]
- AuthSecrets srp_decrypt_secrets(string srp_m2, KeyAttributes key_attrs, string? encrypted_token, string? plain_token);
-
- [Throws=EnsuError]
- sequence<u8> derive_kek_for_login(string password, string kek_salt, u32 mem_limit, u32 ops_limit);
-
- [Throws=EnsuError]
- AuthSecrets decrypt_secrets_with_kek(sequence<u8> kek, KeyAttributes key_attrs, string? encrypted_token, string? plain_token);
-};
diff --git a/rust/bindings/uniffi/core/src/lib.rs b/rust/bindings/uniffi/core/src/lib.rs
deleted file mode 100644
index cd78293f88..0000000000
--- a/rust/bindings/uniffi/core/src/lib.rs
+++ /dev/null
@@ -1,341 +0,0 @@
-use base64::{
- Engine,
- engine::general_purpose::{STANDARD as BASE64_STANDARD, URL_SAFE as BASE64_URL_SAFE},
-};
-use once_cell::sync::Lazy;
-use std::sync::{Mutex, MutexGuard};
-
-use ente_core::{auth, crypto};
-
-uniffi::include_scaffolding!("core");
-
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub struct AuthSecrets {
- pub master_key: Vec<u8>,
- pub secret_key: Vec<u8>,
- pub token: Vec<u8>,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub struct KeyAttributes {
- pub kek_salt: String,
- pub encrypted_key: String,
- pub key_decryption_nonce: String,
- pub public_key: String,
- pub encrypted_secret_key: String,
- pub secret_key_decryption_nonce: String,
- pub mem_limit: Option<u32>,
- pub ops_limit: Option<u32>,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub struct SrpAttributes {
- pub srp_user_id: String,
- pub srp_salt: String,
- pub kek_salt: String,
- pub mem_limit: u32,
- pub ops_limit: u32,
- pub is_email_mfa_enabled: bool,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub struct SrpSessionResult {
- pub srp_a: String,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub struct SrpVerifyResult {
- pub srp_m1: String,
-}
-
-#[derive(Debug, thiserror::Error)]
-pub enum EnsuError {
- #[error("{reason}")]
- Message { reason: String },
-}
-
-impl From<auth::AuthError> for EnsuError {
- fn from(err: auth::AuthError) -> Self {
- EnsuError::Message {
- reason: err.to_string(),
- }
- }
-}
-
-struct SrpState {
- session: auth::SrpSession,
- kek: crypto::SecretVec,
-}
-
-static SRP_STATE: Lazy<Mutex<Option<SrpState>>> = Lazy::new(|| Mutex::new(None));
-
-fn lock_srp_state() -> Result<MutexGuard<'static, Option<SrpState>>, EnsuError> {
- SRP_STATE.lock().map_err(|_| EnsuError::Message {
- reason: "SRP state lock poisoned".to_string(),
- })
-}
-
-fn to_core_key_attrs(attrs: &KeyAttributes) -> auth::KeyAttributes {
- auth::KeyAttributes {
- kek_salt: attrs.kek_salt.clone(),
- encrypted_key: attrs.encrypted_key.clone(),
- key_decryption_nonce: attrs.key_decryption_nonce.clone(),
- public_key: attrs.public_key.clone(),
- encrypted_secret_key: attrs.encrypted_secret_key.clone(),
- secret_key_decryption_nonce: attrs.secret_key_decryption_nonce.clone(),
- mem_limit: attrs.mem_limit,
- ops_limit: attrs.ops_limit,
- master_key_encrypted_with_recovery_key: None,
- master_key_decryption_nonce: None,
- recovery_key_encrypted_with_master_key: None,
- recovery_key_decryption_nonce: None,
- }
-}
-
-fn to_core_srp_attrs(attrs: &SrpAttributes) -> auth::SrpAttributes {
- auth::SrpAttributes {
- srp_user_id: attrs.srp_user_id.clone(),
- srp_salt: attrs.srp_salt.clone(),
- mem_limit: attrs.mem_limit,
- ops_limit: attrs.ops_limit,
- kek_salt: attrs.kek_salt.clone(),
- is_email_mfa_enabled: attrs.is_email_mfa_enabled,
- }
-}
-
-fn secrets_from_login_result(result: auth::LoginResult) -> AuthSecrets {
- AuthSecrets {
- master_key: result.master_key.into_vec(),
- secret_key: result.secret_key.into_vec(),
- token: result.token.into_vec(),
- }
-}
-
-fn secrets_from_decrypted(result: auth::DecryptedSecrets) -> AuthSecrets {
- AuthSecrets {
- master_key: result.master_key.into_vec(),
- secret_key: result.secret_key.into_vec(),
- token: result.token.into_vec(),
- }
-}
-
-fn decode_token(token: &str) -> Result<Vec<u8>, EnsuError> {
- // Tokens are generated by the server as base64 URL-safe with padding
- // (Go's base64.URLEncoding). Older tokens might still be standard base64.
- BASE64_URL_SAFE
- .decode(token)
- .or_else(|_| BASE64_STANDARD.decode(token))
- .map_err(|e| EnsuError::Message {
- reason: format!("token: {}", e),
- })
-}
-
-fn verify_srp_m2(session: &auth::SrpSession, srp_m2_b64: &str) -> Result<(), EnsuError> {
- if srp_m2_b64.is_empty() {
- return Err(EnsuError::Message {
- reason: "Missing server proof".to_string(),
- });
- }
-
- let srp_m2 = crypto::decode_b64(srp_m2_b64).map_err(|e| EnsuError::Message {
- reason: format!("srp_m2: {}", e),
- })?;
- session.verify_m2(&srp_m2)?;
- Ok(())
-}
-
-pub fn init_crypto() -> Result<(), EnsuError> {
- // No-op, kept only for binding compatibility: the pure-Rust crypto needs
- // no initialization.
- Ok(())
-}
-
-pub fn srp_start(
- password: String,
- srp_attrs: SrpAttributes,
-) -> Result<SrpSessionResult, EnsuError> {
- let srp_attrs_core = to_core_srp_attrs(&srp_attrs);
- let creds = auth::derive_srp_credentials(&password, &srp_attrs_core)?;
-
- let srp_salt = crypto::decode_b64(&srp_attrs.srp_salt).map_err(|e| EnsuError::Message {
- reason: format!("srp_salt: {}", e),
- })?;
-
- let session = auth::SrpSession::new(&srp_attrs.srp_user_id, &srp_salt, &creds.login_key)?;
- let srp_a = crypto::encode_b64(&session.public_a());
-
- let mut guard = lock_srp_state()?;
- if guard.is_some() {
- return Err(EnsuError::Message {
- reason:
- "SRP session already initialized. Call srp_clear() before starting a new session"
- .to_string(),
- });
- }
-
- *guard = Some(SrpState {
- session,
- kek: creds.kek,
- });
-
- Ok(SrpSessionResult { srp_a })
-}
-
-pub fn srp_finish(srp_b: String) -> Result<SrpVerifyResult, EnsuError> {
- let mut guard = lock_srp_state()?;
- let state = guard.as_mut().ok_or_else(|| EnsuError::Message {
- reason: "SRP session not initialized".to_string(),
- })?;
-
- let srp_b_bytes = crypto::decode_b64(&srp_b).map_err(|e| EnsuError::Message {
- reason: format!("srp_b: {}", e),
- })?;
-
- let srp_m1 = state.session.compute_m1(&srp_b_bytes)?;
- let srp_m1 = crypto::encode_b64(&srp_m1);
-
- Ok(SrpVerifyResult { srp_m1 })
-}
-
-pub fn srp_clear() {
- // Best-effort cleanup. Even if the lock is poisoned, we should avoid panicking.
- match SRP_STATE.lock() {
- Ok(mut guard) => {
- *guard = None;
- }
- Err(poisoned) => {
- let mut guard = poisoned.into_inner();
- *guard = None;
- }
- }
-}
-
-pub fn srp_decrypt_secrets(
- srp_m2: String,
- key_attrs: KeyAttributes,
- encrypted_token: Option<String>,
- plain_token: Option<String>,
-) -> Result<AuthSecrets, EnsuError> {
- // Consume the SRP state up front so any downstream failure also clears the
- // KEK and lets callers start a fresh session.
- let mut guard = lock_srp_state()?;
- let state = guard.take().ok_or_else(|| EnsuError::Message {
- reason: "SRP session not initialized".to_string(),
- })?;
- verify_srp_m2(&state.session, &srp_m2)?;
-
- let core_attrs = to_core_key_attrs(&key_attrs);
-
- if let Some(token) = encrypted_token {
- let result = auth::decrypt_secrets(&state.kek, &core_attrs, &token)?;
- return Ok(secrets_from_decrypted(result));
- }
-
- if let Some(token) = plain_token {
- let (master_key, secret_key) = auth::decrypt_keys_only(&state.kek, &core_attrs)?;
- let token_bytes = decode_token(&token)?;
- return Ok(AuthSecrets {
- master_key: master_key.into_vec(),
- secret_key: secret_key.into_vec(),
- token: token_bytes,
- });
- }
-
- Err(EnsuError::Message {
- reason: "Missing auth token".to_string(),
- })
-}
-
-pub fn derive_kek_for_login(
- password: String,
- kek_salt: String,
- mem_limit: u32,
- ops_limit: u32,
-) -> Result<Vec<u8>, EnsuError> {
- let kek = auth::derive_kek(&password, &kek_salt, mem_limit, ops_limit)?;
- Ok(kek.into_vec())
-}
-
-pub fn decrypt_secrets_with_kek(
- kek: Vec<u8>,
- key_attrs: KeyAttributes,
- encrypted_token: Option<String>,
- plain_token: Option<String>,
-) -> Result<AuthSecrets, EnsuError> {
- let kek = crypto::SecretVec::new(kek);
- let core_attrs = to_core_key_attrs(&key_attrs);
-
- if let Some(token) = encrypted_token {
- let result = auth::decrypt_secrets_with_kek(&kek, &core_attrs, &token)?;
- return Ok(secrets_from_login_result(result));
- }
-
- if let Some(token) = plain_token {
- let (master_key, secret_key) = auth::decrypt_keys_only(&kek, &core_attrs)?;
- let token_bytes = decode_token(&token)?;
- return Ok(AuthSecrets {
- master_key: master_key.into_vec(),
- secret_key: secret_key.into_vec(),
- token: token_bytes,
- });
- }
-
- Err(EnsuError::Message {
- reason: "Missing auth token".to_string(),
- })
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn sample_session() -> auth::SrpSession {
- auth::SrpSession::new("test-user-id", &[0u8; 16], &[0u8; 16]).unwrap()
- }
-
- fn sample_key_attributes() -> KeyAttributes {
- KeyAttributes {
- kek_salt: String::new(),
- encrypted_key: String::new(),
- key_decryption_nonce: String::new(),
- public_key: String::new(),
- encrypted_secret_key: String::new(),
- secret_key_decryption_nonce: String::new(),
- mem_limit: None,
- ops_limit: None,
- }
- }
-
- #[test]
- fn test_verify_srp_m2_rejects_missing_server_proof() {
- let session = sample_session();
- let err = verify_srp_m2(&session, "").unwrap_err();
- assert_eq!(err.to_string(), "Missing server proof");
- }
-
- #[test]
- fn test_verify_srp_m2_rejects_invalid_base64() {
- let session = sample_session();
- let err = verify_srp_m2(&session, "%%%").unwrap_err();
- assert!(err.to_string().starts_with("srp_m2: "));
- }
-
- #[test]
- fn test_srp_decrypt_secrets_clears_state_on_bad_server_proof() {
- srp_clear();
- *SRP_STATE.lock().unwrap() = Some(SrpState {
- session: sample_session(),
- kek: crypto::SecretVec::new(vec![0u8; 32]),
- });
-
- let err = srp_decrypt_secrets(
- String::new(),
- sample_key_attributes(),
- None,
- Some("token".to_string()),
- )
- .unwrap_err();
- assert_eq!(err.to_string(), "Missing server proof");
- assert!(SRP_STATE.lock().unwrap().is_none());
- }
-}
diff --git a/rust/bindings/uniffi/core/uniffi.toml b/rust/bindings/uniffi/core/uniffi.toml
deleted file mode 100644
index f8dded3b17..0000000000
--- a/rust/bindings/uniffi/core/uniffi.toml
+++ /dev/null
@@ -1,2 +0,0 @@
-[bindings.kotlin]
-package_name = "io.ente.ensu.crypto"
diff --git a/rust/crates/ensu/packaging.md b/rust/crates/ensu/packaging.md
index db9a1993b9..2362f45879 100644
--- a/rust/crates/ensu/packaging.md
+++ b/rust/crates/ensu/packaging.md
@@ -24,7 +24,6 @@ Web app depends on shared WASM bindings at `web/packages/wasm`.
Android and Apple native apps use UniFFI + adapters.
-- Core UniFFI bindings: `rust/bindings/uniffi/core`
- Ensu UniFFI bindings: `rust/bindings/uniffi/ensu`
## Native packaging layers
diff --git a/web/apps/ensu/package.json b/web/apps/ensu/package.json
index f691a9309f..516fc168fd 100644
--- a/web/apps/ensu/package.json
+++ b/web/apps/ensu/package.json
@@ -16,7 +16,6 @@
"@tauri-apps/plugin-process": "2.3.1",
"@tauri-apps/plugin-updater": "2.10.1",
"@wllama/wllama": "2.4.0",
- "ente-accounts": "*",
"ente-base": "*",
"ente-new": "*",
"ente-wasm": "*",
diff --git a/web/apps/ensu/src/components/chat/ChatDialogs.tsx b/web/apps/ensu/src/components/chat/ChatDialogs.tsx
index d8bc8e936c..bf7e1b6dd5 100644
--- a/web/apps/ensu/src/components/chat/ChatDialogs.tsx
+++ b/web/apps/ensu/src/components/chat/ChatDialogs.tsx
@@ -5,7 +5,6 @@ import {
Cancel01Icon,
File01Icon,
InformationCircleIcon,
- Key01Icon,
Settings01Icon,
SlidersHorizontalIcon,
Upload01Icon,
@@ -71,13 +70,8 @@ export interface ChatDialogsProps {
settingsItemSx: SxEntry;
smallIconProps: IconProps;
compactIconProps: IconProps;
- isLoggedIn: boolean;
- signedInEmail?: string | null;
saveLogs: () => void | Promise<void>;
handleCheckForUpdates: () => void | Promise<void>;
- handleLogout: () => void;
- openLoginFromChat: () => void;
- openPasskeysFromChat: () => void;
advancedUnlocked: boolean;
buildVersion?: string;
handleBuildVersionTap: () => void;
@@ -128,13 +122,8 @@ export const ChatDialogs = memo(
settingsItemSx,
smallIconProps,
compactIconProps,
- isLoggedIn,
- signedInEmail,
saveLogs,
handleCheckForUpdates,
- handleLogout,
- openLoginFromChat,
- openPasskeysFromChat,
advancedUnlocked,
buildVersion,
handleBuildVersionTap,
@@ -216,6 +205,8 @@ export const ChatDialogs = memo(
const [showAdvancedLimits, setShowAdvancedLimits] =
React.useState(false);
const [selectedModelId, setSelectedModelId] = React.useState("default");
+ const [showBackupComingSoon, setShowBackupComingSoon] =
+ React.useState(false);
// --- System prompt draft state ---
const [draftSystemPrompt, setDraftSystemPrompt] = React.useState("");
@@ -481,29 +472,6 @@ export const ChatDialogs = memo(
</DialogTitle>
<DialogContent sx={{ flex: 1, overflowY: "auto" }}>
<Stack sx={{ gap: 2 }}>
- {isLoggedIn && (
- <Box
- sx={{
- px: 2,
- py: 1.5,
- borderRadius: 2,
- border: "1px solid",
- borderColor: "divider",
- bgcolor: "background.default",
- }}
- >
- <Typography
- variant="mini"
- sx={{ color: "text.muted" }}
- >
- Signed in as
- </Typography>
- <Typography variant="small">
- {signedInEmail ?? ""}
- </Typography>
- </Box>
- )}
-
<Stack sx={{ gap: 1 }}>
<ListItemButton
onClick={() => {
@@ -578,83 +546,28 @@ export const ChatDialogs = memo(
/>
</ListItemButton>
- {isLoggedIn && (
- <ListItemButton
- onClick={() => {
- closeSettingsModal();
- openPasskeysFromChat();
- }}
- sx={settingsItemSx}
- >
- <HugeiconsIcon
- icon={Key01Icon}
- {...compactIconProps}
- />
- <Typography
- variant="small"
- sx={{ flex: 1 }}
- >
- Passkeys
- </Typography>
- <HugeiconsIcon
- icon={ArrowRight01Icon}
- {...smallIconProps}
- />
- </ListItemButton>
- )}
-
- {!isLoggedIn && (
- <ListItemButton
- onClick={() => {
- closeSettingsModal();
- openLoginFromChat();
- }}
- sx={settingsItemSx}
- >
- <HugeiconsIcon
- icon={Upload01Icon}
- {...compactIconProps}
- />
- <Typography
- variant="small"
- sx={{ flex: 1 }}
- >
- Sign In to Backup
- </Typography>
- <HugeiconsIcon
- icon={ArrowRight01Icon}
- {...smallIconProps}
- />
- </ListItemButton>
- )}
-
- {isLoggedIn && (
- <ListItemButton
- onClick={() => {
- closeSettingsModal();
- handleLogout();
- }}
- sx={[
- settingsItemSx,
- { color: "critical.main" },
- ]}
+ <ListItemButton
+ onClick={() => {
+ closeSettingsModal();
+ setShowBackupComingSoon(true);
+ }}
+ sx={settingsItemSx}
+ >
+ <HugeiconsIcon
+ icon={Upload01Icon}
+ {...compactIconProps}
+ />
+ <Typography
+ variant="small"
+ sx={{ flex: 1 }}
>
- <HugeiconsIcon
- icon={Cancel01Icon}
- {...compactIconProps}
- />
- <Typography
- variant="small"
- sx={{ flex: 1, fontWeight: 600 }}
- >
- Sign Out
- </Typography>
- <HugeiconsIcon
- icon={ArrowRight01Icon}
- {...smallIconProps}
- />
- </ListItemButton>
- )}
+ Sign In to Backup
+ </Typography>
+ <HugeiconsIcon
+ icon={ArrowRight01Icon}
+ {...smallIconProps}
+ />
+ </ListItemButton>
<ListItemButton
onClick={() => {
@@ -788,6 +701,32 @@ export const ChatDialogs = memo(
</DialogContent>
</Dialog>
+ <Dialog
+ open={showBackupComingSoon}
+ onClose={() => setShowBackupComingSoon(false)}
+ fullScreen={isSmall}
+ maxWidth="xs"
+ fullWidth
+ slotProps={{ paper: { sx: dialogPaperSx } }}
+ >
+ <DialogTitle sx={dialogTitleSx}>Coming soon</DialogTitle>
+ <DialogContent>
+ <Typography variant="body" sx={{ color: "text.muted" }}>
+ Sign in and cloud backup will be available in a
+ future update.
+ </Typography>
+ </DialogContent>
+ <DialogActions sx={{ px: 3, pb: 3 }}>
+ <Button
+ variant="contained"
+ color="accent"
+ onClick={() => setShowBackupComingSoon(false)}
+ >
+ Got it
+ </Button>
+ </DialogActions>
+ </Dialog>
+
<Dialog
open={Boolean(deleteSessionId)}
onClose={handleCancelDeleteSession}
diff --git a/web/apps/ensu/src/components/chat/ChatSidebar.tsx b/web/apps/ensu/src/components/chat/ChatSidebar.tsx
index ee567d90b9..26e5bce9fc 100644
--- a/web/apps/ensu/src/components/chat/ChatSidebar.tsx
+++ b/web/apps/ensu/src/components/chat/ChatSidebar.tsx
@@ -20,7 +20,6 @@ import {
Typography,
} from "@mui/material";
import type { SxProps, Theme } from "@mui/material/styles";
-import { savedLocalUser } from "ente-accounts/services/accounts-db";
import React, { memo } from "react";
type IconProps = { size: number; strokeWidth: number };
@@ -44,7 +43,6 @@ export interface ChatSidebarProps {
currentSessionId?: string;
handleSelectSession: (sessionId: string) => void;
requestDeleteSession: (sessionId: string) => void;
- isLoggedIn: boolean;
openSettingsModal: () => void;
}
@@ -68,7 +66,6 @@ export const ChatSidebar = memo(
currentSessionId,
handleSelectSession,
requestDeleteSession,
- isLoggedIn,
openSettingsModal,
}: ChatSidebarProps) => (
<Stack
@@ -394,9 +391,7 @@ export const ChatSidebar = memo(
variant="small"
sx={{ flex: 1, fontWeight: 600 }}
>
- {isLoggedIn
- ? (savedLocalUser()?.email ?? "Account")
- : "Settings"}
+ Settings
</Typography>
<HugeiconsIcon
icon={ArrowRight01Icon}
diff --git a/web/apps/ensu/src/pages/_app.tsx b/web/apps/ensu/src/pages/_app.tsx
index 822f4c95b1..2bb0aa7f11 100644
--- a/web/apps/ensu/src/pages/_app.tsx
+++ b/web/apps/ensu/src/pages/_app.tsx
@@ -1,6 +1,6 @@
import { WhatsNewDialog } from "@/components/WhatsNewDialog";
import { setupAutoAppUpdates } from "@/services/app-update";
-import { ensuLogout } from "@/services/logout";
+import { resetEnsuAppState } from "@/services/reset";
import { isTauriRuntime } from "@/services/tauri-runtime";
import {
getPendingDesktopWhatsNew,
@@ -9,7 +9,6 @@ import {
} from "@/services/whats-new";
import { CssBaseline } from "@mui/material";
import { ThemeProvider } from "@mui/material/styles";
-import { savedLocalUser } from "ente-accounts/services/accounts-db";
import { staticAppTitle } from "ente-base/app";
import { CustomHead } from "ente-base/components/Head";
import {
@@ -42,7 +41,7 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {
const [isWhatsNewOpen, setIsWhatsNewOpen] = useState(false);
useEffect(() => {
- logStartupBanner(savedLocalUser()?.id);
+ logStartupBanner();
}, []);
useEffect(() => setupAutoAppUpdates(showMiniDialog), [showMiniDialog]);
@@ -93,8 +92,8 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {
};
}, []);
- const logout = useCallback(() => {
- void ensuLogout();
+ const resetAppState = useCallback(() => {
+ void resetEnsuAppState();
}, []);
const handleWhatsNewClose = useCallback(() => {
@@ -104,8 +103,8 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {
}, []);
const baseContext = useMemo(
- () => deriveBaseContext({ logout, showMiniDialog }),
- [logout, showMiniDialog],
+ () => deriveBaseContext({ logout: resetAppState, showMiniDialog }),
+ [resetAppState, showMiniDialog],
);
const title = staticAppTitle;
diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsx
index 7dd49b46b9..8e6f54a181 100644
--- a/web/apps/ensu/src/pages/chat.tsx
+++ b/web/apps/ensu/src/pages/chat.tsx
@@ -11,9 +11,7 @@ import {
type BranchSwitcher,
} from "@/services/chat/branching";
import {
- cachedChatKey,
cachedLocalChatKey,
- getOrCreateChatKey,
getOrCreateLocalChatKey,
initChatKeyStore,
} from "@/services/chat/chatKey";
@@ -34,10 +32,7 @@ import {
type ChatMessage,
type ChatSession,
} from "@/services/chat/store";
-import {
- DESKTOP_IMAGE_ATTACHMENTS_ENABLED,
- SIGN_IN_ENABLED,
-} from "@/services/featureFlags";
+import { DESKTOP_IMAGE_ATTACHMENTS_ENABLED } from "@/services/featureFlags";
import {
DEFAULT_MODEL,
FALLBACK_DESKTOP_MODEL_PRESETS,
@@ -52,17 +47,11 @@ import type {
ModelInfo,
ModelSettings,
} from "@/services/llm/types";
-import {
- clearMasterKeyFromEverywhere,
- masterKeyFromSession,
- updateSessionFromTauriSecureStorageIfNeeded,
-} from "@/services/session";
import { isTauriRuntime as detectTauriAppRuntime } from "@/services/tauri-runtime";
import { Menu01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import {
Box,
- Button,
Drawer,
IconButton,
Stack,
@@ -70,15 +59,12 @@ import {
useMediaQuery,
} from "@mui/material";
import { getLuminance, useTheme } from "@mui/material/styles";
-import { savedLocalUser } from "ente-accounts/services/accounts-db";
-import { openAccountsManagePasskeysPage } from "ente-accounts/services/passkey";
import { NavbarBase } from "ente-base/components/Navbar";
import { useBaseContext } from "ente-base/context";
import { buildEnvEnsuDesktopVersion } from "ente-base/env";
import { getKV, removeKV, setKV } from "ente-base/kv";
import log from "ente-base/log";
import { savedLogs } from "ente-base/log-web";
-import { savedAuthToken } from "ente-base/token";
import { saveStringAsFile } from "ente-base/utils/web";
import { type NotificationAttributes } from "ente-new/photos/components/Notification";
import { useRouter } from "next/router";
@@ -423,12 +409,11 @@ const detectTauriRuntime = () => detectTauriAppRuntime();
const Page: React.FC = () => {
const router = useRouter();
- const { logout, showMiniDialog } = useBaseContext();
+ const { showMiniDialog } = useBaseContext();
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const assetBasePath = router.basePath ?? "";
const logoSrc = `${assetBasePath}/images/ensu-logo.svg`;
- const comingSoonDuckySrc = `${assetBasePath}/images/ensu-ducky.png`;
const [isDarkMode, setIsDarkMode] = useState(theme.palette.mode === "dark");
useEffect(() => {
@@ -578,7 +563,6 @@ const Page: React.FC = () => {
const [loading, setLoading] = useState(true);
const [firstPaintDone, setFirstPaintDone] = useState(false);
- const [isLoggedIn, setIsLoggedIn] = useState(false);
const [chatKey, setChatKey] = useState<string | undefined>();
const [sessions, setSessions] = useState<ChatSession[]>([]);
const [allMessages, setAllMessages] = useState<ChatMessage[]>([]);
@@ -710,8 +694,7 @@ const Page: React.FC = () => {
promise: Promise<void> | null;
}>({ sessionId: undefined, promise: null });
- const authRefreshCancelledRef = useRef(false);
- const authRetryCancelledRef = useRef(false);
+ const chatKeyInitCancelledRef = useRef(false);
const scheduleIdleTask = useCallback(
(callback: () => void, timeout = 1200) => {
@@ -772,68 +755,12 @@ const Page: React.FC = () => {
[router],
);
- const refreshAuthState = useCallback(async () => {
+ const refreshLocalChatKey = useCallback(async () => {
await initChatKeyStore();
- await updateSessionFromTauriSecureStorageIfNeeded();
- const token = await savedAuthToken();
- const hasToken = !!token;
-
- log.info("Refreshing auth state", { hasToken });
-
- if (hasToken) {
- const cachedRemote = cachedChatKey();
- if (cachedRemote) {
- log.info("Using cached remote chat key");
- setChatKey(cachedRemote);
- setIsLoggedIn(true);
- return;
- }
-
- let masterKey: string | undefined;
-
- try {
- masterKey = await masterKeyFromSession();
- } catch (error) {
- log.error("Failed to read master key from session", error);
- await clearMasterKeyFromEverywhere();
- }
-
- if (!masterKey) {
- log.warn(
- "No master key found in session storage; redirecting to credentials",
- );
- setChatKey(undefined);
- setIsLoggedIn(false);
- if (router.pathname !== "/credentials") {
- void router.replace("/credentials");
- }
- return;
- }
-
- try {
- log.info("Found master key in session, deriving chat key");
- const remoteKey = await getOrCreateChatKey(masterKey);
- setChatKey(remoteKey);
- setIsLoggedIn(true);
- return;
- } catch (error) {
- log.error("Failed to load remote chat key", error);
- showMiniDialog({
- title: "Chat key unavailable",
- message:
- "We could not load your chat encryption key. Please try again.",
- });
- setChatKey(undefined);
- setIsLoggedIn(true);
- return;
- }
- }
-
- setIsLoggedIn(false);
const cachedLocal = cachedLocalChatKey();
if (cachedLocal) {
- log.info("Falling back to cached local chat key");
+ log.info("Using cached local chat key");
setChatKey(cachedLocal);
return;
}
@@ -849,24 +776,24 @@ const Page: React.FC = () => {
"We could not initialize encryption. Please refresh the page.",
});
}
- }, [router, showMiniDialog]);
+ }, [showMiniDialog]);
useEffect(() => {
- authRefreshCancelledRef.current = false;
+ chatKeyInitCancelledRef.current = false;
void (async () => {
try {
- await refreshAuthState();
+ await refreshLocalChatKey();
} catch (error) {
- log.error("Failed to refresh auth state", error);
+ log.error("Failed to initialize local chat key", error);
}
- if (!authRefreshCancelledRef.current) setLoading(false);
+ if (!chatKeyInitCancelledRef.current) setLoading(false);
})();
return () => {
- authRefreshCancelledRef.current = true;
+ chatKeyInitCancelledRef.current = true;
};
- }, [refreshAuthState]);
+ }, [refreshLocalChatKey]);
useEffect(() => {
routeInitializedRef.current = false;
@@ -902,55 +829,6 @@ const Page: React.FC = () => {
isDraftSessionRef.current = isDraftSession;
}, [isDraftSession]);
- useEffect(() => {
- if (typeof window === "undefined") return;
-
- authRetryCancelledRef.current = false;
- let attempts = 0;
- let timeoutId: number | undefined;
-
- const retry = async () => {
- if (authRetryCancelledRef.current) return;
- const token = await savedAuthToken();
- let masterKey: string | undefined;
-
- try {
- masterKey = await masterKeyFromSession();
- } catch (error) {
- log.error("Failed to read master key from session", error);
- await clearMasterKeyFromEverywhere();
- }
-
- const remoteKey = cachedChatKey();
-
- // If we are logged in, we want to wait for either the master key to
- // appear in session storage, or for a previously cached remote key
- // to be available.
- if (token && (masterKey || remoteKey)) {
- await refreshAuthState();
- return;
- }
-
- // If we're not logged in, we just retry a few times to see if a
- // login token appears (e.g. from a recent redirect).
- if (!token && attempts >= 5) {
- return;
- }
-
- attempts += 1;
- if (attempts < 15) {
- timeoutId = window.setTimeout(retry, 600);
- }
- };
-
- timeoutId = window.setTimeout(retry, 600);
-
- return () => {
- authRetryCancelledRef.current = true;
- if (timeoutId) window.clearTimeout(timeoutId);
- };
- }, [refreshAuthState]);
-
useEffect(() => {
if (typeof window === "undefined") return;
@@ -1425,7 +1303,7 @@ const Page: React.FC = () => {
if (typeof window === "undefined") return;
const handleFocus = () => {
- void refreshAuthState();
+ void refreshLocalChatKey();
if (chatKey) {
void refreshSessions();
void refreshMessages();
@@ -1434,7 +1312,7 @@ const Page: React.FC = () => {
const handleVisibility = () => {
if (!document.hidden) {
- void refreshAuthState();
+ void refreshLocalChatKey();
if (chatKey) {
void refreshSessions();
void refreshMessages();
@@ -1449,7 +1327,7 @@ const Page: React.FC = () => {
window.removeEventListener("focus", handleFocus);
document.removeEventListener("visibilitychange", handleVisibility);
};
- }, [chatKey, refreshAuthState, refreshMessages, refreshSessions]);
+ }, [chatKey, refreshLocalChatKey, refreshMessages, refreshSessions]);
const deleteSessionTarget = useMemo(
() =>
@@ -3774,65 +3652,6 @@ const Page: React.FC = () => {
setPendingImages((prev) => prev.filter((img) => img.id !== id));
}, []);
- const handleLogout = useCallback(
- () =>
- showMiniDialog({
- title: "Sign out",
- message: "Are you sure you want to sign out?",
- continue: {
- text: "Sign out",
- color: "critical",
- action: logout,
- },
- buttonDirection: "row",
- }),
- [logout, showMiniDialog],
- );
-
- const openLoginFromChat = useCallback(() => {
- if (!SIGN_IN_ENABLED) {
- showMiniDialog({
- title: "Coming Soon",
- message: (
- <Stack
- sx={{
- gap: 1.25,
- alignItems: "center",
- textAlign: "center",
- }}
- >
- <Box
- component="img"
- src={comingSoonDuckySrc}
- alt="Ensu ducky"
- sx={{ width: 92, height: 92, objectFit: "contain" }}
- />
- <Box component="span" sx={{ px: 3 }}>
- Sign in and cloud backup will be available in a
- future update.
- </Box>
- </Stack>
- ),
- cancel: "Got it",
- });
- return;
- }
- void router.push("/login");
- }, [comingSoonDuckySrc, router, showMiniDialog]);
-
- const openPasskeysFromChat = useCallback(async () => {
- try {
- await openAccountsManagePasskeysPage();
- } catch (e) {
- log.error("Failed to open passkeys page", e);
- showMiniDialog({
- title: "Passkeys unavailable",
- message:
- "We could not open the passkeys page. Please try again.",
- });
- }
- }, [showMiniDialog]);
-
const handleSend = useCallback(async () => {
const trimmed = input.trim();
const hasDocuments = pendingDocuments.length > 0;
@@ -4092,7 +3911,6 @@ const Page: React.FC = () => {
currentSessionId={currentSessionId}
handleSelectSession={handleSelectSession}
requestDeleteSession={requestDeleteSession}
- isLoggedIn={isLoggedIn}
openSettingsModal={openSettingsModal}
/>
);
@@ -4231,22 +4049,6 @@ const Page: React.FC = () => {
</Box>
</Stack>
</Stack>
- {!isLoggedIn && (
- <Button
- onClick={openLoginFromChat}
- color="inherit"
- variant="text"
- sx={{
- textTransform: "none",
- fontWeight: 600,
- fontSize: "13px",
- color: "text.base",
- py: 0.75,
- }}
- >
- Sign In
- </Button>
- )}
</NavbarBase>
<ChatMessageList
@@ -4381,13 +4183,8 @@ const Page: React.FC = () => {
settingsItemSx={settingsItemSx}
smallIconProps={smallIconProps}
compactIconProps={compactIconProps}
- isLoggedIn={isLoggedIn}
- signedInEmail={savedLocalUser()?.email ?? ""}
saveLogs={saveLogs}
handleCheckForUpdates={handleCheckForUpdates}
- handleLogout={handleLogout}
- openLoginFromChat={openLoginFromChat}
- openPasskeysFromChat={openPasskeysFromChat}
advancedUnlocked={advancedUnlocked}
buildVersion={buildVersion}
handleBuildVersionTap={handleBuildVersionTap}
diff --git a/web/apps/ensu/src/pages/credentials.tsx b/web/apps/ensu/src/pages/credentials.tsx
deleted file mode 100644
index 9b8df2e13d..0000000000
--- a/web/apps/ensu/src/pages/credentials.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from "ente-accounts/pages/credentials";
diff --git a/web/apps/ensu/src/pages/index.tsx b/web/apps/ensu/src/pages/index.tsx
index a4acf4eb5a..a355a1f6b2 100644
--- a/web/apps/ensu/src/pages/index.tsx
+++ b/web/apps/ensu/src/pages/index.tsx
@@ -6,16 +6,6 @@ const Page: React.FC = () => {
const router = useRouter();
useEffect(() => {
- const shouldOpenLogin =
- typeof window !== "undefined" &&
- window.sessionStorage.getItem("ensu.openLogin") === "1";
-
- if (shouldOpenLogin) {
- window.sessionStorage.removeItem("ensu.openLogin");
- void router.replace("/login");
- return;
- }
-
void router.replace("/chat");
}, [router]);
diff --git a/web/apps/ensu/src/pages/login.tsx b/web/apps/ensu/src/pages/login.tsx
deleted file mode 100644
index 675471334f..0000000000
--- a/web/apps/ensu/src/pages/login.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from "ente-accounts/pages/login";
diff --git a/web/apps/ensu/src/pages/passkeys/finish.tsx b/web/apps/ensu/src/pages/passkeys/finish.tsx
deleted file mode 100644
index 88c2314928..0000000000
--- a/web/apps/ensu/src/pages/passkeys/finish.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from "ente-accounts/pages/passkeys/finish";
diff --git a/web/apps/ensu/src/pages/passkeys/recover.tsx b/web/apps/ensu/src/pages/passkeys/recover.tsx
deleted file mode 100644
index 972142211c..0000000000
--- a/web/apps/ensu/src/pages/passkeys/recover.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import Page_ from "ente-accounts/pages/two-factor/recover";
-
-const Page = () => <Page_ twoFactorType="passkey" />;
-
-export default Page;
diff --git a/web/apps/ensu/src/pages/two-factor/recover.tsx b/web/apps/ensu/src/pages/two-factor/recover.tsx
deleted file mode 100644
index 201393276a..0000000000
--- a/web/apps/ensu/src/pages/two-factor/recover.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import Page_ from "ente-accounts/pages/two-factor/recover";
-
-const Page = () => <Page_ twoFactorType="totp" />;
-
-export default Page;
diff --git a/web/apps/ensu/src/pages/two-factor/setup.tsx b/web/apps/ensu/src/pages/two-factor/setup.tsx
deleted file mode 100644
index 7f9adb38e6..0000000000
--- a/web/apps/ensu/src/pages/two-factor/setup.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from "ente-accounts/pages/two-factor/setup";
diff --git a/web/apps/ensu/src/pages/two-factor/verify.tsx b/web/apps/ensu/src/pages/two-factor/verify.tsx
deleted file mode 100644
index f3f3c99656..0000000000
--- a/web/apps/ensu/src/pages/two-factor/verify.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from "ente-accounts/pages/two-factor/verify";
diff --git a/web/apps/ensu/src/pages/verify.tsx b/web/apps/ensu/src/pages/verify.tsx
deleted file mode 100644
index 7ec623fac9..0000000000
--- a/web/apps/ensu/src/pages/verify.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from "ente-accounts/pages/verify";
diff --git a/web/apps/ensu/src/services/auth/srp.ts b/web/apps/ensu/src/services/auth/srp.ts
deleted file mode 100644
index 01300adf2b..0000000000
--- a/web/apps/ensu/src/services/auth/srp.ts
+++ /dev/null
@@ -1,309 +0,0 @@
-import {
- replaceSavedLocalUser,
- saveKeyAttributes,
-} from "ente-accounts/services/accounts-db";
-import { ensureOk, publicRequestHeaders } from "ente-base/http";
-import log from "ente-base/log";
-import { apiURL } from "ente-base/origins";
-import { saveAuthToken } from "ente-base/token";
-import { z } from "zod";
-import { saveMasterKeyInSession } from "../session";
-import { ensureCryptoInit, enteWasm } from "../wasm";
-
-/** Minimal SRP attributes needed for login. */
-export const RemoteSRPAttributes = z.object({
- srpUserID: z.string(),
- srpSalt: z.string(),
- memLimit: z.number(),
- opsLimit: z.number(),
- kekSalt: z.string(),
- isEmailMFAEnabled: z.boolean(),
-});
-
-export type SRPAttributes = z.infer<typeof RemoteSRPAttributes>;
-
-/** Minimal key attributes needed for decrypting secrets. */
-export const RemoteKeyAttributes = z
- .object({
- kekSalt: z.string(),
- encryptedKey: z.string(),
- keyDecryptionNonce: z.string(),
- publicKey: z.string(),
- encryptedSecretKey: z.string(),
- secretKeyDecryptionNonce: z.string(),
- memLimit: z.number(),
- opsLimit: z.number(),
-
- // Optional recovery-related attributes (present for newer accounts).
- masterKeyEncryptedWithRecoveryKey: z.string().optional().nullable(),
- masterKeyDecryptionNonce: z.string().optional().nullable(),
- recoveryKeyEncryptedWithMasterKey: z.string().optional().nullable(),
- recoveryKeyDecryptionNonce: z.string().optional().nullable(),
- })
- // We only care about the fields above; ignore any extra fields.
- .loose();
-
-export type KeyAttributes = z.infer<typeof RemoteKeyAttributes>;
-
-const RemoteSRPVerificationResponse = z.object({
- id: z.number(),
- keyAttributes: RemoteKeyAttributes.optional().nullable(),
- encryptedToken: z.string().optional().nullable(),
- token: z.string().optional().nullable(),
- twoFactorSessionID: z.string().optional().nullable(),
- passkeySessionID: z.string().optional().nullable(),
- accountsUrl: z.string().optional().nullable(),
- twoFactorSessionIDV2: z.string().optional().nullable(),
- srpM2: z.string(),
-});
-
-type SRPVerificationResponse = z.infer<typeof RemoteSRPVerificationResponse>;
-
-const CreateSRPSessionResponse = z.object({
- sessionID: z.string(),
- srpB: z.string(),
-});
-
-type CreateSRPSessionResponse = z.infer<typeof CreateSRPSessionResponse>;
-
-export class SRPLoginError extends Error {
- constructor(
- public code:
- | "SRP_NOT_AVAILABLE"
- | "EMAIL_MFA_ENABLED"
- | "INCORRECT_PASSWORD"
- | "TWO_FACTOR_REQUIRED"
- | "MISSING_KEY_ATTRIBUTES"
- | "MISSING_TOKEN"
- | "DECRYPT_FAILED"
- | "INVALID_RESPONSE",
- message: string,
- ) {
- super(message);
- this.name = "SRPLoginError";
- }
-}
-
-/**
- * Fetch SRP attributes for a user.
- *
- * Returns undefined if SRP isn't setup (or the user doesn't exist).
- */
-export const getSRPAttributes = async (
- email: string,
-): Promise<SRPAttributes | undefined> => {
- const res = await fetch(await apiURL("/users/srp/attributes", { email }), {
- headers: publicRequestHeaders(),
- });
- if (res.status == 404) return undefined;
- ensureOk(res);
-
- const body = z
- .object({ attributes: RemoteSRPAttributes })
- .parse(await res.json());
- return body.attributes;
-};
-
-const createSRPSession = async (req: {
- srpUserID: string;
- srpA: string;
-}): Promise<CreateSRPSessionResponse> => {
- const res = await fetch(await apiURL("/users/srp/create-session"), {
- method: "POST",
- headers: publicRequestHeaders(),
- body: JSON.stringify(req),
- });
- ensureOk(res);
- return CreateSRPSessionResponse.parse(await res.json());
-};
-
-const verifySRPSession = async (req: {
- sessionID: string;
- srpUserID: string;
- srpM1: string;
-}): Promise<SRPVerificationResponse> => {
- const res = await fetch(await apiURL("/users/srp/verify-session"), {
- method: "POST",
- headers: publicRequestHeaders(),
- body: JSON.stringify(req),
- });
-
- if (res.status == 401) {
- throw new SRPLoginError(
- "INCORRECT_PASSWORD",
- "Incorrect password or no account",
- );
- }
-
- ensureOk(res);
- return RemoteSRPVerificationResponse.parse(await res.json());
-};
-
-const isWasmError = (
- error: unknown,
-): error is { code?: string; message?: string } =>
- typeof error === "object" && error !== null && "code" in error;
-
-/**
- * Perform SRP login and persist token + key attributes + master key.
- */
-export const loginWithSRP = async (
- email: string,
- password: string,
- srpAttributesOverride?: SRPAttributes,
-) => {
- try {
- const srpAttributes =
- srpAttributesOverride ?? (await getSRPAttributes(email));
- if (!srpAttributes) {
- throw new SRPLoginError(
- "SRP_NOT_AVAILABLE",
- "This account is not configured for SRP login.",
- );
- }
-
- if (srpAttributes.isEmailMFAEnabled) {
- throw new SRPLoginError(
- "EMAIL_MFA_ENABLED",
- "This account requires email verification instead of SRP.",
- );
- }
-
- await ensureCryptoInit();
- const wasm = await enteWasm();
-
- // 1) Derive KEK + SRP login key.
- const creds = await wasm.auth_derive_srp_credentials(
- password,
- srpAttributes,
- );
-
- // 2) SRP handshake.
- const session = new wasm.SrpSession(
- srpAttributes.srpUserID,
- srpAttributes.srpSalt,
- creds.login_key,
- );
-
- const { sessionID, srpB } = await createSRPSession({
- srpUserID: srpAttributes.srpUserID,
- srpA: await session.public_a(),
- });
-
- const srpM1 = await session.compute_m1(srpB);
-
- const response = await verifySRPSession({
- sessionID,
- srpUserID: srpAttributes.srpUserID,
- srpM1,
- });
-
- // 3) Verify server proof.
- await session.verify_m2(response.srpM2);
-
- // 4) Handle second factor (not supported in this initial web client).
- if (
- response.passkeySessionID ||
- response.twoFactorSessionID ||
- response.twoFactorSessionIDV2
- ) {
- throw new SRPLoginError(
- "TWO_FACTOR_REQUIRED",
- "Second factor verification is required but is not supported in Ensu web yet.",
- );
- }
-
- const keyAttributes = response.keyAttributes ?? undefined;
- if (!keyAttributes) {
- throw new SRPLoginError(
- "MISSING_KEY_ATTRIBUTES",
- "Server did not return key attributes.",
- );
- }
-
- const normalizedKeyAttributes = {
- ...keyAttributes,
- masterKeyEncryptedWithRecoveryKey:
- keyAttributes.masterKeyEncryptedWithRecoveryKey ?? undefined,
- masterKeyDecryptionNonce:
- keyAttributes.masterKeyDecryptionNonce ?? undefined,
- recoveryKeyEncryptedWithMasterKey:
- keyAttributes.recoveryKeyEncryptedWithMasterKey ?? undefined,
- recoveryKeyDecryptionNonce:
- keyAttributes.recoveryKeyDecryptionNonce ?? undefined,
- };
-
- // 5) Decrypt secrets.
- let masterKey: string;
- let token: string;
-
- if (response.encryptedToken) {
- const secrets = await wasm.auth_decrypt_secrets(
- creds.kek,
- normalizedKeyAttributes,
- response.encryptedToken,
- );
- masterKey = secrets.master_key;
- token = secrets.token;
- } else if (response.token) {
- const keys = await wasm.auth_decrypt_keys_only(
- creds.kek,
- normalizedKeyAttributes,
- );
- masterKey = keys.master_key;
- token = response.token;
- } else {
- throw new SRPLoginError(
- "MISSING_TOKEN",
- "Server did not return an auth token.",
- );
- }
-
- // 6) Persist.
- await saveAuthToken(token);
- replaceSavedLocalUser({
- id: response.id,
- email,
- token,
- isTwoFactorEnabled: false,
- });
- saveKeyAttributes(normalizedKeyAttributes);
-
- await saveMasterKeyInSession(masterKey);
-
- return { id: response.id, email, token };
- } catch (error) {
- if (error instanceof SRPLoginError) {
- log.error("SRP login failed", error);
- console.error("SRP login failed", error);
- throw error;
- }
-
- if (error instanceof z.ZodError) {
- log.error("SRP login failed: invalid response", error);
- console.error("SRP login failed: invalid response", error);
- throw new SRPLoginError(
- "INVALID_RESPONSE",
- "Unexpected response from server. Please try again.",
- );
- }
-
- if (isWasmError(error)) {
- const code = error.code ?? "";
- const message = error.message ?? "Unknown error";
-
- log.error("SRP login failed (wasm)", error);
- console.error("SRP login failed (wasm)", error);
-
- if (code == "incorrect_password") {
- throw new SRPLoginError("INCORRECT_PASSWORD", message);
- }
-
- throw new SRPLoginError("DECRYPT_FAILED", message);
- }
-
- log.error("SRP login failed", error);
- console.error("SRP login failed", error);
- throw error;
- }
-};
diff --git a/web/apps/ensu/src/services/chat/chatKey.ts b/web/apps/ensu/src/services/chat/chatKey.ts
index 42fe55a332..bcc39f8c8b 100644
--- a/web/apps/ensu/src/services/chat/chatKey.ts
+++ b/web/apps/ensu/src/services/chat/chatKey.ts
@@ -1,6 +1,4 @@
import { isTauriRuntime } from "@/services/tauri-runtime";
-import { savedLocalUser } from "ente-accounts/services/accounts-db";
-import { HTTPError } from "ente-base/http";
import log from "ente-base/log";
import {
secureStorageDelete,
@@ -8,7 +6,6 @@ import {
secureStorageSet,
} from "../secure-storage";
import { ensureCryptoInit, enteWasm } from "../wasm";
-import { ChatKeyNotFoundError, createChatKey, getChatKey } from "./gateway";
const CHAT_KEY_LOCAL_STORAGE_KEY = "ensu.chatKey";
const LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY = "ensu.chatKey.local";
@@ -19,16 +16,28 @@ const LEGACY_ATTACHMENT_KEY_SECURE_STORAGE_KEY = "legacyAttachmentKey.v2";
const LEGACY_REMOTE_CHAT_KEY_SECURE_STORAGE_KEY = "remoteChatKey";
const LEGACY_LOCAL_CHAT_KEY_SECURE_STORAGE_KEY = "localChatKey";
-type PersistedChatKeys = { remoteChatKey?: string; localChatKey?: string };
+type PersistedChatKeys = { localChatKey?: string };
+type LegacyChatKeys = { remoteChatKey?: string; localChatKey?: string };
let _persistedChatKeys: PersistedChatKeys = {};
-let _legacyPersistedChatKeys: PersistedChatKeys = {};
+let _legacyPersistedChatKeys: LegacyChatKeys = {};
let _legacyAttachmentChatKey: string | undefined;
/** All distinct keys discovered during init, before any cleanup. */
let _allDiscoveredLocalChatKeys: string[] = [];
let _chatKeyStoreInitPromise: Promise<void> | undefined;
let _chatKeyStoreInitUserID: number | undefined;
+const legacyUserID = () => {
+ try {
+ const raw = readLocalStorageKey("user");
+ if (!raw) return undefined;
+ const id = (JSON.parse(raw) as { id?: unknown }).id;
+ return typeof id === "number" ? id : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
const readLocalStorageKey = (key: string) => {
if (typeof localStorage === "undefined") return undefined;
return localStorage.getItem(key) ?? undefined;
@@ -44,37 +53,39 @@ const removeLocalStorageKey = (key: string) => {
localStorage.removeItem(key);
};
-const scopedRemoteChatKeyLocalStorageKey = () => {
- const userID = savedLocalUser()?.id;
- return userID ? `${CHAT_KEY_LOCAL_STORAGE_KEY}.${userID}` : undefined;
-};
+const legacyRemoteChatKeyLocalStorageKeys = () => {
+ const keys = [CHAT_KEY_LOCAL_STORAGE_KEY];
+ const userID = legacyUserID();
+ if (userID) keys.push(`${CHAT_KEY_LOCAL_STORAGE_KEY}.${userID}`);
+
+ if (typeof localStorage !== "undefined") {
+ for (let i = 0; i < localStorage.length; i += 1) {
+ const key = localStorage.key(i);
+ if (
+ key?.startsWith(`${CHAT_KEY_LOCAL_STORAGE_KEY}.`) &&
+ key !== LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY &&
+ !keys.includes(key)
+ ) {
+ keys.push(key);
+ }
+ }
+ }
-const scopedRemoteChatKeySecureStorageKey = () => {
- const userID = savedLocalUser()?.id;
- return userID
- ? `${REMOTE_CHAT_KEY_SECURE_STORAGE_KEY}.${userID}`
- : undefined;
+ return keys;
};
-const scopedLegacyRemoteChatKeySecureStorageKey = () => {
- const userID = savedLocalUser()?.id;
+const legacyRemoteChatKeySecureStorageKeys = () => {
+ const userID = legacyUserID();
return userID
- ? `${LEGACY_REMOTE_CHAT_KEY_SECURE_STORAGE_KEY}.${userID}`
- : undefined;
+ ? [
+ `${REMOTE_CHAT_KEY_SECURE_STORAGE_KEY}.${userID}`,
+ `${LEGACY_REMOTE_CHAT_KEY_SECURE_STORAGE_KEY}.${userID}`,
+ ]
+ : [];
};
const clearLegacyRemoteChatKeyLocalStorage = () =>
- removeLocalStorageKey(CHAT_KEY_LOCAL_STORAGE_KEY);
-
-const clearScopedRemoteChatKeyLocalStorage = () => {
- if (typeof localStorage === "undefined") return;
- const keys = [];
- for (let i = 0; i < localStorage.length; i += 1) {
- const key = localStorage.key(i);
- if (key?.startsWith(`${CHAT_KEY_LOCAL_STORAGE_KEY}.`)) keys.push(key);
- }
- for (const key of keys) localStorage.removeItem(key);
-};
+ legacyRemoteChatKeyLocalStorageKeys().forEach(removeLocalStorageKey);
const nativeChatKeyPath = async () => {
const { appDataDir, join } = await import("@tauri-apps/api/path");
@@ -96,10 +107,6 @@ const readNativeChatKeys = async (): Promise<PersistedChatKeys> => {
const raw = new TextDecoder().decode(await readFile(path));
const parsed = JSON.parse(raw) as PersistedChatKeys;
return {
- remoteChatKey:
- typeof parsed.remoteChatKey === "string"
- ? parsed.remoteChatKey
- : undefined,
localChatKey:
typeof parsed.localChatKey === "string"
? parsed.localChatKey
@@ -114,20 +121,6 @@ const persistNativeChatKeys = async () => {
if (!isTauriRuntime()) return;
const operations: Promise<void>[] = [];
- const remoteStorageKey = scopedRemoteChatKeySecureStorageKey();
- if (remoteStorageKey) {
- if (_persistedChatKeys.remoteChatKey) {
- operations.push(
- secureStorageSet(
- remoteStorageKey,
- _persistedChatKeys.remoteChatKey,
- ),
- );
- } else {
- operations.push(secureStorageDelete(remoteStorageKey));
- }
- }
-
if (_persistedChatKeys.localChatKey) {
operations.push(
secureStorageSet(
@@ -150,7 +143,6 @@ const persistNativeChatKeysSoon = () => {
const cleanupLegacyChatKeyCopies = async () => {
clearLegacyRemoteChatKeyLocalStorage();
- clearScopedRemoteChatKeyLocalStorage();
removeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);
try {
@@ -165,49 +157,43 @@ const cleanupLegacyChatKeyCopies = async () => {
export const initChatKeyStore = async () => {
if (!isTauriRuntime()) return;
- const userID = savedLocalUser()?.id;
+ const userID = legacyUserID();
if (_chatKeyStoreInitPromise && _chatKeyStoreInitUserID === userID) {
return _chatKeyStoreInitPromise;
}
_chatKeyStoreInitUserID = userID;
_chatKeyStoreInitPromise = (async () => {
- const remoteStorageKey = scopedRemoteChatKeySecureStorageKey();
- const legacyRemoteStorageKey =
- scopedLegacyRemoteChatKeySecureStorageKey();
- const remoteLocalStorageKey = scopedRemoteChatKeyLocalStorageKey();
+ const remoteStorageKeys = legacyRemoteChatKeySecureStorageKeys();
+ const remoteLocalStorageKeys = legacyRemoteChatKeyLocalStorageKeys();
const [
- secureRemoteChatKey,
secureLocalChatKey,
secureLegacyAttachmentKey,
- legacySecureRemoteChatKey,
legacySecureLocalChatKey,
+ secureRemoteChatKeys,
nativeKeys,
] = await Promise.all([
- remoteStorageKey
- ? secureStorageGet(remoteStorageKey).catch(() => undefined)
- : Promise.resolve(undefined),
secureStorageGet(LOCAL_CHAT_KEY_SECURE_STORAGE_KEY).catch(
() => undefined,
),
secureStorageGet(LEGACY_ATTACHMENT_KEY_SECURE_STORAGE_KEY).catch(
() => undefined,
),
- legacyRemoteStorageKey
- ? secureStorageGet(legacyRemoteStorageKey).catch(
- () => undefined,
- )
- : Promise.resolve(undefined),
secureStorageGet(LEGACY_LOCAL_CHAT_KEY_SECURE_STORAGE_KEY).catch(
() => undefined,
),
+ Promise.all(
+ remoteStorageKeys.map((key) =>
+ secureStorageGet(key).catch(() => undefined),
+ ),
+ ),
readNativeChatKeys(),
]);
const legacyRemoteChatKey =
- legacySecureRemoteChatKey ??
- (remoteLocalStorageKey
- ? readLocalStorageKey(remoteLocalStorageKey)
- : undefined);
+ secureRemoteChatKeys.find(Boolean) ??
+ remoteLocalStorageKeys
+ .map((key) => readLocalStorageKey(key))
+ .find(Boolean);
// Prefer localStorage over legacy secure storage for the local key.
// Pre-v0.1.12 builds only used localStorage, so when both exist the
// localStorage value is the key that actually encrypted the legacy DB.
@@ -217,10 +203,10 @@ export const initChatKeyStore = async () => {
readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY) ??
legacySecureLocalChatKey ??
nativeKeys.localChatKey;
- const remoteChatKey = secureRemoteChatKey ?? legacyRemoteChatKey;
- const localChatKey = secureLocalChatKey ?? legacyLocalChatKey;
+ const localChatKey =
+ secureLocalChatKey ?? legacyLocalChatKey ?? legacyRemoteChatKey;
- _persistedChatKeys = { remoteChatKey, localChatKey };
+ _persistedChatKeys = { localChatKey };
_legacyPersistedChatKeys = {
remoteChatKey: legacyRemoteChatKey,
localChatKey: legacyLocalChatKey,
@@ -242,6 +228,7 @@ export const initChatKeyStore = async () => {
legacySecureLocalChatKey,
nativeKeys.localChatKey,
rawLocalStorage,
+ legacyRemoteChatKey,
]) {
if (k && !seen.has(k)) {
seen.add(k);
@@ -251,10 +238,7 @@ export const initChatKeyStore = async () => {
_allDiscoveredLocalChatKeys = all;
}
- if (
- secureRemoteChatKey !== remoteChatKey ||
- secureLocalChatKey !== localChatKey
- ) {
+ if (secureLocalChatKey !== localChatKey) {
try {
await persistNativeChatKeys();
} catch (error) {
@@ -280,48 +264,14 @@ export const initChatKeyStore = async () => {
};
const setCachedChatKey = (chatKey: string) => {
- if (isTauriRuntime()) {
- _persistedChatKeys.remoteChatKey = chatKey;
- persistNativeChatKeysSoon();
- return;
- }
-
- clearLegacyRemoteChatKeyLocalStorage();
- const storageKey = scopedRemoteChatKeyLocalStorageKey();
- if (!storageKey) return;
- writeLocalStorageKey(storageKey, chatKey);
-};
-
-const setCachedLocalChatKey = (chatKey: string) => {
if (isTauriRuntime()) {
_persistedChatKeys.localChatKey = chatKey;
persistNativeChatKeysSoon();
return;
}
- writeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY, chatKey);
-};
-
-/**
- * Return the cached chat key (base64), if present.
- */
-export const cachedChatKey = (): string | undefined => {
- if (isTauriRuntime()) {
- return _persistedChatKeys.remoteChatKey;
- }
-
clearLegacyRemoteChatKeyLocalStorage();
- const storageKey = scopedRemoteChatKeyLocalStorageKey();
- return storageKey ? readLocalStorageKey(storageKey) : undefined;
-};
-
-export const legacyCachedChatKey = (): string | undefined => {
- if (isTauriRuntime()) {
- return _legacyPersistedChatKeys.remoteChatKey;
- }
-
- const storageKey = scopedRemoteChatKeyLocalStorageKey();
- return storageKey ? readLocalStorageKey(storageKey) : undefined;
+ writeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY, chatKey);
};
/**
@@ -332,7 +282,12 @@ export const cachedLocalChatKey = (): string | undefined => {
return _persistedChatKeys.localChatKey;
}
- return readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);
+ return (
+ readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY) ??
+ legacyRemoteChatKeyLocalStorageKeys()
+ .map((key) => readLocalStorageKey(key))
+ .find(Boolean)
+ );
};
export const legacyLocalChatKey = (): string | undefined => {
@@ -346,11 +301,10 @@ export const legacyLocalChatKey = (): string | undefined => {
/**
* Return all distinct legacy key candidates that might decrypt a legacy DB.
*
- * Unlike {@link legacyLocalChatKey} and {@link legacyCachedChatKey} which
- * return the single "best" key from a prioritized chain, this returns every
- * key found across all legacy storage locations so the migration can try
- * each one. This is needed because stale keys in the OS keyring (secure
- * storage) can shadow the correct key in localStorage.
+ * Unlike {@link legacyLocalChatKey}, this returns every key found across all
+ * legacy storage locations so the migration can try each one. This is needed
+ * because stale keys in the OS keyring can shadow the correct key in
+ * localStorage.
*/
export const allLegacyKeyCandidates = (): string[] => {
const seen = new Set<string>();
@@ -363,7 +317,6 @@ export const allLegacyKeyCandidates = (): string[] => {
};
add(_legacyPersistedChatKeys.remoteChatKey);
add(_legacyPersistedChatKeys.localChatKey);
- add(_persistedChatKeys.remoteChatKey);
add(_persistedChatKeys.localChatKey);
// Include every local chat key discovered during init (before cleanup
// deleted legacy copies). This ensures we try the raw localStorage key
@@ -388,79 +341,8 @@ export const setLegacyAttachmentChatKey = async (chatKey?: string) => {
}
};
-export const clearCachedChatKey = () => {
- if (isTauriRuntime()) {
- delete _persistedChatKeys.remoteChatKey;
- persistNativeChatKeysSoon();
- }
-
- clearLegacyRemoteChatKeyLocalStorage();
- clearScopedRemoteChatKeyLocalStorage();
-};
-
-export const clearLocalChatKey = () => {
- if (isTauriRuntime()) {
- delete _persistedChatKeys.localChatKey;
- persistNativeChatKeysSoon();
- return;
- }
-
- removeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);
-};
-
-/**
- * Get (or create) the chat encryption key.
- *
- * The key is stored on the server encrypted with the user's master key.
- */
-export const getOrCreateChatKey = async (masterKeyB64: string) => {
- await initChatKeyStore();
- const cached = cachedChatKey();
- if (cached) return cached;
-
- await ensureCryptoInit();
- const wasm = await enteWasm();
-
- try {
- const remote = await getChatKey();
- const chatKey = await wasm.crypto_decrypt_blob(
- remote.encryptedKey,
- remote.header,
- masterKeyB64,
- );
- setCachedChatKey(chatKey);
- return chatKey;
- } catch (e) {
- if (!(e instanceof ChatKeyNotFoundError)) throw e;
-
- const chatKey = await wasm.crypto_generate_key();
- const encrypted = await wasm.crypto_encrypt_blob(chatKey, masterKeyB64);
-
- try {
- await createChatKey(
- encrypted.encrypted_data,
- encrypted.decryption_header,
- );
- setCachedChatKey(chatKey);
- return chatKey;
- } catch (error) {
- if (error instanceof HTTPError && error.res.status === 409) {
- const remote = await getChatKey();
- const resolved = await wasm.crypto_decrypt_blob(
- remote.encryptedKey,
- remote.header,
- masterKeyB64,
- );
- setCachedChatKey(resolved);
- return resolved;
- }
- throw error;
- }
- }
-};
-
/**
- * Get or create a local-only chat key (used when the user is not signed in).
+ * Get or create the local-only chat encryption key.
*/
export const getOrCreateLocalChatKey = async () => {
await initChatKeyStore();
@@ -470,6 +352,6 @@ export const getOrCreateLocalChatKey = async () => {
await ensureCryptoInit();
const wasm = await enteWasm();
const chatKey = await wasm.crypto_generate_key();
- setCachedLocalChatKey(chatKey);
+ setCachedChatKey(chatKey);
return chatKey;
};
diff --git a/web/apps/ensu/src/services/chat/gateway.ts b/web/apps/ensu/src/services/chat/gateway.ts
deleted file mode 100644
index 5ae93eb648..0000000000
--- a/web/apps/ensu/src/services/chat/gateway.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
-import { apiURL } from "ente-base/origins";
-import { z } from "zod";
-
-export class ChatKeyNotFoundError extends Error {
- constructor() {
- super("Chat key not found");
- this.name = "ChatKeyNotFoundError";
- }
-}
-
-const RemoteChatKey = z.object({
- encryptedKey: z.string().optional(),
- encrypted_key: z.string().optional(),
- encryptedData: z.string().optional(),
- encrypted_data: z.string().optional(),
- header: z.string(),
-});
-
-type RemoteChatKey = z.infer<typeof RemoteChatKey>;
-
-export interface ChatKey {
- encryptedKey: string;
- header: string;
-}
-
-export const getChatKey = async (): Promise<ChatKey> => {
- const res = await fetch(await apiURL("/llmchat/chat/key"), {
- headers: await authenticatedRequestHeaders(),
- });
-
- if (res.status == 404) throw new ChatKeyNotFoundError();
-
- if (res.status === 400) {
- try {
- const payload = z
- .object({ code: z.string().optional() })
- .parse(await res.json());
- if (
- payload.code === "AUTH_KEY_NOT_CREATED" ||
- payload.code === "AuthKeyNotCreated"
- ) {
- throw new ChatKeyNotFoundError();
- }
- } catch (error) {
- // ignore payload parse errors
- }
- ensureOk(res);
- }
-
- ensureOk(res);
- const data: RemoteChatKey = RemoteChatKey.parse(await res.json());
-
- const encryptedKey =
- data.encryptedKey ??
- data.encrypted_key ??
- data.encryptedData ??
- data.encrypted_data;
- if (!encryptedKey) throw new Error("Invalid chat key response");
-
- return { encryptedKey, header: data.header };
-};
-
-export const createChatKey = async (encryptedKey: string, header: string) => {
- const res = await fetch(await apiURL("/llmchat/chat/key"), {
- method: "POST",
- headers: {
- ...(await authenticatedRequestHeaders()),
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ encryptedKey, header }),
- });
-
- ensureOk(res);
-};
diff --git a/web/apps/ensu/src/services/featureFlags.ts b/web/apps/ensu/src/services/featureFlags.ts
index 58dcbfb9f5..5eae76abf1 100644
--- a/web/apps/ensu/src/services/featureFlags.ts
+++ b/web/apps/ensu/src/services/featureFlags.ts
@@ -1,2 +1 @@
-export const SIGN_IN_ENABLED = false;
export const DESKTOP_IMAGE_ATTACHMENTS_ENABLED = true;
diff --git a/web/apps/ensu/src/services/logout.ts b/web/apps/ensu/src/services/logout.ts
deleted file mode 100644
index 7192404d14..0000000000
--- a/web/apps/ensu/src/services/logout.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { isTauriRuntime } from "@/services/tauri-runtime";
-import { accountLogout } from "ente-accounts/services/logout";
-import log from "ente-base/log";
-
-/**
- * Logout sequence for the Ensu app.
- *
- * This function is guaranteed not to throw any errors.
- */
-export const ensuLogout = async () => {
- const ignoreError = (label: string, e: unknown) =>
- log.error(`Ignoring error during logout (${label})`, e);
-
- await accountLogout();
-
- if (isTauriRuntime()) {
- try {
- const { invoke } = await import("@tauri-apps/api/core");
- await invoke("chat_db_reset");
- } catch (e) {
- ignoreError("Tauri chat DB", e);
- }
- }
-
- window.location.replace("/");
-};
diff --git a/web/apps/ensu/src/services/reset.ts b/web/apps/ensu/src/services/reset.ts
new file mode 100644
index 0000000000..4a51b7a139
--- /dev/null
+++ b/web/apps/ensu/src/services/reset.ts
@@ -0,0 +1,15 @@
+import log from "ente-base/log";
+
+export const resetEnsuAppState = async () => {
+ const ignoreError = (label: string, e: unknown) =>
+ log.error(`Ignoring error during reset (${label})`, e);
+
+ try {
+ const { resetChatStore } = await import("@/services/chat/store");
+ await resetChatStore();
+ } catch (e) {
+ ignoreError("chat store", e);
+ }
+
+ window.location.replace("/");
+};
diff --git a/web/apps/ensu/src/services/session.ts b/web/apps/ensu/src/services/session.ts
deleted file mode 100644
index d04aa75e35..0000000000
--- a/web/apps/ensu/src/services/session.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-import { isTauriRuntime } from "@/services/tauri-runtime";
-import log from "ente-base/log";
-import {
- secureStorageDelete,
- secureStorageGet,
- secureStorageSet,
-} from "./secure-storage";
-import { ensureCryptoInit, enteWasm } from "./wasm";
-
-/**
- * Session storage key used to store the encrypted master key.
- *
- * This intentionally matches the key name used by other Ente web apps, but note
- * that session storage is origin-scoped, so this does not conflict with other
- * apps.
- */
-const MASTER_KEY_SESSION_KEY = "encryptionKey";
-const MASTER_KEY_SECURE_STORAGE_KEY = "masterKey";
-let _tauriMasterKeyCache: string | undefined;
-
-interface SessionKeyData {
- encryptedData: string;
- key: string;
- nonce: string;
-}
-
-const sessionKeyData = async (keyDataB64: string): Promise<SessionKeyData> => {
- await ensureCryptoInit();
- const wasm = await enteWasm();
-
- const key = await wasm.crypto_generate_key();
- const box = await wasm.crypto_encrypt_box(keyDataB64, key);
-
- return { encryptedData: box.encrypted_data, nonce: box.nonce, key };
-};
-
-/** Return the decrypted master key (base64) from session storage, if present. */
-export const masterKeyFromSession = async (): Promise<string | undefined> => {
- if (isTauriRuntime()) {
- if (_tauriMasterKeyCache) return _tauriMasterKeyCache;
- try {
- const masterKey = await secureStorageGet(
- MASTER_KEY_SECURE_STORAGE_KEY,
- );
- if (masterKey) {
- _tauriMasterKeyCache = masterKey;
- return masterKey;
- }
- } catch (error) {
- log.warn(
- "Failed to read master key from secure storage during session lookup",
- error,
- );
- }
- }
-
- const value = sessionStorage.getItem(MASTER_KEY_SESSION_KEY);
- if (!value) return undefined;
-
- const { encryptedData, key, nonce } = JSON.parse(value) as SessionKeyData;
-
- await ensureCryptoInit();
- const wasm = await enteWasm();
- const masterKey = await wasm.crypto_decrypt_box(encryptedData, nonce, key);
- if (isTauriRuntime()) {
- _tauriMasterKeyCache = masterKey;
- }
- return masterKey;
-};
-
-/** Save the master key (base64) in session storage and secure storage on Tauri. */
-export const saveMasterKeyInSession = async (masterKeyB64: string) => {
- if (isTauriRuntime()) {
- _tauriMasterKeyCache = masterKeyB64;
- try {
- await secureStorageSet(MASTER_KEY_SECURE_STORAGE_KEY, masterKeyB64);
- } catch (error) {
- log.warn("Failed to save master key to secure storage", error);
- }
- }
-
- sessionStorage.setItem(
- MASTER_KEY_SESSION_KEY,
- JSON.stringify(await sessionKeyData(masterKeyB64)),
- );
-};
-
-/** Remove the master key from session storage. */
-export const clearMasterKeyFromSession = () => {
- if (isTauriRuntime()) {
- _tauriMasterKeyCache = undefined;
- }
- sessionStorage.removeItem(MASTER_KEY_SESSION_KEY);
-};
-
-/** Remove the master key from session storage and Tauri secure storage. */
-export const clearMasterKeyFromEverywhere = async () => {
- clearMasterKeyFromSession();
- if (isTauriRuntime()) {
- try {
- await secureStorageDelete(MASTER_KEY_SECURE_STORAGE_KEY);
- } catch (error) {
- log.warn("Failed to delete master key from secure storage", error);
- }
- }
-};
-
-/** Hydrate session storage from Tauri secure storage when possible. */
-export const updateSessionFromTauriSecureStorageIfNeeded = async () => {
- if (!isTauriRuntime()) return;
- if (_tauriMasterKeyCache) return;
-
- try {
- const masterKey = await secureStorageGet(MASTER_KEY_SECURE_STORAGE_KEY);
- if (!masterKey) return;
- _tauriMasterKeyCache = masterKey;
- } catch (error) {
- log.warn("Failed to read master key from secure storage", error);
- }
-};
diff --git a/web/apps/ensu/src/services/wasm.ts b/web/apps/ensu/src/services/wasm.ts
index 13367e64f0..f60b84dfbf 100644
--- a/web/apps/ensu/src/services/wasm.ts
+++ b/web/apps/ensu/src/services/wasm.ts
@@ -2,7 +2,7 @@
* Lazy loader for the `ente-wasm` package or Tauri-native bindings.
*
* We keep this behind a dynamic import so that the WASM bundle is only loaded
- * when needed (login/crypto flows), while Tauri uses native Rust bindings.
+ * when local crypto is needed, while Tauri uses native Rust bindings.
*/
import { isTauriRuntime } from "@/services/tauri-runtime";
@@ -20,28 +20,6 @@ export interface EncryptedBlob {
decryption_header: string;
}
-export interface SrpCredentials {
- kek: string;
- login_key: string;
-}
-
-export interface DecryptedSecrets {
- master_key: string;
- secret_key: string;
- token: string;
-}
-
-export interface DecryptedKeys {
- master_key: string;
- secret_key: string;
-}
-
-export interface SrpSessionAdapter {
- public_a(): Promise<string>;
- compute_m1(srpB64: string): Promise<string>;
- verify_m2(srpM2B64: string): Promise<void>;
-}
-
export interface EnteCryptoAdapter {
crypto_init(): Promise<void>;
crypto_generate_key(): Promise<string>;
@@ -60,58 +38,9 @@ export interface EnteCryptoAdapter {
headerB64: string,
keyB64: string,
): Promise<string>;
-
- auth_derive_srp_credentials(
- password: string,
- srpAttributes: Record<string, unknown>,
- ): Promise<SrpCredentials>;
- auth_decrypt_secrets(
- kekB64: string,
- keyAttributes: Record<string, unknown>,
- encryptedTokenB64: string,
- ): Promise<DecryptedSecrets>;
- auth_decrypt_keys_only(
- kekB64: string,
- keyAttributes: Record<string, unknown>,
- ): Promise<DecryptedKeys>;
-
- SrpSession: new (
- srpUserID: string,
- srpSaltB64: string,
- loginKeyB64: string,
- ) => SrpSessionAdapter;
}
const createWasmAdapter = (wasm: EnteWasmModule): EnteCryptoAdapter => {
- class WasmSrpSession implements SrpSessionAdapter {
- private inner: InstanceType<typeof wasm.SrpSession>;
-
- constructor(
- srpUserID: string,
- srpSaltB64: string,
- loginKeyB64: string,
- ) {
- this.inner = new wasm.SrpSession(
- srpUserID,
- srpSaltB64,
- loginKeyB64,
- );
- }
-
- public_a() {
- return Promise.resolve(this.inner.public_a());
- }
-
- compute_m1(srpB64: string) {
- return Promise.resolve(this.inner.compute_m1(srpB64));
- }
-
- verify_m2(srpM2B64: string) {
- this.inner.verify_m2(srpM2B64);
- return Promise.resolve();
- }
- }
-
return {
crypto_init: () => {
wasm.crypto_init();
@@ -130,23 +59,6 @@ const createWasmAdapter = (wasm: EnteWasmModule): EnteCryptoAdapter => {
Promise.resolve(
wasm.crypto_decrypt_blob(encryptedDataB64, headerB64, keyB64),
),
-
- auth_derive_srp_credentials: (password, srpAttributes) =>
- Promise.resolve(
- wasm.auth_derive_srp_credentials(password, srpAttributes),
- ),
- auth_decrypt_secrets: (kekB64, keyAttributes, encryptedTokenB64) =>
- Promise.resolve(
- wasm.auth_decrypt_secrets(
- kekB64,
- keyAttributes,
- encryptedTokenB64,
- ),
- ),
- auth_decrypt_keys_only: (kekB64, keyAttributes) =>
- Promise.resolve(wasm.auth_decrypt_keys_only(kekB64, keyAttributes)),
-
- SrpSession: WasmSrpSession,
};
};
@@ -225,38 +137,6 @@ const createTauriAdapter = async (): Promise<EnteCryptoAdapter> => {
}
};
- class TauriSrpSession implements SrpSessionAdapter {
- private sessionIdPromise: Promise<string>;
-
- constructor(
- srpUserID: string,
- srpSaltB64: string,
- loginKeyB64: string,
- ) {
- this.sessionIdPromise = invokeOrThrow<string>("srp_session_new", {
- input: { srpUserId: srpUserID, srpSaltB64, loginKeyB64 },
- });
- }
-
- async public_a() {
- return invokeOrThrow<string>("srp_session_public_a", {
- input: { sessionId: await this.sessionIdPromise },
- });
- }
-
- async compute_m1(srpB64: string) {
- return invokeOrThrow<string>("srp_session_compute_m1", {
- input: { sessionId: await this.sessionIdPromise, srpB64 },
- });
- }
-
- async verify_m2(srpM2B64: string) {
- await invokeOrThrow("srp_session_verify_m2", {
- input: { sessionId: await this.sessionIdPromise, srpM2B64 },
- });
- }
- }
-
return {
crypto_init: async () => {
await invokeOrThrow("crypto_init");
@@ -278,21 +158,6 @@ const createTauriAdapter = async (): Promise<EnteCryptoAdapter> => {
invokeOrThrow<string>("crypto_decrypt_blob", {
input: { encryptedDataB64, headerB64, keyB64 },
}),
-
- auth_derive_srp_credentials: (password, srpAttributes) =>
- invokeOrThrow<SrpCredentials>("auth_derive_srp_credentials", {
- input: { password, srpAttrs: srpAttributes },
- }),
- auth_decrypt_secrets: (kekB64, keyAttributes, encryptedTokenB64) =>
- invokeOrThrow<DecryptedSecrets>("auth_decrypt_secrets", {
- input: { kekB64, keyAttrs: keyAttributes, encryptedTokenB64 },
- }),
- auth_decrypt_keys_only: (kekB64, keyAttributes) =>
- invokeOrThrow<DecryptedKeys>("auth_decrypt_keys_only", {
- input: { kekB64, keyAttrs: keyAttributes },
- }),
-
- SrpSession: TauriSrpSession,
};
};
diff --git a/web/package-lock.json b/web/package-lock.json
index 0778fc52f5..c41c4e135c 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -175,7 +175,6 @@
"@tauri-apps/plugin-process": "2.3.1",
"@tauri-apps/plugin-updater": "2.10.1",
"@wllama/wllama": "2.4.0",
- "ente-accounts": "*",
"ente-base": "*",
"ente-new": "*",
"ente-wasm": "*",