Modern Apps git

← Modern-Apps.git

email: add outlook oauth

Commit
26514cab25bca571ac1886981daf11dcfd7f0c21
Author
Vayun Mathur <[email protected]>
When
2026-07-16 19:49 UTC (4 months ago)
Parents
690082c

Diff

email/build.gradle.kts
diff --git a/email/build.gradle.kts b/email/build.gradle.ktsindex 0fcde79b3d..61a22ac738 100644--- a/email/build.gradle.kts+++ b/email/build.gradle.kts@@ -7,6 +7,18 @@ android {     namespace = "com.vayunmathur.email"     defaultConfig {         applicationId = "com.vayunmathur.email"++        // Outlook / Microsoft 365 OAuth. Public values (client ID is an+        // identifier, not a secret) so they're committed and the build stays+        // reproducible. Override with -PEVERYSYNC_* style properties if needed.+        val outlookClientId = (project.findProperty("EMAIL_OUTLOOK_CLIENT_ID")+            ?: "4ee55fe9-12c1-4392-82e6-6c7a2a7954c8").toString()+        buildConfigField("String", "OUTLOOK_OAUTH_CLIENT_ID", "\"$outlookClientId\"")+        buildConfigField("String", "OUTLOOK_REDIRECT_URI", "\"com.vayunmathur.email://oauth\"")+    }++    buildFeatures {+        buildConfig = true     }      packaging {@@ -27,6 +39,7 @@ android { dependencies {     implementation(libs.jakarta.mail)     implementation(libs.jakarta.activation)+    implementation(libs.androidx.browser)     implementation(libs.ktor.client.core)     implementation(libs.ktor.client.cio)     implementation(libs.ktor.client.content.negotiation)
email/src/main/AndroidManifest.xml
diff --git a/email/src/main/AndroidManifest.xml b/email/src/main/AndroidManifest.xmlindex c13b1a3977..c32e330c63 100644--- a/email/src/main/AndroidManifest.xml+++ b/email/src/main/AndroidManifest.xml@@ -64,6 +64,19 @@             android:name=".util.EmailNotificationActionReceiver"             android:exported="false" /> +        <activity+            android:name=".ui.OutlookOAuthActivity"+            android:exported="true"+            android:launchMode="singleTask"+            android:theme="@android:style/Theme.NoDisplay">+            <intent-filter>+                <action android:name="android.intent.action.VIEW" />+                <category android:name="android.intent.category.DEFAULT" />+                <category android:name="android.intent.category.BROWSABLE" />+                <data android:scheme="com.vayunmathur.email" android:host="oauth" />+            </intent-filter>+        </activity>+         <activity             android:name=".intents.SearchIntent"             android:exported="true"
email/src/main/java/com/vayunmathur/email/EmailManager.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailManager.kt b/email/src/main/java/com/vayunmathur/email/EmailManager.ktindex f1cc98fb2a..01eea41869 100644--- a/email/src/main/java/com/vayunmathur/email/EmailManager.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailManager.kt@@ -6,6 +6,7 @@ import android.net.Uri import android.os.Environment import android.provider.MediaStore import com.vayunmathur.email.data.CredentialCrypto+import com.vayunmathur.email.data.OutlookOAuth import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File@@ -36,10 +37,18 @@ fun EmailAccount.smtpServer(): ServerConfig = ServerConfig(smtpHost, smtpPort, s fun EmailAccount.loginUser(): String = username.ifBlank { email }  /**- * Decrypt the stored credentials and produce an [EmailManager.AuthType] —- * always app-password (the only auth scheme this app supports).+ * Decrypt the stored credentials and produce an [EmailManager.AuthType].+ *+ * Outlook accounts (`authType == "oauth2"`) authenticate with a fresh XOAUTH2+ * access token (refreshed + persisted here on expiry); every other provider uses+ * a stored app password.  */-fun EmailAccount.authType(): EmailManager.AuthType {+suspend fun EmailAccount.resolveAuth(context: Context): EmailManager.AuthType {+    if (authType == "oauth2") {+        val token = OutlookOAuth.freshAccessToken(context, this)+            ?: error("Account $email is missing an OAuth access token")+        return EmailManager.AuthType.OAuth(token)+    }     val cipher = passwordEncrypted         ?: error("Account ${email} is missing passwordEncrypted")     val iv = passwordIv@@ -56,9 +65,17 @@ class EmailManager {      sealed class AuthType {         data class Password(val value: String) : AuthType()+        /** XOAUTH2 access token (Outlook / Microsoft 365). */+        data class OAuth(val token: String) : AuthType()     } -    private fun getImapSession(server: ServerConfig): Session {+    private val AuthType.credential: String+        get() = when (this) {+            is AuthType.Password -> value+            is AuthType.OAuth -> token+        }++    private fun getImapSession(server: ServerConfig, oauth: Boolean = false): Session {         val proto = server.imapProtocol         val properties = Properties().apply {             this["mail.store.protocol"] = proto@@ -66,6 +83,12 @@ class EmailManager {             this["mail.$proto.port"] = server.port.toString()             this["mail.$proto.fetchsize"] = "1048576"             this["mail.$proto.partialfetch"] = "true"+            if (oauth) {+                // Restrict SASL to XOAUTH2 so the token is sent instead of a password.+                this["mail.$proto.auth.mechanisms"] = "XOAUTH2"+                this["mail.$proto.auth.login.disable"] = "true"+                this["mail.$proto.auth.plain.disable"] = "true"+            }             if (server.useSsl) {                 this["mail.$proto.ssl.enable"] = "true"             } else {@@ -76,13 +99,18 @@ class EmailManager {         return Session.getInstance(properties).also { registerProviders(it) }     } -    private fun getSmtpSession(server: ServerConfig): Session {+    private fun getSmtpSession(server: ServerConfig, oauth: Boolean = false): Session {         val proto = server.smtpProtocol         val properties = Properties().apply {             this["mail.transport.protocol"] = proto             this["mail.$proto.host"] = server.host             this["mail.$proto.port"] = server.port.toString()             this["mail.$proto.auth"] = "true"+            if (oauth) {+                this["mail.$proto.auth.mechanisms"] = "XOAUTH2"+                this["mail.$proto.auth.login.disable"] = "true"+                this["mail.$proto.auth.plain.disable"] = "true"+            }             if (server.useSsl) {                 this["mail.$proto.ssl.enable"] = "true"             } else {@@ -116,11 +144,11 @@ class EmailManager {     }      suspend fun <T> withStore(server: ServerConfig, user: String, auth: AuthType, block: suspend (Store) -> T): T = withContext(Dispatchers.IO) {-        val session = getImapSession(server)+        val oauth = auth is AuthType.OAuth+        val session = getImapSession(server, oauth)         val store = session.getStore(server.imapProtocol)         try {-            val credential = (auth as AuthType.Password).value-            store.connect(server.host, server.port, user, credential)+            store.connect(server.host, server.port, user, auth.credential)             block(store)         } finally {             store.close()@@ -333,7 +361,8 @@ class EmailManager {         from: String? = null,         asHtml: Boolean = false     ) = withContext(Dispatchers.IO) {-        val session = getSmtpSession(server)+        val oauth = auth is AuthType.OAuth+        val session = getSmtpSession(server, oauth)         val message = MimeMessage(session)         message.setFrom(InternetAddress(from ?: user))         message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to))
email/src/main/java/com/vayunmathur/email/data/OutlookOAuth.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/OutlookOAuth.kt b/email/src/main/java/com/vayunmathur/email/data/OutlookOAuth.ktnew file mode 100644index 0000000000..be261a4fa9--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/data/OutlookOAuth.kt@@ -0,0 +1,206 @@+package com.vayunmathur.email.data++import android.content.Context+import android.net.Uri+import android.util.Base64+import android.util.Log+import androidx.browser.customtabs.CustomTabsIntent+import com.vayunmathur.email.BuildConfig+import com.vayunmathur.email.EmailAccount+import java.net.HttpURLConnection+import java.net.URL+import java.security.MessageDigest+import java.security.SecureRandom+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.jsonPrimitive++/**+ * Outlook / Microsoft 365 OAuth2 (Authorization Code + PKCE). Microsoft has+ * disabled basic auth (app passwords) for IMAP/SMTP, so Outlook accounts sign in+ * here and authenticate to the mail servers with XOAUTH2 access tokens.+ *+ * Public client — no secret ships in the APK (PKCE). The client ID is a public+ * identifier baked into [BuildConfig] so the build stays reproducible.+ */+object OutlookOAuth {+    private const val TAG = "OutlookOAuth"+    private const val AUTH_ENDPOINT = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"+    private const val TOKEN_ENDPOINT = "https://login.microsoftonline.com/common/oauth2/v2.0/token"+    private const val PREFS = "outlook_oauth"++    /** IMAP/SMTP XOAUTH2 scopes + OIDC scopes so we can read the account address. */+    private val SCOPES = listOf(+        "https://outlook.office.com/IMAP.AccessAsUser.All",+        "https://outlook.office.com/SMTP.Send",+        "offline_access",+        "openid",+        "email",+        "profile",+    )++    private val json = Json { ignoreUnknownKeys = true }++    val isConfigured: Boolean get() = BuildConfig.OUTLOOK_OAUTH_CLIENT_ID.isNotBlank()++    /** Launch the Microsoft sign-in page in a Custom Tab. */+    fun start(context: Context) {+        if (!isConfigured) return+        val verifier = randomUrlSafe(64)+        val challenge = codeChallenge(verifier)+        val state = randomUrlSafe(24)+        context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()+            .putString("verifier", verifier)+            .putString("state", state)+            .apply()++        val url = Uri.parse(AUTH_ENDPOINT).buildUpon()+            .appendQueryParameter("client_id", BuildConfig.OUTLOOK_OAUTH_CLIENT_ID)+            .appendQueryParameter("response_type", "code")+            .appendQueryParameter("redirect_uri", BuildConfig.OUTLOOK_REDIRECT_URI)+            .appendQueryParameter("response_mode", "query")+            .appendQueryParameter("scope", SCOPES.joinToString(" "))+            .appendQueryParameter("code_challenge", challenge)+            .appendQueryParameter("code_challenge_method", "S256")+            .appendQueryParameter("state", state)+            .build()+        CustomTabsIntent.Builder().build().launchUrl(context, url)+    }++    /** Handle the redirect: exchange the code, persist the account. Returns the email on success. */+    suspend fun complete(context: Context, redirect: Uri): String? {+        val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)+        val verifier = prefs.getString("verifier", null) ?: return null+        val expectedState = prefs.getString("state", null)+        val code = redirect.getQueryParameter("code") ?: return null+        if (redirect.getQueryParameter("state") != expectedState) {+            Log.e(TAG, "OAuth state mismatch")+            return null+        }++        val tokens = exchange(+            mapOf(+                "client_id" to BuildConfig.OUTLOOK_OAUTH_CLIENT_ID,+                "grant_type" to "authorization_code",+                "code" to code,+                "redirect_uri" to BuildConfig.OUTLOOK_REDIRECT_URI,+                "code_verifier" to verifier,+                "scope" to SCOPES.joinToString(" "),+            ),+        ) ?: return null+        prefs.edit().clear().apply()++        val email = tokens.idTokenEmail ?: return null+        val account = EmailAccount(+            email = email,+            provider = PROVIDER_OUTLOOK,+            imapHost = "outlook.office365.com",+            imapPort = 993,+            imapUseSsl = true,+            smtpHost = "smtp-mail.outlook.com",+            smtpPort = 587,+            smtpUseSsl = false,+            authType = "oauth2",+            accessToken = tokens.accessToken,+            refreshToken = tokens.refreshToken,+            expiresAt = tokens.expiresAtMs,+        )+        EmailDatabase.getInstance(context).emailDao().insertAccount(account)+        EmailSyncWorker.schedulePeriodicSync(context)+        EmailSyncWorker.runOneOffSync(context)+        ImapIdleService.start(context)+        return email+    }++    /**+     * Return a valid access token for [account], refreshing (and persisting) it+     * first when it is within a minute of expiring.+     */+    suspend fun freshAccessToken(context: Context, account: EmailAccount): String? {+        if (account.expiresAt > System.currentTimeMillis() + 60_000) return account.accessToken+        val refresh = account.refreshToken?.takeIf { it.isNotBlank() } ?: return account.accessToken.ifBlank { null }+        val tokens = exchange(+            mapOf(+                "client_id" to BuildConfig.OUTLOOK_OAUTH_CLIENT_ID,+                "grant_type" to "refresh_token",+                "refresh_token" to refresh,+                "redirect_uri" to BuildConfig.OUTLOOK_REDIRECT_URI,+                "scope" to SCOPES.joinToString(" "),+            ),+        ) ?: return account.accessToken.ifBlank { null }++        val updated = account.copy(+            accessToken = tokens.accessToken,+            refreshToken = tokens.refreshToken ?: account.refreshToken,+            expiresAt = tokens.expiresAtMs,+        )+        EmailDatabase.getInstance(context).emailDao().insertAccount(updated)+        return updated.accessToken+    }++    private data class Tokens(+        val accessToken: String,+        val refreshToken: String?,+        val expiresAtMs: Long,+        val idTokenEmail: String?,+    )++    private fun exchange(form: Map<String, String>): Tokens? {+        return try {+            val body = form.entries.joinToString("&") {+                "${Uri.encode(it.key)}=${Uri.encode(it.value)}"+            }+            val conn = (URL(TOKEN_ENDPOINT).openConnection() as HttpURLConnection).apply {+                requestMethod = "POST"+                doOutput = true+                setRequestProperty("Content-Type", "application/x-www-form-urlencoded")+            }+            conn.outputStream.use { it.write(body.toByteArray()) }+            val text = if (conn.responseCode in 200..299) {+                conn.inputStream.bufferedReader().use { it.readText() }+            } else {+                Log.e(TAG, "token endpoint ${conn.responseCode}: ${conn.errorStream?.bufferedReader()?.readText()}")+                return null+            }+            val root = json.parseToJsonElement(text) as? JsonObject ?: return null+            val access = root["access_token"]?.jsonPrimitive?.contentOrNull() ?: return null+            val expiresIn = root["expires_in"]?.jsonPrimitive?.contentOrNull()?.toLongOrNull() ?: 3600L+            Tokens(+                accessToken = access,+                refreshToken = root["refresh_token"]?.jsonPrimitive?.contentOrNull(),+                expiresAtMs = System.currentTimeMillis() + expiresIn * 1000,+                idTokenEmail = root["id_token"]?.jsonPrimitive?.contentOrNull()?.let { emailFromIdToken(it) },+            )+        } catch (e: Exception) {+            Log.e(TAG, "token exchange failed", e)+            null+        }+    }++    /** Pull the address out of the OIDC id_token (email, else preferred_username). */+    private fun emailFromIdToken(idToken: String): String? {+        return try {+            val payload = idToken.split(".").getOrNull(1) ?: return null+            val decoded = String(Base64.decode(payload, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP))+            val obj = json.parseToJsonElement(decoded) as? JsonObject ?: return null+            (obj["email"] ?: obj["preferred_username"] ?: obj["upn"])?.jsonPrimitive?.contentOrNull()+        } catch (e: Exception) {+            Log.e(TAG, "id_token decode failed", e)+            null+        }+    }++    private fun kotlinx.serialization.json.JsonPrimitive.contentOrNull(): String? =+        runCatching { content }.getOrNull()?.ifBlank { null }++    private fun randomUrlSafe(bytes: Int): String {+        val buf = ByteArray(bytes)+        SecureRandom().nextBytes(buf)+        return Base64.encodeToString(buf, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)+    }++    private fun codeChallenge(verifier: String): String {+        val digest = MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray())+        return Base64.encodeToString(digest, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)+    }+}
email/src/main/java/com/vayunmathur/email/ui/OutlookOAuthActivity.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/OutlookOAuthActivity.kt b/email/src/main/java/com/vayunmathur/email/ui/OutlookOAuthActivity.ktnew file mode 100644index 0000000000..37f23ff8b5--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/OutlookOAuthActivity.kt@@ -0,0 +1,38 @@+package com.vayunmathur.email.ui++import android.content.Intent+import android.os.Bundle+import android.widget.Toast+import androidx.activity.ComponentActivity+import androidx.lifecycle.lifecycleScope+import com.vayunmathur.email.MainActivity+import com.vayunmathur.email.data.OutlookOAuth+import kotlinx.coroutines.launch++/**+ * Receives the Outlook OAuth redirect (`com.vayunmathur.email://oauth`),+ * completes the PKCE token exchange + account creation, then returns to the app.+ */+class OutlookOAuthActivity : ComponentActivity() {+    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        val data = intent?.data+        if (data == null) {+            finish()+            return+        }+        lifecycleScope.launch {+            val email = OutlookOAuth.complete(applicationContext, data)+            Toast.makeText(+                applicationContext,+                if (email != null) "Added $email" else "Microsoft sign-in failed",+                Toast.LENGTH_SHORT,+            ).show()+            startActivity(+                Intent(this@OutlookOAuthActivity, MainActivity::class.java)+                    .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP),+            )+            finish()+        }+    }+}