Modern Apps git

← Modern-Apps.git

securemail: shared arrival store, worker never kills socket

Commit
2b9fa085e4a4ae3f845a01c19d66d1d13d06323e
Author
vayun-mathur <[email protected]>
When
2026-10-24 04:42 UTC (1 month ago)
Parents
9ca626e

Diff

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.ktnew file mode 100644index 0000000000..fa7286f2be--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt@@ -0,0 +1,94 @@+package com.vayunmathur.securemail.data++import android.content.Context+import android.util.Base64+import com.vayunmathur.securemail.domain.mail.MimeCodec+import com.vayunmathur.securemail.domain.pgp.PgpCrypto+import com.vayunmathur.securemail.platform.crypto.KeyManager+import kotlinx.coroutines.flow.first++/**+ * Single choke point for inbound socket frames (relay MSG + SMTP-ingested+ * blobs): writes to the Room vault, decrypting immediately when the Keystore+ * holds the S2K passphrase. Used by both [MailSocketService] (live socket)+ * and [MailSyncWorker] (background drain) so arrival behavior is identical+ * everywhere — no caller duplicates this logic.+ */+object InboundStore {++    /**+     * Stores one inbound frame. Encrypted frames decrypt on arrival (S2K+     * passphrase loads transparently from Keystore-wrapped storage);+     * unencrypted frames parse their MIME envelope directly; undecryptable+     * frames persist as locked blobs for later retry.+     */+    suspend fun store(+        context: Context,+        id: String,+        unencrypted: Boolean,+        raw: ByteArray,+    ) {+        val app = context.applicationContext+        val repo = MailRepository.get(app)+        val settings = MailConfig(app).settings.first()+        val keyManager = KeyManager(app)+        if (unencrypted) {+            val (subject, body, from) = MimeCodec.parseMime(raw.toString(Charsets.UTF_8))+            repo.messageDao().upsert(+                StoredMessage(+                    id = id,+                    from = from,+                    toJson = settings.address,+                    dateMillis = System.currentTimeMillis(),+                    messageId = id,+                    blobBase64 = "",+                    decryptedBody = body,+                    decryptedSubject = subject,+                    unencrypted = true,+                ),+            )+            return+        }+        val passphrase = keyManager.getKeyPassphrase()+        val stored = if (passphrase != null) {+            runCatching {+                val pgpB64 = MimeCodec.extractPgpPayloadB64(raw)+                val pgpBytes = if (pgpB64 != null) {+                    Base64.decode(pgpB64, Base64.DEFAULT)+                } else {+                    raw+                }+                val mime = PgpCrypto.decrypt(+                    pgpBytes,+                    keyManager.getSecretArmor(),+                    passphrase,+                ).toString(Charsets.UTF_8)+                val (subject, body, from) = MimeCodec.parseMime(mime)+                StoredMessage(+                    id = id,+                    from = from,+                    toJson = settings.address,+                    dateMillis = System.currentTimeMillis(),+                    messageId = id,+                    blobBase64 = Base64.encodeToString(raw, Base64.NO_WRAP),+                    decryptedBody = body,+                    decryptedSubject = subject,+                    unencrypted = false,+                )+            }.getOrNull()+        } else {+            null+        }+        repo.messageDao().upsert(+            stored ?: StoredMessage(+                id = id,+                from = "",+                toJson = settings.address,+                dateMillis = System.currentTimeMillis(),+                messageId = id,+                blobBase64 = Base64.encodeToString(raw, Base64.NO_WRAP),+                unencrypted = false,+            ),+        )+    }+}
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 3e299628cc..55cfc98d9f 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt@@ -5,20 +5,22 @@ import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import com.vayunmathur.library.log.Log import com.vayunmathur.library.work.startRepeatedTask+import com.vayunmathur.securemail.data.InboundStore import com.vayunmathur.securemail.data.MailConfig-import com.vayunmathur.securemail.data.MailRepository import com.vayunmathur.securemail.network.MailSocket import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob-import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.first import kotlin.time.Duration.Companion.minutes  /**  * Periodic backstop behind the live socket: while the app is backgrounded- * without the foreground service, this worker opens a short socket session to- * drain backlog (SUB → MSG drain → close). No-ops without an identity.+ * without the foreground service, this worker ensures the shared socket loop+ * is running so backlog drains (SUB → MSG drain). It never stops the loop:+ * the loop is process-wide and service-owned; stopping it here would kill a+ * live service session mid-claim (this exact race showed "offline" right+ * after registering). No-ops without an identity or when already connected.  */ class MailSyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) { @@ -27,35 +29,21 @@ class MailSyncWorker(context: Context, params: WorkerParameters) : CoroutineWork         if (settings.address.isBlank()) return Result.success()         if (MailSocket.connected) return Result.success()         return try {-            var drained = 0-            // A dedicated scope for the short drain session (the worker's own-            // coroutine must stay free to enforce the delay/stop below).-            val drainScope = CoroutineScope(Dispatchers.IO + SupervisorJob())+            // Nudge the shared loop awake; the SUB drains backlog through the+            // same InboundStore path as the live service. No teardown after:+            // if the service is alive it keeps the session; if not, the loop+            // persists for the worker's lifetime and idles.             MailSocket.start(-                scope = drainScope,+                scope = CoroutineScope(Dispatchers.IO + SupervisorJob()),                 identity = {                     MailSocket.IdentitySnapshot(settings.address, settings.publicArmor)                 },                 onMessage = { id, unencrypted, raw ->-                    val repo = MailRepository.get(applicationContext)-                    repo.messageDao().upsert(-                        com.vayunmathur.securemail.data.StoredMessage(-                            id = id,-                            from = "",-                            toJson = "[\"${settings.address}\"]",-                            dateMillis = System.currentTimeMillis(),-                            messageId = id,-                            blobBase64 = android.util.Base64.encodeToString(raw, android.util.Base64.NO_WRAP),-                            unencrypted = unencrypted,-                        ),-                    )-                    drained+++                    InboundStore.store(applicationContext, id, unencrypted, raw)                 },             )+            // Give the SUB + backlog drain time to complete within the worker.             kotlinx.coroutines.delay(20_000)-            MailSocket.stop()-            drainScope.cancel()-            Log.dev(TAG, "sync worker drained $drained")             Result.success()         } catch (e: Exception) {             Log.status(TAG, "sync worker failed", e)
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 308813e13b..323ca1456c 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt@@ -6,13 +6,9 @@ import android.content.Intent import android.os.IBinder import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.ensureNotificationChannel+import com.vayunmathur.securemail.data.InboundStore import com.vayunmathur.securemail.data.MailConfig-import com.vayunmathur.securemail.data.MailRepository-import com.vayunmathur.securemail.data.StoredMessage-import com.vayunmathur.securemail.domain.mail.MimeCodec-import com.vayunmathur.securemail.domain.pgp.PgpCrypto import com.vayunmathur.securemail.network.MailSocket-import com.vayunmathur.securemail.platform.crypto.KeyManager import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob@@ -54,82 +50,9 @@ class MailSocketService : Service() {                     else MailSocket.IdentitySnapshot(current.address, current.publicArmor)                 },                 onMessage = { id, unencrypted, raw ->-                    // Write straight to the Room vault, decrypting immediately:-                    // the S2K passphrase loads transparently from-                    // Keystore-wrapped storage, so arrival-time decrypt needs-                    // no user interaction. The UI observes the vault as a Flow-                    // and shows decrypted content as soon as it lands.-                    val repo = MailRepository.get(this@MailSocketService)-                    val config = MailConfig(this@MailSocketService)-                    val settings = config.settings.first()-                    val keyManager = KeyManager(this@MailSocketService)-                    if (unencrypted) {-                        // Plaintext frames carry the MIME body directly.-                        val text = raw.toString(Charsets.UTF_8)-                        val (subject, body, from) =-                            MimeCodec.parseMime(text)-                        repo.messageDao().upsert(-                            StoredMessage(-                                id = id,-                                from = from,-                                toJson = settings.address,-                                dateMillis = System.currentTimeMillis(),-                                messageId = id,-                                blobBase64 = "",-                                decryptedBody = body,-                                decryptedSubject = subject,-                                unencrypted = true,-                            ),-                        )-                    } else {-                        val passphrase = keyManager.getKeyPassphrase()-                        val stored = if (passphrase != null) {-                            runCatching {-                                val pgpB64 = MimeCodec.extractPgpPayloadB64(raw)-                                val pgpBytes = if (pgpB64 != null) {-                                    android.util.Base64.decode(-                                        pgpB64, android.util.Base64.DEFAULT,-                                    )-                                } else {-                                    raw-                                }-                                val mime = PgpCrypto.decrypt(-                                    pgpBytes,-                                    keyManager.getSecretArmor(),-                                    passphrase,-                                ).toString(Charsets.UTF_8)-                                val (subject, body, from) = MimeCodec.parseMime(mime)-                                StoredMessage(-                                    id = id,-                                    from = from,-                                    toJson = settings.address,-                                    dateMillis = System.currentTimeMillis(),-                                    messageId = id,-                                    blobBase64 = android.util.Base64.encodeToString(-                                        raw, android.util.Base64.NO_WRAP,-                                    ),-                                    decryptedBody = body,-                                    decryptedSubject = subject,-                                    unencrypted = false,-                                )-                            }.getOrNull()-                        } else {-                            null-                        }-                        repo.messageDao().upsert(-                            stored ?: StoredMessage(-                                id = id,-                                from = "",-                                toJson = settings.address,-                                dateMillis = System.currentTimeMillis(),-                                messageId = id,-                                blobBase64 = android.util.Base64.encodeToString(-                                    raw, android.util.Base64.NO_WRAP,-                                ),-                                unencrypted = false,-                            ),-                        )-                    }+                    // Single choke point (decrypt-on-arrival + vault write),+                    // shared with the background sync worker.+                    InboundStore.store(this@MailSocketService, id, unencrypted, raw)                 },             ) {                 // onBump: socket liveness tick — no-op here; UI polls [MailSocket.connected].