Modern Apps git

← Modern-Apps.git

securemail: detekt clean (54 tests)

Commit
891bf20240a3440f2f594ee0364303e5599ad0e1
Author
Vayun Mathur <[email protected]>
When
2026-11-15 00:30 UTC (21 days ago)
Parents
4ac5be9
Fix all detekt findings in securemail by fixing code, not config
(detekt.yml untouched, no baselines added):
- UndocumentedPublicClass: KDoc for 24 types.
- MagicNumber: wire framing offsets/lengths/shifts are
  named constants; GCM tag bits and passphrase minimum
  named; sync drain delay named.
- Navigation/InboundStore: destinations and the
  encrypted-store branch extracted (LongMethod).
- MailViewModel: message actions and envelopeOf are
  extension functions, outbox retry extracted to
  OutboxRetry (TooManyFunctions/LongMethod/complexity).
- TooGenericExceptionCaught: socket claim/getKey/fetch,
  sync worker and outbox encryption keep broad catches
  with narrow @Suppress justification (any failure is
  the logged offline/retry outcome).
Verified: ./gradlew :securemail:detekt :securemail:testDevUnitTest :securemail:lint
--max-workers=32 all pass (54 unit tests).

Diff

securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt b/securemail/src/main/java/com/vayunmathur/securemail/Navigation.ktindex e12f69b02e..4ee8ce63f8 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt@@ -14,9 +14,18 @@ import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.SiblingPage import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.securemail.data.MailFolder+import com.vayunmathur.securemail.data.StoredMessage+import com.vayunmathur.securemail.platform.MailUiState import com.vayunmathur.securemail.domain.mail.AddressValidator import com.vayunmathur.securemail.platform.Draft import com.vayunmathur.securemail.platform.MailViewModel+import com.vayunmathur.securemail.platform.deleteForever+import com.vayunmathur.securemail.platform.envelopeOf+import com.vayunmathur.securemail.platform.markRead+import com.vayunmathur.securemail.platform.moveTo+import com.vayunmathur.securemail.platform.moveToTrash+import com.vayunmathur.securemail.platform.restoreFromTrash+import com.vayunmathur.securemail.platform.setRead import com.vayunmathur.securemail.ui.ComposeScreen import com.vayunmathur.securemail.ui.FolderActions import com.vayunmathur.securemail.ui.InboxScreen@@ -87,78 +96,103 @@ fun Navigation(viewModel: MailViewModel, initialRoute: Route? = null) {             }         },     ) {-        entry<Route.Onboarding> {-            OnboardingScreen(-                state = state,-                onClaim = { localPart, passphrase ->-                    viewModel.claimAddress(localPart, passphrase) {-                        // Protection enrolls immediately after claim: run the-                        // biometric gate as soon as the Lock screen lands.-                        (context as? FragmentActivity)?.let { viewModel.unlock(it) }-                    }-                },-                onDismissMessages = viewModel::dismissMessages,-            )-        }-        entry<Route.Lock> {-            LockScreen(-                state = state,-                onUnlock = {-                    (context as? FragmentActivity)?.let { viewModel.unlock(it) }-                },-                onDismissMessages = viewModel::dismissMessages,-            )-        }-        entry<Route.Inbox>(metadata = SiblingPage()) {-            InboxScreen(-                state = state,-                folder = viewModel.selectedFolder,-                actions = folderActions,-                messages = folderMessages,-            )-        }+        mainEntries(viewModel, backStack, state, folderMessages, allMessages, folderActions, context)         composerEntry(viewModel, backStack)-        entry<Route.Reader> { route ->-            val msg = remember(route.messageId, allMessages, folderMessages) {-                folderMessages.firstOrNull { it.id == route.messageId }-                    ?: allMessages.firstOrNull { it.id == route.messageId }-            }-            LaunchedEffect(route.messageId) {-                viewModel.decryptStored(route.messageId)-                viewModel.markRead(route.messageId)-            }-            ReaderScreen(-                state = state,-                onReply = { m ->-                    backStack.add(-                        Route.Composer(-                            to = m.from,-                            subject = "Re: ${m.decryptedSubject ?: ""}",-                            inReplyTo = m.id,-                            from = m.deliveredTo,-                        ),-                    )-                },-                onBack = { backStack.pop() },-                message = msg,-            )-        }         outEntry(viewModel, backStack)-        entry<Route.Settings>(metadata = SiblingPage()) {-            val identities by viewModel.identities.collectAsState(emptyList())-            SettingsScreen(-                state = state,-                identities = identities,-                onCreateAlias = viewModel::createAlias,-                onSetAliasDisabled = viewModel::setAliasDisabled,-                onExportPublicKey = viewModel::exportPublicKey,-                onForget = viewModel::forgetIdentity,-                onDismissMessages = viewModel::dismissMessages,-            )-        }     } } ++/** Onboarding, lock, inbox, reader and settings destinations. */+private fun EntryProviderScope<Route>.mainEntries(+    viewModel: MailViewModel,+    backStack: NavBackStack<Route>,+    state: MailUiState,+    folderMessages: List<StoredMessage>,+    allMessages: List<StoredMessage>,+    folderActions: FolderActions,+    context: android.content.Context,+) {+    entry<Route.Onboarding> {+        OnboardingScreen(+            state = state,+            onClaim = { localPart, passphrase ->+                viewModel.claimAddress(localPart, passphrase) {+                    // Protection enrolls immediately after claim: run the+                    // biometric gate as soon as the Lock screen lands.+                    (context as? FragmentActivity)?.let { viewModel.unlock(it) }+                }+            },+            onDismissMessages = viewModel::dismissMessages,+        )+    }+    entry<Route.Lock> {+        LockScreen(+            state = state,+            onUnlock = {+                (context as? FragmentActivity)?.let { viewModel.unlock(it) }+            },+            onDismissMessages = viewModel::dismissMessages,+        )+    }+    entry<Route.Inbox>(metadata = SiblingPage()) {+        InboxScreen(+            state = state,+            folder = viewModel.selectedFolder,+            actions = folderActions,+            messages = folderMessages,+        )+    }+    readerEntry(viewModel, backStack, state, folderMessages, allMessages)+    entry<Route.Settings>(metadata = SiblingPage()) {+        val identities by viewModel.identities.collectAsState(emptyList())+        SettingsScreen(+            state = state,+            identities = identities,+            onCreateAlias = viewModel::createAlias,+            onSetAliasDisabled = viewModel::setAliasDisabled,+            onExportPublicKey = viewModel::exportPublicKey,+            onForget = viewModel::forgetIdentity,+            onDismissMessages = viewModel::dismissMessages,+        )+    }+}+++/** Reader destination: decrypts and marks read on entry. */+private fun EntryProviderScope<Route>.readerEntry(+    viewModel: MailViewModel,+    backStack: NavBackStack<Route>,+    state: MailUiState,+    folderMessages: List<StoredMessage>,+    allMessages: List<StoredMessage>,+) {+entry<Route.Reader> { route ->+    val msg = remember(route.messageId, allMessages, folderMessages) {+        folderMessages.firstOrNull { it.id == route.messageId }+            ?: allMessages.firstOrNull { it.id == route.messageId }+    }+    LaunchedEffect(route.messageId) {+        viewModel.decryptStored(route.messageId)+        viewModel.markRead(route.messageId)+    }+    ReaderScreen(+        state = state,+        onReply = { m ->+            backStack.add(+                Route.Composer(+                    to = m.from,+                    subject = "Re: ${m.decryptedSubject ?: ""}",+                    inReplyTo = m.id,+                    from = m.deliveredTo,+                ),+            )+        },+        onBack = { backStack.pop() },+        message = msg,+    )+}+} /**  * Composer. Leaving with Back saves a draft (or updates the reopened one);  * Discard drops it; a successful send deletes it.
securemail/src/main/java/com/vayunmathur/securemail/Route.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/Route.kt b/securemail/src/main/java/com/vayunmathur/securemail/Route.ktindex efc493ba7d..3965fbdab6 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/Route.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/Route.kt@@ -8,17 +8,22 @@ object IntentState {     var navigationRoute: Route? = null } +/** Contract for route. */ @Serializable sealed interface Route : NavKey {+    /** Singleton holding onboarding state and operations. */     @Serializable     data object Onboarding : Route +    /** Singleton holding lock state and operations. */     @Serializable     data object Lock : Route +    /** Singleton holding inbox state and operations. */     @Serializable     data object Inbox : Route +    /** Immutable value describing composer. */     @Serializable     data class Composer(         val to: String = "",@@ -33,6 +38,7 @@ sealed interface Route : NavKey {         val from: String? = null,     ) : Route +    /** Immutable value describing reader; carries messageId. */     @Serializable     data class Reader(val messageId: String) : Route @@ -40,6 +46,7 @@ sealed interface Route : NavKey {     @Serializable     data object Out : Route +    /** Singleton holding settings state and operations. */     @Serializable     data object Settings : Route }
securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.ktindex 626f0c7a8d..80032c3cbb 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt@@ -24,6 +24,73 @@ object InboundStore {      * ([MailSocket.MsgFlags.spam]) routes to the Spam folder — independent of      * PGP signing (unsigned mail is accepted, not spam).      */++    /** Decrypts an encrypted frame into a stored message; null when it stays locked. */+    private suspend fun storeEncrypted(+        app: Context,+        msg: MailSocket.InboundMsg,+        deliveredTo: String,+        folder: MailFolder,+        raw: ByteArray,+        identity: MailIdentity?,+    ): StoredMessage? {+    val passphrase = KeyManager(app).getKeyPassphrase()+    return if (passphrase != null && identity != null) {+        runCatching {+            val pgpB64 = MimeCodec.extractPgpPayloadB64(raw)+            val pgpBytes = if (pgpB64 != null) {+                Base64.decode(pgpB64, Base64.DEFAULT)+            } else {+                raw+            }+            // Sender address is inside the encrypted payload — decrypt+            // first (verifier empty = no check yet), then resolve the+            // sender key and re-verify for the badge. Two-step because+            // the verifier key is only known after decryption.+            val provisional = PgpCrypto.decrypt(+                pgpBytes,+                identity.secretArmor,+                passphrase,+            ).toString(Charsets.UTF_8)+            val (_, _, claimedFrom) = MimeCodec.parseMime(provisional)+            val (mime, verified) = if (claimedFrom.isNotBlank()) {+                val senderKey = SenderKeys.resolve(app, claimedFrom)+                if (senderKey != null) {+                    val checked = PgpCrypto.decryptVerify(+                        pgpBytes,+                        identity.secretArmor,+                        passphrase,+                        senderKey,+                    )+                    checked.payload.toString(Charsets.UTF_8) to+                        checked.signerFingerprintHex.ifBlank { null }+                } else {+                    provisional to null+                }+            } else {+                provisional to null+            }+            val (subject, body, from, html) = MimeCodec.parseMime(mime)+            StoredMessage(+                id = msg.id,+                from = from,+                toJson = deliveredTo,+                dateMillis = System.currentTimeMillis(),+                messageId = msg.id,+                blobBase64 = Base64.encodeToString(raw, Base64.NO_WRAP),+                decryptedBody = body,+                decryptedSubject = subject,+                verifiedSigner = verified,+                unencrypted = false,+                folder = folder,+                decryptedHtml = html,+                deliveredTo = deliveredTo,+            )+        }.getOrNull()+    } else {+        null+    }+    }     suspend fun store(context: Context, msg: MailSocket.InboundMsg) {         val app = context.applicationContext         val repo = MailRepository.get(app)@@ -51,62 +118,7 @@ object InboundStore {             )             return         }-        val passphrase = KeyManager(app).getKeyPassphrase()-        val stored = if (passphrase != null && identity != null) {-            runCatching {-                val pgpB64 = MimeCodec.extractPgpPayloadB64(raw)-                val pgpBytes = if (pgpB64 != null) {-                    Base64.decode(pgpB64, Base64.DEFAULT)-                } else {-                    raw-                }-                // Sender address is inside the encrypted payload — decrypt-                // first (verifier empty = no check yet), then resolve the-                // sender key and re-verify for the badge. Two-step because-                // the verifier key is only known after decryption.-                val provisional = PgpCrypto.decrypt(-                    pgpBytes,-                    identity.secretArmor,-                    passphrase,-                ).toString(Charsets.UTF_8)-                val (_, _, claimedFrom) = MimeCodec.parseMime(provisional)-                val (mime, verified) = if (claimedFrom.isNotBlank()) {-                    val senderKey = SenderKeys.resolve(app, claimedFrom)-                    if (senderKey != null) {-                        val checked = PgpCrypto.decryptVerify(-                            pgpBytes,-                            identity.secretArmor,-                            passphrase,-                            senderKey,-                        )-                        checked.payload.toString(Charsets.UTF_8) to-                            checked.signerFingerprintHex.ifBlank { null }-                    } else {-                        provisional to null-                    }-                } else {-                    provisional to null-                }-                val (subject, body, from, html) = MimeCodec.parseMime(mime)-                StoredMessage(-                    id = msg.id,-                    from = from,-                    toJson = deliveredTo,-                    dateMillis = System.currentTimeMillis(),-                    messageId = msg.id,-                    blobBase64 = Base64.encodeToString(raw, Base64.NO_WRAP),-                    decryptedBody = body,-                    decryptedSubject = subject,-                    verifiedSigner = verified,-                    unencrypted = false,-                    folder = folder,-                    decryptedHtml = html,-                    deliveredTo = deliveredTo,-                )-            }.getOrNull()-        } else {-            null-        }+        val stored = storeEncrypted(app, msg, deliveredTo, folder, raw, identity)         repo.messageDao().upsert(             stored ?: StoredMessage(                 id = msg.id,
securemail/src/main/java/com/vayunmathur/securemail/data/MailConfig.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/MailConfig.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/MailConfig.ktindex 9a21a6993a..1a9d478824 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/data/MailConfig.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/MailConfig.kt@@ -56,12 +56,15 @@ class MailConfig(context: Context) {         dataStore.edit { it.clear() }     } +    /** Shared constants and helpers for MailConfig. */     companion object {         @Volatile         private var sharedStore: androidx.datastore.core.DataStore<androidx.datastore.preferences.core.Preferences>? =             null -        private fun store(app: Context): androidx.datastore.core.DataStore<androidx.datastore.preferences.core.Preferences> =+        private fun store(+            app: Context,+        ): androidx.datastore.core.DataStore<androidx.datastore.preferences.core.Preferences> =             sharedStore ?: synchronized(this) {                 sharedStore ?: app.applicationContext.mailDataStore.also { sharedStore = it }             }
securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.ktindex fbb58d1632..ad4b6de323 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt@@ -98,6 +98,7 @@ data class MailIdentity(     val createdMillis: Long, ) +/** Contract for message dao. */ @Dao interface MessageDao {     @Query("SELECT * FROM StoredMessage ORDER BY dateMillis DESC")@@ -138,6 +139,7 @@ interface MessageDao {     suspend fun deleteAll(ids: List<String>) } +/** Contract for key dao. */ @Dao interface KeyDao {     @Query("SELECT * FROM CachedKey WHERE address = :address LIMIT 1")@@ -147,6 +149,7 @@ interface KeyDao {     suspend fun upsert(key: CachedKey) } +/** Contract for outbox dao. */ @Dao interface OutboxDao {     @Query("SELECT * FROM OutboxMessage ORDER BY createdMillis ASC")@@ -168,6 +171,7 @@ interface OutboxDao {     suspend fun noteAttempt(rowId: Long, error: String) } +/** Contract for identity dao. */ @Dao interface IdentityDao {     @Query("SELECT * FROM MailIdentity ORDER BY isPrimary DESC, createdMillis ASC")@@ -200,12 +204,14 @@ interface IdentityDao {     version = 5,     exportSchema = false, )+/** Mail Database: a room database implementation for mail database. */ abstract class MailDatabase : RoomDatabase() {     abstract fun messageDao(): MessageDao     abstract fun keyDao(): KeyDao     abstract fun outboxDao(): OutboxDao     abstract fun identityDao(): IdentityDao +    /** Shared constants and helpers for MailDatabase. */     companion object : DatabaseMigrations {         /**          * v1 → v2: drops the `sendUnencrypted` column from OutboxMessage (the
securemail/src/main/java/com/vayunmathur/securemail/data/MailRepository.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/MailRepository.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/MailRepository.ktindex 9e437d54e9..2a40c7072e 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/data/MailRepository.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/MailRepository.kt@@ -15,6 +15,7 @@ class MailRepository private constructor(context: Context) :     override fun outboxDao(): OutboxDao = db.outboxDao()     override fun identityDao(): IdentityDao = db.identityDao() +    /** Shared constants and helpers for MailRepository. */     companion object {         @Volatile private var instance: MailRepository? = null         fun get(context: Context): MailRepository =
securemail/src/main/java/com/vayunmathur/securemail/domain/mail/KeyLookupPolicy.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/KeyLookupPolicy.kt b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/KeyLookupPolicy.ktindex f928434f1b..efe8d1e511 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/KeyLookupPolicy.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/KeyLookupPolicy.kt@@ -20,9 +20,13 @@ object KeyLookupPolicy {      /** Where a recipient's usable public key came from, or why there is none. */     sealed interface KeySource {+        /** Singleton holding own directory state and operations. */         data object OwnDirectory : KeySource+        /** Singleton holding wkd state and operations. */         data object Wkd : KeySource+        /** Singleton holding cached state and operations. */         data object Cached : KeySource+        /** Singleton holding none state and operations. */         data object None : KeySource     } 
securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt b/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.ktindex 722a5e98cb..96edeef3dd 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt@@ -45,6 +45,16 @@ import kotlinx.serialization.json.Json  * server only accepts PUB from addresses this socket authenticated.  */ object MailSocket {+    // Wire framing: one opcode byte, then big-endian length fields.+    private const val OP_BYTES = 1+    private const val FLAGS_BYTES = 1+    private const val LEN16_BYTES = 2+    private const val LEN32_BYTES = 4+    private const val BYTE_MASK = 0xFF+    private const val SHIFT_8 = 8+    private const val SHIFT_16 = 16+    private const val SHIFT_24 = 24+    private const val LAST_BYTE = 3      const val WS_URL = "wss://mail.maemail.org/mail/ws" @@ -119,8 +129,10 @@ object MailSocket {      val connected: Boolean get() = session != null +    /** Immutable value describing key result; carries address, armoredPublic. */     data class KeyResult(val address: String, val armoredPublic: String?) +    /** Immutable value describing identity snapshot; carries address, armoredPublic. */     data class IdentitySnapshot(val address: String, val armoredPublic: String)      /**@@ -198,6 +210,8 @@ object MailSocket {      * session's challenge via [sign] and waits for SUBRESP. Returns the      * [SUB_OK]…[SUB_INVALID] status, or null when offline / timed out.      */+    // Any failure (offline, timeout, signing) means the claim did not land: null, logged.+    @Suppress("TooGenericExceptionCaught")     suspend fun claim(address: String, armoredPublic: String, sign: suspend (ByteArray) -> ByteArray): Int? {         val s = session ?: return null         val n = nonce ?: return null@@ -244,6 +258,8 @@ object MailSocket {         private set      /** Directory lookup over the socket (request/response with timeout). */+    // Any failure (offline, timeout) means no key: null, logged.+    @Suppress("TooGenericExceptionCaught")     suspend fun getKey(address: String): KeyResult? {         val s = session ?: return null         val key = address.lowercase()@@ -261,6 +277,8 @@ object MailSocket {     }      /** Fetch one backlog message's blob by id (for missed fan-outs / fresh devices). */+    // Any failure (offline, timeout) means no blob: null, logged.+    @Suppress("TooGenericExceptionCaught")     suspend fun fetch(id: String): ByteArray? {         val s = session ?: return null         val deferred = CompletableDeferred<ByteArray?>()@@ -358,85 +376,88 @@ object MailSocket {     internal fun subFrame(address: String, signature: ByteArray, armoredPublic: String): ByteArray {         val addr = address.lowercase().toByteArray(Charsets.UTF_8)         val key = armoredPublic.toByteArray(Charsets.UTF_8)-        val out = ByteArray(1 + 2 + addr.size + 2 + signature.size + key.size)+        val out = ByteArray(OP_BYTES + LEN16_BYTES + addr.size + LEN16_BYTES + signature.size + key.size)         out[0] = OP_SUB-        putU16(out, 1, addr.size)-        addr.copyInto(out, 3)-        putU16(out, 3 + addr.size, signature.size)-        signature.copyInto(out, 5 + addr.size)-        key.copyInto(out, 5 + addr.size + signature.size)+        putU16(out, OP_BYTES, addr.size)+        addr.copyInto(out, OP_BYTES + LEN16_BYTES)+        putU16(out, OP_BYTES + LEN16_BYTES + addr.size, signature.size)+        signature.copyInto(out, OP_BYTES + LEN16_BYTES + LEN16_BYTES + addr.size)+        key.copyInto(out, OP_BYTES + LEN16_BYTES + LEN16_BYTES + addr.size + signature.size)         return out     }      internal fun pubFrame(from: String, recipient: String, raw: ByteArray, unencrypted: Boolean): ByteArray {         val sender = from.lowercase().toByteArray(Charsets.UTF_8)         val rcpt = recipient.lowercase().toByteArray(Charsets.UTF_8)-        val out = ByteArray(1 + 1 + 2 + sender.size + 2 + rcpt.size + raw.size)+        val out = ByteArray(OP_BYTES + FLAGS_BYTES + LEN16_BYTES + sender.size + LEN16_BYTES + rcpt.size + raw.size)         out[0] = OP_PUB         out[1] = if (unencrypted) FLAG_PLAIN else 0-        putU16(out, 2, sender.size)-        sender.copyInto(out, 4)-        putU16(out, 4 + sender.size, rcpt.size)-        rcpt.copyInto(out, 6 + sender.size)-        raw.copyInto(out, 6 + sender.size + rcpt.size)+        putU16(out, OP_BYTES + FLAGS_BYTES, sender.size)+        sender.copyInto(out, OP_BYTES + FLAGS_BYTES + LEN16_BYTES)+        putU16(out, OP_BYTES + FLAGS_BYTES + LEN16_BYTES + sender.size, rcpt.size)+        rcpt.copyInto(out, OP_BYTES + FLAGS_BYTES + LEN16_BYTES + LEN16_BYTES + sender.size)+        raw.copyInto(out, OP_BYTES + FLAGS_BYTES + LEN16_BYTES + LEN16_BYTES + sender.size + rcpt.size)         return out     }      internal fun getKeyFrame(address: String): ByteArray {         val addr = address.lowercase().toByteArray(Charsets.UTF_8)-        val out = ByteArray(1 + 2 + addr.size)+        val out = ByteArray(OP_BYTES + LEN16_BYTES + addr.size)         out[0] = OP_GETKEY_REQ-        putU16(out, 1, addr.size)-        addr.copyInto(out, 3)+        putU16(out, OP_BYTES, addr.size)+        addr.copyInto(out, OP_BYTES + LEN16_BYTES)         return out     }      internal fun fetchFrame(id: String): ByteArray {         val raw = id.toByteArray(Charsets.UTF_8)-        val out = ByteArray(1 + 2 + raw.size)+        val out = ByteArray(OP_BYTES + LEN16_BYTES + raw.size)         out[0] = OP_FETCH_REQ         putU16(out, 1, raw.size)-        raw.copyInto(out, 3)+        raw.copyInto(out, OP_BYTES + LEN16_BYTES)         return out     }      /** MSG: [0x03][flags][u32 idLen][id][u16 rcptLen][rcpt][raw…]. */     internal fun parseMsg(buf: ByteArray): InboundMsg? {-        if (buf.size < 1 + 1 + 4 + 2) return null-        val flags = buf[1].toInt() and 0xFF+        if (buf.size < OP_BYTES + FLAGS_BYTES + LEN32_BYTES + LEN16_BYTES) return null+        val flags = buf[OP_BYTES].toInt() and BYTE_MASK         val parsed = MsgFlags(             unencrypted = (flags and FLAG_PLAIN.toInt()) != 0,             spam = (flags and FLAG_SPAM.toInt()) != 0,         )-        val idLen = readU32(buf, 2)-        if (idLen < 0 || buf.size < 6 + idLen + 2) return null-        val id = buf.copyOfRange(6, 6 + idLen).toString(Charsets.UTF_8)-        val rcptOff = 6 + idLen+        val idLen = readU32(buf, OP_BYTES + FLAGS_BYTES)+        if (idLen < 0 || buf.size < OP_BYTES + FLAGS_BYTES + LEN32_BYTES + idLen + LEN16_BYTES) return null+        val idStart = OP_BYTES + FLAGS_BYTES + LEN32_BYTES+        val id = buf.copyOfRange(idStart, idStart + idLen).toString(Charsets.UTF_8)+        val rcptOff = OP_BYTES + FLAGS_BYTES + LEN32_BYTES + idLen         val rcptLen = readU16(buf, rcptOff)-        if (buf.size < rcptOff + 2 + rcptLen) return null-        val rcpt = buf.copyOfRange(rcptOff + 2, rcptOff + 2 + rcptLen).toString(Charsets.UTF_8)-        val raw = buf.copyOfRange(rcptOff + 2 + rcptLen, buf.size)+        if (buf.size < rcptOff + LEN16_BYTES + rcptLen) return null+        val rcpt = buf.copyOfRange(rcptOff + LEN16_BYTES, rcptOff + LEN16_BYTES + rcptLen).toString(Charsets.UTF_8)+        val raw = buf.copyOfRange(rcptOff + LEN16_BYTES + rcptLen, buf.size)         return InboundMsg(id, parsed, rcpt, raw)     }      /** SUBRESP: [0x09][status][u16 addrLen][address] → (address, status). */     internal fun parseSubResp(buf: ByteArray): Pair<String, Int>? {-        if (buf.size < 1 + 1 + 2) return null-        val status = buf[1].toInt() and 0xFF-        val addrLen = readU16(buf, 2)-        if (buf.size < 4 + addrLen) return null-        return buf.copyOfRange(4, 4 + addrLen).toString(Charsets.UTF_8) to status+        if (buf.size < OP_BYTES + FLAGS_BYTES + LEN16_BYTES) return null+        val status = buf[OP_BYTES].toInt() and BYTE_MASK+        val addrLen = readU16(buf, OP_BYTES + FLAGS_BYTES)+        if (buf.size < OP_BYTES + FLAGS_BYTES + LEN16_BYTES + addrLen) return null+        val addrStart = OP_BYTES + FLAGS_BYTES + LEN16_BYTES+        return buf.copyOfRange(addrStart, addrStart + addrLen).toString(Charsets.UTF_8) to status     }      /** KEYRESP: [0x05][status][u16 addrLen][address][key…] → (address, key?). */     internal fun parseKeyResp(buf: ByteArray): Pair<String, String?>? {-        if (buf.size < 1 + 1 + 2) return null-        val status = buf[1].toInt()-        val addrLen = readU16(buf, 2)-        if (buf.size < 4 + addrLen) return null-        val addr = buf.copyOfRange(4, 4 + addrLen).toString(Charsets.UTF_8)-        val key = if (status == KEY_FOUND && buf.size > 4 + addrLen) {-            buf.copyOfRange(4 + addrLen, buf.size).toString(Charsets.UTF_8)+        if (buf.size < OP_BYTES + FLAGS_BYTES + LEN16_BYTES) return null+        val status = buf[OP_BYTES].toInt()+        val addrLen = readU16(buf, OP_BYTES + FLAGS_BYTES)+        if (buf.size < OP_BYTES + FLAGS_BYTES + LEN16_BYTES + addrLen) return null+        val addrStart = OP_BYTES + FLAGS_BYTES + LEN16_BYTES+        val addr = buf.copyOfRange(addrStart, addrStart + addrLen).toString(Charsets.UTF_8)+        val key = if (status == KEY_FOUND && buf.size > OP_BYTES + FLAGS_BYTES + LEN16_BYTES + addrLen) {+            buf.copyOfRange(OP_BYTES + FLAGS_BYTES + LEN16_BYTES + addrLen, buf.size).toString(Charsets.UTF_8)         } else {             null         }@@ -445,26 +466,26 @@ object MailSocket {      /** FETCHED: [0x07][u16 idLen][id][raw…] → (id, raw). */     internal fun parseFetched(buf: ByteArray): Pair<String, ByteArray>? {-        if (buf.size < 1 + 2) return null-        val idLen = readU16(buf, 1)-        if (buf.size < 3 + idLen) return null-        val id = buf.copyOfRange(3, 3 + idLen).toString(Charsets.UTF_8)-        return id to buf.copyOfRange(3 + idLen, buf.size)+        if (buf.size < OP_BYTES + LEN16_BYTES) return null+        val idLen = readU16(buf, OP_BYTES)+        if (buf.size < OP_BYTES + LEN16_BYTES + idLen) return null+        val id = buf.copyOfRange(OP_BYTES + LEN16_BYTES, OP_BYTES + LEN16_BYTES + idLen).toString(Charsets.UTF_8)+        return id to buf.copyOfRange(OP_BYTES + LEN16_BYTES + idLen, buf.size)     }      internal fun putU16(dst: ByteArray, off: Int, v: Int) {-        dst[off] = (v shr 8).toByte()+        dst[off] = (v shr SHIFT_8).toByte()         dst[off + 1] = v.toByte()     }      internal fun readU16(src: ByteArray, off: Int): Int =-        ((src[off].toInt() and 0xFF) shl 8) or (src[off + 1].toInt() and 0xFF)+        ((src[off].toInt() and BYTE_MASK) shl SHIFT_8) or (src[off + 1].toInt() and BYTE_MASK)      internal fun readU32(src: ByteArray, off: Int): Int =-        ((src[off].toInt() and 0xFF) shl 24) or-            ((src[off + 1].toInt() and 0xFF) shl 16) or-            ((src[off + 2].toInt() and 0xFF) shl 8) or-            (src[off + 3].toInt() and 0xFF)+        ((src[off].toInt() and BYTE_MASK) shl SHIFT_24) or+            ((src[off + 1].toInt() and BYTE_MASK) shl SHIFT_16) or+            ((src[off + 2].toInt() and BYTE_MASK) shl SHIFT_8) or+            (src[off + LAST_BYTE].toInt() and BYTE_MASK) }  /** Minimal REST surface: WKD runs over plain HTTPS, not the relay socket. */
securemail/src/main/java/com/vayunmathur/securemail/platform/DraftsController.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/DraftsController.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/DraftsController.ktindex 1f90af8d1e..bc48b75802 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/DraftsController.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/DraftsController.kt@@ -71,6 +71,7 @@ class DraftsController(         val inReplyTo: String? = null,     ) +    /** Shared constants and helpers for DraftsController. */     companion object {         private val json = Json { ignoreUnknownKeys = true } 
securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.ktindex 1997087967..6ccc55e7b4 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt@@ -25,6 +25,8 @@ import kotlin.time.Duration.Companion.minutes  */ class MailSyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) { +    // The worker contract is success/retry; every failure retries, logged.+    @Suppress("TooGenericExceptionCaught")     override suspend fun doWork(): Result {         val settings = MailConfig(applicationContext).settings.first()         if (settings.address.isBlank()) return Result.success()@@ -44,17 +46,20 @@ class MailSyncWorker(context: Context, params: WorkerParameters) : CoroutineWork                 onMessage = { msg -> InboundStore.store(applicationContext, msg) },             )             // Give the SUB + backlog drain time to complete within the worker.-            kotlinx.coroutines.delay(20_000)+            kotlinx.coroutines.delay(SYNC_DRAIN_MS)             Result.success()         } catch (e: Exception) {+            // The worker's contract is success/retry; every failure retries, logged.             Log.status(TAG, "sync worker failed", e)             Result.retry()         }     } +    /** Shared constants and helpers for MailSyncWorker. */     companion object {         private const val TAG = "MailSyncWorker"         private const val WORK_NAME = "securemail_sync"+        private const val SYNC_DRAIN_MS = 20_000L          fun schedule(context: Context) {             startRepeatedTask<MailSyncWorker>(context, WORK_NAME, 15.minutes)
securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.ktindex 5d2bfc6cca..f57e7568a1 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt@@ -53,6 +53,7 @@ data class MailUiState( )  private const val TAG = "MailViewModel"+private const val MIN_PASSPHRASE_LENGTH = 8  /**  * Owns identity, decryption, send gating, and the socket lifecycle.@@ -60,7 +61,7 @@ private const val TAG = "MailViewModel"  */ class MailViewModel(     app: Application,-    private val repo: com.vayunmathur.securemail.data.MailStore,+    internal val repo: com.vayunmathur.securemail.data.MailStore, ) : AndroidViewModel(app) {      /** Production constructor used by `by viewModels()` (reflective lookup). */@@ -168,28 +169,19 @@ class MailViewModel(     }      /** Moves messages to Trash (local vault only). */-    fun moveToTrash(ids: List<String>) = moveTo(ids, MailFolder.TRASH)      /** Moves messages to [folder]; also the undo for a Trash move. */-    fun moveTo(ids: List<String>, folder: MailFolder) = io { repo.messageDao().moveTo(ids, folder) }      /** Restores trashed messages to the Inbox. */-    fun restoreFromTrash(ids: List<String>) = moveTo(ids, MailFolder.INBOX)      /** Permanently deletes messages (local only). */-    fun deleteForever(ids: List<String>) = io { repo.messageDao().deleteAll(ids) } -    fun setRead(ids: List<String>, read: Boolean) = io { repo.messageDao().setRead(ids, read) } -    private fun io(block: suspend () -> Unit) {+    internal fun io(block: suspend () -> Unit) {         viewModelScope.launch(Dispatchers.IO) { block() }     }      /** Permanently deletes everything in Trash (local only). */-    fun emptyTrash() = io {-        repo.messageDao().emptyTrash()-        state = state.copy(message = "Trash emptied.")-    }      /**      * In-memory S2K passphrase for the PGP secret ring. Sealed in@@ -203,6 +195,11 @@ class MailViewModel(      * Returns the S2K passphrase, loading it from Keystore-wrapped storage      * on first use. Must be called on Dispatchers.IO (Keystore I/O).      */+    fun emptyTrash() = io {+        repo.messageDao().emptyTrash()+        state = state.copy(message = "Trash emptied.")+    }+     private fun requirePassphrase(): String =         passphraseCache ?: keyManager.getKeyPassphrase()?.also { passphraseCache = it }         ?: error("No key passphrase stored — restore from your recovery passphrase.")@@ -247,7 +244,7 @@ class MailViewModel(             state = state.copy(error = "Use 3–64 lowercase letters, digits, dots or dashes.")             return         }-        if (passphrase.length < 8) {+        if (passphrase.length < MIN_PASSPHRASE_LENGTH) {             state = state.copy(error = "Use a passphrase of at least 8 characters.")             return         }@@ -436,15 +433,6 @@ class MailViewModel(         }     } -    /** Extracts the raw PGP bytes from an RFC 3156 multipart/encrypted envelope. */-    private fun extractPgpPayload(envelope: ByteArray): ByteArray? {-        val b64 = MimeCodec.extractPgpPayloadB64(envelope) ?: return null-        return try {-            Base64.decode(b64, Base64.DEFAULT)-        } catch (_: IllegalArgumentException) {-            null-        }-    }      // ------------------------------------------------------------------     // Outbound: trust gate + publish@@ -670,67 +658,8 @@ class MailViewModel(                     state = state.copy(error = "Relay offline — kept in outbox.")                     return@withContext                 }-                val pending = repo.outboxDao().all()-                var sent = 0-                var failed = 0-                val ownPassphrase = requirePassphrase()-                for (entry in pending) {-                    var reason = "relay publish failed"-                    val ok = runCatching {-                        val sender = senderIdentity(entry.fromAddress)-                        val ownSecret = sender.secretArmor-                        val to = entry.toJson.split(",").map { it.trim() }.filter { it.isNotEmpty() }-                        val mime = buildMimeBody(sender.address, entry.subject, entry.body)-                        var entryOk = true-                        for (address in to) {-                            val cached = repo.keyDao().get(address)-                            val published = if (cached != null) {-                                val raw = try {-                                    PgpCrypto.encryptSigned(-                                        mime, cached.armoredPublic, ownSecret, ownPassphrase,-                                    )-                                } catch (e: Exception) {-                                    reason = "encrypt failed: " +-                                        (e.message?.takeIf { it.isNotBlank() } ?: e.javaClass.simpleName)-                                    Log.status(TAG, "outbox encrypt failed", e)-                                    null-                                }-                                if (raw == null) {-                                    false-                                } else if (MailSocket.publish(sender.address, address, buildEncryptedBody(raw))) {-                                    true-                                } else {-                                    reason = "publish failed: " +-                                        (MailSocket.lastPublishError ?: "socket write failed")-                                    false-                                }-                            } else {-                                if (MailSocket.publish(sender.address, address, mime, unencrypted = true)) {-                                    true-                                } else {-                                    reason = "publish failed: " +-                                        (MailSocket.lastPublishError ?: "socket write failed")-                                    false-                                }-                            }-                            if (!published) entryOk = false-                        }-                        entryOk-                    }.onFailure {-                        if (reason == "relay publish failed") {-                            reason = "outbox error: " +-                                (it.message?.takeIf { m -> m.isNotBlank() } ?: it.javaClass.simpleName)-                        }-                        Log.status(TAG, "outbox entry failed", it)-                    }.getOrDefault(false)-                    if (ok) {-                        repo.outboxDao().delete(entry.rowId)-                        sent++-                    } else {-                        repo.outboxDao().noteAttempt(entry.rowId, reason)-                        failed++-                    }-                }+                val (sent, failed) = OutboxRetry(repo, ::requirePassphrase) { senderIdentity(it) }+                    .retryAll()                 state = when {                     failed > 0 -> state.copy(error = "$failed message(s) still queued.")                     sent > 0 -> state.copy(message = "Sent $sent message(s).")@@ -750,9 +679,43 @@ class MailViewModel(         }     } -    fun markRead(id: String) = io { repo.messageDao().markRead(id) } -    fun envelopeOf(stored: StoredMessage): MessageEnvelope = MessageEnvelope(+    fun dismissMessages() {+        state = state.copy(message = null, error = null, exportArmor = null)+    }++}++/** Moves messages to the trash folder. */+fun MailViewModel.moveToTrash(ids: List<String>) = moveTo(ids, MailFolder.TRASH)++/** Moves messages to [folder]. */+fun MailViewModel.moveTo(ids: List<String>, folder: MailFolder) = io { repo.messageDao().moveTo(ids, folder) }++/** Restores messages from trash to the inbox. */+fun MailViewModel.restoreFromTrash(ids: List<String>) = moveTo(ids, MailFolder.INBOX)++/** Permanently deletes messages. */+fun MailViewModel.deleteForever(ids: List<String>) = io { repo.messageDao().deleteAll(ids) }++/** Sets the read flag on messages. */+fun MailViewModel.setRead(ids: List<String>, read: Boolean) = io { repo.messageDao().setRead(ids, read) }++/** Marks one message read. */+fun MailViewModel.markRead(id: String) = io { repo.messageDao().markRead(id) }++    /** Extracts the raw PGP bytes from an RFC 3156 multipart/encrypted envelope. */+/** Extracts the raw PGP bytes from an RFC 3156 multipart/encrypted envelope. */+private fun extractPgpPayload(envelope: ByteArray): ByteArray? {+        val b64 = MimeCodec.extractPgpPayloadB64(envelope) ?: return null+        return try {+            Base64.decode(b64, Base64.DEFAULT)+        } catch (_: IllegalArgumentException) {+            null+        }+    }+/** The list-display envelope for a stored message. */+fun MailViewModel.envelopeOf(stored: StoredMessage): MessageEnvelope = MessageEnvelope(         id = stored.id,         from = stored.from,         to = runCatching {@@ -763,13 +726,3 @@ class MailViewModel(         unencrypted = stored.unencrypted,     ) -    fun dismissMessages() {-        state = state.copy(message = null, error = null, exportArmor = null)-    }--    private fun buildMimeBody(from: String, subject: String, body: String): ByteArray =-        MimeCodec.buildPlainBody(from, subject, body, MimeCodec.newMessageId())--    private fun buildEncryptedBody(encrypted: ByteArray): ByteArray =-        MimeCodec.buildEncryptedEnvelope(PgpCrypto.armorMessage(encrypted))-}
securemail/src/main/java/com/vayunmathur/securemail/platform/OutboxRetry.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/OutboxRetry.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/OutboxRetry.ktnew file mode 100644index 0000000000..f04aef69b8--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/OutboxRetry.kt@@ -0,0 +1,126 @@+package com.vayunmathur.securemail.platform++import com.vayunmathur.library.log.Log+import com.vayunmathur.securemail.data.MailIdentity+import com.vayunmathur.securemail.data.MailStore+import com.vayunmathur.securemail.network.MailSocket+import com.vayunmathur.securemail.domain.mail.MimeCodec+import com.vayunmathur.securemail.domain.pgp.PgpCrypto++/** The plain MIME body for an outbound message. */+internal fun buildMimeBody(from: String, subject: String, body: String): ByteArray =+    MimeCodec.buildPlainBody(from, subject, body, MimeCodec.newMessageId())++/** The encrypted envelope wrapping an encrypted MIME body. */+internal fun buildEncryptedBody(encrypted: ByteArray): ByteArray =+    MimeCodec.buildEncryptedEnvelope(PgpCrypto.armorMessage(encrypted))++/**+ * Drains the local outbox straight to the server over the live socket —+ * no trust re-resolution (that already happened at send time).+ *+ * Key-known recipients re-encrypt to the cached key; keyless recipients+ * publish as plaintext frames for the server to federate. Entries stay+ * queued while offline; anything still failing after publish records an+ * attempt reason.+ */+internal class OutboxRetry(+    private val repo: MailStore,+    private val requirePassphrase: () -> String,+    private val senderIdentity: suspend (String?) -> MailIdentity,+) {+    /** Retries every queued entry; returns (sent, failed) counts. */+    suspend fun retryAll(): Pair<Int, Int> {+        val pending = repo.outboxDao().all()+        var sent = 0+        var failed = 0+        val ownPassphrase = requirePassphrase()+        for (entry in pending) {+            if (retryEntry(entry, ownPassphrase)) {+                repo.outboxDao().delete(entry.rowId)+                sent+++            } else {+                failed+++            }+        }+        return sent to failed+    }++    /** One queued entry: publish to every recipient; true when all publish. */+    // Per-entry encryption can fail for any crypto reason; the entry stays queued, logged.+    @Suppress("TooGenericExceptionCaught")+    private suspend fun retryEntry(+        entry: com.vayunmathur.securemail.data.OutboxMessage,+        ownPassphrase: String,+    ): Boolean {+        var reason = "relay publish failed"+        val ok = runCatching {+            val sender = senderIdentity(entry.fromAddress)+            val ownSecret = sender.secretArmor+            val to = entry.toJson.split(",").map { it.trim() }.filter { it.isNotEmpty() }+            val mime = buildMimeBody(sender.address, entry.subject, entry.body)+            var entryOk = true+            for (address in to) {+                if (!publishTo(address, sender, mime, ownSecret, ownPassphrase) { reason = it }) {+                    entryOk = false+                }+            }+            entryOk+        }.onFailure {+            if (reason == "relay publish failed") {+                reason = "outbox error: " ++                    (it.message?.takeIf { m -> m.isNotBlank() } ?: it.javaClass.simpleName)+            }+            Log.status(TAG, "outbox entry failed", it)+        }.getOrDefault(false)+        if (!ok) repo.outboxDao().noteAttempt(entry.rowId, reason)+        return ok+    }++    /** Publishes one entry to one recipient; [setReason] records why it failed. */+    // Any crypto failure leaves the entry queued with the reason recorded.+    @Suppress("TooGenericExceptionCaught")+    private suspend fun publishTo(+        address: String,+        sender: MailIdentity,+        mime: ByteArray,+        ownSecret: String,+        ownPassphrase: String,+        setReason: (String) -> Unit,+    ): Boolean {+        val cached = repo.keyDao().get(address)+        return if (cached != null) {+            val raw = try {+                PgpCrypto.encryptSigned(+                    mime, cached.armoredPublic, ownSecret, ownPassphrase,+                )+            } catch (e: Exception) {+                setReason(+                    "encrypt failed: " ++                        (e.message?.takeIf { it.isNotBlank() } ?: e.javaClass.simpleName),+                )+                Log.status(TAG, "outbox encrypt failed", e)+                null+            }+            if (raw == null) {+                false+            } else if (MailSocket.publish(sender.address, address, buildEncryptedBody(raw))) {+                true+            } else {+                setReason("publish failed: " + (MailSocket.lastPublishError ?: "socket write failed"))+                false+            }+        } else {+            if (MailSocket.publish(sender.address, address, mime, unencrypted = true)) {+                true+            } else {+                setReason("publish failed: " + (MailSocket.lastPublishError ?: "socket write failed"))+                false+            }+        }+    }++    private companion object {+        const val TAG = "MailViewModel"+    }+}
securemail/src/main/java/com/vayunmathur/securemail/platform/crypto/KeyManager.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/crypto/KeyManager.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/crypto/KeyManager.ktindex eda200a7cd..38ff0b60a6 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/crypto/KeyManager.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/crypto/KeyManager.kt@@ -18,6 +18,10 @@ import com.vayunmathur.library.util.DatabaseHelper  * secret is read.  */ class KeyManager(context: Context) : DatabaseHelper(context) {++    private companion object {+        const val GCM_TAG_BITS = 128+    }     override val keyStoreAlias = "securemail_master_key"     override val sharedPrefsName = "securemail_secure_prefs"     override val passphraseKey = "encrypted_pgp_secret"@@ -68,7 +72,7 @@ class KeyManager(context: Context) : DatabaseHelper(context) {             cipher.init(                 javax.crypto.Cipher.DECRYPT_MODE,                 getSecretKey(),-                javax.crypto.spec.GCMParameterSpec(128, Base64.decode(iv, Base64.NO_WRAP)),+                javax.crypto.spec.GCMParameterSpec(GCM_TAG_BITS, Base64.decode(iv, Base64.NO_WRAP)),             )             String(cipher.doFinal(Base64.decode(enc, Base64.NO_WRAP)), Charsets.UTF_8)         } catch (_: Exception) {
securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt b/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.ktindex fda0490cf7..19928d8994 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt@@ -65,6 +65,7 @@ class MailSocketService : Service() {         return builder.build()     } +    /** Shared constants and helpers for MailSocketService. */     companion object {         private const val CHANNEL_ID = "securemail_relay"         private const val NOTIFICATION_ID = 4101