securemail: direct Room receive, WKD timeouts, honest outbox drain
- Commit
f8e1d164e64e705c6eef621418f3d9063d454cac- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-24 00:49 UTC (1 month ago)
- Parents
73914fa
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 a75777b6db..82d8588383 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt@@ -10,7 +10,6 @@ import androidx.fragment.app.FragmentActivity import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.securemail.platform.MailViewModel-import com.vayunmathur.securemail.service.PendingInbox import com.vayunmathur.securemail.ui.ComposeScreen import com.vayunmathur.securemail.ui.InboxScreen import com.vayunmathur.securemail.ui.LockScreen@@ -68,12 +67,6 @@ fun Navigation(viewModel: MailViewModel, initialRoute: Route? = null) { ) } entry<Route.Inbox> {- // Drain frames that arrived while no UI was alive.- LaunchedEffect(Unit) {- for (p in PendingInbox.drain()) {- viewModel.onInboundMessage(p.id, p.unencrypted, p.raw)- }- } InboxScreen( state = state, onOpen = { backStack.add(Route.Reader(it)) },
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 e4bd141a74..40575dedb2 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt@@ -362,12 +362,18 @@ object KeyLookupHttp { * Fetches a WKD key record (binary OpenPGP key, possibly armored) and * returns it as canonical armor text via the native normalizer. WKD * responses are the raw key bytes, not JSON.+ *+ * Bounded at 10s connect / 15s read: most domains have no WKD at all and+ * a hanging lookup must not stall the send path (which falls through to+ * the explicit unencrypted opt-in). */ suspend fun fetchWkdKey(url: String): String? { return try { val r = NetworkClient.execute( url = url, useSystemTrust = true,+ connectTimeoutMs = 10_000L,+ readTimeoutMs = 15_000L, ) if (!r.isSuccess || r.bytes.isEmpty()) return null runCatching { com.vayunmathur.e2ee.Pgp.normalizeKey(r.bytes) }.getOrNull()
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 3d17c0ceae..c0bf0b9d41 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt@@ -375,27 +375,40 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { val encryptedTo = trust.filter { it.hasKey } val plainTo = trust.filter { !it.hasKey }.map { it.address } val mime = buildMimeBody(subject, body)+ var queued = 0 // Per-recipient encryption: each key-known recipient gets a blob. for (t in encryptedTo) { val cached = repo.keyDao().get(t.address) ?: continue val blob = PgpCrypto.encrypt(mime, cached.armoredPublic) val ok = MailSocket.publish(t.address, blob)- if (!ok) queueOutbox(listOf(t.address), subject, body, inReplyTo, false)+ if (!ok) {+ queueOutbox(listOf(t.address), subject, body, inReplyTo, false)+ queued+++ } } // Keyless recipients: socket plaintext frame (opt-in) for own-domain,- // SMTP federation queue for external (Phase 2 server path).+ // server federation for external — but only when the socket is+ // up; otherwise the local outbox holds them for retry. for (address in plainTo) { if (AddressValidator.isOwnDomain(address)) { val ok = MailSocket.publish(address, mime, unencrypted = true)- if (!ok) queueOutbox(listOf(address), subject, body, inReplyTo, true)+ if (!ok) {+ queueOutbox(listOf(address), subject, body, inReplyTo, true)+ queued+++ } } else {- queueOutbox(listOf(address), subject, body, inReplyTo, true)+ val ok = MailSocket.publish(address, mime, unencrypted = true)+ if (!ok) {+ queueOutbox(listOf(address), subject, body, inReplyTo, true)+ queued+++ } } }+ if (queued > 0) "Queued $queued message(s) — retry from Outbox when online." else "Sent." } } state = outcome.fold(- onSuccess = { state.copy(busy = false, message = "Sent.") },+ onSuccess = { msg -> state.copy(busy = false, message = msg) }, onFailure = { Log.status(TAG, "send failed", it) state.copy(busy = false, error = it.message ?: "Send failed.")@@ -423,19 +436,56 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { ) } + /**+ * Drains the local outbox straight to the server over the live socket —+ * no trust re-resolution (that already happened at send time; the entry+ * records the decision in [OutboxMessage.sendUnencrypted]).+ *+ * Encrypted entries re-encrypt to the cached key; plaintext entries+ * publish as explicit-opt-in unencrypted frames for the server to+ * federate. Entries stay queued while offline; anything still failing+ * after publish records an attempt for the next retry.+ */ fun retryOutbox() { viewModelScope.launch { withContext(Dispatchers.IO) {+ if (!MailSocket.connected) {+ state = state.copy(error = "Relay offline — kept in outbox.")+ return@withContext+ } val pending = repo.outboxDao().all()+ var sent = 0+ var failed = 0 for (entry in pending) {- runCatching {+ val ok = runCatching { val to = entry.toJson.split(",").map { it.trim() }.filter { it.isNotEmpty() }- send(to, entry.subject, entry.body, entry.sendUnencrypted, entry.inReplyTo)+ val mime = buildMimeBody(entry.subject, entry.body)+ var entryOk = true+ for (address in to) {+ val cached = repo.keyDao().get(address)+ if (cached != null && !entry.sendUnencrypted) {+ val blob = PgpCrypto.encrypt(mime, cached.armoredPublic)+ if (MailSocket.publish(address, blob)) continue+ } else if (entry.sendUnencrypted) {+ if (MailSocket.publish(address, mime, unencrypted = true)) continue+ }+ entryOk = false+ }+ entryOk+ }.getOrDefault(false)+ if (ok) { repo.outboxDao().delete(entry.rowId)- }.onFailure {- repo.outboxDao().noteAttempt(entry.rowId, it.message ?: "retry failed")+ sent+++ } else {+ repo.outboxDao().noteAttempt(entry.rowId, "relay publish failed")+ failed++ } }+ state = when {+ failed > 0 -> state.copy(error = "$failed message(s) still queued.")+ sent > 0 -> state.copy(message = "Sent $sent message(s).")+ else -> state.copy(message = "Outbox is empty.")+ } } } }
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 876e689417..87fc6c0f29 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt@@ -8,8 +8,8 @@ import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.ensureNotificationChannel import com.vayunmathur.securemail.data.MailConfig import com.vayunmathur.securemail.data.MailRepository+import com.vayunmathur.securemail.data.StoredMessage import com.vayunmathur.securemail.network.MailSocket-import com.vayunmathur.securemail.platform.MailViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob@@ -51,11 +51,26 @@ class MailSocketService : Service() { else MailSocket.IdentitySnapshot(current.address, current.publicArmor) }, onMessage = { id, unencrypted, raw ->- // Decrypt path needs the ViewModel's key gate; store first.- MailRepository.get(this@MailSocketService)- // The ViewModel is activity-scoped, so route through a process- // holder: store the blob now, decrypt on next UI open.- PendingInbox.store(this@MailSocketService, id, unencrypted, raw)+ // Write straight to the Room vault: the UI observes it as a+ // Flow, so mail appears live whether the UI is open or not,+ // and survives process death (unlike the old in-memory hop).+ // Decryption still happens in the ViewModel on open.+ val repo = MailRepository.get(this@MailSocketService)+ val settings =+ MailConfig(this@MailSocketService).settings.first()+ repo.messageDao().upsert(+ 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,+ ),+ ) }, ) { // onBump: socket liveness tick — no-op here; UI polls [MailSocket.connected].@@ -93,25 +108,3 @@ class MailSocketService : Service() { } } }--/**- * Process-wide inbox for frames that arrived while no ViewModel was alive- * (service-owned socket, activity-scoped ViewModel). The next UI open drains- * this into the Room vault via MailViewModel.- */-object PendingInbox {- private val lock = Any()- private val pending = ArrayDeque<PendingMsg>()-- data class PendingMsg(val id: String, val unencrypted: Boolean, val raw: ByteArray)-- fun store(context: Context, id: String, unencrypted: Boolean, raw: ByteArray) {- synchronized(lock) { pending.addLast(PendingMsg(id, unencrypted, raw)) }- }-- fun drain(): List<PendingMsg> = synchronized(lock) {- val out = pending.toList()- pending.clear()- out- }-}
securemail/src/main/java/com/vayunmathur/securemail/ui/InboxScreen.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/InboxScreen.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/InboxScreen.ktindex c9fa3c8d12..4b3602b3f0 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/ui/InboxScreen.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/InboxScreen.kt@@ -23,7 +23,6 @@ import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.securemail.data.StoredMessage import com.vayunmathur.securemail.platform.MailUiState-import com.vayunmathur.securemail.service.PendingInbox import java.text.DateFormat import java.util.Date