提交 Haven Android 仓库源码 v5.87.79

This commit is contained in:
ali
2026-09-10 13:45:36 +08:00
parent 87b452c4dc
commit 22f4ca5830
2524 changed files with 599455 additions and 1 deletions
+52
View File
@@ -0,0 +1,52 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.hilt)
alias(libs.plugins.ksp)
}
android {
namespace = "sh.haven.core.mail"
compileSdk = 37
defaultConfig {
minSdk = 26
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
testOptions {
unitTests.isReturnDefaultValues = true
}
}
dependencies {
// :core:rclone owns the gomobile binding (rclone-transport, which carries
// the Proton MailBridge wrapper) and the libgojni.so jniLibs — depending on
// it gives us MailBridge at compile time and the native lib in the APK.
implementation(project(":core:rclone"))
implementation(project(":core:data"))
implementation(libs.coroutines.core)
implementation(libs.coroutines.android)
implementation(libs.hilt.android)
ksp(libs.hilt.compiler)
// JVM IMAP/SMTP engine (Stage 2a). The android-mail build of JavaMail is
// purpose-built for Android: zero java.beans/java.awt refs (verified), the
// javax.mail namespace, and the IMAP/SMTP providers. CDDL-1.1 / GPL-2.0
// with classpath-exception — the exception is what permits linking from an
// AGPL app. ImapMailClient registers providers explicitly via Properties
// (mail.imap.class/…) because Android strips META-INF/javamail.* files.
implementation("com.sun.mail:android-mail:1.6.8")
implementation("com.sun.mail:android-activation:1.6.8")
testImplementation(libs.junit)
}
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
}
@@ -0,0 +1,834 @@
package sh.haven.core.mail
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.util.Date
import java.util.Properties
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
import javax.mail.AuthenticationFailedException
import javax.mail.FetchProfile
import javax.mail.Flags
import javax.mail.Folder
import javax.mail.Message
import javax.mail.MessagingException
import javax.mail.Session
import javax.mail.Store
import javax.mail.UIDFolder
import javax.mail.search.AndTerm
import javax.mail.search.BodyTerm
import javax.mail.search.ComparisonTerm
import javax.mail.search.FlagTerm
import javax.mail.search.FromStringTerm
import javax.mail.search.ReceivedDateTerm
import javax.mail.search.RecipientStringTerm
import javax.mail.search.SearchTerm
import javax.mail.search.SubjectTerm
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart
/**
* [MailClient] over generic IMAP using the android-mail (JavaMail) build. The
* read path mirrors [ProtonMailClient]: list folders, list envelopes, and fetch
* a message as raw RFC822 bytes (`Message.writeTo`) so the feature layer parses
* it with the same `MimeParser` both engines share. [send] (CP-6) builds a
* `MimeMessage` and posts it over SMTP on the same tunneled [SocketFactory],
* then best-effort files a copy in the account's Sent folder.
*
* The JVM [Store] for each [sessionId] is held here; the transport rides the
* per-profile tunnel via [MailConnectParams.Imap.socketFactory] (a plain
* tunneled socket), with TLS layered on top by [TunnelingSSLSocketFactory] when
* the account uses implicit SSL.
*/
@Singleton
class ImapMailClient @Inject constructor() : MailClient {
private class ImapSession(
val store: Store,
val session: Session,
val params: MailConnectParams.Imap,
)
private val sessions = ConcurrentHashMap<String, ImapSession>()
override suspend fun login(
sessionId: String,
params: MailConnectParams,
): MailLoginResult = withContext(Dispatchers.IO) {
val p = params as? MailConnectParams.Imap
?: throw IllegalArgumentException(
"ImapMailClient requires MailConnectParams.Imap, got ${params::class.simpleName}",
)
val session = Session.getInstance(buildProps(p))
val store = session.getStore(if (p.tls) "imaps" else "imap")
try {
store.connect(p.server, p.port, p.username, p.password)
} catch (e: AuthenticationFailedException) {
throw MailException.AuthFailed(e.message ?: "IMAP authentication failed")
} catch (e: MessagingException) {
throw MailException.ProtocolError(0, e.message ?: "IMAP connection failed")
}
sessions[sessionId] = ImapSession(store, session, p)
// IMAP has no token/keyring; the result fields are Proton-shaped and unused here.
MailLoginResult(uid = p.username, accessToken = "", refreshToken = "", saltedKeyPass = "")
}
override suspend fun listFolders(sessionId: String): List<MailFolder> =
withContext(Dispatchers.IO) {
val s = session(sessionId)
val listed = runCatching { s.store.defaultFolder.list("*").toList() }.getOrDefault(emptyList())
val folders = listed.mapNotNull { f ->
// attributes are cached from the LIST response (no extra round-trip).
val attrs = runCatching { (f as? com.sun.mail.imap.IMAPFolder)?.attributes?.toList() }
.getOrNull().orEmpty()
// Drop \Noselect containers (e.g. Gmail's "[Gmail]" parent): opening one
// throws. 1b will reintroduce them as non-clickable section headers once the
// folder list is hierarchical.
if (!folderSelectable(attrs)) return@mapNotNull null
MailFolder(
id = f.fullName,
name = f.name.ifBlank { f.fullName },
type = 0,
role = folderRole(f.name, attrs),
)
}
// Some servers don't return INBOX from list("*"); ensure it's present.
val withInbox = if (folders.none { it.isInbox }) {
listOf(MailFolder(id = "INBOX", name = "INBOX", type = 0, role = MailFolderRole.INBOX)) + folders
} else {
folders
}
// Order by special-use role (Inbox · Starred · Important · Sent · Drafts ·
// All Mail · Spam · Trash), then user folders/labels in the server's order.
withInbox.withIndex()
.sortedWith(compareBy({ it.value.role.sortOrder }, { it.index }))
.map { it.value }
}
override suspend fun listMessages(
sessionId: String,
folderId: String,
desc: Boolean,
limit: Int,
offset: Int,
): List<MailMessage> = withContext(Dispatchers.IO) {
val s = session(sessionId)
val fid = imapFolderId(folderId)
val folder = s.store.getFolder(fid)
folder.open(Folder.READ_ONLY)
try {
// Fetch only the most-recent [limit] envelopes (skipping [offset] from
// the newest end) instead of the whole folder — a large inbox over the
// tunnel was the dominant cost. IMAP message numbers are 1..count,
// oldest..newest.
val count = folder.messageCount
val range = recentSlice(count, limit, offset)
?: return@withContext emptyList()
val msgs = folder.getMessages(range.first, range.last)
val fp = FetchProfile().apply {
add(FetchProfile.Item.ENVELOPE)
add(FetchProfile.Item.FLAGS)
add(UIDFolder.FetchProfileItem.UID)
}
folder.fetch(msgs, fp)
val uf = folder as UIDFolder
val list = msgs.map { m -> toMailMessage(m, uf, fid) }
// The slice is oldest-first within the window; newest-first when desc.
if (desc) list.asReversed() else list
} catch (e: MessagingException) {
throw MailException.ProtocolError(0, e.message ?: "IMAP list failed")
} finally {
runCatching { folder.close(false) }
}
}
override suspend fun getMessageRaw(sessionId: String, messageId: String): ByteArray =
withContext(Dispatchers.IO) {
val s = session(sessionId)
val (folderId, uid) = decodeId(messageId)
val folder = s.store.getFolder(folderId)
folder.open(Folder.READ_ONLY)
try {
val m = (folder as UIDFolder).getMessageByUID(uid)
?: throw MailException.ProtocolError(404, "Message $uid not found in $folderId")
ByteArrayOutputStream().also { m.writeTo(it) }.toByteArray()
} catch (e: MessagingException) {
throw MailException.ProtocolError(0, e.message ?: "IMAP fetch failed")
} finally {
runCatching { folder.close(false) }
}
}
override suspend fun setSeen(sessionId: String, messageId: String, seen: Boolean) =
withMessageReadWrite(sessionId, messageId, expungeOnClose = false) { _, m ->
m.setFlag(Flags.Flag.SEEN, seen)
}
override suspend fun setFlagged(sessionId: String, messageId: String, flagged: Boolean) =
withMessageReadWrite(sessionId, messageId, expungeOnClose = false) { _, m ->
m.setFlag(Flags.Flag.FLAGGED, flagged)
}
override suspend fun deleteMessage(sessionId: String, messageId: String) =
// Mark \Deleted; close(true) expunges it. On Gmail this lands the copy in Trash.
withMessageReadWrite(sessionId, messageId, expungeOnClose = true) { _, m ->
m.setFlag(Flags.Flag.DELETED, true)
}
override suspend fun moveMessage(sessionId: String, messageId: String, destFolderId: String) {
withContext(Dispatchers.IO) {
val s = session(sessionId)
val (folderId, uid) = decodeId(messageId)
val destFolderId = imapFolderId(destFolderId)
val dest = s.store.getFolder(destFolderId)
if (!dest.exists()) {
throw MailException.ProtocolError(404, "Destination folder not found: $destFolderId")
}
val src = s.store.getFolder(folderId)
src.open(Folder.READ_WRITE)
try {
val imap = src as com.sun.mail.imap.IMAPFolder
// Prefer the IMAP MOVE extension (RFC 6851). Gmail supports it, and unlike a
// COPY *into* Bin/Trash — which Gmail accepts on the server but answers with a
// response JavaMail surfaces as a (spurious) error — UID MOVE completes cleanly.
val movedViaExtension = imap.doCommand { protocol ->
if (!protocol.hasCapability("MOVE")) return@doCommand java.lang.Boolean.FALSE
val args = com.sun.mail.iap.Argument()
args.writeAtom(uid.toString())
args.writeString(com.sun.mail.imap.protocol.BASE64MailboxEncoder.encode(destFolderId))
val responses = protocol.command("UID MOVE", args)
val last = responses[responses.size - 1]
protocol.notifyResponseHandlers(responses)
protocol.handleResult(last) // throws on a NO/BAD server response
java.lang.Boolean.TRUE
} as? Boolean ?: false
if (!movedViaExtension) {
// Portable fallback for servers without MOVE: COPY to dest, then \Deleted + expunge.
val m = (imap as UIDFolder).getMessageByUID(uid)
?: throw MailException.ProtocolError(404, "Message $uid not found in $folderId")
imap.copyMessages(arrayOf<Message>(m), dest)
m.setFlag(Flags.Flag.DELETED, true)
}
} catch (e: MessagingException) {
throw MailException.ProtocolError(0, e.message ?: "IMAP move failed")
} finally {
runCatching { src.close(true) }
}
}
}
override suspend fun copyMessage(sessionId: String, messageId: String, destFolderId: String) {
withContext(Dispatchers.IO) {
val s = session(sessionId)
val (folderId, uid) = decodeId(messageId)
val destId = imapFolderId(destFolderId)
val dest = s.store.getFolder(destId)
if (!dest.exists()) {
throw MailException.ProtocolError(404, "Destination folder not found: $destId")
}
val src = s.store.getFolder(folderId)
src.open(Folder.READ_ONLY)
try {
// IMAP COPY adds the message to dest, leaving the source intact. On Gmail
// this applies the dest label without removing any existing label.
val m = (src as UIDFolder).getMessageByUID(uid)
?: throw MailException.ProtocolError(404, "Message $uid not found in $folderId")
src.copyMessages(arrayOf<Message>(m), dest)
} catch (e: MessagingException) {
throw MailException.ProtocolError(0, e.message ?: "IMAP copy failed")
} finally {
runCatching { src.close(false) }
}
}
}
override suspend fun folderUidState(sessionId: String, folderId: String): MailFolderUidState =
withContext(Dispatchers.IO) {
val s = session(sessionId)
val folder = s.store.getFolder(folderId)
folder.open(Folder.READ_ONLY)
try {
val uf = folder as UIDFolder
val count = folder.messageCount
val maxUid = if (count > 0) uf.getUID(folder.getMessage(count)) else 0L
val uidNext = (folder as? com.sun.mail.imap.IMAPFolder)?.uidNext?.takeIf { it > 0 }
MailFolderUidState(uidValidity = uf.uidValidity, uidNext = uidNext, maxUid = maxUid)
} catch (e: MessagingException) {
throw MailException.ProtocolError(0, e.message ?: "IMAP UID-state read failed")
} finally {
runCatching { folder.close(false) }
}
}
override suspend fun listSince(
sessionId: String,
folderId: String,
sinceUid: Long,
max: Int,
): List<MailNewMessage> = withContext(Dispatchers.IO) {
val s = session(sessionId)
val folder = s.store.getFolder(folderId)
folder.open(Folder.READ_ONLY)
try {
val uf = folder as UIDFolder
// Inclusive range; getMessagesByUID can return the boundary message, so filter > sinceUid.
val msgs = uf.getMessagesByUID(sinceUid + 1, UIDFolder.LASTUID)
if (msgs.isEmpty()) return@withContext emptyList()
folder.fetch(
msgs,
FetchProfile().apply {
add(FetchProfile.Item.ENVELOPE)
add(FetchProfile.Item.FLAGS)
add(UIDFolder.FetchProfileItem.UID)
},
)
msgs.mapNotNull { m ->
val uid = uf.getUID(m)
if (uid <= sinceUid) null else MailNewMessage(toMailMessage(m, uf, folderId), uid)
}.sortedBy { it.uid }.take(max)
} catch (e: MessagingException) {
throw MailException.ProtocolError(0, e.message ?: "IMAP poll failed")
} finally {
runCatching { folder.close(false) }
}
}
override suspend fun search(
sessionId: String,
folderId: String,
criteria: MailSearchCriteria,
limit: Int,
): List<MailMessage> = withContext(Dispatchers.IO) {
val term = buildSearchTerm(criteria) ?: return@withContext emptyList()
val s = session(sessionId)
val fid = imapFolderId(folderId)
val folder = s.store.getFolder(fid)
folder.open(Folder.READ_ONLY)
try {
val found = folder.search(term)
if (found.isEmpty()) return@withContext emptyList()
// SEARCH returns ascending message numbers (oldest→newest); keep only the newest
// [limit] so a broad match doesn't fetch thousands of envelopes over the tunnel.
val recent = if (found.size > limit) found.copyOfRange(found.size - limit, found.size) else found
folder.fetch(
recent,
FetchProfile().apply {
add(FetchProfile.Item.ENVELOPE)
add(FetchProfile.Item.FLAGS)
add(UIDFolder.FetchProfileItem.UID)
},
)
val uf = folder as UIDFolder
recent.map { toMailMessage(it, uf, fid) }
.sortedByDescending { it.timeSeconds }
} catch (e: MessagingException) {
throw MailException.ProtocolError(0, e.message ?: "IMAP search failed")
} finally {
runCatching { folder.close(false) }
}
}
override suspend fun saveDraft(sessionId: String, mail: OutgoingMail): String =
withContext(Dispatchers.IO) {
val s = session(sessionId)
val p = s.params
// A MimeMessage is built the same way as for send (reusing reply-threading), then
// appended to Drafts flagged \Draft instead of going out over SMTP.
val draftSession = Session.getInstance(buildSmtpProps(p))
val reply = mail.inReplyToMessageId?.let { resolveReplyHeaders(s, it) }
val msg = buildMimeMessage(draftSession, p, mail, reply?.first, reply?.second ?: emptyList())
val drafts = findDraftsFolder(s.store)?.takeIf { it.exists() }
?: throw MailException.ProtocolError(404, "No Drafts folder on this account")
drafts.open(Folder.READ_WRITE)
try {
msg.setFlag(Flags.Flag.DRAFT, true)
msg.setFlag(Flags.Flag.SEEN, true)
drafts.appendMessages(arrayOf<Message>(msg))
drafts.fullName
} catch (e: MessagingException) {
throw MailException.ProtocolError(0, e.message ?: "IMAP draft append failed")
} finally {
runCatching { drafts.close(false) }
}
}
override suspend fun createFolder(sessionId: String, name: String): String =
withContext(Dispatchers.IO) {
val s = session(sessionId)
val trimmed = name.trim()
if (trimmed.isBlank()) throw MailException.ProtocolError(400, "Folder name is blank")
val folder = s.store.getFolder(trimmed)
try {
if (folder.exists()) throw MailException.ProtocolError(409, "Folder already exists: $trimmed")
if (!folder.create(Folder.HOLDS_MESSAGES)) {
throw MailException.ProtocolError(0, "Server refused to create folder: $trimmed")
}
folder.fullName
} catch (e: MessagingException) {
throw MailException.ProtocolError(0, e.message ?: "IMAP create-folder failed")
}
}
override suspend fun deleteFolder(sessionId: String, folderId: String) {
withContext(Dispatchers.IO) {
val s = session(sessionId)
val fid = imapFolderId(folderId)
if (fid.equals("INBOX", ignoreCase = true)) {
throw MailException.ProtocolError(400, "Refusing to delete INBOX")
}
val folder = s.store.getFolder(fid)
try {
if (!folder.exists()) throw MailException.ProtocolError(404, "Folder not found: $fid")
// Refuse special-use system folders (Sent/Drafts/Trash/Spam/All Mail/…) — deleting
// one breaks the account; only user folders/labels may be removed.
val attrs = runCatching {
(folder as? com.sun.mail.imap.IMAPFolder)?.attributes?.toList()
}.getOrNull().orEmpty()
if (folderRole(folder.name, attrs) != MailFolderRole.NONE) {
throw MailException.ProtocolError(400, "Refusing to delete the system folder: $fid")
}
if (folder.isOpen) runCatching { folder.close(false) }
if (!folder.delete(true)) {
throw MailException.ProtocolError(0, "Server refused to delete folder: $fid")
}
} catch (e: MessagingException) {
throw MailException.ProtocolError(0, e.message ?: "IMAP delete-folder failed")
}
}
}
/**
* Open the message's folder READ_WRITE, resolve it by UID, run [block], and close
* (expunging when [expungeOnClose]). Shared by the flag/delete filter ops.
*/
private suspend fun withMessageReadWrite(
sessionId: String,
messageId: String,
expungeOnClose: Boolean,
block: (Folder, Message) -> Unit,
) = withContext(Dispatchers.IO) {
val s = session(sessionId)
val (folderId, uid) = decodeId(messageId)
val folder = s.store.getFolder(folderId)
folder.open(Folder.READ_WRITE)
try {
val m = (folder as UIDFolder).getMessageByUID(uid)
?: throw MailException.ProtocolError(404, "Message $uid not found in $folderId")
block(folder, m)
} catch (e: MessagingException) {
throw MailException.ProtocolError(0, e.message ?: "IMAP update failed")
} finally {
runCatching { folder.close(expungeOnClose) }
}
}
override suspend fun send(sessionId: String, mail: OutgoingMail): SendResult =
withContext(Dispatchers.IO) {
require(mail.to.isNotEmpty()) { "OutgoingMail.to must not be empty" }
val s = session(sessionId)
val p = s.params
// A dedicated Session for SMTP: the stored read Session only carries
// the IMAP socketFactory keys. The build/send is split into testable
// helpers (buildSmtpProps / buildMimeMessage).
val smtpSession = Session.getInstance(buildSmtpProps(p))
// Resolve reply-threading headers from the original message (if this is a reply),
// so the outgoing message carries In-Reply-To / References and threads.
val reply = mail.inReplyToMessageId?.let { resolveReplyHeaders(s, it) }
val msg = buildMimeMessage(smtpSession, p, mail, reply?.first, reply?.second ?: emptyList())
try {
val transport = smtpSession.getTransport(if (smtpImplicitTls(p)) "smtps" else "smtp")
try {
// Pass the creds — JavaMail authenticates only when the server
// advertises AUTH (so a no-auth relay/test sink still works);
// mail.smtp.auth is intentionally NOT forced on.
// Dial the SMTP host, which differs from the IMAP host on real
// providers (smtp.gmail.com vs imap.gmail.com); falls back to
// the IMAP host for self-hosted same-host setups.
transport.connect(smtpHost(p), p.smtpPort, p.username, p.password)
transport.sendMessage(msg, msg.allRecipients)
} finally {
runCatching { transport.close() }
}
} catch (e: AuthenticationFailedException) {
throw MailException.AuthFailed(e.message ?: "SMTP authentication failed")
} catch (e: MessagingException) {
throw MailException.ProtocolError(0, e.message ?: "SMTP send failed")
}
SendResult(
messageId = runCatching { msg.messageID }.getOrNull(),
appendedToSent = appendToSent(s, msg),
)
}
override suspend fun logout(sessionId: String) {
withContext(Dispatchers.IO) {
sessions.remove(sessionId)?.let { runCatching { it.store.close() } }
}
}
// ---- helpers ----
/** Implicit-TLS SMTP iff the submission port is 465 (vs STARTTLS/plaintext on 587/25). */
internal fun smtpImplicitTls(p: MailConnectParams.Imap): Boolean = p.smtpPort == 465
/** SMTP host — the dedicated [MailConnectParams.Imap.smtpServer], or the IMAP host as a fallback. */
internal fun smtpHost(p: MailConnectParams.Imap): String = p.smtpServer ?: p.server
private fun session(sessionId: String): ImapSession {
val s = sessions[sessionId]
?: throw MailException.SessionExpired("IMAP session $sessionId not found")
// Gmail (and most IMAP servers) drop idle connections; reopen the Store on use
// rather than failing with "Socket is closed". IMAPStore.isConnected() pings with a
// NOOP so it detects a dead socket, and params still holds the creds + tunneled
// socket factory, so reconnecting needs no re-prompt.
val alive = try { s.store.isConnected() } catch (e: Exception) { false }
if (!alive) {
try {
val p = s.params
s.store.connect(p.server, p.port, p.username, p.password)
} catch (e: Exception) {
throw MailException.SessionExpired("IMAP session $sessionId reconnect failed: ${e.message}")
}
}
return s
}
private fun toMailMessage(m: Message, uf: UIDFolder, folderId: String): MailMessage {
val from = (m.from?.firstOrNull() as? InternetAddress)
?.let { MailAddress(name = it.personal ?: "", address = it.address ?: "") }
val to = (m.getRecipients(Message.RecipientType.TO) ?: emptyArray())
.filterIsInstance<InternetAddress>()
.map { MailAddress(name = it.personal ?: "", address = it.address ?: "") }
val unread = runCatching { !m.flags.contains(Flags.Flag.SEEN) }.getOrDefault(true)
val timeSeconds = (runCatching { m.receivedDate }.getOrNull()
?: runCatching { m.sentDate }.getOrNull())?.time?.div(1000) ?: 0L
return MailMessage(
id = encodeId(folderId, uf.getUID(m)),
subject = runCatching { m.subject }.getOrNull() ?: "",
from = from,
to = to,
unread = unread,
timeSeconds = timeSeconds,
numAttachments = 0, // not fetched in the list view (needs body structure)
)
}
private fun buildProps(p: MailConnectParams.Imap): Properties = Properties().apply {
// Register providers explicitly — Android strips META-INF/javamail.* so
// protocol auto-discovery fails on-device; without this getStore() throws.
this["mail.imap.class"] = "com.sun.mail.imap.IMAPStore"
this["mail.imaps.class"] = "com.sun.mail.imap.IMAPSSLStore"
this["mail.smtp.class"] = "com.sun.mail.smtp.SMTPTransport"
this["mail.smtps.class"] = "com.sun.mail.smtp.SMTPSSLTransport"
// Read timeout only. connectiontimeout is set per-branch: with a tunnel
// factory it must NOT be set, because it makes JavaMail use the no-arg
// SocketFactory.createSocket() + connect() path, which the tunnel factory
// doesn't implement ("Unconnected sockets not implemented"). The tunnel's
// own dial timeout bounds the connect instead.
this["mail.imap.timeout"] = TIMEOUT_MS
this["mail.imaps.timeout"] = TIMEOUT_MS
val sf = p.socketFactory
if (p.tls) {
this["mail.store.protocol"] = "imaps"
if (sf != null) {
// Route the BASE socket through the tunnel. JavaMail's
// SocketFetcher creates the base socket with `mail.imaps
// .socketFactory`, then — seeing it isn't already an SSLSocket —
// wraps it in implicit TLS itself. (`.ssl.socketFactory` is ONLY
// the wrap factory; setting just that left the BASE socket on the
// default direct factory → a clearnet leak past the tunnel.)
// fallback=false => a dead/blocked tunnel fails the connect.
this["mail.imaps.socketFactory"] = sf
this["mail.imaps.socketFactory.fallback"] = "false"
this["mail.imaps.ssl.checkserveridentity"] = "true"
} else {
this["mail.imaps.connectiontimeout"] = TIMEOUT_MS
}
} else {
this["mail.store.protocol"] = "imap"
if (sf != null) {
this["mail.imap.socketFactory"] = sf
this["mail.imap.socketFactory.fallback"] = "false"
} else {
this["mail.imap.connectiontimeout"] = TIMEOUT_MS
}
}
}
/**
* SMTP session properties. Mirrors the IMAP base-socket lesson from CP-5:
* route the BASE socket through the tunnel ([MailConnectParams.Imap.socketFactory])
* with `fallback=false`, so a dead/blocked tunnel fails the connect instead of
* silently leaking onto the clearnet. `.ssl.socketFactory` is only the wrap
* factory and would leave the base socket on the default direct factory.
*
* The implicit-TLS vs STARTTLS decision keys off the SMTP **port**, not the
* account's [MailConnectParams.Imap.tls] flag: 465 is the conventional
* implicit-TLS submission port, everything else (587 submission, 25 relay,
* test sinks) is plaintext-with-opportunistic-STARTTLS. `tls` governs the IMAP
* side, where a provider is commonly 993-implicit while its SMTP is 587-STARTTLS
* (iCloud, Outlook) — so a single flag can't serve both.
*/
internal fun buildSmtpProps(p: MailConnectParams.Imap): Properties = Properties().apply {
// Register providers explicitly — Android strips META-INF/javamail.* so
// auto-discovery fails on-device; without this getTransport() throws.
this["mail.smtp.class"] = "com.sun.mail.smtp.SMTPTransport"
this["mail.smtps.class"] = "com.sun.mail.smtp.SMTPSSLTransport"
this["mail.smtp.timeout"] = TIMEOUT_MS
this["mail.smtps.timeout"] = TIMEOUT_MS
val sf = p.socketFactory
if (smtpImplicitTls(p)) {
// Implicit TLS (465). JavaMail's SocketFetcher creates the
// base socket with `mail.smtps.socketFactory`, then wraps it in TLS.
this["mail.transport.protocol"] = "smtps"
if (sf != null) {
this["mail.smtps.socketFactory"] = sf
this["mail.smtps.socketFactory.fallback"] = "false"
this["mail.smtps.ssl.checkserveridentity"] = "true"
} else {
this["mail.smtps.connectiontimeout"] = TIMEOUT_MS
}
} else {
// STARTTLS submission (587) or plaintext relay/test (25).
this["mail.transport.protocol"] = "smtp"
this["mail.smtp.starttls.enable"] = "true"
// For a TLS account, REQUIRE STARTTLS: a MITM that strips the
// server's STARTTLS advertisement can otherwise downgrade the
// session to plaintext and harvest the SMTP credentials
// (STRIPTLS). Only an explicitly-plaintext account (tls = false,
// e.g. a local relay / test sink) stays opportunistic.
// (security-review #16)
this["mail.smtp.starttls.required"] = p.tls.toString()
if (sf != null) {
this["mail.smtp.socketFactory"] = sf
this["mail.smtp.socketFactory.fallback"] = "false"
} else {
this["mail.smtp.connectiontimeout"] = TIMEOUT_MS
}
}
}
/** Build the outgoing [MimeMessage]; `saveChanges()` finalises headers + assigns a Message-ID. */
internal fun buildMimeMessage(
smtpSession: Session,
p: MailConnectParams.Imap,
mail: OutgoingMail,
inReplyTo: String? = null,
references: List<String> = emptyList(),
): MimeMessage = MimeMessage(smtpSession).apply {
setFrom(fromAddress(p))
setRecipients(Message.RecipientType.TO, toAddresses(mail.to))
if (mail.cc.isNotEmpty()) setRecipients(Message.RecipientType.CC, toAddresses(mail.cc))
if (mail.bcc.isNotEmpty()) setRecipients(Message.RecipientType.BCC, toAddresses(mail.bcc))
setSubject(mail.subject, "UTF-8")
// RFC 5322 threading: In-Reply-To = the parent's Message-ID; References = the
// parent's References chain plus the parent's own Message-ID.
if (inReplyTo != null) setHeader("In-Reply-To", inReplyTo)
if (references.isNotEmpty()) setHeader("References", references.joinToString(" "))
if (mail.attachments.isEmpty()) {
setText(mail.bodyText, "UTF-8")
} else {
val mp = MimeMultipart("mixed")
mp.addBodyPart(MimeBodyPart().apply { setText(mail.bodyText, "UTF-8") })
for (a in mail.attachments) {
mp.addBodyPart(
MimeBodyPart().apply {
dataHandler = javax.activation.DataHandler(
javax.mail.util.ByteArrayDataSource(a.bytes, a.mimeType),
)
fileName = a.filename
disposition = javax.mail.Part.ATTACHMENT
},
)
}
setContent(mp)
}
sentDate = Date()
saveChanges()
}
/**
* Read the parent message's `Message-ID` (and `References`) so a reply can thread.
* Returns `(inReplyTo, references)` where references = the parent's References chain
* plus its own Message-ID, or null if the parent or its Message-ID can't be read
* (a reply without these headers still sends, just unthreaded). Best-effort.
*/
private fun resolveReplyHeaders(s: ImapSession, messageId: String): Pair<String, List<String>>? =
runCatching {
val (folderId, uid) = decodeId(messageId)
val folder = s.store.getFolder(imapFolderId(folderId))
folder.open(Folder.READ_ONLY)
try {
val m = (folder as UIDFolder).getMessageByUID(uid) ?: return null
val parentId = m.getHeader("Message-ID")?.firstOrNull()?.trim()?.ifBlank { null }
?: return null
val parentRefs = m.getHeader("References")?.firstOrNull()
?.split(Regex("\\s+"))?.mapNotNull { it.trim().ifBlank { null } }.orEmpty()
parentId to (parentRefs + parentId)
} finally {
runCatching { folder.close(false) }
}
}.getOrNull()
/** From the authenticated account; synthesise a domain when the username is a bare local part. */
private fun fromAddress(p: MailConnectParams.Imap): InternetAddress =
InternetAddress(if (p.username.contains('@')) p.username else "${p.username}@${p.server}")
private fun toAddresses(addrs: List<String>): Array<javax.mail.Address> =
addrs.mapNotNull { a -> a.trim().ifBlank { null }?.let { InternetAddress(it, false) } }
.toTypedArray()
/**
* Best-effort file a copy of [msg] in the account's Sent folder over the live
* IMAP [Store]. Never throws — a failed append must not fail the send.
*/
private fun appendToSent(s: ImapSession, msg: MimeMessage): Boolean = runCatching {
val sent = findSentFolder(s.store)?.takeIf { it.exists() } ?: return false
sent.open(Folder.READ_WRITE)
try {
msg.setFlag(Flags.Flag.SEEN, true)
sent.appendMessages(arrayOf<Message>(msg))
true
} finally {
runCatching { sent.close(false) }
}
}.getOrElse {
Log.w(TAG, "append-to-Sent failed: ${it.message}")
false
}
/** Locate the Sent folder: prefer the RFC 6154 `\Sent` special-use attribute, then a name match. */
private fun findSentFolder(store: Store): Folder? {
val all = runCatching { store.defaultFolder.list("*").toList() }.getOrDefault(emptyList())
all.firstOrNull { f ->
runCatching {
(f as? com.sun.mail.imap.IMAPFolder)?.attributes
?.any { it.equals("\\Sent", ignoreCase = true) } == true
}.getOrDefault(false)
}?.let { return it }
val names = setOf("sent", "sent items", "sent mail", "sent messages")
return all.firstOrNull {
it.name.lowercase() in names || it.fullName.lowercase() in names
}
}
/** Locate the Drafts folder: prefer the RFC 6154 `\Drafts` special-use attribute, then a name match. */
private fun findDraftsFolder(store: Store): Folder? {
val all = runCatching { store.defaultFolder.list("*").toList() }.getOrDefault(emptyList())
all.firstOrNull { f ->
runCatching {
(f as? com.sun.mail.imap.IMAPFolder)?.attributes
?.any { it.equals("\\Drafts", ignoreCase = true) } == true
}.getOrDefault(false)
}?.let { return it }
val names = setOf("drafts", "draft")
return all.firstOrNull {
it.name.lowercase() in names || it.fullName.lowercase() in names
}
}
companion object {
private const val TAG = "ImapMailClient"
private const val TIMEOUT_MS = "30000"
/**
* Compose a JavaMail [SearchTerm] from [c] by ANDing every set field, or null when
* [c] is empty (the caller treats that as "no search"). Pure — unit-tested.
*/
internal fun buildSearchTerm(c: MailSearchCriteria): SearchTerm? {
if (c.isEmpty) return null
val terms = mutableListOf<SearchTerm>()
c.from?.let { terms += FromStringTerm(it) }
c.to?.let { terms += RecipientStringTerm(Message.RecipientType.TO, it) }
c.subject?.let { terms += SubjectTerm(it) }
c.bodyText?.let { terms += BodyTerm(it) }
if (c.unreadOnly) terms += FlagTerm(Flags(Flags.Flag.SEEN), false)
c.sinceEpochSec?.let { terms += ReceivedDateTerm(ComparisonTerm.GE, Date(it * 1000)) }
c.beforeEpochSec?.let { terms += ReceivedDateTerm(ComparisonTerm.LE, Date(it * 1000)) }
return if (terms.size == 1) terms[0] else AndTerm(terms.toTypedArray())
}
/**
* The 1-based IMAP message-number window for the most-recent [limit]
* messages, skipping [offset] from the newest end (messages are numbered
* 1=oldest .. [count]=newest). Returns null when there's nothing to fetch
* (empty folder, or [offset] past the start). Clamps the low end to 1, so a
* final short page returns the remaining oldest messages.
*/
internal fun recentSlice(count: Int, limit: Int, offset: Int): IntRange? {
if (count <= 0 || limit <= 0 || offset < 0) return null
val end = count - offset
if (end < 1) return null
val start = maxOf(1, end - limit + 1)
return start..end
}
/**
* Encode a stable opaque message id as `"<folderFullName> <uid>"`. The
* UID is IMAP's per-folder stable identifier; the folder name is needed
* because [getMessageRaw] reopens the folder to fetch by UID. [decodeId]
* splits on the LAST space, so folder names containing spaces ("Sent
* Items 42") round-trip; the numeric UID never contains one. A printable
* space (not a control byte) keeps the id valid as a JSON string on the
* MCP read path.
*/
/**
* Map the cross-engine inbox sentinel ([MailFolder.INBOX_ID] = "0", Proton's id) to
* IMAP's "INBOX". The MCP/read layer is engine-neutral and may pass "0" (e.g. the
* list_mail_messages default), but IMAP has no folder named "0". Normalising here —
* before envelope ids are minted from the folder — keeps every read/modify-by-id path
* resolving to the real mailbox. Other folder ids (from listFolders) pass through.
*/
internal fun imapFolderId(folderId: String): String =
if (folderId == MailFolder.INBOX_ID) "INBOX" else folderId
internal fun encodeId(folderId: String, uid: Long): String = "$folderId $uid"
internal fun decodeId(messageId: String): Pair<String, Long> {
val i = messageId.lastIndexOf(' ')
require(i > 0 && i < messageId.length - 1) { "Malformed IMAP message id: $messageId" }
val uid = messageId.substring(i + 1).toLongOrNull()
?: throw IllegalArgumentException("Malformed IMAP message id (uid): $messageId")
return messageId.substring(0, i) to uid
}
/**
* Classify an IMAP mailbox into an engine-neutral [MailFolderRole] from its leaf
* [name] and its RFC 6154 special-use [attributes] (`\Sent`, `\Drafts`, `\Trash`,
* `\Junk`, `\Flagged`, `\All`, `\Archive`) plus Gmail's non-standard `\Important`.
* INBOX is matched by name (RFC 3501 reserves it; it carries no special-use flag).
* Attribute matching is case-insensitive — servers vary.
*/
internal fun folderRole(name: String, attributes: List<String>): MailFolderRole {
if (name.equals("INBOX", ignoreCase = true)) return MailFolderRole.INBOX
val attrs = attributes.mapTo(HashSet()) { it.lowercase() }
return when {
"\\sent" in attrs -> MailFolderRole.SENT
"\\drafts" in attrs -> MailFolderRole.DRAFTS
"\\trash" in attrs -> MailFolderRole.TRASH
"\\junk" in attrs -> MailFolderRole.SPAM
"\\flagged" in attrs -> MailFolderRole.STARRED // Gmail "Starred"
"\\important" in attrs -> MailFolderRole.IMPORTANT // Gmail (non-RFC) "Important"
"\\all" in attrs -> MailFolderRole.ARCHIVE // Gmail "All Mail"
"\\archive" in attrs -> MailFolderRole.ARCHIVE
else -> MailFolderRole.NONE
}
}
/**
* IMAP `\Noselect` (RFC 3501) mailboxes are containers only — they hold no messages,
* so opening one throws. Gmail's `[Gmail]` parent is the canonical example. Such
* folders are dropped from the list until the tree becomes hierarchical (1b).
*/
internal fun folderSelectable(attributes: List<String>): Boolean =
attributes.none { it.equals("\\Noselect", ignoreCase = true) }
}
}
@@ -0,0 +1,141 @@
package sh.haven.core.mail
/**
* Provider-agnostic mail engine. Implementations: [ProtonMailClient] (Go
* mailbridge, SRP) and the JVM IMAP/SMTP engine (Stage 2a). Each handles one
* [MailConnectParams] variant; [MailSessionManager] routes by the session's
* [MailEngine].
*
* Session state (logged-in, keyring-unlocked accounts) lives behind the
* implementation, keyed by an opaque [sessionId] the caller mints. All methods
* are main-safe (they switch to a background dispatcher internally) and throw
* [MailException] subtypes on failure.
*/
interface MailClient {
/**
* Authenticate and unlock the account using engine-specific [params]. Throws
* [MailException.TwoFaRequired] / [MailException.MailboxPasswordRequired]
* when the caller must re-prompt and retry (the same [sessionId] can be
* reused — no session is registered until unlock succeeds). Throws
* [IllegalArgumentException] if handed the wrong [MailConnectParams] variant.
*/
suspend fun login(
sessionId: String,
params: MailConnectParams,
): MailLoginResult
/** List the account's folders/labels. */
suspend fun listFolders(sessionId: String): List<MailFolder>
/**
* List a page of message envelopes in [folderId], newest first when [desc].
* [limit] caps how many are fetched (so a multi-thousand-message inbox doesn't
* pull every envelope over the tunnel); [offset] skips that many from the
* newest end, so `offset = page * limit` walks older pages ("Load older").
*/
suspend fun listMessages(
sessionId: String,
folderId: String,
desc: Boolean = true,
limit: Int = DEFAULT_PAGE_SIZE,
offset: Int = 0,
): List<MailMessage>
/** Fetch and decrypt one message, returning the raw RFC822 MIME bytes. */
suspend fun getMessageRaw(sessionId: String, messageId: String): ByteArray
/**
* Send [mail] from the connected account, returning the assigned Message-ID
* and whether a copy was filed in Sent. Throws [MailException] on
* transport/auth failure. The Proton engine is not yet wired for send and
* throws [MailException.ProtocolError] with status 501.
*/
suspend fun send(sessionId: String, mail: OutgoingMail): SendResult
/**
* Mark [messageId] read/unread (the IMAP `\Seen` flag). Used by Mail Rules'
* filter actions. The Proton engine throws [MailException.ProtocolError] (501).
*/
suspend fun setSeen(sessionId: String, messageId: String, seen: Boolean)
/** Set/clear the IMAP `\Flagged` (starred) flag on [messageId]. Proton: 501. */
suspend fun setFlagged(sessionId: String, messageId: String, flagged: Boolean)
/**
* Move [messageId] to [destFolderId] (server-side copy + delete + expunge on
* the source). Proton: 501. On Gmail this relabels — "All Mail" retains the copy.
*/
suspend fun moveMessage(sessionId: String, messageId: String, destFolderId: String)
/**
* Delete [messageId] (set `\Deleted` + expunge). On Gmail this moves it to Trash
* rather than erasing it. Proton: 501.
*/
suspend fun deleteMessage(sessionId: String, messageId: String)
/**
* Copy [messageId] into [destFolderId], leaving the original in place (server-side
* IMAP COPY). On Gmail this *applies a label* — the message keeps its current
* folders/labels and gains [destFolderId]. Use for additive labelling (vs
* [moveMessage], which removes the source). Proton: 501.
*/
suspend fun copyMessage(sessionId: String, messageId: String, destFolderId: String)
/**
* Read [folderId]'s IMAP UID state for the Mail-Rules poller (UIDVALIDITY, UIDNEXT,
* highest existing UID). Proton: throws [MailException.ProtocolError] (501).
*/
suspend fun folderUidState(sessionId: String, folderId: String): MailFolderUidState
/**
* Fetch envelopes for messages whose UID is strictly greater than [sinceUid] in
* [folderId], oldest-first, capped at [max]. Each carries its UID so the poller can
* advance its high-water-mark. Proton: 501.
*/
suspend fun listSince(
sessionId: String,
folderId: String,
sinceUid: Long,
max: Int,
): List<MailNewMessage>
/**
* Server-side search of [folderId] for envelopes matching [criteria] (newest-first,
* capped at [limit]). Returns the same envelope shape as [listMessages] so the ids
* feed straight into [getMessageRaw] / the modify ops. Proton: 501.
*/
suspend fun search(
sessionId: String,
folderId: String,
criteria: MailSearchCriteria,
limit: Int = DEFAULT_PAGE_SIZE,
): List<MailMessage>
/**
* Append [mail] to the account's Drafts folder (flagged `\Draft`), without sending.
* Returns the Drafts folder id it landed in. Proton: 501.
*/
suspend fun saveDraft(sessionId: String, mail: OutgoingMail): String
/**
* Create a new folder/label [name] (IMAP CREATE). On Gmail this is a new label.
* Returns the created folder's id (fullName). Throws if it already exists. Proton: 501.
*/
suspend fun createFolder(sessionId: String, name: String): String
/**
* Delete the folder/label [folderId] (IMAP DELETE). On Gmail this removes the *label*
* (messages survive in All Mail); on a plain IMAP server it deletes the mailbox AND its
* messages — so this is destructive. Refuses the special-use system folders. Proton: 501.
*/
suspend fun deleteFolder(sessionId: String, folderId: String)
/** Revoke and drop the session. */
suspend fun logout(sessionId: String)
companion object {
/** Default message-list page size — most-recent N envelopes per fetch. */
const val DEFAULT_PAGE_SIZE = 100
}
}
@@ -0,0 +1,242 @@
package sh.haven.core.mail
/**
* Mail domain models shared across the engine (Proton Go bridge in v1; JVM
* Jakarta Mail in stage 2) and the UI. Kept deliberately small — message
* bodies are parsed from RFC822 in the feature layer, not here.
*/
/**
* Engine-neutral special-use classification for a mailbox, derived from IMAP RFC 6154
* attributes (`\Sent`, `\Trash`, …) or Proton's system-folder ids. The UI uses it to pick
* an icon and to order the folder list (Inbox first, user labels last). [sortOrder] is the
* list position; lower sorts earlier.
*/
enum class MailFolderRole(val sortOrder: Int) {
INBOX(0),
STARRED(1),
IMPORTANT(2),
SENT(3),
DRAFTS(4),
ARCHIVE(5),
SPAM(6),
TRASH(7),
NONE(8),
}
/**
* A mailbox folder / Proton label. [type] is Proton's LabelType (1=label, 2=folder, 3=system).
* [role] is the engine-neutral special-use class (for UI icons + ordering). [selectable] is
* false for IMAP `\Noselect` container mailboxes (e.g. Gmail's `[Gmail]` parent) that hold no
* messages and must not be opened.
*/
data class MailFolder(
val id: String,
val name: String,
val type: Int,
val color: String? = null,
val parentId: String? = null,
val role: MailFolderRole = MailFolderRole.NONE,
val selectable: Boolean = true,
) {
/** Proton system folders carry well-known stable ids ("0"); IMAP's inbox is the fullName "INBOX". */
val isInbox: Boolean get() = role == MailFolderRole.INBOX || id == INBOX_ID || id.equals("INBOX", ignoreCase = true)
companion object {
const val INBOX_ID = "0"
const val ALL_MAIL_ID = "5"
const val SENT_ID = "7"
const val DRAFTS_ID = "8"
const val TRASH_ID = "3"
const val SPAM_ID = "4"
const val ARCHIVE_ID = "6"
const val STARRED_ID = "10"
const val TYPE_SYSTEM = 3
}
}
/** An email address with an optional display name. */
data class MailAddress(
val name: String,
val address: String,
) {
/** "Alice <alice@example.com>" or just the address when unnamed. */
fun display(): String = if (name.isBlank()) address else "$name <$address>"
}
/**
* Message envelope metadata (the message-list row). The decrypted body is
* fetched separately via [MailClient.getMessageRaw] and parsed in the feature
* layer; this model intentionally omits it.
*/
data class MailMessage(
val id: String,
val subject: String,
val from: MailAddress?,
val to: List<MailAddress> = emptyList(),
val unread: Boolean = false,
/** Server timestamp, unix epoch seconds. */
val timeSeconds: Long = 0L,
val numAttachments: Int = 0,
)
/**
* A folder's IMAP UID state, read at the start of a Mail-Rules poll. [maxUid] is the
* highest existing UID (0 when empty); [uidValidity] guards against the server
* renumbering the mailbox; [uidNext] is the advertised next-UID (diagnostic).
*/
data class MailFolderUidState(
val uidValidity: Long,
val uidNext: Long?,
val maxUid: Long,
)
/** A message returned by the new-mail poll: its envelope plus its IMAP [uid]. */
data class MailNewMessage(
val message: MailMessage,
val uid: Long,
)
/**
* An outgoing message handed to [MailClient.send]. Carries a plain-text body and
* optional [attachments]; HTML bodies are still deferred. [to] must be non-empty;
* the From address is the authenticated account and is set by the engine, not the
* caller. [inReplyToMessageId] is the opaque id (from list_mail_messages) of the
* message being replied to — when set, the engine resolves its RFC `Message-ID`
* and `References` and sets `In-Reply-To` / `References` so the reply threads.
*/
data class OutgoingMail(
val to: List<String>,
val cc: List<String> = emptyList(),
val bcc: List<String> = emptyList(),
val subject: String,
val bodyText: String,
val attachments: List<OutgoingAttachment> = emptyList(),
val inReplyToMessageId: String? = null,
)
/**
* A fully-resolved outbound attachment: the bytes are already in hand. The
* feature/app layer resolves the source (a Haven backend path or a device URI)
* to bytes BEFORE calling [MailClient.send], so this domain model — and the JVM
* SMTP engine that consumes it — stays free of Android and FileBackend types.
* Identity (equals/hashCode) is by reference for [bytes]; these are never compared.
*/
data class OutgoingAttachment(
val filename: String,
val mimeType: String,
val bytes: ByteArray,
)
/**
* Outcome of [MailClient.send]. [messageId] is the RFC822 Message-ID assigned to
* the sent message (null if the engine didn't surface one); [appendedToSent] is
* true when a copy was filed in the account's Sent folder — best-effort, so a
* send is reported successful even when the Sent append fails.
*/
data class SendResult(
val messageId: String?,
val appendedToSent: Boolean,
)
/**
* Criteria for [MailClient.search], ANDed together (all non-null fields must match).
* [from]/[to]/[subject]/[bodyText] are server-side substring matches; [unreadOnly]
* restricts to messages without `\Seen`; [sinceEpochSec]/[beforeEpochSec] bound the
* date (inclusive, day granularity on most servers). At least one field should be set.
*/
data class MailSearchCriteria(
val from: String? = null,
val to: String? = null,
val subject: String? = null,
val bodyText: String? = null,
val unreadOnly: Boolean = false,
val sinceEpochSec: Long? = null,
val beforeEpochSec: Long? = null,
) {
/** True when no criterion is set — a search with this would match the whole folder. */
val isEmpty: Boolean
get() = from == null && to == null && subject == null && bodyText == null &&
!unreadOnly && sinceEpochSec == null && beforeEpochSec == null
}
/**
* Result of a successful Proton SRP login + keyring unlock.
*
* SECURITY (R3): [saltedKeyPass] is the derived passphrase that unlocks the
* account's PGP keyrings — as sensitive as the mailbox password. In v1 it is
* held only for the lifetime of the in-memory session and is NOT persisted; on
* process death the user re-authenticates. If silent resume is ever added it
* must be encrypted via core/security CredentialEncryption, never stored raw.
*/
data class MailLoginResult(
val uid: String,
val accessToken: String,
val refreshToken: String,
val saltedKeyPass: String,
)
/**
* Typed failures from the mail engine, mapped from the bridge's HTTP-ish status
* codes so the connect flow can drive a staged dialog (2FA / mailbox password)
* and distinguish a dead session from a hard auth failure.
*/
sealed class MailException(message: String) : Exception(message) {
/** Account has TOTP enabled; retry login with a code. (bridge 412 "2fa_required") */
class TwoFaRequired : MailException("Two-factor authentication code required")
/** Two-password-mode account; retry login with the mailbox password. (bridge 412 "mailbox_password_required") */
class MailboxPasswordRequired : MailException("Mailbox password required")
/** The Go session no longer exists (process restarted / logged out) — re-login. (bridge 440) */
class SessionExpired(message: String) : MailException(message)
/** Wrong credentials / 2FA. (bridge 401) */
class AuthFailed(message: String) : MailException(message)
/** Any other bridge or protocol error, with the originating status. */
class ProtocolError(val status: Int, message: String) : MailException(message)
}
/** Which engine backs a mail session — selects the [MailClient] in the registry. */
enum class MailEngine { PROTON, IMAP }
/**
* Engine-specific connect parameters. The sealed type lets the single
* [MailClient.login] carry both Proton (SRP + a SOCKS5 listener) and IMAP
* (server coordinates + a JVM [javax.net.SocketFactory]) without an FFI-shaped
* `socks: String?` signature leaking into the JVM engine, or vice-versa. Each
* [MailClient] handles exactly one variant and rejects the other.
*/
sealed interface MailConnectParams {
val username: String
val password: String
/** Proton SRP login (+ optional 2FA / mailbox password), routed via SOCKS5. */
data class Proton(
override val username: String,
override val password: String,
val mailboxPassword: String? = null,
val twoFA: String? = null,
/** Bare `host:port` of a SOCKS5 listener (the per-profile tunnel), or null. NOT a URL. */
val socks: String? = null,
) : MailConnectParams
/** Generic IMAP/SMTP with password / app-password, routed via a JVM SocketFactory. */
data class Imap(
override val username: String,
override val password: String,
val server: String,
val port: Int,
val smtpPort: Int,
val tls: Boolean,
/**
* SMTP submission host. Null = reuse [server] (self-hosted where IMAP and
* SMTP share a host). Real providers split them — Gmail's SMTP is
* smtp.gmail.com, not imap.gmail.com — so [send] must dial this.
*/
val smtpServer: String? = null,
/** SocketFactory wrapping the per-profile tunnel, or null for a direct connection. */
val socketFactory: javax.net.SocketFactory? = null,
) : MailConnectParams
}
@@ -0,0 +1,31 @@
package sh.haven.core.mail
import dagger.Binds
import dagger.MapKey
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dagger.multibindings.IntoMap
/** Dagger map key for the per-[MailEngine] [MailClient] registry. */
@MapKey
annotation class MailEngineKey(val value: MailEngine)
/**
* Binds the mail engines into a `Map<MailEngine, MailClient>` that
* [MailSessionManager] routes by the session's engine. Proton is the v1 engine;
* the JVM IMAP/SMTP engine (Stage 2a) adds one more `@IntoMap` binding here.
*/
@Module
@InstallIn(SingletonComponent::class)
abstract class MailModule {
@Binds
@IntoMap
@MailEngineKey(MailEngine.PROTON)
abstract fun bindProtonClient(impl: ProtonMailClient): MailClient
@Binds
@IntoMap
@MailEngineKey(MailEngine.IMAP)
abstract fun bindImapClient(impl: ImapMailClient): MailClient
}
@@ -0,0 +1,166 @@
package sh.haven.core.mail
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.util.UUID
import javax.inject.Inject
import javax.inject.Singleton
private const val TAG = "MailSessionMgr"
/**
* Tracks live mail sessions across engines, mirroring `RcloneSessionManager` but
* far simpler. Each session names a [MailEngine]; [connectSession] and the
* revoke path route to that engine's [MailClient] via the injected registry, so
* a Proton (Go bridge) and an IMAP (JVM) session coexist behind one manager. The
* engine owns the actual session; this holds the per-profile [SessionState] the
* UI observes and the [SessionManagerRegistry] reports.
*/
@Singleton
class MailSessionManager @Inject constructor(
private val clients: Map<MailEngine, @JvmSuppressWildcards MailClient>,
) {
data class SessionState(
val sessionId: String,
val profileId: String,
val label: String,
val engine: MailEngine,
val status: Status,
val errorMessage: String? = null,
) {
enum class Status { CONNECTING, CONNECTED, DISCONNECTED, ERROR }
}
private val _sessions = MutableStateFlow<Map<String, SessionState>>(emptyMap())
val sessions: StateFlow<Map<String, SessionState>> = _sessions.asStateFlow()
/** The engine client for a live [sessionId], or null if unknown. */
fun clientForSession(sessionId: String): MailClient? =
_sessions.value[sessionId]?.let { clients[it.engine] }
/** The engine client for [profileId]'s connected session, or null. */
fun clientForProfile(profileId: String): MailClient? =
_sessions.value.values
.firstOrNull { it.profileId == profileId && it.status == SessionState.Status.CONNECTED }
?.let { clients[it.engine] }
/** Background scope for fire-and-forget session revokes on disconnect. */
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
/** Connected sessions — used by the registry's foreground keep-alive check. */
val activeSessions: List<SessionState>
get() = _sessions.value.values.filter { it.status == SessionState.Status.CONNECTED }
fun registerSession(profileId: String, label: String, engine: MailEngine): String {
val sessionId = UUID.randomUUID().toString()
_sessions.update { map ->
map + (sessionId to SessionState(
sessionId = sessionId,
profileId = profileId,
label = label,
engine = engine,
status = SessionState.Status.CONNECTING,
))
}
return sessionId
}
/**
* Log in and unlock the account for [sessionId] via its engine, marking it
* CONNECTED on success. On [MailException.TwoFaRequired] /
* [MailException.MailboxPasswordRequired] the session is left CONNECTING and
* the exception rethrown so the caller can re-prompt and retry with the same
* [sessionId]. Any other failure marks the session ERROR and rethrows.
*/
suspend fun connectSession(sessionId: String, params: MailConnectParams) {
val state = _sessions.value[sessionId]
?: throw IllegalStateException("Session $sessionId not found")
val client = clients[state.engine]
?: throw IllegalStateException("No mail engine registered for ${state.engine}")
try {
client.login(sessionId = sessionId, params = params)
markConnected(sessionId)
} catch (e: MailException.TwoFaRequired) {
throw e // retryable — keep CONNECTING
} catch (e: MailException.MailboxPasswordRequired) {
throw e // retryable — keep CONNECTING
} catch (e: Exception) {
Log.w(TAG, "Mail login failed for session $sessionId", e)
failSession(sessionId, e.message ?: e.javaClass.simpleName)
throw e
}
}
private fun markConnected(sessionId: String) {
_sessions.update { map ->
val existing = map[sessionId] ?: return@update map
map + (sessionId to existing.copy(
status = SessionState.Status.CONNECTED,
errorMessage = null,
))
}
}
private fun failSession(sessionId: String, message: String) {
_sessions.update { map ->
val existing = map[sessionId] ?: return@update map
map + (sessionId to existing.copy(
status = SessionState.Status.ERROR,
errorMessage = message,
))
}
}
fun isProfileConnected(profileId: String): Boolean =
_sessions.value.values.any {
it.profileId == profileId && it.status == SessionState.Status.CONNECTED
}
/** The opaque Go-bridge session id of [profileId]'s connected session, if any. */
fun getSessionIdForProfile(profileId: String): String? =
_sessions.value.values
.firstOrNull { it.profileId == profileId && it.status == SessionState.Status.CONNECTED }
?.sessionId
fun getSessionsForProfile(profileId: String): List<SessionState> =
_sessions.value.values.filter { it.profileId == profileId }
fun removeSession(sessionId: String) {
val state = _sessions.value[sessionId]
_sessions.update { it - sessionId }
if (state != null) revoke(listOf(state.sessionId to state.engine))
}
fun removeAllSessionsForProfile(profileId: String) {
val toRevoke = _sessions.value.values
.filter { it.profileId == profileId }
.map { it.sessionId to it.engine }
_sessions.update { map -> map.filterValues { it.profileId != profileId } }
revoke(toRevoke)
}
/**
* Best-effort revoke the session(s) in their engine so a disconnect actually
* tears down the server-side session (the Go bridge's in-process entry for
* Proton, the JVM Store for IMAP) — not just the local [SessionState]. Fire-
* and-forget on [scope]; the local map is already cleared.
*/
private fun revoke(sessions: List<Pair<String, MailEngine>>) {
if (sessions.isEmpty()) return
scope.launch {
for ((id, engine) in sessions) {
val client = clients[engine] ?: continue
runCatching { client.logout(id) }
.onFailure { Log.w(TAG, "logout($id) failed: ${it.message}") }
}
}
}
}
@@ -0,0 +1,217 @@
package sh.haven.core.mail
import android.util.Base64
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
import sh.haven.mail.bridge.MailBridge
import javax.inject.Inject
import javax.inject.Singleton
/**
* [MailClient] backed by the Go mailbridge (rclone's go-proton-api + gopenpgp),
* reached through [MailBridge]. Parses the bridge's raw Proton JSON and maps its
* HTTP-ish status codes to [MailException] subtypes.
*
* The Go side holds the logged-in/unlocked session keyed by [sessionId]; this
* class is otherwise stateless.
*/
@Singleton
class ProtonMailClient @Inject constructor() : MailClient {
override suspend fun login(
sessionId: String,
params: MailConnectParams,
): MailLoginResult = withContext(Dispatchers.IO) {
val p = params as? MailConnectParams.Proton
?: throw IllegalArgumentException(
"ProtonMailClient requires MailConnectParams.Proton, got ${params::class.simpleName}",
)
val res = MailBridge.login(
sessionId = sessionId,
username = p.username,
password = p.password,
mailboxPassword = p.mailboxPassword?.ifBlank { null },
twoFA = p.twoFA?.ifBlank { null },
appVersion = APP_VERSION,
socks = p.socks?.ifBlank { null },
)
if (res.status != 200) throw mapError(res.status, res.output)
val o = JSONObject(res.output)
MailLoginResult(
uid = o.optString("uid"),
accessToken = o.optString("accessToken"),
refreshToken = o.optString("refreshToken"),
saltedKeyPass = o.optString("saltedKeyPass"),
)
}
override suspend fun listFolders(sessionId: String): List<MailFolder> = withContext(Dispatchers.IO) {
val res = MailBridge.listFolders(sessionId)
if (res.status != 200) throw mapError(res.status, res.output)
val arr = JSONArray(res.output)
(0 until arr.length()).map { i -> parseFolder(arr.getJSONObject(i)) }
}
override suspend fun listMessages(
sessionId: String,
folderId: String,
desc: Boolean,
limit: Int,
offset: Int,
): List<MailMessage> = withContext(Dispatchers.IO) {
val res = MailBridge.listMessages(sessionId, folderId, desc)
if (res.status != 200) throw mapError(res.status, res.output)
val arr = JSONArray(res.output)
val all = (0 until arr.length()).map { i -> parseMessage(arr.getJSONObject(i)) }
// The Go bridge still fetches the whole label (server-side paging is a
// follow-up); apply the page window client-side so the UI list is bounded
// and "Load older" advances consistently with the IMAP engine.
if (offset >= all.size) emptyList()
else all.drop(offset).take(limit.coerceAtLeast(0))
}
override suspend fun getMessageRaw(sessionId: String, messageId: String): ByteArray =
withContext(Dispatchers.IO) {
val res = MailBridge.getMessage(sessionId, messageId)
if (res.status != 200) throw mapError(res.status, res.output)
val b64 = JSONObject(res.output).optString("rfc822")
Base64.decode(b64, Base64.DEFAULT)
}
override suspend fun send(sessionId: String, mail: OutgoingMail): SendResult {
// Proton send (per-recipient key discovery + internal-E2E / PGP-external /
// encrypt-to-outside schemes + CreateDraft/SendDraft) is the hardest,
// highest-risk piece — a mis-scheme leaks plaintext — and is a later
// checkpoint. The Go mailbridge's `send` RPC also returns 501. Fail loudly
// rather than pretend success; CP-6 ships IMAP/SMTP send only.
throw MailException.ProtocolError(501, "Proton send is not implemented yet")
}
// Mail Rules' IMAP filter actions aren't wired for the Proton (Go-bridge) engine
// yet — its label/message-mutation RPCs are a later checkpoint. Fail loudly (501)
// like send() rather than silently no-op, so a rule on a Proton account is visibly
// unsupported instead of appearing to succeed.
override suspend fun setSeen(sessionId: String, messageId: String, seen: Boolean): Unit =
throw MailException.ProtocolError(501, "Proton mark-read is not implemented yet")
override suspend fun setFlagged(sessionId: String, messageId: String, flagged: Boolean): Unit =
throw MailException.ProtocolError(501, "Proton flag is not implemented yet")
override suspend fun moveMessage(sessionId: String, messageId: String, destFolderId: String): Unit =
throw MailException.ProtocolError(501, "Proton move is not implemented yet")
override suspend fun deleteMessage(sessionId: String, messageId: String): Unit =
throw MailException.ProtocolError(501, "Proton delete is not implemented yet")
override suspend fun copyMessage(sessionId: String, messageId: String, destFolderId: String): Unit =
throw MailException.ProtocolError(501, "Proton label/copy is not implemented yet")
override suspend fun search(
sessionId: String,
folderId: String,
criteria: MailSearchCriteria,
limit: Int,
): List<MailMessage> = throw MailException.ProtocolError(501, "Proton search is not implemented yet")
override suspend fun saveDraft(sessionId: String, mail: OutgoingMail): String =
throw MailException.ProtocolError(501, "Proton draft save is not implemented yet")
override suspend fun createFolder(sessionId: String, name: String): String =
throw MailException.ProtocolError(501, "Proton folder create is not implemented yet")
override suspend fun deleteFolder(sessionId: String, folderId: String): Unit =
throw MailException.ProtocolError(501, "Proton folder delete is not implemented yet")
override suspend fun folderUidState(sessionId: String, folderId: String): MailFolderUidState =
throw MailException.ProtocolError(501, "Proton mail-rules polling is not implemented yet")
override suspend fun listSince(
sessionId: String,
folderId: String,
sinceUid: Long,
max: Int,
): List<MailNewMessage> =
throw MailException.ProtocolError(501, "Proton mail-rules polling is not implemented yet")
override suspend fun logout(sessionId: String) {
withContext(Dispatchers.IO) { MailBridge.logout(sessionId) }
}
// ---- parsing (Proton structs marshal with capitalised Go field names) ----
private fun parseFolder(o: JSONObject): MailFolder {
val id = o.optString("ID")
return MailFolder(
id = id,
name = o.optString("Name"),
type = o.optInt("Type"),
color = o.optString("Color").ifBlank { null },
parentId = o.optString("ParentID").ifBlank { null },
role = protonRole(id),
)
}
/** Proton's system folders carry stable ids; map them to the engine-neutral role for the UI. */
private fun protonRole(id: String): MailFolderRole = when (id) {
MailFolder.INBOX_ID -> MailFolderRole.INBOX
MailFolder.STARRED_ID -> MailFolderRole.STARRED
MailFolder.SENT_ID -> MailFolderRole.SENT
MailFolder.DRAFTS_ID -> MailFolderRole.DRAFTS
MailFolder.ARCHIVE_ID, MailFolder.ALL_MAIL_ID -> MailFolderRole.ARCHIVE
MailFolder.SPAM_ID -> MailFolderRole.SPAM
MailFolder.TRASH_ID -> MailFolderRole.TRASH
else -> MailFolderRole.NONE
}
private fun parseMessage(o: JSONObject): MailMessage = MailMessage(
id = o.optString("ID"),
subject = o.optString("Subject"),
from = o.optJSONObject("Sender")?.let { parseAddress(it) },
to = o.optJSONArray("ToList").toAddressList(),
// proton.Bool marshals as APIBool int (0/1); tolerate a JSON bool too.
unread = o.optInt("Unread", if (o.optBoolean("Unread")) 1 else 0) == 1,
timeSeconds = o.optLong("Time"),
numAttachments = o.optInt("NumAttachments"),
)
private fun parseAddress(o: JSONObject): MailAddress = MailAddress(
name = o.optString("Name"),
address = o.optString("Address"),
)
private fun JSONArray?.toAddressList(): List<MailAddress> {
if (this == null) return emptyList()
return (0 until length()).mapNotNull { i ->
optJSONObject(i)?.let { parseAddress(it) }
}
}
/** Map a bridge status + `{"error":".."}` body to a typed exception. */
private fun mapError(status: Int, output: String): MailException {
val err = runCatching { JSONObject(output).optString("error") }
.getOrNull()?.ifBlank { null } ?: output
return when {
status == 412 && err.contains("2fa", ignoreCase = true) -> MailException.TwoFaRequired()
status == 412 && err.contains("mailbox_password", ignoreCase = true) ->
MailException.MailboxPasswordRequired()
status == 401 -> MailException.AuthFailed(err)
status == 440 -> MailException.SessionExpired(err)
else -> MailException.ProtocolError(status, err)
}
}
companion object {
/**
* Proton `x-pm-appversion`. go-proton-api's default ("go-proton-api") is
* explicitly flagged not-for-production; this borrows rclone's shipping
* Drive default, which authenticates against live Proton via the same
* SRP endpoints. UNVERIFIED for Mail data endpoints — Proton may gate
* those by a mail-specific version; revisit if reads 4xx after a good
* login (R2). userAgent is left at the bridge default (empty), as rclone
* does; wire WithUserAgent in mailbridge.go if Proton starts requiring it.
*/
const val APP_VERSION = "macos-drive@1.0.0-alpha.1+rclone"
}
}
@@ -0,0 +1,192 @@
package sh.haven.core.mail
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import java.net.InetAddress
import java.net.Socket
import javax.mail.Message
import javax.mail.Part
import javax.mail.Session
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMultipart
import javax.net.SocketFactory
/**
* CP-6 (Stage 2a) — server-less coverage of [ImapMailClient]'s send plumbing:
* the SMTP property selection (the CP-5 base-socket / fail-closed lesson applied
* to SMTP) and the outgoing [javax.mail.internet.MimeMessage] construction. The
* live send round-trip is verified over MCP against a real SMTP sink in CP-6's
* device test (the android-mail transport path is the same proven by CP-0).
*/
class ImapMailClientSendTest {
private val client = ImapMailClient()
/** A never-dialed stub — these tests only inspect props/headers, never connect. */
private val stubFactory = object : SocketFactory() {
override fun createSocket(): Socket = throw UnsupportedOperationException()
override fun createSocket(host: String?, port: Int): Socket = throw UnsupportedOperationException()
override fun createSocket(host: String?, port: Int, lh: InetAddress?, lp: Int): Socket =
throw UnsupportedOperationException()
override fun createSocket(host: InetAddress?, port: Int): Socket = throw UnsupportedOperationException()
override fun createSocket(a: InetAddress?, p: Int, la: InetAddress?, lp: Int): Socket =
throw UnsupportedOperationException()
}
private fun imapParams(tls: Boolean, smtpPort: Int) = MailConnectParams.Imap(
username = "alice@example.com",
password = "app-password",
server = "mail.example.com",
port = 993,
smtpPort = smtpPort,
tls = tls,
socketFactory = stubFactory,
)
@Test
fun implicitTlsRoutesBaseSocketThroughTunnelAndFailsClosed() {
val props = client.buildSmtpProps(imapParams(tls = true, smtpPort = 465))
assertEquals("smtps", props["mail.transport.protocol"])
// BASE factory (not just the .ssl wrap factory) → no clearnet leak.
assertSame(stubFactory, props["mail.smtps.socketFactory"])
assertEquals("false", props["mail.smtps.socketFactory.fallback"])
// The wrap-only key must NOT be the one carrying the tunnel.
assertTrue(props["mail.smtps.ssl.socketFactory"] == null)
}
@Test
fun nonTlsUsesStarttlsAndBaseSocketFactory() {
val props = client.buildSmtpProps(imapParams(tls = false, smtpPort = 587))
assertEquals("smtp", props["mail.transport.protocol"])
assertEquals("true", props["mail.smtp.starttls.enable"])
assertSame(stubFactory, props["mail.smtp.socketFactory"])
assertEquals("false", props["mail.smtp.socketFactory.fallback"])
}
/**
* The implicit-TLS vs STARTTLS decision keys off the SMTP **port**, not the
* account's IMAP `tls` flag: an iCloud/Outlook-shaped account is 993-implicit
* on IMAP (tls=true) yet 587-STARTTLS on SMTP — a single flag can't serve both,
* so 587 must still produce a STARTTLS (not implicit-smtps) transport.
*/
@Test
fun implicitTlsImapButPort587SmtpStillUsesStarttls() {
val props = client.buildSmtpProps(imapParams(tls = true, smtpPort = 587))
assertEquals("smtp", props["mail.transport.protocol"])
assertEquals("true", props["mail.smtp.starttls.enable"])
assertSame(stubFactory, props["mail.smtp.socketFactory"])
assertTrue(props["mail.smtps.socketFactory"] == null)
}
@Test
fun smtpHostPrefersDedicatedSmtpServerThenFallsBackToImapHost() {
// Gmail: SMTP host differs from the IMAP host.
val gmail = imapParams(tls = true, smtpPort = 465)
.copy(server = "imap.gmail.com", smtpServer = "smtp.gmail.com")
assertEquals("smtp.gmail.com", client.smtpHost(gmail))
// Self-hosted: no dedicated SMTP host → reuse the IMAP host.
val selfHosted = imapParams(tls = true, smtpPort = 465).copy(server = "mail.example.com")
assertEquals("mail.example.com", client.smtpHost(selfHosted))
}
@Test
fun buildsMimeMessageWithHeadersBodyAndMessageId() {
val p = imapParams(tls = true, smtpPort = 465)
val session = Session.getInstance(client.buildSmtpProps(p))
val msg = client.buildMimeMessage(
session,
p,
OutgoingMail(
to = listOf("bob@example.org"),
cc = listOf("carol@example.org"),
subject = "Hello",
bodyText = "Body text",
),
)
assertEquals("Hello", msg.subject)
assertEquals("alice@example.com", (msg.from.first() as InternetAddress).address)
assertEquals(
"bob@example.org",
(msg.getRecipients(Message.RecipientType.TO).first() as InternetAddress).address,
)
assertEquals(
"carol@example.org",
(msg.getRecipients(Message.RecipientType.CC).first() as InternetAddress).address,
)
assertTrue(msg.getRecipients(Message.RecipientType.BCC).isNullOrEmpty())
assertEquals("Body text", msg.content.toString().trim())
// saveChanges() must have assigned a Message-ID.
assertNotNull(msg.messageID)
}
@Test
fun buildsReplyThreadingHeadersWhenReplying() {
val p = imapParams(tls = true, smtpPort = 465)
val session = Session.getInstance(client.buildSmtpProps(p))
val parentId = "<parent-42@example.org>"
val chain = listOf("<root-1@example.org>", parentId)
val msg = client.buildMimeMessage(
session,
p,
OutgoingMail(to = listOf("bob@example.org"), subject = "Re: Hello", bodyText = "Reply"),
inReplyTo = parentId,
references = chain,
)
assertEquals(parentId, msg.getHeader("In-Reply-To")?.first())
assertEquals(chain.joinToString(" "), msg.getHeader("References")?.first())
}
@Test
fun omitsThreadingHeadersForFreshCompose() {
val p = imapParams(tls = true, smtpPort = 465)
val session = Session.getInstance(client.buildSmtpProps(p))
val msg = client.buildMimeMessage(
session, p, OutgoingMail(to = listOf("bob@example.org"), subject = "Hi", bodyText = "x"),
)
assertTrue(msg.getHeader("In-Reply-To").isNullOrEmpty())
assertTrue(msg.getHeader("References").isNullOrEmpty())
}
@Test
fun buildsMultipartMixedWhenAttachmentsPresent() {
val p = imapParams(tls = true, smtpPort = 465)
val session = Session.getInstance(client.buildSmtpProps(p))
val bytes = "%PDF-1.4\n".toByteArray()
val msg = client.buildMimeMessage(
session,
p,
OutgoingMail(
to = listOf("bob@example.org"),
subject = "With attachment",
bodyText = "See attached.",
attachments = listOf(OutgoingAttachment("doc.pdf", "application/pdf", bytes)),
),
)
val content = msg.content
assertTrue("content is multipart when attachments present", content is MimeMultipart)
val mp = content as MimeMultipart
assertEquals(2, mp.count)
// Part 0 is the text body; part 1 is the attachment.
assertTrue(mp.getBodyPart(0).content.toString().contains("See attached."))
val att = mp.getBodyPart(1)
assertEquals("doc.pdf", att.fileName)
assertEquals(Part.ATTACHMENT, att.disposition)
val out = java.io.ByteArrayOutputStream()
att.inputStream.use { it.copyTo(out) }
assertEquals("%PDF-1.4\n", String(out.toByteArray()))
}
@Test
fun fromSynthesisesDomainForBareUsername() {
val p = imapParams(tls = false, smtpPort = 587).copy(username = "droid")
val session = Session.getInstance(client.buildSmtpProps(p))
val msg = client.buildMimeMessage(
session, p, OutgoingMail(to = listOf("x@y.z"), subject = "s", bodyText = "b"),
)
assertEquals("droid@mail.example.com", (msg.from.first() as InternetAddress).address)
}
}
@@ -0,0 +1,140 @@
package sh.haven.core.mail
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
/**
* CP-2 (Stage 2a) — logic-level coverage of [ImapMailClient] that needs no live
* server: the opaque message-id codec (the part most likely to break silently),
* wrong-param rejection, and IMAP inbox detection. The live read/fetch/parse
* path is proven against a real server by the CP-0 spike (same android-mail lib)
* and device-verified end-to-end in CP-5.
*/
class ImapMailClientTest {
@Test
fun messageIdRoundTrips() {
val cases = listOf(
"INBOX" to 1L,
"INBOX" to 9_999_999L,
"Archive/2026" to 42L, // hierarchy separator in the folder name
"[Gmail]/All Mail" to 7L, // spaces in the folder name
"Sent Items" to 123L,
)
for ((folder, uid) in cases) {
val (f, u) = ImapMailClient.decodeId(ImapMailClient.encodeId(folder, uid))
assertEquals("folder for $folder/$uid", folder, f)
assertEquals("uid for $folder/$uid", uid, u)
}
}
@Test
fun decodeRejectsMalformedIds() {
for (bad in listOf("", "INBOX", "INBOX ", " 5", "INBOX abc")) {
try {
ImapMailClient.decodeId(bad)
fail("expected rejection for malformed id: '$bad'")
} catch (e: IllegalArgumentException) {
// expected
}
}
}
@Test
fun loginRejectsNonImapParams() = runBlocking {
try {
ImapMailClient().login("s1", MailConnectParams.Proton(username = "u", password = "p"))
fail("expected IllegalArgumentException for Proton params on the IMAP engine")
} catch (e: IllegalArgumentException) {
assertTrue(e.message!!.contains("Imap"))
}
}
@Test
fun imapInboxIsDetectedByFullName() {
assertTrue(MailFolder(id = "INBOX", name = "INBOX", type = 0).isInbox)
assertTrue(MailFolder(id = "inbox", name = "inbox", type = 0).isInbox)
assertTrue("Proton inbox id still works", MailFolder(id = "0", name = "Inbox", type = 3).isInbox)
assertTrue(!MailFolder(id = "Archive", name = "Archive", type = 0).isInbox)
}
@Test
fun imapFolderIdMapsInboxSentinel() {
// The engine-neutral read layer may pass Proton's inbox sentinel ("0"); IMAP has no
// such folder, so it normalises to "INBOX". Every other id passes through unchanged.
assertEquals("INBOX", ImapMailClient.imapFolderId("0"))
assertEquals("INBOX", ImapMailClient.imapFolderId(MailFolder.INBOX_ID))
assertEquals("INBOX", ImapMailClient.imapFolderId("INBOX"))
assertEquals("[Gmail]/All Mail", ImapMailClient.imapFolderId("[Gmail]/All Mail"))
assertEquals("Work/2026", ImapMailClient.imapFolderId("Work/2026"))
}
@Test
fun buildSearchTermComposesCriteria() {
// No criteria → null (caller treats as "no search").
assertNull(ImapMailClient.buildSearchTerm(MailSearchCriteria()))
// One criterion → the bare term (no AndTerm wrapper).
val one = ImapMailClient.buildSearchTerm(MailSearchCriteria(subject = "invoice"))
assertTrue(one is javax.mail.search.SubjectTerm)
// Multiple → an AndTerm over all of them.
val many = ImapMailClient.buildSearchTerm(
MailSearchCriteria(from = "a@b.com", unreadOnly = true, sinceEpochSec = 1_700_000_000L),
)
assertTrue(many is javax.mail.search.AndTerm)
assertEquals(3, (many as javax.mail.search.AndTerm).terms.size)
}
@Test
fun folderRoleMapsImapSpecialUse() {
// Gmail's `[Gmail]/*` special-use attributes (leaf names + RFC 6154 / Gmail attrs).
assertEquals(MailFolderRole.SENT, ImapMailClient.folderRole("Sent Mail", listOf("\\HasNoChildren", "\\Sent")))
assertEquals(MailFolderRole.DRAFTS, ImapMailClient.folderRole("Drafts", listOf("\\Drafts")))
assertEquals(MailFolderRole.TRASH, ImapMailClient.folderRole("Trash", listOf("\\Trash")))
assertEquals(MailFolderRole.SPAM, ImapMailClient.folderRole("Spam", listOf("\\Junk")))
assertEquals(MailFolderRole.STARRED, ImapMailClient.folderRole("Starred", listOf("\\Flagged")))
assertEquals(MailFolderRole.IMPORTANT, ImapMailClient.folderRole("Important", listOf("\\Important")))
assertEquals(MailFolderRole.ARCHIVE, ImapMailClient.folderRole("All Mail", listOf("\\All")))
assertEquals(MailFolderRole.ARCHIVE, ImapMailClient.folderRole("Archive", listOf("\\Archive")))
// INBOX wins by name even when no special-use attribute is present.
assertEquals(MailFolderRole.INBOX, ImapMailClient.folderRole("INBOX", emptyList()))
assertEquals(MailFolderRole.INBOX, ImapMailClient.folderRole("inbox", listOf("\\Marked")))
// A plain user label / folder is NONE.
assertEquals(MailFolderRole.NONE, ImapMailClient.folderRole("Work", listOf("\\HasChildren")))
// Attribute match is case-insensitive (servers vary).
assertEquals(MailFolderRole.SENT, ImapMailClient.folderRole("X", listOf("\\sent")))
}
@Test
fun noselectFoldersAreNotSelectable() {
// Gmail's "[Gmail]" parent is \Noselect — opening it throws, so listFolders must drop it.
assertTrue(!ImapMailClient.folderSelectable(listOf("\\Noselect", "\\HasChildren")))
assertTrue("case-insensitive", !ImapMailClient.folderSelectable(listOf("\\noselect")))
assertTrue(ImapMailClient.folderSelectable(listOf("\\HasNoChildren", "\\Sent")))
assertTrue("no attributes = selectable", ImapMailClient.folderSelectable(emptyList()))
}
@Test
fun recentSliceWindowsTheNewestMessages() {
// 1-based message numbers 1=oldest .. count=newest.
// First page: the most-recent `limit`.
assertEquals(901..1000, ImapMailClient.recentSlice(count = 1000, limit = 100, offset = 0))
// Second page ("Load older").
assertEquals(801..900, ImapMailClient.recentSlice(count = 1000, limit = 100, offset = 100))
// Final short page clamps the low end to 1 (the remaining oldest).
assertEquals(1..50, ImapMailClient.recentSlice(count = 1000, limit = 100, offset = 950))
// A folder smaller than a page returns all of it.
assertEquals(1..50, ImapMailClient.recentSlice(count = 50, limit = 100, offset = 0))
}
@Test
fun recentSliceReturnsNullWhenNothingToFetch() {
assertNull("empty folder", ImapMailClient.recentSlice(count = 0, limit = 100, offset = 0))
assertNull("offset == count", ImapMailClient.recentSlice(count = 1000, limit = 100, offset = 1000))
assertNull("offset past end", ImapMailClient.recentSlice(count = 1000, limit = 100, offset = 5000))
assertNull("non-positive limit", ImapMailClient.recentSlice(count = 1000, limit = 0, offset = 0))
}
}
@@ -0,0 +1,109 @@
package sh.haven.core.mail
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
/**
* CP-1 (Stage 2a) — proves [MailSessionManager] routes by the session's
* [MailEngine] across a multi-engine registry, so a Proton and an IMAP session
* each reach their own [MailClient]. No mockk: a recording fake suffices.
*/
class MailSessionManagerRoutingTest {
private class FakeClient : MailClient {
val logins = mutableListOf<Pair<String, MailConnectParams>>()
val logouts = mutableListOf<String>()
override suspend fun login(sessionId: String, params: MailConnectParams): MailLoginResult {
logins += sessionId to params
return MailLoginResult(uid = "uid", accessToken = "at", refreshToken = "rt", saltedKeyPass = "skp")
}
override suspend fun listFolders(sessionId: String) = emptyList<MailFolder>()
override suspend fun listMessages(
sessionId: String,
folderId: String,
desc: Boolean,
limit: Int,
offset: Int,
) = emptyList<MailMessage>()
override suspend fun getMessageRaw(sessionId: String, messageId: String) = ByteArray(0)
override suspend fun send(sessionId: String, mail: OutgoingMail) = SendResult(null, false)
override suspend fun setSeen(sessionId: String, messageId: String, seen: Boolean) {}
override suspend fun setFlagged(sessionId: String, messageId: String, flagged: Boolean) {}
override suspend fun moveMessage(sessionId: String, messageId: String, destFolderId: String) {}
override suspend fun deleteMessage(sessionId: String, messageId: String) {}
override suspend fun copyMessage(sessionId: String, messageId: String, destFolderId: String) {}
override suspend fun search(sessionId: String, folderId: String, criteria: MailSearchCriteria, limit: Int) = emptyList<MailMessage>()
override suspend fun saveDraft(sessionId: String, mail: OutgoingMail) = "Drafts"
override suspend fun createFolder(sessionId: String, name: String) = name
override suspend fun deleteFolder(sessionId: String, folderId: String) {}
override suspend fun folderUidState(sessionId: String, folderId: String) = MailFolderUidState(1, null, 0)
override suspend fun listSince(sessionId: String, folderId: String, sinceUid: Long, max: Int) = emptyList<MailNewMessage>()
override suspend fun logout(sessionId: String) { logouts += sessionId }
}
private fun managerWith(proton: FakeClient, imap: FakeClient) =
MailSessionManager(mapOf(MailEngine.PROTON to proton, MailEngine.IMAP to imap))
@Test
fun connectRoutesToTheSessionsEngine() = runBlocking {
val proton = FakeClient(); val imap = FakeClient()
val mgr = managerWith(proton, imap)
val ps = mgr.registerSession("p1", "Proton", MailEngine.PROTON)
mgr.connectSession(ps, MailConnectParams.Proton(username = "u", password = "pw"))
val isid = mgr.registerSession("p2", "Imap", MailEngine.IMAP)
mgr.connectSession(
isid,
MailConnectParams.Imap(
username = "u", password = "pw",
server = "imap.example.com", port = 993, smtpPort = 465, tls = true,
),
)
assertEquals("proton engine saw exactly its session", listOf(ps), proton.logins.map { it.first })
assertEquals("imap engine saw exactly its session", listOf(isid), imap.logins.map { it.first })
assertTrue(proton.logins[0].second is MailConnectParams.Proton)
assertTrue(imap.logins[0].second is MailConnectParams.Imap)
}
@Test
fun clientLookupReturnsTheEngineForProfileAndSession() = runBlocking {
val proton = FakeClient(); val imap = FakeClient()
val mgr = managerWith(proton, imap)
val ps = mgr.registerSession("p1", "Proton", MailEngine.PROTON)
mgr.connectSession(ps, MailConnectParams.Proton(username = "u", password = "pw"))
val isid = mgr.registerSession("p2", "Imap", MailEngine.IMAP)
mgr.connectSession(
isid,
MailConnectParams.Imap(
username = "u", password = "pw",
server = "s", port = 993, smtpPort = 465, tls = true,
),
)
assertSame(proton, mgr.clientForProfile("p1"))
assertSame(imap, mgr.clientForProfile("p2"))
assertSame(proton, mgr.clientForSession(ps))
assertSame(imap, mgr.clientForSession(isid))
assertNull("unknown profile has no client", mgr.clientForProfile("nope"))
assertNull("unknown session has no client", mgr.clientForSession("nope"))
}
@Test
fun connectOnUnknownSessionThrows() = runBlocking {
val mgr = managerWith(FakeClient(), FakeClient())
try {
mgr.connectSession("ghost", MailConnectParams.Proton(username = "u", password = "pw"))
fail("expected IllegalStateException for an unregistered session")
} catch (e: IllegalStateException) {
assertTrue(e.message!!.contains("ghost"))
}
}
}