From 96c7b6966bd88f5b6116af506657d831269228cb Mon Sep 17 00:00:00 2001 From: Tero Date: Tue, 17 Nov 2026 22:11:05 +0200 Subject: [PATCH] Improve Android OpenPGP, drafts and release builds Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .gitattributes | 1 + README.md | 4 + .../daybreak/mail/AndroidMailService.kt | 8 +- .../java/studio/daybreak/mail/EpMailPlugin.kt | 52 +++++ .../mail/AndroidPgpMimeValidationTest.kt | 52 +++++ mail-ui.js | 75 ++++---- package-lock.json | 4 +- package.json | 3 +- pgp-mail-ui.js | 4 +- pgp-ui.js | 12 +- platform-bridge.js | 11 +- scripts/android-pgp.js | 11 +- scripts/build-all.ps1 | 29 +-- scripts/build-linux-wsl.sh | 34 ++++ scripts/build.ps1 | 20 ++ shortcuts.js | 88 +++++---- styles.css | 3 +- tests/android-pgp.test.cjs | 43 +++++ tests/android-ui-support.test.cjs | 20 +- tests/build-version.test.cjs | 19 ++ tests/draft-composer.test.cjs | 178 ++++++++++++++++++ tests/pgp-private-import-ui.test.cjs | 70 +++++++ www/mail-ui.js | 75 ++++---- www/pgp-mail-ui.js | 4 +- www/pgp-ui.js | 12 +- www/platform-bridge.js | 11 +- www/shortcuts.js | 88 +++++---- www/styles.css | 3 +- 28 files changed, 747 insertions(+), 187 deletions(-) create mode 100644 .gitattributes create mode 100644 android/app/src/test/java/studio/daybreak/mail/AndroidPgpMimeValidationTest.kt create mode 100644 scripts/build-linux-wsl.sh create mode 100644 scripts/build.ps1 create mode 100644 tests/draft-composer.test.cjs create mode 100644 tests/pgp-private-import-ui.test.cjs diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..20676dd --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +scripts/build-linux-wsl.sh text eol=lf diff --git a/README.md b/README.md index b2d8f32..ac72a20 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,8 @@ An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and E ## Desktop app The Electron app runs in its own window. On Windows, ep-mail also shows its icon in the notification area beside the clock; click it to open the app, or right-click for Open and Quit. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. Each account can have its own outgoing signature, new-mail notification toggle, periodic sync interval (2–60 minutes; IDLE remains event-driven), and mail rules. Rules match incoming Inbox messages by sender and/or subject; the first matching rule archives, moves to Inbox/Archive/Trash, applies a label, or flags the message. Sender/domain and extracted message-link checks highlight selected phishing warning signs. Message links are shown separately from the body and require explicit confirmation before opening in a browser. On desktop and Android, incoming HTML is sanitized before display; external HTTPS images stay blocked until you explicitly load them for that message. Loading remote images can disclose your network address and message-open timing to their hosts. Settings, cached recent messages, offline drafts, and queued mail operations are stored with the encrypted account credentials. Search supports text, sender, subject, date range, attachment, and folder filters; a filtered online search scans up to the newest 5,000 messages in the selected folder. When offline, the app can read cached messages, save drafts, and queue supported message actions and sends for retry on the next successful sync. The app uses required STARTTLS for IMAP port 143 and SMTP port 587. Before preparing a new release, bump the version once with `npm run bump:build`; then build all platform targets for that same version. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. Windows builds use the app icon for the executable, window, and shortcuts. If Windows continues showing an old icon for an existing taskbar pin, unpin ep-mail, install or launch the updated build, then pin it again from the updated shortcut. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`. + +On Windows, `npm run build` runs `scripts\build.ps1`, building the Android debug APK and Windows portable executable. For all targets, run `npm run build:all`: it also builds the Windows installer and uses the default WSL distribution to build the Linux AppImage and Debian package. To select a distribution, run `powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-all.ps1 -WslDistribution Ubuntu`. WSL needs Linux Node.js, npm and tar, plus the usual Electron packaging prerequisites and network access to install the locked dependencies. Linux builds use a temporary Linux filesystem workspace, then copy both packages into `release\`. Both build scripts preserve the legacy `ep-mail .apk` copy of the debug APK; it is **not a signed release APK** and will overwrite a same-named signed APK. Use `npm run android:release-apk` afterwards when a signed release is needed. The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker. @@ -26,6 +28,8 @@ npm run android:apk ``` The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk` and copied to `release/ep-mail -debug.apk`; install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`. For a signed release, configure `EP_MAIL_ANDROID_STORE_FILE` (an absolute path), `EP_MAIL_ANDROID_STORE_PASSWORD`, `EP_MAIL_ANDROID_KEY_ALIAS`, and `EP_MAIL_ANDROID_KEY_PASSWORD` in the build environment, then run `npm run android:release-apk`. The signed artifact is copied to `release/ep-mail .apk`; keep keystores and passwords out of the repository and logs. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Notification sender/subject details are hidden by default; enabling them in Settings still keeps lock-screen previews redacted. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management. + +For Android OpenPGP testing, transfer a passphrase-protected, ASCII-armored private key (`.asc`) securely to the device. In **Settings → Encryption keys**, enter its passphrase, select **Import private key from file…**, and choose the file (maximum 200,000 bytes). The file picker is unavailable while app lock is enabled because leaving the app can reset the import; paste the key instead, or temporarily disable app lock and re-enable it after importing. Compare the imported fingerprint with the original, then remove the transferred file and clear the clipboard if used. Keep a separate secure backup of the key and its revocation certificate. Android builds use the Gradle wrapper and Android Gradle Plugin 9.4.0. Capacitor's generated modules are aligned to that plugin version during the build; the legacy Android DSL and external Kotlin plugin remain enabled for compatibility and must be migrated before upgrading to AGP 10. 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 9194f2c..b953203 100644 --- a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt @@ -426,7 +426,7 @@ internal object AndroidMailService { } } - private fun validateOpenPgpMime(message: MimeMessage) { + internal 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.") @@ -434,8 +434,8 @@ internal object AndroidMailService { 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("") + val version = versionPart.inputStream.bufferedReader(Charsets.US_ASCII).use { it.readText().trim() } + val armor = encryptedPart.inputStream.bufferedReader(Charsets.US_ASCII).use { it.readText() } require(versionPart.isMimeType("application/pgp-encrypted") && version == "Version: 1" && encryptedPart.isMimeType("application/octet-stream") && armor.contains("-----BEGIN PGP MESSAGE-----") && armor.contains("-----END PGP MESSAGE-----")) { @@ -443,7 +443,7 @@ internal object AndroidMailService { } } else if (contentType.startsWith("multipart/signed")) { val signaturePart = multipart.getBodyPart(1) - val armor = runCatching { String(signaturePart.inputStream.readBytes(), Charsets.US_ASCII) }.getOrDefault("") + val armor = signaturePart.inputStream.bufferedReader(Charsets.US_ASCII).use { it.readText() } require(signaturePart.isMimeType("application/pgp-signature") && armor.contains("-----BEGIN PGP SIGNATURE-----") && armor.contains("-----END PGP SIGNATURE-----")) { "The OpenPGP signature is missing or malformed." 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 30140e4..2fbb6f0 100644 --- a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt +++ b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt @@ -6,12 +6,15 @@ import android.content.Intent import android.content.IntentFilter import android.net.Uri import android.os.Build +import android.app.Activity import android.app.AlertDialog +import androidx.activity.result.ActivityResult import androidx.biometric.BiometricPrompt import com.getcapacitor.JSObject import com.getcapacitor.Plugin import com.getcapacitor.PluginCall import com.getcapacitor.PluginMethod +import com.getcapacitor.annotation.ActivityCallback import com.getcapacitor.annotation.CapacitorPlugin import java.util.Locale import java.util.UUID @@ -78,6 +81,55 @@ class EpMailPlugin : Plugin() { call.resolve(JSObject().put("version", BuildConfig.VERSION_NAME)) } + @PluginMethod + fun pickPgpPrivateKey(call: PluginCall) { + try { + if (AndroidAccountVault.appLockEnabled()) { + call.reject("File import is unavailable while app lock is enabled. Paste the key instead, or temporarily disable app lock and re-enable it after importing.") + return + } + } catch (error: Exception) { + call.reject(error.message ?: "Could not check the app lock setting.") + return + } + val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply { + addCategory(Intent.CATEGORY_OPENABLE) + type = "*/*" + } + try { + startActivityForResult(call, intent, "pgpPrivateKeyPicked") + } catch (_: android.content.ActivityNotFoundException) { + call.reject("No file picker is available on this device.") + } + } + + @ActivityCallback + private fun pgpPrivateKeyPicked(call: PluginCall?, result: ActivityResult) { + if (call == null) return + if (result.resultCode != Activity.RESULT_OK) { + call.resolve(JSObject().put("canceled", true)) + return + } + val uri = result.data?.data + if (uri == null || uri.scheme != "content") { + call.reject("Could not access the selected key file.") + return + } + mailboxExecutor.execute { + try { + val bytes = context.contentResolver.openInputStream(uri)?.use { + BoundedInputReader.read(it, 200001) + } ?: throw IllegalArgumentException("Could not open the selected key file.") + if (bytes.isEmpty() || bytes.size > 200000) { + throw IllegalArgumentException("That key file is empty or too large (maximum 200 KB).") + } + call.resolve(JSObject().put("armoredKey", String(bytes, Charsets.UTF_8))) + } catch (error: Exception) { + call.reject(error.message ?: "Could not read the selected key file.") + } + } + } + @PluginMethod fun getNotificationPrivacy(call: PluginCall) { try { diff --git a/android/app/src/test/java/studio/daybreak/mail/AndroidPgpMimeValidationTest.kt b/android/app/src/test/java/studio/daybreak/mail/AndroidPgpMimeValidationTest.kt new file mode 100644 index 0000000..f381447 --- /dev/null +++ b/android/app/src/test/java/studio/daybreak/mail/AndroidPgpMimeValidationTest.kt @@ -0,0 +1,52 @@ +package studio.daybreak.mail + +import java.io.ByteArrayInputStream +import java.io.File +import java.util.Properties +import javax.mail.Session +import javax.mail.internet.MimeMessage +import org.junit.Assert.assertThrows +import org.junit.Assume.assumeTrue +import org.junit.Test + +class AndroidPgpMimeValidationTest { + private fun message(contentType: String, parts: String): MimeMessage { + val source = "MIME-Version: 1.0\r\nContent-Type: $contentType; boundary=\"test\"\r\n\r\n$parts" + return MimeMessage(Session.getInstance(Properties()), ByteArrayInputStream(source.toByteArray(Charsets.UTF_8))) + } + + private fun encrypted(version: String = "Version: 1", partType: String = "application/octet-stream", armor: String = "-----BEGIN PGP MESSAGE-----\r\nabc\r\n-----END PGP MESSAGE-----"): MimeMessage = + message("multipart/encrypted; protocol=\"application/pgp-encrypted\"", + "--test\r\nContent-Type: application/pgp-encrypted\r\n\r\n$version\r\n" + + "--test\r\nContent-Type: $partType\r\n\r\n$armor\r\n--test--\r\n") + + private fun signed(armor: String = "-----BEGIN PGP SIGNATURE-----\r\nabc\r\n-----END PGP SIGNATURE-----"): MimeMessage = + message("multipart/signed; protocol=\"application/pgp-signature\"", + "--test\r\nContent-Type: text/plain\r\n\r\nhello\r\n" + + "--test\r\nContent-Type: application/pgp-signature\r\n\r\n$armor\r\n--test--\r\n") + + @Test + fun acceptsValidEncryptedAndSignedMime() { + AndroidMailService.validateOpenPgpMime(encrypted()) + AndroidMailService.validateOpenPgpMime(signed()) + } + + @Test + fun rejectsMalformedEncryptedAndSignedMime() { + assertThrows(IllegalArgumentException::class.java) { AndroidMailService.validateOpenPgpMime(encrypted(version = "Version: 2")) } + assertThrows(IllegalArgumentException::class.java) { AndroidMailService.validateOpenPgpMime(encrypted(partType = "text/plain")) } + assertThrows(IllegalArgumentException::class.java) { AndroidMailService.validateOpenPgpMime(encrypted(armor = "missing armor")) } + assertThrows(IllegalArgumentException::class.java) { AndroidMailService.validateOpenPgpMime(signed(armor = "missing signature")) } + } + + @Test + fun acceptsMimeGeneratedByAndroidOpenPgpBuilder() { + val directory = System.getenv("EP_MAIL_PGP_MIME_FIXTURE_DIR") + assumeTrue("Set EP_MAIL_PGP_MIME_FIXTURE_DIR to run the JavaScript-to-JavaMail integration test.", !directory.isNullOrBlank()) + for (name in listOf("encrypted", "signed", "encrypted-signed")) { + val file = File(directory, "$name.eml") + val parsed = file.inputStream().use { MimeMessage(Session.getInstance(Properties()), it) } + AndroidMailService.validateOpenPgpMime(parsed) + } + } +} diff --git a/mail-ui.js b/mail-ui.js index 81b7c13..9289d8c 100644 --- a/mail-ui.js +++ b/mail-ui.js @@ -595,6 +595,7 @@ function setupDraftComposer() { contentBase64: btoa(binary) }); } + if (closed) return; attachments.push(...selected); renderAttachments(); await persist(); @@ -621,58 +622,66 @@ function setupDraftComposer() { modal.querySelector('.compose-footer').insertBefore(save, selectMailUi('#send')); let saveTimer; let closed = false; - const persist = async () => { - if (closed || !selectMailUi('#compose-to')) return; + let pendingSave = Promise.resolve(); + const persist = () => { + if (closed || !modal.isConnected) return Promise.resolve(false); const values = { - id: modal.dataset.draftId || window.crypto.randomUUID(), - to: selectMailUi('#compose-to').value, - cc: selectMailUi('#compose-cc').value, - subject: selectMailUi('#compose-subject').value, - text: selectMailUi('#compose-body').value, - attachments + to: modal.querySelector('#compose-to').value, + cc: modal.querySelector('#compose-cc').value, + subject: modal.querySelector('#compose-subject').value, + text: modal.querySelector('#compose-body').value, + attachments: [...attachments] }; - if (!Object.values(values).some(value => typeof value === 'string' && value.trim()) && !attachments.length) return; + if (!modal.dataset.draftId && ![values.to, values.cc, values.subject, values.text].some(value => value.trim()) && !values.attachments.length) return Promise.resolve(false); + values.id = modal.dataset.draftId || window.crypto.randomUUID(); modal.dataset.draftId = values.id; - const result = await window.daybreakMail.saveDraft(values); - modal.dataset.draftId = result.id; + const operation = pendingSave.then(async () => { + await window.daybreakMail.saveDraft(values); + return true; + }); + pendingSave = operation.then(() => {}, () => {}); + return operation; }; save.onclick = async () => { try { - await persist(); - toastMailUi('Draft saved on this device'); - if (rendererState.activeFolder === 'Drafts') void syncMailbox(false); + const saved = await persist(); + toastMailUi(saved ? 'Draft saved on this device' : 'Nothing to save in this draft'); + if (saved && rendererState.activeFolder === 'Drafts') void syncMailbox(false); } catch (error) { toastMailUi(error.message || 'Could not save draft'); } }; modal.addEventListener('input', () => { clearTimeout(saveTimer); saveTimer = setTimeout(() => persist().catch(error => toastMailUi(error.message || 'Could not save draft')), 700); }); - modal.querySelector('.modal-overlay')?.addEventListener('click', event => { - if (!event.target.classList.contains('modal-overlay')) return; + const saveAndClose = () => { + if (closed) return; clearTimeout(saveTimer); - persist().then(() => { if (rendererState.activeFolder === 'Drafts') void syncMailbox(false); }) + persist().then(saved => { if (saved && rendererState.activeFolder === 'Drafts') void syncMailbox(false); }) .catch(error => toastMailUi(error.message || 'Could not save draft')); closed = true; + }; + root.querySelector('.modal-overlay')?.addEventListener('click', event => { + if (!event.target.classList.contains('modal-overlay')) return; + saveAndClose(); }, true); - root.querySelector('.modal-close')?.addEventListener('click', () => { - clearTimeout(saveTimer); - persist().then(() => { if (rendererState.activeFolder === 'Drafts') void syncMailbox(false); }) - .catch(error => toastMailUi(error.message || 'Could not save draft')); - closed = true; - }, true); - selectMailUi('#discard').onclick = async () => { + root.querySelector('.modal-close')?.addEventListener('click', saveAndClose, true); + modal.addEventListener('keydown', event => { + if (event.key === 'Escape') saveAndClose(); + }); + const deleteSavedDraft = async () => { clearTimeout(saveTimer); closed = true; + await pendingSave; + if (modal.dataset.draftId) await window.daybreakMail.deleteDraft(modal.dataset.draftId); + }; + modal._deleteSavedDraft = deleteSavedDraft; + selectMailUi('#discard').onclick = async () => { try { - if (modal.dataset.draftId) await window.daybreakMail.deleteDraft(modal.dataset.draftId); + await deleteSavedDraft(); root.innerHTML = ''; if (rendererState.activeFolder === 'Drafts') void syncMailbox(false); } catch (error) { toastMailUi(error.message || 'Could not delete draft'); } }; - selectMailUi('#send').addEventListener('click', () => { - clearTimeout(saveTimer); - closed = true; - }, true); }); } @@ -1053,15 +1062,15 @@ if (window.daybreakMail) { return; } if (result.queued) { - const draftId = selectMailUi('#modal-root .compose-modal')?.dataset.draftId; - if (draftId) await window.daybreakMail.deleteDraft(draftId); + const modal = selectMailUi('#modal-root .compose-modal'); + if (modal?._deleteSavedDraft) await modal._deleteSavedDraft(); selectMailUi('#modal-root').innerHTML = ''; toastMailUi('Offline: message queued and will send when connected'); if (rendererState.activeFolder === 'Drafts') void syncMailbox(false); return; } - const draftId = selectMailUi('#modal-root .compose-modal')?.dataset.draftId; - if (draftId) await window.daybreakMail.deleteDraft(draftId); + const modal = selectMailUi('#modal-root .compose-modal'); + if (modal?._deleteSavedDraft) await modal._deleteSavedDraft(); selectMailUi('#modal-root').innerHTML = ''; toastMailUi(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved'); if (rendererState.activeFolder === 'Sent') syncMailbox(false, { offset: 0 }); diff --git a/package-lock.json b/package-lock.json index d77bdbf..fd20929 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ep-mail", - "version": "0.5.22", + "version": "0.5.23", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ep-mail", - "version": "0.5.22", + "version": "0.5.23", "dependencies": { "@capacitor/android": "^8.5.2", "@capacitor/core": "^8.5.2", diff --git a/package.json b/package.json index e11dcf0..00f139a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ep-mail", - "version": "0.5.22", + "version": "0.5.23", "private": true, "description": "Eternity Project mail client", "homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client", @@ -26,6 +26,7 @@ "android:open": "npm run android:sync && cap open android", "android:apk": "npm run android:sync && node scripts/build-android-apk.cjs", "android:release-apk": "npm run android:sync && node scripts/build-android-release-apk.cjs", + "build": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1", "build:all": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-all.ps1" }, "devDependencies": { diff --git a/pgp-mail-ui.js b/pgp-mail-ui.js index 013a029..c23a295 100644 --- a/pgp-mail-ui.js +++ b/pgp-mail-ui.js @@ -158,8 +158,8 @@ pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) { }); // Compose: encrypt/sign options. -pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) { - baseShowCompose(reply, forward); +pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false, draft = null) { + baseShowCompose(reply, forward, draft); const footer = selectPgpMailUi('#modal-root .compose-footer'); if (!footer || !pgpApi()) return; const box = document.createElement('div'); diff --git a/pgp-ui.js b/pgp-ui.js index 9d9a4bf..7d27dcc 100644 --- a/pgp-ui.js +++ b/pgp-ui.js @@ -32,7 +32,7 @@ function openEncryptionKeys() {
`; - root.innerHTML = `