Compare commits

...
1 Commits
16 changed files with 287 additions and 21 deletions
+5 -5
View File
@@ -1,6 +1,6 @@
# Encryption plan: OpenPGP mail encryption for ep-mail # Encryption plan: OpenPGP mail encryption for ep-mail
Status: **Desktop implementation is complete; an experimental Android Phase 2 path is available for local testing only.** Native confirmation prompts are implemented in that test path, but automated bypass testing, Android interoperability, independent security review, and release assurance remain open. 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. Status: **Desktop implementation is complete; an experimental Android Phase 2 path is available for local testing only.** It now includes per-key authentication-bound biometric/device-credential passphrase release, with passphrase fallback. Native confirmation prompts are implemented, but actual Android biometric/device testing, automated bypass testing, on-device interoperability, independent security review, and release assurance remain open. Do not use the Android test path 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) ## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
@@ -22,8 +22,8 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
**Private keys** **Private keys**
- One or more keys per account; never stored unprotected and never sent anywhere. - One or more keys per account; never stored unprotected and never sent anywhere.
- Always protected by a passphrase (minimum 8 characters). On desktop the whole key store is also encrypted with Electron `safeStorage` (the OS credential store). - Always protected by a passphrase (minimum 8 characters). On desktop the whole key store is also encrypted with Electron `safeStorage` (the OS credential store).
- Android: wrap with a hardware-backed Android Keystore key; optional biometric unlock (Phase 4). - Android test implementation: private keys remain passphrase-protected inside the Keystore-encrypted vault. An optional per-key Android Keystore authentication-bound wrapper can release a cached PGP passphrase after biometric/device-credential authentication. This wrapper and its invalidation recovery have not been independently reviewed or fully device-tested; passphrase entry remains the fallback.
- The passphrase is cached only in memory for a configurable time, then wiped (Phase 4). It is never written to disk. - Desktop passphrases are cached in memory for a configurable time, then cleared. Android never stores plaintext passphrases; its optional experimental biometric feature persists only the authentication-bound Keystore ciphertext. Both paths need platform-specific expiry/invalidation assurance before security claims.
- Export as ASCII-armored files; a revocation certificate is generated when a key is created and can be exported after unlocking. - Export as ASCII-armored files; a revocation certificate is generated when a key is created and can be exported after unlocking.
- Deleting or exporting a private key requires the passphrase. Desktop users can change a key's passphrase by verifying the current one and entering the new one twice; the public key and revocation certificate are preserved. - Deleting or exporting a private key requires the passphrase. Desktop users can change a key's passphrase by verifying the current one and entering the new one twice; the public key and revocation certificate are preserved.
@@ -54,7 +54,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
| 1 | Foundation: OpenPGP.js, passphrase-protected key store (OS credential store on desktop), generate/import/export/delete, revocation certificate, unit tests, Settings UI | Done (desktop) | | 1 | Foundation: OpenPGP.js, passphrase-protected key store (OS credential store on desktop), generate/import/export/delete, revocation certificate, unit tests, Settings UI | Done (desktop) |
| 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Done (desktop) | | 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Done (desktop) |
| 3 | Send: public-key keyring and contact import, encrypt and sign on compose, encrypted Sent copy, downgrade warnings | Done (desktop) | | 3 | Send: public-key keyring and contact import, encrypt and sign on compose, encrypted Sent copy, downgrade warnings | Done (desktop) |
| 4 | Trust and polish: fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore and biometric unlock | Desktop done; Android open | | 4 | Trust and polish: fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore and biometric unlock | Desktop done; Android test path implemented, review/device assurance open |
| 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated, GnuPG and manual Thunderbird interop checks done | | 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated, GnuPG and manual Thunderbird interop checks done |
| 6 | Docs, security review, release | Docs and release done; independent review open | | 6 | Docs, security review, release | Docs and release done; independent review open |
@@ -96,6 +96,6 @@ The desktop Settings → Encryption keys view can search and publish through:
All built-in and custom servers start disabled. Users enable each server explicitly; disabled servers are not contacted for lookup and cannot be used for publication. Searching is user-triggered and checks every enabled server; ep-mail does not perform background lookups while composing. Search addresses are disclosed to each enabled server. Results identify their source servers and duplicate keys are merged by fingerprint. The main process validates returned OpenPGP keys before showing them, and adding a result uses the existing key-replacement confirmation. Discovered keys enter the contact keyring with `unknown` trust; server publication or lookup is never treated as fingerprint verification. All built-in and custom servers start disabled. Users enable each server explicitly; disabled servers are not contacted for lookup and cannot be used for publication. Searching is user-triggered and checks every enabled server; ep-mail does not perform background lookups while composing. Search addresses are disclosed to each enabled server. Results identify their source servers and duplicate keys are merged by fingerprint. The main process validates returned OpenPGP keys before showing them, and adding a result uses the existing key-replacement confirmation. Discovered keys enter the contact keyring with `unknown` trust; server publication or lookup is never treated as fingerprint verification.
Publishing targets one explicitly selected enabled server, not all enabled servers. The destination is shown in the Settings control and named again in a native confirmation before upload. The confirmation identifies the server, email address, and fingerprint and explains that the email/key association becomes public and may be retained. Only the selected key's public material is uploaded; private keys and passphrases are never sent. A successful upload may still require the user to complete email verification before the key becomes searchable. Android key-server support is not included because Android OpenPGP support is not implemented. Publishing targets one explicitly selected enabled server, not all enabled servers. The destination is shown in the Settings control and named again in a native confirmation before upload. The confirmation identifies the server, email address, and fingerprint and explains that the email/key association becomes public and may be retained. Only the selected key's public material is uploaded; private keys and passphrases are never sent. A successful upload may still require the user to complete email verification before the key becomes searchable. Android key-server support is intentionally disabled in the experimental Android scope.
Custom servers are limited to HTTPS HKP/VKS endpoints, redirects are rejected, and lookup responses are size-limited. Key-server data remains subject to the server's availability, privacy practices, and verification policy; users should independently compare fingerprints before trusting a key. Custom servers are limited to HTTPS HKP/VKS endpoints, redirects are rejected, and lookup responses are size-limited. Key-server data remains subject to the server's availability, privacy practices, and verification policy; users should independently compare fingerprints before trusting a key.
+2
View File
@@ -27,6 +27,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 <version>-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 <version>.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. The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk` and copied to `release/ep-mail <version>-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 <version>.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.
On Android, previously cached inbox messages appear while the mailbox refreshes. The app stays in the message list until you select a message; returning to the list does not automatically reopen the newest message.
## Run on Windows or Linux ## Run on Windows or Linux
Install Python 3, open a terminal in this folder, and run: Install Python 3, open a terminal in this folder, and run:
+3 -2
View File
@@ -35,8 +35,9 @@
- [x] Exercise native trust-change and plaintext-send confirmations on an emulator, including cancellation. - [x] Exercise native trust-change and plaintext-send confirmations on an emulator, including cancellation.
- [x] Add Android unit tests for trust-elevation, key-replacement, and plaintext-send confirmation decisions. - [x] Add Android unit tests for trust-elevation, key-replacement, and plaintext-send confirmation decisions.
- [x] Add Android-module tests for signed-only PGP/MIME, clear-signed verification, attached public-key offers, and GnuPG interoperability in a Node harness. - [x] Add Android-module tests for signed-only PGP/MIME, clear-signed verification, attached public-key offers, and GnuPG interoperability in a Node harness.
- [x] Add optional per-key Android biometric/device-credential passphrase release with passphrase fallback.
- [ ] Android release gate: instrumented native-dialog UI and bypass tests, device-level parity/interoperability tests (including Thunderbird/GnuPG on Android), independent human cryptography/security review, and signed release review. - [ ] Android release gate: instrumented native-dialog UI and bypass tests, device-level parity/interoperability tests (including Thunderbird/GnuPG on Android), independent human cryptography/security review, and signed release review.
- [ ] Android follow-up: biometric unlock, full vault lifecycle/recovery, remaining signature parity/device interoperability, and dependency advisory remediation. - [ ] Android follow-up: device-test biometric prompt/key invalidation recovery, full vault lifecycle/recovery, remaining parity/device interoperability, and dependency advisory remediation.
- [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests. - [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 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] Phase 6: documentation and release.
@@ -55,7 +56,7 @@
- [x] Refuse to generate a replacement Keystore key when encrypted vault data already exists; show a fail-closed recovery screen with clear-data guidance. - [x] Refuse to generate a replacement Keystore key when encrypted vault data already exists; show a fail-closed recovery screen with clear-data guidance.
- [ ] Device-test missing/invalidated Keystore keys, corrupted vault data, migration/reinstall behavior, and recovery instructions. - [ ] Device-test missing/invalidated Keystore keys, corrupted vault data, migration/reinstall behavior, and recovery instructions.
- [ ] Define/test full app-data deletion and downloaded-file/OpenPGP-key retention or removal behavior. - [ ] Define/test full app-data deletion and downloaded-file/OpenPGP-key retention or removal behavior.
- [ ] Add app-lock timeout/delay options and decide whether to add biometric unlock; test process recreation and lifecycle transitions. - [ ] Add app-lock timeout/delay process/lifecycle tests and decide whether to add biometric unlock to the separate app lock (PGP per-key biometric release is implemented experimentally).
## Appearance and settings ## Appearance and settings
@@ -368,7 +368,16 @@ internal object AndroidAccountVault {
fun cachedFolder(id: String, folder: String, offset: Int, filters: JSONObject = JSONObject()): JSONObject? { fun cachedFolder(id: String, folder: String, offset: Int, filters: JSONObject = JSONObject()): JSONObject? {
val account = account(id) ?: return null val account = account(id) ?: return null
val cached = account.optJSONObject("mailCache")?.optJSONArray(folder) ?: return null val cached = account.optJSONObject("mailCache")?.optJSONArray(folder) ?: return null
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
val now = System.currentTimeMillis()
val matched = (0 until cached.length()).mapNotNull { cached.optJSONObject(it) } val matched = (0 until cached.length()).mapNotNull { cached.optJSONObject(it) }
.filter { message ->
(0 until snoozed.length()).none { index ->
val item = snoozed.optJSONObject(index) ?: return@none false
item.optString("folder") == folder && item.optLong("uid") == message.optLong("uid") &&
item.optLong("dueAt") > now
}
}
.filter { matchesFilters(it, filters) } .filter { matchesFilters(it, filters) }
.sortedByDescending { it.optLong("timestamp") } .sortedByDescending { it.optLong("timestamp") }
val start = offset.coerceAtLeast(0) val start = offset.coerceAtLeast(0)
@@ -27,6 +27,7 @@ import javax.activation.DataHandler
import javax.mail.Address import javax.mail.Address
import javax.mail.Authenticator import javax.mail.Authenticator
import javax.mail.Flags import javax.mail.Flags
import javax.mail.FetchProfile
import javax.mail.Folder import javax.mail.Folder
import javax.mail.Message import javax.mail.Message
import javax.mail.Multipart import javax.mail.Multipart
@@ -160,6 +161,13 @@ internal object AndroidMailService {
val first = (end - 19).coerceAtLeast(1) val first = (end - 19).coerceAtLeast(1)
val result = JSONArray() val result = JSONArray()
val batch = folder.getMessages(first, end).reversed() val batch = folder.getMessages(first, end).reversed()
val profile = FetchProfile().apply {
add(FetchProfile.Item.ENVELOPE)
add(FetchProfile.Item.FLAGS)
add(FetchProfile.Item.CONTENT_INFO)
add(UIDFolder.FetchProfileItem.UID)
}
folder.fetch(batch.toTypedArray(), profile)
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray() val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
val cached = JSONArray() val cached = JSONArray()
for (message in batch) { for (message in batch) {
@@ -497,6 +497,21 @@ class EpMailPlugin : Plugin() {
} }
@PluginMethod @PluginMethod
fun getCachedFolder(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before loading cached messages.")
val folder = call.getString("folder") ?: "Inbox"
val offset = (call.getInt("offset") ?: 0).coerceAtLeast(0)
val filters = call.getObject("filters") ?: JSObject()
val cached = AndroidAccountVault.cachedFolder(account.optString("id"), folder, offset, JSONObject(filters.toString()))
call.resolve(JSObject().put("cached", cached ?: JSONObject.NULL))
} catch (error: Exception) {
call.reject(error.message ?: "Could not load cached messages.")
}
}
@PluginMethod
fun syncFolder(call: PluginCall) { fun syncFolder(call: PluginCall) {
try { try {
val account = AndroidAccountVault.account() val account = AndroidAccountVault.account()
@@ -0,0 +1,26 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="64"
android:viewportHeight="64">
<path
android:fillColor="@android:color/transparent"
android:strokeColor="#eee9de"
android:strokeWidth="3"
android:pathData="M32,5a27,27 0,1 0,0 54a27,27 0,1 0,0 -54" />
<path
android:strokeColor="#eee9de"
android:strokeWidth="4"
android:pathData="M32,4v56" />
<group android:rotation="22" android:pivotX="32" android:pivotY="18">
<path android:fillColor="@android:color/transparent" android:strokeColor="#eee9de"
android:strokeWidth="3" android:pathData="M20,18a12,5 0,1 0,24 0a12,5 0,1 0,-24 0" />
</group>
<group android:rotation="-22" android:pivotX="32" android:pivotY="46">
<path android:fillColor="@android:color/transparent" android:strokeColor="#eee9de"
android:strokeWidth="3" android:pathData="M20,46a12,5 0,1 0,24 0a12,5 0,1 0,-24 0" />
</group>
<path android:fillColor="@android:color/transparent" android:strokeColor="#eee9de"
android:strokeAlpha="0.75" android:strokeWidth="2"
android:pathData="M24,32a8,8 0,1 0,16 0a8,8 0,1 0,-16 0" />
</vector>
+3 -1
View File
@@ -17,6 +17,8 @@
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen"> <style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item> <item name="windowSplashScreenBackground">#0a0c0b</item>
<item name="windowSplashScreenAnimatedIcon">@drawable/ep_splash_icon</item>
<item name="postSplashScreenTheme">@style/AppTheme.NoActionBar</item>
</style> </style>
</resources> </resources>
+34 -5
View File
@@ -659,6 +659,7 @@ async function syncMailbox(showToast, options = {}) {
const refresh = selectMailUi('#refresh'); const refresh = selectMailUi('#refresh');
if (refresh) refresh.disabled = true; if (refresh) refresh.disabled = true;
const sync = (async () => { const sync = (async () => {
let showingCachedMessages = false;
try { try {
if (rendererState.activeFolder === 'Drafts') { if (rendererState.activeFolder === 'Drafts') {
const result = await window.daybreakMail.listDrafts(); const result = await window.daybreakMail.listDrafts();
@@ -666,9 +667,30 @@ async function syncMailbox(showToast, options = {}) {
if (showToast) toastMailUi(`${result.drafts.length} saved drafts`); if (showToast) toastMailUi(`${result.drafts.length} saved drafts`);
return; return;
} }
const folder = rendererState.activeFolder;
const accountId = mailFeatureState.connectedAccount.id;
const offset = options.offset ?? (options.append ? mailFeatureState.pageOffset + rendererState.messages.length : mailFeatureState.pageOffset);
const filters = mailSearchFilters();
const isCurrentMailbox = () => rendererState.activeFolder === folder && mailFeatureState.connectedAccount?.id === accountId;
if (window.daybreakMail.getCachedFolder && !options.append && offset === 0 && !rendererState.messages.length) {
try {
const cached = await window.daybreakMail.getCachedFolder(folder, offset, filters);
if (cached && isCurrentMailbox()) {
rendererState.messages.splice(0, rendererState.messages.length, ...cached.messages);
rendererState.activeMessage = null;
appShell.renderList();
showingCachedMessages = true;
const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Showing saved messages — syncing';
}
} catch (error) {
console.error('Could not load cached messages:', error);
}
}
if (!isCurrentMailbox()) return;
const result = await window.daybreakMail.syncFolder(folder, offset, filters);
if (!isCurrentMailbox()) return;
const previouslyActiveMessage = rendererState.activeMessage; const previouslyActiveMessage = rendererState.activeMessage;
const offset = options.offset ?? (options.append ? mailFeatureState.pageOffset + rendererState.messages.length : mailFeatureState.pageOffset);
const result = await window.daybreakMail.syncFolder(rendererState.activeFolder, offset, mailSearchFilters());
if (options.append) rendererState.messages.push(...result.messages); if (options.append) rendererState.messages.push(...result.messages);
else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages); else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages);
rendererState.messages.forEach(message => { rendererState.messages.forEach(message => {
@@ -681,7 +703,7 @@ async function syncMailbox(showToast, options = {}) {
mailFeatureState.total = result.total; mailFeatureState.total = result.total;
rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage) rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage)
? previouslyActiveMessage ? previouslyActiveMessage
: rendererState.messages[0]?.id; : window.daybreakMail.platform === 'android' ? null : rendererState.messages[0]?.id;
rendererState.selectedIds.clear(); rendererState.selectedIds.clear();
const unread = rendererState.messages.filter(message => message.unread).length; const unread = rendererState.messages.filter(message => message.unread).length;
const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count'); const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count');
@@ -695,14 +717,21 @@ async function syncMailbox(showToast, options = {}) {
if (rendererState.activeMessage) { if (rendererState.activeMessage) {
appShell.openMessage(rendererState.activeMessage); appShell.openMessage(rendererState.activeMessage);
const current = rendererState.messages.find(message => message.id === rendererState.activeMessage); const current = rendererState.messages.find(message => message.id === rendererState.activeMessage);
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || rendererState.activeFolder, action: 'unread', enabled: false }).catch(() => {}); if (current?.uid && window.daybreakMail.platform !== 'android') window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || rendererState.activeFolder, action: 'unread', enabled: false }).catch(() => {});
} }
else selectMailUi('#reader-pane').innerHTML = appShell.emptyReader(); else {
document.body.classList.remove('reader-open');
selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
}
updateAccountCard(mailFeatureState.connectedAccount); updateAccountCard(mailFeatureState.connectedAccount);
const status = selectMailUi('#mail-status'); const status = selectMailUi('#mail-status');
if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail'; if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`); if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`);
} catch (error) { } catch (error) {
if (showingCachedMessages) {
const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Could not sync — showing saved messages';
}
toastMailUi(error.message || 'Could not sync the inbox'); toastMailUi(error.message || 'Could not sync the inbox');
} finally { } finally {
if (refresh) refresh.disabled = false; if (refresh) refresh.disabled = false;
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.5.14", "version": "0.5.15",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ep-mail", "name": "ep-mail",
"version": "0.5.14", "version": "0.5.15",
"dependencies": { "dependencies": {
"@capacitor/android": "^8.5.2", "@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2", "@capacitor/core": "^8.5.2",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.5.14", "version": "0.5.15",
"private": true, "private": true,
"description": "Eternity Project mail client", "description": "Eternity Project mail client",
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client", "homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
+2
View File
@@ -10685,6 +10685,7 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
var EpMail = registerPlugin("EpMail"); var EpMail = registerPlugin("EpMail");
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android") { if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android") {
const daybreakMail = { const daybreakMail = {
platform: "android",
getAppVersion: () => EpMail.getAppVersion().then((result) => result.version), getAppVersion: () => EpMail.getAppVersion().then((result) => result.version),
getNotificationPrivacy: () => EpMail.getNotificationPrivacy(), getNotificationPrivacy: () => EpMail.getNotificationPrivacy(),
setNotificationDetails: (enabled) => EpMail.setNotificationDetails({ enabled }), setNotificationDetails: (enabled) => EpMail.setNotificationDetails({ enabled }),
@@ -10699,6 +10700,7 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
connect: (details) => EpMail.connect(details), connect: (details) => EpMail.connect(details),
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }), updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }), syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
getCachedFolder: (folder, offset, filters) => EpMail.getCachedFolder({ folder, offset, filters }).then((result) => result.cached),
listFolders: () => EpMail.listFolders(), listFolders: () => EpMail.listFolders(),
createFolder: (name) => EpMail.createFolder({ name }), createFolder: (name) => EpMail.createFolder({ name }),
listDrafts: () => EpMail.listDrafts(), listDrafts: () => EpMail.listDrafts(),
+2
View File
@@ -5,6 +5,7 @@ const EpMail = registerPlugin('EpMail');
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') { if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
const daybreakMail = { const daybreakMail = {
platform: 'android',
getAppVersion: () => EpMail.getAppVersion().then(result => result.version), getAppVersion: () => EpMail.getAppVersion().then(result => result.version),
getNotificationPrivacy: () => EpMail.getNotificationPrivacy(), getNotificationPrivacy: () => EpMail.getNotificationPrivacy(),
setNotificationDetails: enabled => EpMail.setNotificationDetails({ enabled }), setNotificationDetails: enabled => EpMail.setNotificationDetails({ enabled }),
@@ -19,6 +20,7 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
connect: details => EpMail.connect(details), connect: details => EpMail.connect(details),
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }), updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }), syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
getCachedFolder: (folder, offset, filters) => EpMail.getCachedFolder({ folder, offset, filters }).then(result => result.cached),
listFolders: () => EpMail.listFolders(), listFolders: () => EpMail.listFolders(),
createFolder: name => EpMail.createFolder({ name }), createFolder: name => EpMail.createFolder({ name }),
listDrafts: () => EpMail.listDrafts(), listDrafts: () => EpMail.listDrafts(),
+139
View File
@@ -0,0 +1,139 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const root = path.resolve(__dirname, '..');
const source = fs.readFileSync(path.join(root, 'mail-ui.js'), 'utf8');
const syncSource = source.slice(source.indexOf('async function syncMailbox('), source.indexOf('\nif (window.daybreakMail) {', source.indexOf('async function syncMailbox(')));
function deferred() {
let resolve;
const promise = new Promise(done => { resolve = done; });
return { promise, resolve };
}
function harness({ platform = 'android', cached, sync }) {
const messages = [];
const state = { messages, activeMessage: null, activeFolder: 'Inbox', selectedIds: new Set(), query: '' };
const feature = { connectedAccount: { id: 'account' }, pageOffset: 0, syncPromise: null, syncQueued: false };
const elements = new Map();
const opened = [];
const renders = [];
const toasts = [];
const classes = new Set();
const bridge = {
platform,
syncFolder: sync,
updateMessage: () => Promise.resolve()
};
if (cached) bridge.getCachedFolder = cached;
const context = {
window: { daybreakMail: bridge },
document: { body: { classList: { remove: value => classes.delete(value) } } },
rendererState: state,
mailFeatureState: feature,
selectMailUi: selector => {
if (!elements.has(selector)) elements.set(selector, { classList: { toggle() {} }, innerHTML: '', textContent: '' });
return elements.get(selector);
},
appShell: {
renderList: () => renders.push(messages.map(message => message.id)),
openMessage: id => opened.push(id),
emptyReader: () => 'empty'
},
mailSearchFilters: () => ({}),
localStorage: { getItem: () => null },
updateAccountCard() {},
toastMailUi: message => toasts.push(message),
console
};
vm.runInNewContext(`${syncSource}\nthis.syncMailbox = syncMailbox`, context);
return { state, feature, context, elements, opened, renders, classes, toasts };
}
function result(ids) {
return { messages: ids.map(id => ({ id, uid: id, tags: [] })), total: ids.length, start: 1, end: ids.length };
}
test('Android shows cached inbox before network sync without opening a message', async () => {
const network = deferred();
const ui = harness({ cached: async () => result([1]), sync: () => network.promise });
const pending = ui.context.syncMailbox(false);
await new Promise(resolve => setImmediate(resolve));
assert.deepEqual(ui.renders[0], [1]);
assert.equal(ui.state.activeMessage, null);
assert.equal(ui.elements.get('#mail-status').textContent, 'Showing saved messages — syncing');
network.resolve(result([2, 1]));
await pending;
assert.equal(ui.state.activeMessage, null);
assert.deepEqual(ui.opened, []);
assert.deepEqual(ui.state.messages.map(message => message.id), [2, 1]);
});
test('Android refresh respects back navigation during an in-flight sync', async () => {
const network = deferred();
const ui = harness({ sync: () => network.promise });
ui.state.activeMessage = 1;
ui.classes.add('reader-open');
const pending = ui.context.syncMailbox(false);
ui.state.activeMessage = null;
ui.classes.delete('reader-open');
network.resolve(result([1, 2]));
await pending;
assert.equal(ui.state.activeMessage, null);
assert.deepEqual(ui.opened, []);
assert.equal(ui.elements.get('#reader-pane').innerHTML, 'empty');
});
test('refresh keeps an explicitly selected Android message and desktop still selects the first', async () => {
const android = harness({ sync: async () => result([1, 2]) });
android.state.activeMessage = 2;
await android.context.syncMailbox(false);
assert.deepEqual(android.opened, [2]);
const desktop = harness({ platform: 'desktop', sync: async () => result([1, 2]) });
await desktop.context.syncMailbox(false);
assert.deepEqual(desktop.opened, [1]);
});
test('a message selected from the cache stays open when sync finishes', async () => {
const network = deferred();
const ui = harness({ cached: async () => result([1]), sync: () => network.promise });
const pending = ui.context.syncMailbox(false);
await new Promise(resolve => setImmediate(resolve));
ui.state.activeMessage = 1;
network.resolve(result([2, 1]));
await pending;
assert.deepEqual(ui.opened, [1]);
});
test('sync errors leave cached messages visible and report the failure', async () => {
const ui = harness({
cached: async () => result([1]),
sync: async () => { throw new Error('Network failed'); }
});
await ui.context.syncMailbox(false);
assert.deepEqual(ui.state.messages.map(message => message.id), [1]);
assert.equal(ui.elements.get('#mail-status').textContent, 'Could not sync — showing saved messages');
assert.deepEqual(ui.toasts, ['Network failed']);
});
test('a sync result for a previous folder does not replace the current mailbox', async () => {
const network = deferred();
const ui = harness({ sync: () => network.promise });
const pending = ui.context.syncMailbox(false);
ui.state.activeFolder = 'Sent';
network.resolve(result([1]));
await pending;
assert.equal(ui.state.messages.length, 0);
assert.deepEqual(ui.opened, []);
});
test('Android startup theme uses the EP vector on supported splash screens', () => {
const styles = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'res', 'values', 'styles.xml'), 'utf8');
const icon = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'res', 'drawable', 'ep_splash_icon.xml'), 'utf8');
assert.match(styles, /name="windowSplashScreenAnimatedIcon">@drawable\/ep_splash_icon/);
assert.match(styles, /name="postSplashScreenTheme">@style\/AppTheme.NoActionBar/);
assert.match(icon, /android:strokeColor="#eee9de"/);
});
+34 -5
View File
@@ -659,6 +659,7 @@ async function syncMailbox(showToast, options = {}) {
const refresh = selectMailUi('#refresh'); const refresh = selectMailUi('#refresh');
if (refresh) refresh.disabled = true; if (refresh) refresh.disabled = true;
const sync = (async () => { const sync = (async () => {
let showingCachedMessages = false;
try { try {
if (rendererState.activeFolder === 'Drafts') { if (rendererState.activeFolder === 'Drafts') {
const result = await window.daybreakMail.listDrafts(); const result = await window.daybreakMail.listDrafts();
@@ -666,9 +667,30 @@ async function syncMailbox(showToast, options = {}) {
if (showToast) toastMailUi(`${result.drafts.length} saved drafts`); if (showToast) toastMailUi(`${result.drafts.length} saved drafts`);
return; return;
} }
const folder = rendererState.activeFolder;
const accountId = mailFeatureState.connectedAccount.id;
const offset = options.offset ?? (options.append ? mailFeatureState.pageOffset + rendererState.messages.length : mailFeatureState.pageOffset);
const filters = mailSearchFilters();
const isCurrentMailbox = () => rendererState.activeFolder === folder && mailFeatureState.connectedAccount?.id === accountId;
if (window.daybreakMail.getCachedFolder && !options.append && offset === 0 && !rendererState.messages.length) {
try {
const cached = await window.daybreakMail.getCachedFolder(folder, offset, filters);
if (cached && isCurrentMailbox()) {
rendererState.messages.splice(0, rendererState.messages.length, ...cached.messages);
rendererState.activeMessage = null;
appShell.renderList();
showingCachedMessages = true;
const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Showing saved messages — syncing';
}
} catch (error) {
console.error('Could not load cached messages:', error);
}
}
if (!isCurrentMailbox()) return;
const result = await window.daybreakMail.syncFolder(folder, offset, filters);
if (!isCurrentMailbox()) return;
const previouslyActiveMessage = rendererState.activeMessage; const previouslyActiveMessage = rendererState.activeMessage;
const offset = options.offset ?? (options.append ? mailFeatureState.pageOffset + rendererState.messages.length : mailFeatureState.pageOffset);
const result = await window.daybreakMail.syncFolder(rendererState.activeFolder, offset, mailSearchFilters());
if (options.append) rendererState.messages.push(...result.messages); if (options.append) rendererState.messages.push(...result.messages);
else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages); else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages);
rendererState.messages.forEach(message => { rendererState.messages.forEach(message => {
@@ -681,7 +703,7 @@ async function syncMailbox(showToast, options = {}) {
mailFeatureState.total = result.total; mailFeatureState.total = result.total;
rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage) rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage)
? previouslyActiveMessage ? previouslyActiveMessage
: rendererState.messages[0]?.id; : window.daybreakMail.platform === 'android' ? null : rendererState.messages[0]?.id;
rendererState.selectedIds.clear(); rendererState.selectedIds.clear();
const unread = rendererState.messages.filter(message => message.unread).length; const unread = rendererState.messages.filter(message => message.unread).length;
const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count'); const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count');
@@ -695,14 +717,21 @@ async function syncMailbox(showToast, options = {}) {
if (rendererState.activeMessage) { if (rendererState.activeMessage) {
appShell.openMessage(rendererState.activeMessage); appShell.openMessage(rendererState.activeMessage);
const current = rendererState.messages.find(message => message.id === rendererState.activeMessage); const current = rendererState.messages.find(message => message.id === rendererState.activeMessage);
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || rendererState.activeFolder, action: 'unread', enabled: false }).catch(() => {}); if (current?.uid && window.daybreakMail.platform !== 'android') window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || rendererState.activeFolder, action: 'unread', enabled: false }).catch(() => {});
} }
else selectMailUi('#reader-pane').innerHTML = appShell.emptyReader(); else {
document.body.classList.remove('reader-open');
selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
}
updateAccountCard(mailFeatureState.connectedAccount); updateAccountCard(mailFeatureState.connectedAccount);
const status = selectMailUi('#mail-status'); const status = selectMailUi('#mail-status');
if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail'; if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`); if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`);
} catch (error) { } catch (error) {
if (showingCachedMessages) {
const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Could not sync — showing saved messages';
}
toastMailUi(error.message || 'Could not sync the inbox'); toastMailUi(error.message || 'Could not sync the inbox');
} finally { } finally {
if (refresh) refresh.disabled = false; if (refresh) refresh.disabled = false;
+2
View File
@@ -10685,6 +10685,7 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
var EpMail = registerPlugin("EpMail"); var EpMail = registerPlugin("EpMail");
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android") { if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android") {
const daybreakMail = { const daybreakMail = {
platform: "android",
getAppVersion: () => EpMail.getAppVersion().then((result) => result.version), getAppVersion: () => EpMail.getAppVersion().then((result) => result.version),
getNotificationPrivacy: () => EpMail.getNotificationPrivacy(), getNotificationPrivacy: () => EpMail.getNotificationPrivacy(),
setNotificationDetails: (enabled) => EpMail.setNotificationDetails({ enabled }), setNotificationDetails: (enabled) => EpMail.setNotificationDetails({ enabled }),
@@ -10699,6 +10700,7 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
connect: (details) => EpMail.connect(details), connect: (details) => EpMail.connect(details),
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }), updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }), syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
getCachedFolder: (folder, offset, filters) => EpMail.getCachedFolder({ folder, offset, filters }).then((result) => result.cached),
listFolders: () => EpMail.listFolders(), listFolders: () => EpMail.listFolders(),
createFolder: (name) => EpMail.createFolder({ name }), createFolder: (name) => EpMail.createFolder({ name }),
listDrafts: () => EpMail.listDrafts(), listDrafts: () => EpMail.listDrafts(),