Modern Apps git

← Modern-Apps.git

email: switch gmail from oauth to app passwords

Commit
81e0f9658086f02f2c9769b7af14a06d471e143c
Author
Vayun Mathur <[email protected]>
When
2026-05-30 16:42 UTC (6 months ago)
Parents
88e90e6

Diff

email/src/main/AndroidManifest.xml
diff --git a/email/src/main/AndroidManifest.xml b/email/src/main/AndroidManifest.xmlindex fd9f6933aa..ada2aab0e9 100644--- a/email/src/main/AndroidManifest.xml+++ b/email/src/main/AndroidManifest.xml@@ -23,12 +23,6 @@                 <action android:name="android.intent.action.MAIN" />                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>-            <intent-filter>-                <action android:name="android.intent.action.VIEW" />-                <category android:name="android.intent.category.DEFAULT" />-                <category android:name="android.intent.category.BROWSABLE" />-                <data android:scheme="com.googleusercontent.apps.827025129169-kgv8s8dvhd7req7ao2ila1j169r068pp" />-            </intent-filter>              <intent-filter>                 <action android:name="android.intent.action.SEND" />
email/src/main/java/com/vayunmathur/email/EmailManager.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailManager.kt b/email/src/main/java/com/vayunmathur/email/EmailManager.ktindex 9f50e324a6..dbde0dc8d5 100644--- a/email/src/main/java/com/vayunmathur/email/EmailManager.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailManager.kt@@ -32,27 +32,21 @@ fun EmailAccount.imapServer(): ServerConfig = ServerConfig(imapHost, imapPort, i fun EmailAccount.smtpServer(): ServerConfig = ServerConfig(smtpHost, smtpPort, smtpUseSsl)  /**- * Decrypt the stored credentials and produce an [EmailManager.AuthType]- * appropriate for this account — OAuth bearer token for Gmail, app password- * for everything else.+ * Decrypt the stored credentials and produce an [EmailManager.AuthType] —+ * always app-password (the only auth scheme this app supports).  */ fun EmailAccount.authType(): EmailManager.AuthType {-    return if (authType == "oauth2") {-        EmailManager.AuthType.OAuth2(accessToken)-    } else {-        val cipher = passwordEncrypted-            ?: error("Password account ${email} is missing passwordEncrypted")-        val iv = passwordIv-            ?: error("Password account ${email} is missing passwordIv")-        EmailManager.AuthType.Password(CredentialCrypto.decrypt(cipher, iv))-    }+    val cipher = passwordEncrypted+        ?: error("Account ${email} is missing passwordEncrypted")+    val iv = passwordIv+        ?: error("Account ${email} is missing passwordIv")+    return EmailManager.AuthType.Password(CredentialCrypto.decrypt(cipher, iv)) }  class EmailManager {      sealed class AuthType {         data class Password(val value: String) : AuthType()-        data class OAuth2(val accessToken: String) : AuthType()     }      private fun getImapSession(auth: AuthType, server: ServerConfig): Session {@@ -64,9 +58,6 @@ class EmailManager {             properties["mail.imaps.ssl.enable"] = "true"             properties["mail.imaps.fetchsize"] = "1048576"             properties["mail.imaps.partialfetch"] = "true"-            if (auth is AuthType.OAuth2) {-                properties["mail.imaps.auth.mechanisms"] = "XOAUTH2"-            }         } else {             properties["mail.store.protocol"] = "imap"             properties["mail.imap.host"] = server.host@@ -75,9 +66,6 @@ class EmailManager {             properties["mail.imap.starttls.required"] = "true"             properties["mail.imap.fetchsize"] = "1048576"             properties["mail.imap.partialfetch"] = "true"-            if (auth is AuthType.OAuth2) {-                properties["mail.imap.auth.mechanisms"] = "XOAUTH2"-            }         }         return Session.getInstance(properties).also { registerProviders(it) }     }@@ -90,9 +78,6 @@ class EmailManager {             properties["mail.smtps.port"] = server.port.toString()             properties["mail.smtps.ssl.enable"] = "true"             properties["mail.smtps.auth"] = "true"-            if (auth is AuthType.OAuth2) {-                properties["mail.smtps.auth.mechanisms"] = "XOAUTH2"-            }         } else {             properties["mail.transport.protocol"] = "smtp"             properties["mail.smtp.host"] = server.host@@ -100,9 +85,6 @@ class EmailManager {             properties["mail.smtp.starttls.enable"] = "true"             properties["mail.smtp.starttls.required"] = "true"             properties["mail.smtp.auth"] = "true"-            if (auth is AuthType.OAuth2) {-                properties["mail.smtp.auth.mechanisms"] = "XOAUTH2"-            }         }         return Session.getInstance(properties).also { registerProviders(it) }     }@@ -133,10 +115,7 @@ class EmailManager {         val session = getImapSession(auth, server)         val store = session.getStore(server.imapProtocol)         try {-            val credential = when (auth) {-                is AuthType.Password -> auth.value-                is AuthType.OAuth2 -> auth.accessToken-            }+            val credential = (auth as AuthType.Password).value             store.connect(server.host, server.port, user, credential)             block(store)         } finally {@@ -474,10 +453,7 @@ class EmailManager {          val transport = session.getTransport(server.smtpProtocol)         try {-            val credential = when (auth) {-                is AuthType.Password -> auth.value-                is AuthType.OAuth2 -> auth.accessToken-            }+            val credential = (auth as AuthType.Password).value             transport.connect(server.host, server.port, user, credential)             transport.sendMessage(message, message.allRecipients)         } finally {
email/src/main/java/com/vayunmathur/email/EmailModels.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailModels.kt b/email/src/main/java/com/vayunmathur/email/EmailModels.ktindex a5ea01e8d4..20f4b5011d 100644--- a/email/src/main/java/com/vayunmathur/email/EmailModels.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailModels.kt@@ -58,14 +58,18 @@ data class Attachment( @Entity data class EmailAccount(     @PrimaryKey val email: String,-    val accessToken: String,+    /**+     * Legacy OAuth-token columns. Kept in the schema so old DB rows still+     * load, but no longer written: every account now uses an app password.+     */+    val accessToken: String = "",     val refreshToken: String? = null,     val expiresAt: Long = 0,     /**      * Preset identifier — `gmail`, `outlook`, `yahoo`, `icloud`, `fastmail`, or-     * `custom`. Used to (a) skip Gmail-only behaviour (virtual folder filtering,-     * OAuth token refresh) for non-Gmail accounts, and (b) display the provider-     * name in account-picker UIs.+     * `custom`. Used to (a) skip Gmail-only behaviour (virtual folder filtering)+     * for non-Gmail accounts, and (b) display the provider name in+     * account-picker UIs.      *      * `@ColumnInfo(defaultValue = ...)` is required so the schema generated      * from this entity matches `MIGRATION_6_7`, which `ALTER TABLE`s these@@ -89,10 +93,14 @@ data class EmailAccount(     val smtpPort: Int = 465,     @ColumnInfo(defaultValue = "1")     val smtpUseSsl: Boolean = true,-    /** `oauth2` (Google) or `password` (app passwords / IMAP+SMTP). */+    /**+     * Auth scheme. Only `password` is supported now; the column is preserved+     * with its original default for legacy DB compatibility, but every newly+     * added account stores credentials as an encrypted app password.+     */     @ColumnInfo(defaultValue = "oauth2")-    val authType: String = "oauth2",-    /** AES-256-GCM ciphertext of the app password — null for OAuth2 accounts. */+    val authType: String = "password",+    /** AES-256-GCM ciphertext of the app password. */     val passwordEncrypted: ByteArray? = null,     /** GCM IV used to decrypt [passwordEncrypted]. */     val passwordIv: ByteArray? = null,
email/src/main/java/com/vayunmathur/email/EmailViewModel.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt b/email/src/main/java/com/vayunmathur/email/EmailViewModel.ktindex f59470bd10..136bcae31e 100644--- a/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt@@ -9,7 +9,6 @@ import com.vayunmathur.email.data.EmailSyncState import com.vayunmathur.email.data.EmailSyncWorker import com.vayunmathur.email.data.OutboxManager import com.vayunmathur.email.data.OutboxSendWorker-import com.vayunmathur.email.data.TokenRefresher import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch@@ -191,18 +190,7 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) {             }              try {-                try {-                    attemptSend(account)-                } catch (e: javax.mail.AuthenticationFailedException) {-                    // For OAuth2 accounts the token might just be expired —-                    // refresh + retry once. Password accounts can't be-                    // auto-fixed, so just let the error fall through to the-                    // outbox-save path.-                    if (account.authType != "oauth2") throw e-                    val refreshed = TokenRefresher.refresh(getApplication(), account)-                        ?: throw e-                    attemptSend(refreshed)-                }+                attemptSend(account)                 onSuccess()             } catch (e: Exception) {                 val msg = e.message ?: e::class.simpleName ?: "Unknown error"@@ -252,13 +240,7 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) {                 )             }             try {-                val (body, isHtml, attachments) = try {-                    attempt(account)-                } catch (e: javax.mail.AuthenticationFailedException) {-                    if (account.authType != "oauth2") throw e-                    val refreshed = TokenRefresher.refresh(getApplication(), account) ?: throw e-                    attempt(refreshed)-                }+                val (body, isHtml, attachments) = attempt(account)                 if (body != null || attachments.isNotEmpty()) {                     dao.insertMessages(listOf(message.copy(body = body, isHtml = isHtml, hasAttachments = attachments.isNotEmpty())))                     if (attachments.isNotEmpty()) dao.insertAttachments(attachments)
email/src/main/java/com/vayunmathur/email/MainActivity.kt
diff --git a/email/src/main/java/com/vayunmathur/email/MainActivity.kt b/email/src/main/java/com/vayunmathur/email/MainActivity.ktindex 04803a3925..688bc88a35 100644--- a/email/src/main/java/com/vayunmathur/email/MainActivity.kt+++ b/email/src/main/java/com/vayunmathur/email/MainActivity.kt@@ -3,7 +3,6 @@ package com.vayunmathur.email import android.content.Intent import android.net.Uri import android.os.Bundle-import android.util.Base64 import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent@@ -32,29 +31,12 @@ import com.vayunmathur.email.data.EmailDatabase import com.vayunmathur.email.data.EmailSyncWorker import com.vayunmathur.library.ui.* import com.vayunmathur.library.util.*-import io.ktor.client.*-import io.ktor.client.call.*-import io.ktor.client.engine.cio.*-import io.ktor.client.plugins.contentnegotiation.*-import io.ktor.client.request.*-import io.ktor.client.request.forms.*-import io.ktor.client.statement.bodyAsText-import io.ktor.http.*-import io.ktor.serialization.kotlinx.json.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.serialization.Serializable-import kotlinx.serialization.json.Json-import java.security.MessageDigest-import java.security.SecureRandom  class MainActivity : ComponentActivity() {-    private val scope = CoroutineScope(Dispatchers.Main)--    private val clientId = "827025129169-kgv8s8dvhd7req7ao2ila1j169r068pp.apps.googleusercontent.com"-    private val redirectUri = "com.googleusercontent.apps.827025129169-kgv8s8dvhd7req7ao2ila1j169r068pp:/oauth2redirect"      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)@@ -79,39 +61,11 @@ class MainActivity : ComponentActivity() {         setContent {             val viewModel: EmailViewModel = viewModel()             DynamicTheme {-                MainContent(-                    viewModel = viewModel,-                    onLaunchGoogleSignIn = { startGoogleLogin() }-                )+                MainContent(viewModel = viewModel)             }         }     } -    /**-     * Public so the Compose [com.vayunmathur.email.ui.AddAccountScreen] can-     * trigger the Chrome-Custom-Tabs OAuth flow without owning the redirect-     * URI / PKCE state itself.-     */-    fun startGoogleLogin() {-        val verifier = generateCodeVerifier()-        TokenState.codeVerifier = verifier-        val challenge = generateCodeChallenge(verifier)--        val authUri = Uri.parse("https://accounts.google.com/o/oauth2/v2/auth")-            .buildUpon()-            .appendQueryParameter("client_id", clientId)-            .appendQueryParameter("redirect_uri", redirectUri)-            .appendQueryParameter("response_type", "code")-            .appendQueryParameter("scope", "https://mail.google.com/ email profile")-            .appendQueryParameter("code_challenge", challenge)-            .appendQueryParameter("code_challenge_method", "S256")-            .appendQueryParameter("access_type", "offline")-            .appendQueryParameter("prompt", "select_account")-            .build()--        startActivity(Intent(Intent.ACTION_VIEW, authUri))-    }-     override fun onStart() {         super.onStart()         com.vayunmathur.email.util.AppLifecycleTracker.isAppInForeground = true@@ -129,8 +83,7 @@ class MainActivity : ComponentActivity() {      private fun handleIntent(intent: Intent?) {         val data = intent?.data-        val expectedScheme = "com.googleusercontent.apps.827025129169-kgv8s8dvhd7req7ao2ila1j169r068pp"-        +         val accountEmail = intent?.getStringExtra("accountEmail")         val threadId = intent?.getStringExtra("threadId")         if (accountEmail != null && threadId != null) {@@ -139,153 +92,32 @@ class MainActivity : ComponentActivity() {             IntentState.navigationRoute = Route.Composer()         } -        if (data != null && data.scheme == expectedScheme && data.path == "/oauth2redirect") {-            val code = data.getQueryParameter("code")-            if (code != null) {-                exchangeCodeForToken(code)-            }-        } else if (intent?.action == Intent.ACTION_SEND || intent?.action == Intent.ACTION_SENDTO) {+        if (intent?.action == Intent.ACTION_SEND || intent?.action == Intent.ACTION_SENDTO) {             val to = if (intent.action == Intent.ACTION_SENDTO) data?.schemeSpecificPart ?: "" else ""             val subject = intent.getStringExtra(Intent.EXTRA_SUBJECT) ?: ""             val body = intent.getStringExtra(Intent.EXTRA_TEXT) ?: ""-            -            IntentState.navigationRoute = Route.Composer(to, subject, body)-        }-    }--    private fun exchangeCodeForToken(code: String) {-        val verifier = TokenState.codeVerifier ?: return--        scope.launch {-            try {-                HttpClient(CIO) {-                    install(ContentNegotiation) {-                        json(Json { ignoreUnknownKeys = true })-                    }-                }.use { client ->-                    val httpResponse = client.submitForm(-                        url = "https://oauth2.googleapis.com/token",-                        formParameters = parameters {-                            append("client_id", clientId)-                            append("code", code)-                            append("code_verifier", verifier)-                            append("grant_type", "authorization_code")-                            append("redirect_uri", redirectUri)-                        }-                    ) -                    if (httpResponse.status.isSuccess()) {-                        val response: TokenResponse = httpResponse.body()-                        -                        val userInfo: UserInfo = client.get("https://www.googleapis.com/oauth2/v3/userinfo") {-                            bearerAuth(response.accessToken)-                        }.body()--                        val dao = EmailDatabase.getInstance(this@MainActivity).emailDao()-                        dao.insertAccount(EmailAccount(-                            email = userInfo.email,-                            accessToken = response.accessToken,-                            refreshToken = response.refreshToken-                        ))-                        -                        EmailSyncWorker.schedulePeriodicSync(this@MainActivity)-                        EmailSyncWorker.runOneOffSync(this@MainActivity)-                        // (Re)start IDLE now that we have at least one account.-                        com.vayunmathur.email.data.ImapIdleService.start(this@MainActivity)-                    } else {-                        val errorText = httpResponse.bodyAsText()-                        android.util.Log.e("OAuthError", "Failed to exchange code: $errorText")-                    }-                }-            } catch (e: Exception) {-                e.printStackTrace()-            }+            IntentState.navigationRoute = Route.Composer(to, subject, body)         }     }--    private fun generateCodeVerifier(): String {-        val sr = SecureRandom()-        val code = ByteArray(32)-        sr.nextBytes(code)-        return Base64.encodeToString(code, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING).trim()-    }--    private fun generateCodeChallenge(verifier: String): String {-        val bytes = verifier.toByteArray()-        val md = MessageDigest.getInstance("SHA-256")-        md.update(bytes)-        val digest = md.digest()-        return Base64.encodeToString(digest, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING).trim()-    } }  object IntentState {     var navigationRoute by mutableStateOf<Route?>(null) } -object TokenState {-    var codeVerifier: String? = null-}--@Serializable-data class TokenResponse(-    @kotlinx.serialization.SerialName("access_token") val accessToken: String,-    @kotlinx.serialization.SerialName("expires_in") val expiresIn: Int,-    @kotlinx.serialization.SerialName("refresh_token") val refreshToken: String? = null,-    @kotlinx.serialization.SerialName("scope") val scope: String,-    @kotlinx.serialization.SerialName("token_type") val tokenType: String-)--@Serializable-data class UserInfo(-    val email: String,-    val name: String? = null,-    val picture: String? = null-)- @Composable-fun MainContent(viewModel: EmailViewModel, onLaunchGoogleSignIn: () -> Unit) {+fun MainContent(viewModel: EmailViewModel) {     val accounts by viewModel.accounts.collectAsState(emptyList())     if (accounts.isEmpty()) {         // First run: jump straight into the add-account picker. The conditional         // above auto-swaps us into EmailApp once the first account lands.         com.vayunmathur.email.ui.AddAccountScreen(             onBack = null,-            onLaunchGoogleSignIn = onLaunchGoogleSignIn,             onAccountAdded = {},         )     } else {-        EmailApp(viewModel = viewModel, onLaunchGoogleSignIn = onLaunchGoogleSignIn)-    }-}--// Kept for backwards-compat if anything else references it; the active first--// run UI is now AddAccountScreen.-@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun LoginScreen(onGoogleLogin: () -> Unit) {-    Scaffold(-        topBar = { TopAppBar(title = { Text("Email") }) }-    ) { padding ->-        Column(-            modifier = Modifier-                .padding(padding)-                .fillMaxSize(),-            verticalArrangement = Arrangement.Center,-            horizontalAlignment = Alignment.CenterHorizontally-        ) {-            Text(-                text = "Welcome to Email",-                style = MaterialTheme.typography.headlineMedium,-                modifier = Modifier.padding(bottom = 32.dp)-            )-            Button(-                onClick = onGoogleLogin,-                modifier = Modifier.padding(16.dp)-            ) {-                Text("Sign in with Google")-            }-        }+        EmailApp(viewModel = viewModel)     } } @@ -310,7 +142,7 @@ sealed interface Route : NavKey { }  @Composable-fun EmailApp(viewModel: EmailViewModel, onLaunchGoogleSignIn: () -> Unit) {+fun EmailApp(viewModel: EmailViewModel) {     val scope = rememberCoroutineScope()     val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)     val context = LocalContext.current@@ -480,7 +312,6 @@ fun EmailApp(viewModel: EmailViewModel, onLaunchGoogleSignIn: () -> Unit) {             entry<Route.AddAccount>(metadata = ListDetailPage()) {                 com.vayunmathur.email.ui.AddAccountScreen(                     onBack = { backStack.pop() },-                    onLaunchGoogleSignIn = onLaunchGoogleSignIn,                     onAccountAdded = { backStack.pop() },                 )             }@@ -668,7 +499,7 @@ fun MessageListScreen(                         modifier = Modifier.fillMaxSize()                     ) {                     items(messages, key = { "${it.accountEmail}|${it.folderName}|${it.id}" }) { message ->-                        val accountColor = Color(EmailAccount(message.accountEmail, "", "").getColor())+                        val accountColor = Color(EmailAccount(message.accountEmail).getColor())                         val isSelected = message.id in selectedUids                                                  Row(@@ -814,7 +645,7 @@ fun MessageItem(     val senderName = msg.from.substringBefore("<").trim().ifEmpty { msg.from }     val senderEmail = msg.from.substringAfter("<").substringBefore(">").trim()     val initial = senderName.take(1).uppercase()-    val avatarColor = Color(EmailAccount(msg.accountEmail, "", "").getColor())+    val avatarColor = Color(EmailAccount(msg.accountEmail).getColor())      Column {         // Header
email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt b/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.ktindex d7c9dbdee0..93b6aa43da 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt@@ -16,8 +16,7 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :     override suspend fun doWork(): Result {         val db = EmailDatabase.getInstance(applicationContext)         val dao = db.emailDao()-        // Mutable so we can swap in a refreshed account on auth failure.-        val accounts = dao.getAccounts().toMutableList()+        val accounts = dao.getAccounts()          if (accounts.isEmpty()) {             Log.d("EmailSync", "No accounts to sync")@@ -29,16 +28,13 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :         var hasErrors = false         var accountsProcessed = 0 -        for ((i, original) in accounts.withIndex()) {-            // `account` may be replaced with a refreshed copy below.-            var account = original+        for (account in accounts) {             try {                 Log.d("EmailSync", ">>> Starting sync for account: ${account.email}")-                var auth = account.authType()+                val auth = account.authType()                  // Open a SINGLE store for the whole account — folders + every                 // folder's message sync all reuse one TCP/TLS connection.-                // On auth failure we refresh the token and retry once.                 suspend fun runSync(authToUse: EmailManager.AuthType, accountToUse: com.vayunmathur.email.EmailAccount) {                     manager.withStore(accountToUse.imapServer(), accountToUse.email, authToUse) { store ->                         Log.d("EmailSync", "Fetching folders for ${accountToUse.email}...")@@ -150,20 +146,7 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :                     }                 } -                try {-                    runSync(auth, account)-                } catch (e: javax.mail.AuthenticationFailedException) {-                    // Only OAuth2 accounts can be auto-recovered. Password-                    // accounts surface the auth error to the user instead.-                    if (account.authType != "oauth2") throw e-                    Log.d("EmailSync", "Auth failed for ${account.email}; refreshing token")-                    val refreshed = TokenRefresher.refresh(applicationContext, account)-                        ?: throw e-                    account = refreshed-                    accounts[i] = refreshed-                    auth = EmailManager.AuthType.OAuth2(refreshed.accessToken)-                    runSync(auth, refreshed)-                }+                runSync(auth, account)                  Log.d("EmailSync", "<<< Completed sync for account: ${account.email}")             } catch (e: Exception) {
email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.ktindex eeef3027cb..e2dc06f372 100644--- a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt+++ b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt@@ -38,8 +38,8 @@ import kotlinx.coroutines.withContext  * in the foreground.  *  * IDLE connections naturally time out after ~29 minutes on most servers — we- * just catch the disconnect and reconnect with exponential backoff. If we get- * an `AuthenticationFailedException` we refresh the OAuth token first.+ * just catch the disconnect and reconnect with exponential backoff. On+ * auth-failed we stop retrying since app passwords can't be auto-refreshed.  */ class ImapIdleService : Service() { @@ -72,8 +72,7 @@ class ImapIdleService : Service() {         }     } -    private suspend fun idleLoop(initial: com.vayunmathur.email.EmailAccount) {-        var account = initial+    private suspend fun idleLoop(account: com.vayunmathur.email.EmailAccount) {         var backoffMs = 2_000L         val maxBackoffMs = 60_000L         while (scope.coroutineContext.isActive) {@@ -83,19 +82,8 @@ class ImapIdleService : Service() {                 backoffMs = 2_000L                 delay(1_000L)             } catch (e: javax.mail.AuthenticationFailedException) {-                if (account.authType != "oauth2") {-                    Log.w(TAG, "IDLE auth failed for password account ${account.email}; stopping retries")-                    return-                }-                Log.d(TAG, "IDLE auth failed for ${account.email}; refreshing token")-                val refreshed = TokenRefresher.refresh(applicationContext, account)-                if (refreshed != null) {-                    account = refreshed-                    backoffMs = 2_000L-                } else {-                    Log.w(TAG, "IDLE token refresh failed for ${account.email}; sleeping")-                    delay(maxBackoffMs)-                }+                Log.w(TAG, "IDLE auth failed for ${account.email}; stopping retries")+                return             } catch (e: Exception) {                 Log.w(TAG, "IDLE error for ${account.email}: ${e.javaClass.simpleName}: ${e.message}")                 delay(backoffMs)
email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.kt b/email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.ktindex 9eaf52d9a1..772bd9fd98 100644--- a/email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.kt+++ b/email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.kt@@ -42,7 +42,7 @@ class OutboxSendWorker(             return Result.success()         } -        val accounts = dao.getAccounts().associateBy { it.email }.toMutableMap()+        val accounts = dao.getAccounts().associateBy { it.email }         val manager = EmailManager()         var anyFailed = false         val now = System.currentTimeMillis()@@ -60,11 +60,9 @@ class OutboxSendWorker(                 continue             }             val uris = decodePaths(entry.attachmentLocalPaths).map { Uri.fromFile(File(it)) }-            val sendResult = trySendWithRefresh(manager, account, entry, uris)+            val sendResult = trySend(manager, account, entry, uris)             when (sendResult) {                 is SendResult.Success -> {-                    // Cache the (possibly refreshed) account for subsequent entries.-                    accounts[sendResult.account.email] = sendResult.account                     Log.d(TAG, "Sent outbox entry #${entry.id} to ${entry.to}")                     attachmentDirFor(applicationContext, entry.id).deleteRecursively()                     dao.deleteOutboxEntry(entry)@@ -90,27 +88,26 @@ class OutboxSendWorker(     }      private sealed class SendResult {-        data class Success(val account: com.vayunmathur.email.EmailAccount) : SendResult()+        object Success : SendResult()         data class Failure(val message: String, val cause: Throwable?) : SendResult()     }      /**-     * Send the entry, refreshing the access token once on auth failure and-     * retrying. Returns either Success (with the account whose token may have-     * been refreshed) or Failure.+     * Send the entry once. Returns either Success or Failure with the+     * underlying error message.      */-    private suspend fun trySendWithRefresh(+    private suspend fun trySend(         manager: EmailManager,         account: com.vayunmathur.email.EmailAccount,         entry: com.vayunmathur.email.OutboxEntry,         uris: List<android.net.Uri>,     ): SendResult {-        suspend fun attempt(acct: com.vayunmathur.email.EmailAccount): kotlin.Result<Unit> = runCatching {+        val result = runCatching {             manager.sendMessage(                 context = applicationContext,-                server = acct.smtpServer(),-                user = acct.email,-                auth = acct.authType(),+                server = account.smtpServer(),+                user = account.email,+                auth = account.authType(),                 to = entry.to,                 subject = entry.subject,                 body = entry.body,@@ -120,28 +117,9 @@ class OutboxSendWorker(                 references = entry.references,             )         }--        val first = attempt(account)-        if (first.isSuccess) return SendResult.Success(account)-        val firstErr = first.exceptionOrNull()-        if (firstErr !is javax.mail.AuthenticationFailedException) {-            return SendResult.Failure(formatError(firstErr), firstErr)-        }-        // Token likely expired — refresh and retry exactly once.-        // Password accounts can't be auto-refreshed; treat as a hard failure.-        if (account.authType != "oauth2") {-            return SendResult.Failure(formatError(firstErr), firstErr)-        }-        Log.d(TAG, "Auth failure on send; refreshing token for ${account.email}")-        val refreshed = TokenRefresher.refresh(applicationContext, account)-            ?: return SendResult.Failure(-                "Auth failed and token refresh failed — re-login required",-                firstErr,-            )-        val second = attempt(refreshed)-        if (second.isSuccess) return SendResult.Success(refreshed)-        val secondErr = second.exceptionOrNull()-        return SendResult.Failure(formatError(secondErr), secondErr)+        if (result.isSuccess) return SendResult.Success+        val err = result.exceptionOrNull()+        return SendResult.Failure(formatError(err), err)     }      private fun formatError(t: Throwable?): String {
email/src/main/java/com/vayunmathur/email/data/ProviderPresets.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/ProviderPresets.kt b/email/src/main/java/com/vayunmathur/email/data/ProviderPresets.ktindex 6ffe8731f6..58131358e4 100644--- a/email/src/main/java/com/vayunmathur/email/data/ProviderPresets.kt+++ b/email/src/main/java/com/vayunmathur/email/data/ProviderPresets.kt@@ -6,9 +6,9 @@ import com.vayunmathur.email.ServerConfig  * Built-in email provider with pre-filled IMAP/SMTP server settings + a short  * instruction list for users who need to create an app password.  *- * `gmail` is the only OAuth2 preset; the rest use app passwords (long random- * strings the user generates in their provider's account-security settings).- * `custom` is the escape hatch — host/port/security are entered manually.+ * Every preset authenticates with an app password (a long random string the+ * user generates in their provider's account-security settings). `custom` is+ * the escape hatch — host/port/security are entered manually.  */ data class ProviderPreset(     val id: String,@@ -35,9 +35,14 @@ val PROVIDER_PRESETS: List<ProviderPreset> = listOf(         displayName = "Gmail",         imap = ServerConfig("imap.gmail.com", 993, useSsl = true),         smtp = ServerConfig("smtp.gmail.com", 465, useSsl = true),-        authType = "oauth2",-        appPasswordHelpUrl = null,-        instructions = emptyList(),+        authType = "password",+        appPasswordHelpUrl = "https://support.google.com/accounts/answer/185833",+        instructions = listOf(+            "Two-step verification must be enabled on your Google account.",+            "Go to https://myaccount.google.com/apppasswords.",+            "Pick \"Mail\" and \"Other\" — name it \"Email\".",+            "Copy the 16-character app password Google shows and paste it below.",+        ),     ),     ProviderPreset(         id = PROVIDER_OUTLOOK,
email/src/main/java/com/vayunmathur/email/data/TokenRefresher.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/TokenRefresher.kt b/email/src/main/java/com/vayunmathur/email/data/TokenRefresher.ktdeleted file mode 100644index 3dab96be8f..0000000000--- a/email/src/main/java/com/vayunmathur/email/data/TokenRefresher.kt+++ /dev/null@@ -1,90 +0,0 @@-package com.vayunmathur.email.data--import android.content.Context-import android.util.Log-import com.vayunmathur.email.EmailAccount-import io.ktor.client.HttpClient-import io.ktor.client.call.body-import io.ktor.client.engine.cio.CIO-import io.ktor.client.plugins.contentnegotiation.ContentNegotiation-import io.ktor.client.request.forms.submitForm-import io.ktor.client.statement.bodyAsText-import io.ktor.http.isSuccess-import io.ktor.http.parameters-import io.ktor.serialization.kotlinx.json.json-import kotlinx.serialization.SerialName-import kotlinx.serialization.Serializable-import kotlinx.serialization.json.Json--/**- * Helper for refreshing expired Google OAuth access tokens using the refresh- * token stored alongside each [EmailAccount]. Mirrors the token-exchange in- * `MainActivity.exchangeCodeForToken` but uses `grant_type=refresh_token`.- */-object TokenRefresher {--    /** Public client id used during the initial OAuth flow. */-    const val CLIENT_ID =-        "827025129169-kgv8s8dvhd7req7ao2ila1j169r068pp.apps.googleusercontent.com"--    /**-     * Refreshes the access token for [account] and persists the new value.-     * Returns the updated [EmailAccount] (with the new `accessToken` and-     * `expiresAt`) or `null` if the refresh failed.-     */-    suspend fun refresh(context: Context, account: EmailAccount): EmailAccount? {-        if (account.authType != "oauth2") {-            Log.d("TokenRefresher", "Skipping refresh for non-OAuth2 account ${account.email}")-            return null-        }-        val refreshToken = account.refreshToken-        if (refreshToken.isNullOrBlank()) {-            Log.w("TokenRefresher", "No refresh token for ${account.email} — re-login required")-            return null-        }-        return try {-            HttpClient(CIO) {-                install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) }-            }.use { client ->-                val resp = client.submitForm(-                    url = "https://oauth2.googleapis.com/token",-                    formParameters = parameters {-                        append("client_id", CLIENT_ID)-                        // iOS / Android OAuth client types refresh without a-                        // client_secret. (Desktop clients require one — see the-                        // README for client registration steps.)-                        append("refresh_token", refreshToken)-                        append("grant_type", "refresh_token")-                    },-                )-                if (!resp.status.isSuccess()) {-                    Log.w("TokenRefresher", "Refresh failed for ${account.email}: ${resp.status} ${resp.bodyAsText()}")-                    return null-                }-                val body: RefreshResponse = resp.body()-                Log.d("TokenRefresher", "New token for ${account.email}: scope=${body.scope}, expires_in=${body.expiresIn}s, access_token starts ${body.accessToken.take(12)}…")-                val updated = account.copy(-                    accessToken = body.accessToken,-                    // Google usually doesn't return a new refresh_token; keep the old one.-                    refreshToken = body.refreshToken ?: account.refreshToken,-                    expiresAt = System.currentTimeMillis() + body.expiresIn * 1000L,-                )-                EmailDatabase.getInstance(context).emailDao().insertAccount(updated)-                Log.d("TokenRefresher", "Refreshed token for ${account.email}")-                updated-            }-        } catch (e: Exception) {-            Log.e("TokenRefresher", "Refresh exception for ${account.email}: ${e.message}", e)-            null-        }-    }--    @Serializable-    private data class RefreshResponse(-        @SerialName("access_token") val accessToken: String,-        @SerialName("expires_in") val expiresIn: Int,-        @SerialName("refresh_token") val refreshToken: String? = null,-        @SerialName("token_type") val tokenType: String,-        @SerialName("scope") val scope: String? = null,-    )-}
email/src/main/java/com/vayunmathur/email/ui/AddAccountScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/AddAccountScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/AddAccountScreen.ktindex 6785627abf..b837fd9a09 100644--- a/email/src/main/java/com/vayunmathur/email/ui/AddAccountScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/AddAccountScreen.kt@@ -36,20 +36,18 @@ import kotlinx.coroutines.withContext  /**  * Add-account flow: pick a preset (Gmail / Outlook / Yahoo / iCloud / Fastmail- * / Custom) → either kick off the Google OAuth flow (Gmail) or collect an app- * password (everything else). After a successful "Test connection" the account- * is encrypted-and-persisted and a one-off sync is kicked off.+ * / Custom) → collect an app password (all providers). After a successful+ * "Test connection" the account is encrypted-and-persisted and a one-off+ * sync is kicked off.  *  * @param onBack pop the screen. Null when the screen is the first-run gate  *   (the parent re-renders to the inbox automatically once an account exists).- * @param onLaunchGoogleSignIn delegates to [com.vayunmathur.email.MainActivity.startGoogleLogin].- * @param onAccountAdded invoked after a non-Gmail account is saved.+ * @param onAccountAdded invoked after the account is saved.  */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun AddAccountScreen(     onBack: (() -> Unit)?,-    onLaunchGoogleSignIn: () -> Unit,     onAccountAdded: () -> Unit, ) {     var selectedProviderId by rememberSaveable { mutableStateOf<String?>(null) }@@ -82,9 +80,8 @@ fun AddAccountScreen(             if (selectedProvider == null) {                 ProviderPicker(onPick = { selectedProviderId = it.id })             } else {-                ProviderForm(+                PasswordForm(                     preset = selectedProvider,-                    onLaunchGoogleSignIn = onLaunchGoogleSignIn,                     onAccountAdded = onAccountAdded,                 )             }@@ -114,7 +111,6 @@ private fun ProviderPicker(onPick: (ProviderPreset) -> Unit) {                     Text(preset.displayName, style = MaterialTheme.typography.titleMedium)                     Text(                         when (preset.id) {-                            PROVIDER_GMAIL -> "Sign in with Google"                             PROVIDER_CUSTOM -> "Enter IMAP/SMTP server details manually"                             else -> "App password"                         },@@ -127,41 +123,6 @@ private fun ProviderPicker(onPick: (ProviderPreset) -> Unit) {     } } -@Composable-private fun ProviderForm(-    preset: ProviderPreset,-    onLaunchGoogleSignIn: () -> Unit,-    onAccountAdded: () -> Unit,-) {-    if (preset.id == PROVIDER_GMAIL) {-        GmailForm(onLaunchGoogleSignIn = onLaunchGoogleSignIn)-    } else {-        PasswordForm(preset = preset, onAccountAdded = onAccountAdded)-    }-}--@Composable-private fun GmailForm(onLaunchGoogleSignIn: () -> Unit) {-    Column(-        Modifier-            .fillMaxSize()-            .verticalScroll(rememberScrollState())-            .padding(16.dp),-        verticalArrangement = Arrangement.spacedBy(12.dp),-    ) {-        Text(-            "You'll be redirected to Google to sign in. New mail will start syncing automatically once you're back.",-            style = MaterialTheme.typography.bodyMedium,-        )-        Button(-            onClick = onLaunchGoogleSignIn,-            modifier = Modifier.fillMaxWidth(),-        ) {-            Text("Continue with Google")-        }-    }-}- @OptIn(ExperimentalMaterial3Api::class) @Composable private fun PasswordForm(@@ -389,9 +350,6 @@ private suspend fun testAndPersistAccount(      val account = EmailAccount(         email = email,-        accessToken = "",-        refreshToken = null,-        expiresAt = 0,         provider = providerId,         imapHost = imap.host,         imapPort = imap.port,