diff --git a/ANDROID_SECURITY_PLAN.md b/ANDROID_SECURITY_PLAN.md index 7473f74..ee14e89 100644 --- a/ANDROID_SECURITY_PLAN.md +++ b/ANDROID_SECURITY_PLAN.md @@ -1,15 +1,15 @@ # Android security plan for ep-mail -Status: **Plan**. Android already has several useful protections, but it does not yet provide Android OpenPGP support, an app lock, or a release security assurance process. This document turns the remaining Android security work into an incremental plan. It is not a security certification or a substitute for an independent review. +Status: **Experimental Android OpenPGP implementation for local testing; security review and release gate remain open.** This document tracks Android protections and the remaining work. Neither the test implementation nor this plan is a security certification or a substitute for an independent review. Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECURITY_REVIEW.md), and [TODO.md](./TODO.md). ## Implementation progress (2026-11-03) -- Implemented: explicit Android cleartext denial and backup/data-extraction exclusions; removed the wildcard Cordova origin and unused broad `FileProvider`; DAV now requires HTTPS, rejects embedded credentials/fragments, stays on the configured origin, and does not follow redirects; saved attachment names are sanitized; notification details are opt-in, stored in the encrypted vault, and redacted on the lock screen; native logs no longer expose mailbox content; debug APKs are labeled as debug and signed release builds require environment-provided signing credentials. -- Tested: DAV URL, attachment-name, and notification privacy policies have Android unit tests. The debug Android build and unit tests pass, as does the Node test suite. -- Phase 2 preparation only: OpenPGP.js is pinned to the locked 6.3.2 version. `npm audit --omit=dev` reports three moderate advisories in `ip-address` and the `nodemailer`/`mailparser` dependency chain; those dependency updates are not applied here because the suggested mailparser update is outside the current declared range and needs separate compatibility review. -- Still open: invalid-certificate integration tests, device-level review of the merged release APK, app lock/biometric unlock, full vault lifecycle testing, and Android OpenPGP. OpenPGP work remains gated on an independent cryptography/security review. +- Implemented: explicit Android cleartext denial and backup/data-extraction exclusions; removed the wildcard Cordova origin and unused broad `FileProvider`; DAV now requires HTTPS, rejects embedded credentials/fragments, stays on the configured origin, and does not follow redirects; saved attachment names are sanitized; notification details are opt-in, stored in the encrypted vault, and redacted on the lock screen; the optional native Android app lock covers the WebView, disables JavaScript bridge access while locked, and uses the device credential without blocking background sync; native logs no longer expose mailbox content; debug APKs are labeled as debug and signed release builds require environment-provided signing credentials. +- Tested: DAV URL, attachment-name, and notification privacy policies have Android unit tests. The optional app lock was exercised on an Android emulator with a device PIN, including background lock and unlock. Phone and landscape layouts were checked for horizontal overflow. The debug Android build and unit tests pass, as does the Node test suite. +- Experimental Phase 2 implementation: Android now bundles the pinned OpenPGP.js 6.3.2, stores passphrase-protected keys and public contacts in the existing Keystore-encrypted vault, supports key generation/import/export, contact trust controls, PGP/MIME encrypt/sign, and on-demand PGP/MIME or inline-message decryption. Encrypted sends are converted to ciphertext before native sending or offline queueing; decrypted content is held in renderer memory only. Android key-server lookup is disabled, and PGP/MIME messages are capped at 25 MiB on the Android test path. This test path has not had an independent human cryptography review and is not approved for sensitive or production use. +- Still open before release: independent cryptography/security review; native enforcement of trust/key-replacement and plaintext-downgrade decisions; full signed/inline-message and hostile-input parity tests; Android/GnuPG/Thunderbird interoperability; Keystore lifecycle/recovery and biometric design; invalid-certificate integration tests; device-level review of a production-signed merged APK; app-lock timeout and recovery polish; and resolution/compatibility review of the three moderate `npm audit --omit=dev` advisories in `ip-address` and the `nodemailer`/`mailparser` dependency chain. ## Goals and limits diff --git a/ENCRYPTION_PLAN.md b/ENCRYPTION_PLAN.md index cc35fe5..77e36d4 100644 --- a/ENCRYPTION_PLAN.md +++ b/ENCRYPTION_PLAN.md @@ -1,6 +1,6 @@ # Encryption plan: OpenPGP mail encryption for ep-mail -Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android OpenPGP support and an independent human security review are still open. See [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md) for the broader Android security roadmap. Automated review findings and their fixes are documented in [SECURITY_REVIEW.md](./SECURITY_REVIEW.md); see [TODO.md](./TODO.md) for follow-up work. +Status: **Desktop implementation is complete; an experimental Android Phase 2 path is available for local testing only.** Android security review, native policy enforcement, and release assurance remain open, and the Android test path must not be used for sensitive mail. See [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md) for details. Automated review findings and their fixes are documented in [SECURITY_REVIEW.md](./SECURITY_REVIEW.md); see [TODO.md](./TODO.md) for follow-up work. ## 1. Format: OpenPGP with PGP/MIME (RFC 3156) @@ -63,7 +63,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later. - [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): platform-independent key store with an injected storage backend. - [desktop/main.cjs](./desktop/main.cjs): wraps the store with `safeStorage` (`pgp-keys.enc` in the user data folder) and exposes `pgp:*` IPC handlers; key files are saved through native dialogs. - [desktop/preload.cjs](./desktop/preload.cjs): exposes `daybreakMail.pgp`. -- [pgp-ui.js](./pgp-ui.js): Settings → **Encryption keys**. Hidden on platforms without a key store (Android until Phase 4). +- [pgp-ui.js](./pgp-ui.js): Settings → **Encryption keys**. Desktop key management is production functionality; Android exposes an experimental test UI. - Tests: `npm test` ([tests/pgp-keystore.test.cjs](./tests/pgp-keystore.test.cjs)). ## 7. Phases 2–5 implementation notes @@ -72,7 +72,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later. - [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): also stores contact public keys with trust levels (`unknown`, `trusted`, `verified`) and the passphrase-memory setting. - Encrypted messages appear in the list as "Encrypted message"; they are decrypted on demand (`pgp:decrypt-message`) and the plaintext is never cached on disk. Attachments are read from the decrypted payload. - Compose shows Encrypt and Sign options. Encrypt turns on by default when every recipient has a key; if a key is missing the app asks before sending unencrypted. Encryption happens before the message is sent or queued offline, so passphrases and plaintext never enter the outbox. The Sent copy is also encrypted to the sender's own key. -- Multiple outgoing attachments are included in the OpenPGP MIME payload and encrypted/signed together with the body. Android does not yet implement OpenPGP. +- Multiple outgoing attachments are included in the OpenPGP MIME payload and encrypted/signed together with the body. Android's test path supports this format up to 25 MiB, but it has not completed desktop parity, independent review, or release assurance. - Attachment selection has no app-enforced aggregate size cap; local storage capacity and mail-provider limits still apply. - A signature from a key that differs from the one on file for the sender is flagged as a changed key. - Interop: [tests/pgp-gnupg-interop.test.cjs](./tests/pgp-gnupg-interop.test.cjs) runs against a real GnuPG (skipped when it is not installed). diff --git a/README.md b/README.md index 1ac5368..d097e48 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ See the project architecture overview in [ARCHITECTURE.md](./ARCHITECTURE.md). ## Android app -The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, secure account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run: +The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, encrypted account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Android Settings can enable an app lock that covers the WebView and disables its JavaScript bridge when the app leaves the foreground; unlock requires the device PIN, pattern, or password, while background mail sync continues. Configure a secure Android screen lock before enabling it. This is a local privacy control, not protection against a compromised or rooted device. Android OpenPGP is now present as an **experimental test-only feature** for key and message testing. It has not had an independent cryptography/security review and is not approved for sensitive or production mail; do not rely on it to protect important messages. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run: ```sh npm install @@ -39,4 +39,4 @@ On Windows, `py -m http.server 8000` is also available on many Python installati ## Current scope -Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. Compose can attach multiple files of any type; attachments are retained in local drafts and sent with the message. There is no app-enforced total-size cap, though local storage and mail providers may impose limits. Desktop encrypts and signs attachments together with the body when OpenPGP is selected. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys stored encrypted by the operating system; you can import contact keys, enable selected key servers (all are disabled initially), search all enabled servers, and publish a key to one explicitly selected server after a native confirmation names the destination. Discovered keys remain unverified until you compare fingerprints independently. Desktop can read encrypted or signed OpenPGP mail and encrypt or sign outgoing messages (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)); Android OpenPGP support is not available yet. Run the tests with `npm test`. +Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. Compose can attach multiple files of any type; attachments are retained in local drafts and sent with the message. There is no app-enforced total-size cap, though local storage and mail providers may impose limits. Desktop encrypts and signs attachments together with the body when OpenPGP is selected. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys stored encrypted by the operating system; you can import contact keys, enable selected key servers (all are disabled initially), search all enabled servers, and publish a key to one explicitly selected server after a native confirmation names the destination. Discovered keys remain unverified until you compare fingerprints independently. Desktop supports encrypted and signed OpenPGP mail. Android has an experimental test implementation for key management and PGP/MIME send/read; it is not independently reviewed and is not suitable for sensitive mail (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)). Run the tests with `npm test`. diff --git a/SECURITY_REVIEW.md b/SECURITY_REVIEW.md index 44d623d..c885217 100644 --- a/SECURITY_REVIEW.md +++ b/SECURITY_REVIEW.md @@ -64,7 +64,7 @@ Applied fixes: - Replacement-key and trust-elevation confirmation are enforced in `desktop/ipc/pgp.cjs`. `tests/pgp-ipc-registration.test.cjs` verifies both cancellation and confirmation paths for those changes. - Main-process plaintext-send confirmation is implemented in `desktop/ipc/mail.cjs`; direct regression coverage for that dialog's accept/cancel branches remains open. - Human cryptography/security review and dependency remediation remain outstanding. OpenPGP.js is pinned to 6.3.2; `npm audit --omit=dev` currently reports three moderate advisories in `ip-address` and the Nodemailer/mailparser dependency chain. GnuPG interoperability tests are in the current test suite and should be rerun after dependency changes. -- Android has no OpenPGP implementation and is outside the reviewed desktop scope. +- Android's experimental OpenPGP implementation was added after the desktop review and is outside the reviewed scope. It must not be relied on for sensitive mail until independently reviewed; native trust/replacement and downgrade enforcement also remain open. ## Third review pass (2026-10-17) diff --git a/TODO.md b/TODO.md index 39fe742..adfa994 100644 --- a/TODO.md +++ b/TODO.md @@ -26,23 +26,26 @@ ## Mail security -- [x] Add desktop support for encrypting and decrypting mail with OpenPGP (PGP/MIME). Android support remains open; see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md). +- [x] Add desktop support for encrypting and decrypting mail with OpenPGP (PGP/MIME); Android has a separate experimental implementation for local testing only. See [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md). - [x] Phase 1: foundation — OpenPGP.js, passphrase-protected key store (desktop), generate/import/export/delete keys, revocation certificate, tests, Settings UI. - [x] Phase 2: receive — detect PGP/MIME and inline PGP mail, decrypt on open, verify signatures, show encryption/signature status, handle missing keys and wrong passphrases. - [x] Phase 3: send — public-key keyring and key import from contacts/messages, encrypt and sign when composing, encrypted copy in Sent, warn instead of silently downgrading. - [x] Phase 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout. - - [ ] Phase 4 (Android): add Android Keystore key storage, biometric unlock, and the reading/sending bridge (encryption is desktop-only until then). + - [x] Experimental Android test path: Keystore-encrypted vault key storage, key/contact management, PGP/MIME encryption/signing, and on-demand decryption. + - [ ] Android release gate: native trust/replacement and downgrade enforcement, full parity/interoperability tests, independent human cryptography/security review, and signed release review. + - [ ] Android follow-up: biometric unlock, full vault lifecycle/recovery, signed/inline verification parity, and dependency advisory remediation. - [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests. - [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures). - [x] Phase 6: documentation and release. - [x] Manual interoperability check with Thunderbird. - [x] Address findings from the automated OpenPGP security reviews (see [SECURITY_REVIEW.md](./SECURITY_REVIEW.md)). - - [ ] Complete an independent human security review of the encryption code before expanding OpenPGP support to Android. + - [ ] Complete an independent human security review of desktop and Android encryption code before any production reliance or release. - [x] Pin OpenPGP.js to the exact lockfile version while security review is pending. - [ ] Resolve the current moderate dependency advisories reported by `npm audit --omit=dev` with compatibility tests. - [ ] Add direct IPC-handler tests for both accept and cancel paths of the main-process plaintext-send confirmation. - [ ] Complete the Android security work in [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md), including Android OpenPGP and release security checks. - [x] Make Android notification details opt-in, persist the preference in the encrypted vault, and redact lock-screen previews. + - [x] Add an optional native Android app lock using the device credential while leaving background mail sync available. ## Appearance and settings diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt index d72b981..d29abe0 100644 --- a/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt @@ -66,6 +66,70 @@ internal object AndroidAccountVault { write(store) return enabled } + + fun appLockEnabled(): Boolean = read().optBoolean("appLockEnabled", false) + + @Synchronized + fun setAppLockEnabled(enabled: Boolean): Boolean { + val store = read().put("appLockEnabled", enabled) + write(store) + return enabled + } + + fun pgpStore(): JSONObject = read().optJSONObject("pgpStore")?.let { JSONObject(it.toString()) } + ?: JSONObject().put("keys", JSONArray()).put("contacts", JSONArray()).put("settings", JSONObject()) + + @Synchronized + fun savePgpStore(candidate: JSONObject) { + validatePgpStore(candidate) + val store = read().put("pgpStore", JSONObject(candidate.toString())) + write(store) + } + + private fun validatePgpStore(candidate: JSONObject) { + require(candidate.toString().length <= 3_000_000) { "The OpenPGP key store is too large." } + require(!hasPassphraseField(candidate)) { "Passphrases must never be stored." } + val keys = candidate.optJSONArray("keys") ?: JSONArray() + val contacts = candidate.optJSONArray("contacts") ?: JSONArray() + require(keys.length() <= 20 && contacts.length() <= 500) { "The OpenPGP key store has too many entries." } + val fingerprint = Regex("^[0-9A-Fa-f]{40,64}$") + for (index in 0 until keys.length()) { + val entry = keys.optJSONObject(index) ?: throw IllegalArgumentException("An OpenPGP key entry is invalid.") + val privateKey = entry.optString("privateKey") + val publicKey = entry.optString("publicKey") + require(fingerprint.matches(entry.optString("fingerprint")) && + privateKey.length in 1..200_000 && privateKey.contains("BEGIN PGP PRIVATE KEY BLOCK") && + publicKey.length in 1..200_000 && publicKey.contains("BEGIN PGP PUBLIC KEY BLOCK")) { + "An OpenPGP key entry is invalid." + } + } + for (index in 0 until contacts.length()) { + val entry = contacts.optJSONObject(index) ?: throw IllegalArgumentException("An OpenPGP contact entry is invalid.") + val publicKey = entry.optString("publicKey") + require(fingerprint.matches(entry.optString("fingerprint")) && + publicKey.length in 1..200_000 && publicKey.contains("BEGIN PGP PUBLIC KEY BLOCK") && + !publicKey.contains("BEGIN PGP PRIVATE KEY BLOCK")) { + "An OpenPGP contact entry is invalid." + } + require(entry.optString("trust") in setOf("unknown", "trusted", "verified")) { + "An OpenPGP contact trust value is invalid." + } + } + } + + private fun hasPassphraseField(value: Any?): Boolean = when (value) { + is JSONObject -> { + val keys = value.keys() + var found = false + while (keys.hasNext() && !found) { + val key = keys.next() + found = key.contains("passphrase", ignoreCase = true) || hasPassphraseField(value.opt(key)) + } + found + } + is JSONArray -> (0 until value.length()).any { hasPassphraseField(value.opt(it)) } + else -> false + } fun account(id: String? = null): JSONObject? { val store = read() diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt index 8de4f5a..8ed562c 100644 --- a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt @@ -10,7 +10,9 @@ import android.webkit.MimeTypeMap import com.sun.mail.imap.IMAPFolder import org.json.JSONArray import org.json.JSONObject -import java.io.File +import java.io.File +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream import java.text.DateFormat import java.text.SimpleDateFormat import java.util.Calendar @@ -262,12 +264,28 @@ internal object AndroidMailService { JSONObject().put("ok", true) } - fun send(account: JSONObject, input: JSONObject): JSONObject { - val recipient = input.optString("to").trim() - require(recipient.isNotEmpty()) { "Add at least one recipient." } - val properties = smtpProperties(account) - val session = Session.getInstance(properties, credentials(account)) - val message = MimeMessage(session) + fun send(account: JSONObject, input: JSONObject): JSONObject { + val rawBase64 = input.optString("rawBase64") + val session = Session.getInstance(smtpProperties(account), credentials(account)) + val message: MimeMessage + if (rawBase64.isNotBlank()) { + require(rawBase64.length <= 36_000_000 && rawBase64.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) { + "The encrypted message is too large or invalid." + } + val bytes = Base64.decode(rawBase64, Base64.DEFAULT) + require(bytes.size <= 25 * 1024 * 1024) { "The encrypted message is too large to send on Android testing builds." } + message = MimeMessage(session, ByteArrayInputStream(bytes)) + val contentType = message.contentType.lowercase(Locale.ROOT) + require(contentType.startsWith("multipart/encrypted") || contentType.startsWith("multipart/signed")) { + "Only an OpenPGP MIME message can use the encrypted send path." + } + require(message.from?.isNotEmpty() == true && message.allRecipients?.isNotEmpty() == true) { + "The encrypted message needs a sender and at least one recipient." + } + } else { + val recipient = input.optString("to").trim() + require(recipient.isNotEmpty()) { "Add at least one recipient." } + message = MimeMessage(session) message.setFrom(InternetAddress(account.optString("email"), displayName(account), "UTF-8")) message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, true)) val cc = input.optString("cc").trim() @@ -306,9 +324,10 @@ internal object AndroidMailService { } message.setContent(multipart) } - message.sentDate = Date() - message.saveChanges() - input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) } + message.sentDate = Date() + message.saveChanges() + input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) } + } val transport = session.getTransport("smtp") try { @@ -334,8 +353,36 @@ internal object AndroidMailService { } catch (_: Exception) { savedToSent = false } - return JSONObject().put("ok", true).put("savedToSent", savedToSent) - } + return JSONObject().put("ok", true).put("savedToSent", savedToSent) + } + + fun pgpMessageSource(account: JSONObject, folderName: String, uid: Long): JSONObject = withStore(account) { _, store -> + require(uid > 0) { "That message could not be identified." } + val folder = resolveFolder(store, folderName) ?: throw IllegalStateException("That mail folder could not be found.") + folder.open(Folder.READ_ONLY) + try { + val message = (folder as? UIDFolder)?.getMessageByUID(uid) + ?: throw IllegalStateException("The message is no longer available.") + val output = ByteArrayOutputStream() + message.writeTo(output) + val bytes = output.toByteArray() + require(bytes.size <= 25 * 1024 * 1024) { "This encrypted message is too large to open on Android testing builds." } + JSONObject().put("rawBase64", Base64.encodeToString(bytes, Base64.NO_WRAP)) + } finally { + folder.close(false) + } + } + + fun savePgpAttachment(context: Context, input: JSONObject): JSONObject { + val filename = input.optString("filename").replace(Regex("[\\\\/\\r\\n\\u0000]"), "").take(255).ifBlank { "attachment" } + val contentType = input.optString("contentType", "application/octet-stream").lowercase(Locale.ROOT) + require(contentType.matches(Regex("^[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+$"))) { "The attachment content type is invalid." } + val encoded = input.optString("contentBase64") + require(encoded.length <= 36_000_000 && encoded.length % 4 == 0 && encoded.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) { + "The attachment is too large or invalid." + } + return saveAttachmentBytes(context, filename, contentType, Base64.decode(encoded, Base64.DEFAULT)) + } fun flushOutbox(account: JSONObject) { val accountId = account.optString("id") @@ -594,10 +641,12 @@ internal object AndroidMailService { val body = ArrayList() val htmlBodies = ArrayList() val attachments = JSONArray() - val links = linkedSetOf() - collectParts(message, body, htmlBodies, attachments, links) - val bodyText = body.joinToString("\n\n").trim().take(8000) - val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180) + val links = linkedSetOf() + collectParts(message, body, htmlBodies, attachments, links) + val bodyText = body.joinToString("\n\n").trim().take(8000) + val encrypted = isEncryptedMessage(message) || bodyText.contains("-----BEGIN PGP MESSAGE-----") + val visibleBody = if (encrypted) "This message is encrypted. Unlock it with your OpenPGP key to read it." else bodyText + val snippet = (if (encrypted) "Encrypted message" else visibleBody.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180) val date = message.receivedDate ?: message.sentDate ?: Date() val tags = JSONArray().put(requestedFolder) val ruleLabels = account?.optJSONObject("ruleLabels")?.optJSONArray("$labelFolder:$uid") @@ -618,8 +667,9 @@ internal object AndroidMailService { .put("color", "#dce6df") .put("sender", senderName) .put("email", senderEmail) - .put("subject", subject) - .put("snippet", snippet) + .put("subject", subject) + .put("snippet", snippet) + .put("encrypted", encrypted) .put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date)) .put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date)) .put("timestamp", date.time) @@ -632,14 +682,23 @@ internal object AndroidMailService { .put("sourceFolder", labelFolder) .put("html", htmlBodies.firstOrNull()?.take(100000) ?: "") .put("body", JSONArray().apply { - val paragraphs = bodyText.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40) + val paragraphs = visibleBody.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40) if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put) }) .put("links", JSONArray().apply { links.take(30).forEach(::put) }) .put("attachments", attachments) .put("attachment", files.firstOrNull()?.optString("filename") ?: JSONObject.NULL) - .put("size", files.firstOrNull()?.optString("size") ?: "") - } + .put("size", files.firstOrNull()?.optString("size") ?: "") + } + + private fun isEncryptedMessage(part: javax.mail.Part): Boolean { + if (part.isMimeType("multipart/encrypted")) return true + val content = try { part.content } catch (_: Exception) { return false } + if (content is Multipart) { + for (index in 0 until content.count) if (isEncryptedMessage(content.getBodyPart(index))) return true + } else if (content is String && content.contains("-----BEGIN PGP MESSAGE-----")) return true + return false + } private fun attachmentList(attachments: JSONArray): List = (0 until attachments.length()).map { attachments.getJSONObject(it) } diff --git a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt index 517990d..8301377 100644 --- a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt +++ b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt @@ -76,9 +76,80 @@ class EpMailPlugin : Plugin() { call.reject(error.message ?: "Could not save notification privacy settings.") } } - - @PluginMethod - fun getAccount(call: PluginCall) { + + @PluginMethod + fun getAppLockSettings(call: PluginCall) { + try { + val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager + call.resolve(JSObject() + .put("enabled", AndroidAccountVault.appLockEnabled()) + .put("deviceSecure", keyguard.isDeviceSecure)) + } catch (error: Exception) { + call.reject(error.message ?: "Could not read app-lock settings.") + } + } + + @PluginMethod + fun setAppLockEnabled(call: PluginCall) { + try { + val enabled = call.getBoolean("enabled") + ?: throw IllegalArgumentException("Choose whether to lock ep-mail when you leave it.") + val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager + require(!enabled || keyguard.isDeviceSecure) { + "Set a screen lock in Android Settings before enabling the app lock." + } + AndroidAccountVault.setAppLockEnabled(enabled) + (activity as? MainActivity)?.onAppLockSettingChanged(enabled) + call.resolve(JSObject().put("enabled", enabled).put("deviceSecure", keyguard.isDeviceSecure)) + } catch (error: Exception) { + call.reject(error.message ?: "Could not save app-lock settings.") + } + } + + @PluginMethod + fun pgpLoadStore(call: PluginCall) { + try { + call.resolve(AndroidAccountVault.pgpStore().toJSObject()) + } catch (error: Exception) { + call.reject(error.message ?: "Could not load the Android OpenPGP key store.") + } + } + + @PluginMethod + fun pgpSaveStore(call: PluginCall) { + try { + val candidate = call.getObject("store") ?: throw IllegalArgumentException("The OpenPGP key store is missing.") + AndroidAccountVault.savePgpStore(JSONObject(candidate.toString())) + call.resolve(JSObject().put("ok", true)) + } catch (error: Exception) { + call.reject(error.message ?: "Could not save the Android OpenPGP key store.") + } + } + + @PluginMethod + fun pgpGetMessageSource(call: PluginCall) { + try { + val account = AndroidAccountVault.account() + ?: throw IllegalStateException("Add a mail account before opening messages.") + val folder = call.getString("folder") ?: "Inbox" + val uid = call.getLong("uid") ?: 0L + call.resolve(AndroidMailService.pgpMessageSource(account, folder, uid).toJSObject()) + } catch (error: Exception) { + call.reject(error.message ?: "Could not load the encrypted message.") + } + } + + @PluginMethod + fun savePgpAttachment(call: PluginCall) { + try { + call.resolve(AndroidMailService.savePgpAttachment(context, JSONObject(call.data.toString())).toJSObject()) + } catch (error: Exception) { + call.reject(error.message ?: "Could not save the decrypted attachment.") + } + } + + @PluginMethod + fun getAccount(call: PluginCall) { val account = AndroidAccountVault.account() if (account == null) call.resolve() else call.resolve(AndroidAccountVault.publicAccount(account).toJSObject()) diff --git a/android/app/src/main/java/studio/daybreak/mail/MainActivity.java b/android/app/src/main/java/studio/daybreak/mail/MainActivity.java index a7652cd..b6fcd31 100644 --- a/android/app/src/main/java/studio/daybreak/mail/MainActivity.java +++ b/android/app/src/main/java/studio/daybreak/mail/MainActivity.java @@ -1,19 +1,211 @@ package studio.daybreak.mail; -import android.Manifest; -import android.content.pm.PackageManager; -import android.os.Build; -import android.os.Bundle; -import androidx.core.app.ActivityCompat; -import com.getcapacitor.BridgeActivity; - -public class MainActivity extends BridgeActivity { +import android.Manifest; +import android.app.KeyguardManager; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.graphics.Color; +import android.os.Build; +import android.os.Bundle; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.webkit.WebView; +import android.widget.Button; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.TextView; +import androidx.core.app.ActivityCompat; +import com.getcapacitor.BridgeActivity; + +public class MainActivity extends BridgeActivity { + private static final int UNLOCK_REQUEST_CODE = 705; + private FrameLayout appLockOverlay; + private TextView appLockMessage; + private Button appLockButton; + private boolean appLocked; + private boolean awaitingUnlockResult; + private boolean activityResumed; + @Override public void onCreate(Bundle savedInstanceState) { registerPlugin(EpMailPlugin.class); super.onCreate(savedInstanceState); - if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { - ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 701); - } - } -} + AndroidAccountVault.INSTANCE.initialize(getApplicationContext()); + createAppLockOverlay(); + if (isAppLockEnabled()) lockWebView(); + if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 701); + } + } + + @Override + public void onResume() { + super.onResume(); + activityResumed = true; + if (isAppLockEnabled() && appLocked) { + lockWebView(); + configureUnlockButton(); + } + } + + @Override + public void onPause() { + activityResumed = false; + if (isAppLockEnabled()) lockWebView(); + super.onPause(); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode != UNLOCK_REQUEST_CODE) return; + awaitingUnlockResult = false; + if (resultCode == RESULT_OK && isAppLockEnabled()) unlockWebView(true); + else updateAppLockMessage("Unlock with your Android screen lock to view mail."); + } + + public void onAppLockSettingChanged(boolean enabled) { + runOnUiThread(() -> { + if (!enabled) { + awaitingUnlockResult = false; + unlockWebView(false); + } else if (activityResumed) { + appLocked = false; + } else { + lockWebView(); + } + }); + } + + private boolean isAppLockEnabled() { + try { + return AndroidAccountVault.INSTANCE.appLockEnabled(); + } catch (Exception ignored) { + // If the encrypted setting cannot be read, prefer locking over exposing stale UI. + return true; + } + } + + private void createAppLockOverlay() { + View content = findViewById(android.R.id.content); + if (!(content instanceof FrameLayout)) return; + + appLockOverlay = new FrameLayout(this); + appLockOverlay.setBackgroundColor(Color.rgb(25, 21, 18)); + appLockOverlay.setClickable(true); + appLockOverlay.setFocusable(true); + + LinearLayout panel = new LinearLayout(this); + panel.setOrientation(LinearLayout.VERTICAL); + panel.setGravity(Gravity.CENTER); + panel.setPadding(dp(28), dp(28), dp(28), dp(28)); + + TextView title = new TextView(this); + title.setText("ep-mail is locked"); + title.setTextColor(Color.rgb(238, 230, 215)); + title.setTextSize(22); + title.setGravity(Gravity.CENTER); + panel.addView(title, new LinearLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + + appLockMessage = new TextView(this); + appLockMessage.setText("Unlock with your Android screen lock to view mail."); + appLockMessage.setTextColor(Color.rgb(185, 171, 151)); + appLockMessage.setTextSize(15); + appLockMessage.setGravity(Gravity.CENTER); + LinearLayout.LayoutParams messageParams = new LinearLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + messageParams.topMargin = dp(12); + panel.addView(appLockMessage, messageParams); + + appLockButton = new Button(this); + appLockButton.setText("Unlock"); + appLockButton.setOnClickListener(view -> requestDeviceUnlock()); + LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + buttonParams.gravity = Gravity.CENTER_HORIZONTAL; + buttonParams.topMargin = dp(24); + panel.addView(appLockButton, buttonParams); + + FrameLayout.LayoutParams panelParams = new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER); + appLockOverlay.addView(panel, panelParams); + appLockOverlay.setVisibility(View.GONE); + ((FrameLayout) content).addView(appLockOverlay, new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + } + + private void requestDeviceUnlock() { + if (awaitingUnlockResult) return; + KeyguardManager keyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); + if (keyguard == null || !keyguard.isDeviceSecure()) { + updateAppLockMessage("Set a PIN, pattern, or password in Android Settings to unlock ep-mail."); + configureUnlockButton(); + return; + } + configureUnlockButton(); + Intent confirmIntent = keyguard.createConfirmDeviceCredentialIntent( + "Unlock ep-mail", + "Confirm your Android screen lock to view mail." + ); + if (confirmIntent == null) { + updateAppLockMessage("Android could not start screen-lock verification. Try again after unlocking your device."); + return; + } + awaitingUnlockResult = true; + try { + startActivityForResult(confirmIntent, UNLOCK_REQUEST_CODE); + } catch (Exception error) { + awaitingUnlockResult = false; + updateAppLockMessage("Could not start Android screen-lock verification. Try again."); + } + } + + private void configureUnlockButton() { + if (appLockButton == null) return; + KeyguardManager keyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); + if (keyguard != null && keyguard.isDeviceSecure()) { + appLockButton.setText("Unlock"); + appLockButton.setOnClickListener(view -> requestDeviceUnlock()); + } else { + appLockButton.setText("Open security settings"); + appLockButton.setOnClickListener(view -> startActivity( + new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS))); + } + } + + private void lockWebView() { + appLocked = true; + if (appLockOverlay != null) appLockOverlay.setVisibility(View.VISIBLE); + if (getBridge() != null) { + WebView webView = getBridge().getWebView(); + webView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + webView.getSettings().setJavaScriptEnabled(false); + } + } + + private void unlockWebView(boolean reload) { + appLocked = false; + if (getBridge() != null) { + WebView webView = getBridge().getWebView(); + webView.getSettings().setJavaScriptEnabled(true); + webView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO); + if (reload) webView.reload(); + } + if (appLockOverlay != null) appLockOverlay.setVisibility(View.GONE); + if (appLockButton != null) { + appLockButton.setText("Unlock"); + appLockButton.setOnClickListener(view -> requestDeviceUnlock()); + } + } + + private void updateAppLockMessage(String message) { + if (appLockMessage != null) appLockMessage.setText(message); + } + + private int dp(int value) { + return Math.round(value * getResources().getDisplayMetrics().density); + } +} diff --git a/attachments.js b/attachments.js index 8c98d90..5d1eff2 100644 --- a/attachments.js +++ b/attachments.js @@ -60,7 +60,7 @@ function downloadAttachment(details) { attachmentMailUi.wrapOpenMessage(baseOpenMessage => function (id) { baseOpenMessage(id); const message = attachmentMailUi.state.messages.find(item => item.id === id); - if (!message?.uid) return; + if (!message?.uid || message.pgpDecrypted) return; selectAllAttachmentUi('#reader-pane .attachment').forEach(row => { const download = row.querySelector('.download'); if (!download || row.querySelector('.preview-attachment')) return; diff --git a/pgp-mail-ui.js b/pgp-mail-ui.js index d5e701b..d1b5939 100644 --- a/pgp-mail-ui.js +++ b/pgp-mail-ui.js @@ -135,7 +135,7 @@ pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) { if (!footer || !pgpApi()) return; const box = document.createElement('div'); box.className = 'pgp-compose'; - box.innerHTML = ``; + box.innerHTML = `${pgpApi().platform === 'android' ? '' : ''}`; footer.prepend(box); let touched = false; const encrypt = selectPgpMailUi('#pgp-encrypt'); diff --git a/pgp-ui.js b/pgp-ui.js index 474e727..22f4bf4 100644 --- a/pgp-ui.js +++ b/pgp-ui.js @@ -6,12 +6,36 @@ const selectAllPgpKeyUi = pgpKeyMailUi.selectAll; const escapePgpKeyUi = pgpKeyMailUi.escapeHtml; const toastPgpKeyUi = pgpKeyMailUi.toast; function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); } +async function saveAndroidPgpExport(label, value) { + if (window.daybreakMail?.pgp?.platform !== 'android' || typeof value !== 'string') return value; + const warning = /private|revocation/i.test(label) ? ' This contains secret key material; keep it private.' : ''; + if (!confirm(`Copy this ${label.toLowerCase()} to the clipboard?${warning}`)) return { canceled: true }; + if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(value); + else if (prompt(`Copy this ${label.toLowerCase()}:`, value) === null) return { canceled: true }; + return { saved: true }; +} function openEncryptionKeys() { - const root = selectPgpKeyUi('#modal-root'); + const root = selectPgpKeyUi('#modal-root'); const account = window.epMailFeatures.mail.connectedAccount || {}; - root.innerHTML = `