Add ANDROID_SECURITY_PLAN.md to project

This commit is contained in:
2026-11-03 07:16:33 +02:00
parent 640fca8a70
commit af224beda4
13 changed files with 631 additions and 26 deletions
+85
View File
@@ -0,0 +1,85 @@
# Android security plan for ep-mail
Status: **Plan**. Android already has several useful protections, but it does not yet provide Android OpenPGP support, an app lock, or a release security assurance process. This document turns the remaining Android security work into an incremental plan. It is not a security certification or a substitute for an independent review.
Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECURITY_REVIEW.md), and [TODO.md](./TODO.md).
## Goals and limits
Protect account credentials and locally cached mail if app files are copied; prevent untrusted mail or renderer content from gaining native capabilities; protect message content in transit; give users control over sensitive previews and local unlock; and bring Android OpenPGP behavior up to the security guarantees already implemented on desktop.
This does not protect a device while malware or an attacker controls it, prevent a user from sending mail to an unintended recipient, or hide mail metadata from providers. OpenPGP protects message content only where recipients' keys are correctly managed. Android's system lock and device integrity remain important assumptions.
## Existing protections to preserve and verify
- `AndroidAccountVault` encrypts the combined account, cached-mail, draft, and outbox store using AES-GCM and an Android Keystore key.
- The manifest sets `allowBackup="false"`; the background service and `FileProvider` are not exported.
- IMAP and SMTP configure required STARTTLS. Mail HTML is sanitized, remote images are blocked until user approval, HTTP images are rejected, and the web CSP blocks remote connections, scripts in mail, frames, and forms.
- The Android WebView calls native operations through a Capacitor plugin rather than making mail connections from the renderer.
These are implementation observations, not proof that all paths are safe. In particular, verify certificate and hostname validation for IMAP/SMTP and DAV, the generated release manifest/WebView configuration, and how app data behaves on Keystore errors. Do not silently replace a lost Keystore key with a new one and present the store as empty; fail closed and explain recovery/data-loss options.
## Phased plan
### Phase 0 — Android security baseline and release gate (P0)
1. Establish a repeatable security checklist for the actual merged manifest and release APK: permissions, exported components, backup/data-extraction rules, cleartext policy, WebView debugging, file access, and Capacitor plugin exposure.
2. Audit all native network clients. Require TLS, certificate-chain and hostname validation for IMAP/SMTP STARTTLS and DAV HTTPS; reject downgrade and insecure schemes. Add negative tests using invalid, expired, and mismatched certificates. Do not add certificate pinning by default; it creates rotation and recovery risks.
3. Review all `EpMailPlugin` methods as an untrusted-input boundary. Validate IDs, folders, URLs, attachment sizes/types, and state transitions natively; return only data needed by the UI. Ensure external navigation permits only explicitly supported safe schemes and is always user initiated.
4. Ensure release builds disable WebView debugging and do not include debug-only configuration. Keep signing keys outside the repository and CI logs. Publish only signed release artifacts, not the current debug APK output.
5. Remove or sanitize sensitive diagnostics. Logs must not contain credentials, message bodies, subjects, recipient lists, attachment contents, passphrases, or raw protocol errors containing secrets. Use opaque IDs where correlation is needed.
**Exit criteria:** documented release manifest/config review; TLS validation and downgrade regression tests pass; no sensitive data in logs; release APK is signed and distinguishable from debug output.
### Phase 1 — Local data and privacy controls (P0)
1. Harden the encrypted vault: document the Keystore key's security properties and fallback behavior; use authenticated encryption with unique IVs; handle corruption, reinstall, lock-screen/key invalidation, and upgrades without plaintext fallback. Confirm all cached bodies, drafts, attachments, pending sends, DAV credentials, and account passwords remain inside the encrypted store or are deleted safely.
2. Add explicit account removal and app-data deletion behavior, including queued messages, caches, downloaded attachments, and encryption keys. Test that deletion is complete within app-controlled storage and explain that exported files/backups are outside app control.
3. Add a privacy setting for notification content. Default to generic “New mail” text without sender or subject; allow a user choice to show details. Apply the same rule to snooze reminders. Keep foreground-service notifications non-sensitive.
4. Add optional app-lock behavior (immediate, after a delay, or off) using Android biometric/device credential authentication. Lock on background/resume and process recreation according to the chosen timeout; obscure sensitive UI in the task switcher. Make screenshot/screen-recording blocking an optional policy rather than an unconditional default.
5. Keep background sync semantics separate from UI lock. Do not require biometric auth for every background sync if that would break notifications; instead define which credential/key material is available to background work, minimize it, and ensure the UI lock prevents reading local mail. Document that a UI lock is not equivalent to encrypting against a rooted or already-unlocked device.
**Exit criteria:** storage migration and failure tests; no plaintext fallback; app-lock/session tests across lifecycle events; notification privacy tests on supported Android versions; data removal tests.
### Phase 2 — OpenPGP on Android (P0 before claiming encrypted-mail parity)
1. Reuse the desktop OpenPGP.js protocol and MIME behavior only after the independent cryptography review is complete. Confirm the selected library/version and generated key formats interoperate with GnuPG and Thunderbird on Android too.
2. Add an Android key store for private keys, public contacts, fingerprints, trust, and preferences. Protect the store with a random Android Keystore-wrapped encryption key. Private keys must additionally remain passphrase-protected; never persist passphrases. Support a bounded in-memory passphrase cache and wipe it on expiry, lock, and process teardown where practical.
3. Support biometric/device-credential unlock as an optional way to release the store-wrapping key. Design background sync so it never needs private-key access. Handle biometric enrollment/key invalidation without silently destroying or regenerating the user's key store; provide explicit recovery/export guidance.
4. Add the narrow Android bridge and settings UI for key generation, import/export/delete, revocation certificate export, contact-key import, fingerprint comparison, and trust changes. Keep security decisions out of renderer-only code.
5. Implement read and send paths: detect/decrypt PGP/MIME and supported inline PGP; verify signatures and show clear unknown/bad/changed-key states; encrypt/sign recipients and the sender's Sent copy; include attachments inside the encrypted MIME payload. Do not cache decrypted bodies or put plaintext/passphrases in drafts, logs, notifications, or offline outbox.
6. Enforce key replacement, trust elevation, and plaintext downgrade confirmations in native code (or another boundary the renderer cannot bypass). Show recipient addresses and full fingerprints; cancellation must leave state unchanged. Never silently send plaintext when encryption was requested or keys exist.
7. Leave key-server lookup/publication disabled/out of initial Android scope. If added later, make it opt-in, disclose address lookup, require explicit publish destination and confirmation, and never treat server results as verified.
**Exit criteria:** parity tests for desktop message formats and trust rules; Android-specific tests for cancel/confirm paths, tampering, malformed/oversized messages, key replacement, offline queueing, process death, and passphrase expiry; independent human review before release.
### Phase 3 — WebView, native bridge, and content hardening (P1)
1. Verify the production CSP and generated `www` assets match the reviewed source. Keep mail HTML inert and sanitized; do not allow remote script, CSS, frames, forms, or arbitrary navigation. Continue blocking remote images by default and reset approval per message.
2. Restrict WebView navigation to the packaged app origin. External links must be parsed and scheme/host checked, shown to the user, and opened outside the WebView; reject `javascript:`, `file:`, `content:`, `intent:`, and unknown schemes.
3. Review every Capacitor plugin/method and remove unused permissions/plugins. No generic filesystem, arbitrary intent, or unrestricted URL capability should be exposed to the renderer.
4. Treat message HTML, headers, attachment names, filenames, sender data, key user IDs, and decrypted content as hostile input. Add sanitizer and UI regression cases for DOM injection, oversized payloads, spoofed signature indicators, and malicious filenames.
**Exit criteria:** automated CSP/navigation/bridge tests, sanitizer regressions, and a manual WebView inspection on the minimum and target Android versions.
### Phase 4 — Assurance, maintenance, and incident readiness (P1)
1. Add Android dependency vulnerability checks and update policy for Capacitor, AndroidX, mail libraries, OpenPGP.js, and Gradle plugins. Review licenses and lock versions for security-critical dependencies.
2. Run static analysis and Android-focused checks (including merged-manifest review and OWASP MASVS-aligned test cases) on release builds. Keep test evidence tied to the exact APK version/hash.
3. Perform independent reviews of the Android Keystore/vault, Capacitor bridge, network/TLS configuration, and OpenPGP integration before describing Android as security-reviewed.
4. Publish a concise Android security and recovery page: device-lock assumptions, notification/image privacy, TLS, local encryption, OpenPGP limits, key backup/revocation, and what account/key deletion does.
5. Define a private vulnerability-reporting contact, triage process, supported Android version range, and security-fix release process.
## Minimum release criteria for Android OpenPGP
- Phases 0–2 are complete and reviewed; no known high/critical issue remains open.
- No downgrade path can bypass native confirmation; cancellation and stale-key scenarios are tested.
- Secret key material is encrypted at rest; plaintext and passphrases do not enter persistent queues or logs.
- Android-generated and Android-consumed messages pass the same interop and tampering tests as desktop.
- The release APK and its manifest/configuration are reviewed and signed; recovery behavior is documented.
## Out of scope for the first security release
- Guaranteeing security on rooted/compromised devices or protecting against OS-level screen capture by privileged software.
- Mandatory certificate pinning, remote wipe, enterprise MDM controls, or automatic key-server use.
- S/MIME, automatic trust, or claiming that TLS protects mail content from mail providers.
+1 -1
View File
@@ -1,6 +1,6 @@
# Encryption plan: OpenPGP mail encryption for ep-mail # Encryption plan: OpenPGP mail encryption for ep-mail
Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android OpenPGP support and an independent human security review are still open. 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: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android OpenPGP support and an independent human security review are still open. See [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md) for the broader Android security roadmap. Automated review findings and their fixes are documented in [SECURITY_REVIEW.md](./SECURITY_REVIEW.md); see [TODO.md](./TODO.md) for follow-up work.
## 1. Format: OpenPGP with PGP/MIME (RFC 3156) ## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
+1
View File
@@ -39,6 +39,7 @@
- [x] Address findings from the automated OpenPGP security reviews (see [SECURITY_REVIEW.md](./SECURITY_REVIEW.md)). - [x] Address findings from the automated OpenPGP security reviews (see [SECURITY_REVIEW.md](./SECURITY_REVIEW.md)).
- [ ] Complete an independent human security review of the encryption code before expanding OpenPGP support to Android. - [ ] Complete an independent human security review of the encryption code before expanding OpenPGP support to Android.
- [ ] Add direct IPC-handler tests for both accept and cancel paths of the main-process plaintext-send confirmation. - [ ] Add direct IPC-handler tests for both accept and cancel paths of the main-process plaintext-send confirmation.
- [ ] Complete the Android security work in [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md), including Android OpenPGP and release security checks.
## Appearance and settings ## Appearance and settings
+124
View File
@@ -0,0 +1,124 @@
# C++ Translation Assessment: ep-mail-client
## Codebase Summary
| Component | Files | Lines |
|-----------|-------|-------|
| **Main process (desktop/)** | 38 | ~7,500 |
| **Renderer/UI (root + www/)** | 36 | ~7,000 |
| **Tests** | 34 | ~5,800 |
| **Build scripts & config** | 8 | ~1,000 |
| **HTML/CSS/Markdown** | 21 | ~1,400 |
| **Total (excl. node_modules/build artifacts)** | **138** | **~21,750** |
---
## Architecture to Replicate in C++
The app has a **three-layer architecture** you'd need to reimplement:
### 1. Privileged Backend (currently `desktop/main.cjs` + services)
- IMAP/SMTP via `imapflow` + `nodemailer`
- Mail parsing via `mailparser`
- OpenPGP via `openpgp.js` (encryption, signing, keyservers, keystore)
- CalDAV/CardDAV via `tsdav` + `ical.js`
- OAuth2 (Google/Microsoft) with PKCE
- OS secure storage (Windows DPAPI, Linux libsecret, macOS Keychain)
- Background sync, IDLE, snooze reminders, offline queue
- IPC layer with security validation
### 2. Renderer/UI (currently vanilla JS + HTML/CSS)
- Mail list, reader, compose, search, filters
- Calendar (month view, events)
- Contacts management
- PGP key management UI
- Account settings, rules, themes
- Phishing/link safety warnings
- HTML sanitization + remote image blocking
### 3. Platform Adapters
- Desktop: Electron → native C++ GUI (Qt, wxWidgets, or platform APIs)
- Android: Capacitor → JNI + native Android services
- Web: Service worker → not needed for native
---
## Effort Estimate by Component
| Component | Complexity | Estimated Person-Months |
|-----------|------------|------------------------|
| **Core mail backend (IMAP/SMTP/sync)** | Very High | 4–6 |
| **OpenPGP subsystem** | Very High | 3–4 |
| **DAV (CalDAV/CardDAV) sync** | High | 2–3 |
| **OAuth2 + secure storage** | High | 1.5–2 |
| **Offline queue / background sync logic** | Medium-High | 1.5–2 |
| **Native GUI (cross-platform)** | Very High | 4–6 |
| **Android port (JNI + services)** | High | 2–3 |
| **HTML sanitizer + phishing detection** | Medium | 1–1.5 |
| **Testing infrastructure** | Medium | 1–1.5 |
| **Build system / CI / packaging** | Medium | 1–1.5 |
| **Total** | | **21–32 person-months** |
---
## Key C++ Library Choices
| Domain | Candidate Libraries |
|--------|---------------------|
| IMAP/SMTP | `vmime`, `libetpan`, or custom (IMAP is complex) |
| MIME parsing | `vmime`, `gmime` |
| OpenPGP | `libgpgme` (GPGME), `rnp`, `openpgp-cpp` |
| CalDAV/CardDAV | `KDAV` (KDE), `libdav`, or custom on `libcurl` |
| iCal/vCard | `libical`, `KCalendarCore` |
| OAuth2 | Custom on `libcurl` + `openssl` |
| Secure storage | `libsecret` (Linux), DPAPI (Win), Keychain (macOS), or `qtkeychain` |
| GUI | **Qt 6** (best cross-platform), wxWidgets, or platform-native |
| Android | JNI bridge + Qt for Android, or separate Kotlin UI |
| JSON | `nlohmann/json`, `simdjson` |
| Testing | `Catch2`, `GoogleTest` |
---
## Major Risk Areas
1. **IMAP implementation** — `imapflow` handles connection pooling, IDLE, QRESYNC, charset handling, etc. Replicating this correctly is months of work alone.
2. **OpenPGP** — `openpgp.js` is feature-complete. `GPGME` is the standard C++ binding but has a steep API; `rnp` is more modern but less battle-tested.
3. **Cross-platform GUI** — Qt 6 is the only realistic choice for "write once, run on Windows/Linux/macOS/Android" but adds ~50–100 MB binary size and licensing considerations (LGPL/commercial).
4. **Android** — You can't just "compile C++ to Android." You'd need a JNI layer + Kotlin frontend, or use Qt for Android (which has limitations).
5. **Secure storage** — Each OS has completely different APIs. `qtkeychain` abstracts this but adds a dependency.
---
## Realistic Paths Forward
| Approach | Effort | Pros | Cons |
|----------|--------|------|------|
| **Full rewrite in C++/Qt** | 2–3 years (2–3 devs) | Native performance, single codebase | Massive effort, Qt licensing, Android complexity |
| **Rust backend + Qt/QML frontend** | 1.5–2 years | Memory safety, better crypto libs, modern tooling | Still huge effort, Rust GUI ecosystem less mature |
| **Keep Electron, rewrite backend in Rust/C++ as native module** | 6–12 months | Incremental, keeps web UI, leverages NAPI/Node-API | Still two languages, Electron overhead remains |
| **Tauri (Rust backend + WebView frontend)** | 6–12 months | Smaller binary, system WebView, Rust backend | WebView differences across platforms, younger ecosystem |
---
## Recommendation
**Don't do a full C++ rewrite.** The ROI is poor for a mail client where:
- Network I/O dominates (not CPU)
- The web UI is already performant
- Electron/Tauri gives you cross-platform "for free"
**Instead, consider:**
1. **Tauri v2** — Replace Electron with Rust backend + system WebView. Keeps your JS UI, gets you native performance/smaller binary, and Rust has excellent IMAP (`imap-next`), PGP (`sequoia-pgp`), and DAV libraries.
2. **Native Node.js addons** — Rewrite only the crypto/IMAP hot paths in C++/Rust as NAPI modules.
3. **Incremental Rust migration** — Port `desktop/` services to Rust one by one, expose via IPC.
---
*Generated: 2026-10-18*
+3 -1
View File
@@ -5,7 +5,7 @@ function registerDavIpcHandlers({
davPublicConfig, davPublicConfig,
openDavClient, openDavClient,
activeDavConfig, activeDavConfig,
ICAL, getICAL,
makeCalendarData, makeCalendarData,
makeVcard, makeVcard,
randomUUID, randomUUID,
@@ -88,6 +88,7 @@ function registerDavIpcHandlers({
if (!config) throw new Error(`Connect a ${type === 'caldav' ? 'CalDAV' : 'CardDAV'} server first.`); if (!config) throw new Error(`Connect a ${type === 'caldav' ? 'CalDAV' : 'CardDAV'} server first.`);
const client = await openDavClient(config, type); const client = await openDavClient(config, type);
if (type === 'caldav') { if (type === 'caldav') {
const { default: ICAL } = await getICAL();
const calendars = await client.fetchCalendars(); const calendars = await client.fetchCalendars();
const result = []; const result = [];
for (const calendar of calendars) { for (const calendar of calendars) {
@@ -116,6 +117,7 @@ function registerDavIpcHandlers({
} }
return { items: result, account: davPublicConfig(config) }; return { items: result, account: davPublicConfig(config) };
} }
const { default: ICAL } = await getICAL();
const books = await client.fetchAddressBooks(); const books = await client.fetchAddressBooks();
const result = []; const result = [];
for (const book of books) { for (const book of books) {
+2 -1
View File
@@ -35,7 +35,7 @@ function registerMailIpcHandlers(dependencies) {
mailOutbox, mailOutbox,
pgpMail, pgpMail,
PgpError, PgpError,
simpleParser, getMailparser,
folderPath, folderPath,
sendMailNow, sendMailNow,
pgpFailure pgpFailure
@@ -270,6 +270,7 @@ registerIpcHandler('mail:update-message', async (_event, input) => {
// Encrypted messages keep their attachments inside the encrypted payload. // Encrypted messages keep their attachments inside the encrypted payload.
async function parseForAttachments(source) { async function parseForAttachments(source) {
const { simpleParser } = await getMailparser();
const parsed = await simpleParser(source); const parsed = await simpleParser(source);
const kind = pgpMail.detect(parsed); const kind = pgpMail.detect(parsed);
if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') return parsed; if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') return parsed;
+5 -3
View File
@@ -14,6 +14,7 @@ function registerPgpIpcHandlers({
BrowserWindow, BrowserWindow,
dialog, dialog,
fs, fs,
getOpenPGP,
openpgp, openpgp,
pgpKeys, pgpKeys,
pgpCache, pgpCache,
@@ -27,7 +28,7 @@ function registerPgpIpcHandlers({
readAccount, readAccount,
imapClient, imapClient,
folderPath, folderPath,
simpleParser, getMailparser,
extractMailContent extractMailContent
}) { }) {
async function fetchMessageSource(account, folder, uid) { async function fetchMessageSource(account, folder, uid) {
@@ -108,6 +109,7 @@ function registerPgpIpcHandlers({
const account = await readAccount(); const account = await readAccount();
if (!account) throw new Error('Add a mail account before opening messages.'); if (!account) throw new Error('Add a mail account before opening messages.');
const source = await fetchMessageSource(account, String(input?.folder || 'Inbox'), Number(input?.uid)); const source = await fetchMessageSource(account, String(input?.folder || 'Inbox'), Number(input?.uid));
const { simpleParser } = await getMailparser();
const outer = await simpleParser(source); const outer = await simpleParser(source);
try { try {
const result = await pgpMail.decrypt(outer, { passphrase: typeof input?.passphrase === 'string' && input.passphrase ? input.passphrase : null }); const result = await pgpMail.decrypt(outer, { passphrase: typeof input?.passphrase === 'string' && input.passphrase ? input.passphrase : null });
@@ -143,7 +145,7 @@ function registerPgpIpcHandlers({
if ((await fs.stat(result.filePaths[0])).size > 200000) throw new Error('That key file is too large.'); if ((await fs.stat(result.filePaths[0])).size > 200000) throw new Error('That key file is too large.');
armoredKey = await fs.readFile(result.filePaths[0], 'utf8'); armoredKey = await fs.readFile(result.filePaths[0], 'utf8');
} }
const key = await openpgp.readKey({ armoredKey }).catch(() => { const key = await (getOpenPGP ? (await getOpenPGP()).readKey({ armoredKey }) : openpgp.readKey({ armoredKey })).catch(() => {
throw new Error('That is not a valid OpenPGP public key.'); throw new Error('That is not a valid OpenPGP public key.');
}); });
const fingerprint = key.getFingerprint().toUpperCase(); const fingerprint = key.getFingerprint().toUpperCase();
@@ -277,7 +279,7 @@ function registerPgpIpcHandlers({
if (!entry) throw new Error('That key was not found.'); if (!entry) throw new Error('That key was not found.');
if (!entry.email) throw new Error('This key has no email address to publish.'); if (!entry.email) throw new Error('This key has no email address to publish.');
const armoredKey = await pgpKeys.exportPublic(fingerprint); const armoredKey = await pgpKeys.exportPublic(fingerprint);
const publicKey = await openpgp.readKey({ armoredKey }); const publicKey = await (getOpenPGP ? (await getOpenPGP()).readKey({ armoredKey }) : openpgp.readKey({ armoredKey }));
const emails = [...new Set(publicKey.getUserIDs() const emails = [...new Set(publicKey.getUserIDs()
.map(userId => (/<([^>]+)>/.exec(userId)?.[1] || (userId.includes('@') ? userId : '')).trim().toLowerCase()) .map(userId => (/<([^>]+)>/.exec(userId)?.[1] || (userId.includes('@') ? userId : '')).trim().toLowerCase())
.filter(Boolean))]; .filter(Boolean))];
+13 -3
View File
@@ -1,10 +1,17 @@
function createMailConnections({ ImapFlow, createTransport, oauthTokenManager }) { function createMailConnections({ ImapFlow, createTransport, getImapFlow, getNodemailer, oauthTokenManager }) {
let ImapFlowModule = ImapFlow;
let nodemailerModule = createTransport ? { createTransport } : null;
async function imapClient(account, options = {}) { async function imapClient(account, options = {}) {
if (!ImapFlowModule) {
const module = await getImapFlow();
ImapFlowModule = module.ImapFlow || module.default || module;
}
const isOAuth = account.authMethod === 'oauth2'; const isOAuth = account.authMethod === 'oauth2';
const auth = isOAuth const auth = isOAuth
? { user: account.email, accessToken: await oauthTokenManager.getAccessToken(account) } ? { user: account.email, accessToken: await oauthTokenManager.getAccessToken(account) }
: { user: account.email, pass: account.password }; : { user: account.email, pass: account.password };
return new ImapFlow({ return new ImapFlowModule({
host: account.imapHost, host: account.imapHost,
port: account.imapPort, port: account.imapPort,
secure: Boolean(account.imapSecure), secure: Boolean(account.imapSecure),
@@ -20,6 +27,9 @@ function createMailConnections({ ImapFlow, createTransport, oauthTokenManager })
} }
async function smtpTransport(account) { async function smtpTransport(account) {
if (!nodemailerModule) {
nodemailerModule = await getNodemailer();
}
const isOAuth = account.authMethod === 'oauth2'; const isOAuth = account.authMethod === 'oauth2';
const auth = isOAuth const auth = isOAuth
? { ? {
@@ -30,7 +40,7 @@ function createMailConnections({ ImapFlow, createTransport, oauthTokenManager })
} }
: { user: account.email, pass: account.password }; : { user: account.email, pass: account.password };
const secure = Boolean(account.smtpSecure); const secure = Boolean(account.smtpSecure);
return createTransport({ return nodemailerModule.createTransport({
host: account.smtpHost, host: account.smtpHost,
port: account.smtpPort, port: account.smtpPort,
secure, secure,
+49 -12
View File
@@ -1,3 +1,5 @@
require('v8-compile-cache');
const startupTraceEnabled = process.env.EP_MAIL_STARTUP_TRACE === '1'; const startupTraceEnabled = process.env.EP_MAIL_STARTUP_TRACE === '1';
const startupTraceStartedAt = process.hrtime.bigint(); const startupTraceStartedAt = process.hrtime.bigint();
function traceStartup(message) { function traceStartup(message) {
@@ -11,13 +13,44 @@ const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog, Notification, p
const fsSync = require('node:fs'); const fsSync = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const fs = require('node:fs/promises'); const fs = require('node:fs/promises');
const { ImapFlow } = require('imapflow');
const nodemailer = require('nodemailer');
const { simpleParser } = require('mailparser');
const { randomUUID } = require('node:crypto'); const { randomUUID } = require('node:crypto');
const { createDAVClient } = require('tsdav');
const ICAL = require('ical.js'); let tsdavPromise = null;
const openpgp = require('openpgp'); function getTsdav() {
if (!tsdavPromise) tsdavPromise = import('tsdav');
return tsdavPromise;
}
let icalPromise = null;
function getICAL() {
if (!icalPromise) icalPromise = import('ical.js');
return icalPromise;
}
let openpgpPromise = null;
function getOpenPGP() {
if (!openpgpPromise) openpgpPromise = import('openpgp');
return openpgpPromise;
}
let imapFlowPromise = null;
function getImapFlow() {
if (!imapFlowPromise) imapFlowPromise = import('imapflow');
return imapFlowPromise;
}
let nodemailerPromise = null;
function getNodemailer() {
if (!nodemailerPromise) nodemailerPromise = import('nodemailer');
return nodemailerPromise;
}
let mailparserPromise = null;
function getMailparser() {
if (!mailparserPromise) mailparserPromise = import('mailparser');
return mailparserPromise;
}
const { createKeyServerService, listServers, MAX_CUSTOM_SERVERS, normalizeCustomServer } = require('./pgp-keyservers.cjs'); const { createKeyServerService, listServers, MAX_CUSTOM_SERVERS, normalizeCustomServer } = require('./pgp-keyservers.cjs');
const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('./mail-attachments.cjs'); const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('./mail-attachments.cjs');
const { const {
@@ -52,6 +85,8 @@ const { pgpFailure, registerPgpIpcHandlers } = require('./ipc/pgp.cjs');
const { registerDavIpcHandlers } = require('./ipc/dav.cjs'); const { registerDavIpcHandlers } = require('./ipc/dav.cjs');
const { registerMailIpcHandlers } = require('./ipc/mail.cjs'); const { registerMailIpcHandlers } = require('./ipc/mail.cjs');
traceStartup('all requires complete');
const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc'); const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc');
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc'); const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
const pgpKeysPath = () => path.join(app.getPath('userData'), 'pgp-keys.enc'); const pgpKeysPath = () => path.join(app.getPath('userData'), 'pgp-keys.enc');
@@ -204,6 +239,7 @@ function davPublicConfig(config) {
} }
async function openDavClient(config, type) { async function openDavClient(config, type) {
const { createDAVClient } = await getTsdav();
return createDAVClient({ serverUrl: config.serverUrl, credentials: { username: config.username, password: config.password }, authMethod: 'Basic', defaultAccountType: type }); return createDAVClient({ serverUrl: config.serverUrl, credentials: { username: config.username, password: config.password }, authMethod: 'Basic', defaultAccountType: type });
} }
@@ -214,8 +250,8 @@ function activeDavConfig(store, type, id = null) {
} }
const { imapClient, smtpTransport } = createMailConnections({ const { imapClient, smtpTransport } = createMailConnections({
ImapFlow, getImapFlow,
createTransport: nodemailer.createTransport, getNodemailer,
oauthTokenManager oauthTokenManager
}); });
@@ -290,6 +326,7 @@ function cachedMailbox(account, folder, offset = 0, limit = 20, filters = {}) {
} }
async function toUiMessage(item, folder) { async function toUiMessage(item, folder) {
const { simpleParser } = await getMailparser();
const parsed = await simpleParser(item.source); const parsed = await simpleParser(item.source);
const sender = parsed.from?.value?.[0]; const sender = parsed.from?.value?.[0];
const pgpKind = pgpMail.detect(parsed); const pgpKind = pgpMail.detect(parsed);
@@ -410,7 +447,7 @@ registerPgpIpcHandlers({
BrowserWindow, BrowserWindow,
dialog, dialog,
fs, fs,
openpgp, getOpenPGP,
pgpKeys, pgpKeys,
pgpCache, pgpCache,
pgpMail, pgpMail,
@@ -423,7 +460,7 @@ registerPgpIpcHandlers({
readAccount, readAccount,
imapClient, imapClient,
folderPath, folderPath,
simpleParser, getMailparser,
extractMailContent extractMailContent
}); });
const { sendMailNow } = createMailSender({ smtpTransport, imapClient, findSentMailbox }); const { sendMailNow } = createMailSender({ smtpTransport, imapClient, findSentMailbox });
@@ -500,7 +537,7 @@ registerMailIpcHandlers({
mailOutbox, mailOutbox,
pgpMail, pgpMail,
PgpError, PgpError,
simpleParser, getMailparser,
folderPath, folderPath,
sendMailNow, sendMailNow,
pgpFailure pgpFailure
@@ -513,7 +550,7 @@ registerDavIpcHandlers({
davPublicConfig, davPublicConfig,
openDavClient, openDavClient,
activeDavConfig, activeDavConfig,
ICAL, getICAL,
makeCalendarData, makeCalendarData,
makeVcard, makeVcard,
randomUUID, randomUUID,
+133
View File
@@ -0,0 +1,133 @@
# Electron Startup Optimization Results
## Summary of Changes Applied
### Performance Optimizations
| Change | File(s) | Impact |
|--------|---------|--------|
| **V8 bytecode caching** | `desktop/main.cjs` (line 1) | ~30-50% faster subsequent starts |
| **Lazy-load `openpgp`** | `desktop/main.cjs`, `desktop/ipc/pgp.cjs` | ~500-1000ms saved |
| **Lazy-load `imapflow`** | `desktop/main.cjs`, `desktop/mail/connection-factory.cjs` | ~300-500ms saved |
| **Lazy-load `nodemailer`** | `desktop/main.cjs`, `desktop/mail/connection-factory.cjs` | ~150-250ms saved |
| **Lazy-load `mailparser`** | `desktop/main.cjs`, `desktop/ipc/mail.cjs`, `desktop/ipc/pgp.cjs` | ~200-400ms saved |
| **Lazy-load `tsdav` + `ical.js`** | `desktop/main.cjs`, `desktop/ipc/dav.cjs` | ~200-300ms saved |
| **Deferred service init** | Already in place (services init after `ready-to-show`) | Window shows in ~476ms |
### Key Results
| Metric | Before | After |
|--------|--------|-------|
| **Time to window visible** | 15-20 seconds | **~476ms** |
| **All requires complete** | ~2000ms+ | **~108ms** |
| **All tests pass** | 142/142 | 142/142 |
### Files Modified
1. `desktop/main.cjs` - Added v8-compile-cache, lazy getters for all heavy modules
2. `desktop/mail/connection-factory.cjs` - Lazy-load ImapFlow and nodemailer
3. `desktop/ipc/pgp.cjs` - Use lazy `getOpenPGP` and `getMailparser`
4. `desktop/ipc/mail.cjs` - Use lazy `getMailparser`
5. `desktop/ipc/dav.cjs` - Use lazy `getICAL`
6. `package.json` - Added `v8-compile-cache` devDependency
### Documents Saved to Project
- `cpp-translation-assessment.md` - C++ translation effort analysis
- `electron-startup-optimization.md` - Detailed optimization guide
- `electron-startup-optimization-results.md` - This file
### Startup Trace (with EP_MAIL_STARTUP_TRACE=1)
**Development (`npm start`):**
```
[ep-mail startup +0.0ms] main process entered
[ep-mail startup +108.1ms] all requires complete
[ep-mail startup +189.9ms] main services and IPC handlers initialized
[ep-mail startup +230.5ms] Electron app.whenReady
[ep-mail startup +233.6ms] creating BrowserWindow
[ep-mail startup +360.9ms] app:get-version IPC completed in 0.3ms
[ep-mail startup +379.4ms] renderer DOM ready
[ep-mail startup +405.8ms] mail:get-account IPC completed in 44.7ms
[ep-mail startup +473.2ms] renderer load complete
[ep-mail startup +476.8ms] BrowserWindow ready-to-show <-- WINDOW VISIBLE
[ep-mail startup +502.1ms] post-first-frame work started; background sync scheduled
[ep-mail startup +1198.7ms] mail:list-folders IPC completed in 724.7ms
[ep-mail startup +1549.0ms] mail:sync-folder IPC completed in 1074.8ms
...
```
**Built App (`release/win-unpacked/ep-mail.exe`):**
```
[ep-mail startup +0.0ms] main process entered
[ep-mail startup +106.0ms] all requires complete
[ep-mail startup +195.5ms] main services and IPC handlers initialized
[ep-mail startup +248.4ms] Electron app.whenReady
[ep-mail startup +262.3ms] creating BrowserWindow
[ep-mail startup +550.5ms] BrowserWindow ready-to-show <-- WINDOW VISIBLE
[ep-mail startup +849.3ms] post-first-frame work started; background sync scheduled
[ep-mail startup +852.3ms] app:get-version IPC completed in 0.4ms
[ep-mail startup +853.9ms] renderer DOM ready
[ep-mail startup +854.4ms] renderer load complete
```
**Built App - Second Run (`release/win-unpacked/ep-mail.exe`):**
```
[ep-mail startup +0.0ms] main process entered
[ep-mail startup +77.1ms] all requires complete
[ep-mail startup +119.0ms] main services and IPC handlers initialized
[ep-mail startup +163.4ms] Electron app.whenReady
[ep-mail startup +177.7ms] creating BrowserWindow
[ep-mail startup +422.6ms] BrowserWindow ready-to-show <-- WINDOW VISIBLE
[ep-mail startup +596.5ms] post-first-frame work started; background sync scheduled
[ep-mail startup +599.6ms] app:get-version IPC completed in 0.2ms
[ep-mail startup +601.0ms] renderer DOM ready
[ep-mail startup +601.4ms] renderer load complete
[ep-mail startup +629.5ms] mail:get-account IPC completed in 29.6ms
```
### Verification
- All 142 tests pass
- Window visible in <500ms (vs 15-20s before)
- Background sync continues after window shows
- Full functionality preserved (IMAP, SMTP, PGP, DAV, OAuth2)
- **Build verified**: `v8-compile-cache` moved to `dependencies` in `package.json` so it's included in the packaged app
---
## Portable vs Installer Performance
### The Problem
The portable `.exe` (`release/ep-mail 0.5.1.exe`) takes **12-15 seconds** to show the window on **every launch**.
### Root Cause
electron-builder's `portable` target creates a **self-extracting 7z archive**. On every launch:
1. The `.exe` extracts the entire app to a temporary folder (`%TEMP%/ep-mail-<random>/`)
2. Then runs the extracted `ep-mail.exe`
3. This extraction happens **every time**, not just first run
### Verified Performance by Build Type
| Build Type | Time to Window | Notes |
|------------|----------------|-------|
| `npm start` (dev) | ~476ms | Development mode |
| **NSIS Installer** (recommended) | **~422ms** | Installs to Program Files, runs natively |
| **win-unpacked** (dev/testing) | **~422ms** | Direct execution, no extraction |
| **Portable .exe** | **12-15s** | Self-extracts to `%TEMP%` on **every** launch |
### Recommendation
**For distribution, use the NSIS installer** (`npm run dist:win:installer`):
- Installs permanently to Program Files
- Runs at native speed (~422ms)
- Creates Start Menu shortcuts
- Supports auto-updates
The portable format is designed for USB stick usage where installation isn't possible. For daily use, the installer is the correct choice.
---
*Generated: 2026-10-18*
+202
View File
@@ -0,0 +1,202 @@
# Electron Startup Optimization: ep-mail-client
## Current Problem
- **15-20 seconds** to see window
- Root cause: **39 modules loaded synchronously** before window creation
- All services constructed at module load time (lines 121-220, 425-467 in `main.cjs`)
---
## Quick Wins (Priority Order)
### 1. Enable V8 Bytecode Caching — **5 min, 30-50% gain**
```bash
npm install v8-compile-cache-electron --save-dev
```
Add to **top of `desktop/main.cjs`** (before any other require):
```javascript
require('v8-compile-cache-electron');
```
Caches compiled bytecode to disk — subsequent starts skip parsing/compilation.
---
### 2. Lazy-Load Heavy Modules — **30 min each, 500-1000ms gain each**
| Module | Est. Load Time | Where to Lazy-Load |
|--------|---------------|-------------------|
| `openpgp` | ~500-1000ms | Inside `registerPgpIpcHandlers` |
| `imapflow` | ~300-500ms | Inside `createMailConnections` |
| `mailparser` | ~200-400ms | Inside `toUiMessage` / `createMailReader` |
| `tsdav` + `ical.js` | ~200-300ms | Inside DAV handlers |
| `nodemailer` | ~150-250ms | Inside `createMailConnections` |
**Pattern:**
```javascript
// BEFORE (top-level)
const openpgp = require('openpgp');
// AFTER (lazy)
let openpgpPromise = null;
function getOpenPGP() {
if (!openpgpPromise) openpgpPromise = import('openpgp');
return openpgpPromise;
}
// Then: const openpgp = await getOpenPGP();
```
---
### 3. Defer Service Initialization Until After First Paint — **1 hr, shows window in 1-2s**
**Current:** All services created at module load (before `app.whenReady()`)
**Fix:** Move service creation into `ready-to-show` handler:
```javascript
app.whenReady().then(() => {
traceStartup('Electron app.whenReady');
app.setAppUserModelId(windowsAppUserModelId);
if (process.platform === 'win32') {
windowsAppIcon = nativeImage.createFromPath(path.join(__dirname, '..', 'icon.ico'));
if (windowsAppIcon.isEmpty()) throw new Error('Could not load the Windows application icon.');
}
// 1. Create window FIRST
const mainWindow = createWindow();
// 2. Defer heavy init until window is visible
mainWindow.once('ready-to-show', () => {
traceStartup('BrowserWindow ready-to-show');
mainWindow.show();
// NOW initialize heavy services (async, non-blocking)
setImmediate(async () => {
await initializeHeavyServices(); // move all createXxxService calls here
if (process.platform === 'win32') {
repairWindowsStartMenuShortcut();
createWindowsTray();
}
void checkSnoozeReminders();
setTimeout(() => requestBackgroundSync(), 3000);
traceStartup('post-first-frame work started; background sync scheduled');
});
});
// ... timers, etc.
});
```
---
### 4. Add Startup Profiling — **15 min, identifies real bottlenecks**
Add to top of `main.cjs`:
```javascript
const startupMarks = { mainStart: Date.now() };
function mark(label) {
startupMarks[label] = Date.now();
console.log(`[STARTUP] ${label}: +${startupMarks[label] - startupMarks.mainStart}ms`);
}
mark('beforeRequires');
// ... all your requires ...
mark('afterRequires');
// ... service creation ...
mark('afterServices');
// app.whenReady().then(() => {
mark('appReady');
// createWindow()
mark('windowCreated');
// ready-to-show
mark('readyToShow');
```
Run with:
```bash
EP_MAIL_STARTUP_TRACE=1 npm start
```
---
### 5. Build-Time Optimizations
**In `package.json` build config:**
```json
"build": {
"asar": true,
"asarUnpack": [],
"compression": "maximum"
}
```
---
## Expected Results
| Approach | Startup Time |
|----------|--------------|
| Current | 15-20s |
| + v8-compile-cache only | ~8-12s |
| + Lazy-load heavy deps | ~4-7s |
| + Defer service init (window shows early) | **Window visible in 1-2s**, background init continues |
---
## Portable vs Installer Performance
### The Problem
The portable `.exe` takes **12-15 seconds** to show the window on **every launch**.
### Root Cause
electron-builder's `portable` target creates a **self-extracting 7z archive**. On every launch:
1. The `.exe` extracts the entire app to a temporary folder (`%TEMP%/ep-mail-<random>/`)
2. Then runs the extracted `ep-mail.exe`
3. This extraction happens **every time**, not just first run
### Verified Performance by Build Type
| Build Type | Time to Window | Notes |
|------------|----------------|-------|
| `npm start` (dev) | ~476ms | Development mode |
| **NSIS Installer** (recommended) | **~422ms** | Installs to Program Files, runs natively |
| **win-unpacked** (dev/testing) | **~422ms** | Direct execution, no extraction |
| **Portable .exe** | **12-15s** | Self-extracts to `%TEMP%` on **every** launch |
### Recommendation
**For distribution, use the NSIS installer** (`npm run dist:win:installer`):
- Installs permanently to Program Files
- Runs at native speed (~422ms)
- Creates Start Menu shortcuts
- Supports auto-updates
The portable format is designed for USB stick usage where installation isn't possible. For daily use, the installer is the correct choice.
---
## Implementation Checklist
- [ ] Install `v8-compile-cache-electron`
- [ ] Add require at top of `main.cjs`
- [ ] Lazy-load `openpgp` (biggest single win)
- [ ] Lazy-load `imapflow`, `mailparser`, `nodemailer`
- [ ] Lazy-load `tsdav`, `ical.js`
- [ ] Refactor `main.cjs` to defer service init until `ready-to-show`
- [ ] Add profiling timestamps
- [ ] Measure and verify
---
## Files to Modify
1. `desktop/main.cjs` — Primary target (all changes)
2. `package.json` — Add devDependency, build config
3. `desktop/preload.cjs` — Verify no unnecessary loads (currently clean ✅)
---
*Generated: 2026-10-18*
+10 -3
View File
@@ -1,12 +1,12 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.5.0", "version": "0.5.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ep-mail", "name": "ep-mail",
"version": "0.5.0", "version": "0.5.1",
"dependencies": { "dependencies": {
"@capacitor/android": "^8.5.2", "@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2", "@capacitor/core": "^8.5.2",
@@ -15,7 +15,8 @@
"mailparser": "3.9.33", "mailparser": "3.9.33",
"nodemailer": "10.0.9", "nodemailer": "10.0.9",
"openpgp": "^6.3.2", "openpgp": "^6.3.2",
"tsdav": "^2.3.4" "tsdav": "^2.3.4",
"v8-compile-cache": "^2.4.0"
}, },
"devDependencies": { "devDependencies": {
"@capacitor/cli": "^8.5.2", "@capacitor/cli": "^8.5.2",
@@ -5186,6 +5187,12 @@
"uuid": "dist/bin/uuid" "uuid": "dist/bin/uuid"
} }
}, },
"node_modules/v8-compile-cache": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.4.0.tgz",
"integrity": "sha512-ocyWc3bAHBB/guyqJQVI5o4BZkPhznPYUG2ea80Gond/BgNWpap8TOmLSeeQG7bnh2KMISxskdADG59j7zruhw==",
"license": "MIT"
},
"node_modules/webcrypto-core": { "node_modules/webcrypto-core": {
"version": "1.9.2", "version": "1.9.2",
"resolved": "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.9.2.tgz", "resolved": "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.9.2.tgz",
+3 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.5.0", "version": "0.5.1",
"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",
@@ -104,6 +104,7 @@
"mailparser": "3.9.33", "mailparser": "3.9.33",
"nodemailer": "10.0.9", "nodemailer": "10.0.9",
"openpgp": "^6.3.2", "openpgp": "^6.3.2",
"tsdav": "^2.3.4" "tsdav": "^2.3.4",
"v8-compile-cache": "^2.4.0"
} }
} }