securemail: spam flag routing, folders schema, Sent writes, folder filter
- Commit
b24dc086d80bae6a02a7e708103cfe502b8e8a20- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-24 06:45 UTC (1 month ago)
- Parents
0d5a177
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.ktindex 70653b6225..be0970832f 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt@@ -4,6 +4,7 @@ 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.network.MailSocket import com.vayunmathur.securemail.platform.crypto.KeyManager import kotlinx.coroutines.flow.first @@ -20,19 +21,22 @@ 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.+ * frames persist as locked blobs for later retry. The server spam verdict+ * ([MailSocket.MsgFlags.spam]) routes to the Spam folder — independent of+ * PGP signing (unsigned mail is accepted, not spam). */ suspend fun store( context: Context, id: String,- unencrypted: Boolean,+ flags: MailSocket.MsgFlags, raw: ByteArray, ) { val app = context.applicationContext val repo = MailRepository.get(app) val settings = MailConfig(app).settings.first() val keyManager = KeyManager(app)- if (unencrypted) {+ val folder = if (flags.spam) MailFolder.SPAM else MailFolder.INBOX+ if (flags.unencrypted) { val (subject, body, from) = MimeCodec.parseMime(raw.toString(Charsets.UTF_8)) repo.messageDao().upsert( StoredMessage(@@ -45,6 +49,7 @@ object InboundStore { decryptedBody = body, decryptedSubject = subject, unencrypted = true,+ folder = folder, ), ) return@@ -67,9 +72,9 @@ object InboundStore { keyManager.getSecretArmor(), passphrase, ).toString(Charsets.UTF_8)- val (_, _, from) = MimeCodec.parseMime(provisional)- val (mime, verified) = if (from.isNotBlank()) {- val senderKey = SenderKeys.resolve(app, from)+ 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,@@ -85,10 +90,10 @@ object InboundStore { } else { provisional to null }- val (subject, body, resolvedFrom) = MimeCodec.parseMime(mime)+ val (subject, body, from) = MimeCodec.parseMime(mime) StoredMessage( id = id,- from = resolvedFrom,+ from = from, toJson = settings.address, dateMillis = System.currentTimeMillis(), messageId = id,@@ -97,6 +102,7 @@ object InboundStore { decryptedSubject = subject, verifiedSigner = verified, unencrypted = false,+ folder = folder, ) }.getOrNull() } else {@@ -111,6 +117,7 @@ object InboundStore { messageId = id, blobBase64 = Base64.encodeToString(raw, Base64.NO_WRAP), unencrypted = false,+ folder = folder, ), ) }
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 bee4bc4a43..c029374ddd 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt@@ -14,6 +14,18 @@ import androidx.sqlite.execSQL import com.vayunmathur.library.util.DatabaseMigrations import kotlinx.coroutines.flow.Flow +/**+ * Mail folders. Stored as the enum name in [StoredMessage.folder]; the Outbox+ * stays a separate queue table, not a folder value. Spam is assigned by the+ * server verdict at ingest ([InboundStore]); Trash is local-only.+ */+enum class MailFolder {+ INBOX,+ SENT,+ SPAM,+ TRASH,+}+ /** * One stored message: envelope metadata plus the opaque PGP/MIME blob exactly * as it arrived over the socket (raw bytes, base64 in the DB). The server never@@ -34,6 +46,8 @@ data class StoredMessage( val verifiedSigner: String? = null, val unencrypted: Boolean = false, val isRead: Boolean = false,+ /** Folder assignment; defaults to INBOX (v2→v3 backfills existing rows). */+ val folder: MailFolder = MailFolder.INBOX, ) /** Cached public key for a recipient (own directory, WKD, or VKS result). */@@ -64,6 +78,9 @@ interface MessageDao { @Query("SELECT * FROM StoredMessage ORDER BY dateMillis DESC") fun observeAll(): Flow<List<StoredMessage>> + @Query("SELECT * FROM StoredMessage WHERE folder = :folder ORDER BY dateMillis DESC")+ fun observeFolder(folder: MailFolder): Flow<List<StoredMessage>>+ @Query("SELECT * FROM StoredMessage WHERE id = :id LIMIT 1") suspend fun get(id: String): StoredMessage? @@ -79,6 +96,18 @@ interface MessageDao { ) suspend fun storeDecrypted(id: String, body: String, subject: String, verified: String?) + /** Moves a message to Trash (local vault only — the server copy is unaffected). */+ @Query("UPDATE StoredMessage SET folder = 'TRASH' WHERE id = :id")+ suspend fun moveToTrash(id: String)++ /** Restores a trashed message to the Inbox. */+ @Query("UPDATE StoredMessage SET folder = 'INBOX' WHERE id = :id AND folder = 'TRASH'")+ suspend fun restoreFromTrash(id: String)++ /** Permanently deletes everything in Trash (local only). */+ @Query("DELETE FROM StoredMessage WHERE folder = 'TRASH'")+ suspend fun emptyTrash()+ @Query("DELETE FROM StoredMessage WHERE id = :id") suspend fun delete(id: String) }@@ -115,7 +144,7 @@ interface OutboxDao { @Database( entities = [StoredMessage::class, CachedKey::class, OutboxMessage::class],- version = 2,+ version = 3, exportSchema = false, ) abstract class MailDatabase : RoomDatabase() {@@ -156,6 +185,14 @@ abstract class MailDatabase : RoomDatabase() { it.execSQL("ALTER TABLE OutboxMessage_new RENAME TO OutboxMessage") } - override val migrations: List<Migration> = listOf(MIGRATION_1_2)+ /**+ * v2 → v3: adds the `folder` column to StoredMessage (INBOX/SENT/SPAM/+ * TRASH); existing rows backfill to INBOX. The enum stores its name.+ */+ private val MIGRATION_2_3 = Migration(2, 3) {+ it.execSQL("ALTER TABLE StoredMessage ADD COLUMN folder TEXT NOT NULL DEFAULT 'INBOX'")+ }++ override val migrations: List<Migration> = listOf(MIGRATION_1_2, MIGRATION_2_3) } }
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 40575dedb2..95e991a90a 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt@@ -32,6 +32,8 @@ import kotlinx.serialization.json.Json * ``` * * flags bit0: 0 = encrypted PGP/MIME, 1 = unencrypted fallback (explicit opt-in only).+ * flags bit1: 0 = ham, 1 = spam (SPF/DKIM/DMARC failed at receipt; independent+ * of PGP signing — unsigned mail is accepted, not spam). * KEYRESP status: 0 = none, 1 = found (key follows). * * SUB doubles as registration (address claim + public-key publish), exactly like@@ -55,6 +57,11 @@ object MailSocket { const val OP_FETCH_RESP: Byte = 0x07 const val FLAG_PLAIN: Byte = 0x01+ /** Spam flag: SPF/DKIM/DMARC verification failed at receipt (routes to Spam). */+ const val FLAG_SPAM: Byte = 0x02++ /** Decoded MSG frame flags (bit0 = plaintext shape, bit1 = server spam verdict). */+ data class MsgFlags(val unencrypted: Boolean, val spam: Boolean) const val KEY_NONE = 0 const val KEY_FOUND = 1@@ -102,7 +109,7 @@ object MailSocket { fun start( scope: CoroutineScope, identity: suspend () -> IdentitySnapshot?,- onMessage: suspend (id: String, unencrypted: Boolean, raw: ByteArray) -> Unit,+ onMessage: suspend (id: String, flags: MsgFlags, raw: ByteArray) -> Unit, onBump: () -> Unit = {}, ) { if (loop?.isActive == true) return@@ -201,7 +208,7 @@ object MailSocket { private suspend fun WsSession.supervise( conn: CoroutineScope, outer: CoroutineScope,- onMessage: suspend (id: String, unencrypted: Boolean, raw: ByteArray) -> Unit,+ onMessage: suspend (id: String, flags: MsgFlags, raw: ByteArray) -> Unit, onBump: () -> Unit, ) { var lastInbound = System.currentTimeMillis()@@ -233,7 +240,7 @@ object MailSocket { internal suspend fun dispatch( buf: ByteArray,- onMessage: suspend (id: String, unencrypted: Boolean, raw: ByteArray) -> Unit,+ onMessage: suspend (id: String, flags: MsgFlags, raw: ByteArray) -> Unit, ) { when (buf.firstOrNull()) { OP_MSG -> {@@ -294,15 +301,19 @@ object MailSocket { return out } - /** MSG: [0x03][flags][u32 blobLen][id UTF-8][raw…] → (id, unencrypted, raw). */- internal fun parseMsg(buf: ByteArray): Triple<String, Boolean, ByteArray>? {+ /** MSG: [0x03][flags][u32 blobLen][id UTF-8][raw…] → (id, flags, raw). */+ internal fun parseMsg(buf: ByteArray): Triple<String, MsgFlags, ByteArray>? { if (buf.size < 1 + 1 + 4 + 2) return null- val unencrypted = (buf[1].toInt() and 0xFF) != 0+ val flags = buf[1].toInt() and 0xFF+ 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) return null val id = buf.copyOfRange(6, 6 + idLen).toString(Charsets.UTF_8) val raw = buf.copyOfRange(6 + idLen, buf.size)- return Triple(id, unencrypted, raw)+ return Triple(id, parsed, raw) } /** KEYRESP: [0x05][status][u16 addrLen][address][key…] → (address, key?). */
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 55cfc98d9f..27890a5f52 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt@@ -38,8 +38,8 @@ class MailSyncWorker(context: Context, params: WorkerParameters) : CoroutineWork identity = { MailSocket.IdentitySnapshot(settings.address, settings.publicArmor) },- onMessage = { id, unencrypted, raw ->- InboundStore.store(applicationContext, id, unencrypted, raw)+ onMessage = { id, flags, raw ->+ InboundStore.store(applicationContext, id, flags, raw) }, ) // Give the SUB + backlog drain time to complete within the worker.
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 069bc5eb10..513925997c 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt@@ -12,6 +12,7 @@ import com.vayunmathur.library.biometric.unlockDatabaseWithBiometrics import com.vayunmathur.library.log.Log import com.vayunmathur.securemail.data.CachedKey import com.vayunmathur.securemail.data.MailConfig+import com.vayunmathur.securemail.data.MailFolder import com.vayunmathur.securemail.data.MailRepository import com.vayunmathur.securemail.data.OutboxMessage import com.vayunmathur.securemail.data.SenderKeys@@ -27,8 +28,10 @@ import com.vayunmathur.securemail.service.MailSocketService import java.util.UUID import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach+import androidx.compose.runtime.snapshotFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -70,6 +73,46 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { val outboxCount = repo.outboxDao().observeCount() val outboxMessages = repo.outboxDao().observeAll() + /**+ * Selected folder driving the message list (drawer selection). Outbox is+ * not a folder — it renders from [outboxMessages] directly.+ */+ var selectedFolder by mutableStateOf(MailFolder.INBOX)+ private set++ fun selectFolder(folder: MailFolder) {+ selectedFolder = folder+ }++ /** Live messages for the currently selected folder. */+ val folderMessages = snapshotFlow { selectedFolder }.flatMapLatest { folder ->+ repo.messageDao().observeFolder(folder)+ }++ /** Moves a message to Trash (local vault only). */+ fun moveToTrash(id: String) {+ viewModelScope.launch {+ withContext(Dispatchers.IO) { repo.messageDao().moveToTrash(id) }+ }+ }++ /** Restores a trashed message to the Inbox. */+ fun restoreFromTrash(id: String) {+ viewModelScope.launch {+ withContext(Dispatchers.IO) { repo.messageDao().restoreFromTrash(id) }+ }+ }++ /** Permanently deletes everything in Trash (local only). */+ fun emptyTrash() {+ viewModelScope.launch {+ withContext(Dispatchers.IO) {+ repo.messageDao().emptyTrash()+ state = state.copy(message = "Trash emptied.")+ }+ }+ }+ /** * In-memory S2K passphrase for the PGP secret ring. Sealed in * Keystore-wrapped storage at claim time ([KeyManager.storeKeyPassphrase])@@ -445,6 +488,8 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { queued++ } }+ // Sent-folder copy: plaintext (it is our own composition).+ storeSent(to, subject, body) if (queued > 0) "Queued $queued message(s) — retry from Outbox when online." else "Sent." } }@@ -462,6 +507,29 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { } } + /**+ * Records our own composition in the Sent folder (plaintext — it is ours).+ * Runs inside send()'s IO context; failures are swallowed (send succeeded).+ */+ private suspend fun storeSent(to: List<String>, subject: String, body: String) {+ runCatching {+ repo.messageDao().upsert(+ StoredMessage(+ id = "sent-${UUID.randomUUID()}",+ from = state.address,+ toJson = to.joinToString(","),+ dateMillis = System.currentTimeMillis(),+ messageId = newMessageId(),+ blobBase64 = "",+ decryptedBody = body,+ decryptedSubject = subject.ifBlank { "(no subject)" },+ unencrypted = false,+ folder = MailFolder.SENT,+ ),+ )+ }+ }+ private suspend fun queueOutbox( to: List<String>, subject: String,
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 323ca1456c..47da32cd5c 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt@@ -49,10 +49,10 @@ class MailSocketService : Service() { if (current.address.isBlank() || current.publicArmor.isBlank()) null else MailSocket.IdentitySnapshot(current.address, current.publicArmor) },- onMessage = { id, unencrypted, raw ->+ onMessage = { id, flags, raw -> // Single choke point (decrypt-on-arrival + vault write), // shared with the background sync worker.- InboundStore.store(this@MailSocketService, id, unencrypted, raw)+ InboundStore.store(this@MailSocketService, id, flags, raw) }, ) { // onBump: socket liveness tick — no-op here; UI polls [MailSocket.connected].