diff --git a/ANDROID_SECURITY_PLAN.md b/ANDROID_SECURITY_PLAN.md index ee14e89..a195d9e 100644 --- a/ANDROID_SECURITY_PLAN.md +++ b/ANDROID_SECURITY_PLAN.md @@ -7,9 +7,9 @@ Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECU ## 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; 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. +- 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. Android OpenPGP key generation/storage and native trust-change/plaintext-send confirmation dialogs were exercised on an emulator; cancellation preserved the untrusted state and prevented the plaintext send, and confirming a trust change persisted it. 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. The native plugin prompts before trust elevation, key replacement, and plaintext sending when keys exist or encryption was requested, and validates PGP/MIME structure before its protected send path. 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; automated regression tests for native confirmation accept/cancel paths and policy bypass attempts; 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/SECURITY_REVIEW.md b/SECURITY_REVIEW.md index c885217..428c5ac 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'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. +- 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 prompts for trust elevation, key replacement, and plaintext sending are implemented; emulator smoke tests exercised trust accept/cancel and plaintext cancel. Automated regression coverage and resistance to renderer-policy bypasses remain open. ## Third review pass (2026-10-17) diff --git a/TODO.md b/TODO.md index adfa994..79d0b51 100644 --- a/TODO.md +++ b/TODO.md @@ -32,7 +32,8 @@ - [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. - [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. + - [x] Exercise native trust-change and plaintext-send confirmations on an emulator, including cancellation. + - [ ] Android release gate: native confirmation accept/cancel and bypass tests, 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). 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 8ed562c..1c63271 100644 --- a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt @@ -275,10 +275,7 @@ internal object AndroidMailService { 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." - } + validateOpenPgpMime(message) require(message.from?.isNotEmpty() == true && message.allRecipients?.isNotEmpty() == true) { "The encrypted message needs a sender and at least one recipient." } @@ -373,6 +370,33 @@ internal object AndroidMailService { } } + private fun validateOpenPgpMime(message: MimeMessage) { + val contentType = message.contentType.lowercase(Locale.ROOT) + val multipart = message.content as? Multipart + ?: throw IllegalArgumentException("The OpenPGP MIME message is malformed.") + require(multipart.count == 2) { "The OpenPGP MIME message has an unexpected structure." } + if (contentType.startsWith("multipart/encrypted")) { + val versionPart = multipart.getBodyPart(0) + val encryptedPart = multipart.getBodyPart(1) + val version = runCatching { versionPart.content.toString().trim() }.getOrDefault("") + val armor = runCatching { String(encryptedPart.inputStream.readBytes(), Charsets.US_ASCII) }.getOrDefault("") + require(versionPart.isMimeType("application/pgp-encrypted") && version == "Version: 1" && + encryptedPart.isMimeType("application/octet-stream") && + armor.contains("-----BEGIN PGP MESSAGE-----") && armor.contains("-----END PGP MESSAGE-----")) { + "The encrypted OpenPGP payload is missing or malformed." + } + } else if (contentType.startsWith("multipart/signed")) { + val signaturePart = multipart.getBodyPart(1) + val armor = runCatching { String(signaturePart.inputStream.readBytes(), Charsets.US_ASCII) }.getOrDefault("") + require(signaturePart.isMimeType("application/pgp-signature") && + armor.contains("-----BEGIN PGP SIGNATURE-----") && armor.contains("-----END PGP SIGNATURE-----")) { + "The OpenPGP signature is missing or malformed." + } + } else { + throw IllegalArgumentException("Only an OpenPGP MIME message can use the protected send path.") + } + } + 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) 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 8301377..5773a8e 100644 --- a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt +++ b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt @@ -14,8 +14,9 @@ import com.getcapacitor.PluginMethod import com.getcapacitor.annotation.CapacitorPlugin import java.util.Locale import java.util.UUID -import org.json.JSONArray -import org.json.JSONObject +import org.json.JSONArray +import org.json.JSONObject +import javax.mail.internet.InternetAddress @CapacitorPlugin(name = "EpMail") class EpMailPlugin : Plugin() { @@ -119,13 +120,77 @@ class EpMailPlugin : Plugin() { 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)) + val next = JSONObject(candidate.toString()) + val warning = pgpStoreChangeWarning(AndroidAccountVault.pgpStore(), next) + if (warning == null) { + AndroidAccountVault.savePgpStore(next) + call.resolve(JSObject().put("ok", true)) + } else { + val host = activity + host.runOnUiThread { + AlertDialog.Builder(host) + .setTitle("Confirm OpenPGP key changes") + .setMessage(warning) + .setNegativeButton("Cancel") { _, _ -> call.reject("OpenPGP key change cancelled.") } + .setPositiveButton("Confirm changes") { _, _ -> + bridge.execute { + try { + AndroidAccountVault.savePgpStore(next) + call.resolve(JSObject().put("ok", true)) + } catch (error: Exception) { + call.reject(error.message ?: "Could not save the Android OpenPGP key store.") + } + } + } + .setOnCancelListener { call.reject("OpenPGP key change cancelled.") } + .show() + } + } } catch (error: Exception) { call.reject(error.message ?: "Could not save the Android OpenPGP key store.") } } + private fun pgpStoreChangeWarning(previous: JSONObject, candidate: JSONObject): String? { + val oldContacts = previous.optJSONArray("contacts") ?: JSONArray() + val newContacts = candidate.optJSONArray("contacts") ?: JSONArray() + val oldByFingerprint = (0 until oldContacts.length()).mapNotNull { oldContacts.optJSONObject(it) } + .associateBy { it.optString("fingerprint").uppercase(Locale.ROOT) } + val warnings = ArrayList() + for (index in 0 until newContacts.length()) { + val current = newContacts.optJSONObject(index) ?: continue + val fingerprint = current.optString("fingerprint").uppercase(Locale.ROOT) + val previousContact = oldByFingerprint[fingerprint] + val trustOrder = mapOf("unknown" to 0, "trusted" to 1, "verified" to 2) + if (previousContact != null && + (trustOrder[current.optString("trust")] ?: 0) > (trustOrder[previousContact.optString("trust")] ?: 0)) { + warnings.add("Trust change for ${safePgpLabel(current.optJSONArray("emails"))}\nFingerprint: ${formatPgpFingerprint(fingerprint)}\nNew trust: ${current.optString("trust")}") + } + if (previousContact == null) { + val newEmails = jsonStrings(current.optJSONArray("emails")).map { it.lowercase(Locale.ROOT) }.toSet() + for (oldIndex in 0 until oldContacts.length()) { + val old = oldContacts.optJSONObject(oldIndex) ?: continue + val oldFingerprint = old.optString("fingerprint").uppercase(Locale.ROOT) + val overlap = jsonStrings(old.optJSONArray("emails")).map { it.lowercase(Locale.ROOT) }.any(newEmails::contains) + if (overlap && oldFingerprint != fingerprint) { + warnings.add("A different key is already stored for ${safePgpLabel(current.optJSONArray("emails"))}.\nNew fingerprint: ${formatPgpFingerprint(fingerprint)}\nExisting fingerprint: ${formatPgpFingerprint(oldFingerprint)}") + } + } + } + } + return warnings.take(6).takeIf { it.isNotEmpty() }?.joinToString("\n\n")?.let { + "$it\n\nOnly confirm trust or a replacement after comparing fingerprints with the key owner through another channel." + } + } + + private fun jsonStrings(values: JSONArray?): List = + values?.let { array -> (0 until array.length()).mapNotNull { array.optString(it).takeIf(String::isNotBlank) } }.orEmpty() + + private fun safePgpLabel(values: JSONArray?): String = + jsonStrings(values).joinToString(", ").replace(Regex("[\\r\\n\\u0000]"), " ").take(300).ifBlank { "this contact" } + + private fun formatPgpFingerprint(value: String): String = value.chunked(4).joinToString(" ").take(200) + @PluginMethod fun pgpGetMessageSource(call: PluginCall) { try { @@ -380,13 +445,38 @@ class EpMailPlugin : Plugin() { } @PluginMethod - fun send(call: PluginCall) { - val input = JSONObject(call.data.toString()).apply { - if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>") - } - try { - val account = AndroidAccountVault.account() - ?: throw IllegalStateException("Add a mail account before sending.") + fun send(call: PluginCall) { + val input = JSONObject(call.data.toString()).apply { + if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>") + } + val warning = try { plaintextSendWarning(input) } catch (error: Exception) { + call.reject(error.message ?: "Could not check the OpenPGP send policy.") + return + } + if (warning == null) { + sendPrepared(call, input) + return + } + val host = activity + host.runOnUiThread { + AlertDialog.Builder(host) + .setTitle("Send without OpenPGP encryption?") + .setMessage(warning) + .setNegativeButton("Cancel") { _, _ -> + call.resolve(JSObject().put("failed", true).put("code", "PLAINTEXT_CANCELLED").put("message", "Plaintext send cancelled.")) + } + .setPositiveButton("Send plaintext") { _, _ -> bridge.execute { sendPrepared(call, input) } } + .setOnCancelListener { + call.resolve(JSObject().put("failed", true).put("code", "PLAINTEXT_CANCELLED").put("message", "Plaintext send cancelled.")) + } + .show() + } + } + + private fun sendPrepared(call: PluginCall, input: JSONObject) { + try { + val account = AndroidAccountVault.account() + ?: throw IllegalStateException("Add a mail account before sending.") call.resolve(AndroidMailService.send(account, input).toJSObject()) } catch (error: Exception) { val account = AndroidAccountVault.account() @@ -396,9 +486,42 @@ class EpMailPlugin : Plugin() { .put("type", "send") .put("data", input)) call.resolve(JSObject().put("ok", true).put("queued", true)) - } else call.reject(error.message ?: "Could not send the message.") - } - } + } else call.reject(error.message ?: "Could not send the message.") + } + } + + private fun plaintextSendWarning(input: JSONObject): String? { + if (input.optString("rawBase64").isNotBlank()) return null + val recipients = (listOf(input.optString("to"), input.optString("cc")) + .filter(String::isNotBlank) + .flatMap { InternetAddress.parse(it, true).mapNotNull { address -> (address as? InternetAddress)?.address?.lowercase(Locale.ROOT) } }) + .distinct() + if (recipients.isEmpty()) return null + val data = AndroidAccountVault.pgpStore() + val contacts = data.optJSONArray("contacts") ?: JSONArray() + val keys = data.optJSONArray("keys") ?: JSONArray() + val available = ArrayList>() + for (address in recipients) { + for (index in 0 until contacts.length()) { + val contact = contacts.optJSONObject(index) ?: continue + if (jsonStrings(contact.optJSONArray("emails")).any { it.equals(address, true) }) { + available.add(address to contact.optString("fingerprint")) + } + } + for (index in 0 until keys.length()) { + val key = keys.optJSONObject(index) ?: continue + if (key.optString("email").equals(address, true)) available.add(address to key.optString("fingerprint")) + } + } + val explicitRequest = input.optBoolean("pgpRequested") + if (!explicitRequest && available.isEmpty()) return null + val recipientLines = recipients.take(10).map { address -> + val fingerprints = available.filter { it.first == address }.map { formatPgpFingerprint(it.second) }.distinct() + if (fingerprints.isEmpty()) "$address — no key stored" else "$address\n${fingerprints.joinToString("\n")}" + }.joinToString("\n\n") + val prefix = if (explicitRequest) "OpenPGP was requested, but this message will be sent in plaintext." else "A stored OpenPGP key is available for at least one recipient." + return "$prefix\n\nRecipients and stored key fingerprints:\n$recipientLines\n\nThe message body and attachments will be readable by the mail provider and anyone who receives it. Send plaintext anyway?" + } @PluginMethod fun listDrafts(call: PluginCall) { diff --git a/package-lock.json b/package-lock.json index dcb96a5..286186e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ep-mail", - "version": "0.5.7", + "version": "0.5.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ep-mail", - "version": "0.5.7", + "version": "0.5.8", "dependencies": { "@capacitor/android": "^8.5.2", "@capacitor/core": "^8.5.2", diff --git a/package.json b/package.json index 38dca6d..6d1364d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ep-mail", - "version": "0.5.7", + "version": "0.5.8", "private": true, "description": "Eternity Project mail client", "homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client", diff --git a/pgp-mail-ui.js b/pgp-mail-ui.js index d1b5939..cd16030 100644 --- a/pgp-mail-ui.js +++ b/pgp-mail-ui.js @@ -168,23 +168,26 @@ pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) { // Called by the send handler. Returns null (plain mail), false (cancelled) or send options. async function prepareSend(to, cc) { - if (!pgpApi()) return null; + if (!pgpApi()) return null; + const plaintextFallback = () => pgpApi().platform === 'android' + ? { encrypt: false, sign: false, plaintextFallback: true } + : null; let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked); const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked); if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null; const status = await pgpApi().checkSend({ to, cc, sign }); // The default-on update is debounced, so a quick send could skip encryption even though keys exist. if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') { - if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) { - if (!sign) return null; + if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) { + if (!sign) return plaintextFallback(); } else return false; } if (!encrypt && !sign) return null; if (encrypt && status.missing.length) { const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`); - if (!sendPlain) return false; - encrypt = false; - if (!sign) return null; + if (!sendPlain) return false; + encrypt = false; + if (!sign) return plaintextFallback(); } let passphrase = null; if (sign) { diff --git a/platform-bridge.js b/platform-bridge.js index 438f6e9..4294820 100644 --- a/platform-bridge.js +++ b/platform-bridge.js @@ -9974,11 +9974,11 @@ ${parts.join("")}`; storePromise = null; throw error; }); - return storePromise; + return storePromise.then((value) => JSON.parse(JSON.stringify(value))); } async function persist(value) { await EpMail2.pgpSaveStore({ store: value }); - storePromise = value; + storePromise = Promise.resolve(JSON.parse(JSON.stringify(value))); } function cache(fingerprint, passphrase) { if (!cacheMinutes) { @@ -10488,7 +10488,13 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error saveAttachment: (details) => EpMail.saveAttachment(details), openExternal: (url) => EpMail.openExternal({ url }), send: async (message) => { - if (!message?.pgp || !message.pgp.encrypt && !message.pgp.sign) return EpMail.send(message); + if (!message?.pgp || !message.pgp.encrypt && !message.pgp.sign) { + if (message?.pgp?.plaintextFallback) { + const { pgp: _options, ...plainMessage } = message; + return EpMail.send({ ...plainMessage, pgpRequested: true }); + } + return EpMail.send(message); + } try { const { rawBase64, to: to2, from } = await daybreakMail.pgp.buildOutgoing(message); const { pgp: _options, text: _text, attachments: _attachments, ...headers } = message; diff --git a/scripts/android-bridge.js b/scripts/android-bridge.js index b42a51e..66d7f80 100644 --- a/scripts/android-bridge.js +++ b/scripts/android-bridge.js @@ -31,7 +31,13 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') { saveAttachment: details => EpMail.saveAttachment(details), openExternal: url => EpMail.openExternal({ url }), send: async message => { - if (!message?.pgp || (!message.pgp.encrypt && !message.pgp.sign)) return EpMail.send(message); + if (!message?.pgp || (!message.pgp.encrypt && !message.pgp.sign)) { + if (message?.pgp?.plaintextFallback) { + const { pgp: _options, ...plainMessage } = message; + return EpMail.send({ ...plainMessage, pgpRequested: true }); + } + return EpMail.send(message); + } try { const { rawBase64, to, from } = await daybreakMail.pgp.buildOutgoing(message); const { pgp: _options, text: _text, attachments: _attachments, ...headers } = message; diff --git a/scripts/android-pgp.js b/scripts/android-pgp.js index 37492cb..bd2db8b 100644 --- a/scripts/android-pgp.js +++ b/scripts/android-pgp.js @@ -182,11 +182,11 @@ export function createAndroidPgp({ EpMail, getAccount }) { if (Number.isFinite(savedMinutes) && savedMinutes >= 0 && savedMinutes <= 1440) cacheMinutes = Math.round(savedMinutes); return value; }).catch(error => { storePromise = null; throw error; }); - return storePromise; + return storePromise.then(value => JSON.parse(JSON.stringify(value))); } async function persist(value) { await EpMail.pgpSaveStore({ store: value }); - storePromise = value; + storePromise = Promise.resolve(JSON.parse(JSON.stringify(value))); } function cache(fingerprint, passphrase) { if (!cacheMinutes) { passphrases.delete(fingerprint); return; } diff --git a/tests/android-ui-support.test.cjs b/tests/android-ui-support.test.cjs index c246612..eae6850 100644 --- a/tests/android-ui-support.test.cjs +++ b/tests/android-ui-support.test.cjs @@ -73,12 +73,16 @@ test('Android OpenPGP uses the encrypted vault and queues only built MIME data', assert.match(plugin, /fun pgpLoadStore/); assert.match(plugin, /fun pgpSaveStore/); assert.match(plugin, /fun pgpGetMessageSource/); + assert.match(plugin, /pgpStoreChangeWarning/); + assert.match(plugin, /plaintextSendWarning/); + assert.match(plugin, /Send plaintext/); assert.match(androidPgp, /curve25519Legacy/); assert.match(androidPgp, /multipart\/encrypted/); assert.match(androidPgp, /MAX_MESSAGE_BYTES = 25 \* 1024 \* 1024/); assert.match(androidBridge, /buildOutgoing\(message\)/); assert.match(androidBridge, /rawBase64, envelope: \{ from, to \}, text: '', attachments: \[\]/); - assert.match(androidMailService, /Only an OpenPGP MIME message can use the encrypted send path/); + assert.match(androidMailService, /validateOpenPgpMime\(message\)/); + assert.match(androidMailService, /private fun validateOpenPgpMime/); assert.match(androidMailService, /"send" -> send\(account, data\)/); assert.match(androidMailService, /private fun isEncryptedMessage/); }); diff --git a/www/pgp-mail-ui.js b/www/pgp-mail-ui.js index d1b5939..cd16030 100644 --- a/www/pgp-mail-ui.js +++ b/www/pgp-mail-ui.js @@ -168,23 +168,26 @@ pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) { // Called by the send handler. Returns null (plain mail), false (cancelled) or send options. async function prepareSend(to, cc) { - if (!pgpApi()) return null; + if (!pgpApi()) return null; + const plaintextFallback = () => pgpApi().platform === 'android' + ? { encrypt: false, sign: false, plaintextFallback: true } + : null; let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked); const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked); if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null; const status = await pgpApi().checkSend({ to, cc, sign }); // The default-on update is debounced, so a quick send could skip encryption even though keys exist. if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') { - if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) { - if (!sign) return null; + if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) { + if (!sign) return plaintextFallback(); } else return false; } if (!encrypt && !sign) return null; if (encrypt && status.missing.length) { const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`); - if (!sendPlain) return false; - encrypt = false; - if (!sign) return null; + if (!sendPlain) return false; + encrypt = false; + if (!sign) return plaintextFallback(); } let passphrase = null; if (sign) { diff --git a/www/platform-bridge.js b/www/platform-bridge.js index 438f6e9..4294820 100644 --- a/www/platform-bridge.js +++ b/www/platform-bridge.js @@ -9974,11 +9974,11 @@ ${parts.join("")}`; storePromise = null; throw error; }); - return storePromise; + return storePromise.then((value) => JSON.parse(JSON.stringify(value))); } async function persist(value) { await EpMail2.pgpSaveStore({ store: value }); - storePromise = value; + storePromise = Promise.resolve(JSON.parse(JSON.stringify(value))); } function cache(fingerprint, passphrase) { if (!cacheMinutes) { @@ -10488,7 +10488,13 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error saveAttachment: (details) => EpMail.saveAttachment(details), openExternal: (url) => EpMail.openExternal({ url }), send: async (message) => { - if (!message?.pgp || !message.pgp.encrypt && !message.pgp.sign) return EpMail.send(message); + if (!message?.pgp || !message.pgp.encrypt && !message.pgp.sign) { + if (message?.pgp?.plaintextFallback) { + const { pgp: _options, ...plainMessage } = message; + return EpMail.send({ ...plainMessage, pgpRequested: true }); + } + return EpMail.send(message); + } try { const { rawBase64, to: to2, from } = await daybreakMail.pgp.buildOutgoing(message); const { pgp: _options, text: _text, attachments: _attachments, ...headers } = message;