Skip to content

armgit / ente

Public Imported from GitHub
0

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

Fix Ensu token storage & tighten secret handling

Prateek Sunalba6f027e8a5c
diff --git a/mobile/native/android/apps/ensu/.gitignore b/mobile/native/android/apps/ensu/.gitignore
new file mode 100644
index 0000000000..98051e180a
--- /dev/null
+++ b/mobile/native/android/apps/ensu/.gitignore
@@ -0,0 +1,8 @@
+# Gradle
+.gradle/
+
+# Build outputs
+**/build/
+
+# OS
+.DS_Store
diff --git a/mobile/native/android/apps/ensu/app-ui/build.gradle.kts b/mobile/native/android/apps/ensu/app-ui/build.gradle.kts
new file mode 100644
index 0000000000..7d2e4022f1
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/build.gradle.kts
@@ -0,0 +1,66 @@
+plugins {
+ id("com.android.application")
+ id("org.jetbrains.kotlin.android")
+}
+
+android {
+ namespace = "io.ente.ensu"
+ compileSdk = 34
+
+ defaultConfig {
+ applicationId = "io.ente.ensu"
+ minSdk = 23
+ targetSdk = 34
+ versionCode = 1
+ versionName = "1.0"
+ }
+
+ buildFeatures {
+ compose = true
+ }
+
+ composeOptions {
+ kotlinCompilerExtensionVersion = "1.5.11"
+ }
+
+ packaging {
+ resources {
+ excludes += "/META-INF/{AL2.0,LGPL2.1}"
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ kotlinOptions {
+ jvmTarget = "17"
+ }
+}
+
+dependencies {
+ val composeBom = platform("androidx.compose:compose-bom:2024.02.02")
+
+ implementation(composeBom)
+ androidTestImplementation(composeBom)
+
+ implementation("androidx.activity:activity-compose:1.8.2")
+ implementation("androidx.compose.material3:material3")
+ implementation("androidx.compose.ui:ui")
+ implementation("androidx.compose.ui:ui-tooling-preview")
+ implementation("androidx.compose.material:material-icons-core")
+ implementation("androidx.compose.material:material-icons-extended")
+ implementation("androidx.compose.ui:ui-text")
+ implementation("com.google.android.material:material:1.11.0")
+ implementation("androidx.core:core-ktx:1.12.0")
+ implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0")
+ implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0")
+
+ implementation(project(":domain"))
+ implementation(project(":data"))
+ implementation(project(":crypto-auth-core"))
+
+ debugImplementation("androidx.compose.ui:ui-tooling")
+ debugImplementation("androidx.compose.ui:ui-test-manifest")
+}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/AndroidManifest.xml b/mobile/native/android/apps/ensu/app-ui/src/main/AndroidManifest.xml
new file mode 100644
index 0000000000..fbd41fc674
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/AndroidManifest.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <uses-permission android:name="android.permission.INTERNET" />
+
+ <application
+ android:label="@string/app_name"
+ android:icon="@drawable/ic_launcher_foreground"
+ android:roundIcon="@drawable/ic_launcher_foreground"
+ android:theme="@style/Theme.Ensu">
+ <activity
+ android:name=".MainActivity"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ </application>
+
+</manifest>
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
new file mode 100644
index 0000000000..d2ccffe30d
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt
@@ -0,0 +1,44 @@
+package io.ente.ensu
+
+import android.app.Application
+import androidx.lifecycle.AndroidViewModel
+import androidx.lifecycle.viewModelScope
+import io.ente.ensu.data.EndpointPreferencesDataStore
+import io.ente.ensu.data.SessionPreferencesDataStore
+import io.ente.ensu.data.auth.EnsuAuthService
+import io.ente.ensu.data.logging.InMemoryLogRepository
+import io.ente.ensu.data.storage.CredentialStore
+import io.ente.ensu.domain.store.AppStore
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.launch
+
+class AppViewModel(application: Application) : AndroidViewModel(application) {
+ private val sessionPreferences = SessionPreferencesDataStore(application)
+ private val endpointPreferences = EndpointPreferencesDataStore(application)
+ private val credentialStore = CredentialStore(application)
+
+ val logRepository = InMemoryLogRepository()
+ val store = AppStore(sessionPreferences, logRepository = logRepository)
+ val authService = EnsuAuthService(
+ context = application,
+ endpointPreferences = endpointPreferences,
+ credentialStore = credentialStore,
+ logRepository = logRepository
+ )
+
+ val currentEndpointFlow = authService.currentEndpointFlow
+
+ init {
+ store.bootstrap(viewModelScope)
+ val email = credentialStore.getEmail()
+ if (credentialStore.isLoggedIn() && !email.isNullOrBlank()) {
+ store.signIn(email)
+ }
+
+ viewModelScope.launch {
+ authService.storedEndpointFlow.collectLatest { endpoint ->
+ authService.updateEndpoint(endpoint)
+ }
+ }
+ }
+}
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
new file mode 100644
index 0000000000..1b9547256d
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/EnsuApp.kt
@@ -0,0 +1,18 @@
+package io.ente.ensu
+
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+
+@Composable
+fun EnsuApp(appViewModel: AppViewModel) {
+ val appState by appViewModel.store.state.collectAsState()
+ val logs by appViewModel.logRepository.logs.collectAsState()
+ RootView(
+ appState = appState,
+ store = appViewModel.store,
+ logs = logs,
+ authService = appViewModel.authService,
+ currentEndpointFlow = appViewModel.currentEndpointFlow
+ )
+}
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
new file mode 100644
index 0000000000..fba07297e4
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt
@@ -0,0 +1,248 @@
+@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
+
+package io.ente.ensu
+
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.padding
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.outlined.ArrowBack
+import androidx.compose.material.icons.outlined.Menu
+import androidx.compose.material3.DrawerValue
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.ModalNavigationDrawer
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TopAppBar
+import androidx.compose.material3.TopAppBarDefaults
+import androidx.compose.runtime.Composable
+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 io.ente.ensu.auth.AuthFlowScreen
+import io.ente.ensu.chat.ChatView
+import io.ente.ensu.chat.SessionDrawer
+import io.ente.ensu.components.ChoiceDialog
+import io.ente.ensu.data.auth.EnsuAuthService
+import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.designsystem.EnsuTypography
+import io.ente.ensu.domain.model.AttachmentType
+import io.ente.ensu.domain.model.LogEntry
+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.DeveloperSettingsScreen
+import io.ente.ensu.settings.LogViewerScreen
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.launch
+
+@Composable
+fun HomeView(
+ appState: AppState,
+ store: AppStore,
+ logs: List<LogEntry>,
+ authService: EnsuAuthService,
+ currentEndpointFlow: Flow<String>
+) {
+ val drawerState = androidx.compose.material3.rememberDrawerState(DrawerValue.Closed)
+ val scope = rememberCoroutineScope()
+ var isShowingAuth by remember { mutableStateOf(false) }
+ var isShowingSignOutDialog by remember { mutableStateOf(false) }
+ var destination by remember { mutableStateOf(HomeDestination.Chat) }
+
+ val currentSession = appState.chat.sessions.firstOrNull { it.id == appState.chat.currentSessionId }
+ val currentMessages = appState.chat.messages.filter { it.sessionId == currentSession?.id }
+
+ ModalNavigationDrawer(
+ drawerState = drawerState,
+ drawerContent = {
+ SessionDrawer(
+ sessions = appState.chat.sessions,
+ selectedSessionId = appState.chat.currentSessionId,
+ isLoggedIn = appState.auth.isLoggedIn,
+ userEmail = appState.auth.email,
+ onNewChat = {
+ val sessionId = store.createNewSession()
+ store.persistSelectedSession(scope, sessionId)
+ destination = HomeDestination.Chat
+ scope.launch { drawerState.close() }
+ },
+ onSelectSession = { session ->
+ store.selectSession(session.id)
+ store.persistSelectedSession(scope, session.id)
+ destination = HomeDestination.Chat
+ scope.launch { drawerState.close() }
+ },
+ onSync = {},
+ onOpenLogs = {
+ destination = HomeDestination.Logs
+ scope.launch { drawerState.close() }
+ },
+ onOpenModelSettings = {
+ destination = HomeDestination.ModelSettings
+ scope.launch { drawerState.close() }
+ },
+ onOpenDeveloperSettings = {
+ destination = HomeDestination.DeveloperSettings
+ scope.launch { drawerState.close() }
+ },
+ onSignIn = { isShowingAuth = true },
+ onSignOut = { isShowingSignOutDialog = true }
+ )
+ }
+ ) {
+ Scaffold(
+ containerColor = EnsuColor.backgroundBase(),
+ contentWindowInsets = WindowInsets(0, 0, 0, 0),
+ topBar = {
+ when (destination) {
+ HomeDestination.Chat -> {
+ Column {
+ EnsuTopBar(
+ sessionTitle = currentSession?.title,
+ showBrand = currentMessages.isEmpty(),
+ isLoggedIn = appState.auth.isLoggedIn,
+ onOpenDrawer = { scope.launch { drawerState.open() } },
+ onSignIn = { isShowingAuth = true }
+ )
+ androidx.compose.material3.HorizontalDivider(color = EnsuColor.border())
+ }
+ }
+ HomeDestination.Logs -> {
+ SimpleTopBar(title = "Logs") { destination = HomeDestination.Chat }
+ }
+ HomeDestination.ModelSettings -> {
+ SimpleTopBar(title = "Model Settings") { destination = HomeDestination.Chat }
+ }
+ HomeDestination.DeveloperSettings -> {
+ SimpleTopBar(title = "Developer Settings") { destination = HomeDestination.Chat }
+ }
+ }
+ }
+ ) { padding ->
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(padding)
+ ) {
+ when (destination) {
+ HomeDestination.Chat -> {
+ ChatView(
+ chatState = appState.chat.copy(messages = currentMessages),
+ onMessageChange = store::updateMessageText,
+ onSend = store::sendMessage,
+ onStop = {},
+ onAttachmentSelected = { _: AttachmentType -> },
+ onBranchChange = store::updateBranchSelection
+ )
+ }
+ HomeDestination.Logs -> {
+ LogViewerScreen(logs = logs)
+ }
+ HomeDestination.ModelSettings -> {
+ ModelSettingsScreen()
+ }
+ HomeDestination.DeveloperSettings -> {
+ DeveloperSettingsScreen(
+ authService = authService,
+ currentEndpointFlow = currentEndpointFlow,
+ onSaved = { destination = HomeDestination.Chat }
+ )
+ }
+ }
+ }
+ }
+ }
+
+ if (isShowingAuth) {
+ AuthFlowScreen(
+ authService = authService,
+ onLoggedIn = { email ->
+ store.signIn(email)
+ isShowingAuth = false
+ },
+ onDismiss = { isShowingAuth = false }
+ )
+ }
+
+ if (isShowingSignOutDialog) {
+ ChoiceDialog(
+ title = "Sign Out",
+ body = "This will stop syncing your sessions.",
+ firstButtonLabel = "Sign Out",
+ secondButtonLabel = "Cancel",
+ isCritical = false,
+ onFirst = {
+ authService.clearCredentials()
+ store.signOut()
+ isShowingSignOutDialog = false
+ },
+ onSecond = { isShowingSignOutDialog = false },
+ onDismiss = { isShowingSignOutDialog = false }
+ )
+ }
+}
+
+@Composable
+private fun EnsuTopBar(
+ sessionTitle: String?,
+ showBrand: Boolean,
+ isLoggedIn: Boolean,
+ onOpenDrawer: () -> Unit,
+ onSignIn: () -> Unit
+) {
+ val titleText = if (showBrand) "ensu" else sessionTitle?.takeIf { it.isNotBlank() } ?: "New Chat"
+ val titleStyle = if (showBrand) EnsuTypography.h3Bold else EnsuTypography.h3Bold
+
+ TopAppBar(
+ title = {
+ Text(
+ text = titleText,
+ style = titleStyle,
+ color = EnsuColor.textPrimary(),
+ maxLines = 1
+ )
+ },
+ navigationIcon = {
+ IconButton(onClick = onOpenDrawer) {
+ Icon(imageVector = Icons.Outlined.Menu, contentDescription = "Menu")
+ }
+ },
+ actions = {
+ if (!isLoggedIn) {
+ TextButton(onClick = onSignIn) {
+ Text(text = "Sign In", style = EnsuTypography.small, color = EnsuColor.accent())
+ }
+ }
+ },
+ colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())
+ )
+}
+
+@Composable
+private fun SimpleTopBar(title: String, onBack: () -> Unit) {
+ TopAppBar(
+ title = { Text(text = title, style = EnsuTypography.h3Bold) },
+ navigationIcon = {
+ IconButton(onClick = onBack) {
+ Icon(imageVector = Icons.Outlined.ArrowBack, contentDescription = "Back")
+ }
+ },
+ colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())
+ )
+}
+
+private enum class HomeDestination {
+ Chat,
+ Logs,
+ ModelSettings,
+ DeveloperSettings
+}
+
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/MainActivity.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/MainActivity.kt
new file mode 100644
index 0000000000..af8c7e16b2
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/MainActivity.kt
@@ -0,0 +1,22 @@
+package io.ente.ensu
+
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.lifecycle.viewmodel.compose.viewModel
+import io.ente.ensu.designsystem.EnsuTheme
+import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.utils.ApplySystemBars
+
+class MainActivity : ComponentActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContent {
+ EnsuTheme {
+ ApplySystemBars(backgroundColor = EnsuColor.backgroundBase())
+ val appViewModel: AppViewModel = viewModel()
+ EnsuApp(appViewModel = appViewModel)
+ }
+ }
+ }
+}
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
new file mode 100644
index 0000000000..20b6db4f42
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/RootView.kt
@@ -0,0 +1,36 @@
+package io.ente.ensu
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.data.auth.EnsuAuthService
+import io.ente.ensu.domain.model.LogEntry
+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,
+ logs: List<LogEntry>,
+ authService: EnsuAuthService,
+ currentEndpointFlow: Flow<String>
+) {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(EnsuColor.backgroundBase())
+ ) {
+ HomeView(
+ appState = appState,
+ store = store,
+ logs = logs,
+ authService = authService,
+ currentEndpointFlow = currentEndpointFlow
+ )
+ }
+}
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
new file mode 100644
index 0000000000..86fa643578
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthComponents.kt
@@ -0,0 +1,282 @@
+@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.material.icons.Icons
+import androidx.compose.material.icons.outlined.Visibility
+import androidx.compose.material.icons.outlined.VisibilityOff
+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 io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.designsystem.EnsuCornerRadius
+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(
+ imageVector = if (showPassword) Icons.Outlined.VisibilityOff else Icons.Outlined.Visibility,
+ 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 = "β€’ β€’ β€’ β€’ β€’ β€’",
+ 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.accent()
+ )
+ }
+}
+
+@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
new file mode 100644
index 0000000000..b35ae8e34e
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthFlowScreen.kt
@@ -0,0 +1,820 @@
+@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.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.height
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.outlined.ArrowBack
+import androidx.compose.material3.CenterAlignedTopAppBar
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TopAppBarDefaults
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.mutableStateListOf
+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.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
+
+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 = {
+ Text(
+ text = "ensu",
+ style = EnsuTypography.h3Bold,
+ color = EnsuColor.textPrimary()
+ )
+ },
+ navigationIcon = {
+ IconButton(onClick = {
+ if (canGoBack) {
+ backStack.removeLast()
+ } else {
+ onDismiss()
+ }
+ }) {
+ Icon(imageVector = Icons.Outlined.ArrowBack, 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) }
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun EmailEntryView(
+ authService: EnsuAuthService,
+ onNavigate: (AuthRoute) -> Unit
+) {
+ var email by remember { mutableStateOf("") }
+ var isLoading by remember { mutableStateOf(false) }
+ var errorMessage by remember { mutableStateOf<String?>(null) }
+ val isEmailValid = email.trim().contains("@") && email.trim().contains(".") && email.trim().length >= 5
+ val scope = rememberCoroutineScope()
+
+ 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 (errorMessage != null) {
+ Text(
+ text = errorMessage.orEmpty(),
+ style = EnsuTypography.small,
+ color = EnsuColor.error,
+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
+ )
+ }
+ }
+ },
+ bottom = {
+ PrimaryButton(
+ text = "Log in",
+ isLoading = isLoading,
+ isEnabled = isEmailValid && !isLoading
+ ) {
+ scope.launch {
+ if (isLoading) return@launch
+ isLoading = true
+ errorMessage = null
+ try {
+ 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))
+ }
+ } catch (error: Exception) {
+ errorMessage = "Failed to get account info: ${error.message}"
+ } finally {
+ isLoading = false
+ }
+ }
+ }
+ }
+ )
+}
+
+@Composable
+private fun PasswordView(
+ authService: EnsuAuthService,
+ email: String,
+ srpAttributes: SrpAttributes,
+ onNavigate: (AuthRoute) -> Unit,
+ onLoggedIn: () -> Unit
+) {
+ var password by remember { mutableStateOf("") }
+ var showPassword by remember { mutableStateOf(false) }
+ var isLoading by remember { mutableStateOf(false) }
+ var errorMessage by remember { mutableStateOf<String?>(null) }
+ val scope = rememberCoroutineScope()
+ 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 (errorMessage != null) {
+ Text(
+ text = errorMessage.orEmpty(),
+ style = EnsuTypography.small,
+ color = EnsuColor.error,
+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
+ )
+ }
+ },
+ bottom = {
+ PrimaryButton(
+ text = "Log in",
+ isLoading = isLoading,
+ isEnabled = hasPassword && !isLoading
+ ) {
+ scope.launch {
+ if (isLoading) return@launch
+ isLoading = true
+ errorMessage = null
+ try {
+ val result = authService.loginWithSrp(email, password, srpAttributes)
+ handleSrpResult(result, email, srpAttributes, password, onNavigate, onLoggedIn)
+ } catch (error: Exception) {
+ errorMessage = error.message
+ } finally {
+ isLoading = false
+ }
+ }
+ }
+ }
+ )
+}
+
+@Composable
+private fun OtpVerificationView(
+ authService: EnsuAuthService,
+ email: String,
+ srpAttributes: SrpAttributes,
+ onNavigate: (AuthRoute) -> Unit
+) {
+ var code by remember { mutableStateOf("") }
+ var isLoading by remember { mutableStateOf(false) }
+ var errorMessage by remember { mutableStateOf<String?>(null) }
+ val scope = rememberCoroutineScope()
+ val hasValidCode = code.trim().length == 6
+
+ 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 { errorMessage = "Failed to resend code: ${it.message}" }
+ }
+ }
+ if (errorMessage != null) {
+ Text(
+ text = errorMessage.orEmpty(),
+ style = EnsuTypography.small,
+ color = EnsuColor.error,
+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
+ )
+ }
+ }
+ },
+ bottom = {
+ PrimaryButton(
+ text = "Verify",
+ isLoading = isLoading,
+ isEnabled = hasValidCode && !isLoading
+ ) {
+ scope.launch {
+ if (isLoading) return@launch
+ isLoading = true
+ errorMessage = null
+ try {
+ val payload = authService.verifyOtp(email, code)
+ val keyAttrs = payload.keyAttributes
+ if (keyAttrs == null) {
+ errorMessage = "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.io",
+ 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
+ )
+ )
+ }
+ } catch (error: Exception) {
+ errorMessage = error.message
+ } finally {
+ isLoading = false
+ }
+ }
+ }
+ }
+ )
+}
+
+@Composable
+private fun TwoFactorView(
+ authService: EnsuAuthService,
+ email: String,
+ srpAttributes: SrpAttributes,
+ sessionId: String,
+ password: String?,
+ onNavigate: (AuthRoute) -> Unit,
+ onLoggedIn: () -> Unit
+) {
+ var code by remember { mutableStateOf("") }
+ var isLoading by remember { mutableStateOf(false) }
+ var errorMessage by remember { mutableStateOf<String?>(null) }
+ val scope = rememberCoroutineScope()
+ val hasValidCode = code.trim().length == 6
+
+ 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 (errorMessage != null) {
+ Text(
+ text = errorMessage.orEmpty(),
+ style = EnsuTypography.small,
+ color = EnsuColor.error,
+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
+ )
+ }
+ }
+ },
+ bottom = {
+ PrimaryButton(
+ text = "Verify",
+ isLoading = isLoading,
+ isEnabled = hasValidCode && !isLoading
+ ) {
+ scope.launch {
+ if (isLoading) return@launch
+ isLoading = true
+ errorMessage = null
+ try {
+ val payload = authService.verifyTwoFactor(sessionId, code)
+ val keyAttrs = payload.keyAttributes
+ if (keyAttrs == null) {
+ errorMessage = "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
+ )
+ )
+ }
+ } catch (error: Exception) {
+ errorMessage = error.message
+ } finally {
+ isLoading = false
+ }
+ }
+ }
+ }
+ )
+}
+
+@Composable
+private 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
+ var isChecking by remember { mutableStateOf(false) }
+ var message by remember { mutableStateOf<String?>(null) }
+ val scope = rememberCoroutineScope()
+
+ 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 (message != null) {
+ Text(
+ text = message.orEmpty(),
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted(),
+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
+ )
+ }
+ }
+ },
+ bottom = {
+ PrimaryButton(
+ text = "Check status",
+ isLoading = isChecking,
+ isEnabled = !isChecking
+ ) {
+ scope.launch {
+ if (isChecking) return@launch
+ isChecking = true
+ try {
+ val payload = authService.getTokenForPasskeySession(sessionId)
+ handlePasskeyAuthResponse(
+ authService = authService,
+ payload = payload,
+ email = email,
+ srpAttributes = srpAttributes,
+ password = password,
+ onNavigate = onNavigate,
+ onLoggedIn = onLoggedIn
+ )
+ } catch (error: PasskeySessionNotVerifiedException) {
+ message = "Passkey verification is still pending."
+ } catch (error: PasskeySessionExpiredException) {
+ message = "Login session expired."
+ } catch (error: Exception) {
+ message = "Failed to check passkey status: ${error.message}"
+ } finally {
+ isChecking = false
+ }
+ }
+ }
+ }
+ )
+}
+
+@Composable
+private 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) }
+ var isLoading by remember { mutableStateOf(false) }
+ var errorMessage by remember { mutableStateOf<String?>(null) }
+ val scope = rememberCoroutineScope()
+
+ 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 (errorMessage != null) {
+ Text(
+ text = errorMessage.orEmpty(),
+ style = EnsuTypography.small,
+ color = EnsuColor.error,
+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
+ )
+ }
+ },
+ bottom = {
+ PrimaryButton(
+ text = "Continue",
+ isLoading = isLoading,
+ isEnabled = password.isNotBlank() && !isLoading
+ ) {
+ scope.launch {
+ if (isLoading) return@launch
+ isLoading = true
+ errorMessage = null
+ try {
+ authService.loginAfterChallenge(
+ email = email,
+ password = password,
+ srpAttributes = srpAttributes,
+ userId = userId,
+ keyAttributes = keyAttributes,
+ encryptedToken = encryptedToken,
+ token = token
+ )
+ onLoggedIn()
+ } catch (error: Exception) {
+ errorMessage = "Incorrect password: ${error.message}"
+ } finally {
+ isLoading = false
+ }
+ }
+ }
+ }
+ )
+}
+
+@Composable
+private 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) }
+ var isLoading by remember { mutableStateOf(false) }
+ var errorMessage by remember { mutableStateOf<String?>(null) }
+ val scope = rememberCoroutineScope()
+
+ 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 (errorMessage != null) {
+ Text(
+ text = errorMessage.orEmpty(),
+ style = EnsuTypography.small,
+ color = EnsuColor.error,
+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
+ )
+ }
+ },
+ bottom = {
+ PrimaryButton(
+ text = "Continue",
+ isLoading = isLoading,
+ isEnabled = password.isNotBlank() && !isLoading
+ ) {
+ scope.launch {
+ if (isLoading) return@launch
+ isLoading = true
+ errorMessage = null
+ try {
+ authService.loginAfterChallenge(
+ email = email,
+ password = password,
+ srpAttributes = srpAttributes,
+ userId = auth.userId,
+ keyAttributes = keyAttributes,
+ encryptedToken = auth.encryptedToken,
+ token = auth.token
+ )
+ onLoggedIn()
+ } catch (error: Exception) {
+ errorMessage = "Incorrect password: ${error.message}"
+ } finally {
+ isLoading = false
+ }
+ }
+ }
+ }
+ )
+}
+
+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.io",
+ 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/ChatView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt
new file mode 100644
index 0000000000..3a48453d0a
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt
@@ -0,0 +1,457 @@
+package io.ente.ensu.chat
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+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.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.BasicTextField
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.outlined.ArrowForward
+import androidx.compose.material.icons.outlined.AttachFile
+import androidx.compose.material.icons.outlined.ContentCopy
+import androidx.compose.material.icons.outlined.Edit
+import androidx.compose.material.icons.outlined.StopCircle
+import androidx.compose.material.icons.outlined.Description
+import androidx.compose.material.icons.outlined.Download
+import androidx.compose.material.icons.outlined.Image
+import androidx.compose.material.icons.outlined.Refresh
+import androidx.compose.material.icons.outlined.Code
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.DropdownMenu
+import androidx.compose.material3.DropdownMenuItem
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.Text
+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.graphics.SolidColor
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.ui.text.input.KeyboardCapitalization
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import io.ente.ensu.components.ActionButton
+import io.ente.ensu.components.BranchSwitcher
+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.domain.model.Attachment
+import io.ente.ensu.domain.model.AttachmentType
+import io.ente.ensu.domain.model.ChatMessage
+import io.ente.ensu.domain.model.MessageAuthor
+import io.ente.ensu.domain.state.ChatState
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+@Composable
+fun ChatView(
+ chatState: ChatState,
+ onMessageChange: (String) -> Unit,
+ onSend: () -> Unit,
+ onStop: () -> Unit,
+ onAttachmentSelected: (AttachmentType) -> Unit,
+ onBranchChange: (String, Int) -> Unit
+) {
+ Column(modifier = Modifier.fillMaxSize()) {
+ MessageList(
+ modifier = Modifier
+ .weight(1f)
+ .padding(
+ start = EnsuSpacing.pageHorizontal.dp,
+ end = EnsuSpacing.pageHorizontal.dp,
+ top = EnsuSpacing.pageVertical.dp
+ ),
+ messages = chatState.messages,
+ branchSelections = chatState.branchSelections,
+ onBranchChange = onBranchChange
+ )
+
+ MessageInput(
+ modifier = Modifier
+ .fillMaxWidth()
+ .navigationBarsPadding()
+ .background(EnsuColor.backgroundBase()),
+ messageText = chatState.messageText,
+ attachments = chatState.attachments,
+ isProcessingAttachments = chatState.isProcessingAttachments,
+ isGenerating = chatState.isGenerating,
+ isDownloading = chatState.isDownloading,
+ onMessageChange = onMessageChange,
+ onSend = onSend,
+ onStop = onStop,
+ onAttachmentSelected = onAttachmentSelected
+ )
+ }
+}
+
+@Composable
+private fun MessageList(
+ modifier: Modifier,
+ messages: List<ChatMessage>,
+ branchSelections: Map<String, Int>,
+ onBranchChange: (String, Int) -> Unit
+) {
+ if (messages.isEmpty()) {
+ EmptyState(modifier = modifier)
+ return
+ }
+
+ LazyColumn(
+ modifier = modifier,
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp)
+ ) {
+ items(messages, key = { it.id }) { message ->
+ when (message.author) {
+ MessageAuthor.User -> {
+ UserMessageBubble(
+ message = message,
+ branchSelections = branchSelections,
+ onBranchChange = onBranchChange
+ )
+ }
+ MessageAuthor.Assistant -> {
+ AssistantMessageBubble(
+ message = message,
+ branchSelections = branchSelections,
+ onBranchChange = onBranchChange
+ )
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun EmptyState(modifier: Modifier) {
+ Box(
+ modifier = modifier.fillMaxSize(),
+ contentAlignment = Alignment.Center
+ ) {
+ Text(
+ text = "Start typing to begin a conversation",
+ style = EnsuTypography.body,
+ color = EnsuColor.textMuted(),
+ textAlign = TextAlign.Center
+ )
+ }
+}
+
+@Composable
+private fun UserMessageBubble(
+ message: ChatMessage,
+ branchSelections: Map<String, Int>,
+ onBranchChange: (String, Int) -> Unit
+) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(start = EnsuSpacing.messageBubbleInset.dp),
+ horizontalAlignment = Alignment.End
+ ) {
+ Text(
+ text = message.text,
+ style = EnsuTypography.message,
+ color = EnsuColor.userMessageText(),
+ textAlign = TextAlign.Right
+ )
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+
+ Row(horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
+ ActionButton(
+ icon = Icons.Outlined.Edit,
+ onTap = {},
+ contentDescription = "Edit"
+ )
+ ActionButton(
+ icon = Icons.Outlined.ContentCopy,
+ onTap = {},
+ contentDescription = "Copy"
+ )
+ }
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Spacer(modifier = Modifier.weight(1f))
+ if (message.branchCount > 1) {
+ BranchSwitcher(
+ currentIndex = branchSelections[message.id] ?: 1,
+ totalCount = message.branchCount,
+ onPrevious = {
+ val current = branchSelections[message.id] ?: 1
+ onBranchChange(message.id, (current - 1).coerceAtLeast(1))
+ },
+ onNext = {
+ val current = branchSelections[message.id] ?: 1
+ onBranchChange(message.id, (current + 1).coerceAtMost(message.branchCount))
+ }
+ )
+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
+ }
+ TimestampText(message.timestampMillis)
+ }
+ }
+}
+
+@Composable
+private fun AssistantMessageBubble(
+ message: ChatMessage,
+ branchSelections: Map<String, Int>,
+ onBranchChange: (String, Int) -> Unit
+) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(end = EnsuSpacing.messageBubbleInset.dp),
+ horizontalAlignment = Alignment.Start
+ ) {
+ Text(
+ text = message.text,
+ style = EnsuTypography.message,
+ color = EnsuColor.textPrimary()
+ )
+
+ if (message.isInterrupted) {
+ Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+ Text(
+ text = "Interrupted",
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted()
+ )
+ }
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ ActionButton(
+ icon = Icons.Outlined.ContentCopy,
+ onTap = {},
+ contentDescription = "Copy"
+ )
+ ActionButton(
+ icon = Icons.Outlined.Code,
+ onTap = {},
+ contentDescription = "Raw"
+ )
+ ActionButton(
+ icon = Icons.Outlined.Refresh,
+ onTap = {},
+ contentDescription = "Retry"
+ )
+ message.tokensPerSecond?.let { tokPerSec ->
+ Text(
+ text = String.format(Locale.US, "%.1f tok/s", tokPerSec),
+ style = EnsuTypography.mini,
+ color = EnsuColor.textMuted()
+ )
+ }
+ }
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ TimestampText(message.timestampMillis)
+ Spacer(modifier = Modifier.weight(1f))
+ if (message.branchCount > 1) {
+ BranchSwitcher(
+ currentIndex = branchSelections[message.id] ?: 1,
+ totalCount = message.branchCount,
+ onPrevious = {
+ val current = branchSelections[message.id] ?: 1
+ onBranchChange(message.id, (current - 1).coerceAtLeast(1))
+ },
+ onNext = {
+ val current = branchSelections[message.id] ?: 1
+ onBranchChange(message.id, (current + 1).coerceAtMost(message.branchCount))
+ }
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun TimestampText(timestampMillis: Long) {
+ Text(
+ text = timestampFormatter.format(Date(timestampMillis)),
+ style = EnsuTypography.mini,
+ color = EnsuColor.textMuted()
+ )
+}
+
+@Composable
+private fun MessageInput(
+ modifier: Modifier,
+ messageText: String,
+ attachments: List<Attachment>,
+ isProcessingAttachments: Boolean,
+ isGenerating: Boolean,
+ isDownloading: Boolean,
+ onMessageChange: (String) -> Unit,
+ onSend: () -> Unit,
+ onStop: () -> Unit,
+ onAttachmentSelected: (AttachmentType) -> Unit
+) {
+ var showMenu by remember { mutableStateOf(false) }
+ val placeholder = if (isDownloading) {
+ "Downloading model... (queue messages)"
+ } else {
+ "Compose your message..."
+ }
+
+ Column(
+ modifier = modifier
+ .background(EnsuColor.backgroundBase()),
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)
+ ) {
+ if (attachments.isNotEmpty()) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .horizontalScroll(rememberScrollState())
+ .padding(horizontal = EnsuSpacing.pageHorizontal.dp),
+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)
+ ) {
+ attachments.forEach { attachment ->
+ val icon = when (attachment.type) {
+ AttachmentType.Image -> Icons.Outlined.Image
+ AttachmentType.Document -> Icons.Outlined.Description
+ }
+ io.ente.ensu.components.AttachmentChip(
+ name = attachment.name,
+ size = "${attachment.sizeBytes / 1024} KB",
+ icon = icon,
+ isUploading = attachment.isUploading
+ )
+ }
+ }
+ }
+
+ if (isProcessingAttachments) {
+ Row(
+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
+ Text(text = "Reading attachment...", style = EnsuTypography.small)
+ }
+ }
+
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = EnsuSpacing.pageHorizontal.dp)
+ .padding(bottom = EnsuSpacing.sm.dp)
+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.input.dp))
+ .padding(
+ horizontal = EnsuSpacing.inputHorizontal.dp,
+ vertical = EnsuSpacing.inputVertical.dp
+ )
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ BasicTextField(
+ value = messageText,
+ onValueChange = onMessageChange,
+ modifier = Modifier.weight(1f),
+ textStyle = EnsuTypography.message.copy(color = EnsuColor.textPrimary()),
+ minLines = 1,
+ maxLines = 5,
+ keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences),
+ cursorBrush = SolidColor(EnsuColor.accent())
+ ) { innerTextField ->
+ Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterStart) {
+ if (messageText.isBlank()) {
+ Text(
+ text = placeholder,
+ style = EnsuTypography.message,
+ color = EnsuColor.textMuted()
+ )
+ }
+ innerTextField()
+ }
+ }
+
+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
+
+ Box {
+ IconButton(
+ onClick = { showMenu = true },
+ enabled = !isGenerating && !isDownloading,
+ modifier = Modifier.size(36.dp)
+ ) {
+ Icon(
+ imageVector = Icons.Outlined.AttachFile,
+ contentDescription = "Attach"
+ )
+ }
+ DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {
+ DropdownMenuItem(
+ text = { Text(text = "Image") },
+ onClick = {
+ showMenu = false
+ onAttachmentSelected(AttachmentType.Image)
+ }
+ )
+ DropdownMenuItem(
+ text = { Text(text = "Document") },
+ onClick = {
+ showMenu = false
+ onAttachmentSelected(AttachmentType.Document)
+ }
+ )
+ }
+ }
+
+ IconButton(
+ onClick = if (isGenerating) onStop else onSend,
+ enabled = !isDownloading,
+ modifier = Modifier.size(36.dp)
+ ) {
+ val icon = when {
+ isGenerating -> Icons.Outlined.StopCircle
+ isDownloading -> Icons.Outlined.Download
+ else -> Icons.AutoMirrored.Outlined.ArrowForward
+ }
+ val tint = when {
+ isGenerating -> EnsuColor.stopButton
+ isDownloading -> EnsuColor.textMuted()
+ else -> EnsuColor.textMuted()
+ }
+ Icon(
+ imageVector = icon,
+ contentDescription = "Send",
+ modifier = Modifier.size(22.dp),
+ tint = tint
+ )
+ }
+ }
+ }
+ }
+}
+
+private val timestampFormatter = SimpleDateFormat("h:mm a", Locale.getDefault())
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
new file mode 100644
index 0000000000..026447de5b
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt
@@ -0,0 +1,350 @@
+package io.ente.ensu.chat
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+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.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.systemBars
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.windowInsetsPadding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.ui.graphics.RectangleShape
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.outlined.Add
+import androidx.compose.material.icons.outlined.BugReport
+import androidx.compose.material.icons.outlined.Build
+import androidx.compose.material.icons.outlined.Cloud
+import androidx.compose.material.icons.outlined.Delete
+import androidx.compose.material.icons.outlined.Refresh
+import androidx.compose.material.icons.outlined.Tune
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.Icon
+import androidx.compose.material3.ModalDrawerSheet
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+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.domain.model.ChatSession
+import kotlin.math.absoluteValue
+
+@Composable
+fun SessionDrawer(
+ sessions: List<ChatSession>,
+ selectedSessionId: String?,
+ isLoggedIn: Boolean,
+ userEmail: String?,
+ onNewChat: () -> Unit,
+ onSelectSession: (ChatSession) -> Unit,
+ onSync: () -> Unit,
+ onOpenLogs: () -> Unit,
+ onOpenDeveloperSettings: () -> Unit,
+ onOpenModelSettings: () -> Unit,
+ onSignIn: () -> Unit,
+ onSignOut: () -> Unit
+) {
+ ModalDrawerSheet(
+ drawerContainerColor = EnsuColor.backgroundBase(),
+ drawerShape = RectangleShape
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .windowInsetsPadding(WindowInsets.systemBars)
+ ) {
+ DrawerHeader(
+ isLoggedIn = isLoggedIn,
+ userEmail = userEmail,
+ onSync = onSync,
+ onOpenLogs = onOpenLogs,
+ onOpenDeveloperSettings = onOpenDeveloperSettings,
+ onOpenModelSettings = onOpenModelSettings
+ )
+
+ HorizontalDivider(color = EnsuColor.border())
+
+ Column(
+ modifier = Modifier
+ .weight(1f)
+ .verticalScroll(rememberScrollState())
+ .padding(vertical = EnsuSpacing.lg.dp),
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp)
+ ) {
+ DrawerNewChat(onNewChat = onNewChat)
+ SessionGroups(
+ sessions = sessions,
+ selectedSessionId = selectedSessionId,
+ onSelectSession = onSelectSession
+ )
+ }
+
+ HorizontalDivider(color = EnsuColor.border())
+
+ DrawerFooter(
+ isLoggedIn = isLoggedIn,
+ onSignIn = onSignIn,
+ onSignOut = onSignOut
+ )
+ }
+ }
+}
+
+@Composable
+private fun DrawerHeader(
+ isLoggedIn: Boolean,
+ userEmail: String?,
+ onSync: () -> Unit,
+ onOpenLogs: () -> Unit,
+ onOpenDeveloperSettings: () -> Unit,
+ onOpenModelSettings: () -> Unit
+) {
+ val backgroundBrush = Brush.linearGradient(
+ colors = listOf(
+ EnsuColor.accent().copy(alpha = 0.2f),
+ EnsuColor.backgroundBase()
+ ),
+ start = Offset(0f, 0f),
+ end = Offset(600f, 600f)
+ )
+
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .background(backgroundBrush)
+ .padding(EnsuSpacing.lg.dp),
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)
+ ) {
+ Text(
+ text = "ensu",
+ style = EnsuTypography.h2.copy(letterSpacing = 1.sp),
+ color = EnsuColor.textPrimary()
+ )
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ if (isLoggedIn) {
+ DrawerIconButton(icon = Icons.Outlined.Refresh, contentDescription = "Sync", onClick = onSync)
+ }
+ DrawerIconButton(icon = Icons.Outlined.BugReport, contentDescription = "Logs", onClick = onOpenLogs)
+ DrawerIconButton(icon = Icons.Outlined.Build, contentDescription = "Developer settings", onClick = onOpenDeveloperSettings)
+ DrawerIconButton(icon = Icons.Outlined.Tune, contentDescription = "Model settings", onClick = onOpenModelSettings)
+ Spacer(modifier = Modifier.weight(1f))
+ }
+
+ if (isLoggedIn && !userEmail.isNullOrBlank()) {
+ CloudBadge(email = userEmail)
+ }
+ }
+}
+
+@Composable
+private fun DrawerIconButton(
+ icon: androidx.compose.ui.graphics.vector.ImageVector,
+ contentDescription: String,
+ onClick: () -> Unit
+) {
+ Box(
+ modifier = Modifier
+ .size(40.dp)
+ .clickable(onClick = onClick),
+ contentAlignment = Alignment.Center
+ ) {
+ Icon(
+ imageVector = icon,
+ contentDescription = contentDescription,
+ modifier = Modifier.size(18.dp),
+ tint = EnsuColor.textPrimary()
+ )
+ }
+}
+
+@Composable
+private fun CloudBadge(email: String) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier
+ .clip(RoundedCornerShape(EnsuCornerRadius.card.dp))
+ .background(EnsuColor.fillFaint())
+ .padding(horizontal = EnsuSpacing.md.dp, vertical = EnsuSpacing.sm.dp)
+ ) {
+ Icon(
+ imageVector = Icons.Outlined.Cloud,
+ contentDescription = null,
+ modifier = Modifier.size(16.dp),
+ tint = EnsuColor.textMuted()
+ )
+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
+ Text(
+ text = email,
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted(),
+ maxLines = 1
+ )
+ }
+}
+
+@Composable
+private fun DrawerNewChat(onNewChat: () -> Unit) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable(onClick = onNewChat)
+ .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.sm.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Icon(
+ imageVector = Icons.Outlined.Add,
+ contentDescription = "New chat",
+ modifier = Modifier.size(18.dp),
+ tint = EnsuColor.textPrimary()
+ )
+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
+ Text(text = "New Chat", style = EnsuTypography.body, color = EnsuColor.textPrimary())
+ }
+}
+
+@Composable
+private fun SessionGroups(
+ sessions: List<ChatSession>,
+ selectedSessionId: String?,
+ onSelectSession: (ChatSession) -> Unit
+) {
+ val grouped = sessions.groupBy { sessionGroupLabel(it.updatedAtMillis) }
+ val order = listOf("TODAY", "YESTERDAY", "THIS WEEK", "LAST WEEK", "THIS MONTH", "OLDER")
+
+ Column(
+ modifier = Modifier.fillMaxWidth(),
+ // iOS uses `VStack(..., spacing: EnsuSpacing.lg)`, but Compose text metrics
+ // make this look a bit looser, so we tighten slightly.
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)
+ ) {
+ order.forEach { label ->
+ val groupSessions = grouped[label] ?: return@forEach
+
+ Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {
+ Text(
+ text = label,
+ style = EnsuTypography.tiny.copy(letterSpacing = 1.sp),
+ color = EnsuColor.textMuted(),
+ modifier = Modifier.padding(horizontal = EnsuSpacing.lg.dp)
+ )
+
+ groupSessions.forEach { session ->
+ SessionTile(
+ session = session,
+ isSelected = session.id == selectedSessionId,
+ onSelect = { onSelectSession(session) }
+ )
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun SessionTile(
+ session: ChatSession,
+ isSelected: Boolean,
+ onSelect: () -> Unit
+) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable(onClick = onSelect)
+ .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.sm.dp)
+ ) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)
+ ) {
+ Column(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Text(
+ text = session.title,
+ style = if (isSelected) EnsuTypography.body else EnsuTypography.small,
+ fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Medium,
+ color = EnsuColor.textPrimary()
+ )
+ val subtitle = session.lastMessagePreview ?: "Nothing here"
+ Text(
+ text = subtitle,
+ style = EnsuTypography.mini,
+ color = EnsuColor.textMuted(),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ Box(
+ modifier = Modifier
+ .size(36.dp)
+ .clip(RoundedCornerShape(4.dp))
+ .clickable(onClick = {}),
+ contentAlignment = Alignment.Center
+ ) {
+ Icon(
+ imageVector = Icons.Outlined.Delete,
+ contentDescription = "Delete",
+ modifier = Modifier.size(18.dp),
+ tint = EnsuColor.textMuted()
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun DrawerFooter(
+ isLoggedIn: Boolean,
+ onSignIn: () -> Unit,
+ onSignOut: () -> Unit
+) {
+ val label = if (isLoggedIn) "Sign Out" else "Sign In to Backup"
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable(onClick = if (isLoggedIn) onSignOut else onSignIn)
+ .padding(EnsuSpacing.lg.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(text = label, style = EnsuTypography.body, color = EnsuColor.textPrimary())
+ }
+}
+
+private fun sessionGroupLabel(updatedAtMillis: Long): String {
+ val now = System.currentTimeMillis()
+ val dayMillis = 86_400_000L
+ val daysAgo = ((now - updatedAtMillis) / dayMillis).absoluteValue
+ return when {
+ daysAgo == 0L -> "TODAY"
+ daysAgo == 1L -> "YESTERDAY"
+ daysAgo < 7L -> "THIS WEEK"
+ daysAgo < 14L -> "LAST WEEK"
+ daysAgo < 30L -> "THIS MONTH"
+ else -> "OLDER"
+ }
+}
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
new file mode 100644
index 0000000000..d38a08ccad
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ActionButtons.kt
@@ -0,0 +1,45 @@
+package io.ente.ensu.components
+
+import androidx.compose.foundation.layout.size
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.IconButtonDefaults
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.unit.dp
+import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.designsystem.EnsuTypography
+
+@Composable
+fun ActionButton(
+ icon: ImageVector,
+ onTap: () -> Unit,
+ contentDescription: String,
+ color: Color = EnsuColor.textMuted()
+) {
+ IconButton(
+ onClick = onTap,
+ modifier = Modifier.size(36.dp),
+ colors = IconButtonDefaults.iconButtonColors(contentColor = color)
+ ) {
+ Icon(
+ imageVector = icon,
+ contentDescription = contentDescription,
+ modifier = Modifier.size(16.dp)
+ )
+ }
+}
+
+@Composable
+fun TextActionButton(
+ text: String,
+ onTap: () -> Unit
+) {
+ TextButton(onClick = onTap) {
+ Text(text = text, style = EnsuTypography.small, color = EnsuColor.textMuted())
+ }
+}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/AttachmentChip.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/AttachmentChip.kt
new file mode 100644
index 0000000000..4dcbbc6442
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/AttachmentChip.kt
@@ -0,0 +1,51 @@
+package io.ente.ensu.components
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.material3.AssistChip
+import androidx.compose.material3.AssistChipDefaults
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.Icon
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.unit.dp
+import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.designsystem.EnsuTypography
+
+@Composable
+fun AttachmentChip(
+ name: String,
+ size: String,
+ icon: ImageVector,
+ isUploading: Boolean,
+ onDelete: (() -> Unit)? = null
+) {
+ AssistChip(
+ onClick = { onDelete?.invoke() },
+ label = {
+ Column(verticalArrangement = Arrangement.Center) {
+ Text(text = name, style = EnsuTypography.small, maxLines = 1)
+ Text(text = size, style = EnsuTypography.mini, color = EnsuColor.textMuted())
+ }
+ },
+ leadingIcon = {
+ Icon(imageVector = icon, contentDescription = null, modifier = Modifier.size(16.dp))
+ },
+ trailingIcon = {
+ if (isUploading) {
+ CircularProgressIndicator(
+ modifier = Modifier.size(12.dp),
+ strokeWidth = 2.dp
+ )
+ }
+ },
+ colors = AssistChipDefaults.assistChipColors(containerColor = EnsuColor.fillFaint())
+ )
+}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/BranchSwitcher.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/BranchSwitcher.kt
new file mode 100644
index 0000000000..38cc293a0b
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/BranchSwitcher.kt
@@ -0,0 +1,50 @@
+package io.ente.ensu.components
+
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.size
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.unit.dp
+import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.designsystem.EnsuTypography
+
+@Composable
+fun BranchSwitcher(
+ currentIndex: Int,
+ totalCount: Int,
+ onPrevious: () -> Unit,
+ onNext: () -> Unit
+) {
+ if (totalCount <= 1) return
+
+ Row {
+ TextButton(
+ onClick = onPrevious,
+ enabled = currentIndex > 1,
+ modifier = Modifier.size(36.dp),
+ contentPadding = ButtonDefaults.TextButtonContentPadding
+ ) {
+ Text(text = "<", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ }
+ Spacer(modifier = Modifier.width(4.dp))
+ Text(
+ text = "${currentIndex}/${totalCount}",
+ style = EnsuTypography.small.copy(fontFeatureSettings = "tnum"),
+ color = EnsuColor.textMuted()
+ )
+ Spacer(modifier = Modifier.width(4.dp))
+ TextButton(
+ onClick = onNext,
+ enabled = currentIndex < totalCount,
+ modifier = Modifier.size(36.dp),
+ contentPadding = ButtonDefaults.TextButtonContentPadding
+ ) {
+ Text(text = ">", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ }
+ }
+}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ChoiceDialog.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ChoiceDialog.kt
new file mode 100644
index 0000000000..4d83b62f99
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ChoiceDialog.kt
@@ -0,0 +1,46 @@
+package io.ente.ensu.components
+
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.designsystem.EnsuTypography
+
+@Composable
+fun ChoiceDialog(
+ title: String,
+ body: String,
+ firstButtonLabel: String,
+ secondButtonLabel: String? = null,
+ isCritical: Boolean = false,
+ isDismissible: Boolean = true,
+ onFirst: () -> Unit,
+ onSecond: (() -> Unit)? = null,
+ onDismiss: () -> Unit
+) {
+ AlertDialog(
+ onDismissRequest = { if (isDismissible) onDismiss() },
+ title = { Text(text = title, style = EnsuTypography.h3) },
+ text = { Text(text = body, style = EnsuTypography.body) },
+ confirmButton = {
+ Button(
+ onClick = onFirst,
+ colors = ButtonDefaults.buttonColors(
+ containerColor = if (isCritical) EnsuColor.error else EnsuColor.accent()
+ )
+ ) {
+ Text(text = firstButtonLabel)
+ }
+ },
+ dismissButton = {
+ if (secondButtonLabel != null && onSecond != null) {
+ TextButton(onClick = onSecond) {
+ Text(text = secondButtonLabel)
+ }
+ }
+ }
+ )
+}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/designsystem/EnsuTheme.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/designsystem/EnsuTheme.kt
new file mode 100644
index 0000000000..01e13fee3c
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/designsystem/EnsuTheme.kt
@@ -0,0 +1,191 @@
+package io.ente.ensu.designsystem
+
+import androidx.compose.foundation.isSystemInDarkTheme
+import androidx.compose.material3.ColorScheme
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Typography
+import androidx.compose.material3.darkColorScheme
+import androidx.compose.material3.lightColorScheme
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.Font
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.sp
+import io.ente.ensu.R
+
+object EnsuColor {
+ val backgroundBaseLight = Color(0xFFF8F5F0)
+ val backgroundBaseDark = Color(0xFF141414)
+
+ val textPrimaryLight = Color(0xFF1A1A1A)
+ val textPrimaryDark = Color(0xFFE8E4DF)
+
+ val textMutedLight = Color(0xFF8A8680)
+ val textMutedDark = Color(0xFF777777)
+
+ val borderLight = Color(0xFFD4D0C8)
+ val borderDark = Color(0xFF2A2A2A)
+
+ val fillFaintLight = Color(0xFFF0EBE4)
+ val fillFaintDark = Color(0xFF1E1E1E)
+
+ val accentLight = Color(0xFF9A7E0A)
+ val accentDark = Color(0xFFFFD700)
+
+ val userMessageTextLight = Color(0xFF555555)
+ val userMessageTextDark = Color(0xFF999999)
+
+ val error = Color(0xFFFF4444)
+ val success = Color(0xFF4CAF50)
+ val stopButton = Color(0xFFFF0000)
+
+ val toastBackgroundLight = Color(0xFF1A1A1A)
+ val toastBackgroundDark = Color(0xFFF8F5F0)
+
+ val toastTextLight = Color(0xFFF8F5F0)
+ val toastTextDark = Color(0xFF1A1A1A)
+
+ @Composable
+ fun backgroundBase(): Color = if (isSystemInDarkTheme()) backgroundBaseDark else backgroundBaseLight
+
+ @Composable
+ fun textPrimary(): Color = if (isSystemInDarkTheme()) textPrimaryDark else textPrimaryLight
+
+ @Composable
+ fun textMuted(): Color = if (isSystemInDarkTheme()) textMutedDark else textMutedLight
+
+ @Composable
+ fun border(): Color = if (isSystemInDarkTheme()) borderDark else borderLight
+
+ @Composable
+ fun fillFaint(): Color = if (isSystemInDarkTheme()) fillFaintDark else fillFaintLight
+
+ @Composable
+ fun accent(): Color = if (isSystemInDarkTheme()) accentDark else accentLight
+
+ @Composable
+ fun userMessageText(): Color = if (isSystemInDarkTheme()) userMessageTextDark else userMessageTextLight
+
+ @Composable
+ fun toastBackground(): Color = if (isSystemInDarkTheme()) toastBackgroundDark else toastBackgroundLight
+
+ @Composable
+ fun toastText(): Color = if (isSystemInDarkTheme()) toastTextDark else toastTextLight
+}
+
+object EnsuSpacing {
+ const val xs = 4
+ const val sm = 8
+ const val md = 12
+ const val lg = 16
+ const val xl = 20
+ const val xxl = 24
+ const val xxxl = 32
+
+ const val pageHorizontal = 24
+ const val pageVertical = 24
+ const val inputHorizontal = 16
+ const val inputVertical = 16
+ const val buttonVertical = 18
+ const val cardPadding = 12
+ const val messageBubbleInset = 80
+}
+
+object EnsuCornerRadius {
+ const val button = 8
+ const val input = 8
+ const val card = 12
+ const val toast = 12
+ const val codeBlock = 10
+}
+
+object EnsuTypography {
+ private val serifFamily = FontFamily(
+ Font(R.font.cormorant_garamond_variable, FontWeight.Medium),
+ Font(R.font.cormorant_garamond_variable, FontWeight.SemiBold)
+ )
+
+ private val uiFamily = FontFamily(
+ Font(R.font.inter_regular, FontWeight.Normal),
+ Font(R.font.inter_medium, FontWeight.Medium),
+ Font(R.font.inter_semibold, FontWeight.SemiBold),
+ Font(R.font.inter_bold, FontWeight.Bold)
+ )
+
+ private val messageFamily = FontFamily(
+ Font(R.font.sourceserif4_variable, FontWeight.Normal),
+ Font(R.font.sourceserif4_variable, FontWeight.SemiBold),
+ Font(R.font.sourceserif4_variable, FontWeight.Bold)
+ )
+
+ private val codeFamily = FontFamily(
+ Font(R.font.jetbrainsmono_regular, FontWeight.Normal)
+ )
+
+ val h1 = TextStyle(fontFamily = serifFamily, fontSize = 48.sp, fontWeight = FontWeight.Medium, lineHeight = 82.sp)
+ val h2 = TextStyle(fontFamily = serifFamily, fontSize = 32.sp, fontWeight = FontWeight.Medium, lineHeight = 39.sp)
+ val h3 = TextStyle(fontFamily = serifFamily, fontSize = 24.sp, fontWeight = FontWeight.Medium, lineHeight = 29.sp)
+ val large = TextStyle(fontFamily = serifFamily, fontSize = 18.sp, fontWeight = FontWeight.Medium, lineHeight = 22.sp)
+
+ val h1Bold = TextStyle(fontFamily = serifFamily, fontSize = 48.sp, fontWeight = FontWeight.SemiBold, lineHeight = 82.sp)
+ val h2Bold = TextStyle(fontFamily = serifFamily, fontSize = 32.sp, fontWeight = FontWeight.SemiBold, lineHeight = 39.sp)
+ val h3Bold = TextStyle(fontFamily = serifFamily, fontSize = 24.sp, fontWeight = FontWeight.SemiBold, lineHeight = 29.sp)
+
+ val body = TextStyle(fontFamily = uiFamily, fontSize = 16.sp, fontWeight = FontWeight.Medium, lineHeight = 20.sp)
+ val small = TextStyle(fontFamily = uiFamily, fontSize = 14.sp, fontWeight = FontWeight.Medium, lineHeight = 17.sp)
+ val mini = TextStyle(fontFamily = uiFamily, fontSize = 12.sp, fontWeight = FontWeight.Medium, lineHeight = 15.sp)
+ val tiny = TextStyle(fontFamily = uiFamily, fontSize = 10.sp, fontWeight = FontWeight.Medium, lineHeight = 12.sp)
+
+ val message = TextStyle(fontFamily = messageFamily, fontSize = 15.sp, fontWeight = FontWeight.Normal, lineHeight = 26.sp)
+ val code = TextStyle(fontFamily = codeFamily, fontSize = 13.sp, fontWeight = FontWeight.Normal, lineHeight = 19.sp)
+
+ val material = Typography(
+ bodyLarge = body,
+ bodyMedium = body,
+ bodySmall = small,
+ titleLarge = h2,
+ titleMedium = h3,
+ titleSmall = large,
+ labelLarge = small,
+ labelMedium = mini,
+ labelSmall = tiny
+ )
+}
+
+@Composable
+fun EnsuTheme(content: @Composable () -> Unit) {
+ val isDark = isSystemInDarkTheme()
+ MaterialTheme(
+ colorScheme = if (isDark) darkEnsuColorScheme() else lightEnsuColorScheme(),
+ typography = EnsuTypography.material,
+ content = content
+ )
+}
+
+private fun lightEnsuColorScheme(): ColorScheme = lightColorScheme(
+ primary = EnsuColor.accentLight,
+ onPrimary = EnsuColor.backgroundBaseLight,
+ secondary = EnsuColor.fillFaintLight,
+ onSecondary = EnsuColor.textPrimaryLight,
+ background = EnsuColor.backgroundBaseLight,
+ onBackground = EnsuColor.textPrimaryLight,
+ surface = EnsuColor.fillFaintLight,
+ onSurface = EnsuColor.textPrimaryLight,
+ outline = EnsuColor.borderLight,
+ error = EnsuColor.error
+)
+
+private fun darkEnsuColorScheme(): ColorScheme = darkColorScheme(
+ primary = EnsuColor.accentDark,
+ onPrimary = EnsuColor.backgroundBaseDark,
+ secondary = EnsuColor.fillFaintDark,
+ onSecondary = EnsuColor.textPrimaryDark,
+ background = EnsuColor.backgroundBaseDark,
+ onBackground = EnsuColor.textPrimaryDark,
+ surface = EnsuColor.fillFaintDark,
+ onSurface = EnsuColor.textPrimaryDark,
+ outline = EnsuColor.borderDark,
+ error = EnsuColor.error
+)
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.kt
new file mode 100644
index 0000000000..aaab5048a9
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.kt
@@ -0,0 +1,173 @@
+package io.ente.ensu.modelsettings
+
+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.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.Card
+import androidx.compose.material3.Divider
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+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.Modifier
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.unit.dp
+import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.designsystem.EnsuSpacing
+import io.ente.ensu.designsystem.EnsuTypography
+
+@Composable
+fun ModelSettingsScreen() {
+ var modelUrl by remember { mutableStateOf("") }
+ var mmprojUrl by remember { mutableStateOf("") }
+ var contextLength by remember { mutableStateOf("") }
+ var maxTokens by remember { mutableStateOf("") }
+
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .verticalScroll(rememberScrollState())
+ .padding(EnsuSpacing.pageHorizontal.dp)
+ ) {
+ SectionHeader("Selected model")
+ Text(text = "Qwen3-VL 2B Instruct", style = EnsuTypography.body)
+ Text(text = "Not loaded", style = EnsuTypography.small, color = EnsuColor.textMuted())
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.xl.dp))
+ SectionHeader("Custom Hugging Face model")
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+
+ Text(text = "Direct .gguf file URL", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+ OutlinedTextField(
+ value = modelUrl,
+ onValueChange = { modelUrl = it },
+ placeholder = { Text(text = "https://huggingface.co/...") },
+ modifier = Modifier.fillMaxWidth()
+ )
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
+
+ Text(text = "mmproj .gguf file URL", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+ OutlinedTextField(
+ value = mmprojUrl,
+ onValueChange = { mmprojUrl = it },
+ placeholder = { Text(text = "(optional for multimodal)") },
+ modifier = Modifier.fillMaxWidth()
+ )
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.lg.dp))
+
+ Text(text = "Suggested models:", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ SuggestedModelCard(
+ title = "Qwen3-VL 2B Instruct (Q4_K_M)",
+ subtitle = "Requires mmproj"
+ )
+ SuggestedModelCard(
+ title = "LFM 2.5 1.2B Instruct (Q4_0)",
+ subtitle = "Smallest download"
+ )
+ SuggestedModelCard(
+ title = "LFM 2.5 VL 1.6B (Q4_0)",
+ subtitle = "Requires mmproj"
+ )
+ SuggestedModelCard(
+ title = "Llama 3.2 1B Instruct (Q4_K_M)",
+ subtitle = "Fastest load"
+ )
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.xl.dp))
+ SectionHeader("Custom limits (optional)")
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+
+ Row {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(text = "Context length", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+ OutlinedTextField(
+ value = contextLength,
+ onValueChange = { contextLength = it },
+ placeholder = { Text(text = "8192") },
+ modifier = Modifier.fillMaxWidth(),
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
+ )
+ }
+ Spacer(modifier = Modifier.width(EnsuSpacing.md.dp))
+ Column(modifier = Modifier.weight(1f)) {
+ Text(text = "Max output", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+ OutlinedTextField(
+ value = maxTokens,
+ onValueChange = { maxTokens = it },
+ placeholder = { Text(text = "2048") },
+ modifier = Modifier.fillMaxWidth(),
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
+ )
+ }
+ }
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+ Text(text = "Leave blank to use model defaults", style = EnsuTypography.small, color = EnsuColor.textMuted())
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.xl.dp))
+ Divider()
+ Spacer(modifier = Modifier.height(EnsuSpacing.lg.dp))
+
+ Button(
+ onClick = {},
+ modifier = Modifier.fillMaxWidth(),
+ colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.accent())
+ ) {
+ Text(text = "Use Custom Model", style = EnsuTypography.body)
+ }
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
+
+ TextButton(onClick = {}) {
+ Text(text = "Use Default Model", style = EnsuTypography.body, color = EnsuColor.accent())
+ }
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
+ Text(
+ text = "Changes require redownloading the model.",
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted()
+ )
+ }
+}
+
+@Composable
+private fun SectionHeader(title: String) {
+ Text(text = title, style = EnsuTypography.h3Bold)
+}
+
+@Composable
+private fun SuggestedModelCard(title: String, subtitle: String) {
+ Card(modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = EnsuSpacing.xs.dp)
+ ) {
+ Column(modifier = Modifier.padding(EnsuSpacing.md.dp)) {
+ Text(text = title, style = EnsuTypography.body)
+ Text(text = subtitle, style = EnsuTypography.small, color = EnsuColor.textMuted())
+ TextButton(onClick = {}) {
+ Text(text = "Fill", style = EnsuTypography.small, color = EnsuColor.accent())
+ }
+ }
+ }
+}
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
new file mode 100644
index 0000000000..2db10d9bdd
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/DeveloperSettingsScreen.kt
@@ -0,0 +1,107 @@
+package io.ente.ensu.settings
+
+import androidx.compose.foundation.layout.Column
+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.shape.RoundedCornerShape
+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.Modifier
+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 kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.launch
+
+@Composable
+fun DeveloperSettingsScreen(
+ authService: EnsuAuthService,
+ currentEndpointFlow: Flow<String>,
+ onSaved: () -> Unit
+) {
+ val currentEndpoint by currentEndpointFlow.collectAsState(initial = "https://api.ente.io")
+ 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)
+ ) {
+ 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
+ }
+ }
+ }
+}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/LogViewerScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/LogViewerScreen.kt
new file mode 100644
index 0000000000..1f9ddfd7cf
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/LogViewerScreen.kt
@@ -0,0 +1,111 @@
+package io.ente.ensu.settings
+
+import androidx.compose.foundation.layout.Arrangement
+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.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+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.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.unit.dp
+import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.designsystem.EnsuSpacing
+import io.ente.ensu.designsystem.EnsuTypography
+import io.ente.ensu.domain.model.LogEntry
+import io.ente.ensu.domain.model.LogLevel
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+@Composable
+fun LogViewerScreen(logs: List<LogEntry>) {
+ var selectedLog by remember { mutableStateOf<LogEntry?>(null) }
+
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(EnsuSpacing.pageHorizontal.dp)
+ ) {
+ if (logs.isEmpty()) {
+ Text(text = "No logs available", style = EnsuTypography.body, color = EnsuColor.textMuted())
+ } else {
+ LazyColumn(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {
+ items(logs, key = { it.id }) { log ->
+ LogRow(logEntry = log, onOpenDetails = { selectedLog = log })
+ }
+ }
+ }
+ }
+
+ selectedLog?.let { log ->
+ AlertDialog(
+ onDismissRequest = { selectedLog = null },
+ title = { Text(text = "Log details", style = EnsuTypography.h3) },
+ text = {
+ Column {
+ Text(text = log.message, style = EnsuTypography.body)
+ log.details?.let { details ->
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+ Text(text = details, style = EnsuTypography.small, color = EnsuColor.textMuted())
+ }
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = { selectedLog = null }) {
+ Text(text = "Close")
+ }
+ }
+ )
+ }
+}
+
+@Composable
+private fun LogRow(logEntry: LogEntry, onOpenDetails: () -> Unit) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = EnsuSpacing.xs.dp)
+ ) {
+ Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {
+ Text(
+ text = logEntry.level.name,
+ style = EnsuTypography.mini,
+ color = levelColor(logEntry.level)
+ )
+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
+ Text(
+ text = logTimestampFormatter.format(Date(logEntry.timestampMillis)),
+ style = EnsuTypography.mini,
+ color = EnsuColor.textMuted()
+ )
+ }
+ Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+ Text(text = logEntry.message, style = EnsuTypography.body)
+ TextButton(onClick = onOpenDetails) {
+ Text(text = "Details", style = EnsuTypography.small, color = EnsuColor.accent())
+ }
+ }
+}
+
+@Composable
+private fun levelColor(level: LogLevel): Color = when (level) {
+ LogLevel.Info -> EnsuColor.textMuted()
+ LogLevel.Warning -> EnsuColor.accent()
+ LogLevel.Error -> EnsuColor.error
+}
+
+private val logTimestampFormatter = SimpleDateFormat("h:mm:ss a", Locale.getDefault())
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/utils/SystemBars.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/utils/SystemBars.kt
new file mode 100644
index 0000000000..9404873557
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/utils/SystemBars.kt
@@ -0,0 +1,27 @@
+package io.ente.ensu.utils
+
+import android.app.Activity
+import androidx.compose.foundation.isSystemInDarkTheme
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.SideEffect
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.toArgb
+import androidx.compose.ui.platform.LocalView
+import androidx.core.view.WindowInsetsControllerCompat
+
+@Composable
+fun ApplySystemBars(backgroundColor: Color) {
+ val view = LocalView.current
+ val isDark = isSystemInDarkTheme()
+
+ SideEffect {
+ val window = (view.context as Activity).window
+ window.statusBarColor = backgroundColor.toArgb()
+ window.navigationBarColor = backgroundColor.toArgb()
+
+ WindowInsetsControllerCompat(window, view).apply {
+ isAppearanceLightStatusBars = !isDark
+ isAppearanceLightNavigationBars = !isDark
+ }
+ }
+}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/ic_launcher_foreground.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/ic_launcher_foreground.xml
new file mode 100644
index 0000000000..bc97717d15
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/ic_launcher_foreground.xml
@@ -0,0 +1,12 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp"
+ android:height="108dp"
+ android:viewportWidth="108"
+ android:viewportHeight="108">
+ <path
+ android:fillColor="#9A7E0A"
+ android:pathData="M54,10a44,44 0 1,0 0,88a44,44 0 1,0 0,-88z" />
+ <path
+ android:fillColor="#F8F5F0"
+ android:pathData="M38,34h32v8h-22v8h20v8h-20v8h22v8h-32z" />
+</vector>
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/font/cormorant_garamond_variable.ttf b/mobile/native/android/apps/ensu/app-ui/src/main/res/font/cormorant_garamond_variable.ttf
new file mode 100644
index 0000000000..d992a83ce5
Binary files /dev/null and b/mobile/native/android/apps/ensu/app-ui/src/main/res/font/cormorant_garamond_variable.ttf differ
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/font/inter_bold.ttf b/mobile/native/android/apps/ensu/app-ui/src/main/res/font/inter_bold.ttf
new file mode 100644
index 0000000000..7e1deec31e
Binary files /dev/null and b/mobile/native/android/apps/ensu/app-ui/src/main/res/font/inter_bold.ttf differ
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/font/inter_medium.ttf b/mobile/native/android/apps/ensu/app-ui/src/main/res/font/inter_medium.ttf
new file mode 100644
index 0000000000..7e573f6498
Binary files /dev/null and b/mobile/native/android/apps/ensu/app-ui/src/main/res/font/inter_medium.ttf differ
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/font/inter_regular.ttf b/mobile/native/android/apps/ensu/app-ui/src/main/res/font/inter_regular.ttf
new file mode 100644
index 0000000000..012d1b470d
Binary files /dev/null and b/mobile/native/android/apps/ensu/app-ui/src/main/res/font/inter_regular.ttf differ
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/font/inter_semibold.ttf b/mobile/native/android/apps/ensu/app-ui/src/main/res/font/inter_semibold.ttf
new file mode 100644
index 0000000000..4be54399d6
Binary files /dev/null and b/mobile/native/android/apps/ensu/app-ui/src/main/res/font/inter_semibold.ttf differ
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/font/jetbrainsmono_regular.ttf b/mobile/native/android/apps/ensu/app-ui/src/main/res/font/jetbrainsmono_regular.ttf
new file mode 100644
index 0000000000..711830ede0
Binary files /dev/null and b/mobile/native/android/apps/ensu/app-ui/src/main/res/font/jetbrainsmono_regular.ttf differ
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/font/sourceserif4_variable.ttf b/mobile/native/android/apps/ensu/app-ui/src/main/res/font/sourceserif4_variable.ttf
new file mode 100644
index 0000000000..40bbb58cb5
Binary files /dev/null and b/mobile/native/android/apps/ensu/app-ui/src/main/res/font/sourceserif4_variable.ttf differ
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/values-night/themes.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/values-night/themes.xml
new file mode 100644
index 0000000000..6a37d5490a
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/values-night/themes.xml
@@ -0,0 +1,6 @@
+<resources>
+ <style name="Theme.Ensu" parent="Theme.Material3.DayNight.NoActionBar">
+ <item name="android:statusBarColor">@android:color/transparent</item>
+ <item name="android:navigationBarColor">@android:color/transparent</item>
+ </style>
+</resources>
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/values/colors.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/values/colors.xml
new file mode 100644
index 0000000000..37a54cf429
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/values/colors.xml
@@ -0,0 +1,3 @@
+<resources>
+ <color name="ic_launcher_background">#F8F5F0</color>
+</resources>
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/values/strings.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/values/strings.xml
new file mode 100644
index 0000000000..d8e2335350
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/values/strings.xml
@@ -0,0 +1,3 @@
+<resources>
+ <string name="app_name">Ensu</string>
+</resources>
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/values/themes.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/values/themes.xml
new file mode 100644
index 0000000000..6a37d5490a
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/values/themes.xml
@@ -0,0 +1,6 @@
+<resources>
+ <style name="Theme.Ensu" parent="Theme.Material3.DayNight.NoActionBar">
+ <item name="android:statusBarColor">@android:color/transparent</item>
+ <item name="android:navigationBarColor">@android:color/transparent</item>
+ </style>
+</resources>
diff --git a/mobile/native/android/apps/ensu/build.gradle.kts b/mobile/native/android/apps/ensu/build.gradle.kts
new file mode 100644
index 0000000000..3361df3cf5
--- /dev/null
+++ b/mobile/native/android/apps/ensu/build.gradle.kts
@@ -0,0 +1,7 @@
+plugins {
+ id("com.android.application") version "8.3.2" apply false
+ id("com.android.library") version "8.3.2" apply false
+ id("org.jetbrains.kotlin.android") version "1.9.23" apply false
+ id("org.jetbrains.kotlin.jvm") version "1.9.23" apply false
+ id("org.jetbrains.kotlin.plugin.serialization") version "1.9.23" apply 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
new file mode 100644
index 0000000000..47b4ade596
--- /dev/null
+++ b/mobile/native/android/apps/ensu/crypto-auth-core/build.gradle.kts
@@ -0,0 +1,29 @@
+plugins {
+ id("com.android.library")
+ id("org.jetbrains.kotlin.android")
+}
+
+android {
+ namespace = "io.ente.ensu.crypto"
+ compileSdk = 34
+
+ defaultConfig {
+ minSdk = 23
+ }
+
+ sourceSets["main"].jniLibs.srcDir("src/main/jniLibs")
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ kotlinOptions {
+ jvmTarget = "17"
+ }
+}
+
+dependencies {
+ implementation(project(":domain"))
+ implementation("net.java.dev.jna:jna:5.14.0@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
new file mode 100644
index 0000000000..c387a1b4ed
--- /dev/null
+++ b/mobile/native/android/apps/ensu/crypto-auth-core/src/main/java/io/ente/ensu/crypto/EnsuCryptoBridge.kt
@@ -0,0 +1,48 @@
+@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(
+ keyAttributes: KeyAttributes,
+ encryptedToken: String?,
+ plainToken: String?
+ ): AuthSecrets {
+ return io.ente.ensu.crypto.srpDecryptSecrets(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
new file mode 100644
index 0000000000..17b19a6c77
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/build.gradle.kts
@@ -0,0 +1,33 @@
+plugins {
+ id("com.android.library")
+ id("org.jetbrains.kotlin.android")
+ id("org.jetbrains.kotlin.plugin.serialization")
+}
+
+android {
+ namespace = "io.ente.ensu.data"
+ compileSdk = 34
+
+ defaultConfig {
+ minSdk = 23
+ }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ kotlinOptions {
+ jvmTarget = "17"
+ }
+}
+
+dependencies {
+ implementation(project(":domain"))
+ implementation(project(":crypto-auth-core"))
+ implementation("androidx.core:core-ktx:1.12.0")
+ implementation("androidx.datastore:datastore-preferences:1.1.1")
+ implementation("androidx.security:security-crypto:1.1.0-alpha06")
+ implementation("com.squareup.okhttp3:okhttp:4.12.0")
+ implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.3")
+}
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
new file mode 100644
index 0000000000..fa905953d0
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/EndpointPreferencesDataStore.kt
@@ -0,0 +1,28 @@
+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")
+
+ val endpointFlow: Flow<String?> = context.endpointPreferences.data.map { prefs ->
+ prefs[endpointKey]
+ }
+
+ 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/SessionPreferencesDataStore.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesDataStore.kt
new file mode 100644
index 0000000000..a04512e714
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesDataStore.kt
@@ -0,0 +1,36 @@
+package io.ente.ensu.data
+
+import android.content.Context
+import androidx.datastore.core.DataStore
+import androidx.datastore.preferences.core.Preferences
+import androidx.datastore.preferences.core.edit
+import androidx.datastore.preferences.core.stringPreferencesKey
+import androidx.datastore.preferences.preferencesDataStoreFile
+import androidx.datastore.preferences.core.PreferenceDataStoreFactory
+import io.ente.ensu.domain.preferences.SessionPreferences
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.map
+
+class SessionPreferencesDataStore(context: Context) : SessionPreferences {
+ private val dataStore: DataStore<Preferences> = PreferenceDataStoreFactory.create {
+ context.preferencesDataStoreFile("ensu_session_prefs")
+ }
+
+ override val selectedSessionId: Flow<String?> = dataStore.data.map { preferences ->
+ preferences[Keys.SELECTED_SESSION_ID]
+ }
+
+ override suspend fun setSelectedSessionId(sessionId: String?) {
+ dataStore.edit { preferences ->
+ if (sessionId == null) {
+ preferences.remove(Keys.SELECTED_SESSION_ID)
+ } else {
+ preferences[Keys.SELECTED_SESSION_ID] = sessionId
+ }
+ }
+ }
+
+ private object Keys {
+ val SELECTED_SESSION_ID = stringPreferencesKey("selected_session_id")
+ }
+}
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
new file mode 100644
index 0000000000..0f134280f6
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/AuthModels.kt
@@ -0,0 +1,43 @@
+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
new file mode 100644
index 0000000000..a4d0e4f73d
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthService.kt
@@ -0,0 +1,318 @@
+@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",
+ error.message ?: "Unknown 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", normalized)
+ Result.success(normalized)
+ } catch (error: Exception) {
+ logRepository.log(LogLevel.Error, "Endpoint update failed", error.message ?: "Unknown error")
+ Result.failure(error)
+ }
+ }
+
+ suspend fun getSrpAttributes(email: String): SrpAttributes {
+ val response = networkFactory.authentication.getSrpAttributes(email)
+ 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")
+ 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(
+ keyAttributes = keyAttributes.toCrypto(),
+ encryptedToken = payload.encryptedToken,
+ plainToken = payload.token
+ )
+ }
+
+ storeSecrets(email, payload.userId, secrets)
+ logRepository.log(LogLevel.Info, "SRP login success")
+ 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")
+ }
+
+ 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 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()
+
+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
new file mode 100644
index 0000000000..44e8ab5925
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthTokenProvider.kt
@@ -0,0 +1,8 @@
+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/logging/InMemoryLogRepository.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/InMemoryLogRepository.kt
new file mode 100644
index 0000000000..cd03a26514
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/InMemoryLogRepository.kt
@@ -0,0 +1,26 @@
+package io.ente.ensu.data.logging
+
+import io.ente.ensu.domain.logging.LogRepository
+import io.ente.ensu.domain.model.LogEntry
+import io.ente.ensu.domain.model.LogLevel
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import java.util.UUID
+
+class InMemoryLogRepository : LogRepository {
+ private val _logs = MutableStateFlow<List<LogEntry>>(emptyList())
+ override val logs: StateFlow<List<LogEntry>> = _logs.asStateFlow()
+
+ override fun log(level: LogLevel, message: String, details: String?) {
+ val entry = LogEntry(
+ id = UUID.randomUUID().toString(),
+ timestampMillis = System.currentTimeMillis(),
+ level = level,
+ message = message,
+ details = details
+ )
+ _logs.update { listOf(entry) + it }
+ }
+}
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
new file mode 100644
index 0000000000..9881ab6ed4
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/ApiClient.kt
@@ -0,0 +1,32 @@
+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
new file mode 100644
index 0000000000..8632fe00d9
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/ApiDomain.kt
@@ -0,0 +1,9 @@
+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
new file mode 100644
index 0000000000..31405603ca
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/ApiEndpoint.kt
@@ -0,0 +1,51 @@
+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
new file mode 100644
index 0000000000..502b4ae107
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/AuthTokenProvider.kt
@@ -0,0 +1,5 @@
+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
new file mode 100644
index 0000000000..866ed8dd9f
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/AuthenticationGateway.kt
@@ -0,0 +1,91 @@
+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("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
new file mode 100644
index 0000000000..f2d20869d5
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/EndpointResolver.kt
@@ -0,0 +1,20 @@
+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
new file mode 100644
index 0000000000..77fe57503b
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/HttpClient.kt
@@ -0,0 +1,67 @@
+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
new file mode 100644
index 0000000000..b645f1a747
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/HttpMethod.kt
@@ -0,0 +1,9 @@
+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
new file mode 100644
index 0000000000..a0f4c8d98c
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkConfiguration.kt
@@ -0,0 +1,34 @@
+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.io".toHttpUrl(),
+ accountsEndpoint = "https://accounts.ente.io".toHttpUrl(),
+ castEndpoint = "https://api.ente.io".toHttpUrl(),
+ publicAlbumsEndpoint = "https://albums.ente.io".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
new file mode 100644
index 0000000000..1c275cfa04
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkErrors.kt
@@ -0,0 +1,5 @@
+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
new file mode 100644
index 0000000000..8aaf9db76e
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkFactory.kt
@@ -0,0 +1,17 @@
+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
new file mode 100644
index 0000000000..c1bc4a0ffa
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/NetworkResponses.kt
@@ -0,0 +1,13 @@
+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
new file mode 100644
index 0000000000..b0054df311
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/network/RequestHeadersManager.kt
@@ -0,0 +1,27 @@
+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
new file mode 100644
index 0000000000..91d1b98add
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/CredentialStore.kt
@@ -0,0 +1,58 @@
+package io.ente.ensu.data.storage
+
+import android.content.Context
+import android.util.Base64
+import androidx.security.crypto.EncryptedSharedPreferences
+import androidx.security.crypto.MasterKey
+
+class CredentialStore(context: Context) {
+ private val masterKey = MasterKey.Builder(context)
+ .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
+ .build()
+
+ private val prefs = EncryptedSharedPreferences.create(
+ context,
+ "ensu_credentials",
+ masterKey,
+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
+ 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() {
+ prefs.edit().clear().apply()
+ }
+
+ fun getEmail(): String? = prefs.getString(KEY_EMAIL, null)
+
+ fun getToken(): String? = prefs.getString(KEY_TOKEN, null)
+
+ 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)
+ }
+
+ 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"
+ }
+}
diff --git a/mobile/native/android/apps/ensu/domain/build.gradle.kts b/mobile/native/android/apps/ensu/domain/build.gradle.kts
new file mode 100644
index 0000000000..868fecc2f8
--- /dev/null
+++ b/mobile/native/android/apps/ensu/domain/build.gradle.kts
@@ -0,0 +1,11 @@
+plugins {
+ id("org.jetbrains.kotlin.jvm")
+}
+
+kotlin {
+ jvmToolchain(17)
+}
+
+dependencies {
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.0")
+}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/logging/LogRepository.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/logging/LogRepository.kt
new file mode 100644
index 0000000000..eee9b7da9e
--- /dev/null
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/logging/LogRepository.kt
@@ -0,0 +1,18 @@
+package io.ente.ensu.domain.logging
+
+import io.ente.ensu.domain.model.LogEntry
+import io.ente.ensu.domain.model.LogLevel
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+
+interface LogRepository {
+ val logs: StateFlow<List<LogEntry>>
+ fun log(level: LogLevel, message: String, details: String? = null)
+}
+
+object NoOpLogRepository : LogRepository {
+ private val emptyFlow = MutableStateFlow<List<LogEntry>>(emptyList())
+ override val logs: StateFlow<List<LogEntry>> = emptyFlow
+
+ override fun log(level: LogLevel, message: String, details: String?) = Unit
+}
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
new file mode 100644
index 0000000000..62ebfed4f7
--- /dev/null
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/AuthState.kt
@@ -0,0 +1,6 @@
+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/model/ChatModels.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/ChatModels.kt
new file mode 100644
index 0000000000..a297b2cc3d
--- /dev/null
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/ChatModels.kt
@@ -0,0 +1,40 @@
+package io.ente.ensu.domain.model
+
+import java.util.UUID
+
+enum class MessageAuthor {
+ User,
+ Assistant
+}
+
+data class ChatMessage(
+ val id: String = UUID.randomUUID().toString(),
+ val sessionId: String,
+ val author: MessageAuthor,
+ val text: String,
+ val timestampMillis: Long,
+ val attachments: List<Attachment> = emptyList(),
+ val isInterrupted: Boolean = false,
+ val tokensPerSecond: Double? = null,
+ val branchCount: Int = 1
+)
+
+data class ChatSession(
+ val id: String = UUID.randomUUID().toString(),
+ val title: String,
+ val lastMessagePreview: String? = null,
+ val updatedAtMillis: Long
+)
+
+enum class AttachmentType {
+ Image,
+ Document
+}
+
+data class Attachment(
+ val id: String = UUID.randomUUID().toString(),
+ val name: String,
+ val sizeBytes: Long,
+ val type: AttachmentType,
+ val isUploading: Boolean = false
+)
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/LogEntry.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/LogEntry.kt
new file mode 100644
index 0000000000..2af7e959c6
--- /dev/null
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/LogEntry.kt
@@ -0,0 +1,15 @@
+package io.ente.ensu.domain.model
+
+data class LogEntry(
+ val id: String,
+ val timestampMillis: Long,
+ val level: LogLevel,
+ val message: String,
+ val details: String? = null
+)
+
+enum class LogLevel {
+ Info,
+ Warning,
+ Error
+}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/preferences/SessionPreferences.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/preferences/SessionPreferences.kt
new file mode 100644
index 0000000000..9d628e09ac
--- /dev/null
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/preferences/SessionPreferences.kt
@@ -0,0 +1,8 @@
+package io.ente.ensu.domain.preferences
+
+import kotlinx.coroutines.flow.Flow
+
+interface SessionPreferences {
+ val selectedSessionId: Flow<String?>
+ suspend fun setSelectedSessionId(sessionId: String?)
+}
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
new file mode 100644
index 0000000000..33b7af9159
--- /dev/null
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/AppState.kt
@@ -0,0 +1,11 @@
+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/state/ChatState.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ChatState.kt
new file mode 100644
index 0000000000..ec423448fb
--- /dev/null
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ChatState.kt
@@ -0,0 +1,20 @@
+package io.ente.ensu.domain.state
+
+import io.ente.ensu.domain.model.Attachment
+import io.ente.ensu.domain.model.ChatMessage
+import io.ente.ensu.domain.model.ChatSession
+
+
+data class ChatState(
+ val sessions: List<ChatSession> = emptyList(),
+ val currentSessionId: String? = null,
+ val messages: List<ChatMessage> = emptyList(),
+ val streamingResponse: String = "",
+ val isGenerating: Boolean = false,
+ val isDownloading: Boolean = false,
+ val messageText: String = "",
+ val attachments: List<Attachment> = emptyList(),
+ val editingMessageId: String? = null,
+ val branchSelections: Map<String, Int> = emptyMap(),
+ val isProcessingAttachments: Boolean = false
+)
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/DeveloperSettingsState.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/DeveloperSettingsState.kt
new file mode 100644
index 0000000000..5d8a6929fb
--- /dev/null
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/DeveloperSettingsState.kt
@@ -0,0 +1,5 @@
+package io.ente.ensu.domain.state
+
+data class DeveloperSettingsState(
+ val enableDiagnostics: Boolean = false
+)
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ModelSettingsState.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ModelSettingsState.kt
new file mode 100644
index 0000000000..fdbe117fcd
--- /dev/null
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ModelSettingsState.kt
@@ -0,0 +1,10 @@
+package io.ente.ensu.domain.state
+
+data class ModelSettingsState(
+ val useCustomModel: Boolean = false,
+ val modelUrl: String = "",
+ val mmprojUrl: String = "",
+ val contextLength: String = "",
+ val maxTokens: String = "",
+ val isSaving: Boolean = false
+)
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
new file mode 100644
index 0000000000..015aaa13bd
--- /dev/null
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt
@@ -0,0 +1,165 @@
+package io.ente.ensu.domain.store
+
+import io.ente.ensu.domain.logging.LogRepository
+import io.ente.ensu.domain.logging.NoOpLogRepository
+import io.ente.ensu.domain.model.AuthState
+import io.ente.ensu.domain.model.ChatMessage
+import io.ente.ensu.domain.model.ChatSession
+import io.ente.ensu.domain.model.LogLevel
+import io.ente.ensu.domain.model.MessageAuthor
+import io.ente.ensu.domain.preferences.SessionPreferences
+import io.ente.ensu.domain.state.AppState
+import io.ente.ensu.domain.state.ChatState
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+
+class AppStore(
+ private val sessionPreferences: SessionPreferences,
+ private val clock: () -> Long = { System.currentTimeMillis() },
+ private val logRepository: LogRepository = NoOpLogRepository
+) {
+ private val _state = MutableStateFlow(AppState())
+ val state: StateFlow<AppState> = _state.asStateFlow()
+
+ fun bootstrap(scope: CoroutineScope) {
+ logRepository.log(LogLevel.Info, "EnsΕ« started")
+
+ if (_state.value.chat.sessions.isEmpty()) {
+ seedSessions()
+ }
+
+ scope.launch {
+ sessionPreferences.selectedSessionId.collectLatest { storedId ->
+ if (storedId != null) {
+ _state.update { appState ->
+ if (appState.chat.sessions.any { it.id == storedId }) {
+ appState.copy(chat = appState.chat.copy(currentSessionId = storedId))
+ } else {
+ appState
+ }
+ }
+ }
+ }
+ }
+ }
+
+ fun createNewSession(): String {
+ val session = ChatSession(
+ title = "New Chat",
+ updatedAtMillis = clock()
+ )
+ _state.update { appState ->
+ val updatedSessions = listOf(session) + appState.chat.sessions
+ appState.copy(
+ chat = appState.chat.copy(
+ sessions = updatedSessions,
+ currentSessionId = session.id,
+ messageText = "",
+ attachments = emptyList()
+ )
+ )
+ }
+ logRepository.log(LogLevel.Info, "Created new session")
+ return session.id
+ }
+
+ fun selectSession(sessionId: String) {
+ _state.update { appState ->
+ appState.copy(chat = appState.chat.copy(currentSessionId = sessionId))
+ }
+ logRepository.log(LogLevel.Info, "Selected session", sessionId)
+ }
+
+ fun persistSelectedSession(scope: CoroutineScope, sessionId: String?) {
+ scope.launch {
+ sessionPreferences.setSelectedSessionId(sessionId)
+ }
+ }
+
+ fun updateMessageText(value: String) {
+ _state.update { appState ->
+ appState.copy(chat = appState.chat.copy(messageText = value))
+ }
+ }
+
+ fun updateBranchSelection(messageId: String, selectedIndex: Int) {
+ _state.update { appState ->
+ val updatedSelections = appState.chat.branchSelections.toMutableMap()
+ updatedSelections[messageId] = selectedIndex
+ appState.copy(chat = appState.chat.copy(branchSelections = updatedSelections))
+ }
+ }
+
+ fun sendMessage() {
+ val currentState = _state.value
+ val text = currentState.chat.messageText.trim()
+ if (text.isEmpty()) return
+ val sessionId = currentState.chat.currentSessionId ?: return
+ val timestamp = clock()
+
+ val userMessage = ChatMessage(
+ sessionId = sessionId,
+ author = MessageAuthor.User,
+ text = text,
+ timestampMillis = timestamp
+ )
+ val assistantMessage = ChatMessage(
+ sessionId = sessionId,
+ author = MessageAuthor.Assistant,
+ text = "Thinking about: $text",
+ timestampMillis = timestamp + 3000
+ )
+
+ _state.update { appState ->
+ val updatedMessages = appState.chat.messages + userMessage + assistantMessage
+ val updatedSessions = appState.chat.sessions.map { session ->
+ if (session.id == sessionId) {
+ session.copy(
+ lastMessagePreview = text,
+ updatedAtMillis = timestamp
+ )
+ } else {
+ session
+ }
+ }
+ appState.copy(
+ chat = appState.chat.copy(
+ messages = updatedMessages,
+ messageText = "",
+ sessions = updatedSessions
+ )
+ )
+ }
+ logRepository.log(LogLevel.Info, "Sent message", text)
+ }
+
+ fun signIn(email: String) {
+ _state.update { appState ->
+ appState.copy(auth = AuthState(isLoggedIn = true, email = email))
+ }
+ logRepository.log(LogLevel.Info, "Signed in", email)
+ }
+
+ fun signOut() {
+ _state.update { appState ->
+ appState.copy(auth = AuthState())
+ }
+ logRepository.log(LogLevel.Info, "Signed out")
+ }
+
+ private fun seedSessions() {
+ val now = clock()
+ val sessions = listOf(
+ ChatSession(title = "Ensu starter", lastMessagePreview = "Welcome to EnsΕ«", updatedAtMillis = now - 3_600_000),
+ ChatSession(title = "Project notes", lastMessagePreview = "Draft the plan", updatedAtMillis = now - 86_400_000)
+ )
+ _state.update { appState ->
+ appState.copy(chat = appState.chat.copy(sessions = sessions, currentSessionId = sessions.first().id))
+ }
+ }
+}
diff --git a/mobile/native/android/apps/ensu/gradle.properties b/mobile/native/android/apps/ensu/gradle.properties
new file mode 100644
index 0000000000..f97184bebb
--- /dev/null
+++ b/mobile/native/android/apps/ensu/gradle.properties
@@ -0,0 +1,4 @@
+org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8
+android.useAndroidX=true
+kotlin.code.style=official
+android.nonTransitiveRClass=true
diff --git a/mobile/native/android/apps/ensu/gradle/wrapper/gradle-wrapper.jar b/mobile/native/android/apps/ensu/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000000..61285a659d
Binary files /dev/null and b/mobile/native/android/apps/ensu/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/mobile/native/android/apps/ensu/gradle/wrapper/gradle-wrapper.properties b/mobile/native/android/apps/ensu/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000000..3fa8f862f7
--- /dev/null
+++ b/mobile/native/android/apps/ensu/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,7 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/mobile/native/android/apps/ensu/gradlew b/mobile/native/android/apps/ensu/gradlew
new file mode 100755
index 0000000000..adff685a03
--- /dev/null
+++ b/mobile/native/android/apps/ensu/gradlew
@@ -0,0 +1,248 @@
+#!/bin/sh
+
+#
+# Copyright Β© 2015 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions Β«$varΒ», Β«${var}Β», Β«${var:-default}Β», Β«${var+SET}Β»,
+# Β«${var#prefix}Β», Β«${var%suffix}Β», and Β«$( cmd )Β»;
+# * compound commands having a testable exit status, especially Β«caseΒ»;
+# * various built-in commands including Β«commandΒ», Β«setΒ», and Β«ulimitΒ».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/mobile/native/android/apps/ensu/gradlew.bat b/mobile/native/android/apps/ensu/gradlew.bat
new file mode 100644
index 0000000000..e509b2dd8f
--- /dev/null
+++ b/mobile/native/android/apps/ensu/gradlew.bat
@@ -0,0 +1,93 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/mobile/native/android/apps/ensu/settings.gradle.kts b/mobile/native/android/apps/ensu/settings.gradle.kts
new file mode 100644
index 0000000000..c719f77e08
--- /dev/null
+++ b/mobile/native/android/apps/ensu/settings.gradle.kts
@@ -0,0 +1,18 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+rootProject.name = "ensu"
+include(":app-ui", ":domain", ":data", ":crypto-auth-core")
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/CredentialStore.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/CredentialStore.swift
index 42dc48058d..b296fe7fd9 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Services/CredentialStore.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/CredentialStore.swift
@@ -31,11 +31,24 @@ final class CredentialStore {
guard let data = try? KeychainStore.get(service: keychainService, account: KeychainAccount.token) else {
return nil
}
- return String(data: data, encoding: .utf8)
+ 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 hasConfiguredAccount: Bool {
- token?.isEmpty == false && email?.isEmpty == false
+ 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 {
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuAuthService.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuAuthService.swift
index df2b53d536..84c77a2d5a 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuAuthService.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuAuthService.swift
@@ -183,7 +183,7 @@ final class EnsuAuthService {
encryptedToken: String?,
token: String?
) async throws {
- let kek = try await Task.detached(priority: .userInitiated) {
+ var kek = try await Task.detached(priority: .userInitiated) {
try deriveKekForLogin(
password: password,
kekSalt: srpAttributes.kekSalt,
@@ -191,6 +191,10 @@ final class EnsuAuthService {
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(
@@ -207,9 +211,19 @@ final class EnsuAuthService {
// MARK: - Storage
private func storeSecrets(email: String, userId: Int64, secrets: AuthSecrets) throws {
- let masterKey = Data(secrets.masterKey)
- let secretKey = Data(secrets.secretKey)
- let token = Data(secrets.token).base64URLEncodedString()
+ // 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()
try CredentialStore.shared.save(
email: email,
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/KeychainStore.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/KeychainStore.swift
index 704bda23b9..d8deb855e2 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Services/KeychainStore.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/KeychainStore.swift
@@ -30,6 +30,9 @@ final class KeychainStore {
// Insert.
var insertQuery = query
insertQuery[kSecValueData as String] = data
+ #if os(iOS)
+ insertQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
+ #endif
let addStatus = SecItemAdd(insertQuery as CFDictionary, nil)
if addStatus != errSecSuccess {
throw KeychainStoreError.unexpectedStatus(addStatus)
@@ -60,6 +63,19 @@ final class KeychainStore {
return data
}
+ static func exists(service: String, account: String) -> Bool {
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: account,
+ kSecReturnData as String: false,
+ kSecMatchLimit as String: kSecMatchLimitOne,
+ ]
+
+ let status = SecItemCopyMatching(query as CFDictionary, nil)
+ return status == errSecSuccess
+ }
+
static func delete(service: String, account: String) throws {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Utils/Base64URL.swift b/mobile/native/darwin/Apps/ensu/ensu/Utils/Base64URL.swift
index 10fb84ef48..d55109c4f0 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Utils/Base64URL.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Utils/Base64URL.swift
@@ -1,7 +1,7 @@
import Foundation
extension Data {
- /// Encode data as URL-safe base64 (RFC 4648 Β§5), without padding.
+ /// Encode data as URL-safe base64 (RFC 4648 Β§5), **without padding**.
func base64URLEncodedString() -> String {
let b64 = self.base64EncodedString()
return b64
@@ -10,6 +10,18 @@ extension Data {
.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
diff --git a/mobile/native/darwin/Packages/EnteNetwork/Sources/EnteNetwork/Core/APIClient.swift b/mobile/native/darwin/Packages/EnteNetwork/Sources/EnteNetwork/Core/APIClient.swift
index e6d74e10d3..5fee3cc711 100644
--- a/mobile/native/darwin/Packages/EnteNetwork/Sources/EnteNetwork/Core/APIClient.swift
+++ b/mobile/native/darwin/Packages/EnteNetwork/Sources/EnteNetwork/Core/APIClient.swift
@@ -29,7 +29,7 @@ public class APIClient {
let url = endpointResolver.resolveURL(for: endpoint)
let headers = await buildHeaders(for: endpoint)
- logger.debug("Making request to \(url)")
+ logger.debug("Making request to \(url.enteRedactedForLogging)")
return try await httpClient.request(
url: url,
diff --git a/mobile/native/darwin/Packages/EnteNetwork/Sources/EnteNetwork/Core/HTTPClient.swift b/mobile/native/darwin/Packages/EnteNetwork/Sources/EnteNetwork/Core/HTTPClient.swift
index 806b4e8de8..b5dba5d2cd 100644
--- a/mobile/native/darwin/Packages/EnteNetwork/Sources/EnteNetwork/Core/HTTPClient.swift
+++ b/mobile/native/darwin/Packages/EnteNetwork/Sources/EnteNetwork/Core/HTTPClient.swift
@@ -2,6 +2,19 @@ import Foundation
import EnteCore
import Logging
+extension URL {
+ /// A log-safe representation of the URL that strips query parameters.
+ ///
+ /// Query parameters can contain user identifiers (e.g. email) or tokens in some flows.
+ var enteRedactedForLogging: String {
+ guard var components = URLComponents(url: self, resolvingAgainstBaseURL: false) else {
+ return absoluteString
+ }
+ components.query = nil
+ return components.url?.absoluteString ?? absoluteString
+ }
+}
+
// MARK: - HTTP Method
public enum HTTPMethod: String {
@@ -109,7 +122,6 @@ public class HTTPClient {
components.queryItems = queryItems
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
finalURL = components.url!
- print("🌐 Final URL with encoded parameters: \(finalURL)")
}
var request = URLRequest(url: finalURL)
@@ -129,7 +141,7 @@ public class HTTPClient {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters)
}
- logger.debug("Making \(method.rawValue) request to \(finalURL)")
+ logger.debug("Making \(method.rawValue) request to \(finalURL.enteRedactedForLogging)")
let (data, response) = try await session.data(for: request)
@@ -179,7 +191,7 @@ public class HTTPClient {
}
}
- logger.debug("Uploading data to \(url)")
+ logger.debug("Uploading data to \(url.enteRedactedForLogging)")
let (responseData, response) = try await session.data(for: request)
@@ -208,7 +220,7 @@ public class HTTPClient {
}
}
- logger.debug("Downloading from \(url)")
+ logger.debug("Downloading from \(url.enteRedactedForLogging)")
let (data, response) = try await session.data(for: request)
diff --git a/rust/ensu_uniffi/.gitignore b/rust/ensu_uniffi/.gitignore
new file mode 100644
index 0000000000..34c78b3bde
--- /dev/null
+++ b/rust/ensu_uniffi/.gitignore
@@ -0,0 +1,5 @@
+# Rust build artifacts
+/target/
+
+# OS
+.DS_Store
diff --git a/rust/ensu_uniffi/Cargo.lock b/rust/ensu_uniffi/Cargo.lock
new file mode 100644
index 0000000000..f9c1bf1529
--- /dev/null
+++ b/rust/ensu_uniffi/Cargo.lock
@@ -0,0 +1,2469 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aead"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
+dependencies = [
+ "crypto-common",
+ "generic-array",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.100"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
+
+[[package]]
+name = "argon2"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
+dependencies = [
+ "base64ct",
+ "blake2",
+ "cpufeatures",
+ "password-hash",
+]
+
+[[package]]
+name = "arrayref"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
+
+[[package]]
+name = "arrayvec"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+
+[[package]]
+name = "askama"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f75363874b771be265f4ffe307ca705ef6f3baa19011c149da8674a87f1b75c4"
+dependencies = [
+ "askama_derive",
+ "itoa",
+ "percent-encoding",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "askama_derive"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "129397200fe83088e8a68407a8e2b1f826cf0086b21ccdb866a722c8bcd3a94f"
+dependencies = [
+ "askama_parser",
+ "basic-toml",
+ "memchr",
+ "proc-macro2",
+ "quote",
+ "rustc-hash",
+ "serde",
+ "serde_derive",
+ "syn",
+]
+
+[[package]]
+name = "askama_parser"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6ab5630b3d5eaf232620167977f95eb51f3432fc76852328774afbd242d4358"
+dependencies = [
+ "memchr",
+ "serde",
+ "serde_derive",
+ "winnow",
+]
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "autocfg"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
+
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+[[package]]
+name = "base64ct"
+version = "1.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+
+[[package]]
+name = "basic-toml"
+version = "0.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "bitflags"
+version = "2.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"
+
+[[package]]
+name = "blake2"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
+dependencies = [
+ "digest",
+]
+
+[[package]]
+name = "blake2b_simd"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b79834656f71332577234b50bfc009996f7449e0c056884e6a02492ded0ca2f3"
+dependencies = [
+ "arrayref",
+ "arrayvec",
+ "constant_time_eq",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "block-padding"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.19.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510"
+
+[[package]]
+name = "bytes"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3"
+
+[[package]]
+name = "camino"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e629a66d692cb9ff1a1c664e41771b3dcaf961985a9774c0eb0bd1b51cf60a48"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "cargo-platform"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "cargo_metadata"
+version = "0.19.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba"
+dependencies = [
+ "camino",
+ "cargo-platform",
+ "semver",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.17",
+]
+
+[[package]]
+name = "cc"
+version = "1.2.53"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "755d2fce177175ffca841e9a06afdb2c4ab0f593d53b4dee48147dfaade85932"
+dependencies = [
+ "find-msvc-tools",
+ "shlex",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "cfg_aliases"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
+
+[[package]]
+name = "chacha20"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures",
+]
+
+[[package]]
+name = "cipher"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
+dependencies = [
+ "crypto-common",
+ "inout",
+ "zeroize",
+]
+
+[[package]]
+name = "constant_time_eq"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
+
+[[package]]
+name = "core-foundation"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "rand_core 0.6.4",
+ "typenum",
+]
+
+[[package]]
+name = "crypto_secretstream"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a6419214057ad50a13efccb3ad7714b86b848e3a5aa7b6cf5a3ff07edf387eb"
+dependencies = [
+ "aead",
+ "chacha20",
+ "getrandom 0.2.17",
+ "poly1305",
+ "rand_core 0.6.4",
+ "subtle",
+]
+
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "curve25519-dalek-derive",
+ "fiat-crypto",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "curve25519-dalek-derive"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+ "subtle",
+]
+
+[[package]]
+name = "displaydoc"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "encoding_rs"
+version = "0.8.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "ensu_uniffi"
+version = "0.1.0"
+dependencies = [
+ "base64",
+ "ente-core",
+ "once_cell",
+ "thiserror 1.0.69",
+ "uniffi",
+]
+
+[[package]]
+name = "ente-core"
+version = "0.0.1"
+dependencies = [
+ "argon2",
+ "base64",
+ "blake2b_simd",
+ "crypto_secretstream",
+ "getrandom 0.2.17",
+ "hex",
+ "md-5",
+ "rand_core 0.6.4",
+ "reqwest",
+ "salsa20",
+ "serde",
+ "serde_json",
+ "sha2",
+ "srp",
+ "subtle",
+ "thiserror 2.0.17",
+ "x25519-dalek",
+ "xsalsa20poly1305",
+ "zeroize",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
+
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db"
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "fs-err"
+version = "2.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88a41f105fe1d5b6b34b2055e3dc59bb79b46b48b2040b9e6c7b4b5de097aa41"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
+
+[[package]]
+name = "futures-sink"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7"
+
+[[package]]
+name = "futures-task"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"
+
+[[package]]
+name = "futures-util"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "pin-project-lite",
+ "pin-utils",
+ "slab",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "wasi",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "r-efi",
+ "wasip2",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "glob"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
+
+[[package]]
+name = "goblin"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b363a30c165f666402fe6a3024d3bec7ebc898f96a4a23bd1c99f8dbf3f4f47"
+dependencies = [
+ "log",
+ "plain",
+ "scroll",
+]
+
+[[package]]
+name = "h2"
+version = "0.4.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "fnv",
+ "futures-core",
+ "futures-sink",
+ "http",
+ "indexmap",
+ "slab",
+ "tokio",
+ "tokio-util",
+ "tracing",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "hex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+
+[[package]]
+name = "http"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"
+dependencies = [
+ "bytes",
+ "itoa",
+]
+
+[[package]]
+name = "http-body"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
+dependencies = [
+ "bytes",
+ "http",
+]
+
+[[package]]
+name = "http-body-util"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
+[[package]]
+name = "hyper"
+version = "1.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "h2",
+ "http",
+ "http-body",
+ "httparse",
+ "itoa",
+ "pin-project-lite",
+ "pin-utils",
+ "smallvec",
+ "tokio",
+ "want",
+]
+
+[[package]]
+name = "hyper-rustls"
+version = "0.27.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58"
+dependencies = [
+ "http",
+ "hyper",
+ "hyper-util",
+ "rustls",
+ "rustls-native-certs",
+ "rustls-pki-types",
+ "tokio",
+ "tokio-rustls",
+ "tower-service",
+]
+
+[[package]]
+name = "hyper-util"
+version = "0.1.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "727805d60e7938b76b826a6ef209eb70eaa1812794f9424d4a4e2d740662df5f"
+dependencies = [
+ "base64",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "futures-util",
+ "http",
+ "http-body",
+ "hyper",
+ "ipnet",
+ "libc",
+ "percent-encoding",
+ "pin-project-lite",
+ "socket2",
+ "system-configuration",
+ "tokio",
+ "tower-service",
+ "tracing",
+ "windows-registry",
+]
+
+[[package]]
+name = "icu_collections"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43"
+dependencies = [
+ "displaydoc",
+ "potential_utf",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_core"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "tinystr",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599"
+dependencies = [
+ "icu_collections",
+ "icu_normalizer_data",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer_data"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a"
+
+[[package]]
+name = "icu_properties"
+version = "2.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec"
+dependencies = [
+ "icu_collections",
+ "icu_locale_core",
+ "icu_properties_data",
+ "icu_provider",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_properties_data"
+version = "2.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af"
+
+[[package]]
+name = "icu_provider"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614"
+dependencies = [
+ "displaydoc",
+ "icu_locale_core",
+ "writeable",
+ "yoke",
+ "zerofrom",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "idna"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
+dependencies = [
+ "idna_adapter",
+ "smallvec",
+ "utf8_iter",
+]
+
+[[package]]
+name = "idna_adapter"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344"
+dependencies = [
+ "icu_normalizer",
+ "icu_properties",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "inout"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
+dependencies = [
+ "block-padding",
+ "generic-array",
+]
+
+[[package]]
+name = "ipnet"
+version = "2.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
+
+[[package]]
+name = "iri-string"
+version = "0.7.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c91338f0783edbd6195decb37bae672fd3b165faffb89bf7b9e6942f8b1a731a"
+dependencies = [
+ "memchr",
+ "serde",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
+
+[[package]]
+name = "js-sys"
+version = "0.3.85"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c942ebf8e95485ca0d52d97da7c5a2c387d0e7f0ba4c35e93bfcaee045955b3"
+dependencies = [
+ "once_cell",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "lazy_static"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+
+[[package]]
+name = "libc"
+version = "0.2.180"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
+
+[[package]]
+name = "litemap"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77"
+
+[[package]]
+name = "log"
+version = "0.4.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+
+[[package]]
+name = "lru-slab"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
+
+[[package]]
+name = "md-5"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
+dependencies = [
+ "cfg-if",
+ "digest",
+]
+
+[[package]]
+name = "memchr"
+version = "2.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
+
+[[package]]
+name = "mime"
+version = "0.3.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
+
+[[package]]
+name = "minimal-lexical"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+
+[[package]]
+name = "mio"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "nom"
+version = "7.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
+dependencies = [
+ "memchr",
+ "minimal-lexical",
+]
+
+[[package]]
+name = "num-bigint"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-integer"
+version = "0.1.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
+
+[[package]]
+name = "opaque-debug"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+
+[[package]]
+name = "openssl-probe"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f50d9b3dabb09ecd771ad0aa242ca6894994c130308ca3d7684634df8037391"
+
+[[package]]
+name = "password-hash"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
+dependencies = [
+ "base64ct",
+ "rand_core 0.6.4",
+ "subtle",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
+
+[[package]]
+name = "pin-utils"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+
+[[package]]
+name = "plain"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
+
+[[package]]
+name = "poly1305"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
+dependencies = [
+ "cpufeatures",
+ "opaque-debug",
+ "universal-hash",
+]
+
+[[package]]
+name = "potential_utf"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77"
+dependencies = [
+ "zerovec",
+]
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.105"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "535d180e0ecab6268a3e718bb9fd44db66bbbc256257165fc699dadf70d16fe7"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quinn"
+version = "0.11.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"
+dependencies = [
+ "bytes",
+ "cfg_aliases",
+ "pin-project-lite",
+ "quinn-proto",
+ "quinn-udp",
+ "rustc-hash",
+ "rustls",
+ "socket2",
+ "thiserror 2.0.17",
+ "tokio",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-proto"
+version = "0.11.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31"
+dependencies = [
+ "bytes",
+ "getrandom 0.3.4",
+ "lru-slab",
+ "rand",
+ "ring",
+ "rustc-hash",
+ "rustls",
+ "rustls-pki-types",
+ "slab",
+ "thiserror 2.0.17",
+ "tinyvec",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-udp"
+version = "0.5.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
+dependencies = [
+ "cfg_aliases",
+ "libc",
+ "once_cell",
+ "socket2",
+ "tracing",
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.43"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc74d9a594b72ae6656596548f56f667211f8a97b3d4c3d467150794690dc40a"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "rand"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
+dependencies = [
+ "rand_chacha",
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom 0.2.17",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
+dependencies = [
+ "getrandom 0.3.4",
+]
+
+[[package]]
+name = "reqwest"
+version = "0.12.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
+dependencies = [
+ "base64",
+ "bytes",
+ "encoding_rs",
+ "futures-core",
+ "h2",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-rustls",
+ "hyper-util",
+ "js-sys",
+ "log",
+ "mime",
+ "percent-encoding",
+ "pin-project-lite",
+ "quinn",
+ "rustls",
+ "rustls-native-certs",
+ "rustls-pki-types",
+ "serde",
+ "serde_json",
+ "serde_urlencoded",
+ "sync_wrapper",
+ "tokio",
+ "tokio-rustls",
+ "tower",
+ "tower-http",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
+[[package]]
+name = "ring"
+version = "0.17.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "getrandom 0.2.17",
+ "libc",
+ "untrusted",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustix"
+version = "1.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls"
+version = "0.23.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b"
+dependencies = [
+ "once_cell",
+ "ring",
+ "rustls-pki-types",
+ "rustls-webpki",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-native-certs"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63"
+dependencies = [
+ "openssl-probe",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework",
+]
+
+[[package]]
+name = "rustls-pki-types"
+version = "1.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
+dependencies = [
+ "web-time",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-webpki"
+version = "0.103.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
+
+[[package]]
+name = "ryu"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a50f4cf475b65d88e057964e0e9bb1f0aa9bbb2036dc65c64596b42932536984"
+
+[[package]]
+name = "salsa20"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213"
+dependencies = [
+ "cipher",
+]
+
+[[package]]
+name = "schannel"
+version = "0.1.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "891d81b926048e76efe18581bf793546b4c0eaf8448d72be8de2bbee5fd166e1"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "scroll"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ab8598aa408498679922eff7fa985c25d58a90771bd6be794434c5277eab1a6"
+dependencies = [
+ "scroll_derive",
+]
+
+[[package]]
+name = "scroll_derive"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1783eabc414609e28a5ba76aee5ddd52199f7107a0b24c2e9746a1ecc34a683d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "security-framework"
+version = "3.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b3297343eaf830f66ede390ea39da1d462b6b0c1b000f420d0a83f898bbbe6ef"
+dependencies = [
+ "bitflags",
+ "core-foundation 0.10.1",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc1f0cbffaac4852523ce30d8bd3c5cdc873501d96ff467ca09b6767bb8cd5c0"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "semver"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
+dependencies = [
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.149"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8bbf91e5a4d6315eee45e704372590b30e260ee83af6639d64557f51b067776"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "serde_urlencoded"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
+dependencies = [
+ "form_urlencoded",
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "shlex"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+
+[[package]]
+name = "siphasher"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d"
+
+[[package]]
+name = "slab"
+version = "0.4.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589"
+
+[[package]]
+name = "smallvec"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
+
+[[package]]
+name = "smawk"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7c388c1b5e93756d0c740965c41e8822f866621d41acbdf6336a6a168f8840c"
+
+[[package]]
+name = "socket2"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881"
+dependencies = [
+ "libc",
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "srp"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cdd40049b29ab1315ccba7ffcf1eece8162982eab14edfac3cf2c2ffab18193"
+dependencies = [
+ "digest",
+ "generic-array",
+ "lazy_static",
+ "num-bigint",
+ "subtle",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
+[[package]]
+name = "syn"
+version = "2.0.114"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "sync_wrapper"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "synstructure"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "system-configuration"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b"
+dependencies = [
+ "bitflags",
+ "core-foundation 0.9.4",
+ "system-configuration-sys",
+]
+
+[[package]]
+name = "system-configuration-sys"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.24.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "655da9c7eb6305c55742045d5a8d2037996d61d8de95806335c7c86ce0f82e9c"
+dependencies = [
+ "fastrand",
+ "getrandom 0.3.4",
+ "once_cell",
+ "rustix",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "textwrap"
+version = "0.16.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057"
+dependencies = [
+ "smawk",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
+dependencies = [
+ "thiserror-impl 1.0.69",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8"
+dependencies = [
+ "thiserror-impl 2.0.17",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tinystr"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869"
+dependencies = [
+ "displaydoc",
+ "zerovec",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa"
+dependencies = [
+ "tinyvec_macros",
+]
+
+[[package]]
+name = "tinyvec_macros"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
+
+[[package]]
+name = "tokio"
+version = "1.49.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86"
+dependencies = [
+ "bytes",
+ "libc",
+ "mio",
+ "pin-project-lite",
+ "socket2",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "tokio-rustls"
+version = "0.26.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"
+dependencies = [
+ "rustls",
+ "tokio",
+]
+
+[[package]]
+name = "tokio-util"
+version = "0.7.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "futures-sink",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "toml"
+version = "0.9.11+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3afc9a848309fe1aaffaed6e1546a7a14de1f935dc9d89d32afd9a44bab7c46"
+dependencies = [
+ "indexmap",
+ "serde_core",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_parser",
+ "toml_writer",
+ "winnow",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "0.7.5+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "toml_parser"
+version = "1.0.6+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a3198b4b0a8e11f09dd03e133c0280504d0801269e9afa46362ffde1cbeebf44"
+dependencies = [
+ "winnow",
+]
+
+[[package]]
+name = "toml_writer"
+version = "1.0.6+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607"
+
+[[package]]
+name = "tower"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
+dependencies = [
+ "futures-core",
+ "futures-util",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tokio",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "tower-http"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"
+dependencies = [
+ "bitflags",
+ "bytes",
+ "futures-util",
+ "http",
+ "http-body",
+ "iri-string",
+ "pin-project-lite",
+ "tower",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "tower-layer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
+
+[[package]]
+name = "tower-service"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
+
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "pin-project-lite",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+dependencies = [
+ "once_cell",
+]
+
+[[package]]
+name = "try-lock"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+
+[[package]]
+name = "typenum"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"
+
+[[package]]
+name = "uniffi"
+version = "0.31.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8c6dec3fc6645f71a16a3fa9ff57991028153bd194ca97f4b55e610c73ce66a"
+dependencies = [
+ "anyhow",
+ "cargo_metadata",
+ "uniffi_bindgen",
+ "uniffi_build",
+ "uniffi_core",
+ "uniffi_macros",
+ "uniffi_pipeline",
+]
+
+[[package]]
+name = "uniffi_bindgen"
+version = "0.31.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ed0150801958d4825da56a41c71f000a457ac3a4613fa9647df78ac4b6b6881"
+dependencies = [
+ "anyhow",
+ "askama",
+ "camino",
+ "cargo_metadata",
+ "fs-err",
+ "glob",
+ "goblin",
+ "heck",
+ "indexmap",
+ "once_cell",
+ "serde",
+ "tempfile",
+ "textwrap",
+ "toml",
+ "uniffi_internal_macros",
+ "uniffi_meta",
+ "uniffi_pipeline",
+ "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"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b0ef62e69762fbb9386dcb6c87cd3dd05d525fa8a3a579a290892e60ddbda47e"
+dependencies = [
+ "anyhow",
+ "bytes",
+ "once_cell",
+ "static_assertions",
+]
+
+[[package]]
+name = "uniffi_internal_macros"
+version = "0.31.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "98f51ebca0d9a4b2aa6c644d5ede45c56f73906b96403c08a1985e75ccb64a01"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "uniffi_macros"
+version = "0.31.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db9d12529f1223d014fd501e5f29ca0884d15d6ed5ddddd9f506e55350327dc3"
+dependencies = [
+ "camino",
+ "fs-err",
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "serde",
+ "syn",
+ "toml",
+ "uniffi_meta",
+]
+
+[[package]]
+name = "uniffi_meta"
+version = "0.31.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9df6d413db2827c68588f8149d30d49b71d540d46539e435b23a7f7dbd4d4f86"
+dependencies = [
+ "anyhow",
+ "siphasher",
+ "uniffi_internal_macros",
+ "uniffi_pipeline",
+]
+
+[[package]]
+name = "uniffi_pipeline"
+version = "0.31.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a806dddc8208f22efd7e95a5cdf88ed43d0f3271e8f63b47e757a8bbdb43b63a"
+dependencies = [
+ "anyhow",
+ "heck",
+ "indexmap",
+ "tempfile",
+ "uniffi_internal_macros",
+]
+
+[[package]]
+name = "uniffi_udl"
+version = "0.31.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d1a7339539bf6f6fa3e9b534dece13f778bda2d54b1a6d4e40b4d6090ac26e7"
+dependencies = [
+ "anyhow",
+ "textwrap",
+ "uniffi_meta",
+ "weedle2",
+]
+
+[[package]]
+name = "universal-hash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
+dependencies = [
+ "crypto-common",
+ "subtle",
+]
+
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
+[[package]]
+name = "url"
+version = "2.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
+]
+
+[[package]]
+name = "utf8_iter"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "want"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
+dependencies = [
+ "try-lock",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasip2"
+version = "1.0.2+wasi-0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"
+dependencies = [
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.108"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64024a30ec1e37399cf85a7ffefebdb72205ca1c972291c51512360d90bd8566"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.58"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70a6e77fd0ae8029c9ea0063f87c46fde723e7d887703d74ad2616d792e51e6f"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "js-sys",
+ "once_cell",
+ "wasm-bindgen",
+ "web-sys",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.108"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "008b239d9c740232e71bd39e8ef6429d27097518b6b30bdf9086833bd5b6d608"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.108"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5256bae2d58f54820e6490f9839c49780dff84c65aeab9e772f15d5f0e913a55"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.108"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f01b580c9ac74c8d8f0c0e4afb04eeef2acf145458e52c03845ee9cd23e3d12"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.85"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "312e32e551d92129218ea9a2452120f4aabc03529ef03e4d0d82fb2780608598"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "weedle2"
+version = "5.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "998d2c24ec099a87daf9467808859f9d82b61f1d9c9701251aea037f514eae0e"
+dependencies = [
+ "nom",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-registry"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
+dependencies = [
+ "windows-link",
+ "windows-result",
+ "windows-strings",
+]
+
+[[package]]
+name = "windows-result"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-strings"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
+dependencies = [
+ "windows-targets 0.53.5",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm 0.52.6",
+ "windows_aarch64_msvc 0.52.6",
+ "windows_i686_gnu 0.52.6",
+ "windows_i686_gnullvm 0.52.6",
+ "windows_i686_msvc 0.52.6",
+ "windows_x86_64_gnu 0.52.6",
+ "windows_x86_64_gnullvm 0.52.6",
+ "windows_x86_64_msvc 0.52.6",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.53.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
+dependencies = [
+ "windows-link",
+ "windows_aarch64_gnullvm 0.53.1",
+ "windows_aarch64_msvc 0.53.1",
+ "windows_i686_gnu 0.53.1",
+ "windows_i686_gnullvm 0.53.1",
+ "windows_i686_msvc 0.53.1",
+ "windows_x86_64_gnu 0.53.1",
+ "windows_x86_64_gnullvm 0.53.1",
+ "windows_x86_64_msvc 0.53.1",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
+
+[[package]]
+name = "winnow"
+version = "0.7.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+
+[[package]]
+name = "writeable"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9"
+
+[[package]]
+name = "x25519-dalek"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
+dependencies = [
+ "curve25519-dalek",
+ "rand_core 0.6.4",
+ "serde",
+ "zeroize",
+]
+
+[[package]]
+name = "xsalsa20poly1305"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02a6dad357567f81cd78ee75f7c61f1b30bb2fe4390be8fb7c69e2ac8dffb6c7"
+dependencies = [
+ "aead",
+ "poly1305",
+ "salsa20",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "yoke"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954"
+dependencies = [
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.8.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "668f5168d10b9ee831de31933dc111a459c97ec93225beb307aed970d1372dfd"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c7962b26b0a8685668b671ee4b54d007a67d4eaf05fda79ac0ecf41e32270f1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zerofrom"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
+dependencies = [
+ "zeroize_derive",
+]
+
+[[package]]
+name = "zeroize_derive"
+version = "1.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zerotrie"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851"
+dependencies = [
+ "displaydoc",
+ "yoke",
+ "zerofrom",
+]
+
+[[package]]
+name = "zerovec"
+version = "0.11.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002"
+dependencies = [
+ "yoke",
+ "zerofrom",
+ "zerovec-derive",
+]
+
+[[package]]
+name = "zerovec-derive"
+version = "0.11.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94f63c051f4fe3c1509da62131a678643c5b6fbdc9273b2b79d4378ebda003d2"
diff --git a/rust/ensu_uniffi/Cargo.toml b/rust/ensu_uniffi/Cargo.toml
new file mode 100644
index 0000000000..c48838f749
--- /dev/null
+++ b/rust/ensu_uniffi/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "ensu_uniffi"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+name = "ensu_uniffi"
+crate-type = ["cdylib", "staticlib"]
+
+[dependencies]
+base64 = "0.22"
+once_cell = "1.19"
+thiserror = "1.0"
+uniffi = "0.31.0"
+ente-core = { path = "../core", features = ["srp"] }
+
+[build-dependencies]
+uniffi = { version = "0.31.0", features = ["build"] }
diff --git a/rust/ensu_uniffi/build.rs b/rust/ensu_uniffi/build.rs
new file mode 100644
index 0000000000..7fdeb625f3
--- /dev/null
+++ b/rust/ensu_uniffi/build.rs
@@ -0,0 +1,3 @@
+fn main() {
+ uniffi::generate_scaffolding("./src/ensu_uniffi.udl").unwrap();
+}
diff --git a/rust/ensu_uniffi/src/ensu_uniffi.udl b/rust/ensu_uniffi/src/ensu_uniffi.udl
new file mode 100644
index 0000000000..fd3ad7c86a
--- /dev/null
+++ b/rust/ensu_uniffi/src/ensu_uniffi.udl
@@ -0,0 +1,60 @@
+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 message);
+};
+
+namespace ensu_uniffi {
+ [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(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/ensu_uniffi/src/lib.rs b/rust/ensu_uniffi/src/lib.rs
new file mode 100644
index 0000000000..24fe6fdc28
--- /dev/null
+++ b/rust/ensu_uniffi/src/lib.rs
@@ -0,0 +1,271 @@
+use base64::{
+ engine::general_purpose::{STANDARD as BASE64_STANDARD, URL_SAFE as BASE64_URL_SAFE},
+ Engine,
+};
+use once_cell::sync::Lazy;
+use std::sync::{Mutex, MutexGuard};
+
+use ente_core::{auth, crypto};
+
+uniffi::include_scaffolding!("ensu_uniffi");
+
+#[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("{message}")]
+ Message { message: String },
+}
+
+impl From<auth::AuthError> for EnsuError {
+ fn from(err: auth::AuthError) -> Self {
+ EnsuError::Message {
+ message: 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 {
+ message: "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,
+ secret_key: result.secret_key,
+ token: result.token,
+ }
+}
+
+fn secrets_from_decrypted(result: auth::DecryptedSecrets) -> AuthSecrets {
+ AuthSecrets {
+ master_key: result.master_key,
+ secret_key: result.secret_key,
+ token: result.token,
+ }
+}
+
+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 {
+ message: format!("token: {}", e),
+ })
+}
+
+pub fn init_crypto() -> Result<(), EnsuError> {
+ crypto::init().map_err(|e| EnsuError::Message {
+ message: e.to_string(),
+ })
+}
+
+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 {
+ message: 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 {
+ message:
+ "SRP session already initialized. Call srp_clear() before starting a new session"
+ .to_string(),
+ });
+ }
+
+ *guard = Some(SrpState {
+ session,
+ kek: crypto::SecretVec::new(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 {
+ message: "SRP session not initialized".to_string(),
+ })?;
+
+ let srp_b_bytes = crypto::decode_b64(&srp_b).map_err(|e| EnsuError::Message {
+ message: 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(
+ key_attrs: KeyAttributes,
+ encrypted_token: Option<String>,
+ plain_token: Option<String>,
+) -> Result<AuthSecrets, EnsuError> {
+ // Consume the SRP state so KEK doesn't linger in memory if the caller forgets srp_clear().
+ let state = {
+ let mut guard = lock_srp_state()?;
+ guard.take().ok_or_else(|| EnsuError::Message {
+ message: "SRP session not initialized".to_string(),
+ })?
+ };
+
+ 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,
+ secret_key,
+ token: token_bytes,
+ });
+ }
+
+ Err(EnsuError::Message {
+ message: "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)
+}
+
+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,
+ secret_key,
+ token: token_bytes,
+ });
+ }
+
+ Err(EnsuError::Message {
+ message: "Missing auth token".to_string(),
+ })
+}
diff --git a/rust/ensu_uniffi/uniffi.toml b/rust/ensu_uniffi/uniffi.toml
new file mode 100644
index 0000000000..f8dded3b17
--- /dev/null
+++ b/rust/ensu_uniffi/uniffi.toml
@@ -0,0 +1,2 @@
+[bindings.kotlin]
+package_name = "io.ente.ensu.crypto"