Modern Apps git

← Modern-Apps.git

email: restore accounts on platform backup without secrets

Commit
180c7e70cfcee535a9721b442df682b1b5eec102
Author
Vayun Mathur <[email protected]>
When
2026-12-04 21:52 UTC (1 day ago)
Parents
dec505c
Platform (key/value) restore previously carried only the
email_settings preference, so every account was lost on a clean-slate
restore: the raw SQLCipher email-db cannot transfer (its passphrase
is wrapped by the non-exportable db_no_auth_key) and its rows hold
passwords sealed by the device-bound CredentialCrypto key, which is
undecryptable-by-design on a new device.

Declare platform/AppBackupAgent (library BaseBackupAgent pattern, as
in weather) so cloud backup carries the email_settings prefs plus one
sanitized payload staged by the agent: account server config,
addresses, folders and blocked senders from data/EmailBackup, with
passwordEncrypted/passwordIv and the legacy plaintext
accessToken/refreshToken excluded entirely. The raw database is
still never file-copied; data_extraction_rules documents the scope
split (rules govern device transfer only once the agent exists).

Restored accounts are inserted with empty credential fields.
needsReauth() (password accounts: no sealed password; OAuth: no live
token and no password) drives the follow-up: EmailSyncWorker and
ImapIdleService skip such accounts instead of failing or spinning on
resolveAuth, MainContent prompts once per launch, and Settings shows
a password field per affected account whose save re-seals the app
password under the new device key via EmailViewModel.reauthAccount
and restarts sync/IDLE. Messages, drafts and outbox content are not
backed up; they re-sync after re-auth.

Verified: ./gradlew :email:lint :email:lintVitalRelease
:email:testDevUnitTest green (baseline on 30be4a93a also green, so
no pre-existing failures); new EmailBackupTest pins secret exclusion
from the encoded payload, config round-trip with cleared
credentials, and needsReauth for live vs restored accounts.

Diff

email/AGENTS.md
diff --git a/email/AGENTS.md b/email/AGENTS.mdindex a16826eb17..e10c39412f 100644--- a/email/AGENTS.md+++ b/email/AGENTS.md@@ -26,6 +26,7 @@ _Install: ./install email (dev by default)._ - Startup never crashes the first screen: constructing `EmailRepository` and `EmailViewModel` never builds the database (stores and `draftsActions` are lazy, DAO flows are acquired via a guard that falls back to an empty flow), `MainActivity.onCreateBeforeContent` steps run in isolation via `platform/StartupGuard` (catches `Throwable`, rethrows only cancellation), the backfills and IDLE start guard their own database access, and `EmailViewModel.accounts` degrades to an empty list (the Add Account gate) when the database will not build or open on the device - `network/imap/TrustAll.kt` exists for debug only; never widen its use - Upgrades from app versions before v2.6.0 start with a fresh local database (supported upgrade floor: Email DB v17; DB versions 1–16 open destructively, v17 onward migrates normally)+- Platform backup never copies the raw SQLCipher DB or any credential: account passwords are sealed by the device-bound Keystore (`CredentialCrypto`) and cannot transfer, so `AppBackupAgent` backs up only the sanitized `EmailBackup` payload; restored accounts have empty credential fields, are skipped by sync/IDLE, and prompt for re-auth in Settings  ## Key files ### Root — entry + navigation@@ -54,6 +55,7 @@ _Install: ./install email (dev by default)._ - com/vayunmathur/email/data/OutlookOAuth.kt - com/vayunmathur/email/data/ProviderPresets.kt - com/vayunmathur/email/data/CredentialCrypto.kt+- com/vayunmathur/email/data/EmailBackup.kt — sanitized platform-backup payload (accounts/folders/blocked senders, no secrets) + `needsReauth()` - com/vayunmathur/email/data/DateMillisBackfill.kt - com/vayunmathur/email/data/PeekContentBackfill.kt ### network/ — raw IMAP + SMTP clients@@ -73,6 +75,7 @@ _Install: ./install email (dev by default)._ ### platform/ — ViewModel, actions, notifications, lifecycle - com/vayunmathur/email/platform/EmailViewModel.kt - com/vayunmathur/email/platform/StartupGuard.kt — isolated best-effort startup steps (#939)+- com/vayunmathur/email/platform/AppBackupAgent.kt — key/value backup agent: sanitized account payload + `email_settings` prefs; restored accounts prompt for the app password in Settings - com/vayunmathur/email/platform/EmailManager.kt - com/vayunmathur/email/platform/EmailUiContract.kt - com/vayunmathur/email/platform/EmailClientFlag.kt
email/src/main/AndroidManifest.xml
diff --git a/email/src/main/AndroidManifest.xml b/email/src/main/AndroidManifest.xmlindex e7f96f5be9..b3dca0d01c 100644--- a/email/src/main/AndroidManifest.xml+++ b/email/src/main/AndroidManifest.xml@@ -19,6 +19,7 @@      <application         android:allowBackup="true"+        android:backupAgent=".platform.AppBackupAgent"         android:dataExtractionRules="@xml/data_extraction_rules"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"
email/src/main/java/com/vayunmathur/email/data/EmailBackup.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailBackup.kt b/email/src/main/java/com/vayunmathur/email/data/EmailBackup.ktnew file mode 100644index 0000000000..4177781125--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/data/EmailBackup.kt@@ -0,0 +1,121 @@+package com.vayunmathur.email.data++import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Sanitized, backup-safe view of the account state that must survive a+ * platform (key/value) restore: server config, addresses, folders and+ * per-account preferences — never credentials.+ *+ * Account passwords are AES-GCM sealed by [CredentialCrypto] under the+ * Android Keystore alias `email_account_pw`, and the SQLCipher passphrase+ * is wrapped by the non-exportable `db_no_auth_key`. Neither key leaves+ * the device, so the raw `email-db` file and the sealed+ * `passwordEncrypted`/`passwordIv` columns are undecryptable-by-design+ * after a restore. Copying them would restore garbage, not an account.+ * This payload therefore carries no secret material at all: no password+ * ciphertext or IV, and no legacy OAuth `accessToken`/`refreshToken`.+ * Restored accounts come back with empty credential fields, which+ * [needsReauth] reports so the UI prompts for the app password instead+ * of failing silently in sync.+ */+@Serializable+data class EmailBackupAccount(+    val email: String,+    val provider: String,+    val imapHost: String,+    val imapPort: Int,+    val imapUseSsl: Boolean,+    val smtpHost: String,+    val smtpPort: Int,+    val smtpUseSsl: Boolean,+    val username: String,+    val authType: String,+    val signature: String,+    val allowInsecureCertificates: Boolean,+)++/** Versioned backup payload carried as one file inside the key/value backup zip. */+@Serializable+data class EmailBackupPayload(+    val version: Int = CURRENT_VERSION,+    val accounts: List<EmailBackupAccount> = emptyList(),+    val folders: List<EmailFolder> = emptyList(),+    val blockedSenders: List<String> = emptyList(),+) {+    companion object {+        const val CURRENT_VERSION = 1+    }+}++/**+ * True when this account has no usable credential and must be+ * re-authenticated. Password accounts need their sealed password;+ * OAuth accounts need a live token (a restored OAuth account has+ * neither, since tokens never enter the backup payload).+ */+fun EmailAccount.needsReauth(): Boolean =+    if (authType == "oauth2") {+        accessToken.isBlank() && refreshToken.isNullOrBlank() &&+            (passwordEncrypted == null || passwordIv == null)+    } else {+        passwordEncrypted == null || passwordIv == null+    }++/** Strips every secret field; the result is safe to leave the device in a backup. */+fun EmailAccount.toBackupAccount(): EmailBackupAccount = EmailBackupAccount(+    email = email,+    provider = provider,+    imapHost = imapHost,+    imapPort = imapPort,+    imapUseSsl = imapUseSsl,+    smtpHost = smtpHost,+    smtpPort = smtpPort,+    smtpUseSsl = smtpUseSsl,+    username = username,+    authType = authType,+    signature = signature,+    allowInsecureCertificates = allowInsecureCertificates,+)++/**+ * Rebuilds the live account row with empty credential fields+ * (`accessToken`, `refreshToken`, `passwordEncrypted`, `passwordIv` all+ * cleared), so [needsReauth] prompts for a fresh app password on first+ * launch rather than attempting to decrypt a transferred sealed blob.+ */+fun EmailBackupAccount.toRestoredAccount(): EmailAccount = EmailAccount(+    email = email,+    accessToken = "",+    refreshToken = null,+    expiresAt = 0,+    provider = provider,+    imapHost = imapHost,+    imapPort = imapPort,+    imapUseSsl = imapUseSsl,+    smtpHost = smtpHost,+    smtpPort = smtpPort,+    smtpUseSsl = smtpUseSsl,+    username = username,+    authType = authType,+    passwordEncrypted = null,+    passwordIv = null,+    signature = signature,+    allowInsecureCertificates = allowInsecureCertificates,+)++/** JSON codec for [EmailBackupPayload]; unknown fields are ignored for forward compatibility. */+object EmailBackupCodec {+    private val json = Json { ignoreUnknownKeys = true }++    fun encode(payload: EmailBackupPayload): String = json.encodeToString(payload)++    /** Non-throwing decode: a corrupt or future payload restores nothing, never crashes. */+    fun decode(text: String): EmailBackupPayload? =+        try {+            json.decodeFromString<EmailBackupPayload>(text)+        } catch (_: Exception) {+            null+        }+}
email/src/main/java/com/vayunmathur/email/data/EmailSettings.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailSettings.kt b/email/src/main/java/com/vayunmathur/email/data/EmailSettings.ktindex bd4880da69..66fea962fa 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailSettings.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailSettings.kt@@ -21,7 +21,7 @@ import kotlinx.coroutines.flow.asStateFlow  */ class EmailSettings private constructor(context: Context) { -    private val prefs = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)+    private val prefs = context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)      private val _loadRemoteImages = MutableStateFlow(prefs.getBoolean(KEY_LOAD_REMOTE_IMAGES, false)) @@ -53,7 +53,8 @@ class EmailSettings private constructor(context: Context) {      /** Holds preference keys and defaults for email settings. */     companion object {-        private const val PREFS = "email_settings"+        /** SharedPreferences file name; also the key/value backup pref name. */+        const val PREFS_NAME = "email_settings"         private const val KEY_LOAD_REMOTE_IMAGES = "load_remote_images"         private const val KEY_HAS_ASKED_NOTIFICATIONS = "has_asked_notifications" 
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 32c8ba7a52..c4dad6b768 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt@@ -45,6 +45,14 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :         var accountsProcessed = 0          for (account in accounts) {+            // Restored accounts carry no credential (see EmailBackup):+            // skip them until the user re-enters the app password in+            // Settings, instead of failing every sync run on resolveAuth.+            if (account.needsReauth()) {+                Log.status("EmailSync", "Skipping ${account.email}; password needed after restore")+                accountsProcessed+++                continue+            }             val ok = try {                 syncAccount(db, account, nonInboxOnly, accounts.size, accountsProcessed)                 true
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 7f590d900d..8fac7fb533 100644--- a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt+++ b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt@@ -85,12 +85,19 @@ class ImapIdleService : Service() {         }         if (accounts.isEmpty()) { stopSelf(); return }         try { EmailSyncWorker.scheduleHourlyNonInboxSync(applicationContext) } catch (_: Exception) {}+        // Restored accounts have no credential to log in with; do not+        // spin an IDLE reconnect loop for them (see EmailBackup).         val current = accounts.map { it.email }.toSet()         accountJobs.keys.filter { it !in current }.forEach { accountJobs[it]?.cancel(); accountJobs.remove(it) }         for (account in accounts) {+            if (account.needsReauth()) {+                Log.status(TAG, "IDLE skipped for ${account.email}; password needed after restore")+                continue+            }             accountJobs[account.email]?.cancel()             accountJobs[account.email] = scope.launch { idleLoop(account) }         }+        if (accountJobs.isEmpty()) stopSelf()     }      private suspend fun idleLoop(account: EmailAccount) {
email/src/main/java/com/vayunmathur/email/platform/AppBackupAgent.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/AppBackupAgent.kt b/email/src/main/java/com/vayunmathur/email/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..f81705e92c--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/platform/AppBackupAgent.kt@@ -0,0 +1,126 @@+package com.vayunmathur.email.platform++import android.app.backup.BackupDataInput+import android.app.backup.BackupDataOutput+import android.content.Context+import android.os.ParcelFileDescriptor+import com.vayunmathur.email.data.EmailBackupCodec+import com.vayunmathur.email.data.EmailBackupPayload+import com.vayunmathur.email.data.EmailRepository+import com.vayunmathur.email.data.EmailSettings+import com.vayunmathur.email.data.toBackupAccount+import com.vayunmathur.email.data.toRestoredAccount+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.util.BaseBackupAgent+import java.io.File+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking++/**+ * Key/value (platform) backup for Email.+ *+ * Declaring this agent switches the app from Auto Backup file rules to+ * key/value backup, exactly as in weather: the raw SQLCipher `email-db`+ * is never copied (its passphrase is wrapped by the non-exportable+ * `db_no_auth_key`, so a restored file cannot be opened, and its rows+ * hold Keystore-sealed passwords). Instead the agent stages one+ * sanitized payload file — accounts, folders and blocked senders with+ * every secret field stripped by [toBackupAccount] — plus the+ * `email_settings` preferences, and [BaseBackupAgent] carries them in+ * its single backup entity. Messages, drafts and the outbox are mail+ * content and are deliberately not backed up; they re-sync from the+ * server once the account is re-authenticated.+ *+ * On restore the payload is imported into the fresh (locally keyed)+ * database with empty credential fields, so accounts are present on+ * first launch and prompt for their app password instead of being+ * silently dropped or crashing sync with undecryptable secrets.+ */+class AppBackupAgent : BaseBackupAgent() {++    override val prefNames: List<String>+        get() = listOf(EmailSettings.PREFS_NAME)++    override val extraFiles: List<File>+        get() = listOf(backupFile(this))++    override fun onBackup(+        oldState: ParcelFileDescriptor?,+        data: BackupDataOutput?,+        newState: ParcelFileDescriptor?,+    ) {+        writeBackupPayload()+        super.onBackup(oldState, data, newState)+    }++    override fun onRestore(+        data: BackupDataInput?,+        appVersionCode: Int,+        newState: ParcelFileDescriptor?,+    ) {+        super.onRestore(data, appVersionCode, newState)+        importBackupPayload()+    }++    private fun writeBackupPayload() {+        try {+            val payload = runBlocking(Dispatchers.IO) {+                val repo = EmailRepository.get(this@AppBackupAgent)+                val db = repo.getDatabase()+                val accounts = db.accountDao().getAccounts()+                EmailBackupPayload(+                    accounts = accounts.map { it.toBackupAccount() },+                    folders = accounts.flatMap { account ->+                        db.accountDao().getFoldersFlow(account.email).first()+                    },+                    blockedSenders = db.accountDao().getBlockedSendersFlow().first()+                        .map { it.address },+                )+            }+            val file = backupFile(this)+            file.parentFile?.mkdirs()+            file.writeText(EmailBackupCodec.encode(payload))+        } catch (cancelled: kotlinx.coroutines.CancellationException) {+            throw cancelled+        } catch (failure: Throwable) {+            // A database that will not open must not fail the whole+            // backup: stage no payload and let preferences still carry.+            Log.status(TAG, "Backup payload skipped; database unavailable", failure)+            backupFile(this).delete()+        }+    }++    private fun importBackupPayload() {+        val file = backupFile(this)+        if (!file.exists()) return+        try {+            val payload = EmailBackupCodec.decode(file.readText()) ?: return+            runBlocking(Dispatchers.IO) {+                val dao = EmailRepository.get(this@AppBackupAgent).getDatabase().accountDao()+                payload.accounts.forEach { dao.insertAccount(it.toRestoredAccount()) }+                if (payload.folders.isNotEmpty()) dao.insertFolders(payload.folders)+                payload.blockedSenders.forEach {+                    dao.insertBlockedSender(com.vayunmathur.email.data.BlockedSender(it))+                }+            }+        } catch (cancelled: kotlinx.coroutines.CancellationException) {+            throw cancelled+        } catch (failure: Throwable) {+            Log.status(TAG, "Restored accounts import failed", failure)+        } finally {+            // The staging file has served its purpose; live state is in+            // the database now. Deleting also keeps it out of any later+            // file-based transfer.+            file.delete()+        }+    }++    companion object {+        private const val TAG = "EmailBackupAgent"++        /** Staging file for the sanitized payload, under files/ (never file-backed-up raw). */+        fun backupFile(context: Context): File =+            File(context.filesDir, "email_backup/accounts.json")+    }+}
email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.ktindex 3fb49c64f9..a788d61e91 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt@@ -238,6 +238,34 @@ class EmailViewModel(application: Application) :         }     } +    /**+     * Re-authenticates a restored account: seals the freshly entered app+     * password with this device's Keystore key and stores it on the+     * existing account row (server config, folders and signature are+     * preserved), then restarts sync and IDLE for it.+     */+    fun reauthAccount(email: String, password: String) {+        if (password.isBlank()) return+        viewModelScope.launch {+            val account = accountsDao.getAccountByEmail(email) ?: return@launch+            val (cipher, iv) = try {+                com.vayunmathur.email.data.CredentialCrypto.encrypt(password)+            } catch (failure: Throwable) {+                Log.status("EmailViewModel", "Could not store password for $email", failure)+                return@launch+            }+            accountsDao.insertAccount(+                account.copy(+                    authType = "password",+                    passwordEncrypted = cipher,+                    passwordIv = iv,+                ),+            )+            EmailSyncWorker.runOneOffSync(appContext)+            com.vayunmathur.email.data.ImapIdleService.start(appContext)+        }+    }+     fun selectFolder(folderName: String) {         _selectedFolderName.value = folderName         _searchQuery.value = ""
email/src/main/java/com/vayunmathur/email/ui/MainContent.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/MainContent.kt b/email/src/main/java/com/vayunmathur/email/ui/MainContent.ktindex 5732c2c967..5a71854096 100644--- a/email/src/main/java/com/vayunmathur/email/ui/MainContent.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/MainContent.kt@@ -15,6 +15,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.email.Navigation import com.vayunmathur.email.Route import com.vayunmathur.email.data.EmailSettings+import com.vayunmathur.email.data.needsReauth import com.vayunmathur.email.platform.addAccountEntries import com.vayunmathur.email.platform.EmailViewModel import com.vayunmathur.email.platform.IntentState@@ -46,6 +47,18 @@ fun MainContent(viewModel: EmailViewModel) {             }         }     }+    // Restored accounts arrive without credentials (passwords are sealed+    // by the old device's Keystore and never back up): prompt once per+    // launch until each is re-authenticated in Settings, rather than+    // letting sync fail silently.+    val needsReauthAccounts = accounts.filter { it.needsReauth() }+    LaunchedEffect(needsReauthAccounts.map { it.email }) {+        if (needsReauthAccounts.isNotEmpty()) {+            com.vayunmathur.library.util.AppMessages.show(+                context.getString(com.vayunmathur.email.R.string.accounts_restored_need_password),+            )+        }+    }     val navigationRoute = IntentState.navigationRoute     val isEmlViewer = navigationRoute is Route.EmlViewer 
email/src/main/java/com/vayunmathur/email/ui/SettingsContent.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/SettingsContent.kt b/email/src/main/java/com/vayunmathur/email/ui/SettingsContent.ktindex 15f8df0567..3ecea942bd 100644--- a/email/src/main/java/com/vayunmathur/email/ui/SettingsContent.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/SettingsContent.kt@@ -15,6 +15,7 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.email.R import com.vayunmathur.email.data.BlockedSender import com.vayunmathur.email.data.EmailAccount+import com.vayunmathur.email.data.needsReauth import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.ListItem@@ -35,6 +36,7 @@ fun SettingsContent(     onSaveSignature: (String, String) -> Unit,     onAllowInsecureChange: (String, Boolean) -> Unit,     onUnblock: (String) -> Unit,+    onReauth: (String, String) -> Unit = { _, _ -> }, ) {     Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {         Text(stringResource(R.string.reading), style = MaterialTheme.typography.titleMedium)@@ -53,6 +55,29 @@ fun SettingsContent(             var sig by remember(acc.email) { mutableStateOf(acc.signature) }             Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {                 Text(acc.email, style = MaterialTheme.typography.labelLarge)+                if (acc.needsReauth()) {+                    var newPassword by remember(acc.email) { mutableStateOf("") }+                    Text(+                        stringResource(R.string.password_needed_after_restore),+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.error,+                    )+                    if (acc.authType != "oauth2") {+                        OutlinedTextField(+                            value = newPassword,+                            onValueChange = { newPassword = it },+                            modifier = Modifier.fillMaxWidth(),+                            label = { Text(stringResource(R.string.app_password)) },+                            singleLine = true,+                            visualTransformation = androidx.compose.ui.text.input.PasswordVisualTransformation(),+                        )+                        Button(+                            onClick = { onReauth(acc.email, newPassword) },+                            enabled = newPassword.isNotBlank(),+                            modifier = Modifier.align(Alignment.End),+                        ) { Text(stringResource(R.string.save_password)) }+                    }+                }                 OutlinedTextField(                     value = sig,                     onValueChange = { sig = it },
email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.ktindex b954678d51..b38a72b072 100644--- a/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt@@ -56,6 +56,10 @@ fun SettingsScreen(viewModel: EmailViewModel, onBack: () -> Unit) {             },             onAllowInsecureChange = { email, v -> viewModel.setAllowInsecureCertificates(email, v) },             onUnblock = { viewModel.unblockSender(it) },+            onReauth = { email, password ->+                viewModel.reauthAccount(email, password)+                AppMessages.show(resources.getString(R.string.password_saved))+            },         )     } }
email/src/main/res/values/strings.xml
diff --git a/email/src/main/res/values/strings.xml b/email/src/main/res/values/strings.xmlindex c29204e8de..a33df6f3b3 100644--- a/email/src/main/res/values/strings.xml+++ b/email/src/main/res/values/strings.xml@@ -158,6 +158,10 @@     <string name="clear_formatting">Clear formatting</string>     <string name="allow_insecure_certificates">Allow insecure certificates</string>     <string name="allow_insecure_certificates_summary">Warning: accepts any certificate for this account\'s mail servers, including invalid or self-signed ones. Anyone on the network could intercept this account\'s mail and password. Only enable for a trusted self-hosted server.</string>+    <string name="password_needed_after_restore">Password needed — this account was restored without its password. Enter the app password to reconnect.</string>+    <string name="save_password">Save password</string>+    <string name="password_saved">Password saved</string>+    <string name="accounts_restored_need_password">Your accounts were restored. Sign in again for each account (app password in Settings) to reconnect.</string>     <string name="email_sync_channel_name">Background email sync</string>     <string name="email_sync_channel_desc">Keeps an IMAP connection open so new mail arrives instantly.</string>     <string name="unified_inbox_label">Unified Inbox</string>
email/src/main/res/xml/data_extraction_rules.xml
diff --git a/email/src/main/res/xml/data_extraction_rules.xml b/email/src/main/res/xml/data_extraction_rules.xmlindex 99c69df49b..461906234b 100644--- a/email/src/main/res/xml/data_extraction_rules.xml+++ b/email/src/main/res/xml/data_extraction_rules.xml@@ -53,6 +53,19 @@   Device transfer carries the same single preference. It is not widened relative to cloud   backup, because D2D does not migrate AndroidKeyStore material and the accounts database   would arrive unopenable.++  SCOPE: email declares android:backupAgent=".platform.AppBackupAgent" and does NOT set+  android:fullBackupOnly, so Android uses key/value backup and the <cloud-backup> section+  below is NOT consulted for cloud backup. Cloud content is exactly what AppBackupAgent+  stages: the email_settings preferences plus one sanitized payload+  (files/email_backup/accounts.json) holding account server config, addresses, folders+  and blocked senders with every secret field stripped (no passwordEncrypted/passwordIv,+  no accessToken/refreshToken — see data/EmailBackup.kt). Restored accounts carry empty+  credential fields and prompt for the app password on first launch. The rules below+  govern <device-transfer>, and are the correct control if the backupAgent is ever+  removed: the raw database and the sealed secrets must still never be file-copied.+  files/email_backup/accounts.json is agent staging only; it is not named here, so a+  file-based transfer does not carry it raw. --> <data-extraction-rules>     <cloud-backup disableIfNoEncryptionCapabilities="true">
email/src/test/java/com/vayunmathur/email/data/EmailBackupTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/EmailBackupTest.kt b/email/src/test/java/com/vayunmathur/email/data/EmailBackupTest.ktnew file mode 100644index 0000000000..bacc8b4f75--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/EmailBackupTest.kt@@ -0,0 +1,103 @@+package com.vayunmathur.email.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pins the platform-backup secret handling: the payload that leaves the+ * device must carry account config with no secret material, and a+ * restored account must come back present-but-credential-less+ * ([needsReauth]) rather than holding a transferred sealed blob that+ * this device's Keystore cannot decrypt.+ */+class EmailBackupTest {++    private fun liveAccount() = EmailAccount(+        email = "[email protected]",+        accessToken = "ACCESS_TOKEN_SECRET",+        refreshToken = "REFRESH_TOKEN_SECRET",+        expiresAt = 999L,+        provider = "custom",+        imapHost = "imap.example.com",+        imapPort = 993,+        imapUseSsl = true,+        smtpHost = "smtp.example.com",+        smtpPort = 465,+        smtpUseSsl = true,+        username = "me-login",+        authType = "password",+        passwordEncrypted = byteArrayOf(1, 2, 3, 4),+        passwordIv = byteArrayOf(5, 6, 7, 8),+        signature = "-- Me",+        allowInsecureCertificates = true,+    )++    @Test+    fun `encoded payload contains no secrets`() {+        val payload = EmailBackupPayload(+            accounts = listOf(liveAccount().toBackupAccount()),+            folders = listOf(EmailFolder("[email protected]", "INBOX", "INBOX")),+            blockedSenders = listOf("[email protected]"),+        )+        val encoded = EmailBackupCodec.encode(payload)+        assertFalse(encoded.contains("ACCESS_TOKEN_SECRET"), encoded)+        assertFalse(encoded.contains("REFRESH_TOKEN_SECRET"), encoded)+        assertFalse(encoded.contains("passwordEncrypted"), encoded)+        assertFalse(encoded.contains("passwordIv"), encoded)+        assertFalse(encoded.contains("accessToken"), encoded)+        assertFalse(encoded.contains("refreshToken"), encoded)+    }++    @Test+    fun `round trip preserves config and clears credentials`() {+        val payload = EmailBackupPayload(+            accounts = listOf(liveAccount().toBackupAccount()),+            folders = listOf(EmailFolder("[email protected]", "INBOX", "INBOX")),+            blockedSenders = listOf("[email protected]"),+        )+        val decoded = EmailBackupCodec.decode(EmailBackupCodec.encode(payload))+        assertEquals(payload, decoded)++        val restored = decoded!!.accounts.single().toRestoredAccount()+        assertEquals("[email protected]", restored.email)+        assertEquals("imap.example.com", restored.imapHost)+        assertEquals(993, restored.imapPort)+        assertEquals("smtp.example.com", restored.smtpHost)+        assertEquals("me-login", restored.username)+        assertEquals("-- Me", restored.signature)+        assertTrue(restored.allowInsecureCertificates)+        assertEquals("", restored.accessToken)+        assertNull(restored.refreshToken)+        assertEquals(0L, restored.expiresAt)+        assertNull(restored.passwordEncrypted)+        assertNull(restored.passwordIv)+        assertTrue(restored.needsReauth())+        assertEquals("INBOX", decoded.folders.single().fullName)+        assertEquals(listOf("[email protected]"), decoded.blockedSenders)+    }++    @Test+    fun `live password account does not need reauth`() {+        assertFalse(liveAccount().needsReauth())+    }++    @Test+    fun `live oauth account with tokens does not need reauth`() {+        val oauth = liveAccount().copy(+            authType = "oauth2",+            passwordEncrypted = null,+            passwordIv = null,+        )+        assertFalse(oauth.needsReauth())+        assertTrue(oauth.copy(accessToken = "", refreshToken = null).needsReauth())+    }++    @Test+    fun `corrupt payload decodes to null`() {+        assertNull(EmailBackupCodec.decode("not json"))+        assertNull(EmailBackupCodec.decode(""))+    }+}